max_stars_repo_path stringlengths 4 286 | max_stars_repo_name stringlengths 5 119 | max_stars_count int64 0 191k | id stringlengths 1 7 | content stringlengths 6 1.03M | content_cleaned stringlengths 6 1.03M | language stringclasses 111 values | language_score float64 0.03 1 | comments stringlengths 0 556k | edu_score float64 0.32 5.03 | edu_int_score int64 0 5 |
|---|---|---|---|---|---|---|---|---|---|---|
eds/openmtc-gevent/server/openmtc-scl/src/openmtc_scl/plugins/lwm2m_dm_server/DMServerCore.py | piyush82/elastest-device-emulator-service | 0 | 6614151 | <filename>eds/openmtc-gevent/server/openmtc-scl/src/openmtc_scl/plugins/lwm2m_dm_server/DMServerCore.py
from gevent.server import DatagramServer
from json import dumps, loads
from aplus import Promise
from lwm2m_lib.import_common_libs import connection, options, link, constants
from lwm2m_lib.operations.Registration import Registration, Endpoint
from lwm2m_lib.operations.ObservationNotification import ObservationNotificationEngine, GeneralObservationInformation
from lwm2m_lib.operations.Execution import Execution
from lwm2m_lib.operations.Discovery import Discovery
from lwm2m_lib.operations.Read import Read
from lwm2m_lib.operations.Write import Write
from lwm2m_lib.operations.Create import Create
from lwm2m_lib.operations.WriteAttributes import WriteAttributes
from lwm2m_lib.operations.OperationRequest import OperationRequest
from lwm2m_lib.data_model.ParseQueryPayload import ParsePath, ParsePayload, ParseQuery
from lwm2m_lib.data_model.ClientsCollection import ClientEndpoint, LWM2MResourceTree #ClientsCollection
from lwm2m_lib.operations.OperationRequest import OperationRequest
from lwm2m_lib.api import lwm2m_api
from gevent.coros import Semaphore
# Constants
OBSERVE_OPTION_VALUE_OBSERVATION = 0
OBSERVE_OPTION_VALUE_CANCEL_OBSERVATION = 1
URI_QUERY_VALUE = 15
LOCATION_VALUE = 8
URI_PATH_VALUE = 11
URI_HOST_VALUE = 3
URI_PORT_VALUE = 7
class DMServerCore(OperationRequest):
def __init__(self, server_ip, server_port, client_ip, client_port):
super(DMServerCore, self).__init__()
self.lwm2m_dm_server_ip = server_ip
self.lwm2m_dm_server_port = server_port
self.local_client_ip_ = client_ip
self.local_client_port_ = client_port
self.sem = Semaphore()
self.sem_counter = 0
self.lwm2m_resources = LWM2MResourceTree()
self.registration = Registration(self.lwm2m_resources)
self.execution = Execution(self.lwm2m_resources)
self.discover = Discovery(lwm2m_resources=self.lwm2m_resources)
self.observation = ObservationNotificationEngine(self.lwm2m_resources)
self.read = Read(self.lwm2m_resources)
self.write = Write(self.lwm2m_resources)
self.create_object_instance = Create(self.lwm2m_resources)
self.write_attributes = WriteAttributes(self.lwm2m_resources)
def create_server(self, ):
""" Creates and starts a LWM2M DM Server using Gevent DatagramServer. The server
listens at the ip and port specified below. A handler is used to entertain the
requests coming at that port """
self.dm_server = DatagramServer((self.lwm2m_dm_server_ip, \
self.lwm2m_dm_server_port), self.handle_request)
self.dm_server.start()
def stop_server(self, ):
""" Stops the LWM2M DM Server """
self.dm_server.stop()
def handle_request(self, message, remote):
""" Handles the requests coming at the specified ip and port """
rx_record = connection.ReceptionRecord(None, message, remote)
msg = rx_record.message
uri_query = msg.findOption(options.UriQuery)
self.process(rx_record, remote, uri_query)
def handle_lwm2m_put(self, msg, uri_query, remote, rx_record):
""" It consists of Normal Update, Write Operation, Write Attribute Operation.
Write Operation is used to update the resource(s) as per the request. Write
Attributes operation is used to update the attributes of the object, object
instance or resource. """
method = None
try:
method = uri_query[0].value.split("=")[1]
except:
pass
if method == "write":
path = msg.findOption(URI_PATH_VALUE)
content_type_number = msg.findOption(options.ContentType)
if content_type_number is None:
content_type = "text/plain"
else:
content_type = constants.media_types[content_type_number.value]
self.write.write_resource(msg.payload, path, content_type)
payload_forward = msg.payload
msg = connection.Message(connection.Message.ACK, code=constants.CHANGED, payload="Resource Updated")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
client_port = self.generate_client_port()
self.write.forward_write_request(path, payload_forward, \
content_type, remote, client_port)
elif method == "write_attributes":
path = msg.findOption(URI_PATH_VALUE)
content_type_number = msg.findOption(options.ContentType)
if content_type_number is None:
content_type = "text/plain"
else:
content_type = constants.media_types[content_type_number.value]
payload = loads(msg.payload)
self.write_attributes.set_attributes(path, remote, payload)
msg = connection.Message(connection.Message.ACK, code=constants.CHANGED, payload="Resource Attributes Updated")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
client_port = self.generate_client_port()
self.write_attributes.forward_request(path, remote, payload, content_type, client_port)
else:
endpoint_location = msg.findOption(URI_PATH_VALUE)[0].value
if msg.payload == "":
self.logger.info("Updating the Registration Params")
endpoint_object = self.lwm2m_resources.return_endpoint_object(endpoint_location=endpoint_location)
endpoint_object.listener_ip = uri_query[6].value.split("=")[1]
endpoint_object.local_ip = uri_query[6].value.split("=")[1]
msg = connection.Message(connection.Message.ACK, code=constants.CHANGED, payload="Resource Updated")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
else:
self.logger.info("Adding/Updating the Resources")
payload = self.update_resource(loads(msg.payload), endpoint_location=endpoint_location)
msg = connection.Message(connection.Message.ACK, code=constants.CHANGED, payload="Resource Updated")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
self.logger.info("Forwarding the Notification")
request = lwm2m_api()
client_port = self.generate_client_port()
response = request.send_notification(self.general_observation.listener_ip, self.general_observation.listener_port, \
self.general_observation.token_id, payload, content_type="application/json", client_port=client_port)
def update_resource(self, res_payload, endpoint_location=None, endpoint_name=None):
total_res_dict = {}
total_object_info = {}
payload = res_payload
endpoint_object = self.registration.handle_put_resource_updates(res_payload, endpoint_location=endpoint_location, endpoint_name=endpoint_name)
for item, value in payload.iteritems():
resources_dict = endpoint_object.objects_dict[item]["object"].resources_id_dict
res_dict = {}
for item1, value1 in resources_dict.iteritems():
res_dict.update({
item1 : value1["object"].res_value
})
total_res_dict.update({
item : {"resources" : res_dict }
})
total_object_info = {endpoint_object.endpoint_name : total_res_dict}
return total_object_info
def process(self, rx_record, remote, uri_query):
""" Processes various requests like CON (POST, PUT, GET) or NON.
POST requests : Generally used for Registration and Execution
PUT requests : Generally used for Updating the resources
GET requests : Generally used for Discovery, Observation, Cancel Observation """
msg = rx_record.message
self.uri_query = uri_query
if msg.transaction_type == connection.Message.CON:
if constants.POST == msg.code:
method = None
try:
method = uri_query[0].value.split("=")[1]
except:
pass
if method == "create":
path = msg.findOption(URI_PATH_VALUE)
content_type_number = msg.findOption(options.ContentType)
if content_type_number is None:
content_type = "text/plain"
else:
content_type = constants.media_types[content_type_number.value]
self.create_object_instance.create_instance(path, remote, content_type, loads(msg.payload))
resources = loads(msg.payload)
msg = connection.Message(connection.Message.ACK, code=constants.CREATED, payload="Resource Created")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
client_port = self.generate_client_port()
self.create_object_instance.forward_request(path, remote, resources, content_type, client_port)
elif method == "execute":
path = msg.findOption(URI_PATH_VALUE)
content_type_number = msg.findOption(options.ContentType)
if content_type_number is None:
content_type = "text/plain"
else:
content_type = constants.media_types[content_type_number.value]
self.execution.execute_resource(path, remote, msg.payload)
execute_payload = msg.payload
msg = connection.Message(connection.Message.ACK, code=constants.CHANGED, payload="Resource Executed")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
client_port = self.generate_client_port()
self.execution.forward_request(path, remote, execute_payload, client_port)
elif method == "notify":
self.logger.info("Notification Received")
client_port = self.generate_client_port()
for item1, item2 in loads(msg.payload).iteritems():
if item1 == "observer_ip":
observer_ip = item2
elif item1 == "observer_port":
observer_port = item2
elif item1 != "observer_ip" and item1 != "observer_port":
endpoint_name = item1
for item3, item4 in item2.iteritems():
for item5, item6 in item4["resources"].iteritems():
pass
res = {
item3 : {"resources" : {item5.split("_")[0]:{"res_value" : item6, "res_inst_id" : item5.split("_")[1]}}}
}
payload = {}
payload = self.update_resource(res, endpoint_name=endpoint_name)
payload["observer_ip"] = observer_ip
payload["observer_port"] = observer_port
token_id = msg.token
observe_value = msg.findOption(options.Observe).value
self.logger.info("Forwarding Notification")
content_type = "application/json"
request = lwm2m_api()
response = request.send_notification(self.general_observation.listener_ip, self.general_observation.listener_port, token_id, payload, \
content_type=content_type, time_elapse=observe_value, client_port=client_port)
msg = connection.Message(connection.Message.ACK, code=constants.CREATED, payload="Notification Received")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
else:
""" Handles the Client Registration Request """
self.logger.info("Registering Client Endpoint in the LWM2M DM Server")
endpoint = self.registration.process_registration(msg, uri_query)
response = self.registration.register_client(endpoint)
registered_client_location = response
if registered_client_location is not None:
self.logger.info("Client Endpoint Registration Successful for Endpoint : %s", endpoint.endpoint_name)
self.logger.info("The registered location is %s", registered_client_location)
payload = self.set_general_observation_params()
else:
self.logger.info("Client Endpoint Registration Failed")
msg = connection.Message(connection.Message.ACK, code=constants.CREATED, location=registered_client_location)
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
#Send the General Observation to the Registered Client
#self.send_general_observation(registered_client_location)
elif constants.PUT == msg.code:
""" It consists of Normal Update, Write Operation, Write Attribute Operation.
Write Operation is used to update the resource(s) as per the request. Write
Attributes operation is used to update the attributes of the object, object
instance or resource. """
self.handle_lwm2m_put(msg, uri_query, remote, rx_record)
elif constants.GET == msg.code:
""" Handles Requests like Discovery, Observation """
try:
observe_value = msg.findOption(options.Observe).value
except:
observe_value = ""
if observe_value == OBSERVE_OPTION_VALUE_OBSERVATION:
""" Sets the Observation. Two types of observations. General Observation
and Specific Observation. General Observation is used for anything that is
not observed and updates are sent as general notifications using a general
token. Specific observation is implicitly defined by the observer(as request)
and handled as specific notification with a specific token """
path = msg.findOption(URI_PATH_VALUE)
if len(path) == 1:
self.set_m2m_server_adapter_params(rx_record, remote)
else:
self.logger.info("Specific Observation Request Received")
content_type_number = msg.findOption(options.ContentType)
if content_type_number is None:
content_type = "text/plain"
else:
content_type = constants.media_types[content_type_number.value]
token_id = msg.token
app_ip = loads(msg.payload)["app_ip"]
app_port = loads(msg.payload)["app_port"]
client_port = self.generate_client_port()
response = self.observation.forward_request(path, remote, observe_value, \
self.lwm2m_dm_server_ip, self.lwm2m_dm_server_port, \
app_ip, app_port, token_id, client_port)
msg = connection.Message(connection.Message.ACK, code=constants.CONTENT, \
payload="test") #todo: payload to be replaced
self.dm_server.sendto(msg._pack(rx_record.transaction_id, token_id), remote)
elif observe_value == OBSERVE_OPTION_VALUE_CANCEL_OBSERVATION:
""" Removes the observation from the List """
self.logger.info("Cancel Observation Request Received")
path = msg.findOption(URI_PATH_VALUE)
token_id = msg.token
app_ip = loads(msg.payload)["app_ip"]
app_port = loads(msg.payload)["app_port"]
client_port = self.generate_client_port()
response = self.observation.forward_request(path, remote, observe_value, \
self.lwm2m_dm_server_ip, self.lwm2m_dm_server_port, \
app_ip, app_port, token_id, client_port)
def _handle_response(response):
msg = connection.Message(connection.Message.ACK, code=constants.CONTENT, payload=response)
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
response.then(_handle_response)
else:
method = None
try:
method = uri_query[0].value.split("=")[1]
except:
pass
if method == "read":
path = msg.findOption(URI_PATH_VALUE)
self.read.read_resource(path, remote)
msg = connection.Message(connection.Message.ACK, code=constants.CONTENT, \
payload="info read", content_type="text/plain")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
elif method == "discover":
if msg.payload == "/.well-known/core":
payload = dumps(self.discover.get_all_resources())
else:
path = msg.findOption(URI_PATH_VALUE)
client_port = self.generate_client_port()
payload = self.discover.forward_request(path, remote, client_port)
def _handle_response(payload):
msg = connection.Message(connection.Message.ACK, code=constants.CONTENT, \
payload=payload, content_type="application/json")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
if payload is Promise:
payload.then(_handle_response)
else:
_handle_response(payload)
elif msg.transaction_type == connection.Message.NON:
print "reached msg non"
payload = msg.payload
print payload
def set_general_observation_params(self, ):
return {"listener_ip" : self.lwm2m_dm_server_ip, "listener_port" : self.lwm2m_dm_server_port}
def send_general_observation(self, registered_client_location):
if registered_client_location is not None:
payload = dumps(self.set_general_observation_params())
endpoint_object = self.lwm2m_resources.return_endpoint_object(endpoint_location=registered_client_location)
client_listener_ip = endpoint_object.listener_ip
client_listener_port = endpoint_object.listener_port
request = lwm2m_api()
response = request.observe_resource(client_listener_ip, client_listener_port, \
payload=payload, client_port=self.generate_client_port())
def set_m2m_server_adapter_params(self, rx_record, remote):
msg = rx_record.message
#content_type is application/json
listener_ip = loads(msg.payload)["listener_ip"]
listener_port = loads(msg.payload)["listener_port"]
token_id = msg.token
self.general_observation = GeneralObservationInformation(listener_ip, listener_port, token_id)
response = "Observation Started on the LWM2M Server"
msg = connection.Message(connection.Message.ACK, code=constants.CONTENT, payload=response)
self.dm_server.sendto(msg._pack(rx_record.transaction_id, token_id), remote)
def generate_client_port(self, ):
if self.sem_counter >= 1000:
self.sem_counter = 0
self.sem.acquire()
self.sem_counter += 1
sem_counter = self.sem_counter
self.sem.release()
client_port = self.local_client_port_ + sem_counter
return client_port
| <filename>eds/openmtc-gevent/server/openmtc-scl/src/openmtc_scl/plugins/lwm2m_dm_server/DMServerCore.py
from gevent.server import DatagramServer
from json import dumps, loads
from aplus import Promise
from lwm2m_lib.import_common_libs import connection, options, link, constants
from lwm2m_lib.operations.Registration import Registration, Endpoint
from lwm2m_lib.operations.ObservationNotification import ObservationNotificationEngine, GeneralObservationInformation
from lwm2m_lib.operations.Execution import Execution
from lwm2m_lib.operations.Discovery import Discovery
from lwm2m_lib.operations.Read import Read
from lwm2m_lib.operations.Write import Write
from lwm2m_lib.operations.Create import Create
from lwm2m_lib.operations.WriteAttributes import WriteAttributes
from lwm2m_lib.operations.OperationRequest import OperationRequest
from lwm2m_lib.data_model.ParseQueryPayload import ParsePath, ParsePayload, ParseQuery
from lwm2m_lib.data_model.ClientsCollection import ClientEndpoint, LWM2MResourceTree #ClientsCollection
from lwm2m_lib.operations.OperationRequest import OperationRequest
from lwm2m_lib.api import lwm2m_api
from gevent.coros import Semaphore
# Constants
OBSERVE_OPTION_VALUE_OBSERVATION = 0
OBSERVE_OPTION_VALUE_CANCEL_OBSERVATION = 1
URI_QUERY_VALUE = 15
LOCATION_VALUE = 8
URI_PATH_VALUE = 11
URI_HOST_VALUE = 3
URI_PORT_VALUE = 7
class DMServerCore(OperationRequest):
def __init__(self, server_ip, server_port, client_ip, client_port):
super(DMServerCore, self).__init__()
self.lwm2m_dm_server_ip = server_ip
self.lwm2m_dm_server_port = server_port
self.local_client_ip_ = client_ip
self.local_client_port_ = client_port
self.sem = Semaphore()
self.sem_counter = 0
self.lwm2m_resources = LWM2MResourceTree()
self.registration = Registration(self.lwm2m_resources)
self.execution = Execution(self.lwm2m_resources)
self.discover = Discovery(lwm2m_resources=self.lwm2m_resources)
self.observation = ObservationNotificationEngine(self.lwm2m_resources)
self.read = Read(self.lwm2m_resources)
self.write = Write(self.lwm2m_resources)
self.create_object_instance = Create(self.lwm2m_resources)
self.write_attributes = WriteAttributes(self.lwm2m_resources)
def create_server(self, ):
""" Creates and starts a LWM2M DM Server using Gevent DatagramServer. The server
listens at the ip and port specified below. A handler is used to entertain the
requests coming at that port """
self.dm_server = DatagramServer((self.lwm2m_dm_server_ip, \
self.lwm2m_dm_server_port), self.handle_request)
self.dm_server.start()
def stop_server(self, ):
""" Stops the LWM2M DM Server """
self.dm_server.stop()
def handle_request(self, message, remote):
""" Handles the requests coming at the specified ip and port """
rx_record = connection.ReceptionRecord(None, message, remote)
msg = rx_record.message
uri_query = msg.findOption(options.UriQuery)
self.process(rx_record, remote, uri_query)
def handle_lwm2m_put(self, msg, uri_query, remote, rx_record):
""" It consists of Normal Update, Write Operation, Write Attribute Operation.
Write Operation is used to update the resource(s) as per the request. Write
Attributes operation is used to update the attributes of the object, object
instance or resource. """
method = None
try:
method = uri_query[0].value.split("=")[1]
except:
pass
if method == "write":
path = msg.findOption(URI_PATH_VALUE)
content_type_number = msg.findOption(options.ContentType)
if content_type_number is None:
content_type = "text/plain"
else:
content_type = constants.media_types[content_type_number.value]
self.write.write_resource(msg.payload, path, content_type)
payload_forward = msg.payload
msg = connection.Message(connection.Message.ACK, code=constants.CHANGED, payload="Resource Updated")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
client_port = self.generate_client_port()
self.write.forward_write_request(path, payload_forward, \
content_type, remote, client_port)
elif method == "write_attributes":
path = msg.findOption(URI_PATH_VALUE)
content_type_number = msg.findOption(options.ContentType)
if content_type_number is None:
content_type = "text/plain"
else:
content_type = constants.media_types[content_type_number.value]
payload = loads(msg.payload)
self.write_attributes.set_attributes(path, remote, payload)
msg = connection.Message(connection.Message.ACK, code=constants.CHANGED, payload="Resource Attributes Updated")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
client_port = self.generate_client_port()
self.write_attributes.forward_request(path, remote, payload, content_type, client_port)
else:
endpoint_location = msg.findOption(URI_PATH_VALUE)[0].value
if msg.payload == "":
self.logger.info("Updating the Registration Params")
endpoint_object = self.lwm2m_resources.return_endpoint_object(endpoint_location=endpoint_location)
endpoint_object.listener_ip = uri_query[6].value.split("=")[1]
endpoint_object.local_ip = uri_query[6].value.split("=")[1]
msg = connection.Message(connection.Message.ACK, code=constants.CHANGED, payload="Resource Updated")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
else:
self.logger.info("Adding/Updating the Resources")
payload = self.update_resource(loads(msg.payload), endpoint_location=endpoint_location)
msg = connection.Message(connection.Message.ACK, code=constants.CHANGED, payload="Resource Updated")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
self.logger.info("Forwarding the Notification")
request = lwm2m_api()
client_port = self.generate_client_port()
response = request.send_notification(self.general_observation.listener_ip, self.general_observation.listener_port, \
self.general_observation.token_id, payload, content_type="application/json", client_port=client_port)
def update_resource(self, res_payload, endpoint_location=None, endpoint_name=None):
total_res_dict = {}
total_object_info = {}
payload = res_payload
endpoint_object = self.registration.handle_put_resource_updates(res_payload, endpoint_location=endpoint_location, endpoint_name=endpoint_name)
for item, value in payload.iteritems():
resources_dict = endpoint_object.objects_dict[item]["object"].resources_id_dict
res_dict = {}
for item1, value1 in resources_dict.iteritems():
res_dict.update({
item1 : value1["object"].res_value
})
total_res_dict.update({
item : {"resources" : res_dict }
})
total_object_info = {endpoint_object.endpoint_name : total_res_dict}
return total_object_info
def process(self, rx_record, remote, uri_query):
""" Processes various requests like CON (POST, PUT, GET) or NON.
POST requests : Generally used for Registration and Execution
PUT requests : Generally used for Updating the resources
GET requests : Generally used for Discovery, Observation, Cancel Observation """
msg = rx_record.message
self.uri_query = uri_query
if msg.transaction_type == connection.Message.CON:
if constants.POST == msg.code:
method = None
try:
method = uri_query[0].value.split("=")[1]
except:
pass
if method == "create":
path = msg.findOption(URI_PATH_VALUE)
content_type_number = msg.findOption(options.ContentType)
if content_type_number is None:
content_type = "text/plain"
else:
content_type = constants.media_types[content_type_number.value]
self.create_object_instance.create_instance(path, remote, content_type, loads(msg.payload))
resources = loads(msg.payload)
msg = connection.Message(connection.Message.ACK, code=constants.CREATED, payload="Resource Created")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
client_port = self.generate_client_port()
self.create_object_instance.forward_request(path, remote, resources, content_type, client_port)
elif method == "execute":
path = msg.findOption(URI_PATH_VALUE)
content_type_number = msg.findOption(options.ContentType)
if content_type_number is None:
content_type = "text/plain"
else:
content_type = constants.media_types[content_type_number.value]
self.execution.execute_resource(path, remote, msg.payload)
execute_payload = msg.payload
msg = connection.Message(connection.Message.ACK, code=constants.CHANGED, payload="Resource Executed")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
client_port = self.generate_client_port()
self.execution.forward_request(path, remote, execute_payload, client_port)
elif method == "notify":
self.logger.info("Notification Received")
client_port = self.generate_client_port()
for item1, item2 in loads(msg.payload).iteritems():
if item1 == "observer_ip":
observer_ip = item2
elif item1 == "observer_port":
observer_port = item2
elif item1 != "observer_ip" and item1 != "observer_port":
endpoint_name = item1
for item3, item4 in item2.iteritems():
for item5, item6 in item4["resources"].iteritems():
pass
res = {
item3 : {"resources" : {item5.split("_")[0]:{"res_value" : item6, "res_inst_id" : item5.split("_")[1]}}}
}
payload = {}
payload = self.update_resource(res, endpoint_name=endpoint_name)
payload["observer_ip"] = observer_ip
payload["observer_port"] = observer_port
token_id = msg.token
observe_value = msg.findOption(options.Observe).value
self.logger.info("Forwarding Notification")
content_type = "application/json"
request = lwm2m_api()
response = request.send_notification(self.general_observation.listener_ip, self.general_observation.listener_port, token_id, payload, \
content_type=content_type, time_elapse=observe_value, client_port=client_port)
msg = connection.Message(connection.Message.ACK, code=constants.CREATED, payload="Notification Received")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
else:
""" Handles the Client Registration Request """
self.logger.info("Registering Client Endpoint in the LWM2M DM Server")
endpoint = self.registration.process_registration(msg, uri_query)
response = self.registration.register_client(endpoint)
registered_client_location = response
if registered_client_location is not None:
self.logger.info("Client Endpoint Registration Successful for Endpoint : %s", endpoint.endpoint_name)
self.logger.info("The registered location is %s", registered_client_location)
payload = self.set_general_observation_params()
else:
self.logger.info("Client Endpoint Registration Failed")
msg = connection.Message(connection.Message.ACK, code=constants.CREATED, location=registered_client_location)
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
#Send the General Observation to the Registered Client
#self.send_general_observation(registered_client_location)
elif constants.PUT == msg.code:
""" It consists of Normal Update, Write Operation, Write Attribute Operation.
Write Operation is used to update the resource(s) as per the request. Write
Attributes operation is used to update the attributes of the object, object
instance or resource. """
self.handle_lwm2m_put(msg, uri_query, remote, rx_record)
elif constants.GET == msg.code:
""" Handles Requests like Discovery, Observation """
try:
observe_value = msg.findOption(options.Observe).value
except:
observe_value = ""
if observe_value == OBSERVE_OPTION_VALUE_OBSERVATION:
""" Sets the Observation. Two types of observations. General Observation
and Specific Observation. General Observation is used for anything that is
not observed and updates are sent as general notifications using a general
token. Specific observation is implicitly defined by the observer(as request)
and handled as specific notification with a specific token """
path = msg.findOption(URI_PATH_VALUE)
if len(path) == 1:
self.set_m2m_server_adapter_params(rx_record, remote)
else:
self.logger.info("Specific Observation Request Received")
content_type_number = msg.findOption(options.ContentType)
if content_type_number is None:
content_type = "text/plain"
else:
content_type = constants.media_types[content_type_number.value]
token_id = msg.token
app_ip = loads(msg.payload)["app_ip"]
app_port = loads(msg.payload)["app_port"]
client_port = self.generate_client_port()
response = self.observation.forward_request(path, remote, observe_value, \
self.lwm2m_dm_server_ip, self.lwm2m_dm_server_port, \
app_ip, app_port, token_id, client_port)
msg = connection.Message(connection.Message.ACK, code=constants.CONTENT, \
payload="test") #todo: payload to be replaced
self.dm_server.sendto(msg._pack(rx_record.transaction_id, token_id), remote)
elif observe_value == OBSERVE_OPTION_VALUE_CANCEL_OBSERVATION:
""" Removes the observation from the List """
self.logger.info("Cancel Observation Request Received")
path = msg.findOption(URI_PATH_VALUE)
token_id = msg.token
app_ip = loads(msg.payload)["app_ip"]
app_port = loads(msg.payload)["app_port"]
client_port = self.generate_client_port()
response = self.observation.forward_request(path, remote, observe_value, \
self.lwm2m_dm_server_ip, self.lwm2m_dm_server_port, \
app_ip, app_port, token_id, client_port)
def _handle_response(response):
msg = connection.Message(connection.Message.ACK, code=constants.CONTENT, payload=response)
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
response.then(_handle_response)
else:
method = None
try:
method = uri_query[0].value.split("=")[1]
except:
pass
if method == "read":
path = msg.findOption(URI_PATH_VALUE)
self.read.read_resource(path, remote)
msg = connection.Message(connection.Message.ACK, code=constants.CONTENT, \
payload="info read", content_type="text/plain")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
elif method == "discover":
if msg.payload == "/.well-known/core":
payload = dumps(self.discover.get_all_resources())
else:
path = msg.findOption(URI_PATH_VALUE)
client_port = self.generate_client_port()
payload = self.discover.forward_request(path, remote, client_port)
def _handle_response(payload):
msg = connection.Message(connection.Message.ACK, code=constants.CONTENT, \
payload=payload, content_type="application/json")
self.dm_server.sendto(msg._pack(rx_record.transaction_id), remote)
if payload is Promise:
payload.then(_handle_response)
else:
_handle_response(payload)
elif msg.transaction_type == connection.Message.NON:
print "reached msg non"
payload = msg.payload
print payload
def set_general_observation_params(self, ):
return {"listener_ip" : self.lwm2m_dm_server_ip, "listener_port" : self.lwm2m_dm_server_port}
def send_general_observation(self, registered_client_location):
if registered_client_location is not None:
payload = dumps(self.set_general_observation_params())
endpoint_object = self.lwm2m_resources.return_endpoint_object(endpoint_location=registered_client_location)
client_listener_ip = endpoint_object.listener_ip
client_listener_port = endpoint_object.listener_port
request = lwm2m_api()
response = request.observe_resource(client_listener_ip, client_listener_port, \
payload=payload, client_port=self.generate_client_port())
def set_m2m_server_adapter_params(self, rx_record, remote):
msg = rx_record.message
#content_type is application/json
listener_ip = loads(msg.payload)["listener_ip"]
listener_port = loads(msg.payload)["listener_port"]
token_id = msg.token
self.general_observation = GeneralObservationInformation(listener_ip, listener_port, token_id)
response = "Observation Started on the LWM2M Server"
msg = connection.Message(connection.Message.ACK, code=constants.CONTENT, payload=response)
self.dm_server.sendto(msg._pack(rx_record.transaction_id, token_id), remote)
def generate_client_port(self, ):
if self.sem_counter >= 1000:
self.sem_counter = 0
self.sem.acquire()
self.sem_counter += 1
sem_counter = self.sem_counter
self.sem.release()
client_port = self.local_client_port_ + sem_counter
return client_port
| en | 0.836542 | #ClientsCollection # Constants Creates and starts a LWM2M DM Server using Gevent DatagramServer. The server listens at the ip and port specified below. A handler is used to entertain the requests coming at that port Stops the LWM2M DM Server Handles the requests coming at the specified ip and port It consists of Normal Update, Write Operation, Write Attribute Operation. Write Operation is used to update the resource(s) as per the request. Write Attributes operation is used to update the attributes of the object, object instance or resource. Processes various requests like CON (POST, PUT, GET) or NON. POST requests : Generally used for Registration and Execution PUT requests : Generally used for Updating the resources GET requests : Generally used for Discovery, Observation, Cancel Observation Handles the Client Registration Request #Send the General Observation to the Registered Client #self.send_general_observation(registered_client_location) It consists of Normal Update, Write Operation, Write Attribute Operation. Write Operation is used to update the resource(s) as per the request. Write Attributes operation is used to update the attributes of the object, object instance or resource. Handles Requests like Discovery, Observation Sets the Observation. Two types of observations. General Observation and Specific Observation. General Observation is used for anything that is not observed and updates are sent as general notifications using a general token. Specific observation is implicitly defined by the observer(as request) and handled as specific notification with a specific token #todo: payload to be replaced Removes the observation from the List #content_type is application/json | 1.592084 | 2 |
mmdeploy/backend/torchscript/wrapper.py | xizi/mmdeploy | 746 | 6614152 | <filename>mmdeploy/backend/torchscript/wrapper.py
# Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
from typing import Dict, Optional, Sequence, Union
import torch
from mmdeploy.utils import Backend
from mmdeploy.utils.timer import TimeCounter
from ..base import BACKEND_WRAPPER, BaseWrapper
from .init_plugins import get_ops_path
@BACKEND_WRAPPER.register_module(Backend.TORCHSCRIPT.value)
class TorchscriptWrapper(BaseWrapper):
"""Torchscript engine wrapper for inference.
Args:
model (torch.jit.RecursiveScriptModule): torchscript engine to wrap.
input_names (Sequence[str] | None): Names of model inputs in order.
Defaults to `None` and the wrapper will accept list or Tensor.
output_names (Sequence[str] | None): Names of model outputs in order.
Defaults to `None` and the wrapper will return list or Tensor.
Note:
If the engine is converted from onnx model. The input_names and
output_names should be the same as onnx model.
Examples:
>>> from mmdeploy.backend.torchscript import TorchscriptWrapper
>>> engine_file = 'resnet.engine'
>>> model = TorchscriptWrapper(engine_file, input_names=['input'], \
>>> output_names=['output'])
>>> inputs = dict(input=torch.randn(1, 3, 224, 224))
>>> outputs = model(inputs)
>>> print(outputs)
"""
def __init__(self,
model: Union[str, torch.jit.RecursiveScriptModule],
input_names: Optional[Sequence[str]] = None,
output_names: Optional[Sequence[str]] = None):
# load custom ops if exist
custom_ops_path = get_ops_path()
if osp.exists(custom_ops_path):
torch.ops.load_library(custom_ops_path)
super().__init__(output_names)
self.ts_model = model
if isinstance(self.ts_model, str):
self.ts_model = torch.jit.load(self.ts_model)
assert isinstance(self.ts_model, torch.jit.RecursiveScriptModule
), 'failed to load torchscript model.'
self._input_names = input_names
self._output_names = output_names
def forward(
self, inputs: Union[torch.Tensor, Sequence[torch.Tensor],
Dict[str, torch.Tensor]]
) -> Union[torch.Tensor, Sequence[torch.Tensor], Dict[str, torch.Tensor]]:
"""Run forward inference.
Args:
inputs (torch.Tensor | Sequence[torch.Tensor] | Dict[str,
torch.Tensor]): The input tensor, or tensor sequence, or pairs
of input names and tensors.
Return:
outputs (torch.Tensor | Sequence[torch.Tensor] | Dict[str,
torch.Tensor]): The input tensor, or tensor sequence, or pairs
of input names and tensors.
"""
is_dict_inputs = isinstance(inputs, Dict)
if is_dict_inputs:
# inputs to dict
assert self._input_names is not None, \
'input names have not been given.'
inputs = [inputs[input_name] for input_name in self._input_names]
elif isinstance(inputs, torch.Tensor):
inputs = [inputs]
outputs = self.__torchscript_execute(inputs)
if self._output_names is not None and is_dict_inputs:
# output to dict
if isinstance(outputs, torch.Tensor):
outputs = [outputs]
outputs = dict(zip(self._output_names, outputs))
if isinstance(outputs, tuple) and self._output_names is not None:
assert len(outputs) == len(self._output_names)
outputs = dict(zip(self._output_names, outputs))
return outputs
@TimeCounter.count_time()
def __torchscript_execute(
self, inputs: Sequence[torch.Tensor]) -> Sequence[torch.Tensor]:
"""Run inference with TorchScript.
Args:
inputs (Sequence[torch.Tensor]): A list of integer binding the
input/output.
Returns:
torch.Tensor | Sequence[torch.Tensor]: The inference outputs from
TorchScript.
"""
return self.ts_model(*inputs)
| <filename>mmdeploy/backend/torchscript/wrapper.py
# Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
from typing import Dict, Optional, Sequence, Union
import torch
from mmdeploy.utils import Backend
from mmdeploy.utils.timer import TimeCounter
from ..base import BACKEND_WRAPPER, BaseWrapper
from .init_plugins import get_ops_path
@BACKEND_WRAPPER.register_module(Backend.TORCHSCRIPT.value)
class TorchscriptWrapper(BaseWrapper):
"""Torchscript engine wrapper for inference.
Args:
model (torch.jit.RecursiveScriptModule): torchscript engine to wrap.
input_names (Sequence[str] | None): Names of model inputs in order.
Defaults to `None` and the wrapper will accept list or Tensor.
output_names (Sequence[str] | None): Names of model outputs in order.
Defaults to `None` and the wrapper will return list or Tensor.
Note:
If the engine is converted from onnx model. The input_names and
output_names should be the same as onnx model.
Examples:
>>> from mmdeploy.backend.torchscript import TorchscriptWrapper
>>> engine_file = 'resnet.engine'
>>> model = TorchscriptWrapper(engine_file, input_names=['input'], \
>>> output_names=['output'])
>>> inputs = dict(input=torch.randn(1, 3, 224, 224))
>>> outputs = model(inputs)
>>> print(outputs)
"""
def __init__(self,
model: Union[str, torch.jit.RecursiveScriptModule],
input_names: Optional[Sequence[str]] = None,
output_names: Optional[Sequence[str]] = None):
# load custom ops if exist
custom_ops_path = get_ops_path()
if osp.exists(custom_ops_path):
torch.ops.load_library(custom_ops_path)
super().__init__(output_names)
self.ts_model = model
if isinstance(self.ts_model, str):
self.ts_model = torch.jit.load(self.ts_model)
assert isinstance(self.ts_model, torch.jit.RecursiveScriptModule
), 'failed to load torchscript model.'
self._input_names = input_names
self._output_names = output_names
def forward(
self, inputs: Union[torch.Tensor, Sequence[torch.Tensor],
Dict[str, torch.Tensor]]
) -> Union[torch.Tensor, Sequence[torch.Tensor], Dict[str, torch.Tensor]]:
"""Run forward inference.
Args:
inputs (torch.Tensor | Sequence[torch.Tensor] | Dict[str,
torch.Tensor]): The input tensor, or tensor sequence, or pairs
of input names and tensors.
Return:
outputs (torch.Tensor | Sequence[torch.Tensor] | Dict[str,
torch.Tensor]): The input tensor, or tensor sequence, or pairs
of input names and tensors.
"""
is_dict_inputs = isinstance(inputs, Dict)
if is_dict_inputs:
# inputs to dict
assert self._input_names is not None, \
'input names have not been given.'
inputs = [inputs[input_name] for input_name in self._input_names]
elif isinstance(inputs, torch.Tensor):
inputs = [inputs]
outputs = self.__torchscript_execute(inputs)
if self._output_names is not None and is_dict_inputs:
# output to dict
if isinstance(outputs, torch.Tensor):
outputs = [outputs]
outputs = dict(zip(self._output_names, outputs))
if isinstance(outputs, tuple) and self._output_names is not None:
assert len(outputs) == len(self._output_names)
outputs = dict(zip(self._output_names, outputs))
return outputs
@TimeCounter.count_time()
def __torchscript_execute(
self, inputs: Sequence[torch.Tensor]) -> Sequence[torch.Tensor]:
"""Run inference with TorchScript.
Args:
inputs (Sequence[torch.Tensor]): A list of integer binding the
input/output.
Returns:
torch.Tensor | Sequence[torch.Tensor]: The inference outputs from
TorchScript.
"""
return self.ts_model(*inputs)
| en | 0.58721 | # Copyright (c) OpenMMLab. All rights reserved. Torchscript engine wrapper for inference. Args: model (torch.jit.RecursiveScriptModule): torchscript engine to wrap. input_names (Sequence[str] | None): Names of model inputs in order. Defaults to `None` and the wrapper will accept list or Tensor. output_names (Sequence[str] | None): Names of model outputs in order. Defaults to `None` and the wrapper will return list or Tensor. Note: If the engine is converted from onnx model. The input_names and output_names should be the same as onnx model. Examples: >>> from mmdeploy.backend.torchscript import TorchscriptWrapper >>> engine_file = 'resnet.engine' >>> model = TorchscriptWrapper(engine_file, input_names=['input'], \ >>> output_names=['output']) >>> inputs = dict(input=torch.randn(1, 3, 224, 224)) >>> outputs = model(inputs) >>> print(outputs) # load custom ops if exist Run forward inference. Args: inputs (torch.Tensor | Sequence[torch.Tensor] | Dict[str, torch.Tensor]): The input tensor, or tensor sequence, or pairs of input names and tensors. Return: outputs (torch.Tensor | Sequence[torch.Tensor] | Dict[str, torch.Tensor]): The input tensor, or tensor sequence, or pairs of input names and tensors. # inputs to dict # output to dict Run inference with TorchScript. Args: inputs (Sequence[torch.Tensor]): A list of integer binding the input/output. Returns: torch.Tensor | Sequence[torch.Tensor]: The inference outputs from TorchScript. | 2.201832 | 2 |
example/bar.py | Hasenpfote/malloc_tracer | 2 | 6614153 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
class Klass(object):
CONSTANT = 'CONSTANT'
def __init__(self, value):
self._value = value
def method(self, x):
dataset1 = np.empty((100, ), dtype=np.float64)
print('x', x)
dataset1 = np.empty((1000, ), dtype=np.float64)
l = [i for i in range(100000)]
if x == 0:
dataset4a = np.empty((100000, ), dtype=np.float64)
return 0
elif x == 1:
dataset4b = np.empty((100000, ), dtype=np.float64)
return 1
dataset3 = np.empty((3000, ), dtype=np.float64)
return 2
@staticmethod
def smethod():
dataset = np.empty((100, ), dtype=np.float64)
l = [i for i in range(100000)]
print('Hello')
return dataset
@classmethod
def cmethod(cls, var):
return cls.CONSTANT + var
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
class Klass(object):
CONSTANT = 'CONSTANT'
def __init__(self, value):
self._value = value
def method(self, x):
dataset1 = np.empty((100, ), dtype=np.float64)
print('x', x)
dataset1 = np.empty((1000, ), dtype=np.float64)
l = [i for i in range(100000)]
if x == 0:
dataset4a = np.empty((100000, ), dtype=np.float64)
return 0
elif x == 1:
dataset4b = np.empty((100000, ), dtype=np.float64)
return 1
dataset3 = np.empty((3000, ), dtype=np.float64)
return 2
@staticmethod
def smethod():
dataset = np.empty((100, ), dtype=np.float64)
l = [i for i in range(100000)]
print('Hello')
return dataset
@classmethod
def cmethod(cls, var):
return cls.CONSTANT + var
| en | 0.308914 | #!/usr/bin/env python3 # -*- coding: utf-8 -*- | 3.084776 | 3 |
decomposition/Tucker.py | NieCha/TensorNetwork | 4 | 6614154 | import numpy as np
import tensorly
import copy
import torch as tc
def hosvd(x):
"""
:param x: 待分解的张量
:return G: 核张量
:return U: 变换矩阵
:return lm: 各个键约化矩阵的本征谱
"""
ndim = x.ndim
U = list() # 用于存取各个变换矩阵
lm = list() # 用于存取各个键约化矩阵的本征谱
x = tc.from_numpy(x)
for n in range(ndim):
index = list(range(ndim))
index.pop(n)
_mat = tc.tensordot(x, x, [index, index])
_lm, _U = tc.symeig(_mat, eigenvectors=True)
lm.append(_lm.numpy())
U.append(_U)
# 计算核张量
G = tucker_product(x, U)
U1 = [u.numpy() for u in U]
return G, U1, lm
def tucker_product(x, U, dim=1):
"""
:param x: 张量
:param U: 变换矩阵
:param dim: 收缩各个矩阵的第几个指标
:return G: 返回Tucker乘积的结果
"""
ndim = x.ndim
if type(x) is not tc.Tensor:
x = tc.from_numpy(x)
U1 = list()
for n in range(len(U)):
if type(U[n]) is not tc.Tensor:
U1.append(tc.from_numpy(U[n]))
else:
U1.append(U[n])
ind_x = ''
for n in range(ndim):
ind_x += chr(97 + n)
ind_x1 = ''
for n in range(ndim):
ind_x1 += chr(97 + ndim + n)
contract_eq = copy.deepcopy(ind_x)
for n in range(ndim):
if dim == 0:
contract_eq += ',' + ind_x[n] + ind_x1[n]
else:
contract_eq += ',' + ind_x1[n] + ind_x[n]
contract_eq += '->' + ind_x1
# print(x.shape, U[0].shape, U[1].shape, U[2].shape)
# print(type(contract_eq), contract_eq)
G = tc.einsum(contract_eq, [x] + U1)
G = G.numpy()
return G
# HOOI higher-order orthogonal iteration
#使用HOSVD初始化,然后采用ALS迭代求解
def HOOI(tensor, rank=None, n_iter_max=100, init='svd', svd='numpy_svd', tol=0.0001):
return tensorly.decomposition.Tucker(tensor, rank=None, n_iter_max=100, init='svd', svd='numpy_svd', tol=0.0001)
| import numpy as np
import tensorly
import copy
import torch as tc
def hosvd(x):
"""
:param x: 待分解的张量
:return G: 核张量
:return U: 变换矩阵
:return lm: 各个键约化矩阵的本征谱
"""
ndim = x.ndim
U = list() # 用于存取各个变换矩阵
lm = list() # 用于存取各个键约化矩阵的本征谱
x = tc.from_numpy(x)
for n in range(ndim):
index = list(range(ndim))
index.pop(n)
_mat = tc.tensordot(x, x, [index, index])
_lm, _U = tc.symeig(_mat, eigenvectors=True)
lm.append(_lm.numpy())
U.append(_U)
# 计算核张量
G = tucker_product(x, U)
U1 = [u.numpy() for u in U]
return G, U1, lm
def tucker_product(x, U, dim=1):
"""
:param x: 张量
:param U: 变换矩阵
:param dim: 收缩各个矩阵的第几个指标
:return G: 返回Tucker乘积的结果
"""
ndim = x.ndim
if type(x) is not tc.Tensor:
x = tc.from_numpy(x)
U1 = list()
for n in range(len(U)):
if type(U[n]) is not tc.Tensor:
U1.append(tc.from_numpy(U[n]))
else:
U1.append(U[n])
ind_x = ''
for n in range(ndim):
ind_x += chr(97 + n)
ind_x1 = ''
for n in range(ndim):
ind_x1 += chr(97 + ndim + n)
contract_eq = copy.deepcopy(ind_x)
for n in range(ndim):
if dim == 0:
contract_eq += ',' + ind_x[n] + ind_x1[n]
else:
contract_eq += ',' + ind_x1[n] + ind_x[n]
contract_eq += '->' + ind_x1
# print(x.shape, U[0].shape, U[1].shape, U[2].shape)
# print(type(contract_eq), contract_eq)
G = tc.einsum(contract_eq, [x] + U1)
G = G.numpy()
return G
# HOOI higher-order orthogonal iteration
#使用HOSVD初始化,然后采用ALS迭代求解
def HOOI(tensor, rank=None, n_iter_max=100, init='svd', svd='numpy_svd', tol=0.0001):
return tensorly.decomposition.Tucker(tensor, rank=None, n_iter_max=100, init='svd', svd='numpy_svd', tol=0.0001)
| zh | 0.537688 | :param x: 待分解的张量 :return G: 核张量 :return U: 变换矩阵 :return lm: 各个键约化矩阵的本征谱 # 用于存取各个变换矩阵 # 用于存取各个键约化矩阵的本征谱 # 计算核张量 :param x: 张量 :param U: 变换矩阵 :param dim: 收缩各个矩阵的第几个指标 :return G: 返回Tucker乘积的结果 # print(x.shape, U[0].shape, U[1].shape, U[2].shape) # print(type(contract_eq), contract_eq) # HOOI higher-order orthogonal iteration #使用HOSVD初始化,然后采用ALS迭代求解 | 2.324069 | 2 |
app/wiki_phil.py | chalence/reddit-algebra | 0 | 6614155 | <filename>app/wiki_phil.py
import urllib2
import sys
from bs4 import BeautifulSoup
import re
def strip_brackets(string):
"""
remove parenthesis from a string
leave parenthesis between "<a></a>" tags in place
"""
string = "" + str(string)
d = 0
k = 0
out = ''
for i in string:
#check for tag when not in parantheses mode
if d < 1:
if i == '>':
k-=1
if i =="<":
k += 1
#check for parentheses
if k < 1:
if i == '(':
d += 1
if d > 0:
out += ' '
else:
out += i
if i == ')' :
d -= 1
else:
out +=i
return out
class PhilosophyGame():
def __init__(self,verbose=True):
self.iter=0
self.path=[]
self.verbose = verbose
self.ptitle = re.compile(r'"wgPageName":"(.+?)"')
def trace(self,article):
site = urllib2.urlopen(article)
data = site.read()
self.last = article
self.lastprefix = self.last[:self.last.find("wiki/")+5]
wiktionary = False
if 'wiktionary' in self.lastprefix:
wiktionary = True
site.close()
soup = BeautifulSoup(data)
if self.iter ==0:
self.title = re.search(self.ptitle,str(soup)).group(1)
current_title = re.search(self.ptitle,str(soup)).group(1)
#self.path.append(current_title)
if self.verbose:
print self.iter, ' ', current_title
for s in soup.find_all('table'):
s.extract()
pnodes = []
for node in soup.find(id="bodyContent").find_all('p'):
# the first undecorated <p> should be the first paragraph
if node.attrs == {}:
pnodes.append(node)
num = 0
for node in pnodes:
try:
remove = ['span','sup']
if wiktionary: remove=['sup']
for s in node.find_all(remove):
s.extract()
stnode = strip_brackets(str(node))
trimmed=BeautifulSoup(stnode)
links = []
if not trimmed.find('a'):
raise TypeError('no links!')
for l in trimmed.find_all('a'):
links.append(l['href'])
break
except TypeError:
continue
#if links==[]:
# print "No links found on page!"
# print "Error article:", current_title
# print "Starting article:", self.title
# sys.exit(1)
# to remove articles that don't exist (yet)
next = [s for s in links if 'redlink' not in s][0]
# it's possible we get linked to wikitionary:
nextarticle = next[next.find('/wiki')+6:]
if 'wiktionary' in next:
nextlink = 'http://en.wiktionary.org/wiki/'
else:
nextlink = 'http://en.wikipedia.org/wiki/'
nextlink = nextlink + nextarticle
if nextarticle == 'Philosophy':
if self.verbose:
print "Made it to Philosophy! Number of iterations taken = ", self.iter
self.path.append(nextarticle)
return
else:
# does the next article match any previously visited article? Then we're in a loop
for a in self.path:
if a==nextarticle:
print "Infinite loop!", self.title
self.path.extend([nextarticle,'-LOOP-'])
return
self.iter = self.iter + 1
self.path.append(nextarticle)
self.trace(nextlink)
# input: name of article
# output: list of the path it took to philosophy
# or None if philosophy is not reached or error occurred
def search_article(article):
game = PhilosophyGame(verbose=False)
full_article = "http://en.wikipedia.org/wiki/" + article
try:
game.trace(full_article)
return game.path
except Exception:
return None
if __name__ == "__main__":
article = "Vermont"
game = PhilosophyGame(verbose=False)
full_article = "http://en.wikipedia.org/wiki/" + article
print "source article = ", full_article
try:
game.trace(full_article)
print "path to philosophy = ", game.path
except Exception:
print "something went wrong with ", article
| <filename>app/wiki_phil.py
import urllib2
import sys
from bs4 import BeautifulSoup
import re
def strip_brackets(string):
"""
remove parenthesis from a string
leave parenthesis between "<a></a>" tags in place
"""
string = "" + str(string)
d = 0
k = 0
out = ''
for i in string:
#check for tag when not in parantheses mode
if d < 1:
if i == '>':
k-=1
if i =="<":
k += 1
#check for parentheses
if k < 1:
if i == '(':
d += 1
if d > 0:
out += ' '
else:
out += i
if i == ')' :
d -= 1
else:
out +=i
return out
class PhilosophyGame():
def __init__(self,verbose=True):
self.iter=0
self.path=[]
self.verbose = verbose
self.ptitle = re.compile(r'"wgPageName":"(.+?)"')
def trace(self,article):
site = urllib2.urlopen(article)
data = site.read()
self.last = article
self.lastprefix = self.last[:self.last.find("wiki/")+5]
wiktionary = False
if 'wiktionary' in self.lastprefix:
wiktionary = True
site.close()
soup = BeautifulSoup(data)
if self.iter ==0:
self.title = re.search(self.ptitle,str(soup)).group(1)
current_title = re.search(self.ptitle,str(soup)).group(1)
#self.path.append(current_title)
if self.verbose:
print self.iter, ' ', current_title
for s in soup.find_all('table'):
s.extract()
pnodes = []
for node in soup.find(id="bodyContent").find_all('p'):
# the first undecorated <p> should be the first paragraph
if node.attrs == {}:
pnodes.append(node)
num = 0
for node in pnodes:
try:
remove = ['span','sup']
if wiktionary: remove=['sup']
for s in node.find_all(remove):
s.extract()
stnode = strip_brackets(str(node))
trimmed=BeautifulSoup(stnode)
links = []
if not trimmed.find('a'):
raise TypeError('no links!')
for l in trimmed.find_all('a'):
links.append(l['href'])
break
except TypeError:
continue
#if links==[]:
# print "No links found on page!"
# print "Error article:", current_title
# print "Starting article:", self.title
# sys.exit(1)
# to remove articles that don't exist (yet)
next = [s for s in links if 'redlink' not in s][0]
# it's possible we get linked to wikitionary:
nextarticle = next[next.find('/wiki')+6:]
if 'wiktionary' in next:
nextlink = 'http://en.wiktionary.org/wiki/'
else:
nextlink = 'http://en.wikipedia.org/wiki/'
nextlink = nextlink + nextarticle
if nextarticle == 'Philosophy':
if self.verbose:
print "Made it to Philosophy! Number of iterations taken = ", self.iter
self.path.append(nextarticle)
return
else:
# does the next article match any previously visited article? Then we're in a loop
for a in self.path:
if a==nextarticle:
print "Infinite loop!", self.title
self.path.extend([nextarticle,'-LOOP-'])
return
self.iter = self.iter + 1
self.path.append(nextarticle)
self.trace(nextlink)
# input: name of article
# output: list of the path it took to philosophy
# or None if philosophy is not reached or error occurred
def search_article(article):
game = PhilosophyGame(verbose=False)
full_article = "http://en.wikipedia.org/wiki/" + article
try:
game.trace(full_article)
return game.path
except Exception:
return None
if __name__ == "__main__":
article = "Vermont"
game = PhilosophyGame(verbose=False)
full_article = "http://en.wikipedia.org/wiki/" + article
print "source article = ", full_article
try:
game.trace(full_article)
print "path to philosophy = ", game.path
except Exception:
print "something went wrong with ", article
| en | 0.818341 | remove parenthesis from a string leave parenthesis between "<a></a>" tags in place #check for tag when not in parantheses mode #check for parentheses #self.path.append(current_title) # the first undecorated <p> should be the first paragraph #if links==[]: # print "No links found on page!" # print "Error article:", current_title # print "Starting article:", self.title # sys.exit(1) # to remove articles that don't exist (yet) # it's possible we get linked to wikitionary: # does the next article match any previously visited article? Then we're in a loop # input: name of article # output: list of the path it took to philosophy # or None if philosophy is not reached or error occurred | 3.310197 | 3 |
karp5/tests/cli/test_recover.py | spraakbanken/karp-backend-v5 | 4 | 6614156 | <filename>karp5/tests/cli/test_recover.py
import pytest
@pytest.mark.xfail(reason="fails though the command works live.")
def test_cli_recover(cli_w_foo):
mode = "foo"
lexicon = "foo"
suffix = "test_cli_recover"
r = cli_w_foo.recover_mode(mode, lexicons=[lexicon], suffix=suffix)
assert r.exit_code == 0
| <filename>karp5/tests/cli/test_recover.py
import pytest
@pytest.mark.xfail(reason="fails though the command works live.")
def test_cli_recover(cli_w_foo):
mode = "foo"
lexicon = "foo"
suffix = "test_cli_recover"
r = cli_w_foo.recover_mode(mode, lexicons=[lexicon], suffix=suffix)
assert r.exit_code == 0
| none | 1 | 1.896495 | 2 | |
mpf/core/__init__.py | Scottacus64/mpf | 163 | 6614157 | """Core modules in MPF."""
| """Core modules in MPF."""
| en | 0.458839 | Core modules in MPF. | 0.97831 | 1 |
pfunk/utils/publishing.py | capless/pfunk | 5 | 6614158 | from faunadb import query as q
from faunadb.errors import BadRequest
def create_or_update_role(client, payload:dict={}):
"""
Utility that attempts to create a role and if that fails it attempts to update it.
Args:
client: FaunaClient instance
payload: dict containing the details about the role
Returns: query
"""
try:
response = client.query(
q.create_role(payload)
)
except BadRequest as err:
payload_copy = payload.copy()
role_name = payload_copy.pop("name")
response = client.query(
q.update(
q.role(role_name),
payload_copy
)
)
return response
def create_or_update_function(client, payload):
"""
Utility that attempts to create a function and if that fails it attempts to update it.
Args:
client: FaunaClient instance
payload: dict contains the details about the function
Returns: query
"""
try:
response = client.query(
q.create_function(
payload
)
)
except BadRequest as e:
payload_copy = payload.copy()
function_name = payload_copy.pop('name')
response = client.query(
q.update(
q.function(function_name),
payload_copy
)
)
return response | from faunadb import query as q
from faunadb.errors import BadRequest
def create_or_update_role(client, payload:dict={}):
"""
Utility that attempts to create a role and if that fails it attempts to update it.
Args:
client: FaunaClient instance
payload: dict containing the details about the role
Returns: query
"""
try:
response = client.query(
q.create_role(payload)
)
except BadRequest as err:
payload_copy = payload.copy()
role_name = payload_copy.pop("name")
response = client.query(
q.update(
q.role(role_name),
payload_copy
)
)
return response
def create_or_update_function(client, payload):
"""
Utility that attempts to create a function and if that fails it attempts to update it.
Args:
client: FaunaClient instance
payload: dict contains the details about the function
Returns: query
"""
try:
response = client.query(
q.create_function(
payload
)
)
except BadRequest as e:
payload_copy = payload.copy()
function_name = payload_copy.pop('name')
response = client.query(
q.update(
q.function(function_name),
payload_copy
)
)
return response | en | 0.878726 | Utility that attempts to create a role and if that fails it attempts to update it. Args: client: FaunaClient instance payload: dict containing the details about the role Returns: query Utility that attempts to create a function and if that fails it attempts to update it. Args: client: FaunaClient instance payload: dict contains the details about the function Returns: query | 2.546387 | 3 |
project/core/views.py | Nikhil7280/Project_H2O | 1 | 6614159 | <filename>project/core/views.py
from flask import render_template,request,Blueprint
core=Blueprint('core',__name__)
@core.route('/')
def index():
return render_template('index.html')
@core.route('/info')
def info():
# general info about company
return render_template('info.html')
@core.route('/contactus')
def contactus():
return render_template('contactus.html') | <filename>project/core/views.py
from flask import render_template,request,Blueprint
core=Blueprint('core',__name__)
@core.route('/')
def index():
return render_template('index.html')
@core.route('/info')
def info():
# general info about company
return render_template('info.html')
@core.route('/contactus')
def contactus():
return render_template('contactus.html') | en | 0.897911 | # general info about company | 2.30178 | 2 |
cpdb/data/migrations/0005_alter_officer_add_fields.py | invinst/CPDBv2_backend | 25 | 6614160 | <filename>cpdb/data/migrations/0005_alter_officer_add_fields.py
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-09-07 08:26
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('data', '0004_merge'),
]
operations = [
migrations.RemoveField(
model_name='officer',
name='age_at_march_11_2016',
),
migrations.RemoveField(
model_name='officer',
name='full_name',
),
migrations.AddField(
model_name='officer',
name='birth_year',
field=models.IntegerField(null=True),
),
migrations.AddField(
model_name='officer',
name='first_name',
field=models.CharField(blank=True, db_index=True, max_length=255, null=True),
),
migrations.AddField(
model_name='officer',
name='last_name',
field=models.CharField(blank=True, db_index=True, max_length=255, null=True),
),
]
| <filename>cpdb/data/migrations/0005_alter_officer_add_fields.py
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-09-07 08:26
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('data', '0004_merge'),
]
operations = [
migrations.RemoveField(
model_name='officer',
name='age_at_march_11_2016',
),
migrations.RemoveField(
model_name='officer',
name='full_name',
),
migrations.AddField(
model_name='officer',
name='birth_year',
field=models.IntegerField(null=True),
),
migrations.AddField(
model_name='officer',
name='first_name',
field=models.CharField(blank=True, db_index=True, max_length=255, null=True),
),
migrations.AddField(
model_name='officer',
name='last_name',
field=models.CharField(blank=True, db_index=True, max_length=255, null=True),
),
]
| en | 0.83361 | # -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-09-07 08:26 | 1.64743 | 2 |
JDjango/frames/mainFrame/events.py | JIYANG-PLUS/JDjango | 3 | 6614161 | from .listener import *
from ..sqliteFrame import *
"""
作用:实现事件功能
"""
class MainFrameFuncs(MainFrameListener):
def __init__(self, parent=None):
super().__init__(parent=parent)
self.order_container = (self.cmdCodes, self.info_cmdCodes,)
def onHelpsORM(self, e):
"""ORM帮助(一键生成)"""
dlg = ORMDialog(self)
dlg.ShowModal()
dlg.Close(True)
def onMenuVSCode(self, e):
"""外部发起VSCode编辑"""
# 检测是否配置code命令环境
if wx.Shell("code -v"):
dirname = get_configs(CONFIG_PATH)['dirname']
self.cmdVscode = subprocess.Popen(f'code {dirname}', shell=True)
self.cmdCodes.append(self.cmdVscode)
self.info_cmdCodes[self.cmdVscode] = '开启VSCode编辑器'
else:
self.infoBar.ShowMessage(f'未检测到code命令', wx.ICON_ERROR)
def onPortProgressVirtualView(self, e):
"""查看虚拟环境路径"""
RichMsgDialog.showOkMsgDialog(self, env.getPython3Env(), '虚拟环境路径')
@RegisterOriginOrderDecorator(msg = 'collectstatic')
@VirtualEnvMustExistDecorator()
def onPortProgressCollectstatic(self, e):
"""python manage.py collectstatic"""
return (
subprocess.Popen(f'{env.getDjangoOrderArgs()} collectstatic', shell=True)
, *self.order_container
)
@RegisterOriginOrderDecorator(msg = 'freeze')
@VirtualEnvMustExistDecorator()
def onPortProgressPipFreeze(self, e):
"""导出包pip freeze"""
return (
subprocess.Popen(f'{env.getPipOrderArgs(mode="freeze")}', shell=True)
, *self.order_container
)
@VirtualEnvMustExistDecorator()
def onPortProgressPipInstall(self, e):
"""虚拟环境安装包pip install"""
dlg = wx.TextEntryDialog(self, u"包名:", u"虚拟环境安装三方库", u"")
if dlg.ShowModal() == wx.ID_OK:
module_name = dlg.GetValue()
self.cmdPipInstall = subprocess.Popen(f'{env.getPipOrderArgs()} {module_name}', shell=True)
self.cmdCodes.append(self.cmdPipInstall)
self.info_cmdCodes[self.cmdPipInstall] = 'install'
dlg.Close(True)
@RegisterOriginOrderDecorator(msg = 'shell')
@VirtualEnvMustExistDecorator()
def onPortProgressShell(self, e):
"""python manage.py shell"""
return (
subprocess.Popen(f'{env.getDjangoOrderArgs()} shell', shell=True)
, *self.order_container
)
@RegisterOriginOrderDecorator(msg = 'makemigrations')
@VirtualEnvMustExistDecorator()
def onPortProgressMakemigrations(self, e):
"""python manage.py makemigrations"""
return (
subprocess.Popen(f'{env.getDjangoOrderArgs()} makemigrations', shell=True)
, *self.order_container
)
@RegisterOriginOrderDecorator(msg = 'migrate')
@VirtualEnvMustExistDecorator()
def onPortProgressMigrate(self, e):
"""python manage.py migtrate"""
return (
subprocess.Popen(f'{env.getDjangoOrderArgs()} migrate', shell=True)
, *self.order_container
)
@RegisterOriginOrderDecorator(msg = 'flush')
@VirtualEnvMustExistDecorator()
def onPortProgressFlush(self, e):
"""python manage.py flush"""
return (
subprocess.Popen(f'{env.getDjangoOrderArgs()} flush', shell=True)
, *self.order_container
)
@RegisterOriginOrderDecorator(msg = 'createsuperuser')
@VirtualEnvMustExistDecorator()
def onPortProgressCreatesuperuser(self, e):
"""python manage.py createsuperuser"""
return (
subprocess.Popen(f'{env.getDjangoOrderArgs()} createsuperuser', shell=True)
, *self.order_container
)
def onPortProgressVirtual(self, e):
"""创建虚拟环境"""
# venv.create(env_dir, system_site_packages=False, clear=False, symlinks=False, with_pip=False, prompt=None)
dlg = wx.DirDialog(self, u"选择即将写入的虚拟环境文件夹", style=wx.DD_DEFAULT_STYLE)
if dlg.ShowModal() == wx.ID_OK:
env_dir = dlg.GetPath()
t = len(os.listdir(env_dir))
if t > 0:
self.infoBar.ShowMessage(f'检测到选择的文件夹下存在其它文件,禁止操作。', wx.ICON_ERROR)
else:
venv.create(env_dir, system_site_packages=False, clear=True, symlinks=False, with_pip=True, prompt=None)
# 分操作系统自动绑定python解释器
this_platform = env.getPlatform().lower()
if 'windows' == this_platform:
temp_path = os.path.join(env_dir, 'Scripts', 'python.exe')
env.setPython3Env(temp_path)
self.infoBar.ShowMessage(f'创建并绑定成功,命令路径:{temp_path}', wx.ICON_INFORMATION)
elif 'darwin' == this_platform:
temp_path = os.path.join(env_dir, 'bin', 'python')
env.setPython3Env(temp_path)
self.infoBar.ShowMessage(f'创建并绑定成功,命令路径:{temp_path}', wx.ICON_INFORMATION)
else:
self.infoBar.ShowMessage(f'创建成功,虚拟目录:{env_dir}', wx.ICON_INFORMATION)
dlg.Destroy()
def onPortProgressKillProgress(self, e):
"""终止进程"""
dlg = wx.TextEntryDialog(self, u"占用端口号:", u"终止进程", u"")
if dlg.ShowModal() == wx.ID_OK:
port = dlg.GetValue()
env.killProgress(port = port)
self.infoBar.ShowMessage(f'已终止。', wx.ICON_INFORMATION)
dlg.Close(True)
def onPortProgressFaster(self, e):
"""一键配置镜像环境"""
rpath = os.path.expanduser('~')
# 根据系统依次安装镜像环境
platform = env.getPlatform().lower()
if 'windows' == platform:
if 'pip' in os.listdir(rpath):
pip_path = os.path.join(rpath, 'pip')
if 'pip.ini' in os.listdir(pip_path):
self.infoBar.ShowMessage(f'当前环境已配置镜像。', wx.ICON_WARNING)
else:
# TEMPLATE_DIR
write_file(os.path.join(pip_path, 'pip.ini'), read_file(os.path.join(TEMPLATE_DIR, 'pip', 'pip.ini')))
self.infoBar.ShowMessage(f'配置镜像环境成功。', wx.ICON_INFORMATION)
else:
pip_path = os.path.join(rpath, 'pip')
os.mkdir(pip_path)
write_file(os.path.join(pip_path, 'pip.ini'), read_file(os.path.join(TEMPLATE_DIR, 'pip', 'pip.ini')))
self.infoBar.ShowMessage(f'配置镜像环境成功。', wx.ICON_INFORMATION)
elif 'linux' == platform: # 理论上,Mac和Linux配置镜像环境步骤一致
if '.pip' in os.listdir(rpath):
pip_path = os.path.join(rpath, '.pip')
if 'pip.conf' in os.listdir(pip_path):
self.infoBar.ShowMessage(f'当前环境已配置镜像。', wx.ICON_WARNING)
else:
write_file(os.path.join(pip_path, 'pip.conf'), read_file(os.path.join(TEMPLATE_DIR, 'pip', 'pip.ini')))
self.infoBar.ShowMessage(f'配置镜像环境成功。', wx.ICON_INFORMATION)
else:
pip_path = os.path.join(rpath, '.pip')
os.mkdir(pip_path)
write_file(os.path.join(pip_path, 'pip.conf'), read_file(os.path.join(TEMPLATE_DIR, 'pip', 'pip.ini')))
self.infoBar.ShowMessage(f'配置镜像环境成功。', wx.ICON_INFORMATION)
elif 'darwin' == platform:
if '.pip' in os.listdir(rpath):
pip_path = os.path.join(rpath, '.pip')
if 'pip.conf' in os.listdir(pip_path):
self.infoBar.ShowMessage(f'当前环境已配置镜像。', wx.ICON_WARNING)
else:
write_file(os.path.join(pip_path, 'pip.conf'), read_file(os.path.join(TEMPLATE_DIR, 'pip', 'pip.ini')))
self.infoBar.ShowMessage(f'配置镜像环境成功。', wx.ICON_INFORMATION)
else:
pip_path = os.path.join(rpath, '.pip')
os.mkdir(pip_path)
write_file(os.path.join(pip_path, 'pip.conf'), read_file(os.path.join(TEMPLATE_DIR, 'pip', 'pip.ini')))
self.infoBar.ShowMessage(f'配置镜像环境成功。', wx.ICON_INFORMATION)
else:
self.infoBar.ShowMessage(f'未知系统', wx.ICON_WARNING)
def onModelsProxyGenerate(self, e):
"""创建代理模型"""
def onPortProgressStop(self, e):
"""关闭网站运行状态"""
try:
self.server.terminate()
env.killProgress()
except:
self.infoBar.ShowMessage(f'网站未正常启动或启动异常,导致关闭失败。', wx.ICON_ERROR)
else:
self.infos.AppendText(out_infos(f"网站已关闭。", level=1))
self.portProgressRun.Enable(True)
self.portProgressStop.Enable(False)
self.sys_toolbar.EnableTool(self.shotcut_run.GetId(), True)
self.sys_toolbar.EnableTool(self.shotcut_stop.GetId(), False)
self.infoBar.ShowMessage(f'网站已关闭。', wx.ICON_INFORMATION)
def onPortProgressVirtualChoice(self, e):
"""选择虚拟环境"""
dlg = wx.FileDialog(self, "选择虚拟环境下的python.exe文件", "", "", "*.*", wx.FD_OPEN)
if dlg.ShowModal() == wx.ID_OK:
env.setPython3Env(os.path.join(dlg.GetDirectory(), dlg.GetFilename()))
self.infoBar.ShowMessage(f'虚拟环境绑定成功!', wx.ICON_INFORMATION)
dlg.Close(True)
def onHelpSeeOrKill(self, e):
"""查看或终止进程"""
RichMsgDialog.showOkMsgDialog(self, CON_MSG_PROGRESS_USE, CON_TIPS_COMMON)
@VirtualEnvMustExistDecorator()
def onPortProgressRun(self, e):
"""子进程运行Django"""
port = env.getDjangoRunPort()
host = env.getDjangoRunHost()
try:
self.server = subprocess.Popen(f'{env.getDjangoOrderArgs()} runserver {port}', shell=True) # , stderr=subprocess.PIPE, stdout=subprocess.PIPE
except:
self.infos.AppendText(out_infos(f"虚拟环境错误,或项目路径错误,或端口被占用。", level=3))
else:
import webbrowser
webbrowser.open(f"{host}:{port}/admin/")
self.infos.AppendText(out_infos(f"网站正在运行,根路由:{host}:{port}。可复制到浏览器打开", level=1))
self.portProgressRun.Enable(False)
self.portProgressStop.Enable(True)
self.sys_toolbar.EnableTool(self.shotcut_run.GetId(), False)
self.sys_toolbar.EnableTool(self.shotcut_stop.GetId(), True)
def onModelsGenerate(self, e):
"""创建模型"""
# dlg = ModelsCreateDialog(self)
# dlg.ShowModal()
# dlg.Close(True)
self.auiNotebook.AddPage(AutoGenModelsPanel(self.auiNotebook), '新增模型', select=True)
self.auiNotebook.SetSelection(self.auiNotebook.GetPageCount())
def onSqliteManageTool(self, e):
"""跨平台的Sqlite工具"""
subFrame = SQLiteManageFrame(None)
subFrame.Show()
# manager = os.path.join(os.path.dirname(BASE_DIR), 'sqlite3Manager.pyw')
# subprocess.Popen(f'{env.getRealPythonOrder()} {manager}', shell=True)
def onMenusSettings(self, e):
"""Settings"""
dlg = SettingsDialog(self)
dlg.ShowModal()
dlg.Close(True)
def onHelpsDocumentation(self, e):
"""帮助文档"""
dlg = DocumentationDialog(self)
dlg.ShowModal()
dlg.Close(True)
def onCreateProject(self, e):
"""新建项目"""
dlg = ProjectCreateDialog(self)
dlg.ShowModal()
dlg.Close(True)
def onUrlsFix(self, e):
"""修复路由"""
for _ in self.unurls:
djangotools.fix_urls(_) # 逐个修复
self.infos.AppendText(out_infos(f"{_}注册完成!", level=1))
else:
self.unurls.clear()
self.infos.AppendText(out_infos(f"路由修复完成!", level=1))
if 'urls' in self.needfix:
self.needfix.remove('urls')
self._open_checked_fix_btn('urls', f_type='close')
def onUrlsCheck(self, e):
"""检查路由"""
# 检查情形有:
# 只针对以本工具生成的app,而不是Django原生命令python manage.py startapp ...
# 路由必须在主路径urls.py中用include()函数注册
# 默认未每个应用程序注册ulrs,取environment.py中的urls别名
self.unurls = set(djangotools.judge_in_main_urls()) # 全局监测
if len(self.unurls) <= 0:
self._open_checked_fix_btn('urls', f_type='close')
self.infos.AppendText(out_infos(f"路由检测完成,无已知错误。", level=1))
else:
msg = ','.join(self.unurls)
self.infos.AppendText(out_infos(f"{msg}未注册。", level=3))
self._open_checked_fix_btn('urls')
def onAdminRename(self, e):
"""重命名后台名称"""
dlg = AdminRenameDialog(self)
dlg.ShowModal()
dlg.Close(True)
def onViewsGenerateFunc(self, e):
"""多样式新增视图"""
# dlg = ViewGenerateDialog(self)
# dlg.ShowModal()
# dlg.Close(True)
self.auiNotebook.AddPage(AutoGenViewsPanel(self.auiNotebook), '新增视图', select=True)
self.auiNotebook.SetSelection(self.auiNotebook.GetPageCount()) # 页签焦点切换
def onFontsMinus(self, e):
"""显示框字体减小"""
env.setFontSize(step = 1, method = 'minus')
self._set_fonts(e)
def onFontsAdd(self, e):
"""显示框字体增大"""
env.setFontSize(step = 1, method = 'add')
self._set_fonts(e)
def OnKeyDown(self, event):
"""键盘监听"""
code = event.GetKeyCode()
if wx.WXK_NUMPAD_ENTER == code or 13 == code:
self.onExecCommand()
def onAbout(self, e):
"""关于"""
aboutInfo = wx.adv.AboutDialogInfo()
aboutInfo.SetName("JDjango")
aboutInfo.SetVersion(MY_APP_VERSION_STRING)
aboutInfo.SetDescription(T_("一种快速编写Django的辅助工具!QQ交流群:781517315"))
aboutInfo.SetCopyright("(C) 2020-2021")
aboutInfo.SetWebSite("https://github.com/JIYANG-PLUS/JDjango")
aboutInfo.AddDeveloper("笔小芯 -- <EMAIL>\n感谢:@coshare")
wx.adv.AboutBox(aboutInfo)
def onExit(self, e):
"""退出"""
self.Close(True)
def onOpen(self, e):
"""查看文件"""
self.dirname = r''
dlg = wx.FileDialog(self, "选择一个文件", self.dirname, "", "*.*", wx.FD_OPEN)
if dlg.ShowModal() == wx.ID_OK:
self.filename = dlg.GetFilename()
self.dirname = dlg.GetDirectory()
with open(os.path.join(self.dirname, self.filename), 'r', encoding="utf-8") as f:
self.infos.SetValue(f.read())
dlg.Close(True)
def onClear(self, e):
"""清空提示台"""
self.infos.Clear()
def onGenerate(self, e):
"""生成应用程序"""
dlg = wx.TextEntryDialog(None, u"请输入应用程序名:", u"创建应用程序", u"")
if dlg.ShowModal() == wx.ID_OK:
message = dlg.GetValue() # 获取文本框中输入的值
returnStatus = djangotools.startapp(message)
if 0 == returnStatus:
self.unapps.add(message)
url_alias = [os.path.basename(_).split('.')[0] for _ in env.getUrlsAlias()][0]
self.unurls.add(f'{message}.{url_alias}')
self.infos.AppendText(out_infos(f"{message}应用程序创建成功!", level=1))
self.onAppsFix(e) # 自动完成注册
self.onUrlsFix(e) # 自动完成路由注册
self._init_config() # 重新初始化 配置文件【此操作为敏感操作】
self.infoBar.ShowMessage(f"{message}应用程序创建成功!", wx.ICON_INFORMATION)
else:
dlg_tip = wx.MessageDialog(None, f"{message}应用程序名已存在,或不符合纯字母+数字命名的约定!", CON_TIPS_COMMON, wx.OK | wx.ICON_INFORMATION)
if dlg_tip.ShowModal() == wx.ID_OK: pass
dlg_tip.Close(True)
dlg.Close(True)
def onButtonClick(self, e):
"""界面按钮点击事件"""
bId = e.GetId()
if bId == self.btn_select_project.GetId(): # 选择项目根路径
self.onSelectProjectRoot()
elif bId == self.btn_check_project.GetId(): # 检测/校验项目
self.onCheckGlobalProject(e)
self.infoBar.ShowMessage("检测成功,具体内容详见输出窗口。", wx.ICON_INFORMATION)
elif bId == self.btn_fixed_project.GetId(): # 修复项目
self.onFixGlobalProject(e)
self.infoBar.ShowMessage(f"修复成功!", wx.ICON_INFORMATION)
elif bId == self.btn_config_project.GetId(): # 项目配置和修改
dlg = SettingsDialog(self)
dlg.ShowModal()
dlg.Close(True)
elif bId == self.btn_exec.GetId(): # 执行命令
self.onExecCommand()
elif bId == self.btn_clear_text.GetId():
self.onClear(e)
def onBtnOpenDocs(self, e):
"""查看帮助文档"""
dlg = DocumentationDialog(self)
dlg.ShowModal()
dlg.Close(True)
def onExecCommand(self):
"""仿Linux命令"""
command = self.cmdInput.GetValue().strip()
try:
order_split = [_ for _ in command.split() if _]
if order_split:
args = order_split[1:]
if 'ls' == order_split[0].lower():
s = cmd.ls(*args)
elif 'pwd' == command.lower():
s = cmd.pwd()
elif 'cd' == order_split[0].lower():
s = cmd.cd(*args)
elif 'zip' == order_split[0].lower():
s = cmd.zip(*args)
elif 'unzip' == order_split[0].lower():
s = cmd.unzip(*args)
elif 'rm' == order_split[0].lower():
s = cmd.rm(*args)
elif 'mkdir' == order_split[0].lower():
s = cmd.mkdir(*args)
elif 'mkfile' == order_split[0].lower():
s = cmd.mkfile(*args)
elif 'ping' == order_split[0].lower():
s = cmd.ping(*args)
elif 'date' == command.lower():
s = cmd.date()
elif '>' == order_split[0].lower():
s = cmd.print(' '.join(args))
else:
s = cmd.exec(' '.join(order_split))
self.infos.AppendText(out_command_infos(command))
if s:
self.infos.AppendText(f"{s}\n")
self.cmdInput.Clear()
except Exception as e:
self.infos.AppendText(out_infos(f'{e}'))
def onSelectProjectRoot(self):
"""选择项目根路径【项目入口】"""
dlg = wx.FileDialog(self, "选择Django项目的manage.py文件", r'', "", "*.py", wx.FD_OPEN)
if dlg.ShowModal() == wx.ID_OK:
self._disable_all_btn() # 初始化按钮状态
filename = dlg.GetFilename()
self.dirname = dlg.GetDirectory()
if 'manage.py' == filename:
# self.path.SetValue(f'当前项目路径:{self.dirname}') 【为了美观而放弃】
self.SetStatusText(f'{self.dirname}', 2)
try:
self._init_config() # 初始化配置文件
except Exception as e:
self.infos.AppendText(out_infos('配置文件config.json初始化失败!', level=3))
else:
# 开放所有的检测按钮
self._open_all_check_btn()
# 开放部分必要按钮
self._open_part_necessary_btns()
self.infos.Clear()
# self.path.Clear()
self.infos.AppendText(out_infos(f'项目{os.path.basename(self.dirname)}导入成功!', level=1))
self.infoBar.ShowMessage(f'项目{os.path.basename(self.dirname)}导入成功!', wx.ICON_INFORMATION)
else:
self.infos.AppendText(out_infos('项目导入失败,请选择Django项目根路径下的manage.py文件。', level=3))
dlg.Close(True)
def onAppsCheck(self, e):
"""应用程序 检测"""
apps = get_configs(CONFIG_PATH)['app_names'] # 实际的 所有 应用程序
flag = 0
with open(self.path_settings, 'r', encoding='utf-8') as f:
settings_apps = eval(djangotools.get_list_patt_content_contain_code(retools.PATT_INSTALLED_APPS, f.read()))
for app in apps:
if app not in settings_apps:
self.unapps.add(app)
self.infos.AppendText(out_infos(f'{app}应用程序未注册!', 2))
flag = 1
if 1 == flag:
self._open_checked_fix_btn('apps')
else:
self._open_checked_fix_btn('apps', f_type='close')
self.infos.AppendText(out_infos('应用程序检测完成,无已知错误。', level=1))
def onCheckGlobalProject(self, e):
"""检测项目【全局】"""
self.onAppsCheck(e) # 校验 APP
self.onUrlsCheck(e) # 校验 路由
def onAppsFix(self, e):
"""修复未注册应用"""
try:
content = read_file(self.path_settings)
temp = retools.PATT_INSTALLED_APPS.search(content).group(0)
INSTALLED_APPS = temp.split('\n')
for _ in self.unapps:
INSTALLED_APPS.insert(-1, f" '{_}',")
self.infos.AppendText(out_infos(f'{_}注册完成。', level=1))
self.unapps.clear() # 清空未注册应用程序
except:
self.infos.AppendText(
out_infos('项目残缺,无法修复。请检查本项目是否为Django项目。', level=3))
else:
new_content = content.replace(temp, '\n'.join(INSTALLED_APPS))
write_file(self.path_settings, new_content)
self.infos.AppendText(out_infos('应用程序修复完成。', level=1))
if 'apps' in self.needfix:
self.needfix.remove('apps')
self._open_checked_fix_btn('apps', f_type='close') # 必须最后执行(控件的不可用性)
def onFixGlobalProject(self, e):
"""修复项目 【全局】"""
self.onAppsFix(e) # 修复 应用程序
self.onUrlsFix(e) # 修复 路由
def onAdminGenerateBase(self, e):
"""管理中心 简单配置"""
dlg = AdminCreateSimpleDialog(self)
dlg.ShowModal()
dlg.Close(True)
def onCloseWindow(self, e):
"""窗口关闭前操作"""
if self.timer is not None:
self.timer.Stop()
self.timer = None
self.Destroy()
def DoSearch(self, text):
return True
def onAuiNotebookClose(self, e):
"""切换标签关闭前"""
# print(self.auiNotebook.GetPageText(self.auiNotebook.GetCurrentPage()))
if (0 == e.GetSelection()):
# e.Skip()
# e.StopPropagation()
e.Veto() # 否决掉事件的发生
self.infoBar.ShowMessage(f"核心标签不允许关闭!", wx.ICON_WARNING)
def onLanguage(self, e):
"""语言"""
self.auiNotebook.AddPage(wx.Panel(self.auiNotebook), '测试', select=True)
self.auiNotebook.SetSelection(self.auiNotebook.GetPageCount())
def OnTest(self, e):
"""开发用,测试函数"""
r = RichMsgDialog.showAskQuestionDialog(self, '测试', '标题')
print(r)
| from .listener import *
from ..sqliteFrame import *
"""
作用:实现事件功能
"""
class MainFrameFuncs(MainFrameListener):
def __init__(self, parent=None):
super().__init__(parent=parent)
self.order_container = (self.cmdCodes, self.info_cmdCodes,)
def onHelpsORM(self, e):
"""ORM帮助(一键生成)"""
dlg = ORMDialog(self)
dlg.ShowModal()
dlg.Close(True)
def onMenuVSCode(self, e):
"""外部发起VSCode编辑"""
# 检测是否配置code命令环境
if wx.Shell("code -v"):
dirname = get_configs(CONFIG_PATH)['dirname']
self.cmdVscode = subprocess.Popen(f'code {dirname}', shell=True)
self.cmdCodes.append(self.cmdVscode)
self.info_cmdCodes[self.cmdVscode] = '开启VSCode编辑器'
else:
self.infoBar.ShowMessage(f'未检测到code命令', wx.ICON_ERROR)
def onPortProgressVirtualView(self, e):
"""查看虚拟环境路径"""
RichMsgDialog.showOkMsgDialog(self, env.getPython3Env(), '虚拟环境路径')
@RegisterOriginOrderDecorator(msg = 'collectstatic')
@VirtualEnvMustExistDecorator()
def onPortProgressCollectstatic(self, e):
"""python manage.py collectstatic"""
return (
subprocess.Popen(f'{env.getDjangoOrderArgs()} collectstatic', shell=True)
, *self.order_container
)
@RegisterOriginOrderDecorator(msg = 'freeze')
@VirtualEnvMustExistDecorator()
def onPortProgressPipFreeze(self, e):
"""导出包pip freeze"""
return (
subprocess.Popen(f'{env.getPipOrderArgs(mode="freeze")}', shell=True)
, *self.order_container
)
@VirtualEnvMustExistDecorator()
def onPortProgressPipInstall(self, e):
"""虚拟环境安装包pip install"""
dlg = wx.TextEntryDialog(self, u"包名:", u"虚拟环境安装三方库", u"")
if dlg.ShowModal() == wx.ID_OK:
module_name = dlg.GetValue()
self.cmdPipInstall = subprocess.Popen(f'{env.getPipOrderArgs()} {module_name}', shell=True)
self.cmdCodes.append(self.cmdPipInstall)
self.info_cmdCodes[self.cmdPipInstall] = 'install'
dlg.Close(True)
@RegisterOriginOrderDecorator(msg = 'shell')
@VirtualEnvMustExistDecorator()
def onPortProgressShell(self, e):
"""python manage.py shell"""
return (
subprocess.Popen(f'{env.getDjangoOrderArgs()} shell', shell=True)
, *self.order_container
)
@RegisterOriginOrderDecorator(msg = 'makemigrations')
@VirtualEnvMustExistDecorator()
def onPortProgressMakemigrations(self, e):
"""python manage.py makemigrations"""
return (
subprocess.Popen(f'{env.getDjangoOrderArgs()} makemigrations', shell=True)
, *self.order_container
)
@RegisterOriginOrderDecorator(msg = 'migrate')
@VirtualEnvMustExistDecorator()
def onPortProgressMigrate(self, e):
"""python manage.py migtrate"""
return (
subprocess.Popen(f'{env.getDjangoOrderArgs()} migrate', shell=True)
, *self.order_container
)
@RegisterOriginOrderDecorator(msg = 'flush')
@VirtualEnvMustExistDecorator()
def onPortProgressFlush(self, e):
"""python manage.py flush"""
return (
subprocess.Popen(f'{env.getDjangoOrderArgs()} flush', shell=True)
, *self.order_container
)
@RegisterOriginOrderDecorator(msg = 'createsuperuser')
@VirtualEnvMustExistDecorator()
def onPortProgressCreatesuperuser(self, e):
"""python manage.py createsuperuser"""
return (
subprocess.Popen(f'{env.getDjangoOrderArgs()} createsuperuser', shell=True)
, *self.order_container
)
def onPortProgressVirtual(self, e):
"""创建虚拟环境"""
# venv.create(env_dir, system_site_packages=False, clear=False, symlinks=False, with_pip=False, prompt=None)
dlg = wx.DirDialog(self, u"选择即将写入的虚拟环境文件夹", style=wx.DD_DEFAULT_STYLE)
if dlg.ShowModal() == wx.ID_OK:
env_dir = dlg.GetPath()
t = len(os.listdir(env_dir))
if t > 0:
self.infoBar.ShowMessage(f'检测到选择的文件夹下存在其它文件,禁止操作。', wx.ICON_ERROR)
else:
venv.create(env_dir, system_site_packages=False, clear=True, symlinks=False, with_pip=True, prompt=None)
# 分操作系统自动绑定python解释器
this_platform = env.getPlatform().lower()
if 'windows' == this_platform:
temp_path = os.path.join(env_dir, 'Scripts', 'python.exe')
env.setPython3Env(temp_path)
self.infoBar.ShowMessage(f'创建并绑定成功,命令路径:{temp_path}', wx.ICON_INFORMATION)
elif 'darwin' == this_platform:
temp_path = os.path.join(env_dir, 'bin', 'python')
env.setPython3Env(temp_path)
self.infoBar.ShowMessage(f'创建并绑定成功,命令路径:{temp_path}', wx.ICON_INFORMATION)
else:
self.infoBar.ShowMessage(f'创建成功,虚拟目录:{env_dir}', wx.ICON_INFORMATION)
dlg.Destroy()
def onPortProgressKillProgress(self, e):
"""终止进程"""
dlg = wx.TextEntryDialog(self, u"占用端口号:", u"终止进程", u"")
if dlg.ShowModal() == wx.ID_OK:
port = dlg.GetValue()
env.killProgress(port = port)
self.infoBar.ShowMessage(f'已终止。', wx.ICON_INFORMATION)
dlg.Close(True)
def onPortProgressFaster(self, e):
"""一键配置镜像环境"""
rpath = os.path.expanduser('~')
# 根据系统依次安装镜像环境
platform = env.getPlatform().lower()
if 'windows' == platform:
if 'pip' in os.listdir(rpath):
pip_path = os.path.join(rpath, 'pip')
if 'pip.ini' in os.listdir(pip_path):
self.infoBar.ShowMessage(f'当前环境已配置镜像。', wx.ICON_WARNING)
else:
# TEMPLATE_DIR
write_file(os.path.join(pip_path, 'pip.ini'), read_file(os.path.join(TEMPLATE_DIR, 'pip', 'pip.ini')))
self.infoBar.ShowMessage(f'配置镜像环境成功。', wx.ICON_INFORMATION)
else:
pip_path = os.path.join(rpath, 'pip')
os.mkdir(pip_path)
write_file(os.path.join(pip_path, 'pip.ini'), read_file(os.path.join(TEMPLATE_DIR, 'pip', 'pip.ini')))
self.infoBar.ShowMessage(f'配置镜像环境成功。', wx.ICON_INFORMATION)
elif 'linux' == platform: # 理论上,Mac和Linux配置镜像环境步骤一致
if '.pip' in os.listdir(rpath):
pip_path = os.path.join(rpath, '.pip')
if 'pip.conf' in os.listdir(pip_path):
self.infoBar.ShowMessage(f'当前环境已配置镜像。', wx.ICON_WARNING)
else:
write_file(os.path.join(pip_path, 'pip.conf'), read_file(os.path.join(TEMPLATE_DIR, 'pip', 'pip.ini')))
self.infoBar.ShowMessage(f'配置镜像环境成功。', wx.ICON_INFORMATION)
else:
pip_path = os.path.join(rpath, '.pip')
os.mkdir(pip_path)
write_file(os.path.join(pip_path, 'pip.conf'), read_file(os.path.join(TEMPLATE_DIR, 'pip', 'pip.ini')))
self.infoBar.ShowMessage(f'配置镜像环境成功。', wx.ICON_INFORMATION)
elif 'darwin' == platform:
if '.pip' in os.listdir(rpath):
pip_path = os.path.join(rpath, '.pip')
if 'pip.conf' in os.listdir(pip_path):
self.infoBar.ShowMessage(f'当前环境已配置镜像。', wx.ICON_WARNING)
else:
write_file(os.path.join(pip_path, 'pip.conf'), read_file(os.path.join(TEMPLATE_DIR, 'pip', 'pip.ini')))
self.infoBar.ShowMessage(f'配置镜像环境成功。', wx.ICON_INFORMATION)
else:
pip_path = os.path.join(rpath, '.pip')
os.mkdir(pip_path)
write_file(os.path.join(pip_path, 'pip.conf'), read_file(os.path.join(TEMPLATE_DIR, 'pip', 'pip.ini')))
self.infoBar.ShowMessage(f'配置镜像环境成功。', wx.ICON_INFORMATION)
else:
self.infoBar.ShowMessage(f'未知系统', wx.ICON_WARNING)
def onModelsProxyGenerate(self, e):
"""创建代理模型"""
def onPortProgressStop(self, e):
"""关闭网站运行状态"""
try:
self.server.terminate()
env.killProgress()
except:
self.infoBar.ShowMessage(f'网站未正常启动或启动异常,导致关闭失败。', wx.ICON_ERROR)
else:
self.infos.AppendText(out_infos(f"网站已关闭。", level=1))
self.portProgressRun.Enable(True)
self.portProgressStop.Enable(False)
self.sys_toolbar.EnableTool(self.shotcut_run.GetId(), True)
self.sys_toolbar.EnableTool(self.shotcut_stop.GetId(), False)
self.infoBar.ShowMessage(f'网站已关闭。', wx.ICON_INFORMATION)
def onPortProgressVirtualChoice(self, e):
"""选择虚拟环境"""
dlg = wx.FileDialog(self, "选择虚拟环境下的python.exe文件", "", "", "*.*", wx.FD_OPEN)
if dlg.ShowModal() == wx.ID_OK:
env.setPython3Env(os.path.join(dlg.GetDirectory(), dlg.GetFilename()))
self.infoBar.ShowMessage(f'虚拟环境绑定成功!', wx.ICON_INFORMATION)
dlg.Close(True)
def onHelpSeeOrKill(self, e):
"""查看或终止进程"""
RichMsgDialog.showOkMsgDialog(self, CON_MSG_PROGRESS_USE, CON_TIPS_COMMON)
@VirtualEnvMustExistDecorator()
def onPortProgressRun(self, e):
"""子进程运行Django"""
port = env.getDjangoRunPort()
host = env.getDjangoRunHost()
try:
self.server = subprocess.Popen(f'{env.getDjangoOrderArgs()} runserver {port}', shell=True) # , stderr=subprocess.PIPE, stdout=subprocess.PIPE
except:
self.infos.AppendText(out_infos(f"虚拟环境错误,或项目路径错误,或端口被占用。", level=3))
else:
import webbrowser
webbrowser.open(f"{host}:{port}/admin/")
self.infos.AppendText(out_infos(f"网站正在运行,根路由:{host}:{port}。可复制到浏览器打开", level=1))
self.portProgressRun.Enable(False)
self.portProgressStop.Enable(True)
self.sys_toolbar.EnableTool(self.shotcut_run.GetId(), False)
self.sys_toolbar.EnableTool(self.shotcut_stop.GetId(), True)
def onModelsGenerate(self, e):
"""创建模型"""
# dlg = ModelsCreateDialog(self)
# dlg.ShowModal()
# dlg.Close(True)
self.auiNotebook.AddPage(AutoGenModelsPanel(self.auiNotebook), '新增模型', select=True)
self.auiNotebook.SetSelection(self.auiNotebook.GetPageCount())
def onSqliteManageTool(self, e):
"""跨平台的Sqlite工具"""
subFrame = SQLiteManageFrame(None)
subFrame.Show()
# manager = os.path.join(os.path.dirname(BASE_DIR), 'sqlite3Manager.pyw')
# subprocess.Popen(f'{env.getRealPythonOrder()} {manager}', shell=True)
def onMenusSettings(self, e):
"""Settings"""
dlg = SettingsDialog(self)
dlg.ShowModal()
dlg.Close(True)
def onHelpsDocumentation(self, e):
"""帮助文档"""
dlg = DocumentationDialog(self)
dlg.ShowModal()
dlg.Close(True)
def onCreateProject(self, e):
"""新建项目"""
dlg = ProjectCreateDialog(self)
dlg.ShowModal()
dlg.Close(True)
def onUrlsFix(self, e):
"""修复路由"""
for _ in self.unurls:
djangotools.fix_urls(_) # 逐个修复
self.infos.AppendText(out_infos(f"{_}注册完成!", level=1))
else:
self.unurls.clear()
self.infos.AppendText(out_infos(f"路由修复完成!", level=1))
if 'urls' in self.needfix:
self.needfix.remove('urls')
self._open_checked_fix_btn('urls', f_type='close')
def onUrlsCheck(self, e):
"""检查路由"""
# 检查情形有:
# 只针对以本工具生成的app,而不是Django原生命令python manage.py startapp ...
# 路由必须在主路径urls.py中用include()函数注册
# 默认未每个应用程序注册ulrs,取environment.py中的urls别名
self.unurls = set(djangotools.judge_in_main_urls()) # 全局监测
if len(self.unurls) <= 0:
self._open_checked_fix_btn('urls', f_type='close')
self.infos.AppendText(out_infos(f"路由检测完成,无已知错误。", level=1))
else:
msg = ','.join(self.unurls)
self.infos.AppendText(out_infos(f"{msg}未注册。", level=3))
self._open_checked_fix_btn('urls')
def onAdminRename(self, e):
"""重命名后台名称"""
dlg = AdminRenameDialog(self)
dlg.ShowModal()
dlg.Close(True)
def onViewsGenerateFunc(self, e):
"""多样式新增视图"""
# dlg = ViewGenerateDialog(self)
# dlg.ShowModal()
# dlg.Close(True)
self.auiNotebook.AddPage(AutoGenViewsPanel(self.auiNotebook), '新增视图', select=True)
self.auiNotebook.SetSelection(self.auiNotebook.GetPageCount()) # 页签焦点切换
def onFontsMinus(self, e):
"""显示框字体减小"""
env.setFontSize(step = 1, method = 'minus')
self._set_fonts(e)
def onFontsAdd(self, e):
"""显示框字体增大"""
env.setFontSize(step = 1, method = 'add')
self._set_fonts(e)
def OnKeyDown(self, event):
"""键盘监听"""
code = event.GetKeyCode()
if wx.WXK_NUMPAD_ENTER == code or 13 == code:
self.onExecCommand()
def onAbout(self, e):
"""关于"""
aboutInfo = wx.adv.AboutDialogInfo()
aboutInfo.SetName("JDjango")
aboutInfo.SetVersion(MY_APP_VERSION_STRING)
aboutInfo.SetDescription(T_("一种快速编写Django的辅助工具!QQ交流群:781517315"))
aboutInfo.SetCopyright("(C) 2020-2021")
aboutInfo.SetWebSite("https://github.com/JIYANG-PLUS/JDjango")
aboutInfo.AddDeveloper("笔小芯 -- <EMAIL>\n感谢:@coshare")
wx.adv.AboutBox(aboutInfo)
def onExit(self, e):
"""退出"""
self.Close(True)
def onOpen(self, e):
"""查看文件"""
self.dirname = r''
dlg = wx.FileDialog(self, "选择一个文件", self.dirname, "", "*.*", wx.FD_OPEN)
if dlg.ShowModal() == wx.ID_OK:
self.filename = dlg.GetFilename()
self.dirname = dlg.GetDirectory()
with open(os.path.join(self.dirname, self.filename), 'r', encoding="utf-8") as f:
self.infos.SetValue(f.read())
dlg.Close(True)
def onClear(self, e):
"""清空提示台"""
self.infos.Clear()
def onGenerate(self, e):
"""生成应用程序"""
dlg = wx.TextEntryDialog(None, u"请输入应用程序名:", u"创建应用程序", u"")
if dlg.ShowModal() == wx.ID_OK:
message = dlg.GetValue() # 获取文本框中输入的值
returnStatus = djangotools.startapp(message)
if 0 == returnStatus:
self.unapps.add(message)
url_alias = [os.path.basename(_).split('.')[0] for _ in env.getUrlsAlias()][0]
self.unurls.add(f'{message}.{url_alias}')
self.infos.AppendText(out_infos(f"{message}应用程序创建成功!", level=1))
self.onAppsFix(e) # 自动完成注册
self.onUrlsFix(e) # 自动完成路由注册
self._init_config() # 重新初始化 配置文件【此操作为敏感操作】
self.infoBar.ShowMessage(f"{message}应用程序创建成功!", wx.ICON_INFORMATION)
else:
dlg_tip = wx.MessageDialog(None, f"{message}应用程序名已存在,或不符合纯字母+数字命名的约定!", CON_TIPS_COMMON, wx.OK | wx.ICON_INFORMATION)
if dlg_tip.ShowModal() == wx.ID_OK: pass
dlg_tip.Close(True)
dlg.Close(True)
def onButtonClick(self, e):
"""界面按钮点击事件"""
bId = e.GetId()
if bId == self.btn_select_project.GetId(): # 选择项目根路径
self.onSelectProjectRoot()
elif bId == self.btn_check_project.GetId(): # 检测/校验项目
self.onCheckGlobalProject(e)
self.infoBar.ShowMessage("检测成功,具体内容详见输出窗口。", wx.ICON_INFORMATION)
elif bId == self.btn_fixed_project.GetId(): # 修复项目
self.onFixGlobalProject(e)
self.infoBar.ShowMessage(f"修复成功!", wx.ICON_INFORMATION)
elif bId == self.btn_config_project.GetId(): # 项目配置和修改
dlg = SettingsDialog(self)
dlg.ShowModal()
dlg.Close(True)
elif bId == self.btn_exec.GetId(): # 执行命令
self.onExecCommand()
elif bId == self.btn_clear_text.GetId():
self.onClear(e)
def onBtnOpenDocs(self, e):
"""查看帮助文档"""
dlg = DocumentationDialog(self)
dlg.ShowModal()
dlg.Close(True)
def onExecCommand(self):
"""仿Linux命令"""
command = self.cmdInput.GetValue().strip()
try:
order_split = [_ for _ in command.split() if _]
if order_split:
args = order_split[1:]
if 'ls' == order_split[0].lower():
s = cmd.ls(*args)
elif 'pwd' == command.lower():
s = cmd.pwd()
elif 'cd' == order_split[0].lower():
s = cmd.cd(*args)
elif 'zip' == order_split[0].lower():
s = cmd.zip(*args)
elif 'unzip' == order_split[0].lower():
s = cmd.unzip(*args)
elif 'rm' == order_split[0].lower():
s = cmd.rm(*args)
elif 'mkdir' == order_split[0].lower():
s = cmd.mkdir(*args)
elif 'mkfile' == order_split[0].lower():
s = cmd.mkfile(*args)
elif 'ping' == order_split[0].lower():
s = cmd.ping(*args)
elif 'date' == command.lower():
s = cmd.date()
elif '>' == order_split[0].lower():
s = cmd.print(' '.join(args))
else:
s = cmd.exec(' '.join(order_split))
self.infos.AppendText(out_command_infos(command))
if s:
self.infos.AppendText(f"{s}\n")
self.cmdInput.Clear()
except Exception as e:
self.infos.AppendText(out_infos(f'{e}'))
def onSelectProjectRoot(self):
"""选择项目根路径【项目入口】"""
dlg = wx.FileDialog(self, "选择Django项目的manage.py文件", r'', "", "*.py", wx.FD_OPEN)
if dlg.ShowModal() == wx.ID_OK:
self._disable_all_btn() # 初始化按钮状态
filename = dlg.GetFilename()
self.dirname = dlg.GetDirectory()
if 'manage.py' == filename:
# self.path.SetValue(f'当前项目路径:{self.dirname}') 【为了美观而放弃】
self.SetStatusText(f'{self.dirname}', 2)
try:
self._init_config() # 初始化配置文件
except Exception as e:
self.infos.AppendText(out_infos('配置文件config.json初始化失败!', level=3))
else:
# 开放所有的检测按钮
self._open_all_check_btn()
# 开放部分必要按钮
self._open_part_necessary_btns()
self.infos.Clear()
# self.path.Clear()
self.infos.AppendText(out_infos(f'项目{os.path.basename(self.dirname)}导入成功!', level=1))
self.infoBar.ShowMessage(f'项目{os.path.basename(self.dirname)}导入成功!', wx.ICON_INFORMATION)
else:
self.infos.AppendText(out_infos('项目导入失败,请选择Django项目根路径下的manage.py文件。', level=3))
dlg.Close(True)
def onAppsCheck(self, e):
"""应用程序 检测"""
apps = get_configs(CONFIG_PATH)['app_names'] # 实际的 所有 应用程序
flag = 0
with open(self.path_settings, 'r', encoding='utf-8') as f:
settings_apps = eval(djangotools.get_list_patt_content_contain_code(retools.PATT_INSTALLED_APPS, f.read()))
for app in apps:
if app not in settings_apps:
self.unapps.add(app)
self.infos.AppendText(out_infos(f'{app}应用程序未注册!', 2))
flag = 1
if 1 == flag:
self._open_checked_fix_btn('apps')
else:
self._open_checked_fix_btn('apps', f_type='close')
self.infos.AppendText(out_infos('应用程序检测完成,无已知错误。', level=1))
def onCheckGlobalProject(self, e):
"""检测项目【全局】"""
self.onAppsCheck(e) # 校验 APP
self.onUrlsCheck(e) # 校验 路由
def onAppsFix(self, e):
"""修复未注册应用"""
try:
content = read_file(self.path_settings)
temp = retools.PATT_INSTALLED_APPS.search(content).group(0)
INSTALLED_APPS = temp.split('\n')
for _ in self.unapps:
INSTALLED_APPS.insert(-1, f" '{_}',")
self.infos.AppendText(out_infos(f'{_}注册完成。', level=1))
self.unapps.clear() # 清空未注册应用程序
except:
self.infos.AppendText(
out_infos('项目残缺,无法修复。请检查本项目是否为Django项目。', level=3))
else:
new_content = content.replace(temp, '\n'.join(INSTALLED_APPS))
write_file(self.path_settings, new_content)
self.infos.AppendText(out_infos('应用程序修复完成。', level=1))
if 'apps' in self.needfix:
self.needfix.remove('apps')
self._open_checked_fix_btn('apps', f_type='close') # 必须最后执行(控件的不可用性)
def onFixGlobalProject(self, e):
"""修复项目 【全局】"""
self.onAppsFix(e) # 修复 应用程序
self.onUrlsFix(e) # 修复 路由
def onAdminGenerateBase(self, e):
"""管理中心 简单配置"""
dlg = AdminCreateSimpleDialog(self)
dlg.ShowModal()
dlg.Close(True)
def onCloseWindow(self, e):
"""窗口关闭前操作"""
if self.timer is not None:
self.timer.Stop()
self.timer = None
self.Destroy()
def DoSearch(self, text):
return True
def onAuiNotebookClose(self, e):
"""切换标签关闭前"""
# print(self.auiNotebook.GetPageText(self.auiNotebook.GetCurrentPage()))
if (0 == e.GetSelection()):
# e.Skip()
# e.StopPropagation()
e.Veto() # 否决掉事件的发生
self.infoBar.ShowMessage(f"核心标签不允许关闭!", wx.ICON_WARNING)
def onLanguage(self, e):
"""语言"""
self.auiNotebook.AddPage(wx.Panel(self.auiNotebook), '测试', select=True)
self.auiNotebook.SetSelection(self.auiNotebook.GetPageCount())
def OnTest(self, e):
"""开发用,测试函数"""
r = RichMsgDialog.showAskQuestionDialog(self, '测试', '标题')
print(r)
| zh | 0.832301 | 作用:实现事件功能 ORM帮助(一键生成) 外部发起VSCode编辑 # 检测是否配置code命令环境 查看虚拟环境路径 python manage.py collectstatic 导出包pip freeze 虚拟环境安装包pip install python manage.py shell python manage.py makemigrations python manage.py migtrate python manage.py flush python manage.py createsuperuser 创建虚拟环境 # venv.create(env_dir, system_site_packages=False, clear=False, symlinks=False, with_pip=False, prompt=None) # 分操作系统自动绑定python解释器 终止进程 一键配置镜像环境 # 根据系统依次安装镜像环境 # TEMPLATE_DIR # 理论上,Mac和Linux配置镜像环境步骤一致 创建代理模型 关闭网站运行状态 选择虚拟环境 查看或终止进程 子进程运行Django # , stderr=subprocess.PIPE, stdout=subprocess.PIPE 创建模型 # dlg = ModelsCreateDialog(self) # dlg.ShowModal() # dlg.Close(True) 跨平台的Sqlite工具 # manager = os.path.join(os.path.dirname(BASE_DIR), 'sqlite3Manager.pyw') # subprocess.Popen(f'{env.getRealPythonOrder()} {manager}', shell=True) Settings 帮助文档 新建项目 修复路由 # 逐个修复 检查路由 # 检查情形有: # 只针对以本工具生成的app,而不是Django原生命令python manage.py startapp ... # 路由必须在主路径urls.py中用include()函数注册 # 默认未每个应用程序注册ulrs,取environment.py中的urls别名 # 全局监测 重命名后台名称 多样式新增视图 # dlg = ViewGenerateDialog(self) # dlg.ShowModal() # dlg.Close(True) # 页签焦点切换 显示框字体减小 显示框字体增大 键盘监听 关于 退出 查看文件 清空提示台 生成应用程序 # 获取文本框中输入的值 # 自动完成注册 # 自动完成路由注册 # 重新初始化 配置文件【此操作为敏感操作】 界面按钮点击事件 # 选择项目根路径 # 检测/校验项目 # 修复项目 # 项目配置和修改 # 执行命令 查看帮助文档 仿Linux命令 选择项目根路径【项目入口】 # 初始化按钮状态 # self.path.SetValue(f'当前项目路径:{self.dirname}') 【为了美观而放弃】 # 初始化配置文件 # 开放所有的检测按钮 # 开放部分必要按钮 # self.path.Clear() 应用程序 检测 # 实际的 所有 应用程序 检测项目【全局】 # 校验 APP # 校验 路由 修复未注册应用 # 清空未注册应用程序 # 必须最后执行(控件的不可用性) 修复项目 【全局】 # 修复 应用程序 # 修复 路由 管理中心 简单配置 窗口关闭前操作 切换标签关闭前 # print(self.auiNotebook.GetPageText(self.auiNotebook.GetCurrentPage())) # e.Skip() # e.StopPropagation() # 否决掉事件的发生 语言 开发用,测试函数 | 2.473883 | 2 |
rom_generator/scenes/imported/BasicScenesB.py | ikarth/game-boy-rom-generator | 3 | 6614162 | # Generated Scene Functions
# BasicScenes.py
from rom_generator import generator
from rom_generator import script_functions as script
def scene_generation():
sprite_sheet_data = [
generator.makeSpriteSheet('actor.png', name='actor', type='actor', frames=3),
generator.makeSpriteSheet('actor_animated.png', name='actor_animated', type='actor_animated', frames=6),
generator.makeSpriteSheet('cat.png', name='cat', type='static', frames=1),
generator.makeSpriteSheet('checkbox.png', name='checkbox', type='actor', frames=3),
generator.makeSpriteSheet('connector.png', name='connector', type='animated', frames=2),
generator.makeSpriteSheet('dog.png', name='dog', type='static', frames=1),
generator.makeSpriteSheet('duck.png', name='duck', type='animated', frames=2),
generator.makeSpriteSheet('fire.png', name='fire', type='animated', frames=4),
generator.makeSpriteSheet('GreenBlock.png', name='GreenBlock', type='static', frames=1),
generator.makeSpriteSheet('ice.png', name='ice', type='static', frames=1),
generator.makeSpriteSheet('key_00.png', name='key_00', type='static', frames=1),
generator.makeSpriteSheet('MazeBlock.png', name='MazeBlock', type='static', frames=1),
generator.makeSpriteSheet('npc001.png', name='npc001', type='actor', frames=3),
generator.makeSpriteSheet('npc002.png', name='npc002', type='actor', frames=3),
generator.makeSpriteSheet('npc003.png', name='npc003', type='actor_animated', frames=6),
generator.makeSpriteSheet('player.png', name='player', type='actor_animated', frames=6),
generator.makeSpriteSheet('radio.png', name='radio', type='static', frames=1),
generator.makeSpriteSheet('rock.png', name='rock', type='static', frames=1),
generator.makeSpriteSheet('sage.png', name='sage', type='static', frames=1),
generator.makeSpriteSheet('savepoint.png', name='savepoint', type='animated', frames=2),
generator.makeSpriteSheet('signpost.png', name='signpost', type='static', frames=1),
generator.makeSpriteSheet('static.png', name='static', type='static', frames=1),
generator.makeSpriteSheet('torch.png', name='torch', type='static', frames=1),
generator.makeSpriteSheet('tower.png', name='tower', type='static', frames=1)]
def findSpriteByName(sprite_name):
'''
Returns first sprite that matches the name given.
'''
try:
return [s for s in sprite_sheet_data if (s['name'] == sprite_name)][0]
except:
return None
def getBySceneLabel(scene_label):
'''
This is mostly here so we can get the matching scene from the original
template data. As used here it just grabs the first scene that was made
from that template, so if the template is used more than once it won't
behave as expected and you should generate a proper relationship instad.
'''
s_id = generator.getSceneIdByLabel(scene_label)
if s_id == None:
return '<♔' + scene_label + '♔>'
return s_id
def scene_gen_Outside_00001(callback):
actor_00 = generator.makeActor(None, 25, 14, 'static', moveSpeed=0, direction='down', script=[], sprite_id=findSpriteByName('rock')['id'])
actor_00['script'] = [
script.actorPush(do_continue=False),
script.end()
]
actor_01 = generator.makeActor(None, 27, 23, 'static', direction='down', script=[], sprite_id=findSpriteByName('signpost')['id'])
actor_01['script'] = [
script.text(text='Welcome to\nGBStudio!'),
script.end()
]
actor_02 = generator.makeActor(None, 21, 18, 'static', animate=True, animSpeed=1, direction='down', script=[], sprite_id=findSpriteByName('duck')['id'])
actor_03 = generator.makeActor(None, 3, 24, 'randomWalk', direction='down', script=[], sprite_id=findSpriteByName('npc003')['id'])
actor_03['script'] = [
script.text(text='Have you seen my\ncat anywhere?'),
script.ifTrue(variable='0', children = {
'true': [script.text(text='He\'s by the house?\nThank you!'), script.setTrue(variable='4'), script.end()],
'false': [script.end()]
}),
script.end()
]
actor_04 = generator.makeActor(None, 4, 6, 'static', direction='down', script=[], sprite_id=findSpriteByName('cat')['id'])
actor_04['script'] = [
script.text(text='Meow!'),
script.setTrue(variable='0'),
script.end()
]
actor_05 = generator.makeActor(None, 21, 24, 'faceInteraction', direction='up', script=[], sprite_id=findSpriteByName('npc001')['id'])
actor_05['script'] = [
script.ifTrue(variable='1', children = {
'true': [script.text(text='I guess it was a\nmisunderstanding.'), script.setTrue(variable='8'), script.end()],
'false': [script.text(text='What is that guy\nlooking at?'), script.actorSetDirection(actorId='a85c4ba5-9bc0-4daa-94bc-4ef68a690659', direction='up'), script.end()]
}),
script.end()
]
actor_06 = generator.makeActor(None, 21, 16, 'faceInteraction', direction='down', script=[], sprite_id=findSpriteByName('npc001')['id'])
actor_06['script'] = [
script.text(text='Check out this\nsweet duck!'),
script.setTrue(variable='1'),
script.actorSetDirection(actorId='5cf6eb6c-be62-4efc-9cbb-14a8efac21a8', direction='down'),
script.end()
]
actor_list = [actor_00, actor_01, actor_02, actor_03, actor_04, actor_05, actor_06]
trigger_00 = generator.makeTrigger('trigger_00', 25, 13, 2, 2)
trigger_01 = generator.makeTrigger('trigger_01', 24, 8, 2, 1)
trigger_02 = generator.makeTrigger('trigger_02', 10, 8, 2, 1)
trigger_list = []
collision_data_list = [255, 255, 7, 0, 255, 255, 7, 0, 255, 255, 7, 0, 153, 153, 5, 0, 3, 63, 4, 0, 3, 63, 4, 0, 3, 63, 28, 0, 1, 63, 144, 7, 3, 51, 240, 252, 3, 0, 0, 192, 3, 0, 0, 192, 1, 0, 0, 128, 99, 0, 0, 192, 243, 0, 0, 192, 243, 0, 0, 192, 97, 0, 0, 128, 3, 0, 0, 192, 3, 128, 255, 207, 3, 248, 0, 216, 1, 14, 0, 144, 3, 2, 0, 208, 3, 30, 0, 208, 3, 112, 0, 220, 1, 192, 255, 135, 3, 0, 0, 192, 2, 0, 0, 192, 2, 0, 0, 192, 1, 0, 0, 128, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
gen_scene_bkg = generator.makeBackground("outside.png")
scene_script = [
script.end()
]
gen_scene_scn = generator.makeScene("_gen_Outside", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_Outside_00001)
gen_scene_scn['script'] = scene_script
def addConnection_00(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_00 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_00['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_00
connection_00 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_00, 'args': { 'exit_location': (25, 15), 'exit_direction': 'down', 'entrance': gen_scene_scn['id'], 'entrance_location': (25, 13), 'entrance_size': (2, 2) } }
def addConnection_01(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_01 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_01['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_01
connection_01 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_01, 'args': { 'exit_location': (24, 9), 'exit_direction': 'down', 'entrance': gen_scene_scn['id'], 'entrance_location': (24, 8), 'entrance_size': (2, 1) } }
def addConnection_02(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_02 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_02['script'] = [
script.switchScene(x=destination_location[0], y=destination_location[1], direction=destination_direction, sceneId=destination_scene_id, fadeSpeed='2'),
script.end()
]
return trigger_02
connection_02 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_02, 'args': { 'exit_location': (10, 9), 'exit_direction': 'down', 'entrance': gen_scene_scn['id'], 'entrance_location': (10, 8), 'entrance_size': (2, 1) } }
gen_scene_connections = [connection_00, connection_01, connection_02]
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_Cave_00002(callback):
actor_00 = generator.makeActor(None, 4, 6, 'faceInteraction', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('torch')['id'])
actor_01 = generator.makeActor(None, 4, 4, 'static', animate=True, moveSpeed=1, animSpeed=4, direction='down', script=[], sprite_id=findSpriteByName('fire')['id'])
actor_02 = generator.makeActor(None, 9, 7, 'static', direction='down', script=[], sprite_id=findSpriteByName('sage')['id'])
actor_02['script'] = [
script.text(text='It\'s dangerous to\ngo without docs.'),
script.text(text='Check out\ngbstudio.dev/docs'),
script.text(text='Also, try moving\nthe rock outside.'),
script.setTrue(variable='7'),
script.end()
]
actor_03 = generator.makeActor(None, 14, 6, 'faceInteraction', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('torch')['id'])
actor_04 = generator.makeActor(None, 14, 4, 'static', animate=True, moveSpeed=1, animSpeed=4, direction='down', script=[], sprite_id=findSpriteByName('fire')['id'])
actor_05 = generator.makeActor(None, 14, 11, 'static', animate=True, moveSpeed=1, animSpeed=2, direction='down', script=[], sprite_id=findSpriteByName('savepoint')['id'])
actor_05['script'] = [
script.choice(variable='11', trueText='Save Game', falseText='Cancel'),
script.ifTrue(variable='11', children = {
'true': [script.saveData(), script.text(text='Game progress has\nbeen saved.'), script.text(text='It is now safe to\nturn off your\nsystem.'), script.end()],
'false': [script.end()]
}),
script.end()
]
actor_list = [actor_00, actor_01, actor_02, actor_03, actor_04, actor_05]
trigger_00 = generator.makeTrigger('trigger_00', 9, 17, 2, 1)
trigger_list = []
collision_data_list = [0, 0, 0, 0, 0, 0, 0, 224, 255, 127, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 254, 249, 7, 144, 0]
gen_scene_bkg = generator.makeBackground("cave.png")
scene_script = [
script.end()
]
gen_scene_scn = generator.makeScene("_gen_Cave", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_Cave_00002)
gen_scene_scn['script'] = scene_script
def addConnection_00(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_00 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_00['script'] = [
script.switchScene(x=destination_location[0], y=destination_location[1], direction=destination_direction, sceneId=destination_scene_id, fadeSpeed='2'),
script.end()
]
return trigger_00
connection_00 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_00, 'args': { 'exit_location': (9, 15), 'exit_direction': 'up', 'entrance': gen_scene_scn['id'], 'entrance_location': (9, 17), 'entrance_size': (2, 1) } }
gen_scene_connections = [connection_00]
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_House_00003(callback):
actor_00 = generator.makeActor(None, 12, 5, 'faceInteraction', direction='down', script=[], sprite_id=findSpriteByName('npc002')['id'])
actor_00['script'] = [
script.ifFalse(variable='2', children = {
'true': [script.text(text='Have you tried\nusing this radio?'), script.end()],
'false': [script.text(text='Yeah it doesn\'t\nfit does it?'), script.actorEmote(actorId='566c8812-a204-45b5-b93a-c113c10c20de', emoteId='3'), script.text(text='But it\'s all I\nhave right now...'), script.setTrue(variable='6'), script.end()]
}),
script.end()
]
actor_01 = generator.makeActor(None, 15, 5, 'static', direction='down', script=[], sprite_id=findSpriteByName('radio')['id'])
actor_01['script'] = [
script.ifFalse(variable='2', children = {
'true': [script.musicPlay(musicId='f50428ab-a084-4591-9bba-2ba10fe7b1c6', loop=True), script.setTrue(variable='2'), script.end()],
'false': [script.musicStop(), script.setFalse(variable='2'), script.end()]
}),
script.end()
]
actor_02 = generator.makeActor(None, 15, 11, 'static', direction='down', script=[], sprite_id=findSpriteByName('signpost')['id'])
actor_02['script'] = [
script.text(text='Add sprites to\nassets/sprites'),
script.end()
]
actor_03 = generator.makeActor(None, 3, 11, 'static', direction='down', script=[], sprite_id=findSpriteByName('signpost')['id'])
actor_03['script'] = [
script.text(text='Add backgrounds to\nassets/backgrounds'),
script.end()
]
actor_04 = generator.makeActor(None, 3, 5, 'static', direction='down', script=[], sprite_id=findSpriteByName('signpost')['id'])
actor_04['script'] = [
script.text(text='This room is\npretty empty.'),
script.text(text='Try to edit\nhouse.png'),
script.end()
]
actor_list = [actor_00, actor_01, actor_02, actor_03, actor_04]
trigger_00 = generator.makeTrigger('trigger_00', 9, 16, 2, 1)
trigger_list = []
collision_data_list = [0, 0, 0, 0, 0, 0, 0, 224, 255, 127, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 2, 0, 228, 159, 127, 0, 9, 0, 240, 0]
gen_scene_bkg = generator.makeBackground("house.png")
scene_script = [
script.end()
]
gen_scene_scn = generator.makeScene("_gen_House", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_House_00003)
gen_scene_scn['script'] = scene_script
def addConnection_00(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_00 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_00['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_00
connection_00 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_00, 'args': { 'exit_location': (9, 14), 'exit_direction': 'up', 'entrance': gen_scene_scn['id'], 'entrance_location': (9, 16), 'entrance_size': (2, 1) } }
gen_scene_connections = [connection_00]
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_Stars_00004(callback):
actor_00 = generator.makeActor(None, 15, 12, 'static', direction='down', script=[], sprite_id=findSpriteByName('dog')['id'])
actor_00['script'] = [
script.text(text='How did you\nget here!?!?'),
script.incValue(variable='3'),
script.ifValue(variable='3', operator='==', comparator=1, children = {
'true': [script.text(text='You have spoken to\nme $03$ time.'), script.end()],
'false': [script.text(text='You have spoken to\nme $03$ times.'), script.end()]
}),
script.setTrue(variable='9'),
script.end()
]
actor_list = [actor_00]
trigger_list = []
collision_data_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
gen_scene_bkg = generator.makeBackground("stars.png")
scene_script = [
script.end()
]
gen_scene_scn = generator.makeScene("_gen_Stars", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_Stars_00004)
gen_scene_scn['script'] = scene_script
gen_scene_connections = []
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_Logo_00005(callback):
actor_list = []
trigger_list = []
collision_data_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
gen_scene_bkg = generator.makeBackground("logo.png")
scene_script = [
script.actorHide(actorId='player'), script.overlayShow(color='black', x=0, y=0), script.overlayMoveTo(x=0, y=18, speed='2'), script.wait(time=2), script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Title Screen>♔', x=0, y=0, direction='', fadeSpeed='2'), script.end()
]
gen_scene_scn = generator.makeScene("_gen_Logo", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_Logo_00005)
gen_scene_scn['script'] = scene_script
gen_scene_connections = []
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_Title_Screen_00006(callback):
actor_list = []
trigger_list = []
collision_data_list = []
gen_scene_bkg = generator.makeBackground("titlescreen.png")
gen_scene_scn = generator.makeScene("_gen_Title_Screen", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_Title_Screen_00006)
possible_scene_script = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
possible_scene_script[0] = [
script.actorHide(actorId='player'), script.awaitInput(input=['a', 'b', 'start', 'select']), script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(), script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'), script.end()]
}), script.end()]
}), script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'), script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [script.loadData(), script.end()],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}), script.end()]
}), script.end()]
})
]
possible_scene_script[1] = [
script.actorHide(actorId='player'), script.awaitInput(input=['a', 'b', 'start', 'select']), script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(), script.switchScene(sceneId=gen_scene_scn['id'], x=0, y=0, direction='', fadeSpeed='2'), script.end()]
}), script.end()]
}), script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'), script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId=gen_scene_scn['id'], x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [script.loadData(), script.end()],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}), script.end()]
}), script.end()]
}), script.end()
]
possible_scene_script[2] = [
script.actorHide(actorId='player'), script.awaitInput(input=['a', 'b', 'start', 'select']), script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(), script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2')]
})]
}), script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'), script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4')],
'false': [script.ifSavedData(children = {
'true': [script.loadData()],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[3] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.group(children = {
'true': [script.setInputScript(input='start',
children = {
'true': [script.scenePushState(), script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2')]
})]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4')],
'false': [script.ifSavedData(children = {
'true': [script.loadData()],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[4] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.group(children = {
'true': [script.setInputScript(input='start',
children = {
'true': []
})]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4')],
'false': [script.ifSavedData(children = {
'true': [script.loadData()],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[5] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.group(children = {
'true': [script.setInputScript(input='start',
children = {
'true': []
})]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [],
'false': [script.ifSavedData(children = {
'true': [script.loadData()],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[6] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.group(children = {
'true': [script.setInputScript(input='start',
children = {
'true': [script.scenePushState(), script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2')]
})]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [],
'false': [script.ifSavedData(children = {
'true': [script.loadData()],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[7] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.group(children = {
'true': [script.setInputScript(input='start',
children = {
'true': []
})]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [],
'false': [script.ifSavedData(children = {
'true': [script.loadData()],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[8] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [],
'false': [script.ifSavedData(children = {
'true': [script.loadData()],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[9] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select'])
]
possible_scene_script[10] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [],
'false': [script.ifSavedData(children = {
'true': [script.loadData()],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[11] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [],
'false': [script.ifSavedData(children = {
'true': [],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[12] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.loop(children = {
'true': [
script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [],
'false': []
})]
})
]
possible_scene_script[13] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.loop(children = {
'true': []
})
]
# doesn't work
possible_scene_script[14] = [
script.actorHide(actorId='player'), script.awaitInput(input=['a', 'b', 'start', 'select']), script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(), script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'), script.end()]
}), script.end()]
}), script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'), script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}), script.end()]
}), script.end()]
})
]
# works
possible_scene_script[15] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'), script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}), script.end()]
}), script.end()]
})
]
# works
possible_scene_script[16] = [
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'), script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}), script.end()]
}), script.end()]
})
]
# Doesn't work
possible_scene_script[17] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(), script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'), script.end()]
}), script.end()]
}), script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'), script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': []
}), script.end()]
})
]
# doesn't work
possible_scene_script[18] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(),
script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'),
script.end()]
}),
script.end()]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [script.end()],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}),
script.end()]
}),
script.end()]
})
]
# works
possible_scene_script[19] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [script.end()],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}),
script.end()]
}),
script.end()]
})
]
# works
possible_scene_script[20] = [
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [script.end()],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}),
script.end()]
}),
script.end()]
})
]
# doesn't work
possible_scene_script[21] = [
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(),
script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'),
script.end()]
}),
script.end()]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': []
}),
script.end()]
})
]
# works
possible_scene_script[22] = [
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [
script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'),
script.end()]
}),
script.end()]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': []
}),
script.end()]
})
]
# doesn't work
possible_scene_script[23] = [
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(),
]
}),
script.end()]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': []
}),
script.end()]
})
]
# works
possible_scene_script[24] = [
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': []
}),
script.end()]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': []
}),
script.end()]
})
]
possible_scene_script[25] = [
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(),
script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'),
script.end()]
}),
script.end()]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': []
}),
script.end()]
})
]
possible_scene_script[26] = [
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(),
script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'),
script.end()]
}),
script.end()]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': []
}),
script.end()]
})
]
possible_scene_script[27] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(),
script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'),
script.end()]
}),
script.end()]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [script.loadData(),
script.end()],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}),
script.end()]
}),
script.end()]
})
]
scene_script = possible_scene_script[callback()]
gen_scene_scn['script'] = scene_script
gen_scene_connections = []
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_Underground_00007(callback):
actor_00 = generator.makeActor(None, 7, 25, 'static', direction='down', script=[], sprite_id=findSpriteByName('signpost')['id'])
actor_00['script'] = [
script.text(text='Try to get the ice\nblock to the mark.'),
script.text(text='If you get stuck,\nI\'ll reset it!'),
script.actorSetPosition(actorId='27de6d44-f7c0-48df-a952-2c87471bbfd4', x=24, y=18),
script.end()
]
actor_01 = generator.makeActor(None, 24, 18, 'static', moveSpeed=2, direction='down', script=[], sprite_id=findSpriteByName('ice')['id'])
actor_01['script'] = [
script.ifActorAtPosition(actorId='27de6d44-f7c0-48df-a952-2c87471bbfd4', x=15, y=10, children = {
'true': [script.end()],
'false': [script.actorPush(do_continue=True), script.ifActorAtPosition(actorId='27de6d44-f7c0-48df-a952-2c87471bbfd4', x=15, y=10, children = {
'true': [script.text(text='Success!'), script.setTrue(variable='5'), script.end()],
'false': [script.end()]
}), script.end()]
}),
script.setTrue(variable='12'),
script.end()
]
actor_02 = generator.makeActor(None, 23, 27, 'static', moveSpeed=0, direction='down', script=[], sprite_id=findSpriteByName('rock')['id'])
actor_02['script'] = [
script.actorPush(do_continue=False),
script.end()
]
actor_03 = generator.makeActor(None, 21, 27, 'static', moveSpeed=0, direction='down', script=[], sprite_id=findSpriteByName('rock')['id'])
actor_03['script'] = [
script.actorPush(do_continue=False),
script.end()
]
actor_04 = generator.makeActor(None, 19, 27, 'static', moveSpeed=0, direction='down', script=[], sprite_id=findSpriteByName('rock')['id'])
actor_04['script'] = [
script.actorPush(do_continue=False),
script.end()
]
actor_list = [actor_00, actor_01, actor_02, actor_03, actor_04]
trigger_00 = generator.makeTrigger('trigger_00', 21, 30, 2, 2)
trigger_list = []
collision_data_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 248, 255, 255, 31, 248, 255, 255, 31, 8, 128, 1, 19, 200, 128, 1, 19, 200, 0, 0, 16, 200, 0, 0, 16, 8, 0, 0, 16, 8, 0, 0, 16, 8, 0, 6, 16, 8, 0, 6, 16, 8, 3, 6, 16, 8, 3, 0, 16, 248, 255, 255, 28, 254, 255, 255, 124, 254, 255, 255, 124, 2, 0, 0, 64, 2, 0, 158, 71, 2, 128, 159, 71, 2, 128, 159, 71, 2, 128, 7, 118, 2, 128, 7, 118, 2, 128, 7, 118, 2, 0, 6, 118, 2, 0, 6, 118, 254, 255, 159, 127, 0, 0, 144, 0]
gen_scene_bkg = generator.makeBackground("underground.png")
scene_script = [
script.group(children = {
'true': [script.ifTrue(variable='12', children = {
'true': [script.actorSetPosition(actorId='27de6d44-f7c0-48df-a952-2c87471bbfd4', x=24, y=15), script.end()],
'false': [script.end()]
}), script.end()]
}), script.end()
]
gen_scene_scn = generator.makeScene("_gen_Underground", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_Underground_00007)
gen_scene_scn['script'] = scene_script
def addConnection_00(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_00 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_00['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_00
connection_00 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_00, 'args': { 'exit_location': (21, 29), 'exit_direction': 'up', 'entrance': gen_scene_scn['id'], 'entrance_location': (21, 30), 'entrance_size': (2, 2) } }
gen_scene_connections = [connection_00]
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_Menu_00008(callback):
actor_00 = generator.makeActor(None, 2, 4, 'faceInteraction', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('checkbox')['id'])
actor_00['script'] = [
script.end()
]
actor_01 = generator.makeActor(None, 2, 6, 'faceInteraction', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('checkbox')['id'])
actor_01['script'] = [
script.end()
]
actor_02 = generator.makeActor(None, 2, 8, 'faceInteraction', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('checkbox')['id'])
actor_02['script'] = [
script.end()
]
actor_03 = generator.makeActor(None, 2, 11, 'faceInteraction', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('checkbox')['id'])
actor_03['script'] = [
script.end()
]
actor_04 = generator.makeActor(None, 2, 13, 'faceInteraction', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('checkbox')['id'])
actor_04['script'] = [
script.end()
]
actor_05 = generator.makeActor(None, 2, 15, 'faceInteraction', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('checkbox')['id'])
actor_05['script'] = [
script.end()
]
actor_list = [actor_00, actor_01, actor_02, actor_03, actor_04, actor_05]
trigger_list = []
collision_data_list = []
gen_scene_bkg = generator.makeBackground("menu.png")
scene_script = [
script.actorHide(actorId='player'), script.group(children = {
'true': [script.ifTrue(variable='4', children = {
'true': [script.actorSetDirection(actorId='d983c34a-9eba-4cb3-83cf-4e6ddb6d39ad', direction='up'), script.end()],
'false': [script.end()]
}), script.ifTrue(variable='5', children = {
'true': [script.actorSetDirection(actorId='044598b7-a634-427d-9c88-e998fabe8d9a', direction='up'), script.end()],
'false': [script.end()]
}), script.ifTrue(variable='6', children = {
'true': [script.actorSetDirection(actorId='6d80f0f6-047d-4494-811d-5f526e58959e', direction='up'), script.end()],
'false': [script.end()]
}), script.ifTrue(variable='7', children = {
'true': [script.actorSetDirection(actorId='51558c54-c7e2-46d1-9015-f7b83a6a4ff4', direction='up'), script.end()],
'false': [script.end()]
}), script.ifTrue(variable='8', children = {
'true': [script.actorSetDirection(actorId='62ecd9f0-005a-402f-8ad0-8ec8c3b514f3', direction='up'), script.end()],
'false': [script.end()]
}), script.ifTrue(variable='9', children = {
'true': [script.actorSetDirection(actorId='4c9409a4-0872-486e-a1a1-5b74caaa6960', direction='up'), script.end()],
'false': [script.end()]
}), script.end()]
}), script.awaitInput(input=['a', 'b', 'start', 'select']), script.scenePopState(fadeSpeed='2'), script.end()
]
gen_scene_scn = generator.makeScene("_gen_Menu", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_Menu_00008)
gen_scene_scn['script'] = scene_script
gen_scene_connections = []
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_example_hall_02_00009(callback):
actor_00 = generator.makeActor(None, 20, 13, 'static', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('rock')['id'])
actor_00['script'] = [
script.text(text=["You push the rock\nbut it doesn't\nbudge."], avatarId=''),
script.end()
]
actor_01 = generator.makeActor(None, 6, 11, 'static', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('key_00')['id'])
actor_01['startScript'] = [
script.ifTrue(variable='25', children = {
'true': [script.actorHide(actorId='$self$'), script.end()],
'false': [script.end()]
}),
script.end()
]
actor_01['script'] = [
script.actorHide(actorId='$self$'),
script.setTrue(variable='25'),
script.text(text=['You got the key!'], avatarId=''),
script.end()
]
actor_list = [actor_00, actor_01]
trigger_00 = generator.makeTrigger('trigger_00', 15, 27, 2, 1)
trigger_01 = generator.makeTrigger('trigger_01', 8, 5, 2, 1)
trigger_02 = generator.makeTrigger('trigger_02', 1, 10, 1, 2)
trigger_list = []
collision_data_list = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 207, 255, 255, 255, 240, 255, 255, 15, 255, 252, 3, 240, 207, 63, 0, 255, 252, 1, 240, 207, 31, 0, 255, 252, 3, 240, 207, 63, 0, 255, 252, 3, 240, 207, 255, 63, 255, 252, 255, 243, 207, 255, 63, 255, 252, 255, 243, 207, 255, 63, 255, 252, 63, 240, 207, 255, 3, 255, 252, 63, 0, 0, 252, 63, 0, 192, 255, 3, 0, 252, 255, 195, 255, 255, 63, 252, 255, 255, 231, 255]
gen_scene_bkg = generator.makeBackground("halls_02.png")
gen_scene_scn = generator.makeScene("_gen_example_hall_02", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_example_hall_02_00009)
def addConnection_00(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_00 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_00['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_00
connection_00 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_00, 'args': { 'exit_location': (15, 26), 'exit_direction': 'up', 'entrance': gen_scene_scn['id'], 'entrance_location': (15, 27), 'entrance_size': (2, 1) } }
def addConnection_01(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_01 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_01['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_01
connection_01 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_01, 'args': { 'exit_location': (8, 6), 'exit_direction': 'down', 'entrance': gen_scene_scn['id'], 'entrance_location': (8, 5), 'entrance_size': (2, 1) } }
def addConnection_02(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_02 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_02['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_02
connection_02 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_02, 'args': { 'exit_location': (2, 11), 'exit_direction': 'right', 'entrance': gen_scene_scn['id'], 'entrance_location': (1, 10), 'entrance_size': (1, 2) } }
gen_scene_connections = [connection_00, connection_01, connection_02]
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_example_hall_03_00010(callback):
actor_list = []
trigger_00 = generator.makeTrigger('trigger_00', 11, 24, 2, 1)
trigger_01 = generator.makeTrigger('trigger_01', 20, 19, 2, 1)
trigger_02 = generator.makeTrigger('trigger_02', 14, 7, 2, 1)
trigger_list = []
collision_data_list = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 243, 255, 255, 63, 255, 255, 255, 243, 255, 255, 63, 255, 255, 255, 243, 255, 255, 63, 255, 255, 255, 243, 255, 255, 63, 252, 255, 255, 195, 255, 255, 63, 252, 255, 255, 195, 255, 255, 63, 252, 255, 255, 195, 252, 63, 0, 0, 255, 3, 0, 240, 63, 0, 0, 255, 127, 254, 255, 255, 231, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
gen_scene_bkg = generator.makeBackground("halls_03.png")
gen_scene_scn = generator.makeScene("_gen_example_hall_03", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_example_hall_03_00010)
def addConnection_00(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_00 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_00['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_00
connection_00 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_00, 'args': { 'exit_location': (11, 23), 'exit_direction': 'up', 'entrance': gen_scene_scn['id'], 'entrance_location': (11, 24), 'entrance_size': (2, 1) } }
def addConnection_01(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_01 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_01['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_01
connection_01 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_01, 'args': { 'exit_location': (20, 20), 'exit_direction': 'down', 'entrance': gen_scene_scn['id'], 'entrance_location': (20, 19), 'entrance_size': (2, 1) } }
def addConnection_02(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_02 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_02['script'] = [
script.ifTrue(variable='25', children = {
'true': [script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'), script.end()],
'false': [script.text(text=['The door is\nlocked.'], avatarId=''), script.end()]
}),
script.end()
]
return trigger_02
connection_02 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_02, 'args': { 'exit_location': (14, 8), 'exit_direction': 'down', 'entrance': gen_scene_scn['id'], 'entrance_location': (14, 7), 'entrance_size': (2, 1) } }
gen_scene_connections = [connection_00, connection_01, connection_02]
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_example_hall_04_00011(callback):
actor_list = []
trigger_00 = generator.makeTrigger('trigger_00', 18, 15, 2, 1)
trigger_01 = generator.makeTrigger('trigger_01', 13, 26, 2, 1)
trigger_02 = generator.makeTrigger('trigger_02', 4, 11, 2, 1)
trigger_list = []
collision_data_list = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 207, 255, 255, 255, 252, 255, 255, 207, 255, 255, 255, 252, 63, 255, 207, 255, 192, 255, 252, 15, 252, 207, 255, 192, 255, 252, 207, 255, 15, 0, 252, 255, 0, 192, 255, 15, 0, 252, 255, 0, 192, 255, 15, 0, 252, 255, 255, 249, 255, 255, 159, 255, 255, 255, 255, 255]
gen_scene_bkg = generator.makeBackground("halls_04.png")
gen_scene_scn = generator.makeScene("_gen_example_hall_04", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_example_hall_04_00011)
def addConnection_00(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_00 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_00['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_00
connection_00 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_00, 'args': { 'exit_location': (18, 16), 'exit_direction': 'down', 'entrance': gen_scene_scn['id'], 'entrance_location': (18, 15), 'entrance_size': (2, 1) } }
def addConnection_01(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_01 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_01['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_01
connection_01 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_01, 'args': { 'exit_location': (13, 25), 'exit_direction': 'up', 'entrance': gen_scene_scn['id'], 'entrance_location': (13, 26), 'entrance_size': (2, 1) } }
def addConnection_02(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_02 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_02['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_02
connection_02 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_02, 'args': { 'exit_location': (4, 12), 'exit_direction': 'down', 'entrance': gen_scene_scn['id'], 'entrance_location': (4, 11), 'entrance_size': (2, 1) } }
gen_scene_connections = [connection_00, connection_01, connection_02]
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_Scene_12_00012(callback):
actor_list = []
trigger_00 = generator.makeTrigger('trigger_00', 9, 17, 2, 1)
trigger_list = []
collision_data_list = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 0, 192, 3, 0, 60, 0, 192, 3, 0, 60, 0, 192, 3, 0, 60, 0, 192, 3, 0, 60, 0, 192, 3, 0, 60, 0, 192, 255, 249, 255, 159, 255]
gen_scene_bkg = generator.makeBackground("cave.png")
gen_scene_scn = generator.makeScene("_gen_Scene_12", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_Scene_12_00012)
def addConnection_00(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_00 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_00['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_00
connection_00 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_00, 'args': { 'exit_location': (9, 16), 'exit_direction': 'up', 'entrance': gen_scene_scn['id'], 'entrance_location': (9, 17), 'entrance_size': (2, 1) } }
gen_scene_connections = [connection_00]
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def catalog():
"""
Returns a list of scene functions from this part of the library.
"""
return [scene_gen_Outside_00001,
#scene_gen_Cave_00002,
#scene_gen_House_00003,
#scene_gen_Stars_00004,
scene_gen_Logo_00005,
scene_gen_Title_Screen_00006,
scene_gen_Underground_00007,
scene_gen_Menu_00008,
#scene_gen_example_hall_02_00009,
#scene_gen_example_hall_03_00010,
scene_gen_example_hall_04_00011,
#scene_gen_Scene_12_00012
]
return catalog, sprite_sheet_data
def createExampleProject(num):
"""
Demonstration of how the scene generators in this file can be used.
"""
project = generator.makeBasicProject()
# Create sprite sheet for the player sprite
player_sprite_sheet = generator.addSpriteSheet(project, "actor_animated.png", "actor_animated", "actor_animated")
project.settings["playerSpriteSheetId"] = player_sprite_sheet["id"]
scene_data_list = []
catalog, sprites = scene_generation()
for scn_func in catalog():
scene_data_list.append(scn_func(lambda: num))
for element_sprite in sprites:
project.spriteSheets.append(element_sprite)
generator.connectScenesRandomlySymmetric(scene_data_list)
for sdata in scene_data_list:
generator.addSceneData(project, generator.translateReferences(sdata, scene_data_list))
# Add some music
project.music.append(generator.makeMusic("template", "template.mod"))
# Set the starting scene
project.settings["startSceneId"] = project.scenes[0]["id"]
project.settings["startX"] = 7
project.settings["startY"] = 21
return project
def runTest(test_dir, num):
generator.initializeGenerator()
project = createExampleProject(num)
generator.writeProjectToDisk(project, output_path = test_dir)
# test creating scenes...
if __name__ == '__main__':
for n in range(25):
destination = f"../gbprojects/generated_export_test_{n}/"
runTest(destination, n)
| # Generated Scene Functions
# BasicScenes.py
from rom_generator import generator
from rom_generator import script_functions as script
def scene_generation():
sprite_sheet_data = [
generator.makeSpriteSheet('actor.png', name='actor', type='actor', frames=3),
generator.makeSpriteSheet('actor_animated.png', name='actor_animated', type='actor_animated', frames=6),
generator.makeSpriteSheet('cat.png', name='cat', type='static', frames=1),
generator.makeSpriteSheet('checkbox.png', name='checkbox', type='actor', frames=3),
generator.makeSpriteSheet('connector.png', name='connector', type='animated', frames=2),
generator.makeSpriteSheet('dog.png', name='dog', type='static', frames=1),
generator.makeSpriteSheet('duck.png', name='duck', type='animated', frames=2),
generator.makeSpriteSheet('fire.png', name='fire', type='animated', frames=4),
generator.makeSpriteSheet('GreenBlock.png', name='GreenBlock', type='static', frames=1),
generator.makeSpriteSheet('ice.png', name='ice', type='static', frames=1),
generator.makeSpriteSheet('key_00.png', name='key_00', type='static', frames=1),
generator.makeSpriteSheet('MazeBlock.png', name='MazeBlock', type='static', frames=1),
generator.makeSpriteSheet('npc001.png', name='npc001', type='actor', frames=3),
generator.makeSpriteSheet('npc002.png', name='npc002', type='actor', frames=3),
generator.makeSpriteSheet('npc003.png', name='npc003', type='actor_animated', frames=6),
generator.makeSpriteSheet('player.png', name='player', type='actor_animated', frames=6),
generator.makeSpriteSheet('radio.png', name='radio', type='static', frames=1),
generator.makeSpriteSheet('rock.png', name='rock', type='static', frames=1),
generator.makeSpriteSheet('sage.png', name='sage', type='static', frames=1),
generator.makeSpriteSheet('savepoint.png', name='savepoint', type='animated', frames=2),
generator.makeSpriteSheet('signpost.png', name='signpost', type='static', frames=1),
generator.makeSpriteSheet('static.png', name='static', type='static', frames=1),
generator.makeSpriteSheet('torch.png', name='torch', type='static', frames=1),
generator.makeSpriteSheet('tower.png', name='tower', type='static', frames=1)]
def findSpriteByName(sprite_name):
'''
Returns first sprite that matches the name given.
'''
try:
return [s for s in sprite_sheet_data if (s['name'] == sprite_name)][0]
except:
return None
def getBySceneLabel(scene_label):
'''
This is mostly here so we can get the matching scene from the original
template data. As used here it just grabs the first scene that was made
from that template, so if the template is used more than once it won't
behave as expected and you should generate a proper relationship instad.
'''
s_id = generator.getSceneIdByLabel(scene_label)
if s_id == None:
return '<♔' + scene_label + '♔>'
return s_id
def scene_gen_Outside_00001(callback):
actor_00 = generator.makeActor(None, 25, 14, 'static', moveSpeed=0, direction='down', script=[], sprite_id=findSpriteByName('rock')['id'])
actor_00['script'] = [
script.actorPush(do_continue=False),
script.end()
]
actor_01 = generator.makeActor(None, 27, 23, 'static', direction='down', script=[], sprite_id=findSpriteByName('signpost')['id'])
actor_01['script'] = [
script.text(text='Welcome to\nGBStudio!'),
script.end()
]
actor_02 = generator.makeActor(None, 21, 18, 'static', animate=True, animSpeed=1, direction='down', script=[], sprite_id=findSpriteByName('duck')['id'])
actor_03 = generator.makeActor(None, 3, 24, 'randomWalk', direction='down', script=[], sprite_id=findSpriteByName('npc003')['id'])
actor_03['script'] = [
script.text(text='Have you seen my\ncat anywhere?'),
script.ifTrue(variable='0', children = {
'true': [script.text(text='He\'s by the house?\nThank you!'), script.setTrue(variable='4'), script.end()],
'false': [script.end()]
}),
script.end()
]
actor_04 = generator.makeActor(None, 4, 6, 'static', direction='down', script=[], sprite_id=findSpriteByName('cat')['id'])
actor_04['script'] = [
script.text(text='Meow!'),
script.setTrue(variable='0'),
script.end()
]
actor_05 = generator.makeActor(None, 21, 24, 'faceInteraction', direction='up', script=[], sprite_id=findSpriteByName('npc001')['id'])
actor_05['script'] = [
script.ifTrue(variable='1', children = {
'true': [script.text(text='I guess it was a\nmisunderstanding.'), script.setTrue(variable='8'), script.end()],
'false': [script.text(text='What is that guy\nlooking at?'), script.actorSetDirection(actorId='a85c4ba5-9bc0-4daa-94bc-4ef68a690659', direction='up'), script.end()]
}),
script.end()
]
actor_06 = generator.makeActor(None, 21, 16, 'faceInteraction', direction='down', script=[], sprite_id=findSpriteByName('npc001')['id'])
actor_06['script'] = [
script.text(text='Check out this\nsweet duck!'),
script.setTrue(variable='1'),
script.actorSetDirection(actorId='5cf6eb6c-be62-4efc-9cbb-14a8efac21a8', direction='down'),
script.end()
]
actor_list = [actor_00, actor_01, actor_02, actor_03, actor_04, actor_05, actor_06]
trigger_00 = generator.makeTrigger('trigger_00', 25, 13, 2, 2)
trigger_01 = generator.makeTrigger('trigger_01', 24, 8, 2, 1)
trigger_02 = generator.makeTrigger('trigger_02', 10, 8, 2, 1)
trigger_list = []
collision_data_list = [255, 255, 7, 0, 255, 255, 7, 0, 255, 255, 7, 0, 153, 153, 5, 0, 3, 63, 4, 0, 3, 63, 4, 0, 3, 63, 28, 0, 1, 63, 144, 7, 3, 51, 240, 252, 3, 0, 0, 192, 3, 0, 0, 192, 1, 0, 0, 128, 99, 0, 0, 192, 243, 0, 0, 192, 243, 0, 0, 192, 97, 0, 0, 128, 3, 0, 0, 192, 3, 128, 255, 207, 3, 248, 0, 216, 1, 14, 0, 144, 3, 2, 0, 208, 3, 30, 0, 208, 3, 112, 0, 220, 1, 192, 255, 135, 3, 0, 0, 192, 2, 0, 0, 192, 2, 0, 0, 192, 1, 0, 0, 128, 255, 255, 255, 255, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
gen_scene_bkg = generator.makeBackground("outside.png")
scene_script = [
script.end()
]
gen_scene_scn = generator.makeScene("_gen_Outside", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_Outside_00001)
gen_scene_scn['script'] = scene_script
def addConnection_00(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_00 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_00['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_00
connection_00 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_00, 'args': { 'exit_location': (25, 15), 'exit_direction': 'down', 'entrance': gen_scene_scn['id'], 'entrance_location': (25, 13), 'entrance_size': (2, 2) } }
def addConnection_01(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_01 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_01['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_01
connection_01 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_01, 'args': { 'exit_location': (24, 9), 'exit_direction': 'down', 'entrance': gen_scene_scn['id'], 'entrance_location': (24, 8), 'entrance_size': (2, 1) } }
def addConnection_02(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_02 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_02['script'] = [
script.switchScene(x=destination_location[0], y=destination_location[1], direction=destination_direction, sceneId=destination_scene_id, fadeSpeed='2'),
script.end()
]
return trigger_02
connection_02 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_02, 'args': { 'exit_location': (10, 9), 'exit_direction': 'down', 'entrance': gen_scene_scn['id'], 'entrance_location': (10, 8), 'entrance_size': (2, 1) } }
gen_scene_connections = [connection_00, connection_01, connection_02]
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_Cave_00002(callback):
actor_00 = generator.makeActor(None, 4, 6, 'faceInteraction', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('torch')['id'])
actor_01 = generator.makeActor(None, 4, 4, 'static', animate=True, moveSpeed=1, animSpeed=4, direction='down', script=[], sprite_id=findSpriteByName('fire')['id'])
actor_02 = generator.makeActor(None, 9, 7, 'static', direction='down', script=[], sprite_id=findSpriteByName('sage')['id'])
actor_02['script'] = [
script.text(text='It\'s dangerous to\ngo without docs.'),
script.text(text='Check out\ngbstudio.dev/docs'),
script.text(text='Also, try moving\nthe rock outside.'),
script.setTrue(variable='7'),
script.end()
]
actor_03 = generator.makeActor(None, 14, 6, 'faceInteraction', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('torch')['id'])
actor_04 = generator.makeActor(None, 14, 4, 'static', animate=True, moveSpeed=1, animSpeed=4, direction='down', script=[], sprite_id=findSpriteByName('fire')['id'])
actor_05 = generator.makeActor(None, 14, 11, 'static', animate=True, moveSpeed=1, animSpeed=2, direction='down', script=[], sprite_id=findSpriteByName('savepoint')['id'])
actor_05['script'] = [
script.choice(variable='11', trueText='Save Game', falseText='Cancel'),
script.ifTrue(variable='11', children = {
'true': [script.saveData(), script.text(text='Game progress has\nbeen saved.'), script.text(text='It is now safe to\nturn off your\nsystem.'), script.end()],
'false': [script.end()]
}),
script.end()
]
actor_list = [actor_00, actor_01, actor_02, actor_03, actor_04, actor_05]
trigger_00 = generator.makeTrigger('trigger_00', 9, 17, 2, 1)
trigger_list = []
collision_data_list = [0, 0, 0, 0, 0, 0, 0, 224, 255, 127, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 254, 249, 7, 144, 0]
gen_scene_bkg = generator.makeBackground("cave.png")
scene_script = [
script.end()
]
gen_scene_scn = generator.makeScene("_gen_Cave", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_Cave_00002)
gen_scene_scn['script'] = scene_script
def addConnection_00(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_00 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_00['script'] = [
script.switchScene(x=destination_location[0], y=destination_location[1], direction=destination_direction, sceneId=destination_scene_id, fadeSpeed='2'),
script.end()
]
return trigger_00
connection_00 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_00, 'args': { 'exit_location': (9, 15), 'exit_direction': 'up', 'entrance': gen_scene_scn['id'], 'entrance_location': (9, 17), 'entrance_size': (2, 1) } }
gen_scene_connections = [connection_00]
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_House_00003(callback):
actor_00 = generator.makeActor(None, 12, 5, 'faceInteraction', direction='down', script=[], sprite_id=findSpriteByName('npc002')['id'])
actor_00['script'] = [
script.ifFalse(variable='2', children = {
'true': [script.text(text='Have you tried\nusing this radio?'), script.end()],
'false': [script.text(text='Yeah it doesn\'t\nfit does it?'), script.actorEmote(actorId='566c8812-a204-45b5-b93a-c113c10c20de', emoteId='3'), script.text(text='But it\'s all I\nhave right now...'), script.setTrue(variable='6'), script.end()]
}),
script.end()
]
actor_01 = generator.makeActor(None, 15, 5, 'static', direction='down', script=[], sprite_id=findSpriteByName('radio')['id'])
actor_01['script'] = [
script.ifFalse(variable='2', children = {
'true': [script.musicPlay(musicId='f50428ab-a084-4591-9bba-2ba10fe7b1c6', loop=True), script.setTrue(variable='2'), script.end()],
'false': [script.musicStop(), script.setFalse(variable='2'), script.end()]
}),
script.end()
]
actor_02 = generator.makeActor(None, 15, 11, 'static', direction='down', script=[], sprite_id=findSpriteByName('signpost')['id'])
actor_02['script'] = [
script.text(text='Add sprites to\nassets/sprites'),
script.end()
]
actor_03 = generator.makeActor(None, 3, 11, 'static', direction='down', script=[], sprite_id=findSpriteByName('signpost')['id'])
actor_03['script'] = [
script.text(text='Add backgrounds to\nassets/backgrounds'),
script.end()
]
actor_04 = generator.makeActor(None, 3, 5, 'static', direction='down', script=[], sprite_id=findSpriteByName('signpost')['id'])
actor_04['script'] = [
script.text(text='This room is\npretty empty.'),
script.text(text='Try to edit\nhouse.png'),
script.end()
]
actor_list = [actor_00, actor_01, actor_02, actor_03, actor_04]
trigger_00 = generator.makeTrigger('trigger_00', 9, 16, 2, 1)
trigger_list = []
collision_data_list = [0, 0, 0, 0, 0, 0, 0, 224, 255, 127, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 2, 0, 36, 0, 64, 2, 0, 228, 159, 127, 0, 9, 0, 240, 0]
gen_scene_bkg = generator.makeBackground("house.png")
scene_script = [
script.end()
]
gen_scene_scn = generator.makeScene("_gen_House", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_House_00003)
gen_scene_scn['script'] = scene_script
def addConnection_00(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_00 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_00['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_00
connection_00 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_00, 'args': { 'exit_location': (9, 14), 'exit_direction': 'up', 'entrance': gen_scene_scn['id'], 'entrance_location': (9, 16), 'entrance_size': (2, 1) } }
gen_scene_connections = [connection_00]
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_Stars_00004(callback):
actor_00 = generator.makeActor(None, 15, 12, 'static', direction='down', script=[], sprite_id=findSpriteByName('dog')['id'])
actor_00['script'] = [
script.text(text='How did you\nget here!?!?'),
script.incValue(variable='3'),
script.ifValue(variable='3', operator='==', comparator=1, children = {
'true': [script.text(text='You have spoken to\nme $03$ time.'), script.end()],
'false': [script.text(text='You have spoken to\nme $03$ times.'), script.end()]
}),
script.setTrue(variable='9'),
script.end()
]
actor_list = [actor_00]
trigger_list = []
collision_data_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
gen_scene_bkg = generator.makeBackground("stars.png")
scene_script = [
script.end()
]
gen_scene_scn = generator.makeScene("_gen_Stars", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_Stars_00004)
gen_scene_scn['script'] = scene_script
gen_scene_connections = []
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_Logo_00005(callback):
actor_list = []
trigger_list = []
collision_data_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
gen_scene_bkg = generator.makeBackground("logo.png")
scene_script = [
script.actorHide(actorId='player'), script.overlayShow(color='black', x=0, y=0), script.overlayMoveTo(x=0, y=18, speed='2'), script.wait(time=2), script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Title Screen>♔', x=0, y=0, direction='', fadeSpeed='2'), script.end()
]
gen_scene_scn = generator.makeScene("_gen_Logo", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_Logo_00005)
gen_scene_scn['script'] = scene_script
gen_scene_connections = []
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_Title_Screen_00006(callback):
actor_list = []
trigger_list = []
collision_data_list = []
gen_scene_bkg = generator.makeBackground("titlescreen.png")
gen_scene_scn = generator.makeScene("_gen_Title_Screen", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_Title_Screen_00006)
possible_scene_script = [[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[],[]]
possible_scene_script[0] = [
script.actorHide(actorId='player'), script.awaitInput(input=['a', 'b', 'start', 'select']), script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(), script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'), script.end()]
}), script.end()]
}), script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'), script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [script.loadData(), script.end()],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}), script.end()]
}), script.end()]
})
]
possible_scene_script[1] = [
script.actorHide(actorId='player'), script.awaitInput(input=['a', 'b', 'start', 'select']), script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(), script.switchScene(sceneId=gen_scene_scn['id'], x=0, y=0, direction='', fadeSpeed='2'), script.end()]
}), script.end()]
}), script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'), script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId=gen_scene_scn['id'], x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [script.loadData(), script.end()],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}), script.end()]
}), script.end()]
}), script.end()
]
possible_scene_script[2] = [
script.actorHide(actorId='player'), script.awaitInput(input=['a', 'b', 'start', 'select']), script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(), script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2')]
})]
}), script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'), script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4')],
'false': [script.ifSavedData(children = {
'true': [script.loadData()],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[3] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.group(children = {
'true': [script.setInputScript(input='start',
children = {
'true': [script.scenePushState(), script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2')]
})]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4')],
'false': [script.ifSavedData(children = {
'true': [script.loadData()],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[4] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.group(children = {
'true': [script.setInputScript(input='start',
children = {
'true': []
})]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4')],
'false': [script.ifSavedData(children = {
'true': [script.loadData()],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[5] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.group(children = {
'true': [script.setInputScript(input='start',
children = {
'true': []
})]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [],
'false': [script.ifSavedData(children = {
'true': [script.loadData()],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[6] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.group(children = {
'true': [script.setInputScript(input='start',
children = {
'true': [script.scenePushState(), script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2')]
})]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [],
'false': [script.ifSavedData(children = {
'true': [script.loadData()],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[7] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.group(children = {
'true': [script.setInputScript(input='start',
children = {
'true': []
})]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [],
'false': [script.ifSavedData(children = {
'true': [script.loadData()],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[8] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [],
'false': [script.ifSavedData(children = {
'true': [script.loadData()],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[9] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select'])
]
possible_scene_script[10] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [],
'false': [script.ifSavedData(children = {
'true': [script.loadData()],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[11] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [],
'false': [script.ifSavedData(children = {
'true': [],
'false': [script.text(text='No Save Data\nFound...')]
})]
})]
})
]
possible_scene_script[12] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.loop(children = {
'true': [
script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [],
'false': []
})]
})
]
possible_scene_script[13] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.loop(children = {
'true': []
})
]
# doesn't work
possible_scene_script[14] = [
script.actorHide(actorId='player'), script.awaitInput(input=['a', 'b', 'start', 'select']), script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(), script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'), script.end()]
}), script.end()]
}), script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'), script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}), script.end()]
}), script.end()]
})
]
# works
possible_scene_script[15] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'), script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}), script.end()]
}), script.end()]
})
]
# works
possible_scene_script[16] = [
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'), script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}), script.end()]
}), script.end()]
})
]
# Doesn't work
possible_scene_script[17] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(), script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'), script.end()]
}), script.end()]
}), script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'), script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': []
}), script.end()]
})
]
# doesn't work
possible_scene_script[18] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(),
script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'),
script.end()]
}),
script.end()]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [script.end()],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}),
script.end()]
}),
script.end()]
})
]
# works
possible_scene_script[19] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [script.end()],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}),
script.end()]
}),
script.end()]
})
]
# works
possible_scene_script[20] = [
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [script.end()],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}),
script.end()]
}),
script.end()]
})
]
# doesn't work
possible_scene_script[21] = [
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(),
script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'),
script.end()]
}),
script.end()]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': []
}),
script.end()]
})
]
# works
possible_scene_script[22] = [
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [
script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'),
script.end()]
}),
script.end()]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': []
}),
script.end()]
})
]
# doesn't work
possible_scene_script[23] = [
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(),
]
}),
script.end()]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': []
}),
script.end()]
})
]
# works
possible_scene_script[24] = [
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': []
}),
script.end()]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': []
}),
script.end()]
})
]
possible_scene_script[25] = [
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(),
script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'),
script.end()]
}),
script.end()]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': []
}),
script.end()]
})
]
possible_scene_script[26] = [
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(),
script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'),
script.end()]
}),
script.end()]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': []
}),
script.end()]
})
]
possible_scene_script[27] = [
script.actorHide(actorId='player'),
script.awaitInput(input=['a', 'b', 'start', 'select']),
script.group(children = {
'true': [script.setInputScript(input='start', children = {
'true': [script.scenePushState(),
script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Menu>♔', x=0, y=0, direction='', fadeSpeed='2'),
script.end()]
}),
script.end()]
}),
script.loop(children = {
'true': [script.choice(variable='10', trueText='New Game', falseText='Continue'),
script.ifTrue(variable='10', children = {
'true': [script.switchScene(sceneId='♔REFERENCE_TO_SCENES_<Outside>♔', x=27, y=26, direction='left', fadeSpeed='4'), script.end()],
'false': [script.ifSavedData(children = {
'true': [script.loadData(),
script.end()],
'false': [script.text(text='No Save Data\nFound...'), script.end()]
}),
script.end()]
}),
script.end()]
})
]
scene_script = possible_scene_script[callback()]
gen_scene_scn['script'] = scene_script
gen_scene_connections = []
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_Underground_00007(callback):
actor_00 = generator.makeActor(None, 7, 25, 'static', direction='down', script=[], sprite_id=findSpriteByName('signpost')['id'])
actor_00['script'] = [
script.text(text='Try to get the ice\nblock to the mark.'),
script.text(text='If you get stuck,\nI\'ll reset it!'),
script.actorSetPosition(actorId='27de6d44-f7c0-48df-a952-2c87471bbfd4', x=24, y=18),
script.end()
]
actor_01 = generator.makeActor(None, 24, 18, 'static', moveSpeed=2, direction='down', script=[], sprite_id=findSpriteByName('ice')['id'])
actor_01['script'] = [
script.ifActorAtPosition(actorId='27de6d44-f7c0-48df-a952-2c87471bbfd4', x=15, y=10, children = {
'true': [script.end()],
'false': [script.actorPush(do_continue=True), script.ifActorAtPosition(actorId='27de6d44-f7c0-48df-a952-2c87471bbfd4', x=15, y=10, children = {
'true': [script.text(text='Success!'), script.setTrue(variable='5'), script.end()],
'false': [script.end()]
}), script.end()]
}),
script.setTrue(variable='12'),
script.end()
]
actor_02 = generator.makeActor(None, 23, 27, 'static', moveSpeed=0, direction='down', script=[], sprite_id=findSpriteByName('rock')['id'])
actor_02['script'] = [
script.actorPush(do_continue=False),
script.end()
]
actor_03 = generator.makeActor(None, 21, 27, 'static', moveSpeed=0, direction='down', script=[], sprite_id=findSpriteByName('rock')['id'])
actor_03['script'] = [
script.actorPush(do_continue=False),
script.end()
]
actor_04 = generator.makeActor(None, 19, 27, 'static', moveSpeed=0, direction='down', script=[], sprite_id=findSpriteByName('rock')['id'])
actor_04['script'] = [
script.actorPush(do_continue=False),
script.end()
]
actor_list = [actor_00, actor_01, actor_02, actor_03, actor_04]
trigger_00 = generator.makeTrigger('trigger_00', 21, 30, 2, 2)
trigger_list = []
collision_data_list = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 248, 255, 255, 31, 248, 255, 255, 31, 8, 128, 1, 19, 200, 128, 1, 19, 200, 0, 0, 16, 200, 0, 0, 16, 8, 0, 0, 16, 8, 0, 0, 16, 8, 0, 6, 16, 8, 0, 6, 16, 8, 3, 6, 16, 8, 3, 0, 16, 248, 255, 255, 28, 254, 255, 255, 124, 254, 255, 255, 124, 2, 0, 0, 64, 2, 0, 158, 71, 2, 128, 159, 71, 2, 128, 159, 71, 2, 128, 7, 118, 2, 128, 7, 118, 2, 128, 7, 118, 2, 0, 6, 118, 2, 0, 6, 118, 254, 255, 159, 127, 0, 0, 144, 0]
gen_scene_bkg = generator.makeBackground("underground.png")
scene_script = [
script.group(children = {
'true': [script.ifTrue(variable='12', children = {
'true': [script.actorSetPosition(actorId='27de6d44-f7c0-48df-a952-2c87471bbfd4', x=24, y=15), script.end()],
'false': [script.end()]
}), script.end()]
}), script.end()
]
gen_scene_scn = generator.makeScene("_gen_Underground", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_Underground_00007)
gen_scene_scn['script'] = scene_script
def addConnection_00(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_00 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_00['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_00
connection_00 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_00, 'args': { 'exit_location': (21, 29), 'exit_direction': 'up', 'entrance': gen_scene_scn['id'], 'entrance_location': (21, 30), 'entrance_size': (2, 2) } }
gen_scene_connections = [connection_00]
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_Menu_00008(callback):
actor_00 = generator.makeActor(None, 2, 4, 'faceInteraction', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('checkbox')['id'])
actor_00['script'] = [
script.end()
]
actor_01 = generator.makeActor(None, 2, 6, 'faceInteraction', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('checkbox')['id'])
actor_01['script'] = [
script.end()
]
actor_02 = generator.makeActor(None, 2, 8, 'faceInteraction', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('checkbox')['id'])
actor_02['script'] = [
script.end()
]
actor_03 = generator.makeActor(None, 2, 11, 'faceInteraction', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('checkbox')['id'])
actor_03['script'] = [
script.end()
]
actor_04 = generator.makeActor(None, 2, 13, 'faceInteraction', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('checkbox')['id'])
actor_04['script'] = [
script.end()
]
actor_05 = generator.makeActor(None, 2, 15, 'faceInteraction', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('checkbox')['id'])
actor_05['script'] = [
script.end()
]
actor_list = [actor_00, actor_01, actor_02, actor_03, actor_04, actor_05]
trigger_list = []
collision_data_list = []
gen_scene_bkg = generator.makeBackground("menu.png")
scene_script = [
script.actorHide(actorId='player'), script.group(children = {
'true': [script.ifTrue(variable='4', children = {
'true': [script.actorSetDirection(actorId='d983c34a-9eba-4cb3-83cf-4e6ddb6d39ad', direction='up'), script.end()],
'false': [script.end()]
}), script.ifTrue(variable='5', children = {
'true': [script.actorSetDirection(actorId='044598b7-a634-427d-9c88-e998fabe8d9a', direction='up'), script.end()],
'false': [script.end()]
}), script.ifTrue(variable='6', children = {
'true': [script.actorSetDirection(actorId='6d80f0f6-047d-4494-811d-5f526e58959e', direction='up'), script.end()],
'false': [script.end()]
}), script.ifTrue(variable='7', children = {
'true': [script.actorSetDirection(actorId='51558c54-c7e2-46d1-9015-f7b83a6a4ff4', direction='up'), script.end()],
'false': [script.end()]
}), script.ifTrue(variable='8', children = {
'true': [script.actorSetDirection(actorId='62ecd9f0-005a-402f-8ad0-8ec8c3b514f3', direction='up'), script.end()],
'false': [script.end()]
}), script.ifTrue(variable='9', children = {
'true': [script.actorSetDirection(actorId='4c9409a4-0872-486e-a1a1-5b74caaa6960', direction='up'), script.end()],
'false': [script.end()]
}), script.end()]
}), script.awaitInput(input=['a', 'b', 'start', 'select']), script.scenePopState(fadeSpeed='2'), script.end()
]
gen_scene_scn = generator.makeScene("_gen_Menu", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_Menu_00008)
gen_scene_scn['script'] = scene_script
gen_scene_connections = []
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_example_hall_02_00009(callback):
actor_00 = generator.makeActor(None, 20, 13, 'static', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('rock')['id'])
actor_00['script'] = [
script.text(text=["You push the rock\nbut it doesn't\nbudge."], avatarId=''),
script.end()
]
actor_01 = generator.makeActor(None, 6, 11, 'static', moveSpeed=1, animSpeed=3, direction='down', script=[], sprite_id=findSpriteByName('key_00')['id'])
actor_01['startScript'] = [
script.ifTrue(variable='25', children = {
'true': [script.actorHide(actorId='$self$'), script.end()],
'false': [script.end()]
}),
script.end()
]
actor_01['script'] = [
script.actorHide(actorId='$self$'),
script.setTrue(variable='25'),
script.text(text=['You got the key!'], avatarId=''),
script.end()
]
actor_list = [actor_00, actor_01]
trigger_00 = generator.makeTrigger('trigger_00', 15, 27, 2, 1)
trigger_01 = generator.makeTrigger('trigger_01', 8, 5, 2, 1)
trigger_02 = generator.makeTrigger('trigger_02', 1, 10, 1, 2)
trigger_list = []
collision_data_list = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 207, 255, 255, 255, 240, 255, 255, 15, 255, 252, 3, 240, 207, 63, 0, 255, 252, 1, 240, 207, 31, 0, 255, 252, 3, 240, 207, 63, 0, 255, 252, 3, 240, 207, 255, 63, 255, 252, 255, 243, 207, 255, 63, 255, 252, 255, 243, 207, 255, 63, 255, 252, 63, 240, 207, 255, 3, 255, 252, 63, 0, 0, 252, 63, 0, 192, 255, 3, 0, 252, 255, 195, 255, 255, 63, 252, 255, 255, 231, 255]
gen_scene_bkg = generator.makeBackground("halls_02.png")
gen_scene_scn = generator.makeScene("_gen_example_hall_02", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_example_hall_02_00009)
def addConnection_00(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_00 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_00['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_00
connection_00 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_00, 'args': { 'exit_location': (15, 26), 'exit_direction': 'up', 'entrance': gen_scene_scn['id'], 'entrance_location': (15, 27), 'entrance_size': (2, 1) } }
def addConnection_01(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_01 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_01['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_01
connection_01 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_01, 'args': { 'exit_location': (8, 6), 'exit_direction': 'down', 'entrance': gen_scene_scn['id'], 'entrance_location': (8, 5), 'entrance_size': (2, 1) } }
def addConnection_02(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_02 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_02['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_02
connection_02 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_02, 'args': { 'exit_location': (2, 11), 'exit_direction': 'right', 'entrance': gen_scene_scn['id'], 'entrance_location': (1, 10), 'entrance_size': (1, 2) } }
gen_scene_connections = [connection_00, connection_01, connection_02]
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_example_hall_03_00010(callback):
actor_list = []
trigger_00 = generator.makeTrigger('trigger_00', 11, 24, 2, 1)
trigger_01 = generator.makeTrigger('trigger_01', 20, 19, 2, 1)
trigger_02 = generator.makeTrigger('trigger_02', 14, 7, 2, 1)
trigger_list = []
collision_data_list = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 243, 255, 255, 63, 255, 255, 255, 243, 255, 255, 63, 255, 255, 255, 243, 255, 255, 63, 255, 255, 255, 243, 255, 255, 63, 252, 255, 255, 195, 255, 255, 63, 252, 255, 255, 195, 255, 255, 63, 252, 255, 255, 195, 252, 63, 0, 0, 255, 3, 0, 240, 63, 0, 0, 255, 127, 254, 255, 255, 231, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]
gen_scene_bkg = generator.makeBackground("halls_03.png")
gen_scene_scn = generator.makeScene("_gen_example_hall_03", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_example_hall_03_00010)
def addConnection_00(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_00 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_00['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_00
connection_00 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_00, 'args': { 'exit_location': (11, 23), 'exit_direction': 'up', 'entrance': gen_scene_scn['id'], 'entrance_location': (11, 24), 'entrance_size': (2, 1) } }
def addConnection_01(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_01 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_01['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_01
connection_01 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_01, 'args': { 'exit_location': (20, 20), 'exit_direction': 'down', 'entrance': gen_scene_scn['id'], 'entrance_location': (20, 19), 'entrance_size': (2, 1) } }
def addConnection_02(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_02 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_02['script'] = [
script.ifTrue(variable='25', children = {
'true': [script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'), script.end()],
'false': [script.text(text=['The door is\nlocked.'], avatarId=''), script.end()]
}),
script.end()
]
return trigger_02
connection_02 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_02, 'args': { 'exit_location': (14, 8), 'exit_direction': 'down', 'entrance': gen_scene_scn['id'], 'entrance_location': (14, 7), 'entrance_size': (2, 1) } }
gen_scene_connections = [connection_00, connection_01, connection_02]
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_example_hall_04_00011(callback):
actor_list = []
trigger_00 = generator.makeTrigger('trigger_00', 18, 15, 2, 1)
trigger_01 = generator.makeTrigger('trigger_01', 13, 26, 2, 1)
trigger_02 = generator.makeTrigger('trigger_02', 4, 11, 2, 1)
trigger_list = []
collision_data_list = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 252, 255, 255, 207, 255, 255, 255, 252, 255, 255, 207, 255, 255, 255, 252, 63, 255, 207, 255, 192, 255, 252, 15, 252, 207, 255, 192, 255, 252, 207, 255, 15, 0, 252, 255, 0, 192, 255, 15, 0, 252, 255, 0, 192, 255, 15, 0, 252, 255, 255, 249, 255, 255, 159, 255, 255, 255, 255, 255]
gen_scene_bkg = generator.makeBackground("halls_04.png")
gen_scene_scn = generator.makeScene("_gen_example_hall_04", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_example_hall_04_00011)
def addConnection_00(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_00 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_00['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_00
connection_00 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_00, 'args': { 'exit_location': (18, 16), 'exit_direction': 'down', 'entrance': gen_scene_scn['id'], 'entrance_location': (18, 15), 'entrance_size': (2, 1) } }
def addConnection_01(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_01 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_01['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_01
connection_01 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_01, 'args': { 'exit_location': (13, 25), 'exit_direction': 'up', 'entrance': gen_scene_scn['id'], 'entrance_location': (13, 26), 'entrance_size': (2, 1) } }
def addConnection_02(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_02 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_02['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_02
connection_02 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_02, 'args': { 'exit_location': (4, 12), 'exit_direction': 'down', 'entrance': gen_scene_scn['id'], 'entrance_location': (4, 11), 'entrance_size': (2, 1) } }
gen_scene_connections = [connection_00, connection_01, connection_02]
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def scene_gen_Scene_12_00012(callback):
actor_list = []
trigger_00 = generator.makeTrigger('trigger_00', 9, 17, 2, 1)
trigger_list = []
collision_data_list = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 63, 0, 192, 3, 0, 60, 0, 192, 3, 0, 60, 0, 192, 3, 0, 60, 0, 192, 3, 0, 60, 0, 192, 3, 0, 60, 0, 192, 255, 249, 255, 159, 255]
gen_scene_bkg = generator.makeBackground("cave.png")
gen_scene_scn = generator.makeScene("_gen_Scene_12", gen_scene_bkg, collisions=collision_data_list, actors=actor_list, triggers=trigger_list, scene_label=scene_gen_Scene_12_00012)
def addConnection_00(source_location, source_size, destination_scene_id, destination_location, destination_direction):
trigger_00 = generator.makeTrigger('trigger_connection', source_location[0], source_location[1], source_size[0], source_size[1])
trigger_00['script'] = [
script.switchScene(sceneId=destination_scene_id, x=destination_location[0], y=destination_location[1], direction=destination_direction, fadeSpeed='2'),
script.end()
]
return trigger_00
connection_00 = {'type': 'SLOT_CONNECTION', 'creator': addConnection_00, 'args': { 'exit_location': (9, 16), 'exit_direction': 'up', 'entrance': gen_scene_scn['id'], 'entrance_location': (9, 17), 'entrance_size': (2, 1) } }
gen_scene_connections = [connection_00]
scene_data = {"scene": gen_scene_scn, "background": gen_scene_bkg, "sprites": [], "connections": gen_scene_connections, "references": [], "tags": []}
return scene_data
def catalog():
"""
Returns a list of scene functions from this part of the library.
"""
return [scene_gen_Outside_00001,
#scene_gen_Cave_00002,
#scene_gen_House_00003,
#scene_gen_Stars_00004,
scene_gen_Logo_00005,
scene_gen_Title_Screen_00006,
scene_gen_Underground_00007,
scene_gen_Menu_00008,
#scene_gen_example_hall_02_00009,
#scene_gen_example_hall_03_00010,
scene_gen_example_hall_04_00011,
#scene_gen_Scene_12_00012
]
return catalog, sprite_sheet_data
def createExampleProject(num):
"""
Demonstration of how the scene generators in this file can be used.
"""
project = generator.makeBasicProject()
# Create sprite sheet for the player sprite
player_sprite_sheet = generator.addSpriteSheet(project, "actor_animated.png", "actor_animated", "actor_animated")
project.settings["playerSpriteSheetId"] = player_sprite_sheet["id"]
scene_data_list = []
catalog, sprites = scene_generation()
for scn_func in catalog():
scene_data_list.append(scn_func(lambda: num))
for element_sprite in sprites:
project.spriteSheets.append(element_sprite)
generator.connectScenesRandomlySymmetric(scene_data_list)
for sdata in scene_data_list:
generator.addSceneData(project, generator.translateReferences(sdata, scene_data_list))
# Add some music
project.music.append(generator.makeMusic("template", "template.mod"))
# Set the starting scene
project.settings["startSceneId"] = project.scenes[0]["id"]
project.settings["startX"] = 7
project.settings["startY"] = 21
return project
def runTest(test_dir, num):
generator.initializeGenerator()
project = createExampleProject(num)
generator.writeProjectToDisk(project, output_path = test_dir)
# test creating scenes...
if __name__ == '__main__':
for n in range(25):
destination = f"../gbprojects/generated_export_test_{n}/"
runTest(destination, n)
| en | 0.860996 | # Generated Scene Functions # BasicScenes.py Returns first sprite that matches the name given. This is mostly here so we can get the matching scene from the original
template data. As used here it just grabs the first scene that was made
from that template, so if the template is used more than once it won't
behave as expected and you should generate a proper relationship instad. # doesn't work # works # works # Doesn't work # doesn't work # works # works # doesn't work # works # doesn't work # works Returns a list of scene functions from this part of the library. #scene_gen_Cave_00002, #scene_gen_House_00003, #scene_gen_Stars_00004, #scene_gen_example_hall_02_00009, #scene_gen_example_hall_03_00010, #scene_gen_Scene_12_00012 Demonstration of how the scene generators in this file can be used. # Create sprite sheet for the player sprite # Add some music # Set the starting scene # test creating scenes... | 2.460807 | 2 |
data_capture/tests/test_price_list_views.py | connectthefuture/calc | 0 | 6614163 | import json
import unittest.mock as mock
from datetime import datetime, date
from freezegun import freeze_time
from model_mommy import mommy
from django.test import override_settings
from django.utils import timezone
from hourglass.tests.common import ProtectedViewTestCase
from ..models import SubmittedPriceList
from ..management.commands.initgroups import PRICE_LIST_UPLOAD_PERMISSION
from .common import FAKE_SCHEDULE, uploaded_csv_file
from ..schedules import registry
frozen_datetime = datetime(2016, 2, 11, 15, 20, 31)
class ListViewTests(ProtectedViewTestCase):
url = '/data-capture/price-lists'
def login(self, **kwargs):
kwargs['permissions'] = [PRICE_LIST_UPLOAD_PERMISSION]
return super().login(**kwargs)
def test_get_is_ok(self):
self.login()
res = self.client.get(self.url)
self.assertEqual(res.status_code, 200)
def test_has_context_vars(self):
self.login()
res = self.client.get(self.url)
ctx = res.context
self.assertIn('approved_price_lists', ctx)
self.assertIn('unreviewed_price_lists', ctx)
self.assertIn('rejected_price_lists', ctx)
self.assertIn('retired_price_lists', ctx)
def test_only_includes_price_lists_for_user(self):
user = self.login()
other_user = self.create_user('other_user')
for val, label in SubmittedPriceList.STATUS_CHOICES:
mommy.make(SubmittedPriceList,
submitter=user,
status=val)
mommy.make(SubmittedPriceList,
submitter=other_user,
status=val)
res = self.client.get(self.url)
ctx = res.context
self.assertEqual(len(ctx['approved_price_lists']), 1)
self.assertEqual(len(ctx['unreviewed_price_lists']), 1)
self.assertEqual(len(ctx['rejected_price_lists']), 1)
self.assertEqual(len(ctx['retired_price_lists']), 1)
@override_settings(DATA_CAPTURE_SCHEDULES=[FAKE_SCHEDULE])
class DetailsViewTests(ProtectedViewTestCase):
url = '/data-capture/price-lists/'
valid_post_data = {
'vendor_name': "<NAME>",
'is_small_business': 'False',
'contractor_site': 'Customer',
'escalation_rate': '0',
'contract_start_0': '1985',
'contract_start_1': '07',
'contract_start_2': '08',
'contract_end_0': '1989',
'contract_end_1': '04',
'contract_end_2': '14',
}
def login(self, **kwargs):
kwargs['permissions'] = [PRICE_LIST_UPLOAD_PERMISSION]
return super().login(**kwargs)
def setUp(self):
super().setUp()
a_user = self.create_user('a_user')
p = registry.load_from_upload(FAKE_SCHEDULE, uploaded_csv_file())
serialized = registry.serialize(p)
self.price_list = mommy.make(
SubmittedPriceList,
schedule=FAKE_SCHEDULE,
submitter=a_user,
contract_number="GS-12-1234",
serialized_gleaned_data=json.dumps(serialized),
created_at=timezone.now(),
is_small_business=True,
contractor_site='Both',
escalation_rate=1.2,
contract_start=date(2016, 2, 11),
contract_end=date(2020, 2, 11),
status=SubmittedPriceList.STATUS_UNREVIEWED)
self.url += str(self.price_list.pk)
def test_get_is_ok(self):
self.login()
res = self.client.get(self.url)
self.assertEqual(res.status_code, 200)
self.assertFalse(res.context['show_edit_form'])
def test_has_context_vars(self):
self.login()
res = self.client.get(self.url)
ctx = res.context
self.assertIn('price_list', ctx)
self.assertIn('gleaned_data', ctx)
self.assertEqual(ctx['price_list'], self.price_list)
@freeze_time(frozen_datetime)
def test_post_updates_price_list(self):
user = self.login()
res = self.client.post(self.url, self.valid_post_data, follow=True)
self.assertRedirects(res, self.url)
self.assertEqual(res.status_code, 200)
self.assertHasMessage(
res,
'success',
"Your changes have been submitted. An administrator will "
"review them before they are live in CALC.")
pl = SubmittedPriceList.objects.get(id=self.price_list.pk)
self.assertEqual(pl.status_changed_by, user)
self.assertEqual(pl.status, SubmittedPriceList.STATUS_UNREVIEWED)
self.assertEqual(
pl.status_changed_at,
timezone.make_aware(frozen_datetime))
self.assertEqual(pl.submitter, user)
self.assertEqual(pl.vendor_name, self.valid_post_data['vendor_name'])
self.assertEqual(pl.is_small_business, False)
self.assertEqual(pl.contractor_site,
self.valid_post_data['contractor_site'])
self.assertEqual(pl.contract_start, date(1985, 7, 8))
self.assertEqual(pl.contract_end, date(1989, 4, 14))
self.assertEqual(pl.escalation_rate, 0)
@mock.patch.object(SubmittedPriceList, 'unreview')
def test_valid_post_calls_unreview(self, mock):
self.login()
res = self.client.post(self.url, self.valid_post_data, follow=True)
self.assertRedirects(res, self.url)
self.assertEqual(res.status_code, 200)
self.assertEqual(mock.call_count, 1)
def test_invalid_post_shows_errors(self):
self.login()
data = self.valid_post_data.copy()
data['contractor_site'] = 'LOL'
res = self.client.post(self.url, data)
self.assertTrue(res.context['show_edit_form'], True)
self.assertContains(res, 'LOL is not one of the available choices')
def test_post_of_unchanged_data_shows_message(self):
self.login()
pl = SubmittedPriceList.objects.get(id=self.price_list.pk)
data = {
'vendor_name': pl.vendor_name,
'is_small_business': pl.is_small_business,
'contractor_site': pl.contractor_site,
'escalation_rate': pl.escalation_rate,
'contract_start_0': pl.contract_start.year,
'contract_start_1': pl.contract_start.month,
'contract_start_2': pl.contract_start.day,
'contract_end_0': pl.contract_end.year,
'contract_end_1': pl.contract_end.month,
'contract_end_2': pl.contract_end.day,
}
res = self.client.post(self.url, data, follow=True)
self.assertRedirects(res, self.url)
self.assertHasMessage(
res,
'info',
"This price list has not been modified because no changes "
"were found in the submitted form."
)
| import json
import unittest.mock as mock
from datetime import datetime, date
from freezegun import freeze_time
from model_mommy import mommy
from django.test import override_settings
from django.utils import timezone
from hourglass.tests.common import ProtectedViewTestCase
from ..models import SubmittedPriceList
from ..management.commands.initgroups import PRICE_LIST_UPLOAD_PERMISSION
from .common import FAKE_SCHEDULE, uploaded_csv_file
from ..schedules import registry
frozen_datetime = datetime(2016, 2, 11, 15, 20, 31)
class ListViewTests(ProtectedViewTestCase):
url = '/data-capture/price-lists'
def login(self, **kwargs):
kwargs['permissions'] = [PRICE_LIST_UPLOAD_PERMISSION]
return super().login(**kwargs)
def test_get_is_ok(self):
self.login()
res = self.client.get(self.url)
self.assertEqual(res.status_code, 200)
def test_has_context_vars(self):
self.login()
res = self.client.get(self.url)
ctx = res.context
self.assertIn('approved_price_lists', ctx)
self.assertIn('unreviewed_price_lists', ctx)
self.assertIn('rejected_price_lists', ctx)
self.assertIn('retired_price_lists', ctx)
def test_only_includes_price_lists_for_user(self):
user = self.login()
other_user = self.create_user('other_user')
for val, label in SubmittedPriceList.STATUS_CHOICES:
mommy.make(SubmittedPriceList,
submitter=user,
status=val)
mommy.make(SubmittedPriceList,
submitter=other_user,
status=val)
res = self.client.get(self.url)
ctx = res.context
self.assertEqual(len(ctx['approved_price_lists']), 1)
self.assertEqual(len(ctx['unreviewed_price_lists']), 1)
self.assertEqual(len(ctx['rejected_price_lists']), 1)
self.assertEqual(len(ctx['retired_price_lists']), 1)
@override_settings(DATA_CAPTURE_SCHEDULES=[FAKE_SCHEDULE])
class DetailsViewTests(ProtectedViewTestCase):
url = '/data-capture/price-lists/'
valid_post_data = {
'vendor_name': "<NAME>",
'is_small_business': 'False',
'contractor_site': 'Customer',
'escalation_rate': '0',
'contract_start_0': '1985',
'contract_start_1': '07',
'contract_start_2': '08',
'contract_end_0': '1989',
'contract_end_1': '04',
'contract_end_2': '14',
}
def login(self, **kwargs):
kwargs['permissions'] = [PRICE_LIST_UPLOAD_PERMISSION]
return super().login(**kwargs)
def setUp(self):
super().setUp()
a_user = self.create_user('a_user')
p = registry.load_from_upload(FAKE_SCHEDULE, uploaded_csv_file())
serialized = registry.serialize(p)
self.price_list = mommy.make(
SubmittedPriceList,
schedule=FAKE_SCHEDULE,
submitter=a_user,
contract_number="GS-12-1234",
serialized_gleaned_data=json.dumps(serialized),
created_at=timezone.now(),
is_small_business=True,
contractor_site='Both',
escalation_rate=1.2,
contract_start=date(2016, 2, 11),
contract_end=date(2020, 2, 11),
status=SubmittedPriceList.STATUS_UNREVIEWED)
self.url += str(self.price_list.pk)
def test_get_is_ok(self):
self.login()
res = self.client.get(self.url)
self.assertEqual(res.status_code, 200)
self.assertFalse(res.context['show_edit_form'])
def test_has_context_vars(self):
self.login()
res = self.client.get(self.url)
ctx = res.context
self.assertIn('price_list', ctx)
self.assertIn('gleaned_data', ctx)
self.assertEqual(ctx['price_list'], self.price_list)
@freeze_time(frozen_datetime)
def test_post_updates_price_list(self):
user = self.login()
res = self.client.post(self.url, self.valid_post_data, follow=True)
self.assertRedirects(res, self.url)
self.assertEqual(res.status_code, 200)
self.assertHasMessage(
res,
'success',
"Your changes have been submitted. An administrator will "
"review them before they are live in CALC.")
pl = SubmittedPriceList.objects.get(id=self.price_list.pk)
self.assertEqual(pl.status_changed_by, user)
self.assertEqual(pl.status, SubmittedPriceList.STATUS_UNREVIEWED)
self.assertEqual(
pl.status_changed_at,
timezone.make_aware(frozen_datetime))
self.assertEqual(pl.submitter, user)
self.assertEqual(pl.vendor_name, self.valid_post_data['vendor_name'])
self.assertEqual(pl.is_small_business, False)
self.assertEqual(pl.contractor_site,
self.valid_post_data['contractor_site'])
self.assertEqual(pl.contract_start, date(1985, 7, 8))
self.assertEqual(pl.contract_end, date(1989, 4, 14))
self.assertEqual(pl.escalation_rate, 0)
@mock.patch.object(SubmittedPriceList, 'unreview')
def test_valid_post_calls_unreview(self, mock):
self.login()
res = self.client.post(self.url, self.valid_post_data, follow=True)
self.assertRedirects(res, self.url)
self.assertEqual(res.status_code, 200)
self.assertEqual(mock.call_count, 1)
def test_invalid_post_shows_errors(self):
self.login()
data = self.valid_post_data.copy()
data['contractor_site'] = 'LOL'
res = self.client.post(self.url, data)
self.assertTrue(res.context['show_edit_form'], True)
self.assertContains(res, 'LOL is not one of the available choices')
def test_post_of_unchanged_data_shows_message(self):
self.login()
pl = SubmittedPriceList.objects.get(id=self.price_list.pk)
data = {
'vendor_name': pl.vendor_name,
'is_small_business': pl.is_small_business,
'contractor_site': pl.contractor_site,
'escalation_rate': pl.escalation_rate,
'contract_start_0': pl.contract_start.year,
'contract_start_1': pl.contract_start.month,
'contract_start_2': pl.contract_start.day,
'contract_end_0': pl.contract_end.year,
'contract_end_1': pl.contract_end.month,
'contract_end_2': pl.contract_end.day,
}
res = self.client.post(self.url, data, follow=True)
self.assertRedirects(res, self.url)
self.assertHasMessage(
res,
'info',
"This price list has not been modified because no changes "
"were found in the submitted form."
)
| none | 1 | 2.129497 | 2 | |
research/cifar10_test.py | hawkinsonb/rockpaperscissors-cnn | 2 | 6614164 | #!/usr/bin/env python3
# CNN for cifar-10 set
# tested in Anaconda environment
import os
import numpy as np
import matplotlib.pyplot as plt
import keras
from keras.datasets import cifar10
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, AveragePooling2D
# load the cifar10 data
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# slice data into training and validation sets
(x_train, x_valid) = x_train[5000:], x_train[:5000]
(y_train, y_valid) = y_train[5000:], y_train[:5000]
# normalize training and test data
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
# one-hot encode labels
num_classes = len(np.unique(y_train))
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
# define the model
model = Sequential()
model.add(Conv2D(filters=16, kernel_size=2, padding='same', activation='relu',
input_shape=(32, 32, 3)))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(500, activation='relu'))
# final layer - fully connected and results in a probability for each of
# of the ten classes
model.add(Dense(10, activation='softmax'))
# Save model and weights
save_dir = os.path.join(os.getcwd(), 'saved_models')
model_name = 'keras_cifar10_trained_model.h5'
if not os.path.isdir(save_dir):
os.makedirs(save_dir)
model_path = os.path.join(save_dir, model_name)
model.save(model_path)
print('Saved trained model at %s ' % model_path)
# compile and train model
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=32, epochs=8)
# test and display results
score = model.evaluate(x_test, y_test, batch_size=32, verbose=1)
print('Test score:', score[0])
print('Test accuracy:', score[1])
| #!/usr/bin/env python3
# CNN for cifar-10 set
# tested in Anaconda environment
import os
import numpy as np
import matplotlib.pyplot as plt
import keras
from keras.datasets import cifar10
from keras.utils import np_utils
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, AveragePooling2D
# load the cifar10 data
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# slice data into training and validation sets
(x_train, x_valid) = x_train[5000:], x_train[:5000]
(y_train, y_valid) = y_train[5000:], y_train[:5000]
# normalize training and test data
x_train = x_train.astype('float32') / 255
x_test = x_test.astype('float32') / 255
# one-hot encode labels
num_classes = len(np.unique(y_train))
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
# define the model
model = Sequential()
model.add(Conv2D(filters=16, kernel_size=2, padding='same', activation='relu',
input_shape=(32, 32, 3)))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=32, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=64, kernel_size=2, padding='same', activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(500, activation='relu'))
# final layer - fully connected and results in a probability for each of
# of the ten classes
model.add(Dense(10, activation='softmax'))
# Save model and weights
save_dir = os.path.join(os.getcwd(), 'saved_models')
model_name = 'keras_cifar10_trained_model.h5'
if not os.path.isdir(save_dir):
os.makedirs(save_dir)
model_path = os.path.join(save_dir, model_name)
model.save(model_path)
print('Saved trained model at %s ' % model_path)
# compile and train model
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])
model.fit(x_train, y_train, batch_size=32, epochs=8)
# test and display results
score = model.evaluate(x_test, y_test, batch_size=32, verbose=1)
print('Test score:', score[0])
print('Test accuracy:', score[1])
| en | 0.797392 | #!/usr/bin/env python3 # CNN for cifar-10 set # tested in Anaconda environment # load the cifar10 data # slice data into training and validation sets # normalize training and test data # one-hot encode labels # define the model # final layer - fully connected and results in a probability for each of # of the ten classes # Save model and weights # compile and train model # test and display results | 3.319175 | 3 |
visionsam/scripts/move.py | mateoguaman/Semantic-Autonomous-Mapping | 0 | 6614165 | <gh_stars>0
#!/usr/bin/env python
from __future__ import print_function, division
import roslib
import sys
import rospy
import tf
import math
import time
from time import sleep
from std_msgs.msg import String
from geometry_msgs.msg import Pose, PoseArray, PoseWithCovarianceStamped, Quaternion
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
import actionlib
from actionlib_msgs.msg import *
def main(args):
rospy.init_node('move', anonymous=True)
client = actionlib.SimpleActionClient('move_base', MoveBaseAction)
client.wait_for_server()
goal = MoveBaseGoal()
goalQueue = [ [2.922, 13.86, 0.0], [11.434, 13.567, 0.0], [19.973, 13.41, 0.0], [26.30, 13.587, 0.0], [22.932, 14.364, 0.0], [12.41, 14.306, 0.0], [5.59, 14.36, 0.0], [6.237, 17.24, 0.0], [6.244, 23.65, 0.0], [6.66, 34.54, 0.0], [5.40, 33.24, 0.0], [5.035, 26.69, 0.0], [5.28, 17.73, 0.0], [5.53, 13.68, 0.0]]
for g in goalQueue:
print("Entering goal")
print(g)
goal.target_pose.header.frame_id = '/map'
goal.target_pose.pose.position.x = g[0]
goal.target_pose.pose.position.y = g[1]
goal.target_pose.pose.position.z = g[2]
q = tf.transformations.quaternion_from_euler(0,0,0)
goal.target_pose.pose.orientation = Quaternion(*q)
client.send_goal(goal)
print("Goal sent!")
wait = client.wait_for_result(rospy.Duration(60))
print(wait)
state = client.get_state()
timer = time.time()
if (time.time() - timer >= 60):
print("Timeout")
print("Goal Completed")
if __name__ == '__main__':
main(sys.argv)
| #!/usr/bin/env python
from __future__ import print_function, division
import roslib
import sys
import rospy
import tf
import math
import time
from time import sleep
from std_msgs.msg import String
from geometry_msgs.msg import Pose, PoseArray, PoseWithCovarianceStamped, Quaternion
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal
import actionlib
from actionlib_msgs.msg import *
def main(args):
rospy.init_node('move', anonymous=True)
client = actionlib.SimpleActionClient('move_base', MoveBaseAction)
client.wait_for_server()
goal = MoveBaseGoal()
goalQueue = [ [2.922, 13.86, 0.0], [11.434, 13.567, 0.0], [19.973, 13.41, 0.0], [26.30, 13.587, 0.0], [22.932, 14.364, 0.0], [12.41, 14.306, 0.0], [5.59, 14.36, 0.0], [6.237, 17.24, 0.0], [6.244, 23.65, 0.0], [6.66, 34.54, 0.0], [5.40, 33.24, 0.0], [5.035, 26.69, 0.0], [5.28, 17.73, 0.0], [5.53, 13.68, 0.0]]
for g in goalQueue:
print("Entering goal")
print(g)
goal.target_pose.header.frame_id = '/map'
goal.target_pose.pose.position.x = g[0]
goal.target_pose.pose.position.y = g[1]
goal.target_pose.pose.position.z = g[2]
q = tf.transformations.quaternion_from_euler(0,0,0)
goal.target_pose.pose.orientation = Quaternion(*q)
client.send_goal(goal)
print("Goal sent!")
wait = client.wait_for_result(rospy.Duration(60))
print(wait)
state = client.get_state()
timer = time.time()
if (time.time() - timer >= 60):
print("Timeout")
print("Goal Completed")
if __name__ == '__main__':
main(sys.argv) | ru | 0.26433 | #!/usr/bin/env python | 2.245498 | 2 |
Sprint/acme_report.py | razzlestorm/DS-Unit-3-Sprint-1-Software-Engineering | 0 | 6614166 | <reponame>razzlestorm/DS-Unit-3-Sprint-1-Software-Engineering
from random import randint, uniform
from acme import Product
# Useful to use with random.sample to generate names
ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved']
NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???']
def generate_products(num_products=30):
"""generate a given number of products (default
30), randomly, and return them as a list"""
products = []
# For products in num_products, append a new Product.
for ii in range(num_products):
# The following conforms with PEP8 line length requirements using f-strings.
# f-strings will concat themselves (even with line breaks) if they aren't
# separated by anything.
prod_name = (
f'{ADJECTIVES[randint(0, len(ADJECTIVES)-1)]} '
f'{NOUNS[randint(0, len(NOUNS)-1)]}'
)
prod_price = randint(5, 100)
prod_weight = randint(5, 100)
prod_flammability = uniform(0.0, 2.5)
products.append(Product(prod_name, price=prod_price,
weight=prod_weight, flammability=prod_flammability))
return products
def inventory_report(products):
"""takes a list of products, and prints a "nice" summary"""
'''For the report, you should calculate and print the following values:
- Number of unique product names in the product list
- Average (mean) price, weight, and flammability of listed products'''
# Sets are used here to only get unique product keys
nameset = set()
total_price = 0
total_weight = 0
total_flammability = 0.0
for product in products:
nameset.add(product.name)
total_price += product.price
total_weight += product.weight
total_flammability += product.flammability
print("ACME CORPORATION OFFICIAL INVENTORY REPORT")
print(f"Unique product names: {len(nameset)}")
print(f"Average price: {total_price / len(products)}")
print(f"Average weight: {total_weight / len(products)}")
print(f"Averge flammability: {total_flammability / len(products)}")
if __name__ == '__main__':
inventory_report(generate_products())
| from random import randint, uniform
from acme import Product
# Useful to use with random.sample to generate names
ADJECTIVES = ['Awesome', 'Shiny', 'Impressive', 'Portable', 'Improved']
NOUNS = ['Anvil', 'Catapult', 'Disguise', 'Mousetrap', '???']
def generate_products(num_products=30):
"""generate a given number of products (default
30), randomly, and return them as a list"""
products = []
# For products in num_products, append a new Product.
for ii in range(num_products):
# The following conforms with PEP8 line length requirements using f-strings.
# f-strings will concat themselves (even with line breaks) if they aren't
# separated by anything.
prod_name = (
f'{ADJECTIVES[randint(0, len(ADJECTIVES)-1)]} '
f'{NOUNS[randint(0, len(NOUNS)-1)]}'
)
prod_price = randint(5, 100)
prod_weight = randint(5, 100)
prod_flammability = uniform(0.0, 2.5)
products.append(Product(prod_name, price=prod_price,
weight=prod_weight, flammability=prod_flammability))
return products
def inventory_report(products):
"""takes a list of products, and prints a "nice" summary"""
'''For the report, you should calculate and print the following values:
- Number of unique product names in the product list
- Average (mean) price, weight, and flammability of listed products'''
# Sets are used here to only get unique product keys
nameset = set()
total_price = 0
total_weight = 0
total_flammability = 0.0
for product in products:
nameset.add(product.name)
total_price += product.price
total_weight += product.weight
total_flammability += product.flammability
print("ACME CORPORATION OFFICIAL INVENTORY REPORT")
print(f"Unique product names: {len(nameset)}")
print(f"Average price: {total_price / len(products)}")
print(f"Average weight: {total_weight / len(products)}")
print(f"Averge flammability: {total_flammability / len(products)}")
if __name__ == '__main__':
inventory_report(generate_products()) | en | 0.901123 | # Useful to use with random.sample to generate names generate a given number of products (default 30), randomly, and return them as a list # For products in num_products, append a new Product. # The following conforms with PEP8 line length requirements using f-strings. # f-strings will concat themselves (even with line breaks) if they aren't # separated by anything. takes a list of products, and prints a "nice" summary For the report, you should calculate and print the following values: - Number of unique product names in the product list - Average (mean) price, weight, and flammability of listed products # Sets are used here to only get unique product keys | 3.851228 | 4 |
src/lib/advanced/othername.py | loicbusson/gitpractice | 0 | 6614167 | <reponame>loicbusson/gitpractice
#lalalal
#add method for for for
| #lalalal
#add method for for for | en | 0.885915 | #lalalal #add method for for for | 1.383726 | 1 |
notebook/numpy_select_assign.py | vhn0912/python-snippets | 174 | 6614168 | <reponame>vhn0912/python-snippets
import numpy as np
a_2d = np.arange(12).reshape(3, 4)
print(a_2d)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
a_2d[0, 0] = 100
print(a_2d)
# [[100 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
a_2d[0] = 100
print(a_2d)
# [[100 100 100 100]
# [ 4 5 6 7]
# [ 8 9 10 11]]
a_2d[np.ix_([False, True, True], [1, 3])] = 200
print(a_2d)
# [[100 100 100 100]
# [ 4 200 6 200]
# [ 8 200 10 200]]
a_2d = np.arange(12).reshape(3, 4)
print(a_2d)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
print(a_2d[::2, :3])
# [[ 0 1 2]
# [ 8 9 10]]
print(np.arange(6).reshape(2, 3) * 100)
# [[ 0 100 200]
# [300 400 500]]
a_2d[::2, :3] = np.arange(6).reshape(2, 3) * 100
print(a_2d)
# [[ 0 100 200 3]
# [ 4 5 6 7]
# [300 400 500 11]]
a_2d = np.arange(12).reshape(3, 4)
print(a_2d)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
print(a_2d[::2, :3])
# [[ 0 1 2]
# [ 8 9 10]]
print(np.arange(3) * 100)
# [ 0 100 200]
a_2d[::2, :3] = np.arange(3) * 100
print(a_2d)
# [[ 0 100 200 3]
# [ 4 5 6 7]
# [ 0 100 200 11]]
a_2d = np.arange(12).reshape(3, 4)
print(a_2d)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
print(a_2d[::2, :3])
# [[ 0 1 2]
# [ 8 9 10]]
print(np.arange(2) * 100)
# [ 0 100]
# a_2d[::2, :3] = np.arange(2) * 100
# ValueError: could not broadcast input array from shape (2) into shape (2,3)
| import numpy as np
a_2d = np.arange(12).reshape(3, 4)
print(a_2d)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
a_2d[0, 0] = 100
print(a_2d)
# [[100 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
a_2d[0] = 100
print(a_2d)
# [[100 100 100 100]
# [ 4 5 6 7]
# [ 8 9 10 11]]
a_2d[np.ix_([False, True, True], [1, 3])] = 200
print(a_2d)
# [[100 100 100 100]
# [ 4 200 6 200]
# [ 8 200 10 200]]
a_2d = np.arange(12).reshape(3, 4)
print(a_2d)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
print(a_2d[::2, :3])
# [[ 0 1 2]
# [ 8 9 10]]
print(np.arange(6).reshape(2, 3) * 100)
# [[ 0 100 200]
# [300 400 500]]
a_2d[::2, :3] = np.arange(6).reshape(2, 3) * 100
print(a_2d)
# [[ 0 100 200 3]
# [ 4 5 6 7]
# [300 400 500 11]]
a_2d = np.arange(12).reshape(3, 4)
print(a_2d)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
print(a_2d[::2, :3])
# [[ 0 1 2]
# [ 8 9 10]]
print(np.arange(3) * 100)
# [ 0 100 200]
a_2d[::2, :3] = np.arange(3) * 100
print(a_2d)
# [[ 0 100 200 3]
# [ 4 5 6 7]
# [ 0 100 200 11]]
a_2d = np.arange(12).reshape(3, 4)
print(a_2d)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
print(a_2d[::2, :3])
# [[ 0 1 2]
# [ 8 9 10]]
print(np.arange(2) * 100)
# [ 0 100]
# a_2d[::2, :3] = np.arange(2) * 100
# ValueError: could not broadcast input array from shape (2) into shape (2,3) | en | 0.278205 | # [[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11]] # [[100 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11]] # [[100 100 100 100] # [ 4 5 6 7] # [ 8 9 10 11]] # [[100 100 100 100] # [ 4 200 6 200] # [ 8 200 10 200]] # [[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11]] # [[ 0 1 2] # [ 8 9 10]] # [[ 0 100 200] # [300 400 500]] # [[ 0 100 200 3] # [ 4 5 6 7] # [300 400 500 11]] # [[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11]] # [[ 0 1 2] # [ 8 9 10]] # [ 0 100 200] # [[ 0 100 200 3] # [ 4 5 6 7] # [ 0 100 200 11]] # [[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11]] # [[ 0 1 2] # [ 8 9 10]] # [ 0 100] # a_2d[::2, :3] = np.arange(2) * 100 # ValueError: could not broadcast input array from shape (2) into shape (2,3) | 3.366314 | 3 |
django_gotolong/bstmtdiv/admin.py | ParikhKadam/gotolong | 15 | 6614169 | <gh_stars>10-100
from django.contrib import admin
# Register your models here.
from .models import BstmtDiv
# ...
admin.site.register(BstmtDiv)
| from django.contrib import admin
# Register your models here.
from .models import BstmtDiv
# ...
admin.site.register(BstmtDiv) | en | 0.924973 | # Register your models here. # ... | 1.270606 | 1 |
algostep2.py | swingcake/hashcode19 | 1 | 6614170 | import os
from file_reader import read_file
from file_writer import write_output
from problem_solver import ProblemSolver
from Slide import Slide
# Input
files = ['a_example.txt', 'b_loveley_landscapes.txt', 'c_memorable_moments.txt', 'd_pet_pictures.txt', 'e_shiny_selfies.txt']
# End Input
example_file = os.path.join('data', files[0])
example = read_file(example_file)
print(example)
' will change to slide from their function'
photos = example['rows']
slides = [] # they will pass this
for photo in photos:
if photo['orientation'] == 'H':
# print(photo['tags'])
slides.append(Slide(photo))
''''''
| import os
from file_reader import read_file
from file_writer import write_output
from problem_solver import ProblemSolver
from Slide import Slide
# Input
files = ['a_example.txt', 'b_loveley_landscapes.txt', 'c_memorable_moments.txt', 'd_pet_pictures.txt', 'e_shiny_selfies.txt']
# End Input
example_file = os.path.join('data', files[0])
example = read_file(example_file)
print(example)
' will change to slide from their function'
photos = example['rows']
slides = [] # they will pass this
for photo in photos:
if photo['orientation'] == 'H':
# print(photo['tags'])
slides.append(Slide(photo))
''''''
| en | 0.602576 | # Input # End Input # they will pass this # print(photo['tags']) | 3.287413 | 3 |
Conn to database/source_insert.py | xgxofdream/Notebook_by_Tag | 0 | 6614171 | <reponame>xgxofdream/Notebook_by_Tag
# -*- coding: utf-8 -*-
"""
mySql database connection
Created on Sat Jan 29 22:13:06 2022
@Author: <NAME>, <EMAIL>
"""
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost', user='root', passwd='<PASSWORD>', db='myenglish', port=3306, charset='utf8')
# 生成游标对象
cursor = db.cursor()
# 书的页码
start_page = 1
end_page = 319
chap = ""
# 数据库操作
try:
while start_page <= end_page:
page = 'Page S-'+str(start_page)
start_page = start_page + 1
# sql语句
sql = "INSERT INTO `myenglish`.`english_reference` (" \
"`english_text_location`, `note`, `source_id`" \
") VALUES ('" + page +"', '" + chap +"', '15')"
print (sql)
cursor.execute(sql)
db.commit()
except Exception as e:
print("失败:", e)
# 发生错误时,回滚
db.rollback()
# 关闭游标
cursor.close()
# 关闭连接
db.close | # -*- coding: utf-8 -*-
"""
mySql database connection
Created on Sat Jan 29 22:13:06 2022
@Author: <NAME>, <EMAIL>
"""
import pymysql
# 连接数据库
db = pymysql.connect(host='localhost', user='root', passwd='<PASSWORD>', db='myenglish', port=3306, charset='utf8')
# 生成游标对象
cursor = db.cursor()
# 书的页码
start_page = 1
end_page = 319
chap = ""
# 数据库操作
try:
while start_page <= end_page:
page = 'Page S-'+str(start_page)
start_page = start_page + 1
# sql语句
sql = "INSERT INTO `myenglish`.`english_reference` (" \
"`english_text_location`, `note`, `source_id`" \
") VALUES ('" + page +"', '" + chap +"', '15')"
print (sql)
cursor.execute(sql)
db.commit()
except Exception as e:
print("失败:", e)
# 发生错误时,回滚
db.rollback()
# 关闭游标
cursor.close()
# 关闭连接
db.close | zh | 0.533092 | # -*- coding: utf-8 -*- mySql database connection Created on Sat Jan 29 22:13:06 2022 @Author: <NAME>, <EMAIL> # 连接数据库 # 生成游标对象 # 书的页码 # 数据库操作 # sql语句 # 发生错误时,回滚 # 关闭游标 # 关闭连接 | 3.327285 | 3 |
__init__.py | xiaosean/Efficient-Facial-Feature-Learning-with-Wide-Ensemble-based-Convolutional-Neural-Networks | 0 | 6614172 | <gh_stars>0
from .emotion_model import EmotionRecognition
| from .emotion_model import EmotionRecognition | none | 1 | 1.07732 | 1 | |
src/genie/libs/parser/iosxe/tests/ShowIpDhcpSnoopingBinding/cli/equal/golden_output_expected.py | balmasea/genieparser | 204 | 6614173 | <filename>src/genie/libs/parser/iosxe/tests/ShowIpDhcpSnoopingBinding/cli/equal/golden_output_expected.py
expected_output = {
"interfaces": {
"FiftyGigE6/0/25": {
"vlan": {
"100": {
"mac": "00:11:01:00:00:01",
"ip": "192.168.3.11",
"lease": 1128,
"type": "dhcp-snooping"
}
}
}
}
}
| <filename>src/genie/libs/parser/iosxe/tests/ShowIpDhcpSnoopingBinding/cli/equal/golden_output_expected.py
expected_output = {
"interfaces": {
"FiftyGigE6/0/25": {
"vlan": {
"100": {
"mac": "00:11:01:00:00:01",
"ip": "192.168.3.11",
"lease": 1128,
"type": "dhcp-snooping"
}
}
}
}
}
| none | 1 | 1.415804 | 1 | |
src/cutty/repositories/adapters/providers/__init__.py | cjolowicz/cutty | 1 | 6614174 | """Providers."""
| """Providers."""
| en | 0.907591 | Providers. | 1.196749 | 1 |
gibson2/examples/demo/tiago_dual_ik.py | dnandha/iGibson | 3 | 6614175 | <gh_stars>1-10
from gibson2.robots.tiago_dual_robot import Tiago_Dual
from gibson2.simulator import Simulator
from gibson2.scenes.empty_scene import EmptyScene
from gibson2.utils.utils import parse_config
from gibson2.render.profiler import Profiler
import pybullet as p
from gibson2.external.pybullet_tools.utils import set_joint_positions, joints_from_names, get_joint_positions, \
get_max_limits, get_min_limits, get_sample_fn, get_movable_joints
import numpy as np
import gibson2
import os
def main():
config = parse_config(os.path.join(gibson2.example_config_path, 'tiago_dual_point_nav.yaml'))
s = Simulator(mode='gui', physics_timestep=1 / 240.0)
scene = EmptyScene()
s.import_scene(scene)
tiago = Tiago_Dual(config)
s.import_robot(tiago)
robot_id = tiago.robot_ids[0]
arm_joints = joints_from_names(robot_id, ['arm_left_1_joint',
'arm_left_2_joint',
'arm_left_3_joint',
'arm_left_4_joint',
'arm_left_5_joint',
'arm_left_6_joint',
'arm_left_7_joint'])
gripper_joints = joints_from_names(robot_id, [
'gripper_left_right_finger_joint',
'gripper_left_left_finger_joint'])
tiago.robot_body.reset_position([0, 0, 0])
tiago.robot_body.reset_orientation([0, 0, 1, 0])
x, y, z = tiago.get_end_effector_position()
visual_marker = p.createVisualShape(p.GEOM_SPHERE, radius=0.02)
marker = p.createMultiBody(baseVisualShapeIndex=visual_marker)
all_joints = get_movable_joints(robot_id)
max_limits = get_max_limits(robot_id, all_joints)
min_limits = get_min_limits(robot_id, all_joints)
rest_position = get_joint_positions(robot_id, all_joints)
joint_range = list(np.array(max_limits) - np.array(min_limits))
jd = [0.1 for item in joint_range]
valid_joints = [j.joint_index for j in tiago.ordered_joints]
joint_mask = []
for j in all_joints:
if j in valid_joints:
joint_mask += [True]
else:
joint_mask += [False]
def accurateCalculateInverseKinematics(robotid, endEffectorId, targetPos, threshold, maxIter):
#sample_fn = get_sample_fn(robotid, arm_joints)
#set_joint_positions(robotid, arm_joints, sample_fn())
it = 0
while it < maxIter:
jointPoses = p.calculateInverseKinematics(
robotid,
endEffectorId,
targetPos,
lowerLimits=min_limits,
upperLimits=max_limits,
jointRanges=joint_range,
restPoses=rest_position,
jointDamping=jd)
jointPoses = np.asarray(jointPoses)
set_joint_positions(robotid, valid_joints, jointPoses[joint_mask])
ls = p.getLinkState(robotid, endEffectorId)
newPos = ls[4]
dist = np.linalg.norm(np.array(targetPos) - np.array(newPos))
if dist < threshold:
break
it += 1
print("Num iter: " + str(it) + ", residual: " + str(dist))
return jointPoses
while True:
with Profiler("Simulation step"):
tiago.robot_body.reset_position([0, 0, 0])
tiago.robot_body.reset_orientation([0, 0, 1, 0])
threshold = 0.01
maxIter = 100
joint_pos = accurateCalculateInverseKinematics(
robot_id,
tiago.end_effector_part_index(),
#tiago.parts['gripper_link'].body_part_index,
[x, y, z],
threshold,
maxIter)[2:10]
s.step()
keys = p.getKeyboardEvents()
for k, v in keys.items():
if (k == p.B3G_RIGHT_ARROW and (v & p.KEY_IS_DOWN)):
x += 0.01
if (k == p.B3G_LEFT_ARROW and (v & p.KEY_IS_DOWN)):
x -= 0.01
if (k == p.B3G_UP_ARROW and (v & p.KEY_IS_DOWN)):
y += 0.01
if (k == p.B3G_DOWN_ARROW and (v & p.KEY_IS_DOWN)):
y -= 0.01
if (k == ord('z') and (v & p.KEY_IS_DOWN)):
z += 0.01
if (k == ord('x') and (v & p.KEY_IS_DOWN)):
z -= 0.01
p.resetBasePositionAndOrientation(marker, [x, y, z], [0, 0, 0, 1])
s.disconnect()
if __name__ == '__main__':
main()
| from gibson2.robots.tiago_dual_robot import Tiago_Dual
from gibson2.simulator import Simulator
from gibson2.scenes.empty_scene import EmptyScene
from gibson2.utils.utils import parse_config
from gibson2.render.profiler import Profiler
import pybullet as p
from gibson2.external.pybullet_tools.utils import set_joint_positions, joints_from_names, get_joint_positions, \
get_max_limits, get_min_limits, get_sample_fn, get_movable_joints
import numpy as np
import gibson2
import os
def main():
config = parse_config(os.path.join(gibson2.example_config_path, 'tiago_dual_point_nav.yaml'))
s = Simulator(mode='gui', physics_timestep=1 / 240.0)
scene = EmptyScene()
s.import_scene(scene)
tiago = Tiago_Dual(config)
s.import_robot(tiago)
robot_id = tiago.robot_ids[0]
arm_joints = joints_from_names(robot_id, ['arm_left_1_joint',
'arm_left_2_joint',
'arm_left_3_joint',
'arm_left_4_joint',
'arm_left_5_joint',
'arm_left_6_joint',
'arm_left_7_joint'])
gripper_joints = joints_from_names(robot_id, [
'gripper_left_right_finger_joint',
'gripper_left_left_finger_joint'])
tiago.robot_body.reset_position([0, 0, 0])
tiago.robot_body.reset_orientation([0, 0, 1, 0])
x, y, z = tiago.get_end_effector_position()
visual_marker = p.createVisualShape(p.GEOM_SPHERE, radius=0.02)
marker = p.createMultiBody(baseVisualShapeIndex=visual_marker)
all_joints = get_movable_joints(robot_id)
max_limits = get_max_limits(robot_id, all_joints)
min_limits = get_min_limits(robot_id, all_joints)
rest_position = get_joint_positions(robot_id, all_joints)
joint_range = list(np.array(max_limits) - np.array(min_limits))
jd = [0.1 for item in joint_range]
valid_joints = [j.joint_index for j in tiago.ordered_joints]
joint_mask = []
for j in all_joints:
if j in valid_joints:
joint_mask += [True]
else:
joint_mask += [False]
def accurateCalculateInverseKinematics(robotid, endEffectorId, targetPos, threshold, maxIter):
#sample_fn = get_sample_fn(robotid, arm_joints)
#set_joint_positions(robotid, arm_joints, sample_fn())
it = 0
while it < maxIter:
jointPoses = p.calculateInverseKinematics(
robotid,
endEffectorId,
targetPos,
lowerLimits=min_limits,
upperLimits=max_limits,
jointRanges=joint_range,
restPoses=rest_position,
jointDamping=jd)
jointPoses = np.asarray(jointPoses)
set_joint_positions(robotid, valid_joints, jointPoses[joint_mask])
ls = p.getLinkState(robotid, endEffectorId)
newPos = ls[4]
dist = np.linalg.norm(np.array(targetPos) - np.array(newPos))
if dist < threshold:
break
it += 1
print("Num iter: " + str(it) + ", residual: " + str(dist))
return jointPoses
while True:
with Profiler("Simulation step"):
tiago.robot_body.reset_position([0, 0, 0])
tiago.robot_body.reset_orientation([0, 0, 1, 0])
threshold = 0.01
maxIter = 100
joint_pos = accurateCalculateInverseKinematics(
robot_id,
tiago.end_effector_part_index(),
#tiago.parts['gripper_link'].body_part_index,
[x, y, z],
threshold,
maxIter)[2:10]
s.step()
keys = p.getKeyboardEvents()
for k, v in keys.items():
if (k == p.B3G_RIGHT_ARROW and (v & p.KEY_IS_DOWN)):
x += 0.01
if (k == p.B3G_LEFT_ARROW and (v & p.KEY_IS_DOWN)):
x -= 0.01
if (k == p.B3G_UP_ARROW and (v & p.KEY_IS_DOWN)):
y += 0.01
if (k == p.B3G_DOWN_ARROW and (v & p.KEY_IS_DOWN)):
y -= 0.01
if (k == ord('z') and (v & p.KEY_IS_DOWN)):
z += 0.01
if (k == ord('x') and (v & p.KEY_IS_DOWN)):
z -= 0.01
p.resetBasePositionAndOrientation(marker, [x, y, z], [0, 0, 0, 1])
s.disconnect()
if __name__ == '__main__':
main() | en | 0.463279 | #sample_fn = get_sample_fn(robotid, arm_joints) #set_joint_positions(robotid, arm_joints, sample_fn()) #tiago.parts['gripper_link'].body_part_index, | 2.008764 | 2 |
backend/users/migrations/0001_initial.py | tchestnut85/notefy | 19 | 6614176 | # Generated by Django 3.2.6 on 2021-10-07 22:14
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('email', models.EmailField(max_length=255, unique=True, verbose_name='email address')),
('name', models.CharField(max_length=20, verbose_name='Name')),
('email_verified_hash', models.CharField(default='000000', max_length=32, verbose_name='Verify Token')),
('is_staff', models.BooleanField(default=False, null=True)),
('is_admin', models.BooleanField(default=False, null=True)),
('is_active', models.BooleanField(default=True, null=True)),
('is_superuser', models.BooleanField(default=False, null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('avatar', models.CharField(default='https://assets.servatom.com/notefy/avatars/parrot.png', max_length=400, verbose_name='avatar')),
],
options={
'abstract': False,
},
),
]
| # Generated by Django 3.2.6 on 2021-10-07 22:14
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)),
('email', models.EmailField(max_length=255, unique=True, verbose_name='email address')),
('name', models.CharField(max_length=20, verbose_name='Name')),
('email_verified_hash', models.CharField(default='000000', max_length=32, verbose_name='Verify Token')),
('is_staff', models.BooleanField(default=False, null=True)),
('is_admin', models.BooleanField(default=False, null=True)),
('is_active', models.BooleanField(default=True, null=True)),
('is_superuser', models.BooleanField(default=False, null=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('avatar', models.CharField(default='https://assets.servatom.com/notefy/avatars/parrot.png', max_length=400, verbose_name='avatar')),
],
options={
'abstract': False,
},
),
]
| en | 0.930816 | # Generated by Django 3.2.6 on 2021-10-07 22:14 | 1.897739 | 2 |
Python/civ.py | ben9583/civilization-simulator | 3 | 6614177 | <filename>Python/civ.py<gh_stars>1-10
"""
MIT License
Copyright (c) 2020 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import os
import sys
import pygame
import pygame.gfxdraw
import math
import noise
import random
from datetime import datetime
random.seed(datetime.now())
rand_val = random.randint(0, 100000)
SQRT_3 = 1.732
WINDOW_BOUND = [1366, 700]
GAME_BOUND = [round(WINDOW_BOUND[0]*1/64), round(WINDOW_BOUND[1]*1/64), round(WINDOW_BOUND[0]*31/32), round(WINDOW_BOUND[1]*31/32)]
HEX_WIDTH = 12 #12
DIMENSIONS = [64, 32] #64, 32
CONTINENT_ROUGHNESS = 0.9 #0.9
OCEAN_WORLD = 5
INITIAL_EMPIRES = 16 #16
PEACE_DURATION = 15
ECONOMIC_ADVANTAGE = 2
ENABLE_MULTITHREADING = True
NUM_CORES = 1
if ENABLE_MULTITHREADING:
if sys.platform.startswith('linux'):
stream = os.popen('grep -c ^processor /proc/cpuinfo')
elif sys.platform.startswith('win'):
stream = os.popen('echo %NUMBER_OF_PROCESSORS%')
elif sys.platform.startswith('cygwin'):
stream = os.popen('echo %NUMBER_OF_PROCESSORS%')
elif sys.platform.startswith('msys'):
stream = os.popen('echo %NUMBER_OF_PROCESSORS%')
elif sys.platform.startswith('darwin'):
stream = os.popen('sysctl -n hw.ncpu')
output = stream.read()
NUM_CORES = int(output[:len(output) - 1])
global emp_count, game_tick
noise_vals = []
emp_arr = []
hex_arr = []
emp_count = 1
game_tick = 1
class Empire:
def __init__(self, name, capital, color, economy=100):
global emp_count
self.name = name
self.capital = capital
self.color = verify_color(color)
self.expanding = True
self.economy = economy
self.stability = 1.0
self.war_targets = []
self.peace_deals = []
self.border_emps = []
self.border_count = 0
self.age = 0
emp_count += 1
annex_tile(self, capital)
#self.capital.set_color((0, 0, 0))
self.capital.make_capital()
emp_arr.append(self)
recalc_border_emps(self)
for border_emp in self.border_emps:
recalc_border_emps(border_emp)
class Hex:
def __init__(self, win, x, y):
self.win = win
self.x = x
self.y = y
self.empire = None
self.occupier = None
self.new_empire = None
self.new_occupier = None
self.change_color = False
self.color = (255, 255, 255)
draw_hex_at_coord(self.win, self.x, self.y, self.color)
def set_color(self, color):
self.color = color
draw_hex_at_coord(self.win, self.x, self.y, self.color)
def make_capital(self):
pygame.draw.circle(self.win, (0, 0, 0), (GAME_BOUND[0] + self.x * math.floor(1.5 * HEX_WIDTH), GAME_BOUND[1] + self.y * math.floor(SQRT_3 * HEX_WIDTH) + (self.x % 2) * math.floor(SQRT_3/2 * HEX_WIDTH)), math.ceil(HEX_WIDTH * 0.5))
class DiploObject:
def __init__(self, target, kind, rebel=None, special=0, aggressor=None):
self.target = target
self.type = kind # 0 is a war declartion, 1 is a peace deal
self.tick = game_tick
self.rebel = rebel
self.special = special # 0 is not special, 1 is retribution conflict
self.aggressor = aggressor
def draw_hex(screen, color, x, y, sWidth=10, width=0):
factor_1 = math.floor(SQRT_3 * sWidth / 2)
factor_2 = math.floor(sWidth * 0.5)
pygame.draw.polygon(screen, color, [[x - sWidth, y], [x - factor_2, y - factor_1], [x + factor_2, y - factor_1], [x + sWidth, y], [x + factor_2, y + factor_1], [x - factor_2, y + factor_1]], width)
def draw_hex_at_coord(screen, x, y, color=(255, 255, 255)):
factor_1 = math.floor(1.5 * HEX_WIDTH)
factor_2 = math.floor(SQRT_3 * HEX_WIDTH)
factor_3 = math.floor(SQRT_3/2 * HEX_WIDTH)
draw_hex(screen, color, GAME_BOUND[0] + x * factor_1, GAME_BOUND[1] + y * factor_2 + (x % 2) * factor_3, HEX_WIDTH)
draw_hex(screen, (0, 0, 0), GAME_BOUND[0] + x * factor_1, GAME_BOUND[1] + y * factor_2 + (x % 2) * factor_3, HEX_WIDTH, 1)
def get_key_from_value(tab, value):
i = 0
for val in tab:
if val == value:
return i
i += 1
return -1
def index_at_greatest(tab):
val = -math.inf
index = -1
for i in range(len(tab)):
if tab[i] > val:
val = tab[i]
index = i
return i
def concat_table(tab1, tab2):
tab3 = []
for i in tab1:
tab3.append(i)
for i in tab2:
tab3.append(i)
return tab3
def cpft(a, b, c):
for v in a:
if v[0] == b and v[1] == c:
return True
return False
def verify_color(color, level=0):
if level > 100:
return color
for emp in emp_arr:
diff = ((emp.color[0] - color[0]) ** 2) + ((emp.color[1] - color[1]) ** 2) + ((emp.color[2] - color[2]) ** 2)
if diff < 500:
return verify_color((random.randint(15, 85), random.randint(15, 85), random.randint(15, 85)), level + 1)
return color
def tiles_connected(tile1, tile2, l=None, i=None):
if l == None:
if (tile2.empire != tile2.empire) or (tile1.empire is None or tile2.empire is None):
return False
l = [[tile2.x, tile2.y, 0]]
if i == None:
i = 0
for v in get_surroundings(tile2):
if v == tile1:
return True
coords = [v.x, v.y]
orig = hex_exists(l[0][0], l[0][1])
if not(cpft(l, coords[0], coords[1])) and (is_in_control(tile1.empire, v) or is_in_control(orig.empire, v)):
l.append([coords[0], coords[1], i])
if len(l) <= i:
return False
return tiles_connected(tile1, hex_exists(l[i][0], l[i][1]), l, i + 1)
def hex_exists(x, y):
for hexagon in hex_arr:
if hexagon.x == x and hexagon.y == y:
return hexagon
return None
def get_surroundings(tile):
out = []
out.append(hex_exists(tile.x, tile.y + 1))
out.append(hex_exists(tile.x, tile.y - 1))
out.append(hex_exists(tile.x + 1, tile.y))
out.append(hex_exists(tile.x - 1, tile.y))
if tile.x % 2 == 1:
out.append(hex_exists(tile.x - 1, tile.y + 1))
out.append(hex_exists(tile.x + 1, tile.y + 1))
else:
out.append(hex_exists(tile.x + 1, tile.y - 1))
out.append(hex_exists(tile.x - 1, tile.y - 1))
for i in range(len(out) - 1, -1, -1):
if out[i] is None:
out.pop(i)
return out
def get_cluster(tile, max_size=0, l=None, orig_tile=None):
if orig_tile is None:
orig_tile = tile
if l is None:
l = [tile]
if max_size != 0 and len(l) > max_size:
return l
for v in get_surroundings(tile):
if is_same_tile_type(orig_tile, v) and get_key_from_value(l, v) == -1:
l.append(v)
l = get_cluster(v, max_size, l, orig_tile)
return l
def distance_from_tiles(t0, t1):
return math.sqrt((t0.x - t1.x) ** 2 + (t0.y - t1.y) ** 2)
def is_in_control(emp, tile):
return (tile.empire == emp and tile.occupier is None) or tile.occupier == emp
def is_same_tile_type(tile1, tile2):
if not(tile1.occupier is None):
if not(tile2.occupier is None):
return tile1.empire == tile2.empire and tile1.occupier == tile2.occupier
else:
return is_in_control(tile1.occupier, tile2)
elif tile1.occupier is None:
if not(tile2.occupier is None):
return is_in_control(tile2.occupier, tile1)
else:
return tile1.empire == tile2.empire
def recalc_border_emps(emp):
emp.border_emps = []
emp.border_count = 0
for hexagon in get_empire_tiles(emp):
surroundings = get_surroundings(hexagon)
for surr_hex in surroundings:
if not (surr_hex.empire is None) and not (surr_hex.empire.name == emp.name) and get_key_from_value(emp.border_emps, surr_hex.empire) == -1:
emp.border_emps.append(surr_hex.empire)
emp.border_count += 1
if get_key_from_value(surr_hex.empire.border_emps, emp) == -1:
surr_hex.empire.border_emps.append(emp)
elif surr_hex.empire is None and surr_hex.occupier is None:
emp.expanding = True
def fragment_empire(emp, conqueror):
print("The capital of %s has been captured and %s will liberate its occupations!" % (emp.name, conqueror.name))
tiles = get_empire_tiles(emp)
for hexagon in tiles:
unoccupy_tile(hexagon)
while len(tiles) > 0:
rand_loc = random.randint(0, len(tiles) - 1)
rand_hex = tiles[rand_loc]
tiles.pop(rand_loc)
new_empires = []
rand_hexes = get_surroundings(rand_hex)
for rand in rand_hexes:
if get_key_from_value(tiles, rand) != -1:
if len(rand_hexes) < 30:
rand_hexes_rand_hexes = get_surroundings(rand)
for rand_rand in reversed(rand_hexes_rand_hexes):
if random.randint(0, 1) == 0 and len(rand_hexes) < 30 and get_key_from_value(tiles, rand_rand) != -1 and get_key_from_value(rand_hexes, rand_rand) == -1:
rand_hexes.append(rand_rand)
tiles.pop(get_key_from_value(tiles, rand_rand))
tiles.pop(get_key_from_value(tiles, rand))
elif get_key_from_value(rand_hexes, rand) == -1:
rand_hexes.pop(get_key_from_value(rand_hexes, rand))
if len(rand_hexes) > 9 or len(get_empire_tiles(emp)) < 10:
new_empire = Empire("Empire %d" % (emp_count), rand_hex, (random.randint(15, 85), random.randint(15, 85), random.randint(15, 85)))
new_empires.append(new_empire)
for rand in rand_hexes:
annex_tile(new_empire, rand)
dissolve_empire(emp)
recalc_border_emps(conqueror)
for empire in emp.border_emps:
recalc_border_emps(empire)
for empire in new_empires:
empire.economy = math.floor((emp.economy / len(new_empires)) * 0.8)
peace1 = DiploObject(empire, 1)
peace2 = DiploObject(conqueror, 1)
conqueror.peace_deals.append(peace1)
emp.peace_deals.append(peace2)
recalc_border_emps(empire)
#print(emp.name)
#emp_arr.pop(get_key_from_value(emp_arr, emp))
def partition_empire(emp, conqueror):
print("The capital of %s has been captured by %s and will be partitioned!" % (emp.name, conqueror.name))
main_land = get_cluster(emp.capital)
for hexagon in main_land:
annex_tile(conqueror, hexagon)
for hexagon in shuffle_table(hex_arr):
if hexagon.empire == emp:
if hexagon.occupier is None:
tiles = get_cluster(hexagon)
new_emp = Empire("Empire %d" % (emp_count), hexagon, (random.randint(15, 85), random.randint(15, 85), random.randint(15, 85)))
for tile in tiles:
if tile != new_emp.capital:
annex_tile(new_emp, tile)
else:
annex_tile(hexagon.occupier, hexagon)
elif hexagon.occupier == emp:
unoccupy_tile(hexagon)
for emp_i in emp_arr:
for i in reversed(range(len(emp_i.war_targets))):
if emp_i.war_targets[i].target == emp:
emp_i.war_targets.pop(i)
rebel = False
for war in emp.war_targets:
if not(war.rebel is None) and war.rebel == True:
war.target.stability += 5
rebel = True
if rebel:
emp.stability *= 3
else:
conqueror.economy = round(conqueror.economy * 0.8)
recalc_border_emps(conqueror)
for empire in emp.border_emps:
recalc_border_emps(empire)
emp_arr.pop(get_key_from_value(emp_arr, emp))
def annex_tile(emp, tile):
tile.empire = emp
tile.new_empire = emp
tile.occupier = None
tile.new_occupier = None
tile.change_color = True
tile.set_color((emp.color[0] + 140, emp.color[1] + 140, emp.color[2] + 140))
def delayed_annex_tile(emp, tile):
tile.new_empire = emp
tile.new_occupier = None
tile.set_color(emp.color)
def unoccupy_tile(tile):
tile.occupier = None
tile.new_occupier = None
tile.change_color = True
tile.set_color((tile.empire.color[0] + 140, tile.empire.color[1] + 140, tile.empire.color[2] + 140))
def delayed_unoccupy_tile(tile):
tile.new_occupier = None
tile.set_color(tile.empire.color)
def is_delayed(tile):
return tile.new_occupier != tile.occupier or tile.new_empire != tile.empire
def correct_delayed():
for hexagon in hex_arr:
if is_delayed(hexagon):
hexagon.occupier = hexagon.new_occupier
hexagon.empire = hexagon.new_empire
def occupy_tile(emp, tile, causus):
if tile.empire.capital == tile:
if not (causus is None) and ((causus.special == 1 and causus.aggressor != emp) or (not (causus.rebel is None)) and random.randint(0, 1) == 0):
fragment_empire(tile.empire, emp)
#print("woah")
else:
partition_empire(tile.empire, emp)
emp.economy -= 500
if emp.economy < 0:
emp.economy = 0
return True
else:
tile.occupier = emp
tile.new_occupier = emp
tile.change_color = True
tile.set_color((emp.color[0] + 140, emp.color[1] + 140, emp.color[2] + 140))
emp.economy -= 10
tile.empire.economy -= 10
if emp.economy < 0:
emp.economy = 0
if tile.empire.economy < 0:
tile.empire.economy = 0
return False
def declare_war(initiator, target, special=0, aggressor=None):
init_war_dec = DiploObject(target, 0, None, special, aggressor)
initiator.war_targets.append(init_war_dec)
target_war_dec = DiploObject(initiator, 0, None, special, aggressor)
target.war_targets.append(target_war_dec)
def rebel(emp, tile):
rebel_emp = Empire("Empire %d" % (emp_count), tile, (random.randint(15, 85), random.randint(15, 85), random.randint(15, 85)), round(emp.economy * 0.6))
for surr_hex in get_surroundings(tile):
if surr_hex.color[0] != 0 or surr_hex.color[1] != 0 or surr_hex.color[2] != 0:
annex_tile(rebel_emp, surr_hex)
war1 = DiploObject(emp, 0, True)
war2 = DiploObject(rebel_emp, 0, False)
emp.economy = emp.economy * 0.6
rebel_emp.economy = emp.economy * 0.2
emp.war_targets.append(war2)
rebel_emp.war_targets.append(war1)
def make_peace(emp1, emp2):
c1 = get_cluster(emp1.capital)
for hexagon in c1:
if hexagon.occupier == emp1 and hexagon != emp1.capital:
delayed_annex_tile(emp1, hexagon)
c2 = get_cluster(emp2.capital)
for hexagon in c2:
if hexagon.occupier == emp2 and hexagon != emp2.capital:
delayed_annex_tile(emp2, hexagon)
for hexagon in hex_arr:
if hexagon.empire == emp1 and hexagon.occupier == emp2 and not is_delayed(hexagon):
c3 = get_cluster(hexagon)
for tile in c3:
delayed_unoccupy_tile(tile)
elif hexagon.empire == emp2 and hexagon.occupier == emp1 and not is_delayed(hexagon):
c3 = get_cluster(hexagon)
for tile in c3:
delayed_unoccupy_tile(tile)
elif hexagon.empire == emp1 and hexagon.occupier is None and get_key_from_value(c1, hexagon) == -1 and not is_delayed(hexagon):
c3 = get_cluster(hexagon)
if len(c3) > 10 and not tiles_connected(hexagon, emp1.capital):
new_emp = Empire("Empire %d" % (emp_count), hexagon, (random.randint(15, 85), random.randint(15, 85), random.randint(15, 85)))
for tile in c3:
if tile != new_emp.capital:
delayed_annex_tile(new_emp, tile)
for surr_hex in get_surroundings(hexagon):
if surr_hex.color[0] != 0:
delayed_annex_tile(new_emp, surr_hex)
else:
for tile in c3:
if tile.color[0] == 0:
print("There's been a screw up; Hex info: (%d, %d) E: (%s) O: (%s) P:(%s, %s) (1)" % (hexagon.x, hexagon.y, hexagon.empire.name, hexagon.occupier, emp1.name, emp2.name))
elif tile.occupier is None and tile.empire == emp1:
delayed_annex_tile(emp2, tile)
elif hexagon.empire == emp2 and hexagon.occupier is None and get_key_from_value(c2, hexagon) == -1 and not is_delayed(hexagon):
c3 = get_cluster(hexagon)
if len(c3) > 10 and not tiles_connected(hexagon, emp2.capital):
new_emp = Empire("Empire %d" % (emp_count), hexagon, (random.randint(15, 85), random.randint(15, 85), random.randint(15, 85)))
for tile in c3:
if tile != new_emp.capital:
delayed_annex_tile(new_emp, tile)
for surr_hex in get_surroundings(hexagon):
if surr_hex.color[0] != 0:
delayed_annex_tile(new_emp, surr_hex)
else:
for tile in c3:
if tile.color[0] == 0:
print("There's been a screw up; Hex info: (%d, %d) E: (%s) O: (%s) P:(%s, %s) (2)" % (hexagon.x, hexagon.y, hexagon.empire.name, hexagon.occupier, emp1.name, emp2.name))
elif tile.occupier is None and tile.empire == emp2:
delayed_annex_tile(emp1, tile)
correct_delayed()
checked_emps = [emp1, emp2]
recalc_border_emps(emp1)
for empire in emp1.border_emps:
recalc_border_emps(empire)
checked_emps.append(empire)
recalc_border_emps(emp2)
for empire in emp2.border_emps:
if get_key_from_value(checked_emps, empire) != -1:
recalc_border_emps(empire)
checked_emps.append(empire)
for i in reversed(range(len(emp1.war_targets))):
if emp1.war_targets[i].target == emp2:
emp1.war_targets.pop(i)
for i in reversed(range(len(emp2.war_targets))):
if emp2.war_targets[i].target == emp1:
emp2.war_targets.pop(i)
peace1 = DiploObject(emp2, 1)
peace2 = DiploObject(emp1, 1)
emp1.peace_deals.append(peace1)
emp2.peace_deals.append(peace2)
def dissolve_empire(emp):
for i in reversed(range(len(emp.war_targets))):
for j in reversed(range(len(emp.war_targets[i].target.war_targets))):
if emp.war_targets[i].target.war_targets[j].target == emp:
emp.war_targets[i].target.war_targets.pop(j)
emp.war_targets.pop(i)
for hexagon in hex_arr:
if hexagon.empire == emp and hexagon.occupier is None:
hexagon.empire = None
hexagon.new_empire = None
hexagon.occupier = None
hexagon.new_occupier = None
hexagon.set_color((255, 255, 255))
elif hexagon.empire == emp:
annex_tile(hexagon.occupier, hexagon)
elif hexagon.occupier == emp:
unoccupy_tile(hexagon)
for empire in emp_arr:
for i in reversed(range(len(empire.border_emps))):
try:
if empire.border_emps[i] == emp:
empire.border_emps.pop(i)
recalc_border_emps(empire)
except:
print(empire.name)
print(len(empire.border_emps))
print(i)
for border_emp in empire.border_emps:
print(border_emp)
print(i)
Exception("rip")
index = get_key_from_value(emp_arr, emp)
emp_arr.pop(get_key_from_value(emp_arr, emp))
def sea_invasion(emp, target):
target_tiles = shuffle_table(get_empire_tiles(target))
#print("[s] 1")
invasions = random.randint(1, 3)
invaded = False
for hexagon in target_tiles:
surroundings = get_surroundings(hexagon)
#print("[s] 1.5 (%d, %f)" % (len(get_surroundings(hexagon)), distance_from_tiles(hexagon, target.capital)))
if hexagon.occupier is None and hexagon.empire == target and len(get_surroundings(hexagon)) < 6 and distance_from_tiles(hexagon, target.capital) > 3:
#print("[s] 2")
occupy_tile(emp, hexagon, None)
for surr_hex in surroundings:
if surr_hex.color[0] != 0 and not (surr_hex.empire is None):
occupy_tile(emp, surr_hex, None)
invasions -= 1
invaded = True
if invasions == 0:
break
#print("[s] 3")
if invaded:
#print("[s] 4")
declare_war(emp, target)
def shuffle_table(tab):
out = []
for i in range(len(tab)):
j = random.randint(i, len(tab) - 1)
temp = tab[i]
tab[i] = tab[j]
tab[j] = temp
out.append(tab[i])
return out
def get_empire_tiles(emp):
out = []
for hexagon in hex_arr:
if hexagon.empire == emp:
out.append(hexagon)
return out
def get_controlled_tiles(emp):
out = []
for hexagon in hex_arr:
if is_in_control(emp, hexagon):
out.append(hexagon)
return out
def for_each_empire(emp):
tiles = get_empire_tiles(emp)
#print(emp.economy)
#border_emps = []
deltaE = math.floor((2.5 * len(tiles) + (len(tiles) < 20 and 250 or (250 + -0.55 * ((len(tiles) - 20) ** 1.3)))/3) / (len(emp.war_targets) + 1))
deltaS = 1.0 - (len(tiles) + 1) * 0.02
if deltaE > 750:
deltaE = 750
if deltaS > 0.5:
deltaS = 0.5
if deltaS < -0.5:
deltaS = -0.5
emp.economy += deltaE
emp.stability += deltaS
if emp.economy > 500000:
emp.economy = 500000
if emp.economy < 0:
emp.economy = 0
if emp.stability > 5:
emp.stability = 5;
if emp.stability < 0:
emp.stability = 0;
if emp.expanding:
if len(emp.war_targets) == 0:
expanded = False
for hexagon in reversed(tiles):
surroundings = get_surroundings(hexagon)
#print(emp.economy)
for surr_hex in surroundings:
if surr_hex.empire is None and surr_hex.occupier is None and random.randint(0, 10) < math.log10(emp.economy) - 2:
annex_tile(emp, surr_hex)
tiles.append(hexagon)
expanded = True
if not expanded:
emp.expanding = False
recalc_border_emps(emp)
else:
#recalc_border_emps(emp)
if len(tiles) == 1:
surrounded = True
surroundings = get_surroundings(emp.capital)
if len(surroundings) == 0:
dissolve_empire(emp)
else:
surrounding_emp = surroundings[0].empire
for surr_hex in surroundings:
if surr_hex.empire != surrounding_emp:
surrounded = False
break
if surrounded == True:
partition_empire(emp, surrounding_emp)
if random.randint(min(round(emp.border_count / (1 + len(tiles))) * 200, 1000), 2000) == 2000:
print("%s collapsed!" % (emp.name))
dissolve_empire(emp)
for border_emp in emp.border_emps:
if emp.age > 30 and emp.economy > 1000 and random.randint(0, 20 * len(emp_arr)) == 0 and emp.economy >= border_emp.economy:
can_war = True
for diplo in concat_table(emp.war_targets, emp.peace_deals):
if diplo.target == border_emp:
can_war = False
if can_war:
declare_war(emp, border_emp)
print("%s has declared war on %s" % (emp.name, border_emp.name))
break
if len(emp.war_targets) != 0:
for war in emp.war_targets:
if random.randint(0, game_tick - war.tick) > 25:
print("%s has made peace with %s" % (emp.name, war.target.name))
make_peace(emp, war.target)
break
for hexagon in get_controlled_tiles(emp):
surroundings = get_surroundings(hexagon)
for surr_hex in surroundings:
if not is_in_control(emp, surr_hex):
for target in emp.war_targets:
if target.type == 0 and is_in_control(target.target, surr_hex) and (surr_hex.empire == target.target or surr_hex.empire == emp):
econ_advantage = min(round(emp.economy / (target.target.economy + 1)), 9)
helpers = 0
destroyed_empire = False
for pot_helper in get_surroundings(surr_hex):
if is_in_control(emp, pot_helper):
helpers += 1
if target.rebel is None and random.randint(0, helpers + 1) > 1 and random.randint(0, econ_advantage * ECONOMIC_ADVANTAGE + 1) > 1:
if surr_hex.empire == emp:
unoccupy_tile(surr_hex)
else:
destroyed_empire = occupy_tile(emp, surr_hex, target)
elif target.rebel == True and random.randint(0, helpers + 1) > 1 and random.randint(0, 3) == 0:
if surr_hex.empire == emp:
unoccupy_tile(surr_hex)
else:
destroyed_empire = occupy_tile(emp, surr_hex, target)
elif target.rebel == False and random.randint(0, helpers + 1) > 1 and random.randint(0, 10) == 0:
if surr_hex.empire == emp:
unoccupy_tile(surr_hex)
else:
destroyed_empire = occupy_tile(emp, surr_hex, target)
#break
if destroyed_empire == True and target.special == 0 and random.randint(0, 1) == 0:
recalc_border_emps(emp)
print("All neighboring nations have declared war on %s after a partition!" % (emp.name))
for border_emp in emp.border_emps:
if emp.economy * 0.7 < border_emp.economy:
already_at_war = False
for target in border_emp.war_targets:
if target.target == emp:
already_at_war = True
target.special = 1
target.aggressor = emp
if not already_at_war:
declare_war(border_emp, emp, 1, emp)
else:
"""
for hexagon in tiles:
if random.randint(0, 1500) == 0 and random.randint(math.floor(min(emp.stability, 0.9) * 10), 10) < 5 and distance_from_tiles(emp.capital, hexagon) > 8:
print("A nation has rebelled against %s! (1)" % (emp.name))
rebel(emp, hexagon)
emp.stability *= 0.5
"""
for i in range(0, 3):
rand_hex = hex_arr[random.randint(0, len(hex_arr) - 1)]
if rand_hex.empire == emp and rand_hex.occupier is None and random.randint(math.floor(min(emp.stability, 0.9) * 10), 10) < 5 and distance_from_tiles(emp.capital, rand_hex) > 8 and random.randint(0, 25 + math.floor(distance_from_tiles(emp.capital, rand_hex))) > 25:
print("A nation has rebelled against %s! (2)" % (emp.name))
rebel(emp, rand_hex)
emp.stability *= 0.5
if random.randint(0, 2) == 0 and len(tiles) > 30:
the_tiles = get_empire_tiles(emp)
rand_hex = the_tiles[random.randint(0, len(the_tiles) - 1)]
for i in range(0, random.randint(1, 3)):
rebel(emp, rand_hex)
emp.stability *= 0.5
print("%s has broken out into civil war!" % (emp.name))
break
if random.randint(0, 750) == 0:
for target in shuffle_table(emp_arr):
if emp.economy >= 5000 and emp.economy > target.economy * 1.25:
print("Sea invasion happening by %s on %s!" % (emp.name, target.name))
sea_invasion(emp, target)
break
for i in reversed(range(len(emp.peace_deals))):
if game_tick - emp.peace_deals[i].tick >= PEACE_DURATION:
print("Peace deal between %s and %s has expired" % (emp.name, emp.peace_deals[i].target.name))
emp.peace_deals.pop(i)
#if random.randint(0, 1000) == 0:
# print("%s collapsed!" % (emp.name))
# dissolve_empire(emp)
emp.age += 1
def fix_things():
for hexagon in hex_arr:
if not(hexagon.empire is None) and hexagon.empire == hexagon.occupier:
hexagon.occupier = None
hexagon.new_occupier = None
hexagon.set_color(hexagon.empire.color)
elif not(hexagon.empire is None) and not(hexagon.occupier is None) and len(hexagon.empire.war_targets) == 0:
print("THIS just happened")
print(hexagon.empire.name)
print(hexagon.occupier.name)
print(get_key_from_value(hexagon.empire.war_targets, hexagon.occupier))
print(get_key_from_value(hexagon.occupier.war_targets, hexagon.empire))
hexagon.occupier = None
hexagon.new_occupier = None
hexagon.set_color(hexagon.empire.color)
for emp in emp_arr:
if len(get_empire_tiles(emp)) == 0:
print("FOR some reason, %s wasn't deleted... deleting now" % (emp.name))
emp_arr.pop(get_key_from_value(emp_arr, emp))
def tick(win):
global game_tick
for hexagon in hex_arr:
if hexagon.change_color and not (hexagon.empire is None):
if not(hexagon.occupier is None) and not(hexagon.empire == hexagon.occupier):
hexagon.set_color((hexagon.occupier.color[0] + 70, hexagon.occupier.color[1] + 70, hexagon.occupier.color[2] + 70))
hexagon.change_color = False
elif hexagon.occupier is None:
hexagon.set_color((hexagon.empire.color[0], hexagon.empire.color[1], hexagon.empire.color[2]))
hexagon.change_color = False
if hexagon.empire.capital == hexagon:
#hexagon.set_color((0, 0, 0))
hexagon.make_capital()
elif hexagon.change_color:
hexagon.change_color = False
hexagon.set_color((255, 255, 255))
for emp in emp_arr:
result = for_each_empire(emp)
if result == False:
return False
if game_tick % 10 == 0:
fix_things()
rand_x = random.randint(0, DIMENSIONS[0])
rand_y = random.randint(0, DIMENSIONS[1])
rand_hex = hex_exists(rand_x, rand_y)
if not(rand_hex is None) and rand_hex.empire is None:
print("Empire %d has spawned randomly!" % (emp_count))
Empire("Empire %d" % (emp_count), rand_hex, (random.randint(15, 85), random.randint(15, 85), random.randint(15, 85)))
def startup(win):
global emp_count
for i in range(0, DIMENSIONS[0]):
noise_vals.append([])
for j in range(0, DIMENSIONS[0]):
noise_vals[i].append(noise.snoise2(rand_val + i * 0.075 * CONTINENT_ROUGHNESS, rand_val + j * 0.075 * CONTINENT_ROUGHNESS))
for i in range(0, DIMENSIONS[0]):
for j in range(0, DIMENSIONS[1]):
if noise_vals[i][j] >= -1 + OCEAN_WORLD * 0.2:
hex_arr.append(Hex(win, i, j))
for i in range(0, INITIAL_EMPIRES):
while True:
rand_x = random.randint(0, DIMENSIONS[0])
rand_y = random.randint(0, DIMENSIONS[1])
rand_hex = hex_exists(rand_x, rand_y)
if not (rand_hex is None):
Empire("Empire %d" % (emp_count), rand_hex, (random.randint(15, 85), random.randint(15, 85), random.randint(15, 85)))
break
def main():
if GAME_BOUND[0] + GAME_BOUND[2] > WINDOW_BOUND[0] or GAME_BOUND[1] + GAME_BOUND[3] > WINDOW_BOUND[1]:
raise Exception("Game Error: Game bounding box is bigger than window bounding box")
pygame.init()
win = pygame.display.set_mode((WINDOW_BOUND[0], WINDOW_BOUND[1]))
pygame.display.set_caption("hello")
win.fill((0, 15, 55))
clock = pygame.time.Clock()
global game_tick
global emp_count
startup(win)
result = True
while True:
for e in pygame.event.get():
if e.type == pygame.QUIT:
return
if not (result == False):
result = tick(win)
game_tick += 1
clock.tick(5)
pygame.display.update()
if __name__ == '__main__':
main()
pygame.quit() | <filename>Python/civ.py<gh_stars>1-10
"""
MIT License
Copyright (c) 2020 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import os
import sys
import pygame
import pygame.gfxdraw
import math
import noise
import random
from datetime import datetime
random.seed(datetime.now())
rand_val = random.randint(0, 100000)
SQRT_3 = 1.732
WINDOW_BOUND = [1366, 700]
GAME_BOUND = [round(WINDOW_BOUND[0]*1/64), round(WINDOW_BOUND[1]*1/64), round(WINDOW_BOUND[0]*31/32), round(WINDOW_BOUND[1]*31/32)]
HEX_WIDTH = 12 #12
DIMENSIONS = [64, 32] #64, 32
CONTINENT_ROUGHNESS = 0.9 #0.9
OCEAN_WORLD = 5
INITIAL_EMPIRES = 16 #16
PEACE_DURATION = 15
ECONOMIC_ADVANTAGE = 2
ENABLE_MULTITHREADING = True
NUM_CORES = 1
if ENABLE_MULTITHREADING:
if sys.platform.startswith('linux'):
stream = os.popen('grep -c ^processor /proc/cpuinfo')
elif sys.platform.startswith('win'):
stream = os.popen('echo %NUMBER_OF_PROCESSORS%')
elif sys.platform.startswith('cygwin'):
stream = os.popen('echo %NUMBER_OF_PROCESSORS%')
elif sys.platform.startswith('msys'):
stream = os.popen('echo %NUMBER_OF_PROCESSORS%')
elif sys.platform.startswith('darwin'):
stream = os.popen('sysctl -n hw.ncpu')
output = stream.read()
NUM_CORES = int(output[:len(output) - 1])
global emp_count, game_tick
noise_vals = []
emp_arr = []
hex_arr = []
emp_count = 1
game_tick = 1
class Empire:
def __init__(self, name, capital, color, economy=100):
global emp_count
self.name = name
self.capital = capital
self.color = verify_color(color)
self.expanding = True
self.economy = economy
self.stability = 1.0
self.war_targets = []
self.peace_deals = []
self.border_emps = []
self.border_count = 0
self.age = 0
emp_count += 1
annex_tile(self, capital)
#self.capital.set_color((0, 0, 0))
self.capital.make_capital()
emp_arr.append(self)
recalc_border_emps(self)
for border_emp in self.border_emps:
recalc_border_emps(border_emp)
class Hex:
def __init__(self, win, x, y):
self.win = win
self.x = x
self.y = y
self.empire = None
self.occupier = None
self.new_empire = None
self.new_occupier = None
self.change_color = False
self.color = (255, 255, 255)
draw_hex_at_coord(self.win, self.x, self.y, self.color)
def set_color(self, color):
self.color = color
draw_hex_at_coord(self.win, self.x, self.y, self.color)
def make_capital(self):
pygame.draw.circle(self.win, (0, 0, 0), (GAME_BOUND[0] + self.x * math.floor(1.5 * HEX_WIDTH), GAME_BOUND[1] + self.y * math.floor(SQRT_3 * HEX_WIDTH) + (self.x % 2) * math.floor(SQRT_3/2 * HEX_WIDTH)), math.ceil(HEX_WIDTH * 0.5))
class DiploObject:
def __init__(self, target, kind, rebel=None, special=0, aggressor=None):
self.target = target
self.type = kind # 0 is a war declartion, 1 is a peace deal
self.tick = game_tick
self.rebel = rebel
self.special = special # 0 is not special, 1 is retribution conflict
self.aggressor = aggressor
def draw_hex(screen, color, x, y, sWidth=10, width=0):
factor_1 = math.floor(SQRT_3 * sWidth / 2)
factor_2 = math.floor(sWidth * 0.5)
pygame.draw.polygon(screen, color, [[x - sWidth, y], [x - factor_2, y - factor_1], [x + factor_2, y - factor_1], [x + sWidth, y], [x + factor_2, y + factor_1], [x - factor_2, y + factor_1]], width)
def draw_hex_at_coord(screen, x, y, color=(255, 255, 255)):
factor_1 = math.floor(1.5 * HEX_WIDTH)
factor_2 = math.floor(SQRT_3 * HEX_WIDTH)
factor_3 = math.floor(SQRT_3/2 * HEX_WIDTH)
draw_hex(screen, color, GAME_BOUND[0] + x * factor_1, GAME_BOUND[1] + y * factor_2 + (x % 2) * factor_3, HEX_WIDTH)
draw_hex(screen, (0, 0, 0), GAME_BOUND[0] + x * factor_1, GAME_BOUND[1] + y * factor_2 + (x % 2) * factor_3, HEX_WIDTH, 1)
def get_key_from_value(tab, value):
i = 0
for val in tab:
if val == value:
return i
i += 1
return -1
def index_at_greatest(tab):
val = -math.inf
index = -1
for i in range(len(tab)):
if tab[i] > val:
val = tab[i]
index = i
return i
def concat_table(tab1, tab2):
tab3 = []
for i in tab1:
tab3.append(i)
for i in tab2:
tab3.append(i)
return tab3
def cpft(a, b, c):
for v in a:
if v[0] == b and v[1] == c:
return True
return False
def verify_color(color, level=0):
if level > 100:
return color
for emp in emp_arr:
diff = ((emp.color[0] - color[0]) ** 2) + ((emp.color[1] - color[1]) ** 2) + ((emp.color[2] - color[2]) ** 2)
if diff < 500:
return verify_color((random.randint(15, 85), random.randint(15, 85), random.randint(15, 85)), level + 1)
return color
def tiles_connected(tile1, tile2, l=None, i=None):
if l == None:
if (tile2.empire != tile2.empire) or (tile1.empire is None or tile2.empire is None):
return False
l = [[tile2.x, tile2.y, 0]]
if i == None:
i = 0
for v in get_surroundings(tile2):
if v == tile1:
return True
coords = [v.x, v.y]
orig = hex_exists(l[0][0], l[0][1])
if not(cpft(l, coords[0], coords[1])) and (is_in_control(tile1.empire, v) or is_in_control(orig.empire, v)):
l.append([coords[0], coords[1], i])
if len(l) <= i:
return False
return tiles_connected(tile1, hex_exists(l[i][0], l[i][1]), l, i + 1)
def hex_exists(x, y):
for hexagon in hex_arr:
if hexagon.x == x and hexagon.y == y:
return hexagon
return None
def get_surroundings(tile):
out = []
out.append(hex_exists(tile.x, tile.y + 1))
out.append(hex_exists(tile.x, tile.y - 1))
out.append(hex_exists(tile.x + 1, tile.y))
out.append(hex_exists(tile.x - 1, tile.y))
if tile.x % 2 == 1:
out.append(hex_exists(tile.x - 1, tile.y + 1))
out.append(hex_exists(tile.x + 1, tile.y + 1))
else:
out.append(hex_exists(tile.x + 1, tile.y - 1))
out.append(hex_exists(tile.x - 1, tile.y - 1))
for i in range(len(out) - 1, -1, -1):
if out[i] is None:
out.pop(i)
return out
def get_cluster(tile, max_size=0, l=None, orig_tile=None):
if orig_tile is None:
orig_tile = tile
if l is None:
l = [tile]
if max_size != 0 and len(l) > max_size:
return l
for v in get_surroundings(tile):
if is_same_tile_type(orig_tile, v) and get_key_from_value(l, v) == -1:
l.append(v)
l = get_cluster(v, max_size, l, orig_tile)
return l
def distance_from_tiles(t0, t1):
return math.sqrt((t0.x - t1.x) ** 2 + (t0.y - t1.y) ** 2)
def is_in_control(emp, tile):
return (tile.empire == emp and tile.occupier is None) or tile.occupier == emp
def is_same_tile_type(tile1, tile2):
if not(tile1.occupier is None):
if not(tile2.occupier is None):
return tile1.empire == tile2.empire and tile1.occupier == tile2.occupier
else:
return is_in_control(tile1.occupier, tile2)
elif tile1.occupier is None:
if not(tile2.occupier is None):
return is_in_control(tile2.occupier, tile1)
else:
return tile1.empire == tile2.empire
def recalc_border_emps(emp):
emp.border_emps = []
emp.border_count = 0
for hexagon in get_empire_tiles(emp):
surroundings = get_surroundings(hexagon)
for surr_hex in surroundings:
if not (surr_hex.empire is None) and not (surr_hex.empire.name == emp.name) and get_key_from_value(emp.border_emps, surr_hex.empire) == -1:
emp.border_emps.append(surr_hex.empire)
emp.border_count += 1
if get_key_from_value(surr_hex.empire.border_emps, emp) == -1:
surr_hex.empire.border_emps.append(emp)
elif surr_hex.empire is None and surr_hex.occupier is None:
emp.expanding = True
def fragment_empire(emp, conqueror):
print("The capital of %s has been captured and %s will liberate its occupations!" % (emp.name, conqueror.name))
tiles = get_empire_tiles(emp)
for hexagon in tiles:
unoccupy_tile(hexagon)
while len(tiles) > 0:
rand_loc = random.randint(0, len(tiles) - 1)
rand_hex = tiles[rand_loc]
tiles.pop(rand_loc)
new_empires = []
rand_hexes = get_surroundings(rand_hex)
for rand in rand_hexes:
if get_key_from_value(tiles, rand) != -1:
if len(rand_hexes) < 30:
rand_hexes_rand_hexes = get_surroundings(rand)
for rand_rand in reversed(rand_hexes_rand_hexes):
if random.randint(0, 1) == 0 and len(rand_hexes) < 30 and get_key_from_value(tiles, rand_rand) != -1 and get_key_from_value(rand_hexes, rand_rand) == -1:
rand_hexes.append(rand_rand)
tiles.pop(get_key_from_value(tiles, rand_rand))
tiles.pop(get_key_from_value(tiles, rand))
elif get_key_from_value(rand_hexes, rand) == -1:
rand_hexes.pop(get_key_from_value(rand_hexes, rand))
if len(rand_hexes) > 9 or len(get_empire_tiles(emp)) < 10:
new_empire = Empire("Empire %d" % (emp_count), rand_hex, (random.randint(15, 85), random.randint(15, 85), random.randint(15, 85)))
new_empires.append(new_empire)
for rand in rand_hexes:
annex_tile(new_empire, rand)
dissolve_empire(emp)
recalc_border_emps(conqueror)
for empire in emp.border_emps:
recalc_border_emps(empire)
for empire in new_empires:
empire.economy = math.floor((emp.economy / len(new_empires)) * 0.8)
peace1 = DiploObject(empire, 1)
peace2 = DiploObject(conqueror, 1)
conqueror.peace_deals.append(peace1)
emp.peace_deals.append(peace2)
recalc_border_emps(empire)
#print(emp.name)
#emp_arr.pop(get_key_from_value(emp_arr, emp))
def partition_empire(emp, conqueror):
print("The capital of %s has been captured by %s and will be partitioned!" % (emp.name, conqueror.name))
main_land = get_cluster(emp.capital)
for hexagon in main_land:
annex_tile(conqueror, hexagon)
for hexagon in shuffle_table(hex_arr):
if hexagon.empire == emp:
if hexagon.occupier is None:
tiles = get_cluster(hexagon)
new_emp = Empire("Empire %d" % (emp_count), hexagon, (random.randint(15, 85), random.randint(15, 85), random.randint(15, 85)))
for tile in tiles:
if tile != new_emp.capital:
annex_tile(new_emp, tile)
else:
annex_tile(hexagon.occupier, hexagon)
elif hexagon.occupier == emp:
unoccupy_tile(hexagon)
for emp_i in emp_arr:
for i in reversed(range(len(emp_i.war_targets))):
if emp_i.war_targets[i].target == emp:
emp_i.war_targets.pop(i)
rebel = False
for war in emp.war_targets:
if not(war.rebel is None) and war.rebel == True:
war.target.stability += 5
rebel = True
if rebel:
emp.stability *= 3
else:
conqueror.economy = round(conqueror.economy * 0.8)
recalc_border_emps(conqueror)
for empire in emp.border_emps:
recalc_border_emps(empire)
emp_arr.pop(get_key_from_value(emp_arr, emp))
def annex_tile(emp, tile):
tile.empire = emp
tile.new_empire = emp
tile.occupier = None
tile.new_occupier = None
tile.change_color = True
tile.set_color((emp.color[0] + 140, emp.color[1] + 140, emp.color[2] + 140))
def delayed_annex_tile(emp, tile):
tile.new_empire = emp
tile.new_occupier = None
tile.set_color(emp.color)
def unoccupy_tile(tile):
tile.occupier = None
tile.new_occupier = None
tile.change_color = True
tile.set_color((tile.empire.color[0] + 140, tile.empire.color[1] + 140, tile.empire.color[2] + 140))
def delayed_unoccupy_tile(tile):
tile.new_occupier = None
tile.set_color(tile.empire.color)
def is_delayed(tile):
return tile.new_occupier != tile.occupier or tile.new_empire != tile.empire
def correct_delayed():
for hexagon in hex_arr:
if is_delayed(hexagon):
hexagon.occupier = hexagon.new_occupier
hexagon.empire = hexagon.new_empire
def occupy_tile(emp, tile, causus):
if tile.empire.capital == tile:
if not (causus is None) and ((causus.special == 1 and causus.aggressor != emp) or (not (causus.rebel is None)) and random.randint(0, 1) == 0):
fragment_empire(tile.empire, emp)
#print("woah")
else:
partition_empire(tile.empire, emp)
emp.economy -= 500
if emp.economy < 0:
emp.economy = 0
return True
else:
tile.occupier = emp
tile.new_occupier = emp
tile.change_color = True
tile.set_color((emp.color[0] + 140, emp.color[1] + 140, emp.color[2] + 140))
emp.economy -= 10
tile.empire.economy -= 10
if emp.economy < 0:
emp.economy = 0
if tile.empire.economy < 0:
tile.empire.economy = 0
return False
def declare_war(initiator, target, special=0, aggressor=None):
init_war_dec = DiploObject(target, 0, None, special, aggressor)
initiator.war_targets.append(init_war_dec)
target_war_dec = DiploObject(initiator, 0, None, special, aggressor)
target.war_targets.append(target_war_dec)
def rebel(emp, tile):
rebel_emp = Empire("Empire %d" % (emp_count), tile, (random.randint(15, 85), random.randint(15, 85), random.randint(15, 85)), round(emp.economy * 0.6))
for surr_hex in get_surroundings(tile):
if surr_hex.color[0] != 0 or surr_hex.color[1] != 0 or surr_hex.color[2] != 0:
annex_tile(rebel_emp, surr_hex)
war1 = DiploObject(emp, 0, True)
war2 = DiploObject(rebel_emp, 0, False)
emp.economy = emp.economy * 0.6
rebel_emp.economy = emp.economy * 0.2
emp.war_targets.append(war2)
rebel_emp.war_targets.append(war1)
def make_peace(emp1, emp2):
c1 = get_cluster(emp1.capital)
for hexagon in c1:
if hexagon.occupier == emp1 and hexagon != emp1.capital:
delayed_annex_tile(emp1, hexagon)
c2 = get_cluster(emp2.capital)
for hexagon in c2:
if hexagon.occupier == emp2 and hexagon != emp2.capital:
delayed_annex_tile(emp2, hexagon)
for hexagon in hex_arr:
if hexagon.empire == emp1 and hexagon.occupier == emp2 and not is_delayed(hexagon):
c3 = get_cluster(hexagon)
for tile in c3:
delayed_unoccupy_tile(tile)
elif hexagon.empire == emp2 and hexagon.occupier == emp1 and not is_delayed(hexagon):
c3 = get_cluster(hexagon)
for tile in c3:
delayed_unoccupy_tile(tile)
elif hexagon.empire == emp1 and hexagon.occupier is None and get_key_from_value(c1, hexagon) == -1 and not is_delayed(hexagon):
c3 = get_cluster(hexagon)
if len(c3) > 10 and not tiles_connected(hexagon, emp1.capital):
new_emp = Empire("Empire %d" % (emp_count), hexagon, (random.randint(15, 85), random.randint(15, 85), random.randint(15, 85)))
for tile in c3:
if tile != new_emp.capital:
delayed_annex_tile(new_emp, tile)
for surr_hex in get_surroundings(hexagon):
if surr_hex.color[0] != 0:
delayed_annex_tile(new_emp, surr_hex)
else:
for tile in c3:
if tile.color[0] == 0:
print("There's been a screw up; Hex info: (%d, %d) E: (%s) O: (%s) P:(%s, %s) (1)" % (hexagon.x, hexagon.y, hexagon.empire.name, hexagon.occupier, emp1.name, emp2.name))
elif tile.occupier is None and tile.empire == emp1:
delayed_annex_tile(emp2, tile)
elif hexagon.empire == emp2 and hexagon.occupier is None and get_key_from_value(c2, hexagon) == -1 and not is_delayed(hexagon):
c3 = get_cluster(hexagon)
if len(c3) > 10 and not tiles_connected(hexagon, emp2.capital):
new_emp = Empire("Empire %d" % (emp_count), hexagon, (random.randint(15, 85), random.randint(15, 85), random.randint(15, 85)))
for tile in c3:
if tile != new_emp.capital:
delayed_annex_tile(new_emp, tile)
for surr_hex in get_surroundings(hexagon):
if surr_hex.color[0] != 0:
delayed_annex_tile(new_emp, surr_hex)
else:
for tile in c3:
if tile.color[0] == 0:
print("There's been a screw up; Hex info: (%d, %d) E: (%s) O: (%s) P:(%s, %s) (2)" % (hexagon.x, hexagon.y, hexagon.empire.name, hexagon.occupier, emp1.name, emp2.name))
elif tile.occupier is None and tile.empire == emp2:
delayed_annex_tile(emp1, tile)
correct_delayed()
checked_emps = [emp1, emp2]
recalc_border_emps(emp1)
for empire in emp1.border_emps:
recalc_border_emps(empire)
checked_emps.append(empire)
recalc_border_emps(emp2)
for empire in emp2.border_emps:
if get_key_from_value(checked_emps, empire) != -1:
recalc_border_emps(empire)
checked_emps.append(empire)
for i in reversed(range(len(emp1.war_targets))):
if emp1.war_targets[i].target == emp2:
emp1.war_targets.pop(i)
for i in reversed(range(len(emp2.war_targets))):
if emp2.war_targets[i].target == emp1:
emp2.war_targets.pop(i)
peace1 = DiploObject(emp2, 1)
peace2 = DiploObject(emp1, 1)
emp1.peace_deals.append(peace1)
emp2.peace_deals.append(peace2)
def dissolve_empire(emp):
for i in reversed(range(len(emp.war_targets))):
for j in reversed(range(len(emp.war_targets[i].target.war_targets))):
if emp.war_targets[i].target.war_targets[j].target == emp:
emp.war_targets[i].target.war_targets.pop(j)
emp.war_targets.pop(i)
for hexagon in hex_arr:
if hexagon.empire == emp and hexagon.occupier is None:
hexagon.empire = None
hexagon.new_empire = None
hexagon.occupier = None
hexagon.new_occupier = None
hexagon.set_color((255, 255, 255))
elif hexagon.empire == emp:
annex_tile(hexagon.occupier, hexagon)
elif hexagon.occupier == emp:
unoccupy_tile(hexagon)
for empire in emp_arr:
for i in reversed(range(len(empire.border_emps))):
try:
if empire.border_emps[i] == emp:
empire.border_emps.pop(i)
recalc_border_emps(empire)
except:
print(empire.name)
print(len(empire.border_emps))
print(i)
for border_emp in empire.border_emps:
print(border_emp)
print(i)
Exception("rip")
index = get_key_from_value(emp_arr, emp)
emp_arr.pop(get_key_from_value(emp_arr, emp))
def sea_invasion(emp, target):
target_tiles = shuffle_table(get_empire_tiles(target))
#print("[s] 1")
invasions = random.randint(1, 3)
invaded = False
for hexagon in target_tiles:
surroundings = get_surroundings(hexagon)
#print("[s] 1.5 (%d, %f)" % (len(get_surroundings(hexagon)), distance_from_tiles(hexagon, target.capital)))
if hexagon.occupier is None and hexagon.empire == target and len(get_surroundings(hexagon)) < 6 and distance_from_tiles(hexagon, target.capital) > 3:
#print("[s] 2")
occupy_tile(emp, hexagon, None)
for surr_hex in surroundings:
if surr_hex.color[0] != 0 and not (surr_hex.empire is None):
occupy_tile(emp, surr_hex, None)
invasions -= 1
invaded = True
if invasions == 0:
break
#print("[s] 3")
if invaded:
#print("[s] 4")
declare_war(emp, target)
def shuffle_table(tab):
out = []
for i in range(len(tab)):
j = random.randint(i, len(tab) - 1)
temp = tab[i]
tab[i] = tab[j]
tab[j] = temp
out.append(tab[i])
return out
def get_empire_tiles(emp):
out = []
for hexagon in hex_arr:
if hexagon.empire == emp:
out.append(hexagon)
return out
def get_controlled_tiles(emp):
out = []
for hexagon in hex_arr:
if is_in_control(emp, hexagon):
out.append(hexagon)
return out
def for_each_empire(emp):
tiles = get_empire_tiles(emp)
#print(emp.economy)
#border_emps = []
deltaE = math.floor((2.5 * len(tiles) + (len(tiles) < 20 and 250 or (250 + -0.55 * ((len(tiles) - 20) ** 1.3)))/3) / (len(emp.war_targets) + 1))
deltaS = 1.0 - (len(tiles) + 1) * 0.02
if deltaE > 750:
deltaE = 750
if deltaS > 0.5:
deltaS = 0.5
if deltaS < -0.5:
deltaS = -0.5
emp.economy += deltaE
emp.stability += deltaS
if emp.economy > 500000:
emp.economy = 500000
if emp.economy < 0:
emp.economy = 0
if emp.stability > 5:
emp.stability = 5;
if emp.stability < 0:
emp.stability = 0;
if emp.expanding:
if len(emp.war_targets) == 0:
expanded = False
for hexagon in reversed(tiles):
surroundings = get_surroundings(hexagon)
#print(emp.economy)
for surr_hex in surroundings:
if surr_hex.empire is None and surr_hex.occupier is None and random.randint(0, 10) < math.log10(emp.economy) - 2:
annex_tile(emp, surr_hex)
tiles.append(hexagon)
expanded = True
if not expanded:
emp.expanding = False
recalc_border_emps(emp)
else:
#recalc_border_emps(emp)
if len(tiles) == 1:
surrounded = True
surroundings = get_surroundings(emp.capital)
if len(surroundings) == 0:
dissolve_empire(emp)
else:
surrounding_emp = surroundings[0].empire
for surr_hex in surroundings:
if surr_hex.empire != surrounding_emp:
surrounded = False
break
if surrounded == True:
partition_empire(emp, surrounding_emp)
if random.randint(min(round(emp.border_count / (1 + len(tiles))) * 200, 1000), 2000) == 2000:
print("%s collapsed!" % (emp.name))
dissolve_empire(emp)
for border_emp in emp.border_emps:
if emp.age > 30 and emp.economy > 1000 and random.randint(0, 20 * len(emp_arr)) == 0 and emp.economy >= border_emp.economy:
can_war = True
for diplo in concat_table(emp.war_targets, emp.peace_deals):
if diplo.target == border_emp:
can_war = False
if can_war:
declare_war(emp, border_emp)
print("%s has declared war on %s" % (emp.name, border_emp.name))
break
if len(emp.war_targets) != 0:
for war in emp.war_targets:
if random.randint(0, game_tick - war.tick) > 25:
print("%s has made peace with %s" % (emp.name, war.target.name))
make_peace(emp, war.target)
break
for hexagon in get_controlled_tiles(emp):
surroundings = get_surroundings(hexagon)
for surr_hex in surroundings:
if not is_in_control(emp, surr_hex):
for target in emp.war_targets:
if target.type == 0 and is_in_control(target.target, surr_hex) and (surr_hex.empire == target.target or surr_hex.empire == emp):
econ_advantage = min(round(emp.economy / (target.target.economy + 1)), 9)
helpers = 0
destroyed_empire = False
for pot_helper in get_surroundings(surr_hex):
if is_in_control(emp, pot_helper):
helpers += 1
if target.rebel is None and random.randint(0, helpers + 1) > 1 and random.randint(0, econ_advantage * ECONOMIC_ADVANTAGE + 1) > 1:
if surr_hex.empire == emp:
unoccupy_tile(surr_hex)
else:
destroyed_empire = occupy_tile(emp, surr_hex, target)
elif target.rebel == True and random.randint(0, helpers + 1) > 1 and random.randint(0, 3) == 0:
if surr_hex.empire == emp:
unoccupy_tile(surr_hex)
else:
destroyed_empire = occupy_tile(emp, surr_hex, target)
elif target.rebel == False and random.randint(0, helpers + 1) > 1 and random.randint(0, 10) == 0:
if surr_hex.empire == emp:
unoccupy_tile(surr_hex)
else:
destroyed_empire = occupy_tile(emp, surr_hex, target)
#break
if destroyed_empire == True and target.special == 0 and random.randint(0, 1) == 0:
recalc_border_emps(emp)
print("All neighboring nations have declared war on %s after a partition!" % (emp.name))
for border_emp in emp.border_emps:
if emp.economy * 0.7 < border_emp.economy:
already_at_war = False
for target in border_emp.war_targets:
if target.target == emp:
already_at_war = True
target.special = 1
target.aggressor = emp
if not already_at_war:
declare_war(border_emp, emp, 1, emp)
else:
"""
for hexagon in tiles:
if random.randint(0, 1500) == 0 and random.randint(math.floor(min(emp.stability, 0.9) * 10), 10) < 5 and distance_from_tiles(emp.capital, hexagon) > 8:
print("A nation has rebelled against %s! (1)" % (emp.name))
rebel(emp, hexagon)
emp.stability *= 0.5
"""
for i in range(0, 3):
rand_hex = hex_arr[random.randint(0, len(hex_arr) - 1)]
if rand_hex.empire == emp and rand_hex.occupier is None and random.randint(math.floor(min(emp.stability, 0.9) * 10), 10) < 5 and distance_from_tiles(emp.capital, rand_hex) > 8 and random.randint(0, 25 + math.floor(distance_from_tiles(emp.capital, rand_hex))) > 25:
print("A nation has rebelled against %s! (2)" % (emp.name))
rebel(emp, rand_hex)
emp.stability *= 0.5
if random.randint(0, 2) == 0 and len(tiles) > 30:
the_tiles = get_empire_tiles(emp)
rand_hex = the_tiles[random.randint(0, len(the_tiles) - 1)]
for i in range(0, random.randint(1, 3)):
rebel(emp, rand_hex)
emp.stability *= 0.5
print("%s has broken out into civil war!" % (emp.name))
break
if random.randint(0, 750) == 0:
for target in shuffle_table(emp_arr):
if emp.economy >= 5000 and emp.economy > target.economy * 1.25:
print("Sea invasion happening by %s on %s!" % (emp.name, target.name))
sea_invasion(emp, target)
break
for i in reversed(range(len(emp.peace_deals))):
if game_tick - emp.peace_deals[i].tick >= PEACE_DURATION:
print("Peace deal between %s and %s has expired" % (emp.name, emp.peace_deals[i].target.name))
emp.peace_deals.pop(i)
#if random.randint(0, 1000) == 0:
# print("%s collapsed!" % (emp.name))
# dissolve_empire(emp)
emp.age += 1
def fix_things():
for hexagon in hex_arr:
if not(hexagon.empire is None) and hexagon.empire == hexagon.occupier:
hexagon.occupier = None
hexagon.new_occupier = None
hexagon.set_color(hexagon.empire.color)
elif not(hexagon.empire is None) and not(hexagon.occupier is None) and len(hexagon.empire.war_targets) == 0:
print("THIS just happened")
print(hexagon.empire.name)
print(hexagon.occupier.name)
print(get_key_from_value(hexagon.empire.war_targets, hexagon.occupier))
print(get_key_from_value(hexagon.occupier.war_targets, hexagon.empire))
hexagon.occupier = None
hexagon.new_occupier = None
hexagon.set_color(hexagon.empire.color)
for emp in emp_arr:
if len(get_empire_tiles(emp)) == 0:
print("FOR some reason, %s wasn't deleted... deleting now" % (emp.name))
emp_arr.pop(get_key_from_value(emp_arr, emp))
def tick(win):
global game_tick
for hexagon in hex_arr:
if hexagon.change_color and not (hexagon.empire is None):
if not(hexagon.occupier is None) and not(hexagon.empire == hexagon.occupier):
hexagon.set_color((hexagon.occupier.color[0] + 70, hexagon.occupier.color[1] + 70, hexagon.occupier.color[2] + 70))
hexagon.change_color = False
elif hexagon.occupier is None:
hexagon.set_color((hexagon.empire.color[0], hexagon.empire.color[1], hexagon.empire.color[2]))
hexagon.change_color = False
if hexagon.empire.capital == hexagon:
#hexagon.set_color((0, 0, 0))
hexagon.make_capital()
elif hexagon.change_color:
hexagon.change_color = False
hexagon.set_color((255, 255, 255))
for emp in emp_arr:
result = for_each_empire(emp)
if result == False:
return False
if game_tick % 10 == 0:
fix_things()
rand_x = random.randint(0, DIMENSIONS[0])
rand_y = random.randint(0, DIMENSIONS[1])
rand_hex = hex_exists(rand_x, rand_y)
if not(rand_hex is None) and rand_hex.empire is None:
print("Empire %d has spawned randomly!" % (emp_count))
Empire("Empire %d" % (emp_count), rand_hex, (random.randint(15, 85), random.randint(15, 85), random.randint(15, 85)))
def startup(win):
global emp_count
for i in range(0, DIMENSIONS[0]):
noise_vals.append([])
for j in range(0, DIMENSIONS[0]):
noise_vals[i].append(noise.snoise2(rand_val + i * 0.075 * CONTINENT_ROUGHNESS, rand_val + j * 0.075 * CONTINENT_ROUGHNESS))
for i in range(0, DIMENSIONS[0]):
for j in range(0, DIMENSIONS[1]):
if noise_vals[i][j] >= -1 + OCEAN_WORLD * 0.2:
hex_arr.append(Hex(win, i, j))
for i in range(0, INITIAL_EMPIRES):
while True:
rand_x = random.randint(0, DIMENSIONS[0])
rand_y = random.randint(0, DIMENSIONS[1])
rand_hex = hex_exists(rand_x, rand_y)
if not (rand_hex is None):
Empire("Empire %d" % (emp_count), rand_hex, (random.randint(15, 85), random.randint(15, 85), random.randint(15, 85)))
break
def main():
if GAME_BOUND[0] + GAME_BOUND[2] > WINDOW_BOUND[0] or GAME_BOUND[1] + GAME_BOUND[3] > WINDOW_BOUND[1]:
raise Exception("Game Error: Game bounding box is bigger than window bounding box")
pygame.init()
win = pygame.display.set_mode((WINDOW_BOUND[0], WINDOW_BOUND[1]))
pygame.display.set_caption("hello")
win.fill((0, 15, 55))
clock = pygame.time.Clock()
global game_tick
global emp_count
startup(win)
result = True
while True:
for e in pygame.event.get():
if e.type == pygame.QUIT:
return
if not (result == False):
result = tick(win)
game_tick += 1
clock.tick(5)
pygame.display.update()
if __name__ == '__main__':
main()
pygame.quit() | en | 0.594759 | MIT License Copyright (c) 2020 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #12 #64, 32 #0.9 #16 #self.capital.set_color((0, 0, 0)) # 0 is a war declartion, 1 is a peace deal # 0 is not special, 1 is retribution conflict #print(emp.name) #emp_arr.pop(get_key_from_value(emp_arr, emp)) #print("woah") #print("[s] 1") #print("[s] 1.5 (%d, %f)" % (len(get_surroundings(hexagon)), distance_from_tiles(hexagon, target.capital))) #print("[s] 2") #print("[s] 3") #print("[s] 4") #print(emp.economy) #border_emps = [] #print(emp.economy) #recalc_border_emps(emp) #break for hexagon in tiles: if random.randint(0, 1500) == 0 and random.randint(math.floor(min(emp.stability, 0.9) * 10), 10) < 5 and distance_from_tiles(emp.capital, hexagon) > 8: print("A nation has rebelled against %s! (1)" % (emp.name)) rebel(emp, hexagon) emp.stability *= 0.5 #if random.randint(0, 1000) == 0: # print("%s collapsed!" % (emp.name)) # dissolve_empire(emp) #hexagon.set_color((0, 0, 0)) | 2.381021 | 2 |
auctioning_platform/auctions_infrastructure/auctions_infrastructure/repositories/auctions.py | nhdinh/smp-modulith | 299 | 6614178 | <reponame>nhdinh/smp-modulith
from typing import List
import pytz
from sqlalchemy.engine import Connection, RowProxy
from foundation.events import EventBus
from foundation.value_objects.factories import get_dollars
from auctions.application.repositories import AuctionsRepository
from auctions.domain.entities import Auction, Bid
from auctions.domain.value_objects import AuctionId
from auctions_infrastructure import auctions, bids
class SqlAlchemyAuctionsRepo(AuctionsRepository):
def __init__(self, connection: Connection, event_bus: EventBus) -> None:
self._conn = connection
self._event_bus = event_bus
def get(self, auction_id: AuctionId) -> Auction:
row = self._conn.execute(auctions.select().where(auctions.c.id == auction_id)).first()
if not row:
raise Exception("Not found")
bid_rows = self._conn.execute(bids.select().where(bids.c.auction_id == auction_id)).fetchall()
return self._row_to_entity(row, bid_rows)
def _row_to_entity(self, auction_proxy: RowProxy, bids_proxies: List[RowProxy]) -> Auction:
auction_bids = [Bid(bid.id, bid.bidder_id, get_dollars(bid.amount)) for bid in bids_proxies]
return Auction(
auction_proxy.id,
auction_proxy.title,
get_dollars(auction_proxy.starting_price),
auction_bids,
auction_proxy.ends_at.replace(tzinfo=pytz.UTC),
auction_proxy.ended,
)
def save(self, auction: Auction) -> None:
raw_auction = {
"title": auction.title,
"starting_price": auction.starting_price.amount,
"current_price": auction.current_price.amount,
"ends_at": auction.ends_at,
"ended": auction._ended,
}
update_result = self._conn.execute(auctions.update(values=raw_auction, whereclause=auctions.c.id == auction.id))
if update_result.rowcount != 1:
self._conn.execute(auctions.insert(values=dict(raw_auction, id=auction.id)))
for bid in auction.bids:
if bid.id:
continue
result = self._conn.execute(
bids.insert(values={"auction_id": auction.id, "amount": bid.amount.amount, "bidder_id": bid.bidder_id})
)
(bid.id,) = result.inserted_primary_key
if auction.withdrawn_bids_ids:
self._conn.execute(bids.delete(whereclause=bids.c.id.in_(auction.withdrawn_bids_ids)))
for event in auction.domain_events:
self._event_bus.post(event)
auction.clear_events()
| from typing import List
import pytz
from sqlalchemy.engine import Connection, RowProxy
from foundation.events import EventBus
from foundation.value_objects.factories import get_dollars
from auctions.application.repositories import AuctionsRepository
from auctions.domain.entities import Auction, Bid
from auctions.domain.value_objects import AuctionId
from auctions_infrastructure import auctions, bids
class SqlAlchemyAuctionsRepo(AuctionsRepository):
def __init__(self, connection: Connection, event_bus: EventBus) -> None:
self._conn = connection
self._event_bus = event_bus
def get(self, auction_id: AuctionId) -> Auction:
row = self._conn.execute(auctions.select().where(auctions.c.id == auction_id)).first()
if not row:
raise Exception("Not found")
bid_rows = self._conn.execute(bids.select().where(bids.c.auction_id == auction_id)).fetchall()
return self._row_to_entity(row, bid_rows)
def _row_to_entity(self, auction_proxy: RowProxy, bids_proxies: List[RowProxy]) -> Auction:
auction_bids = [Bid(bid.id, bid.bidder_id, get_dollars(bid.amount)) for bid in bids_proxies]
return Auction(
auction_proxy.id,
auction_proxy.title,
get_dollars(auction_proxy.starting_price),
auction_bids,
auction_proxy.ends_at.replace(tzinfo=pytz.UTC),
auction_proxy.ended,
)
def save(self, auction: Auction) -> None:
raw_auction = {
"title": auction.title,
"starting_price": auction.starting_price.amount,
"current_price": auction.current_price.amount,
"ends_at": auction.ends_at,
"ended": auction._ended,
}
update_result = self._conn.execute(auctions.update(values=raw_auction, whereclause=auctions.c.id == auction.id))
if update_result.rowcount != 1:
self._conn.execute(auctions.insert(values=dict(raw_auction, id=auction.id)))
for bid in auction.bids:
if bid.id:
continue
result = self._conn.execute(
bids.insert(values={"auction_id": auction.id, "amount": bid.amount.amount, "bidder_id": bid.bidder_id})
)
(bid.id,) = result.inserted_primary_key
if auction.withdrawn_bids_ids:
self._conn.execute(bids.delete(whereclause=bids.c.id.in_(auction.withdrawn_bids_ids)))
for event in auction.domain_events:
self._event_bus.post(event)
auction.clear_events() | none | 1 | 2.362311 | 2 | |
agenda_administrativa/settings/base.py | pmsserrana/agenda | 0 | 6614179 | <filename>agenda_administrativa/settings/base.py
import os
import sys
# PATH vars
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
root = lambda *x: os.path.join(BASE_DIR, *x)
sys.path.insert(0, root('apps'))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'CHANGE THIS!!!'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
IN_TESTING = sys.argv[1:2] == ['test']
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
]
PROJECT_APPS = [
# thirdy parts
'rest_framework',
'rest_framework.authtoken',
'rest_framework_jwt',
'braces',
'crispy_forms',
'widget_tweaks',
'easy_select2',
'django_select2',
'compressor',
'debug_toolbar',
'ckeditor',
# local apps
'atividades.apps.AtividadesConfig',
'account.apps.AccountConfig',
'relatorios.apps.RelatoriosConfig',
# admin
# grappelli
'filebrowser',
'grappelli',
'django.contrib.admin',
]
INSTALLED_APPS += PROJECT_APPS
SITE_ID = 1
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
INTERNAL_IPS = ('127.0.0.1',)
ROOT_URLCONF = 'agenda_administrativa.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'agenda_administrativa.wsgi.application'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'agenda_administrativa',
'USER': 'postgres',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
# Internationalization
LANGUAGE_CODE = 'pt-br'
TIME_ZONE = 'America/Sao_Paulo'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
root('static'),
)
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = '/media/'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'DIRS': [
root('templates'),
],
'OPTIONS': {
'debug': DEBUG,
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
}
]
# Password validation
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 60
}
# .local.py overrides all the common settings.
try:
from .local import * # noqa
except ImportError:
pass
# importing test settings file if necessary
if IN_TESTING:
from .testing import * # noqa
# crispy forms
CRISPY_TEMPLATE_PACK = 'bootstrap3'
# login redirect
LOGIN_REDIRECT_URL = 'atividades:agenda_compartilhada'
LOGIN_URL = 'login'
LOGOUT_URL = 'logout'
GRAPPELLI_ADMIN_TITLE = "Agenda Administrativa"
SELECT2_JS = 'bower_components/select2/dist/js/select2.min.js'
SELECT2_CSS = 'bower_components/select2/dist/css/select2.css'
DATE_INPUT_FORMATS = ('%d/%m/%Y', '%d/%m/%y', '%Y-%m-%d',)
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'Custom',
'toolbar_Custom': [
['TextColor', 'BGColor'],
['Styles', 'Format', 'Font', 'FontSize'],
['Bold', 'Italic', 'Underline'],
['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
['Link', 'Unlink'],
['RemoveFormat', 'Source'],
],
'height': 100,
'width': 800,
}
}
| <filename>agenda_administrativa/settings/base.py
import os
import sys
# PATH vars
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
root = lambda *x: os.path.join(BASE_DIR, *x)
sys.path.insert(0, root('apps'))
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'CHANGE THIS!!!'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
IN_TESTING = sys.argv[1:2] == ['test']
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.sites',
]
PROJECT_APPS = [
# thirdy parts
'rest_framework',
'rest_framework.authtoken',
'rest_framework_jwt',
'braces',
'crispy_forms',
'widget_tweaks',
'easy_select2',
'django_select2',
'compressor',
'debug_toolbar',
'ckeditor',
# local apps
'atividades.apps.AtividadesConfig',
'account.apps.AccountConfig',
'relatorios.apps.RelatoriosConfig',
# admin
# grappelli
'filebrowser',
'grappelli',
'django.contrib.admin',
]
INSTALLED_APPS += PROJECT_APPS
SITE_ID = 1
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
INTERNAL_IPS = ('127.0.0.1',)
ROOT_URLCONF = 'agenda_administrativa.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'agenda_administrativa.wsgi.application'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'agenda_administrativa',
'USER': 'postgres',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
# Internationalization
LANGUAGE_CODE = 'pt-br'
TIME_ZONE = 'America/Sao_Paulo'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
root('static'),
)
# See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url
MEDIA_URL = '/media/'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'DIRS': [
root('templates'),
],
'OPTIONS': {
'debug': DEBUG,
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.template.context_processors.debug',
'django.template.context_processors.i18n',
'django.template.context_processors.media',
'django.template.context_processors.static',
'django.template.context_processors.tz',
'django.contrib.messages.context_processors.messages',
],
},
}
]
# Password validation
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication',
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
'PAGE_SIZE': 60
}
# .local.py overrides all the common settings.
try:
from .local import * # noqa
except ImportError:
pass
# importing test settings file if necessary
if IN_TESTING:
from .testing import * # noqa
# crispy forms
CRISPY_TEMPLATE_PACK = 'bootstrap3'
# login redirect
LOGIN_REDIRECT_URL = 'atividades:agenda_compartilhada'
LOGIN_URL = 'login'
LOGOUT_URL = 'logout'
GRAPPELLI_ADMIN_TITLE = "Agenda Administrativa"
SELECT2_JS = 'bower_components/select2/dist/js/select2.min.js'
SELECT2_CSS = 'bower_components/select2/dist/css/select2.css'
DATE_INPUT_FORMATS = ('%d/%m/%Y', '%d/%m/%y', '%Y-%m-%d',)
CKEDITOR_CONFIGS = {
'default': {
'toolbar': 'Custom',
'toolbar_Custom': [
['TextColor', 'BGColor'],
['Styles', 'Format', 'Font', 'FontSize'],
['Bold', 'Italic', 'Underline'],
['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'],
['Link', 'Unlink'],
['RemoveFormat', 'Source'],
],
'height': 100,
'width': 800,
}
}
| en | 0.717141 | # PATH vars # SECURITY WARNING: keep the secret key used in production secret! # SECURITY WARNING: don't run with debug turned on in production! # Application definition # thirdy parts # local apps # admin # grappelli # Python dotted path to the WSGI application used by Django's runserver. # Database # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP. # Set to empty string for default. # Internationalization # Static files (CSS, JavaScript, Images) # See: https://docs.djangoproject.com/en/dev/ref/settings/#static-root # Additional locations of static files # See: https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-root # See: https://docs.djangoproject.com/en/dev/ref/settings/#media-url # Password validation # .local.py overrides all the common settings. # noqa # importing test settings file if necessary # noqa # crispy forms # login redirect | 1.765102 | 2 |
5-Dataset_Class/custom_dataset.py | mntalha/Efficient-PyTorch_Dataloader_Application | 0 | 6614180 | <reponame>mntalha/Efficient-PyTorch_Dataloader_Application
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 9 14:03:58 2021
@author: talha
"""
import os
from torch.utils.data import Dataset, DataLoader
from PIL import Image
import torchvision.transforms as transforms
import timeit
class CustomImageDataset(Dataset):
def __init__(self, img_path,transform =True):
self.img_path = img_path
self.transform = transform
if self.check_path(self.img_path):
self.img_name_list = os.listdir(self.img_path)
self.transform_operation = transforms.Compose([
transforms.Resize([28,28]),
transforms.ToTensor(),
])
def check_path(self,path):
#check path control
if isinstance(path, str): #Image path is a string
if os.path.exists(path):
#☺print ("Path is exist")
return True
else:
raise FileNotFoundError('Path is not found on your system')
##you can control with len(object)
def __len__(self):
return len(self.img_name_list)
def __getitem__(self, idx):
img_name =os.path.join(self.img_path,self.img_name_list[idx])
#cv2 could be used but pillow has straightforward structure
image = Image.open(img_name).convert("L") #gray scale image
if self.transform:
image = self.transform_operation(image)
return (image)
if __name__ == "__main__":
img_path = "../3-Data/train_img"
dataset=CustomImageDataset(img_path)
trainloader = DataLoader(dataset=dataset,batch_size=64,num_workers=0, shuffle=False,pin_memory=False)
start = timeit.default_timer()
for i in trainloader:
# print(i)
print("The time difference is :", timeit.default_timer() - start)
break
| # -*- coding: utf-8 -*-
"""
Created on Thu Sep 9 14:03:58 2021
@author: talha
"""
import os
from torch.utils.data import Dataset, DataLoader
from PIL import Image
import torchvision.transforms as transforms
import timeit
class CustomImageDataset(Dataset):
def __init__(self, img_path,transform =True):
self.img_path = img_path
self.transform = transform
if self.check_path(self.img_path):
self.img_name_list = os.listdir(self.img_path)
self.transform_operation = transforms.Compose([
transforms.Resize([28,28]),
transforms.ToTensor(),
])
def check_path(self,path):
#check path control
if isinstance(path, str): #Image path is a string
if os.path.exists(path):
#☺print ("Path is exist")
return True
else:
raise FileNotFoundError('Path is not found on your system')
##you can control with len(object)
def __len__(self):
return len(self.img_name_list)
def __getitem__(self, idx):
img_name =os.path.join(self.img_path,self.img_name_list[idx])
#cv2 could be used but pillow has straightforward structure
image = Image.open(img_name).convert("L") #gray scale image
if self.transform:
image = self.transform_operation(image)
return (image)
if __name__ == "__main__":
img_path = "../3-Data/train_img"
dataset=CustomImageDataset(img_path)
trainloader = DataLoader(dataset=dataset,batch_size=64,num_workers=0, shuffle=False,pin_memory=False)
start = timeit.default_timer()
for i in trainloader:
# print(i)
print("The time difference is :", timeit.default_timer() - start)
break | en | 0.83658 | # -*- coding: utf-8 -*- Created on Thu Sep 9 14:03:58 2021 @author: talha #check path control #Image path is a string #☺print ("Path is exist") ##you can control with len(object) #cv2 could be used but pillow has straightforward structure #gray scale image # print(i) | 2.638173 | 3 |
tkinter/elements.py | LucasRibeiroRJBR/genshin_app | 1 | 6614181 | from tkinter import *
import tkinter.ttk as ttk
import pyglet
import pygame
import util.images
pygame.init()
def sound():
pygame.mixer.music.load("sound/element.mp3")
pygame.mixer.music.play()
def aanemo():
pygame.mixer.music.load("sound/element.mp3")
pygame.mixer.music.play()
exec("l = ttk.Button(container_char, image=util.images.get('jean'), style='my.TLabel', command=sound).grid(row=0,column=0)\n"
"l = ttk.Button(container_char, image=util.images.get('sucrose'), style='my.TLabel', command=sound).grid(row=0,column=1)\n"
"l = ttk.Button(container_char, image=util.images.get('traveler_Anemo'), style='my.TLabel', command=sound).grid(row=0,column=2)\n"
"l = ttk.Button(container_char, image=util.images.get('venti'), style='my.TLabel', command=sound).grid(row=0,column=3)\n"
"l = ttk.Button(container_char, image=util.images.get('xiao'), style='my.TLabel', command=sound).grid(row=0,column=4)")
def ccryo():
pygame.mixer.music.load("sound/element.mp3")
pygame.mixer.music.play()
exec("l = ttk.Button(container_char).grid(row=0,column=0)\n"
"l.destroy()\n"
"l = ttk.Button(container_char, image=util.images.get('chongyun'), style='my.TLabel', command=sound).grid(row=0,column=0)\n"
"l = ttk.Button(container_char, image=util.images.get('diona'), style='my.TLabel', command=sound).grid(row=0,column=1)\n"
"l = ttk.Button(container_char, image=util.images.get('kaeya'), style='my.TLabel', command=sound).grid(row=0,column=2)\n"
"l = ttk.Button(container_char, image=util.images.get('qiqi'), style='my.TLabel', command=sound).grid(row=0,column=3)")
root = Tk()
root.geometry("600x500")
# root.resizable(False,False)
root.config(bg="#202020")
root.columnconfigure(0, weight=2)
root.rowconfigure(0, weight=2)
pyglet.font.add_file("font/HYWenHei.ttf")
style = ttk.Style()
style.theme_use('clam')
style.configure('my.TButton', background="#202020", relief=FLAT, padding=0, bordercolor="#202020", borderwidth=-1)
style.configure('my.TLabel', padding=0, boderwidth=0, background="#202020", borderwidth=-1)
container = Frame(root, background="#202020")
container.grid(row=0, column=0)
letreiro = ttk.Label(container, text="Elements", font=("HYWenHei-85W", 25), foreground="White", background="#202020")
letreiro.grid(row=0, columnspan=7)
bt_anemo = ttk.Button(container, image=util.images.get('anemo'), style="my.TButton", command=aanemo)
bt_cryo = ttk.Button(container, image=util.images.get('cryo'), style="my.TButton", command=ccryo)
bt_dendro = ttk.Button(container, image=util.images.get('dendro'), style="my.TButton", command=sound)
bt_electro = ttk.Button(container, image=util.images.get('electro'), style="my.TButton", command=sound)
bt_geo = ttk.Button(container, image=util.images.get('geo'), style="my.TButton", command=sound)
bt_hydro = ttk.Button(container, image=util.images.get('hydro'), style="my.TButton", command=sound)
bt_pyro = ttk.Button(container, image=util.images.get('pyro'), style="my.TButton", command=sound)
bt_pyro.grid(row=1, column=0)
bt_hydro.grid(row=1, column=1)
bt_anemo.grid(row=1, column=2)
bt_electro.grid(row=1, column=3)
bt_dendro.grid(row=1, column=4)
bt_cryo.grid(row=1, column=5)
bt_geo.grid(row=1, column=6)
container_char = Frame(root, background="#202020")
container_char.grid(row=1, column=0)
l_vazio = ttk.Label(container_char, image=util.images.get('vazio'), style="my.TLabel").grid(row=0, column=0)
root.mainloop()
| from tkinter import *
import tkinter.ttk as ttk
import pyglet
import pygame
import util.images
pygame.init()
def sound():
pygame.mixer.music.load("sound/element.mp3")
pygame.mixer.music.play()
def aanemo():
pygame.mixer.music.load("sound/element.mp3")
pygame.mixer.music.play()
exec("l = ttk.Button(container_char, image=util.images.get('jean'), style='my.TLabel', command=sound).grid(row=0,column=0)\n"
"l = ttk.Button(container_char, image=util.images.get('sucrose'), style='my.TLabel', command=sound).grid(row=0,column=1)\n"
"l = ttk.Button(container_char, image=util.images.get('traveler_Anemo'), style='my.TLabel', command=sound).grid(row=0,column=2)\n"
"l = ttk.Button(container_char, image=util.images.get('venti'), style='my.TLabel', command=sound).grid(row=0,column=3)\n"
"l = ttk.Button(container_char, image=util.images.get('xiao'), style='my.TLabel', command=sound).grid(row=0,column=4)")
def ccryo():
pygame.mixer.music.load("sound/element.mp3")
pygame.mixer.music.play()
exec("l = ttk.Button(container_char).grid(row=0,column=0)\n"
"l.destroy()\n"
"l = ttk.Button(container_char, image=util.images.get('chongyun'), style='my.TLabel', command=sound).grid(row=0,column=0)\n"
"l = ttk.Button(container_char, image=util.images.get('diona'), style='my.TLabel', command=sound).grid(row=0,column=1)\n"
"l = ttk.Button(container_char, image=util.images.get('kaeya'), style='my.TLabel', command=sound).grid(row=0,column=2)\n"
"l = ttk.Button(container_char, image=util.images.get('qiqi'), style='my.TLabel', command=sound).grid(row=0,column=3)")
root = Tk()
root.geometry("600x500")
# root.resizable(False,False)
root.config(bg="#202020")
root.columnconfigure(0, weight=2)
root.rowconfigure(0, weight=2)
pyglet.font.add_file("font/HYWenHei.ttf")
style = ttk.Style()
style.theme_use('clam')
style.configure('my.TButton', background="#202020", relief=FLAT, padding=0, bordercolor="#202020", borderwidth=-1)
style.configure('my.TLabel', padding=0, boderwidth=0, background="#202020", borderwidth=-1)
container = Frame(root, background="#202020")
container.grid(row=0, column=0)
letreiro = ttk.Label(container, text="Elements", font=("HYWenHei-85W", 25), foreground="White", background="#202020")
letreiro.grid(row=0, columnspan=7)
bt_anemo = ttk.Button(container, image=util.images.get('anemo'), style="my.TButton", command=aanemo)
bt_cryo = ttk.Button(container, image=util.images.get('cryo'), style="my.TButton", command=ccryo)
bt_dendro = ttk.Button(container, image=util.images.get('dendro'), style="my.TButton", command=sound)
bt_electro = ttk.Button(container, image=util.images.get('electro'), style="my.TButton", command=sound)
bt_geo = ttk.Button(container, image=util.images.get('geo'), style="my.TButton", command=sound)
bt_hydro = ttk.Button(container, image=util.images.get('hydro'), style="my.TButton", command=sound)
bt_pyro = ttk.Button(container, image=util.images.get('pyro'), style="my.TButton", command=sound)
bt_pyro.grid(row=1, column=0)
bt_hydro.grid(row=1, column=1)
bt_anemo.grid(row=1, column=2)
bt_electro.grid(row=1, column=3)
bt_dendro.grid(row=1, column=4)
bt_cryo.grid(row=1, column=5)
bt_geo.grid(row=1, column=6)
container_char = Frame(root, background="#202020")
container_char.grid(row=1, column=0)
l_vazio = ttk.Label(container_char, image=util.images.get('vazio'), style="my.TLabel").grid(row=0, column=0)
root.mainloop()
| pl | 0.336981 | # root.resizable(False,False) | 3.120522 | 3 |
TX/utils.py | trinity-project/trinity | 60 | 6614182 | import binascii
import time
import requests
from base58 import b58decode
from neocore.KeyPair import KeyPair
from neocore.UInt160 import UInt160
from neocore.UInt256 import UInt256
from neocore.BigInteger import BigInteger
from neocore.Cryptography.Crypto import Crypto
from TX.config import headers, NODEURL
def hex_reverse(input):
tmp=binascii.unhexlify(input[2:])
be=bytearray(tmp)
be.reverse()
output=binascii.hexlify(be).decode()
return output
def int_to_hex(input):
return binascii.hexlify(bytes([int(input)])).decode()
def pubkeyToAddressHash(pubkey):
pubkey="21"+pubkey+"ac"
sc =pubkey.encode()
sc_hash=Crypto.ToScriptHash(sc).ToString2()
return sc_hash
def pubkeyToAddress(pubkey):
pubkey = "21" + pubkey + "ac"
sc =pubkey.encode()
address=Crypto.ToAddress(Crypto.ToScriptHash(sc))
return address
def ToAddresstHash(address):
data = b58decode(address)
if len(data) != 25:
raise ValueError('Not correct Address, wrong length.')
if data[0] != 23:
raise ValueError('Not correct Coin Version')
checksum = Crypto.Default().Hash256(data[:21])[:4]
if checksum != data[21:]:
raise Exception('Address format error')
return UInt160(data=data[1:21])
def createVerifyScript(script):
tmp = hex(int(len(script)/2))[2:]
if len(tmp) % 2 == 1:
tmp = "0" + tmp
be=bytearray (binascii.unhexlify(tmp))
be.reverse()
hex_len=binascii.hexlify(be).decode()
verify_script="".join([hex_len, script])
return verify_script
def createTxid(txData):
ba = binascii.unhexlify(txData)
hash = Crypto.Hash256(ba)
return "0x"+UInt256(data=hash).ToString()
def createMultiSigAddress(script):
scriptHash=Crypto.ToScriptHash(script)
address=Crypto.ToAddress(scriptHash)
return address
def create_opdata(address_from, address_to, value, contract_hash):
op_data = ""
value = binascii.hexlify(BigInteger(value * pow(10, 8)).ToByteArray()).decode()
scripthash_from = ToAddresstHash(address_from).ToString2()
scripthash_to = ToAddresstHash(address_to).ToString2()
method = binascii.hexlify("transfer".encode()).decode()
invoke_args = [value, scripthash_to, scripthash_from]
for item in invoke_args:
op_data += "".join([int_to_hex(len(item) / 2), item])
op_data += "53" # PUSH3
op_data += "c1" # PACK
op_data += int_to_hex(len(method) / 2)
op_data += method
op_data += "67" # APPCALL
op_data += hex_reverse(contract_hash)
op_data += "f1" # maybe THROWIFNOT
return op_data
def createRSMCContract(hashSelf,pubkeySelf,hashOther,pubkeyOther,magicTimestamp):
magicTimestamp = binascii.hexlify(str(magicTimestamp).encode()).decode()
length=hex(int(len(magicTimestamp)/2))[2:]
magicTimestamp=length+magicTimestamp
contractTemplate="5dc56b6c766b00527ac46c766b51527ac46c766b52527ac461{magicTimestamp}6c766b53527ac4616829537" \
"97374656d2e457865637574696f6e456e67696e652e476574536372697074436f6e7461696e65726c766b5452" \
"<KEY>" \
"<KEY>" \
"6c766b58c36168154e656f2e4174747269627574652e476574446174616114{hashOther}9c6c766b59527ac4" \
"6c766b59c364c300616c766b00c36121{pubkeySelf}ac642f006c766b51c36121{pubkeyOther}<KEY>" \
"766b00c36121{pubkeyOther}ac642f006c766b51c36121{pubkeySelf}<KEY>" \
"c462b8006c766b58c36168154e656f2e4174747269627574652e476574446174616114{hashSelf}9c6c766b5" \
"b527ac46c766b5bc3644c00616c766b52c36c766b54c3617c6599016c766b5c527ac46c766b5cc36422006c76" \
"6b52c36c766b00c36c766b51c3615272654a006c766b5a527ac4623700006c766b5a527ac4622c00616c766b5" \
"<KEY>" \
"6656c56b6c766b00527ac46c766b51527ac46c766b52527ac4616168184e656f2e426c6f636b636861696e2e4" \
"<KEY>" \
"6c766b51c36121{pubkeySelf}ac642f006c766b52c36121{pubkeyOther}<KEY>" \
"{pubkeyOther}ac642f006c766b52c36121{pubkeySelf}ac62040000620400516c766b55527ac4620e00006c" \
"<KEY>" \
"<KEY>" \
"636b2e4765745472616e73616374696f6e736c766b53527ac46c766b51c361681d4e656f2e5472616e7361637" \
"<KEY>" \
"<KEY>" \
"<KEY>" \
"766b5ac3c36c766b5b527ac4616c766b5bc36168174e656f2e5472616e73616374696f6e2e476574486173686" \
"<KEY>" \
"<KEY>" \
"<KEY>"
RSMCContract=contractTemplate.format(hashOther=hashOther,pubkeySelf=pubkeySelf,hashSelf=hashSelf,
pubkeyOther=pubkeyOther,magicTimestamp=magicTimestamp)
return {
"script":RSMCContract,
"address":createMultiSigAddress(RSMCContract)
}
def createHTLCContract(futureTimestamp,pubkeySelf,pubkeyOther,hashR):
futureTimestamp=hex_reverse(hex(int(futureTimestamp)))
contractTemplate="<KEY>" \
"26c6f636b636861696e2e4765744865696768746168184e656f2e426c6f636b636861696e2e4765744865616465" \
"726c766b54527ac46c766b00c36121{pubkeyA}ac642f006c766b51c36121{<KEY>" \
"1{pubkeyB}ac642f006c766b51c36121{pubkeyA}<KEY>" \
"656f2e4865616465722e47657454696d657374616d7004{futureTimestamp}9f6c766b56527ac46c766b56c364" \
"3600616c766b55c36422006c766b53c36114{hashR}9c620400006c766b57527ac46212006c766b55c36c766b57" \
"527ac46203006c766b57c3616c7566"
HTLCContract=contractTemplate.format(futureTimestamp=futureTimestamp,pubkeyA=pubkeySelf,pubkeyB=pubkeyOther,hashR=hashR)
return {
"script":HTLCContract,
"address":createMultiSigAddress(HTLCContract)
}
def createMultiSigContract(pubkeySelf,pubkeyOther):
contractTemplate = "53c56b6c766b00527ac46c766b51527ac4616c766b00c36121{pubkeySelf}<KEY>" \
"21{pubkeyOther}ac635f006c766b00c36121{pubkeyOther}ac642f006c766b51c36121{pubkeySelf}" \
"<KEY>"
script=contractTemplate.format(pubkeySelf=pubkeySelf,pubkeyOther=pubkeyOther)
address=createMultiSigAddress(script)
return {
"script":script,
"address":address
}
def blockheight_to_script(input):
input=hex(input)[2:]
if len(input) % 2 == 1:
input = "0" + input
be=bytearray (binascii.unhexlify(input))
be.reverse()
revese_hex=binascii.hexlify(be).decode()
revese_hex_len=binascii.hexlify(bytes([int(len(revese_hex)/2)])).decode()
len_all=str(83+int(revese_hex_len))
output="".join([len_all,revese_hex_len, revese_hex])
return output
def R_to_script(input):
hex_R=binascii.hexlify(input.encode()).decode()
hex_R_len=binascii.hexlify(bytes([int(len(hex_R)/2)])).decode()
len_all="c3"
output="".join([len_all,hex_R_len, hex_R])
return output
def privtkey_sign(txData,privteKey):
return binascii.hexlify(Crypto.Sign(message=txData, private_key=privteKey)).decode()
def privtKey_to_publicKey(privtKey):
pk=binascii.unhexlify(privtKey)
keypair = KeyPair(pk)
vk=keypair.PublicKey.encode_point(True).decode()
return vk
def sign(txData,privtKey):
signature = privtkey_sign(txData,privtKey)
publicKey=privtKey_to_publicKey(privtKey)
rawData=txData+"01"+"41"+"40"+signature+"23"+"21"+publicKey+"ac"
return rawData
def get_neovout_by_address(address,amount):
data = {
"jsonrpc": "2.0",
"method": "getNeoVout",
"params": [address,amount],
"id": 1
}
res = requests.post(NODEURL, headers=headers, json=data).json()
return res["result"]
def get_gasvout_by_address(address,amount):
data = {
"jsonrpc": "2.0",
"method": "getGasVout",
"params": [address,amount],
"id": 1
}
res = requests.post(NODEURL, headers=headers, json=data).json()
return res["result"]
if __name__=="__main__":
# print(b58decode("b58decode"))
print (blockheight_to_script(543367))
print (R_to_script("eefc152a46960a4d3092146ae8b27890c3a3d12db14f6f7309d3f5c41b4e456d"))
print (createTxid("80000220d904f61978b83b706445d2c418e336de4d6261d4f0045b02bf190150410fa91bb27e69ed1c32ab5a34232283957aac0f54481a92e34c9107f234c00000029b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc500e1f505000000009f4ae7295ca9cf93a5bbad7fb715116c3adc55f79b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc500e9a43500000000d904f61978b83b706445d2c418e336de4d6261d4"))
# print (blockheight_to_script(1380761))
# print (createTxid("d101a00400ca9a3b140069ec6703aa90a51280ab74eb92cb09cca0549514dfee2d95daf8b67b960aaf997900ab94abc3fd1b53c1087472616e7366657267f1dfcf0051ec48ec95c8d0569e0b95075d099d84f10400ca9a3b140069ec6703aa90a51280ab74eb92cb09cca05495142099925aaeee225009fc51b599c71fee77bd30ca53c1087472616e7366657267f1dfcf0051ec48ec95c8d0569e0b95075d099d84f100000000000000000320dfee2d95daf8b67b960aaf997900ab94abc3fd1b202099925aaeee225009fc51b599c71fee77bd30caf0045ac46e4b0000"))
# sadf=createRSMCContract(hashSelf="3503e814a07c87a94870295c53be41bb289cde87",hashOther="f196e324402cc78ba506a8b28d79a3ee6951f50f",pubkeyOther="034e9d2751e1fec65a6a42bc097bdf55c7a79762df7d6e970277f46405c376683a",pubkeySelf="03eb0881d1d64754d50255bf16079ed6cbc3982463a8904cb919422b39178bef3f",magicTimestamp=time.time())
# print (sadf)
| import binascii
import time
import requests
from base58 import b58decode
from neocore.KeyPair import KeyPair
from neocore.UInt160 import UInt160
from neocore.UInt256 import UInt256
from neocore.BigInteger import BigInteger
from neocore.Cryptography.Crypto import Crypto
from TX.config import headers, NODEURL
def hex_reverse(input):
tmp=binascii.unhexlify(input[2:])
be=bytearray(tmp)
be.reverse()
output=binascii.hexlify(be).decode()
return output
def int_to_hex(input):
return binascii.hexlify(bytes([int(input)])).decode()
def pubkeyToAddressHash(pubkey):
pubkey="21"+pubkey+"ac"
sc =pubkey.encode()
sc_hash=Crypto.ToScriptHash(sc).ToString2()
return sc_hash
def pubkeyToAddress(pubkey):
pubkey = "21" + pubkey + "ac"
sc =pubkey.encode()
address=Crypto.ToAddress(Crypto.ToScriptHash(sc))
return address
def ToAddresstHash(address):
data = b58decode(address)
if len(data) != 25:
raise ValueError('Not correct Address, wrong length.')
if data[0] != 23:
raise ValueError('Not correct Coin Version')
checksum = Crypto.Default().Hash256(data[:21])[:4]
if checksum != data[21:]:
raise Exception('Address format error')
return UInt160(data=data[1:21])
def createVerifyScript(script):
tmp = hex(int(len(script)/2))[2:]
if len(tmp) % 2 == 1:
tmp = "0" + tmp
be=bytearray (binascii.unhexlify(tmp))
be.reverse()
hex_len=binascii.hexlify(be).decode()
verify_script="".join([hex_len, script])
return verify_script
def createTxid(txData):
ba = binascii.unhexlify(txData)
hash = Crypto.Hash256(ba)
return "0x"+UInt256(data=hash).ToString()
def createMultiSigAddress(script):
scriptHash=Crypto.ToScriptHash(script)
address=Crypto.ToAddress(scriptHash)
return address
def create_opdata(address_from, address_to, value, contract_hash):
op_data = ""
value = binascii.hexlify(BigInteger(value * pow(10, 8)).ToByteArray()).decode()
scripthash_from = ToAddresstHash(address_from).ToString2()
scripthash_to = ToAddresstHash(address_to).ToString2()
method = binascii.hexlify("transfer".encode()).decode()
invoke_args = [value, scripthash_to, scripthash_from]
for item in invoke_args:
op_data += "".join([int_to_hex(len(item) / 2), item])
op_data += "53" # PUSH3
op_data += "c1" # PACK
op_data += int_to_hex(len(method) / 2)
op_data += method
op_data += "67" # APPCALL
op_data += hex_reverse(contract_hash)
op_data += "f1" # maybe THROWIFNOT
return op_data
def createRSMCContract(hashSelf,pubkeySelf,hashOther,pubkeyOther,magicTimestamp):
magicTimestamp = binascii.hexlify(str(magicTimestamp).encode()).decode()
length=hex(int(len(magicTimestamp)/2))[2:]
magicTimestamp=length+magicTimestamp
contractTemplate="5dc56b6c766b00527ac46c766b51527ac46c766b52527ac461{magicTimestamp}6c766b53527ac4616829537" \
"97374656d2e457865637574696f6e456e67696e652e476574536372697074436f6e7461696e65726c766b5452" \
"<KEY>" \
"<KEY>" \
"6c766b58c36168154e656f2e4174747269627574652e476574446174616114{hashOther}9c6c766b59527ac4" \
"6c766b59c364c300616c766b00c36121{pubkeySelf}ac642f006c766b51c36121{pubkeyOther}<KEY>" \
"766b00c36121{pubkeyOther}ac642f006c766b51c36121{pubkeySelf}<KEY>" \
"c462b8006c766b58c36168154e656f2e4174747269627574652e476574446174616114{hashSelf}9c6c766b5" \
"b527ac46c766b5bc3644c00616c766b52c36c766b54c3617c6599016c766b5c527ac46c766b5cc36422006c76" \
"6b52c36c766b00c36c766b51c3615272654a006c766b5a527ac4623700006c766b5a527ac4622c00616c766b5" \
"<KEY>" \
"6656c56b6c766b00527ac46c766b51527ac46c766b52527ac4616168184e656f2e426c6f636b636861696e2e4" \
"<KEY>" \
"6c766b51c36121{pubkeySelf}ac642f006c766b52c36121{pubkeyOther}<KEY>" \
"{pubkeyOther}ac642f006c766b52c36121{pubkeySelf}ac62040000620400516c766b55527ac4620e00006c" \
"<KEY>" \
"<KEY>" \
"636b2e4765745472616e73616374696f6e736c766b53527ac46c766b51c361681d4e656f2e5472616e7361637" \
"<KEY>" \
"<KEY>" \
"<KEY>" \
"766b5ac3c36c766b5b527ac4616c766b5bc36168174e656f2e5472616e73616374696f6e2e476574486173686" \
"<KEY>" \
"<KEY>" \
"<KEY>"
RSMCContract=contractTemplate.format(hashOther=hashOther,pubkeySelf=pubkeySelf,hashSelf=hashSelf,
pubkeyOther=pubkeyOther,magicTimestamp=magicTimestamp)
return {
"script":RSMCContract,
"address":createMultiSigAddress(RSMCContract)
}
def createHTLCContract(futureTimestamp,pubkeySelf,pubkeyOther,hashR):
futureTimestamp=hex_reverse(hex(int(futureTimestamp)))
contractTemplate="<KEY>" \
"26c6f636b636861696e2e4765744865696768746168184e656f2e426c6f636b636861696e2e4765744865616465" \
"726c766b54527ac46c766b00c36121{pubkeyA}ac642f006c766b51c36121{<KEY>" \
"1{pubkeyB}ac642f006c766b51c36121{pubkeyA}<KEY>" \
"656f2e4865616465722e47657454696d657374616d7004{futureTimestamp}9f6c766b56527ac46c766b56c364" \
"3600616c766b55c36422006c766b53c36114{hashR}9c620400006c766b57527ac46212006c766b55c36c766b57" \
"527ac46203006c766b57c3616c7566"
HTLCContract=contractTemplate.format(futureTimestamp=futureTimestamp,pubkeyA=pubkeySelf,pubkeyB=pubkeyOther,hashR=hashR)
return {
"script":HTLCContract,
"address":createMultiSigAddress(HTLCContract)
}
def createMultiSigContract(pubkeySelf,pubkeyOther):
contractTemplate = "53c56b6c766b00527ac46c766b51527ac4616c766b00c36121{pubkeySelf}<KEY>" \
"21{pubkeyOther}ac635f006c766b00c36121{pubkeyOther}ac642f006c766b51c36121{pubkeySelf}" \
"<KEY>"
script=contractTemplate.format(pubkeySelf=pubkeySelf,pubkeyOther=pubkeyOther)
address=createMultiSigAddress(script)
return {
"script":script,
"address":address
}
def blockheight_to_script(input):
input=hex(input)[2:]
if len(input) % 2 == 1:
input = "0" + input
be=bytearray (binascii.unhexlify(input))
be.reverse()
revese_hex=binascii.hexlify(be).decode()
revese_hex_len=binascii.hexlify(bytes([int(len(revese_hex)/2)])).decode()
len_all=str(83+int(revese_hex_len))
output="".join([len_all,revese_hex_len, revese_hex])
return output
def R_to_script(input):
hex_R=binascii.hexlify(input.encode()).decode()
hex_R_len=binascii.hexlify(bytes([int(len(hex_R)/2)])).decode()
len_all="c3"
output="".join([len_all,hex_R_len, hex_R])
return output
def privtkey_sign(txData,privteKey):
return binascii.hexlify(Crypto.Sign(message=txData, private_key=privteKey)).decode()
def privtKey_to_publicKey(privtKey):
pk=binascii.unhexlify(privtKey)
keypair = KeyPair(pk)
vk=keypair.PublicKey.encode_point(True).decode()
return vk
def sign(txData,privtKey):
signature = privtkey_sign(txData,privtKey)
publicKey=privtKey_to_publicKey(privtKey)
rawData=txData+"01"+"41"+"40"+signature+"23"+"21"+publicKey+"ac"
return rawData
def get_neovout_by_address(address,amount):
data = {
"jsonrpc": "2.0",
"method": "getNeoVout",
"params": [address,amount],
"id": 1
}
res = requests.post(NODEURL, headers=headers, json=data).json()
return res["result"]
def get_gasvout_by_address(address,amount):
data = {
"jsonrpc": "2.0",
"method": "getGasVout",
"params": [address,amount],
"id": 1
}
res = requests.post(NODEURL, headers=headers, json=data).json()
return res["result"]
if __name__=="__main__":
# print(b58decode("b58decode"))
print (blockheight_to_script(543367))
print (R_to_script("eefc152a46960a4d3092146ae8b27890c3a3d12db14f6f7309d3f5c41b4e456d"))
print (createTxid("80000220d904f61978b83b706445d2c418e336de4d6261d4f0045b02bf190150410fa91bb27e69ed1c32ab5a34232283957aac0f54481a92e34c9107f234c00000029b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc500e1f505000000009f4ae7295ca9cf93a5bbad7fb715116c3adc55f79b7cffdaa674beae0f930ebe6085af9093e5fe56b34a5c220ccdcf6efc336fc500e9a43500000000d904f61978b83b706445d2c418e336de4d6261d4"))
# print (blockheight_to_script(1380761))
# print (createTxid("d101a00400ca9a3b140069ec6703aa90a51280ab74eb92cb09cca0549514dfee2d95daf8b67b960aaf997900ab94abc3fd1b53c1087472616e7366657267f1dfcf0051ec48ec95c8d0569e0b95075d099d84f10400ca9a3b140069ec6703aa90a51280ab74eb92cb09cca05495142099925aaeee225009fc51b599c71fee77bd30ca53c1087472616e7366657267f1dfcf0051ec48ec95c8d0569e0b95075d099d84f100000000000000000320dfee2d95daf8b67b960aaf997900ab94abc3fd1b202099925aaeee225009fc51b599c71fee77bd30caf0045ac46e4b0000"))
# sadf=createRSMCContract(hashSelf="3503e814a07c87a94870295c53be41bb289cde87",hashOther="f196e324402cc78ba506a8b28d79a3ee6951f50f",pubkeyOther="034e9d2751e1fec65a6a42bc097bdf55c7a79762df7d6e970277f46405c376683a",pubkeySelf="03eb0881d1d64754d50255bf16079ed6cbc3982463a8904cb919422b39178bef3f",magicTimestamp=time.time())
# print (sadf)
| en | 0.38316 | # PUSH3 # PACK # APPCALL # maybe THROWIFNOT # print(b58decode("b58decode")) # print (blockheight_to_script(1380761)) # print (createTxid("d101a00400ca9a3b140069ec6703aa90a51280ab74eb92cb09cca0549514dfee2d95daf8b67b960aaf997900ab94abc3fd1b53c1087472616e7366657267f1dfcf0051ec48ec95c8d0569e0b95075d099d84f10400ca9a3b140069ec6703aa90a51280ab74eb92cb09cca05495142099925aaeee225009fc51b599c71fee77bd30ca53c1087472616e7366657267f1dfcf0051ec48ec95c8d0569e0b95075d099d84f100000000000000000320dfee2d95daf8b67b960aaf997900ab94abc3fd1b202099925aaeee225009fc51b599c71fee77bd30caf0045ac46e4b0000")) # sadf=createRSMCContract(hashSelf="3503e814a07c87a94870295c53be41bb289cde87",hashOther="f196e324402cc78ba506a8b28d79a3ee6951f50f",pubkeyOther="034e9d2751e1fec65a6a42bc097bdf55c7a79762df7d6e970277f46405c376683a",pubkeySelf="03eb0881d1d64754d50255bf16079ed6cbc3982463a8904cb919422b39178bef3f",magicTimestamp=time.time()) # print (sadf) | 2.209821 | 2 |
pymontecarlo_gui/options/model/photon_scattering_cross_section.py | pymontecarlo/pymontecarlo-gui | 0 | 6614183 | """
Photon scattering cross section models.
"""
# Standard library modules.
# Third party modules.
# Local modules.
from pymontecarlo_gui.options.model.base import ModelFieldBase
# Globals and constants variables.
class PhotonScatteringCrossSectionModelField(ModelFieldBase):
def title(self):
return "Photon scattering cross section"
| """
Photon scattering cross section models.
"""
# Standard library modules.
# Third party modules.
# Local modules.
from pymontecarlo_gui.options.model.base import ModelFieldBase
# Globals and constants variables.
class PhotonScatteringCrossSectionModelField(ModelFieldBase):
def title(self):
return "Photon scattering cross section"
| en | 0.546271 | Photon scattering cross section models. # Standard library modules. # Third party modules. # Local modules. # Globals and constants variables. | 1.854289 | 2 |
colibri_battery/scripts/battery_pub.py | shevchenco123/28-Constellations | 0 | 6614184 | #!/usr/bin/env python
import rospy
from colibri_battery.msg import Battery
import serial
import time
import string
import logging.handlers
VT = []
ASC2_num = 30
B_v = ()
Battery_send_num = []
B_V_bat_cell = []
B_Temp = []
t = serial.Serial('/dev/battery', 9600)
t.close()
#LOG_FILE = '/home/colibri/colibri_ws/src/colibri_battery/log/bat_state.log'
#handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024, backupCount=5)
#fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s'
#formatter = logging.Formatter(fmt)
#handler.setFormatter(formatter)
#logger = logging.getLogger('bat_state')
#logger.addHandler(handler)
#logger.setLevel(logging.DEBUG)
def battery_info():
global Battery_send_num, B_C_stt, B_SOC, B_Alarm, B_Curr_Discharge, B_Total_Volt
pub = rospy.Publisher('battery_info', Battery, queue_size=10)
rospy.init_node('battery_pub')
rate = rospy.Rate(1) # 1hz
batten = Battery()
while not rospy.is_shutdown():
# hello_str = "hello world %s" % rospy.get_time()
t.timeout = 3
t.open()
# t.reset_input_buffer()
t.write(':000200000ee8~')
str_1 = t.read(174)
Battery_send_str = list(str_1)
del Battery_send_num[:]
del B_V_bat_cell[:]
if len(Battery_send_str) == 174:
for i in range(1, 173):
Battery_send_num = Battery_send_num + [string.atoi(str_1[i], 16)]
Battery_send_num = [':'] + Battery_send_num + ['~']
i = 25
B_Total_Volt = Battery_send_num[i] * 256 * 16 + Battery_send_num[i + 1] * 256 + \
Battery_send_num[i + 2] * 16 + Battery_send_num[i + 3]
i = 99
B_Curr_Discharge = Battery_send_num[i] * 256 * 16 + Battery_send_num[i + 1] * 256 + \
Battery_send_num[i + 2] * 16 + Battery_send_num[i + 3]
i = 119
B_C_stt = Battery_send_num[i] * 256 * 16 + Battery_send_num[i + 1] * 256 + \
Battery_send_num[i + 2] * 16 + Battery_send_num[i + 3]
i = 127
B_Alarm = Battery_send_num[i] * 256 * 16 + Battery_send_num[i + 1] * 256 + \
Battery_send_num[i + 2] * 16 + Battery_send_num[i + 3]
i = 161
B_SOC = Battery_send_num[i] * 16 + Battery_send_num[i + 1]
t.close()
time.sleep(0.5 - 0.22)
batten.Chg_state = B_C_stt
batten.SOC = B_SOC
batten.Voltage = B_Total_Volt * 2 / 1000.0
batten.Bat_alarm = B_Alarm
# rospy.loginfo(batten)
pub.publish(batten)
# logger.info("%s %s %2.2s %s", B_Curr_Discharge, B_SOC, B_Total_Volt * 2, B_C_stt)
if __name__ == '__main__':
try:
battery_info()
except rospy.ROSInterruptException:
pass
| #!/usr/bin/env python
import rospy
from colibri_battery.msg import Battery
import serial
import time
import string
import logging.handlers
VT = []
ASC2_num = 30
B_v = ()
Battery_send_num = []
B_V_bat_cell = []
B_Temp = []
t = serial.Serial('/dev/battery', 9600)
t.close()
#LOG_FILE = '/home/colibri/colibri_ws/src/colibri_battery/log/bat_state.log'
#handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024, backupCount=5)
#fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s'
#formatter = logging.Formatter(fmt)
#handler.setFormatter(formatter)
#logger = logging.getLogger('bat_state')
#logger.addHandler(handler)
#logger.setLevel(logging.DEBUG)
def battery_info():
global Battery_send_num, B_C_stt, B_SOC, B_Alarm, B_Curr_Discharge, B_Total_Volt
pub = rospy.Publisher('battery_info', Battery, queue_size=10)
rospy.init_node('battery_pub')
rate = rospy.Rate(1) # 1hz
batten = Battery()
while not rospy.is_shutdown():
# hello_str = "hello world %s" % rospy.get_time()
t.timeout = 3
t.open()
# t.reset_input_buffer()
t.write(':000200000ee8~')
str_1 = t.read(174)
Battery_send_str = list(str_1)
del Battery_send_num[:]
del B_V_bat_cell[:]
if len(Battery_send_str) == 174:
for i in range(1, 173):
Battery_send_num = Battery_send_num + [string.atoi(str_1[i], 16)]
Battery_send_num = [':'] + Battery_send_num + ['~']
i = 25
B_Total_Volt = Battery_send_num[i] * 256 * 16 + Battery_send_num[i + 1] * 256 + \
Battery_send_num[i + 2] * 16 + Battery_send_num[i + 3]
i = 99
B_Curr_Discharge = Battery_send_num[i] * 256 * 16 + Battery_send_num[i + 1] * 256 + \
Battery_send_num[i + 2] * 16 + Battery_send_num[i + 3]
i = 119
B_C_stt = Battery_send_num[i] * 256 * 16 + Battery_send_num[i + 1] * 256 + \
Battery_send_num[i + 2] * 16 + Battery_send_num[i + 3]
i = 127
B_Alarm = Battery_send_num[i] * 256 * 16 + Battery_send_num[i + 1] * 256 + \
Battery_send_num[i + 2] * 16 + Battery_send_num[i + 3]
i = 161
B_SOC = Battery_send_num[i] * 16 + Battery_send_num[i + 1]
t.close()
time.sleep(0.5 - 0.22)
batten.Chg_state = B_C_stt
batten.SOC = B_SOC
batten.Voltage = B_Total_Volt * 2 / 1000.0
batten.Bat_alarm = B_Alarm
# rospy.loginfo(batten)
pub.publish(batten)
# logger.info("%s %s %2.2s %s", B_Curr_Discharge, B_SOC, B_Total_Volt * 2, B_C_stt)
if __name__ == '__main__':
try:
battery_info()
except rospy.ROSInterruptException:
pass
| en | 0.161822 | #!/usr/bin/env python #LOG_FILE = '/home/colibri/colibri_ws/src/colibri_battery/log/bat_state.log' #handler = logging.handlers.RotatingFileHandler(LOG_FILE, maxBytes=1024 * 1024, backupCount=5) #fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(message)s' #formatter = logging.Formatter(fmt) #handler.setFormatter(formatter) #logger = logging.getLogger('bat_state') #logger.addHandler(handler) #logger.setLevel(logging.DEBUG) # 1hz # hello_str = "hello world %s" % rospy.get_time() # t.reset_input_buffer() # rospy.loginfo(batten) # logger.info("%s %s %2.2s %s", B_Curr_Discharge, B_SOC, B_Total_Volt * 2, B_C_stt) | 2.130328 | 2 |
day-02/part-1/jon.py | lypnol/adventofcode-2021 | 6 | 6614185 | from tool.runners.python import SubmissionPy
class JonSubmission(SubmissionPy):
def run(self, s):
x, d = 0, 0
for l in s.splitlines():
if l[0] == "f":
x += int(l[8:])
elif l[0] == "d":
d += int(l[5:])
else: # u
d -= int(l[3:])
return x*d
def run_alt(self, s):
x, d = 0, 0
n = len(s)
i = 0
while i < n:
if s[i] == "f":
x += int(s[i+8])
i += 10
elif s[i] == "d":
d += int(s[i+5])
i += 7
else: # u
d -= int(s[i+3])
i += 5
return x*d
def test_jon():
"""
Run `python -m pytest ./day-02/part-1/jon.py` to test the submission.
"""
assert (
JonSubmission().run(
"""forward 5
down 5
forward 8
up 3
down 8
forward 2
""".strip()
)
== 150
)
| from tool.runners.python import SubmissionPy
class JonSubmission(SubmissionPy):
def run(self, s):
x, d = 0, 0
for l in s.splitlines():
if l[0] == "f":
x += int(l[8:])
elif l[0] == "d":
d += int(l[5:])
else: # u
d -= int(l[3:])
return x*d
def run_alt(self, s):
x, d = 0, 0
n = len(s)
i = 0
while i < n:
if s[i] == "f":
x += int(s[i+8])
i += 10
elif s[i] == "d":
d += int(s[i+5])
i += 7
else: # u
d -= int(s[i+3])
i += 5
return x*d
def test_jon():
"""
Run `python -m pytest ./day-02/part-1/jon.py` to test the submission.
"""
assert (
JonSubmission().run(
"""forward 5
down 5
forward 8
up 3
down 8
forward 2
""".strip()
)
== 150
)
| en | 0.69383 | # u # u Run `python -m pytest ./day-02/part-1/jon.py` to test the submission. forward 5 down 5 forward 8 up 3 down 8 forward 2 | 3.002276 | 3 |
rlv/core/label.py | norefle/rl-vista | 1 | 6614186 | import pygame
from rlv.core.component import Component
class Label(Component):
def __init__(self, name, parent, text, size, surface):
super().__init__(name, parent)
self.font = pygame.font.SysFont("Roboto", size)
self.text = self.font.render(text, True, (0, 0, 0))
self.screen = surface
def on_settext(self, dt, text, target):
if target == self.entity:
self.text = self.font.render(text, True, (0, 0, 0))
return True
else:
return False
def on_render(self, dt):
(x, y, z) = self.entity.get_position()
self.screen.blit(self.text, (x, y))
return False # Do not prevent other components from rendering
| import pygame
from rlv.core.component import Component
class Label(Component):
def __init__(self, name, parent, text, size, surface):
super().__init__(name, parent)
self.font = pygame.font.SysFont("Roboto", size)
self.text = self.font.render(text, True, (0, 0, 0))
self.screen = surface
def on_settext(self, dt, text, target):
if target == self.entity:
self.text = self.font.render(text, True, (0, 0, 0))
return True
else:
return False
def on_render(self, dt):
(x, y, z) = self.entity.get_position()
self.screen.blit(self.text, (x, y))
return False # Do not prevent other components from rendering
| en | 0.757243 | # Do not prevent other components from rendering | 3.034425 | 3 |
tests/test_chebi.py | LosoiP/pathwalue | 1 | 6614187 | # -*- coding: utf-8 -*-
"""
Test chebi module.
"""
import pytest
from context import chebi
class TestParseChemicalData:
chemical_data_valid = [
{'COMPOUND_ID': '10', 'TYPE': 'CHARGE', 'CHEMICAL_DATA': '-1'},
{'COMPOUND_ID': '10', 'TYPE': 'FORMULA', 'CHEMICAL_DATA': 'H2O'},
{'COMPOUND_ID': '10', 'TYPE': 'MASS', 'CHEMICAL_DATA': '18.1'},
{'COMPOUND_ID': '12', 'TYPE': 'MONOISOTOPIC MASS',
'CHEMICAL_DATA': '18.2'},
]
chemical_data_invalid_type = [
{'COMPOUND_ID': '10', 'TYPE': '', 'CHEMICAL_DATA': '-1'},
]
compound_parents = {'10': 'P10', '11': 'P11'}
def test_return_correct_charge(self):
charges, *__ = chebi.parse_chemical_data(self.chemical_data_valid)
assert charges['10'] == -1
def test_return_correct_charge_parents(self):
charges, *__ = chebi.parse_chemical_data(self.chemical_data_valid,
self.compound_parents)
assert charges['P10'] == -1
def test_return_correct_formula(self):
__, formulae, __ = chebi.parse_chemical_data(self.chemical_data_valid)
assert formulae['10'] == 'H2O'
def test_return_correct_formula_parents(self):
__, formulae, __ = chebi.parse_chemical_data(self.chemical_data_valid,
self.compound_parents)
assert formulae['P10'] == 'H2O'
def test_return_correct_masses(self):
*__, masses = chebi.parse_chemical_data(self.chemical_data_valid)
assert masses == {'10': 18.1, '12': 18.2}
def test_return_correct_mass_parents(self):
*__, masses = chebi.parse_chemical_data(self.chemical_data_valid,
self.compound_parents)
assert masses == {'P10': 18.1, '12': 18.2}
def test_raise_value_error_invalid_type(self):
with pytest.raises(ValueError):
chebi.parse_chemical_data(self.chemical_data_invalid_type)
class TestParseCompounds:
compounds_valid = [
{'ID': '10', 'NAME': 'c0', 'PARENT_ID': 'null', 'STATUS': 'C'},
{'ID': '11', 'NAME': 'null', 'PARENT_ID': '10', 'STATUS': 'C'},
]
compounds_invalid = [
{'ID': '12', 'NAME': 'null', 'PARENT_ID': 'null', 'STATUS': 'C'},
]
def test_return_correct_compound_names(self):
__, compound_names = chebi.parse_compounds(self.compounds_valid)
assert compound_names == {'10': 'c0'}
def test_return_correct_compound_parents(self):
compound_parents, __ = chebi.parse_compounds(self.compounds_valid)
assert compound_parents == {'11': '10'}
def test_raise_value_error_name_null_parent_null(self):
with pytest.raises(ValueError):
chebi.parse_compounds(self.compounds_invalid)
class TestParseRelations:
relations = [
{
'ID': 'R1', 'FINAL_ID': 'V1', 'INIT_ID': 'V2', 'STATUS': 'C',
'TYPE': 'T1'
},
{
'ID': 'R2', 'FINAL_ID': 'V2', 'INIT_ID': 'V1', 'STATUS': 'E',
'TYPE': 'T2'
},
]
vertex_compounds = {'V1': 'C1', 'V2': 'C2'}
def test_return_correct_compound_names(self):
compound_relations = chebi.parse_relations(self.relations,
self.vertex_compounds)
assert compound_relations == {'C1': {'C2': 'T1'}}
class TestParseVertices:
vertices = [
{'ID': 'V1', 'COMPOUND_CHILD_ID': 'C1'},
{'ID': 'V2', 'COMPOUND_CHILD_ID': 'C2'},
]
compound_parents = {'C1': 'P1'}
def test_return_correct_vertex_compounds(self):
vertex_compounds = chebi.parse_vertices(self.vertices)
assert vertex_compounds == {'V1': 'C1', 'V2': 'C2'}
def test_return_correct_vertex_compounds_parents(self):
vertex_compounds = chebi.parse_vertices(self.vertices,
self.compound_parents)
assert vertex_compounds == {'V1': 'P1', 'V2': 'C2'}
| # -*- coding: utf-8 -*-
"""
Test chebi module.
"""
import pytest
from context import chebi
class TestParseChemicalData:
chemical_data_valid = [
{'COMPOUND_ID': '10', 'TYPE': 'CHARGE', 'CHEMICAL_DATA': '-1'},
{'COMPOUND_ID': '10', 'TYPE': 'FORMULA', 'CHEMICAL_DATA': 'H2O'},
{'COMPOUND_ID': '10', 'TYPE': 'MASS', 'CHEMICAL_DATA': '18.1'},
{'COMPOUND_ID': '12', 'TYPE': 'MONOISOTOPIC MASS',
'CHEMICAL_DATA': '18.2'},
]
chemical_data_invalid_type = [
{'COMPOUND_ID': '10', 'TYPE': '', 'CHEMICAL_DATA': '-1'},
]
compound_parents = {'10': 'P10', '11': 'P11'}
def test_return_correct_charge(self):
charges, *__ = chebi.parse_chemical_data(self.chemical_data_valid)
assert charges['10'] == -1
def test_return_correct_charge_parents(self):
charges, *__ = chebi.parse_chemical_data(self.chemical_data_valid,
self.compound_parents)
assert charges['P10'] == -1
def test_return_correct_formula(self):
__, formulae, __ = chebi.parse_chemical_data(self.chemical_data_valid)
assert formulae['10'] == 'H2O'
def test_return_correct_formula_parents(self):
__, formulae, __ = chebi.parse_chemical_data(self.chemical_data_valid,
self.compound_parents)
assert formulae['P10'] == 'H2O'
def test_return_correct_masses(self):
*__, masses = chebi.parse_chemical_data(self.chemical_data_valid)
assert masses == {'10': 18.1, '12': 18.2}
def test_return_correct_mass_parents(self):
*__, masses = chebi.parse_chemical_data(self.chemical_data_valid,
self.compound_parents)
assert masses == {'P10': 18.1, '12': 18.2}
def test_raise_value_error_invalid_type(self):
with pytest.raises(ValueError):
chebi.parse_chemical_data(self.chemical_data_invalid_type)
class TestParseCompounds:
compounds_valid = [
{'ID': '10', 'NAME': 'c0', 'PARENT_ID': 'null', 'STATUS': 'C'},
{'ID': '11', 'NAME': 'null', 'PARENT_ID': '10', 'STATUS': 'C'},
]
compounds_invalid = [
{'ID': '12', 'NAME': 'null', 'PARENT_ID': 'null', 'STATUS': 'C'},
]
def test_return_correct_compound_names(self):
__, compound_names = chebi.parse_compounds(self.compounds_valid)
assert compound_names == {'10': 'c0'}
def test_return_correct_compound_parents(self):
compound_parents, __ = chebi.parse_compounds(self.compounds_valid)
assert compound_parents == {'11': '10'}
def test_raise_value_error_name_null_parent_null(self):
with pytest.raises(ValueError):
chebi.parse_compounds(self.compounds_invalid)
class TestParseRelations:
relations = [
{
'ID': 'R1', 'FINAL_ID': 'V1', 'INIT_ID': 'V2', 'STATUS': 'C',
'TYPE': 'T1'
},
{
'ID': 'R2', 'FINAL_ID': 'V2', 'INIT_ID': 'V1', 'STATUS': 'E',
'TYPE': 'T2'
},
]
vertex_compounds = {'V1': 'C1', 'V2': 'C2'}
def test_return_correct_compound_names(self):
compound_relations = chebi.parse_relations(self.relations,
self.vertex_compounds)
assert compound_relations == {'C1': {'C2': 'T1'}}
class TestParseVertices:
vertices = [
{'ID': 'V1', 'COMPOUND_CHILD_ID': 'C1'},
{'ID': 'V2', 'COMPOUND_CHILD_ID': 'C2'},
]
compound_parents = {'C1': 'P1'}
def test_return_correct_vertex_compounds(self):
vertex_compounds = chebi.parse_vertices(self.vertices)
assert vertex_compounds == {'V1': 'C1', 'V2': 'C2'}
def test_return_correct_vertex_compounds_parents(self):
vertex_compounds = chebi.parse_vertices(self.vertices,
self.compound_parents)
assert vertex_compounds == {'V1': 'P1', 'V2': 'C2'}
| en | 0.399597 | # -*- coding: utf-8 -*- Test chebi module. | 2.473625 | 2 |
models/release.py | gnydick/qairon | 0 | 6614188 | <reponame>gnydick/qairon
from datetime import datetime
from sqlalchemy import *
from sqlalchemy.orm import relationship
from db import db
class Release(db.Model):
__tablename__ = "release"
id = Column(String, primary_key=True)
build_id = Column(String, ForeignKey('build.id'), nullable=False)
deployment_id = Column(String, ForeignKey('deployment.id'), nullable=False)
build_num = Column(Integer, nullable=False)
created_at = Column(DateTime, nullable=False)
last_updated_at = Column(DateTime, nullable=False)
build = relationship('Build', back_populates='releases')
deployment = relationship('Deployment', back_populates='releases', foreign_keys=[deployment_id])
release_artifacts = relationship('ReleaseArtifact', back_populates='release')
def __repr__(self):
return self.id
@db.event.listens_for(Release, 'before_insert')
def my_before_insert_listener(mapper, connection, release):
now = datetime.now()
release.created_at = now
release.last_updated_at = now
__update_id__(release)
@db.event.listens_for(Release, 'before_update')
def my_before_update_listener(mapper, connection, release):
now = datetime.now()
release.last_updated_at = now
__update_id__(release)
def __update_id__(release):
release.id = '%s:%s' % (release.deployment_id, release.build_num)
| from datetime import datetime
from sqlalchemy import *
from sqlalchemy.orm import relationship
from db import db
class Release(db.Model):
__tablename__ = "release"
id = Column(String, primary_key=True)
build_id = Column(String, ForeignKey('build.id'), nullable=False)
deployment_id = Column(String, ForeignKey('deployment.id'), nullable=False)
build_num = Column(Integer, nullable=False)
created_at = Column(DateTime, nullable=False)
last_updated_at = Column(DateTime, nullable=False)
build = relationship('Build', back_populates='releases')
deployment = relationship('Deployment', back_populates='releases', foreign_keys=[deployment_id])
release_artifacts = relationship('ReleaseArtifact', back_populates='release')
def __repr__(self):
return self.id
@db.event.listens_for(Release, 'before_insert')
def my_before_insert_listener(mapper, connection, release):
now = datetime.now()
release.created_at = now
release.last_updated_at = now
__update_id__(release)
@db.event.listens_for(Release, 'before_update')
def my_before_update_listener(mapper, connection, release):
now = datetime.now()
release.last_updated_at = now
__update_id__(release)
def __update_id__(release):
release.id = '%s:%s' % (release.deployment_id, release.build_num) | none | 1 | 2.657949 | 3 | |
src/areamanager.py | pariahsoft/Driftwood | 14 | 6614189 | ####################################
# Driftwood 2D Game Dev. Suite #
# areamanager.py #
# Copyright 2014-2017 #
# <NAME> & <NAME> #
####################################
# **********
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# **********
import math
from sdl2 import *
import tilemap
def int_greater_than_or_equal_to(x: float) -> int:
return int(math.ceil(x))
def int_smaller_than(x: float) -> int:
return int(math.floor(x - 0.001))
class AreaManager:
"""The Area Manager
This class manages the currently focused area.
Attributes:
driftwood: Base class instance.
filename: Filename of the current area.
tilemap: Tilemap instance for the area's tilemap.
changed: Whether the area should be rebuilt. This is true if the area changed since last checked.
offset: Offset at which to draw the area inside the viewport.
refocused: Whether we have gone to a new area since last checked.
"""
def __init__(self, driftwood):
"""AreaManager class initializer.
Args:
driftwood: Base class instance.
"""
self.driftwood = driftwood
self.filename = ""
self.tilemap = None
self.changed = False
self.offset = [0, 0]
self.refocused = False
self._autospawns = []
self.driftwood.tick.register(self._tick)
def register(self) -> None:
"""Register our tick callback."""
self.driftwood.tick.register(self._tick)
def focus(self, filename: str) -> bool:
"""Load and make active a new area.
Args:
filename: Filename of the area's Tiled map file.
Returns:
True if succeeded, False if failed.
"""
# Input Check
try:
CHECK(filename, str)
except CheckFailure as e:
self.driftwood.log.msg("ERROR", "Area", "focus", "bad argument", e)
return False
# Ask the resource manager for the JSON map file.
map_json = self.driftwood.resource.request_json(filename)
if map_json: # Did we successfully retrieve the map?
self.tilemap = tilemap.Tilemap(self.driftwood, self)
self.filename = filename # Set out current filename.
if not self.tilemap._read(filename, map_json): # Read the tilemap.
self.driftwood.log.msg("ERROR", "Area", "focus", "could not load tilemap", filename)
self.tilemap = None
return False
self.driftwood.log.info("Area", "loaded", filename)
# We have moved areas.
self.refocused = True
# Call world's global on_focus handlers.
self.driftwood.script._call_global_triggers("on_focus")
# If there is an on_focus function defined for this map, call it.
if "on_focus" in self.tilemap.properties:
args = self.tilemap.properties["on_focus"].split(',')
if len(args) < 2:
self.driftwood.log.msg("ERROR", "Area", "Focus", "invalid on_focus event",
self.tilemap.properties["on_focus"])
return True
self.driftwood.script.call(*args)
# Are we autospawning any entities?
for ent in self._autospawns:
print(ent)
self.driftwood.entity.insert(*ent)
self._autospawns = []
return True
else:
self.driftwood.log.msg("ERROR", "Area", "focus", "could not load area", filename)
return False
def _blur(self) -> None:
"""Call the global on_blur functions, and call the map's on_blur, if it has one. This is called when we leave
an area.
"""
# Call the world's global on_blur handlers.
self.driftwood.script._call_global_triggers("on_blur")
if "on_blur" in self.tilemap.properties:
args = self.tilemap.properties["on_blur"].split(',')
if len(args) < 2:
self.driftwood.log.msg("ERROR", "Area", "blur", "invalid on_blur event",
self.tilemap.properties["on_blur"])
return
self.driftwood.script.call(*args)
self.tilemap = None
def _tick(self, seconds_past: float) -> None:
"""Tick callback.
"""
if self.changed: # TODO: Only redraw portions that have changed.
if self.refocused:
self.driftwood.frame.prepare(self.tilemap.width * self.tilemap.tilewidth,
self.tilemap.height * self.tilemap.tileheight)
self.refocused = False
else:
self.driftwood.frame.clear()
self.driftwood.frame.calc_rects()
self.__build_frame()
self.driftwood.frame.finish_frame()
self.changed = False
def __build_frame(self) -> None:
"""Build the frame and pass to WindowManager.
For every tile and entity in each layer, copy its graphic onto the frame, then give the frame to WindowManager
for display.
"""
tilemap = self.tilemap
tilewidth = tilemap.tilewidth
tileheight = tilemap.tileheight
offset = self.offset
# Find the tiles that will show up if we draw them.
x_begin, x_end, y_begin, y_end = self.calculate_visible_tile_bounds()
# Start with the bottom layer and work up.
for l in range(len(tilemap.layers)):
layer = tilemap.layers[l]
srcrect = [-1, -1, tilewidth, tileheight]
dstrect = [-1, -1, tilewidth, tileheight]
# Draw each tile in the layer into its position.
for y in range(y_begin, y_end + 1):
for x in range(x_begin, x_end + 1):
# Retrieve data about the tile.
tile = layer.tiles[y * tilemap.width + x]
tileset = tile.tileset
if not tileset and not tile.gid:
# This is a dummy tile, don't draw it.
continue
member = tile.members[tile._Tile__cur_member]
if member == -1:
# This tile is invisible at this point in its animation, don't draw it.
continue
# Get the source and destination rectangles needed by SDL_RenderCopy.
srcrect[0] = member % tileset.width * tilewidth
srcrect[1] = member // tileset.width * tileheight
dstrect[0] = x * tilewidth + offset[0]
dstrect[1] = y * tileheight + offset[1]
# Copy the tile onto our frame.
r = self.driftwood.frame.copy(tileset.texture, srcrect, dstrect)
if r < 0:
self.driftwood.log.msg("ERROR", "Area", "__build_frame", "SDL", SDL_GetError())
# Draw the lights onto the layer.
for light in self.driftwood.light.layer(l):
srcrect = 0, 0, light.lightmap.width, light.lightmap.height
dstrect = [light.x - light.w // 2, light.y - light.h // 2, light.w, light.h]
dstrect[0] += self.offset[0]
dstrect[1] += self.offset[1]
r = self.driftwood.frame.copy(light.lightmap.texture, srcrect, dstrect, alpha=light.alpha,
blendmode=light.blendmode, colormod=light.colormod)
if r < 0:
self.driftwood.log.msg("ERROR", "Area", "__build_frame", "SDL", SDL_GetError())
arearect = (
0,
0,
self.tilemap.width * self.tilemap.tilewidth,
self.tilemap.height * self.tilemap.tileheight,
)
tall_parts = []
# Draw each entity on the layer into its position.
for entity in self.driftwood.entity.layer(l):
tall_amount = entity.height - self.tilemap.tileheight
# Get the destination rectangle needed by SDL_RenderCopy.
dstrect = [entity.x, entity.y - tall_amount, entity.width, entity.height]
# Draw the layers of the entity.
for srcrect in entity.srcrect():
srcrect = list(srcrect)
# Clip entities so they don't appear outside the area.
clip_left = 0 if arearect[0] <= dstrect[0] else arearect[0] - dstrect[0]
clip_top = 0 if arearect[1] <= dstrect[1] else arearect[1] - dstrect[1]
clip_right = 0 if dstrect[0] + dstrect[2] <= arearect[2] \
else (dstrect[0] + dstrect[2]) - arearect[2]
clip_bot = 0 if dstrect[1] + dstrect[3] <= arearect[3] \
else (dstrect[1] + dstrect[3]) - arearect[3]
srcrect[0] += clip_left
dstrect[0] += clip_left
srcrect[1] += clip_top
dstrect[1] += clip_top
srcrect[2] -= clip_left + clip_right
dstrect[2] -= clip_left + clip_right
srcrect[3] -= clip_top + clip_bot
dstrect[3] -= clip_top + clip_bot
# Area rumble et al.
dstrect[0] += self.offset[0]
dstrect[1] += self.offset[1]
# Copy the entity onto our frame.
r = self.driftwood.frame.copy(entity.spritesheet.texture, srcrect, dstrect)
if r < 0:
self.driftwood.log.msg("ERROR", "Area", "__build_frame", "SDL", SDL_GetError())
if tall_amount: # It's taller than the tile. Figure out where to put the tall part.
dstrect = [entity.x, entity.y - tall_amount, entity.width,
entity.height - (entity.height - tall_amount)]
srcrect[3] = dstrect[3]
# Clip entities so they don't appear outside the area.
clip_left = 0 if arearect[0] <= dstrect[0] else arearect[0] - dstrect[0]
clip_top = 0 if arearect[1] <= dstrect[1] else arearect[1] - dstrect[1]
clip_right = 0 if dstrect[0] + dstrect[2] <= arearect[2] \
else (dstrect[0] + dstrect[2]) - arearect[2]
clip_bot = 0 if dstrect[1] + dstrect[3] <= arearect[3] \
else (dstrect[1] + dstrect[3]) - arearect[3]
srcrect[0] += clip_left
dstrect[0] += clip_left
srcrect[1] += clip_top
dstrect[1] += clip_top
srcrect[2] -= clip_left + clip_right
dstrect[2] -= clip_left + clip_right
srcrect[3] -= clip_top + clip_bot
dstrect[3] -= clip_top + clip_bot
# Area rumble et al.
dstrect[0] += self.offset[0]
dstrect[1] += self.offset[1]
tall_parts.append([entity.spritesheet.texture, srcrect, dstrect])
# Draw the tall bits here.
for tall in tall_parts:
r = self.driftwood.frame.copy(*tall)
if r < 0:
self.driftwood.log.msg("ERROR", "Area", "__build_frame", "SDL", SDL_GetError())
def calculate_visible_tile_bounds(self) -> [int]:
tilemap = self.tilemap
tilewidth = tilemap.tilewidth
tileheight = tilemap.tileheight
offset = self.offset
viewport_width, viewport_height = self.driftwood.window.resolution()
viewport_left_bound = -self.driftwood.frame._frame[2].x
viewport_top_bound = -self.driftwood.frame._frame[2].y
viewport_right_bound = viewport_left_bound + viewport_width
viewport_bottom_bound = viewport_top_bound + viewport_height
# A tile will show up onscreen when it intersects the viewport rectangle. We can express the state of this
# intersection with a set of four inequalities, all of which must be true for the intersection to occur.
# --------------------------------------------------------------------------------------------------------
# viewport_left_bound <= tile_right_bound
# viewport_top_bound <= tile_bottom_bound
# tile_left_bound < viewport_right_bound
# tile_top_bound < viewport_bottom_bound
# The following equations hold. (Unit of measurement is pixels.)
# --------------------------------------------------------------
# tile_left_bound = tile_x_pos * tilewidth + offset[0]
# tile_top_bound = tile_y_pos * tileheight + offset[1]
# tile_right_bound = (tile_x_pos + 1) * tilewidth + offset[0] - 1
# tile_bottom_bound = (tile_y_pos + 1) * tileheight + offset[1] - 1
# Substitute the equations into the inequalities.
# -----------------------------------------------
# viewport_left_bound <= (tile_x_pos + 1) * tilewidth + offset[0] - 1
# viewport_top_bound <= (tile_y_pos + 1) * tileheight + offset[1] - 1
# tile_x_pos * tilewidth + offset[0] < viewport_right_bound
# tile_y_pos * tileheight + offset[1] < viewport_bottom_bound
# Solve for tile_x_pos and tile_y_pos.
# ------------------------------------
# (viewport_left_bound - offset[0] + 1) / tilewidth - 1 <= tile_x_pos
# (viewport_top_bound - offset[1] + 1) / tileheight - 1 <= tile_y_pos
# tile_x_pos < (viewport_right_bound - offset[0]) / tilewidth
# tile_y_pos < (viewport_bottom_bound - offset[1]) / tileheight
# We can now compute the minimum and maximum X and Y coordinates for visible tiles.
x_begin = int_greater_than_or_equal_to((viewport_left_bound - offset[0] + 1) / tilewidth - 1)
y_begin = int_greater_than_or_equal_to((viewport_top_bound - offset[1] + 1) / tileheight - 1)
x_end = int_smaller_than((viewport_right_bound - offset[0]) / tilewidth)
y_end = int_smaller_than((viewport_bottom_bound - offset[1]) / tileheight)
x_begin = max(0, x_begin)
y_begin = max(0, y_begin)
x_end = min(x_end, tilemap.width - 1)
y_end = min(y_end, tilemap.height - 1)
return x_begin, x_end, y_begin, y_end
| ####################################
# Driftwood 2D Game Dev. Suite #
# areamanager.py #
# Copyright 2014-2017 #
# <NAME> & <NAME> #
####################################
# **********
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
# **********
import math
from sdl2 import *
import tilemap
def int_greater_than_or_equal_to(x: float) -> int:
return int(math.ceil(x))
def int_smaller_than(x: float) -> int:
return int(math.floor(x - 0.001))
class AreaManager:
"""The Area Manager
This class manages the currently focused area.
Attributes:
driftwood: Base class instance.
filename: Filename of the current area.
tilemap: Tilemap instance for the area's tilemap.
changed: Whether the area should be rebuilt. This is true if the area changed since last checked.
offset: Offset at which to draw the area inside the viewport.
refocused: Whether we have gone to a new area since last checked.
"""
def __init__(self, driftwood):
"""AreaManager class initializer.
Args:
driftwood: Base class instance.
"""
self.driftwood = driftwood
self.filename = ""
self.tilemap = None
self.changed = False
self.offset = [0, 0]
self.refocused = False
self._autospawns = []
self.driftwood.tick.register(self._tick)
def register(self) -> None:
"""Register our tick callback."""
self.driftwood.tick.register(self._tick)
def focus(self, filename: str) -> bool:
"""Load and make active a new area.
Args:
filename: Filename of the area's Tiled map file.
Returns:
True if succeeded, False if failed.
"""
# Input Check
try:
CHECK(filename, str)
except CheckFailure as e:
self.driftwood.log.msg("ERROR", "Area", "focus", "bad argument", e)
return False
# Ask the resource manager for the JSON map file.
map_json = self.driftwood.resource.request_json(filename)
if map_json: # Did we successfully retrieve the map?
self.tilemap = tilemap.Tilemap(self.driftwood, self)
self.filename = filename # Set out current filename.
if not self.tilemap._read(filename, map_json): # Read the tilemap.
self.driftwood.log.msg("ERROR", "Area", "focus", "could not load tilemap", filename)
self.tilemap = None
return False
self.driftwood.log.info("Area", "loaded", filename)
# We have moved areas.
self.refocused = True
# Call world's global on_focus handlers.
self.driftwood.script._call_global_triggers("on_focus")
# If there is an on_focus function defined for this map, call it.
if "on_focus" in self.tilemap.properties:
args = self.tilemap.properties["on_focus"].split(',')
if len(args) < 2:
self.driftwood.log.msg("ERROR", "Area", "Focus", "invalid on_focus event",
self.tilemap.properties["on_focus"])
return True
self.driftwood.script.call(*args)
# Are we autospawning any entities?
for ent in self._autospawns:
print(ent)
self.driftwood.entity.insert(*ent)
self._autospawns = []
return True
else:
self.driftwood.log.msg("ERROR", "Area", "focus", "could not load area", filename)
return False
def _blur(self) -> None:
"""Call the global on_blur functions, and call the map's on_blur, if it has one. This is called when we leave
an area.
"""
# Call the world's global on_blur handlers.
self.driftwood.script._call_global_triggers("on_blur")
if "on_blur" in self.tilemap.properties:
args = self.tilemap.properties["on_blur"].split(',')
if len(args) < 2:
self.driftwood.log.msg("ERROR", "Area", "blur", "invalid on_blur event",
self.tilemap.properties["on_blur"])
return
self.driftwood.script.call(*args)
self.tilemap = None
def _tick(self, seconds_past: float) -> None:
"""Tick callback.
"""
if self.changed: # TODO: Only redraw portions that have changed.
if self.refocused:
self.driftwood.frame.prepare(self.tilemap.width * self.tilemap.tilewidth,
self.tilemap.height * self.tilemap.tileheight)
self.refocused = False
else:
self.driftwood.frame.clear()
self.driftwood.frame.calc_rects()
self.__build_frame()
self.driftwood.frame.finish_frame()
self.changed = False
def __build_frame(self) -> None:
"""Build the frame and pass to WindowManager.
For every tile and entity in each layer, copy its graphic onto the frame, then give the frame to WindowManager
for display.
"""
tilemap = self.tilemap
tilewidth = tilemap.tilewidth
tileheight = tilemap.tileheight
offset = self.offset
# Find the tiles that will show up if we draw them.
x_begin, x_end, y_begin, y_end = self.calculate_visible_tile_bounds()
# Start with the bottom layer and work up.
for l in range(len(tilemap.layers)):
layer = tilemap.layers[l]
srcrect = [-1, -1, tilewidth, tileheight]
dstrect = [-1, -1, tilewidth, tileheight]
# Draw each tile in the layer into its position.
for y in range(y_begin, y_end + 1):
for x in range(x_begin, x_end + 1):
# Retrieve data about the tile.
tile = layer.tiles[y * tilemap.width + x]
tileset = tile.tileset
if not tileset and not tile.gid:
# This is a dummy tile, don't draw it.
continue
member = tile.members[tile._Tile__cur_member]
if member == -1:
# This tile is invisible at this point in its animation, don't draw it.
continue
# Get the source and destination rectangles needed by SDL_RenderCopy.
srcrect[0] = member % tileset.width * tilewidth
srcrect[1] = member // tileset.width * tileheight
dstrect[0] = x * tilewidth + offset[0]
dstrect[1] = y * tileheight + offset[1]
# Copy the tile onto our frame.
r = self.driftwood.frame.copy(tileset.texture, srcrect, dstrect)
if r < 0:
self.driftwood.log.msg("ERROR", "Area", "__build_frame", "SDL", SDL_GetError())
# Draw the lights onto the layer.
for light in self.driftwood.light.layer(l):
srcrect = 0, 0, light.lightmap.width, light.lightmap.height
dstrect = [light.x - light.w // 2, light.y - light.h // 2, light.w, light.h]
dstrect[0] += self.offset[0]
dstrect[1] += self.offset[1]
r = self.driftwood.frame.copy(light.lightmap.texture, srcrect, dstrect, alpha=light.alpha,
blendmode=light.blendmode, colormod=light.colormod)
if r < 0:
self.driftwood.log.msg("ERROR", "Area", "__build_frame", "SDL", SDL_GetError())
arearect = (
0,
0,
self.tilemap.width * self.tilemap.tilewidth,
self.tilemap.height * self.tilemap.tileheight,
)
tall_parts = []
# Draw each entity on the layer into its position.
for entity in self.driftwood.entity.layer(l):
tall_amount = entity.height - self.tilemap.tileheight
# Get the destination rectangle needed by SDL_RenderCopy.
dstrect = [entity.x, entity.y - tall_amount, entity.width, entity.height]
# Draw the layers of the entity.
for srcrect in entity.srcrect():
srcrect = list(srcrect)
# Clip entities so they don't appear outside the area.
clip_left = 0 if arearect[0] <= dstrect[0] else arearect[0] - dstrect[0]
clip_top = 0 if arearect[1] <= dstrect[1] else arearect[1] - dstrect[1]
clip_right = 0 if dstrect[0] + dstrect[2] <= arearect[2] \
else (dstrect[0] + dstrect[2]) - arearect[2]
clip_bot = 0 if dstrect[1] + dstrect[3] <= arearect[3] \
else (dstrect[1] + dstrect[3]) - arearect[3]
srcrect[0] += clip_left
dstrect[0] += clip_left
srcrect[1] += clip_top
dstrect[1] += clip_top
srcrect[2] -= clip_left + clip_right
dstrect[2] -= clip_left + clip_right
srcrect[3] -= clip_top + clip_bot
dstrect[3] -= clip_top + clip_bot
# Area rumble et al.
dstrect[0] += self.offset[0]
dstrect[1] += self.offset[1]
# Copy the entity onto our frame.
r = self.driftwood.frame.copy(entity.spritesheet.texture, srcrect, dstrect)
if r < 0:
self.driftwood.log.msg("ERROR", "Area", "__build_frame", "SDL", SDL_GetError())
if tall_amount: # It's taller than the tile. Figure out where to put the tall part.
dstrect = [entity.x, entity.y - tall_amount, entity.width,
entity.height - (entity.height - tall_amount)]
srcrect[3] = dstrect[3]
# Clip entities so they don't appear outside the area.
clip_left = 0 if arearect[0] <= dstrect[0] else arearect[0] - dstrect[0]
clip_top = 0 if arearect[1] <= dstrect[1] else arearect[1] - dstrect[1]
clip_right = 0 if dstrect[0] + dstrect[2] <= arearect[2] \
else (dstrect[0] + dstrect[2]) - arearect[2]
clip_bot = 0 if dstrect[1] + dstrect[3] <= arearect[3] \
else (dstrect[1] + dstrect[3]) - arearect[3]
srcrect[0] += clip_left
dstrect[0] += clip_left
srcrect[1] += clip_top
dstrect[1] += clip_top
srcrect[2] -= clip_left + clip_right
dstrect[2] -= clip_left + clip_right
srcrect[3] -= clip_top + clip_bot
dstrect[3] -= clip_top + clip_bot
# Area rumble et al.
dstrect[0] += self.offset[0]
dstrect[1] += self.offset[1]
tall_parts.append([entity.spritesheet.texture, srcrect, dstrect])
# Draw the tall bits here.
for tall in tall_parts:
r = self.driftwood.frame.copy(*tall)
if r < 0:
self.driftwood.log.msg("ERROR", "Area", "__build_frame", "SDL", SDL_GetError())
def calculate_visible_tile_bounds(self) -> [int]:
tilemap = self.tilemap
tilewidth = tilemap.tilewidth
tileheight = tilemap.tileheight
offset = self.offset
viewport_width, viewport_height = self.driftwood.window.resolution()
viewport_left_bound = -self.driftwood.frame._frame[2].x
viewport_top_bound = -self.driftwood.frame._frame[2].y
viewport_right_bound = viewport_left_bound + viewport_width
viewport_bottom_bound = viewport_top_bound + viewport_height
# A tile will show up onscreen when it intersects the viewport rectangle. We can express the state of this
# intersection with a set of four inequalities, all of which must be true for the intersection to occur.
# --------------------------------------------------------------------------------------------------------
# viewport_left_bound <= tile_right_bound
# viewport_top_bound <= tile_bottom_bound
# tile_left_bound < viewport_right_bound
# tile_top_bound < viewport_bottom_bound
# The following equations hold. (Unit of measurement is pixels.)
# --------------------------------------------------------------
# tile_left_bound = tile_x_pos * tilewidth + offset[0]
# tile_top_bound = tile_y_pos * tileheight + offset[1]
# tile_right_bound = (tile_x_pos + 1) * tilewidth + offset[0] - 1
# tile_bottom_bound = (tile_y_pos + 1) * tileheight + offset[1] - 1
# Substitute the equations into the inequalities.
# -----------------------------------------------
# viewport_left_bound <= (tile_x_pos + 1) * tilewidth + offset[0] - 1
# viewport_top_bound <= (tile_y_pos + 1) * tileheight + offset[1] - 1
# tile_x_pos * tilewidth + offset[0] < viewport_right_bound
# tile_y_pos * tileheight + offset[1] < viewport_bottom_bound
# Solve for tile_x_pos and tile_y_pos.
# ------------------------------------
# (viewport_left_bound - offset[0] + 1) / tilewidth - 1 <= tile_x_pos
# (viewport_top_bound - offset[1] + 1) / tileheight - 1 <= tile_y_pos
# tile_x_pos < (viewport_right_bound - offset[0]) / tilewidth
# tile_y_pos < (viewport_bottom_bound - offset[1]) / tileheight
# We can now compute the minimum and maximum X and Y coordinates for visible tiles.
x_begin = int_greater_than_or_equal_to((viewport_left_bound - offset[0] + 1) / tilewidth - 1)
y_begin = int_greater_than_or_equal_to((viewport_top_bound - offset[1] + 1) / tileheight - 1)
x_end = int_smaller_than((viewport_right_bound - offset[0]) / tilewidth)
y_end = int_smaller_than((viewport_bottom_bound - offset[1]) / tileheight)
x_begin = max(0, x_begin)
y_begin = max(0, y_begin)
x_end = min(x_end, tilemap.width - 1)
y_end = min(y_end, tilemap.height - 1)
return x_begin, x_end, y_begin, y_end
| en | 0.72836 | #################################### # Driftwood 2D Game Dev. Suite # # areamanager.py # # Copyright 2014-2017 # # <NAME> & <NAME> # #################################### # ********** # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to # deal in the Software without restriction, including without limitation the # rights to use, copy, modify, merge, publish, distribute, sublicense, and/or # sell copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS # IN THE SOFTWARE. # ********** The Area Manager This class manages the currently focused area. Attributes: driftwood: Base class instance. filename: Filename of the current area. tilemap: Tilemap instance for the area's tilemap. changed: Whether the area should be rebuilt. This is true if the area changed since last checked. offset: Offset at which to draw the area inside the viewport. refocused: Whether we have gone to a new area since last checked. AreaManager class initializer. Args: driftwood: Base class instance. Register our tick callback. Load and make active a new area. Args: filename: Filename of the area's Tiled map file. Returns: True if succeeded, False if failed. # Input Check # Ask the resource manager for the JSON map file. # Did we successfully retrieve the map? # Set out current filename. # Read the tilemap. # We have moved areas. # Call world's global on_focus handlers. # If there is an on_focus function defined for this map, call it. # Are we autospawning any entities? Call the global on_blur functions, and call the map's on_blur, if it has one. This is called when we leave an area. # Call the world's global on_blur handlers. Tick callback. # TODO: Only redraw portions that have changed. Build the frame and pass to WindowManager. For every tile and entity in each layer, copy its graphic onto the frame, then give the frame to WindowManager for display. # Find the tiles that will show up if we draw them. # Start with the bottom layer and work up. # Draw each tile in the layer into its position. # Retrieve data about the tile. # This is a dummy tile, don't draw it. # This tile is invisible at this point in its animation, don't draw it. # Get the source and destination rectangles needed by SDL_RenderCopy. # Copy the tile onto our frame. # Draw the lights onto the layer. # Draw each entity on the layer into its position. # Get the destination rectangle needed by SDL_RenderCopy. # Draw the layers of the entity. # Clip entities so they don't appear outside the area. # Area rumble et al. # Copy the entity onto our frame. # It's taller than the tile. Figure out where to put the tall part. # Clip entities so they don't appear outside the area. # Area rumble et al. # Draw the tall bits here. # A tile will show up onscreen when it intersects the viewport rectangle. We can express the state of this # intersection with a set of four inequalities, all of which must be true for the intersection to occur. # -------------------------------------------------------------------------------------------------------- # viewport_left_bound <= tile_right_bound # viewport_top_bound <= tile_bottom_bound # tile_left_bound < viewport_right_bound # tile_top_bound < viewport_bottom_bound # The following equations hold. (Unit of measurement is pixels.) # -------------------------------------------------------------- # tile_left_bound = tile_x_pos * tilewidth + offset[0] # tile_top_bound = tile_y_pos * tileheight + offset[1] # tile_right_bound = (tile_x_pos + 1) * tilewidth + offset[0] - 1 # tile_bottom_bound = (tile_y_pos + 1) * tileheight + offset[1] - 1 # Substitute the equations into the inequalities. # ----------------------------------------------- # viewport_left_bound <= (tile_x_pos + 1) * tilewidth + offset[0] - 1 # viewport_top_bound <= (tile_y_pos + 1) * tileheight + offset[1] - 1 # tile_x_pos * tilewidth + offset[0] < viewport_right_bound # tile_y_pos * tileheight + offset[1] < viewport_bottom_bound # Solve for tile_x_pos and tile_y_pos. # ------------------------------------ # (viewport_left_bound - offset[0] + 1) / tilewidth - 1 <= tile_x_pos # (viewport_top_bound - offset[1] + 1) / tileheight - 1 <= tile_y_pos # tile_x_pos < (viewport_right_bound - offset[0]) / tilewidth # tile_y_pos < (viewport_bottom_bound - offset[1]) / tileheight # We can now compute the minimum and maximum X and Y coordinates for visible tiles. | 2.157376 | 2 |
get_predictions.py | Lednik7/SMART_Product | 2 | 6614190 | import numpy as np
from read_models import read_models
abstract_certain_feat_xgb, abstract_certain_vect_xgb, \
abstract_subject_feat_xgb, abstract_subject_vect_xgb, \
career_feat_xgb, career_vect_xgb, \
education_vect_xgb, specific_feat_xgb, specific_vect_xgb, \
time_bound_feat_xgb, time_bound_vect_xgb, topic_art_vect_xgb, \
topic_career_vect_xgb, topic_community_vect_xgb, \
topic_fixing_vect_xgb, topic_habits_vect_xgb, \
topic_hard_skill_vect_xgb, topic_health_vect_xgb, \
topic_knowledge_vect_xgb, topic_soft_skill_vect_xgb, \
topic_subjectivity_vect_xgb, topic_tool_vect_xgb = read_models()
topic_map = {
'art_pred':'Искусство',
'knowledge_pred':'Знания',
'hard_skill_pred':'Hard skills',
'soft_skill_pred':'Soft skills',
'subjectivity_pred':'Субъективизация',
'tool_pred':'Инструменты/Прикладное',
'health_pred':'Здоровье',
'habits_pred':'Привычки',
'fixing_pred':'Фиксация',
'community_pred':'Общество/Семья',
'career_pred':'Карьера',
}
def algo_vote(predictions:list):
zero_counter = int()
one_counter = int()
for i in predictions:
if i == 0:
zero_counter += 1
else:
one_counter += 1
if zero_counter > one_counter:
return 0
elif zero_counter == one_counter:
return 0
else:
return 1
def get_prediction(model1, model2, features, vectors, raw_domain):
pred1 = model1.predict(features)
pred2 = model2.predict(vectors)
final_pred = algo_vote([pred1, pred2])
return final_pred
def predict_topic(model1, vectors):
pred1 = model1.predict(vectors)[0]
return pred1
def predict(features, vectors, raw_domain, input_df):
# SMART
# is specific
specific_pred = get_prediction(specific_feat_xgb, specific_vect_xgb, features, vectors, raw_domain)
if specific_pred == 1:
specific_pred = 'Цель сформулирована конкретно/specific'
else:
specific_pred = 'Цель сформулирована НЕ конкретно/specific'
# is attainable
obstackles = input_df.loc[:, 'are_obstackles_expected'].tolist()[0]
if obstackles == 0:
attainable_pred = 'Цель достижима/attainable'
else:
attainable_pred = 'Цель НЕ достижима/attainable'
# is time bound
time_bound_pred = get_prediction(time_bound_feat_xgb, time_bound_vect_xgb, features, vectors, raw_domain)
if time_bound_pred == 1:
time_bound_pred = 'Цель ограничена во времени/time-bound'
else:
time_bound_pred = 'Цель НЕ ограничена во времени/time-bound'
SMART_pred = [specific_pred, attainable_pred, time_bound_pred]
# is education
education_pred = education_vect_xgb.predict(vectors)
if education_pred == 1:
education_pred = 'Цель имеет отношение к образованию'
else:
education_pred = 'Цель НЕ имеет отношения к образованию'
# is career
career_pred = get_prediction(career_feat_xgb, career_vect_xgb, features, vectors, raw_domain)
if career_pred == 1:
career_pred = 'Цель имеет отношения к карьере'
else:
career_pred = 'Цель НЕ имеет отношения к карьере'
edu_car_pred = [education_pred, career_pred]
# is certain
abstract_pred = ''
certain_pred = get_prediction(abstract_certain_feat_xgb, abstract_certain_vect_xgb,
features, vectors, raw_domain)
if certain_pred == 1:
abstract_pred = 'Цель сформулирована конкретно'
else:
# is subject|abstract
subject_pred = get_prediction(abstract_subject_feat_xgb, abstract_subject_vect_xgb,
features, vectors, raw_domain)
if subject_pred == 1:
abstract_pred = 'Цель сформулирована предметно'
else:
abstract_pred = 'Цель сформулирована абстрактно'
# TOPICS
art_pred = predict_topic(topic_art_vect_xgb, vectors)
knowledge_pred = predict_topic(topic_knowledge_vect_xgb, vectors)
hard_skill_pred = predict_topic(topic_hard_skill_vect_xgb, vectors)
soft_skill_pred = predict_topic(topic_soft_skill_vect_xgb, vectors)
subjectivity_pred = predict_topic(topic_subjectivity_vect_xgb, vectors)
tool_pred = predict_topic(topic_tool_vect_xgb, vectors)
health_pred = predict_topic(topic_health_vect_xgb, vectors)
habits_pred = predict_topic(topic_habits_vect_xgb, vectors)
fixing_pred = predict_topic(topic_fixing_vect_xgb, vectors)
community_pred = predict_topic(topic_community_vect_xgb, vectors)
career_pred = predict_topic(topic_career_vect_xgb, vectors)
topics_pred = []
for value, key in [(art_pred, 'art_pred'), (knowledge_pred, 'knowledge_pred'),
(hard_skill_pred, 'hard_skill_pred'), (soft_skill_pred, 'soft_skill_pred'),
(subjectivity_pred, 'subjectivity_pred'), (tool_pred, 'tool_pred'),
(health_pred, 'health_pred'), (habits_pred, 'habits_pred'),
(fixing_pred, 'fixing_pred'), (community_pred, 'community_pred'),
(career_pred, 'career_pred')]:
if value == 1:
topics_pred.append(topic_map[key])
return SMART_pred, edu_car_pred, abstract_pred, topics_pred | import numpy as np
from read_models import read_models
abstract_certain_feat_xgb, abstract_certain_vect_xgb, \
abstract_subject_feat_xgb, abstract_subject_vect_xgb, \
career_feat_xgb, career_vect_xgb, \
education_vect_xgb, specific_feat_xgb, specific_vect_xgb, \
time_bound_feat_xgb, time_bound_vect_xgb, topic_art_vect_xgb, \
topic_career_vect_xgb, topic_community_vect_xgb, \
topic_fixing_vect_xgb, topic_habits_vect_xgb, \
topic_hard_skill_vect_xgb, topic_health_vect_xgb, \
topic_knowledge_vect_xgb, topic_soft_skill_vect_xgb, \
topic_subjectivity_vect_xgb, topic_tool_vect_xgb = read_models()
topic_map = {
'art_pred':'Искусство',
'knowledge_pred':'Знания',
'hard_skill_pred':'Hard skills',
'soft_skill_pred':'Soft skills',
'subjectivity_pred':'Субъективизация',
'tool_pred':'Инструменты/Прикладное',
'health_pred':'Здоровье',
'habits_pred':'Привычки',
'fixing_pred':'Фиксация',
'community_pred':'Общество/Семья',
'career_pred':'Карьера',
}
def algo_vote(predictions:list):
zero_counter = int()
one_counter = int()
for i in predictions:
if i == 0:
zero_counter += 1
else:
one_counter += 1
if zero_counter > one_counter:
return 0
elif zero_counter == one_counter:
return 0
else:
return 1
def get_prediction(model1, model2, features, vectors, raw_domain):
pred1 = model1.predict(features)
pred2 = model2.predict(vectors)
final_pred = algo_vote([pred1, pred2])
return final_pred
def predict_topic(model1, vectors):
pred1 = model1.predict(vectors)[0]
return pred1
def predict(features, vectors, raw_domain, input_df):
# SMART
# is specific
specific_pred = get_prediction(specific_feat_xgb, specific_vect_xgb, features, vectors, raw_domain)
if specific_pred == 1:
specific_pred = 'Цель сформулирована конкретно/specific'
else:
specific_pred = 'Цель сформулирована НЕ конкретно/specific'
# is attainable
obstackles = input_df.loc[:, 'are_obstackles_expected'].tolist()[0]
if obstackles == 0:
attainable_pred = 'Цель достижима/attainable'
else:
attainable_pred = 'Цель НЕ достижима/attainable'
# is time bound
time_bound_pred = get_prediction(time_bound_feat_xgb, time_bound_vect_xgb, features, vectors, raw_domain)
if time_bound_pred == 1:
time_bound_pred = 'Цель ограничена во времени/time-bound'
else:
time_bound_pred = 'Цель НЕ ограничена во времени/time-bound'
SMART_pred = [specific_pred, attainable_pred, time_bound_pred]
# is education
education_pred = education_vect_xgb.predict(vectors)
if education_pred == 1:
education_pred = 'Цель имеет отношение к образованию'
else:
education_pred = 'Цель НЕ имеет отношения к образованию'
# is career
career_pred = get_prediction(career_feat_xgb, career_vect_xgb, features, vectors, raw_domain)
if career_pred == 1:
career_pred = 'Цель имеет отношения к карьере'
else:
career_pred = 'Цель НЕ имеет отношения к карьере'
edu_car_pred = [education_pred, career_pred]
# is certain
abstract_pred = ''
certain_pred = get_prediction(abstract_certain_feat_xgb, abstract_certain_vect_xgb,
features, vectors, raw_domain)
if certain_pred == 1:
abstract_pred = 'Цель сформулирована конкретно'
else:
# is subject|abstract
subject_pred = get_prediction(abstract_subject_feat_xgb, abstract_subject_vect_xgb,
features, vectors, raw_domain)
if subject_pred == 1:
abstract_pred = 'Цель сформулирована предметно'
else:
abstract_pred = 'Цель сформулирована абстрактно'
# TOPICS
art_pred = predict_topic(topic_art_vect_xgb, vectors)
knowledge_pred = predict_topic(topic_knowledge_vect_xgb, vectors)
hard_skill_pred = predict_topic(topic_hard_skill_vect_xgb, vectors)
soft_skill_pred = predict_topic(topic_soft_skill_vect_xgb, vectors)
subjectivity_pred = predict_topic(topic_subjectivity_vect_xgb, vectors)
tool_pred = predict_topic(topic_tool_vect_xgb, vectors)
health_pred = predict_topic(topic_health_vect_xgb, vectors)
habits_pred = predict_topic(topic_habits_vect_xgb, vectors)
fixing_pred = predict_topic(topic_fixing_vect_xgb, vectors)
community_pred = predict_topic(topic_community_vect_xgb, vectors)
career_pred = predict_topic(topic_career_vect_xgb, vectors)
topics_pred = []
for value, key in [(art_pred, 'art_pred'), (knowledge_pred, 'knowledge_pred'),
(hard_skill_pred, 'hard_skill_pred'), (soft_skill_pred, 'soft_skill_pred'),
(subjectivity_pred, 'subjectivity_pred'), (tool_pred, 'tool_pred'),
(health_pred, 'health_pred'), (habits_pred, 'habits_pred'),
(fixing_pred, 'fixing_pred'), (community_pred, 'community_pred'),
(career_pred, 'career_pred')]:
if value == 1:
topics_pred.append(topic_map[key])
return SMART_pred, edu_car_pred, abstract_pred, topics_pred | en | 0.974631 | # SMART # is specific # is attainable # is time bound # is education # is career # is certain # is subject|abstract # TOPICS | 2.207417 | 2 |
clouds/workflows/__init__.py | OATML/clouds | 0 | 6614191 | <filename>clouds/workflows/__init__.py
from clouds.workflows import tuning
from clouds.workflows import plotting
from clouds.workflows import training
from clouds.workflows import prediction
| <filename>clouds/workflows/__init__.py
from clouds.workflows import tuning
from clouds.workflows import plotting
from clouds.workflows import training
from clouds.workflows import prediction
| none | 1 | 1.109362 | 1 | |
git2web/project.py | nigelbabu/git2web | 2 | 6614192 | <gh_stars>1-10
from git2web import app
from git2web.functions import path_to_conf, list_of_members
from configobj import ConfigObj
from flask import session, redirect, g, url_for, render_template, \
flash, request
# index, project list
@app.route('/')
def index():
if not session.get('logged_in'):
return redirect(url_for('login'))
config = ConfigObj(path_to_conf())
return render_template('index.html', config=config)
# individual groups
@app.route('/group/<groupname>')
def showgroup(groupname):
if not session.get('logged_in'):
return redirect(url_for('login'))
config = ConfigObj(path_to_conf())
section = 'group ' + groupname
if section not in config:
flash('Group not found')
return redirect(url_for('index'))
return render_template('group.html', config=config, group=groupname, section=section)
#remove person from the project
@app.route('/group/<groupname>/delete/<person>')
def remove_project_person(groupname, person):
config = ConfigObj(path_to_conf())
section = 'group ' + groupname
members = config[section]['members'].split()
if person in members:
members.remove(person)
config[section]['members'] = ' '.join(members)
try:
config.write()
flash('Deleted person')
except:
flash('Could not delete person')
return redirect(url_for('showgroup', groupname=groupname))
#add person to project
@app.route('/group/<groupname>/add', methods=['GET', 'POST'])
def add_project_person(groupname):
config = ConfigObj(path_to_conf())
section = 'group ' + groupname
existing_members = config[section]['members'].split()
if request.method == 'POST':
if request.form['keynames'] != '0':
existing_members = config[section]['members'].split()
existing_members.append(request.form['keynames'])
config[section]['members'] = ' '.join(existing_members)
print config[section]['members']
try:
config.write()
flash('Added person')
except:
flash('Could not add person')
return redirect(url_for('showgroup', groupname=groupname))
else:
members = filter(lambda x: x not in existing_members, list_of_members())
if not members:
flash('No new members')
return redirect(url_for('showgroup', groupname=groupname))
return render_template('groupadd.html', members=members, group=groupname)
| from git2web import app
from git2web.functions import path_to_conf, list_of_members
from configobj import ConfigObj
from flask import session, redirect, g, url_for, render_template, \
flash, request
# index, project list
@app.route('/')
def index():
if not session.get('logged_in'):
return redirect(url_for('login'))
config = ConfigObj(path_to_conf())
return render_template('index.html', config=config)
# individual groups
@app.route('/group/<groupname>')
def showgroup(groupname):
if not session.get('logged_in'):
return redirect(url_for('login'))
config = ConfigObj(path_to_conf())
section = 'group ' + groupname
if section not in config:
flash('Group not found')
return redirect(url_for('index'))
return render_template('group.html', config=config, group=groupname, section=section)
#remove person from the project
@app.route('/group/<groupname>/delete/<person>')
def remove_project_person(groupname, person):
config = ConfigObj(path_to_conf())
section = 'group ' + groupname
members = config[section]['members'].split()
if person in members:
members.remove(person)
config[section]['members'] = ' '.join(members)
try:
config.write()
flash('Deleted person')
except:
flash('Could not delete person')
return redirect(url_for('showgroup', groupname=groupname))
#add person to project
@app.route('/group/<groupname>/add', methods=['GET', 'POST'])
def add_project_person(groupname):
config = ConfigObj(path_to_conf())
section = 'group ' + groupname
existing_members = config[section]['members'].split()
if request.method == 'POST':
if request.form['keynames'] != '0':
existing_members = config[section]['members'].split()
existing_members.append(request.form['keynames'])
config[section]['members'] = ' '.join(existing_members)
print config[section]['members']
try:
config.write()
flash('Added person')
except:
flash('Could not add person')
return redirect(url_for('showgroup', groupname=groupname))
else:
members = filter(lambda x: x not in existing_members, list_of_members())
if not members:
flash('No new members')
return redirect(url_for('showgroup', groupname=groupname))
return render_template('groupadd.html', members=members, group=groupname) | en | 0.74749 | # index, project list # individual groups #remove person from the project #add person to project | 2.43332 | 2 |
src/fractal/mind/_op/stream.py | jedhsu/fractal | 0 | 6614193 | """
*Mind Stream*
"""
def mind_stream() -> Iterator[Batch]:
batchsize = min(
params.batch_size,
length(W),
)
batches = Flux.Data.DataLoader(
data,
batchsize,
partial=false,
shuffle=true,
)
return map(
batches,
b,
)
| """
*Mind Stream*
"""
def mind_stream() -> Iterator[Batch]:
batchsize = min(
params.batch_size,
length(W),
)
batches = Flux.Data.DataLoader(
data,
batchsize,
partial=false,
shuffle=true,
)
return map(
batches,
b,
)
| en | 0.677652 | *Mind Stream* | 2.478647 | 2 |
format-conversion/nlp_util/pstree.py | jkkummerfeld/1ec-graph-parser | 13 | 6614194 | <gh_stars>10-100
#!/usr/bin/env python
import re, string
from collections import defaultdict
DEFAULT_LABEL = 'label_not_set'
TRACE_LABEL = '-NONE-'
class TreeIterator:
'''Iterator for traversal of a tree.
PSTree uses pre-order traversal by default, but this supports post-order too, e.g.:
>>> tree = tree_from_text("(ROOT (S (NP-SBJ (NNP Ms.) (NNP Haag) ) (VP (VBZ plays) (NP (NNP Elianti) )) (. .) ))")
>>> for node in TreeIterator(tree, 'post'):
... print node
(NNP Ms.)
(NNP Haag)
(NP-SBJ (NNP Ms.) (NNP Haag))
(VBZ plays)
(NNP Elianti)
(NP (NNP Elianti))
(VP (VBZ plays) (NP (NNP Elianti)))
(. .)
(S (NP-SBJ (NNP Ms.) (NNP Haag)) (VP (VBZ plays) (NP (NNP Elianti))) (. .))
(ROOT (S (NP-SBJ (NNP Ms.) (NNP Haag)) (VP (VBZ plays) (NP (NNP Elianti))) (. .)))
'''
def __init__(self, tree, order='pre'):
self.tree = tree
self.pos = [0]
self.order = order
def __iter__(self):
return self
def next(self):
while True:
if len(self.pos) == 0:
raise StopIteration
# For pre-order traversal, return nodes when first reached
ans = None
if self.order == 'pre' and self.pos[-1] == 0:
ans = self.tree
# Update internal state to point at the next node in the tree
if self.pos[-1] < len(self.tree.subtrees):
self.tree = self.tree.subtrees[self.pos[-1]]
self.pos[-1] += 1
self.pos.append(0)
else:
if self.order == 'post':
ans = self.tree
self.tree = self.tree.parent
self.pos.pop()
if ans is not None:
return ans
class PSTree:
'''Phrase Structure Tree
>>> tree = tree_from_text("(ROOT (NP (NNP Newspaper)))")
>>> print tree
(ROOT (NP (NNP Newspaper)))
>>> tree = tree_from_text("(ROOT (S (NP-SBJ (NNP Ms.) (NNP Haag) ) (VP (VBZ plays) (NP (NNP Elianti) )) (. .) ))")
>>> print tree
(ROOT (S (NP-SBJ (NNP Ms.) (NNP Haag)) (VP (VBZ plays) (NP (NNP Elianti))) (. .)))
>>> print tree.word_yield()
Ms. Haag plays Elianti .
>>> tree = tree_from_text("(ROOT (NFP ...))")
>>> print tree
(ROOT (NFP ...))
>>> tree.word_yield()
'...'
>>> tree = tree_from_text("(VP (VBD was) (VP (VBN named) (S (NP-SBJ (-NONE- *-1) ) (NP-PRD (NP (DT a) (JJ nonexecutive) (NN director) ) (PP (IN of) (NP (DT this) (JJ British) (JJ industrial) (NN conglomerate) ))))))")
>>> print tree
(VP (VBD was) (VP (VBN named) (S (NP-SBJ (-NONE- *-1)) (NP-PRD (NP (DT a) (JJ nonexecutive) (NN director)) (PP (IN of) (NP (DT this) (JJ British) (JJ industrial) (NN conglomerate)))))))
>>> tree.word_yield()
'was named *-1 a nonexecutive director of this British industrial conglomerate'
'''
def __init__(self, word=None, label=DEFAULT_LABEL, span=(0, 0), parent=None, subtrees=None):
self.word = word
self.label = label
self.span = span
self.wordspan = span
self.parent = parent
self.unique_id = None
self.subtrees = []
if subtrees is not None:
self.subtrees = subtrees
for subtree in subtrees:
subtree.parent = self
def __iter__(self):
return TreeIterator(self, 'pre')
def clone(self):
ans = PSTree(self.word, self.label, self.span)
for subtree in self.subtrees:
subclone = subtree.clone()
subclone.parent = ans
ans.subtrees.append(subclone)
return ans
def is_terminal(self):
'''Check if the tree has no children.'''
return len(self.subtrees) == 0
def is_trace(self):
'''Check if this tree is the end of a trace.'''
return self.label == TRACE_LABEL
def is_punct(self):
if self.label in {"IN", "TO", "RB", "AUX", "DT"} or self.word is None:
return False
if self.word in {"!", "#", "'", "''", "*", ",", "-", "--", ".", "...", ":", ";", "=", "?", "@", "\*", "\*\*", "`", "``"}:
return True
return False
def is_conjunction(self):
return self.label in {'CC', 'CONJP'}
def root(self):
'''Follow parents until a node is reached that has no parent.'''
if self.parent is not None:
return self.parent.root()
else:
return self
def __repr__(self):
'''Return a bracket notation style representation of the tree.'''
# TODO: Shift this to str and add more field info
ans = '('
if self.is_trace():
ans += TRACE_LABEL + ' ' + self.word
elif self.is_terminal():
ans += self.label + ' ' + self.word
else:
ans += self.label
for subtree in self.subtrees:
ans += ' ' + subtree.__repr__()
ans += ')'
return ans
def set_unique_id(self, cur=0):
'''Set a unique numerical ID for each node.'''
self.unique_id = cur
cur += 1
for subtree in self.subtrees:
cur = subtree.set_unique_id(cur)
return cur
def calculate_spans(self, left=0, wordleft=0):
'''Update the spans for every node in this tree.'''
right = left
wordright = wordleft
if self.is_terminal():
if not self.is_trace():
wordright += 1
right += 1
for subtree in self.subtrees:
right, wordright = subtree.calculate_spans(right, wordright)
self.span = (left, right)
self.wordspan = (wordleft, wordright)
return right, wordright
def check_consistency(self):
'''Check that the parents and spans are consistent with the tree
structure.'''
ans = True
if self.is_terminal():
if self.is_trace() and self.span[0] != self.span[1]:
print "non-zero span at a terminal trace node"
ans = False
elif self.span[0] + 1 != self.span[1]:
print "span changes by value other than 1 at non-trace terminal node"
ans = False
else:
for i in xrange(len(self.subtrees)):
subtree = self.subtrees[i]
if subtree.parent != self:
print "bad parent link"
ans = False
if i > 0 and self.subtrees[i - 1].span[1] != subtree.span[0]:
print "Subtree spans don't match"
ans = False
ans = ans and subtree.check_consistency()
if self.span != (self.subtrees[0].span[0], self.subtrees[-1].span[1]):
print "Span doesn't match subtree spans"
ans = False
return ans
def production_list(self, ans=None):
'''Get a list of productions as:
(node label, node span, ((subtree1, end1), (subtree2, end2)...))'''
if ans is None:
ans = []
if len(self.subtrees) > 0:
cur = (self.label, self.span, tuple([(sub.label, sub.span[1]) for sub in self.subtrees]))
ans.append(cur)
for sub in self.subtrees:
sub.production_list(ans)
return ans
def word_yield(self, span=None, as_list=False):
'''Return the set of words at terminal nodes, either as a space separated
string, or as a list.'''
if self.is_terminal():
if span is None or span[0] <= self.span[0] < span[1]:
if self.word is None:
return None
if as_list:
return [self.word]
else:
return self.word
else:
return None
else:
ans = []
for subtree in self.subtrees:
words = subtree.word_yield(span, as_list)
if words is not None:
if as_list:
ans += words
else:
ans.append(words)
if not as_list:
ans = ' '.join(ans)
return ans
def node_dict(self, depth=0, node_dict=None):
'''Get a dictionary of labelled nodes. Note that we use a dictionary to
take into consideration unaries like (NP (NP ...))'''
if node_dict is None:
node_dict = defaultdict(lambda: [])
for subtree in self.subtrees:
subtree.node_dict(depth + 1, node_dict)
node_dict[(self.label, self.span[0], self.span[1])].append(depth)
return node_dict
def get_nodes(self, request='all', start=-1, end=-1, node_list=None):
'''Get the node(s) that have a given span. Unspecified endpoints are
treated as wildcards. The request can be 'lowest', 'highest', or 'all'.
For 'all', the list of nodes is in order from the highest first.'''
if request not in ['highest', 'lowest', 'all']:
raise Exception("%s is not a valid request" % str(request))
if request == 'lowest' and start < 0 and end < 0:
raise Exception("Lowest is not well defined when both ends are wildcards")
if request == 'all' and node_list is None:
node_list = []
if request == 'highest':
if self.span[0] == start or start < 0:
if self.span[1] == end or end < 0:
return self
for subtree in self.subtrees:
# Skip subtrees with no overlapping range
if 0 < end <= subtree.span[0] or subtree.span[1] < start:
continue
ans = subtree.get_nodes(request, start, end, node_list)
if ans is not None and request != 'all':
return ans
if self.span[0] == start or start < 0:
if self.span[1] == end or end < 0:
if request == 'lowest':
return self
elif request == 'all':
node_list.insert(0, self)
return node_list
if request == 'all':
return node_list
else:
return None
def get_spanning_nodes(self, start, end, node_list=None):
return_ans = False
if node_list is None:
return_ans = True
node_list = []
if self.span[0] == start and self.span[1] <= end:
node_list.append(self)
start = self.span[1]
else:
for subtree in self.subtrees:
if subtree.span[1] < start:
continue
start = subtree.get_spanning_nodes(start, end, node_list)
if start == end:
break
if return_ans:
if start == end:
return node_list
else:
return None
else:
return start
def tree_from_text(text, allow_empty_labels=False, allow_empty_words=False):
'''Construct a PSTree from the provided string, which is assumed to represent
a tree with nested round brackets. Nodes are labeled by the text between the
open bracket and the next space (possibly an empty string). Words are the
text after that space and before the close bracket.'''
root = None
cur = None
pos = 0
word = ''
for char in text:
# Consume random text up to the first '('
if cur is None:
if char == '(':
root = PSTree()
cur = root
continue
if char == '(':
word = word.strip()
if cur.label is DEFAULT_LABEL:
if len(word) == 0 and not allow_empty_labels:
raise Exception("Empty label found\n%s" % text)
cur.label = word
word = ''
if word != '':
raise Exception("Stray '%s' while processing\n%s" % (word, text))
sub = PSTree()
cur.subtrees.append(sub)
sub.parent = cur
cur = sub
elif char == ')':
word = word.strip()
if word != '':
if len(word) == 0 and not allow_empty_words:
raise Exception("Empty word found\n%s" % text)
cur.word = word
word = ''
cur.span = (pos, pos + 1)
pos += 1
else:
cur.span = (cur.subtrees[0].span[0], cur.subtrees[-1].span[1])
cur = cur.parent
elif char == ' ':
if cur.label is DEFAULT_LABEL:
if len(word) == 0 and not allow_empty_labels:
raise Exception("Empty label found\n%s" % text)
cur.label = word
word = ''
else:
word += char
else:
word += char
if cur is not None:
raise Exception("Text did not include complete tree\n%s" % text)
root.calculate_spans()
return root
def get_reference(text, sep='-'):
# Work backwards through it
cur = []
for char in text[::-1]:
if char in string.digits:
cur.append(char)
elif char == sep:
if len(cur) == 0:
return None
else:
return ''.join(cur)
elif char in {'-', '='}:
cur = []
return None
def tree_from_shp(text, allow_empty_labels=False, allow_empty_words=False):
'''Construct a PSTree from the provided split head grammar parse.'''
# Create spine defined non-terminals
nodes = {}
sent_len = 0
nulls_to_add = []
trace_edges = {}
for line in text:
# Extract data
parts = line.strip().split()
num = int(parts[0])
sent_len = max(sent_len, num)
word = parts[1]
POS = parts[2]
spine = parts[3]
tnum = int(parts[4])
tlabel = parts[5]
structural_edge = (tnum, tlabel)
for i in range(6, len(parts), 6):
tnum = int(parts[i])
tlabel = parts[i + 1]
tlabel += "_T" if parts[i + 2] == 'T' else "_F"
slabel = parts[i + 3]
slabel += "_T" if parts[i + 4] == 'T' else "_F"
trace = parts[i + 5]
if trace.endswith("_chain"):
trace = trace[:-6]
edge = (tnum, tlabel, num, slabel, trace)
if num not in trace_edges:
trace_edges[num] = []
trace_edges[num].append(edge)
# Make spine
prev_node = PSTree(word, POS, (num - 1, num))
symbol_count = defaultdict(lambda: 0)
node_map = {
POS +"_0_F": prev_node
}
nodes[num] = (word, POS, spine, structural_edge, node_map)
if spine != '_':
cur = []
depth = 0
null_node = []
for char in spine +"_":
if char == ')':
cur.append(")")
depth -= 1
elif char == '(':
cur.append("(")
depth += 1
elif char == '_':
if depth != 0:
cur.append(" ")
else:
# Generate new node
if '(' not in cur:
symbol = ''.join(cur)
node = PSTree(None, symbol, (num - 1, num), None, [prev_node])
prev_node.parent = node
count = symbol_count[symbol +"_F"]
symbol_count[symbol +"_F"] += 1
node_map["{}_{}_F".format(symbol, count)] = node
prev_node = node
if len(null_node) > 0:
for null in null_node:
nulls_to_add.append((null, node))
null_node = []
else:
modified = []
to_add = []
for char2 in cur:
to_add.append(char2)
if char2 == ')':
if not ' ' in to_add and len(to_add) > 1:
to_add[0] += '-NONE- '
modified.append(''.join(to_add))
to_add = []
elif char2 == '(':
modified.append(''.join(to_add[:-1]))
to_add = ['(']
modified = ''.join(modified)
null = tree_from_text(modified)
for node in null:
symbol = node.label
count = symbol_count[symbol +"_T"]
symbol_count[symbol +"_T"] += 1
node_map["{}_{}_T".format(symbol, count)] = node
null_node.append(null)
cur = []
else:
cur.append(char)
# Link together with structural edges, ensuring proper nesting
root = None
decisions = {}
for length in xrange(1, len(nodes) + 1):
for pos in nodes:
word, POS, spine, structural_edge, node_map = nodes[pos]
tnum, tlabel = structural_edge
if abs(pos - tnum) == length:
# Identify the top of the spine at this position
top = None
for name in node_map:
if node_map[name].parent is None and name.endswith("_F"):
top = node_map[name]
# Attach it to the target
if tnum == 0:
root = PSTree(None, "ROOT", (0, sent_len), None, [top])
top.parent = root
else:
left = tnum > pos
target_info = nodes[tnum]
tlabel += "_F"
tnode = target_info[4][tlabel]
# Check that linking to this node won't cause a crossing
for opos in xrange(min(pos, tnum) + 1, max(pos, tnum)):
if opos in decisions:
onode = decisions[opos]
# See if this is above our node
pnode = tnode
while pnode is not None:
if pnode == onode:
tnode = onode
break
pnode = pnode.parent
top.parent = tnode
if left:
tnode.subtrees.insert(0, top)
else:
tnode.subtrees.append(top)
decisions[pos] = tnode
# TODO: gather stats on the original trees
for null, node in nulls_to_add:
pos = len(node.subtrees)
if null.label.startswith("ADVP"):
pass
elif node.label.startswith("SBAR") or null.label.startswith("NP-SBJ"):
pos = 0
else:
npos = 0
for subnode in node.subtrees:
npos += 1
if subnode.label.startswith("VB"):
pos = npos
if subnode.label.startswith("LST"):
pos = npos + 1
break
if subnode.label.startswith("VP"):
pos = max(0, npos - 1)
break
if len(node.subtrees) > pos:
sub_label = node.subtrees[pos].label
if sub_label.startswith("-L") or sub_label in {",", "LST", "``"}:
pos += 1
node.subtrees.insert(pos, null)
null.parent = node
root.calculate_spans()
# Add traces
max_index = 0
for num in trace_edges:
for tnum, tlabel, snum, slabel, trace in trace_edges[num]:
snode = nodes[snum][4][slabel]
tnode = nodes[tnum][4][tlabel]
if tlabel.endswith("_T") and slabel.endswith("_T"):
tmp = snode
snode = tnode
tnode = tmp
if trace == '=':
identity = get_reference(tnode.label)
if identity is None:
max_index += 1
identity = max_index
tnode.label += "-{}".format(identity)
snode.label += "={}".format(identity)
else:
identity = get_reference(snode.label)
if identity is None:
max_index += 1
identity = max_index
snode.label += "-{}".format(identity)
tnode.subtrees[0].word += "-{}".format(identity)
return root
def clone_and_find(nodes):
'''Clone the tree these nodes are in and finds the equivalent nodes in the
new tree.'''
return_list = True
if type(nodes) != type([]):
return_list = False
nodes = [nodes]
# Note the paths to the nodes
paths = []
for node in nodes:
paths.append([])
tree = node
while tree.parent is not None:
prev = tree
tree = tree.parent
paths[-1].append(tree.subtrees.index(prev))
# Duplicate and follow the path back to the equivalent node
ntree = nodes[0].root().clone()
ans = []
for path in paths:
tree = ntree
for index in path[::-1]:
tree = tree.subtrees[index]
ans.append(tree)
if return_list:
return ans
else:
return ans[0]
if __name__ == '__main__':
print "Running doctest"
import doctest
doctest.testmod()
| #!/usr/bin/env python
import re, string
from collections import defaultdict
DEFAULT_LABEL = 'label_not_set'
TRACE_LABEL = '-NONE-'
class TreeIterator:
'''Iterator for traversal of a tree.
PSTree uses pre-order traversal by default, but this supports post-order too, e.g.:
>>> tree = tree_from_text("(ROOT (S (NP-SBJ (NNP Ms.) (NNP Haag) ) (VP (VBZ plays) (NP (NNP Elianti) )) (. .) ))")
>>> for node in TreeIterator(tree, 'post'):
... print node
(NNP Ms.)
(NNP Haag)
(NP-SBJ (NNP Ms.) (NNP Haag))
(VBZ plays)
(NNP Elianti)
(NP (NNP Elianti))
(VP (VBZ plays) (NP (NNP Elianti)))
(. .)
(S (NP-SBJ (NNP Ms.) (NNP Haag)) (VP (VBZ plays) (NP (NNP Elianti))) (. .))
(ROOT (S (NP-SBJ (NNP Ms.) (NNP Haag)) (VP (VBZ plays) (NP (NNP Elianti))) (. .)))
'''
def __init__(self, tree, order='pre'):
self.tree = tree
self.pos = [0]
self.order = order
def __iter__(self):
return self
def next(self):
while True:
if len(self.pos) == 0:
raise StopIteration
# For pre-order traversal, return nodes when first reached
ans = None
if self.order == 'pre' and self.pos[-1] == 0:
ans = self.tree
# Update internal state to point at the next node in the tree
if self.pos[-1] < len(self.tree.subtrees):
self.tree = self.tree.subtrees[self.pos[-1]]
self.pos[-1] += 1
self.pos.append(0)
else:
if self.order == 'post':
ans = self.tree
self.tree = self.tree.parent
self.pos.pop()
if ans is not None:
return ans
class PSTree:
'''Phrase Structure Tree
>>> tree = tree_from_text("(ROOT (NP (NNP Newspaper)))")
>>> print tree
(ROOT (NP (NNP Newspaper)))
>>> tree = tree_from_text("(ROOT (S (NP-SBJ (NNP Ms.) (NNP Haag) ) (VP (VBZ plays) (NP (NNP Elianti) )) (. .) ))")
>>> print tree
(ROOT (S (NP-SBJ (NNP Ms.) (NNP Haag)) (VP (VBZ plays) (NP (NNP Elianti))) (. .)))
>>> print tree.word_yield()
Ms. Haag plays Elianti .
>>> tree = tree_from_text("(ROOT (NFP ...))")
>>> print tree
(ROOT (NFP ...))
>>> tree.word_yield()
'...'
>>> tree = tree_from_text("(VP (VBD was) (VP (VBN named) (S (NP-SBJ (-NONE- *-1) ) (NP-PRD (NP (DT a) (JJ nonexecutive) (NN director) ) (PP (IN of) (NP (DT this) (JJ British) (JJ industrial) (NN conglomerate) ))))))")
>>> print tree
(VP (VBD was) (VP (VBN named) (S (NP-SBJ (-NONE- *-1)) (NP-PRD (NP (DT a) (JJ nonexecutive) (NN director)) (PP (IN of) (NP (DT this) (JJ British) (JJ industrial) (NN conglomerate)))))))
>>> tree.word_yield()
'was named *-1 a nonexecutive director of this British industrial conglomerate'
'''
def __init__(self, word=None, label=DEFAULT_LABEL, span=(0, 0), parent=None, subtrees=None):
self.word = word
self.label = label
self.span = span
self.wordspan = span
self.parent = parent
self.unique_id = None
self.subtrees = []
if subtrees is not None:
self.subtrees = subtrees
for subtree in subtrees:
subtree.parent = self
def __iter__(self):
return TreeIterator(self, 'pre')
def clone(self):
ans = PSTree(self.word, self.label, self.span)
for subtree in self.subtrees:
subclone = subtree.clone()
subclone.parent = ans
ans.subtrees.append(subclone)
return ans
def is_terminal(self):
'''Check if the tree has no children.'''
return len(self.subtrees) == 0
def is_trace(self):
'''Check if this tree is the end of a trace.'''
return self.label == TRACE_LABEL
def is_punct(self):
if self.label in {"IN", "TO", "RB", "AUX", "DT"} or self.word is None:
return False
if self.word in {"!", "#", "'", "''", "*", ",", "-", "--", ".", "...", ":", ";", "=", "?", "@", "\*", "\*\*", "`", "``"}:
return True
return False
def is_conjunction(self):
return self.label in {'CC', 'CONJP'}
def root(self):
'''Follow parents until a node is reached that has no parent.'''
if self.parent is not None:
return self.parent.root()
else:
return self
def __repr__(self):
'''Return a bracket notation style representation of the tree.'''
# TODO: Shift this to str and add more field info
ans = '('
if self.is_trace():
ans += TRACE_LABEL + ' ' + self.word
elif self.is_terminal():
ans += self.label + ' ' + self.word
else:
ans += self.label
for subtree in self.subtrees:
ans += ' ' + subtree.__repr__()
ans += ')'
return ans
def set_unique_id(self, cur=0):
'''Set a unique numerical ID for each node.'''
self.unique_id = cur
cur += 1
for subtree in self.subtrees:
cur = subtree.set_unique_id(cur)
return cur
def calculate_spans(self, left=0, wordleft=0):
'''Update the spans for every node in this tree.'''
right = left
wordright = wordleft
if self.is_terminal():
if not self.is_trace():
wordright += 1
right += 1
for subtree in self.subtrees:
right, wordright = subtree.calculate_spans(right, wordright)
self.span = (left, right)
self.wordspan = (wordleft, wordright)
return right, wordright
def check_consistency(self):
'''Check that the parents and spans are consistent with the tree
structure.'''
ans = True
if self.is_terminal():
if self.is_trace() and self.span[0] != self.span[1]:
print "non-zero span at a terminal trace node"
ans = False
elif self.span[0] + 1 != self.span[1]:
print "span changes by value other than 1 at non-trace terminal node"
ans = False
else:
for i in xrange(len(self.subtrees)):
subtree = self.subtrees[i]
if subtree.parent != self:
print "bad parent link"
ans = False
if i > 0 and self.subtrees[i - 1].span[1] != subtree.span[0]:
print "Subtree spans don't match"
ans = False
ans = ans and subtree.check_consistency()
if self.span != (self.subtrees[0].span[0], self.subtrees[-1].span[1]):
print "Span doesn't match subtree spans"
ans = False
return ans
def production_list(self, ans=None):
'''Get a list of productions as:
(node label, node span, ((subtree1, end1), (subtree2, end2)...))'''
if ans is None:
ans = []
if len(self.subtrees) > 0:
cur = (self.label, self.span, tuple([(sub.label, sub.span[1]) for sub in self.subtrees]))
ans.append(cur)
for sub in self.subtrees:
sub.production_list(ans)
return ans
def word_yield(self, span=None, as_list=False):
'''Return the set of words at terminal nodes, either as a space separated
string, or as a list.'''
if self.is_terminal():
if span is None or span[0] <= self.span[0] < span[1]:
if self.word is None:
return None
if as_list:
return [self.word]
else:
return self.word
else:
return None
else:
ans = []
for subtree in self.subtrees:
words = subtree.word_yield(span, as_list)
if words is not None:
if as_list:
ans += words
else:
ans.append(words)
if not as_list:
ans = ' '.join(ans)
return ans
def node_dict(self, depth=0, node_dict=None):
'''Get a dictionary of labelled nodes. Note that we use a dictionary to
take into consideration unaries like (NP (NP ...))'''
if node_dict is None:
node_dict = defaultdict(lambda: [])
for subtree in self.subtrees:
subtree.node_dict(depth + 1, node_dict)
node_dict[(self.label, self.span[0], self.span[1])].append(depth)
return node_dict
def get_nodes(self, request='all', start=-1, end=-1, node_list=None):
'''Get the node(s) that have a given span. Unspecified endpoints are
treated as wildcards. The request can be 'lowest', 'highest', or 'all'.
For 'all', the list of nodes is in order from the highest first.'''
if request not in ['highest', 'lowest', 'all']:
raise Exception("%s is not a valid request" % str(request))
if request == 'lowest' and start < 0 and end < 0:
raise Exception("Lowest is not well defined when both ends are wildcards")
if request == 'all' and node_list is None:
node_list = []
if request == 'highest':
if self.span[0] == start or start < 0:
if self.span[1] == end or end < 0:
return self
for subtree in self.subtrees:
# Skip subtrees with no overlapping range
if 0 < end <= subtree.span[0] or subtree.span[1] < start:
continue
ans = subtree.get_nodes(request, start, end, node_list)
if ans is not None and request != 'all':
return ans
if self.span[0] == start or start < 0:
if self.span[1] == end or end < 0:
if request == 'lowest':
return self
elif request == 'all':
node_list.insert(0, self)
return node_list
if request == 'all':
return node_list
else:
return None
def get_spanning_nodes(self, start, end, node_list=None):
return_ans = False
if node_list is None:
return_ans = True
node_list = []
if self.span[0] == start and self.span[1] <= end:
node_list.append(self)
start = self.span[1]
else:
for subtree in self.subtrees:
if subtree.span[1] < start:
continue
start = subtree.get_spanning_nodes(start, end, node_list)
if start == end:
break
if return_ans:
if start == end:
return node_list
else:
return None
else:
return start
def tree_from_text(text, allow_empty_labels=False, allow_empty_words=False):
'''Construct a PSTree from the provided string, which is assumed to represent
a tree with nested round brackets. Nodes are labeled by the text between the
open bracket and the next space (possibly an empty string). Words are the
text after that space and before the close bracket.'''
root = None
cur = None
pos = 0
word = ''
for char in text:
# Consume random text up to the first '('
if cur is None:
if char == '(':
root = PSTree()
cur = root
continue
if char == '(':
word = word.strip()
if cur.label is DEFAULT_LABEL:
if len(word) == 0 and not allow_empty_labels:
raise Exception("Empty label found\n%s" % text)
cur.label = word
word = ''
if word != '':
raise Exception("Stray '%s' while processing\n%s" % (word, text))
sub = PSTree()
cur.subtrees.append(sub)
sub.parent = cur
cur = sub
elif char == ')':
word = word.strip()
if word != '':
if len(word) == 0 and not allow_empty_words:
raise Exception("Empty word found\n%s" % text)
cur.word = word
word = ''
cur.span = (pos, pos + 1)
pos += 1
else:
cur.span = (cur.subtrees[0].span[0], cur.subtrees[-1].span[1])
cur = cur.parent
elif char == ' ':
if cur.label is DEFAULT_LABEL:
if len(word) == 0 and not allow_empty_labels:
raise Exception("Empty label found\n%s" % text)
cur.label = word
word = ''
else:
word += char
else:
word += char
if cur is not None:
raise Exception("Text did not include complete tree\n%s" % text)
root.calculate_spans()
return root
def get_reference(text, sep='-'):
# Work backwards through it
cur = []
for char in text[::-1]:
if char in string.digits:
cur.append(char)
elif char == sep:
if len(cur) == 0:
return None
else:
return ''.join(cur)
elif char in {'-', '='}:
cur = []
return None
def tree_from_shp(text, allow_empty_labels=False, allow_empty_words=False):
'''Construct a PSTree from the provided split head grammar parse.'''
# Create spine defined non-terminals
nodes = {}
sent_len = 0
nulls_to_add = []
trace_edges = {}
for line in text:
# Extract data
parts = line.strip().split()
num = int(parts[0])
sent_len = max(sent_len, num)
word = parts[1]
POS = parts[2]
spine = parts[3]
tnum = int(parts[4])
tlabel = parts[5]
structural_edge = (tnum, tlabel)
for i in range(6, len(parts), 6):
tnum = int(parts[i])
tlabel = parts[i + 1]
tlabel += "_T" if parts[i + 2] == 'T' else "_F"
slabel = parts[i + 3]
slabel += "_T" if parts[i + 4] == 'T' else "_F"
trace = parts[i + 5]
if trace.endswith("_chain"):
trace = trace[:-6]
edge = (tnum, tlabel, num, slabel, trace)
if num not in trace_edges:
trace_edges[num] = []
trace_edges[num].append(edge)
# Make spine
prev_node = PSTree(word, POS, (num - 1, num))
symbol_count = defaultdict(lambda: 0)
node_map = {
POS +"_0_F": prev_node
}
nodes[num] = (word, POS, spine, structural_edge, node_map)
if spine != '_':
cur = []
depth = 0
null_node = []
for char in spine +"_":
if char == ')':
cur.append(")")
depth -= 1
elif char == '(':
cur.append("(")
depth += 1
elif char == '_':
if depth != 0:
cur.append(" ")
else:
# Generate new node
if '(' not in cur:
symbol = ''.join(cur)
node = PSTree(None, symbol, (num - 1, num), None, [prev_node])
prev_node.parent = node
count = symbol_count[symbol +"_F"]
symbol_count[symbol +"_F"] += 1
node_map["{}_{}_F".format(symbol, count)] = node
prev_node = node
if len(null_node) > 0:
for null in null_node:
nulls_to_add.append((null, node))
null_node = []
else:
modified = []
to_add = []
for char2 in cur:
to_add.append(char2)
if char2 == ')':
if not ' ' in to_add and len(to_add) > 1:
to_add[0] += '-NONE- '
modified.append(''.join(to_add))
to_add = []
elif char2 == '(':
modified.append(''.join(to_add[:-1]))
to_add = ['(']
modified = ''.join(modified)
null = tree_from_text(modified)
for node in null:
symbol = node.label
count = symbol_count[symbol +"_T"]
symbol_count[symbol +"_T"] += 1
node_map["{}_{}_T".format(symbol, count)] = node
null_node.append(null)
cur = []
else:
cur.append(char)
# Link together with structural edges, ensuring proper nesting
root = None
decisions = {}
for length in xrange(1, len(nodes) + 1):
for pos in nodes:
word, POS, spine, structural_edge, node_map = nodes[pos]
tnum, tlabel = structural_edge
if abs(pos - tnum) == length:
# Identify the top of the spine at this position
top = None
for name in node_map:
if node_map[name].parent is None and name.endswith("_F"):
top = node_map[name]
# Attach it to the target
if tnum == 0:
root = PSTree(None, "ROOT", (0, sent_len), None, [top])
top.parent = root
else:
left = tnum > pos
target_info = nodes[tnum]
tlabel += "_F"
tnode = target_info[4][tlabel]
# Check that linking to this node won't cause a crossing
for opos in xrange(min(pos, tnum) + 1, max(pos, tnum)):
if opos in decisions:
onode = decisions[opos]
# See if this is above our node
pnode = tnode
while pnode is not None:
if pnode == onode:
tnode = onode
break
pnode = pnode.parent
top.parent = tnode
if left:
tnode.subtrees.insert(0, top)
else:
tnode.subtrees.append(top)
decisions[pos] = tnode
# TODO: gather stats on the original trees
for null, node in nulls_to_add:
pos = len(node.subtrees)
if null.label.startswith("ADVP"):
pass
elif node.label.startswith("SBAR") or null.label.startswith("NP-SBJ"):
pos = 0
else:
npos = 0
for subnode in node.subtrees:
npos += 1
if subnode.label.startswith("VB"):
pos = npos
if subnode.label.startswith("LST"):
pos = npos + 1
break
if subnode.label.startswith("VP"):
pos = max(0, npos - 1)
break
if len(node.subtrees) > pos:
sub_label = node.subtrees[pos].label
if sub_label.startswith("-L") or sub_label in {",", "LST", "``"}:
pos += 1
node.subtrees.insert(pos, null)
null.parent = node
root.calculate_spans()
# Add traces
max_index = 0
for num in trace_edges:
for tnum, tlabel, snum, slabel, trace in trace_edges[num]:
snode = nodes[snum][4][slabel]
tnode = nodes[tnum][4][tlabel]
if tlabel.endswith("_T") and slabel.endswith("_T"):
tmp = snode
snode = tnode
tnode = tmp
if trace == '=':
identity = get_reference(tnode.label)
if identity is None:
max_index += 1
identity = max_index
tnode.label += "-{}".format(identity)
snode.label += "={}".format(identity)
else:
identity = get_reference(snode.label)
if identity is None:
max_index += 1
identity = max_index
snode.label += "-{}".format(identity)
tnode.subtrees[0].word += "-{}".format(identity)
return root
def clone_and_find(nodes):
'''Clone the tree these nodes are in and finds the equivalent nodes in the
new tree.'''
return_list = True
if type(nodes) != type([]):
return_list = False
nodes = [nodes]
# Note the paths to the nodes
paths = []
for node in nodes:
paths.append([])
tree = node
while tree.parent is not None:
prev = tree
tree = tree.parent
paths[-1].append(tree.subtrees.index(prev))
# Duplicate and follow the path back to the equivalent node
ntree = nodes[0].root().clone()
ans = []
for path in paths:
tree = ntree
for index in path[::-1]:
tree = tree.subtrees[index]
ans.append(tree)
if return_list:
return ans
else:
return ans[0]
if __name__ == '__main__':
print "Running doctest"
import doctest
doctest.testmod() | en | 0.864694 | #!/usr/bin/env python Iterator for traversal of a tree. PSTree uses pre-order traversal by default, but this supports post-order too, e.g.: >>> tree = tree_from_text("(ROOT (S (NP-SBJ (NNP Ms.) (NNP Haag) ) (VP (VBZ plays) (NP (NNP Elianti) )) (. .) ))") >>> for node in TreeIterator(tree, 'post'): ... print node (NNP Ms.) (NNP Haag) (NP-SBJ (NNP Ms.) (NNP Haag)) (VBZ plays) (NNP Elianti) (NP (NNP Elianti)) (VP (VBZ plays) (NP (NNP Elianti))) (. .) (S (NP-SBJ (NNP Ms.) (NNP Haag)) (VP (VBZ plays) (NP (NNP Elianti))) (. .)) (ROOT (S (NP-SBJ (NNP Ms.) (NNP Haag)) (VP (VBZ plays) (NP (NNP Elianti))) (. .))) # For pre-order traversal, return nodes when first reached # Update internal state to point at the next node in the tree Phrase Structure Tree >>> tree = tree_from_text("(ROOT (NP (NNP Newspaper)))") >>> print tree (ROOT (NP (NNP Newspaper))) >>> tree = tree_from_text("(ROOT (S (NP-SBJ (NNP Ms.) (NNP Haag) ) (VP (VBZ plays) (NP (NNP Elianti) )) (. .) ))") >>> print tree (ROOT (S (NP-SBJ (NNP Ms.) (NNP Haag)) (VP (VBZ plays) (NP (NNP Elianti))) (. .))) >>> print tree.word_yield() Ms. Haag plays Elianti . >>> tree = tree_from_text("(ROOT (NFP ...))") >>> print tree (ROOT (NFP ...)) >>> tree.word_yield() '...' >>> tree = tree_from_text("(VP (VBD was) (VP (VBN named) (S (NP-SBJ (-NONE- *-1) ) (NP-PRD (NP (DT a) (JJ nonexecutive) (NN director) ) (PP (IN of) (NP (DT this) (JJ British) (JJ industrial) (NN conglomerate) ))))))") >>> print tree (VP (VBD was) (VP (VBN named) (S (NP-SBJ (-NONE- *-1)) (NP-PRD (NP (DT a) (JJ nonexecutive) (NN director)) (PP (IN of) (NP (DT this) (JJ British) (JJ industrial) (NN conglomerate))))))) >>> tree.word_yield() 'was named *-1 a nonexecutive director of this British industrial conglomerate' Check if the tree has no children. Check if this tree is the end of a trace. Follow parents until a node is reached that has no parent. Return a bracket notation style representation of the tree. # TODO: Shift this to str and add more field info Set a unique numerical ID for each node. Update the spans for every node in this tree. Check that the parents and spans are consistent with the tree structure. Get a list of productions as: (node label, node span, ((subtree1, end1), (subtree2, end2)...)) Return the set of words at terminal nodes, either as a space separated string, or as a list. Get a dictionary of labelled nodes. Note that we use a dictionary to take into consideration unaries like (NP (NP ...)) Get the node(s) that have a given span. Unspecified endpoints are treated as wildcards. The request can be 'lowest', 'highest', or 'all'. For 'all', the list of nodes is in order from the highest first. # Skip subtrees with no overlapping range Construct a PSTree from the provided string, which is assumed to represent a tree with nested round brackets. Nodes are labeled by the text between the open bracket and the next space (possibly an empty string). Words are the text after that space and before the close bracket. # Consume random text up to the first '(' # Work backwards through it Construct a PSTree from the provided split head grammar parse. # Create spine defined non-terminals # Extract data # Make spine # Generate new node # Link together with structural edges, ensuring proper nesting # Identify the top of the spine at this position # Attach it to the target # Check that linking to this node won't cause a crossing # See if this is above our node # TODO: gather stats on the original trees # Add traces Clone the tree these nodes are in and finds the equivalent nodes in the new tree. # Note the paths to the nodes # Duplicate and follow the path back to the equivalent node | 3.413647 | 3 |
Assignment2/5.py | JulianConneely/multiParadigm | 0 | 6614195 | <reponame>JulianConneely/multiParadigm<gh_stars>0
# 5. Replace a given character with '*'. Given a string, and a character to replace,
# return a string where each occurance of the character is replaced with '*'.
# statement
statement = "Recursion is not rocket surgery"
# takes in statement, old character, new character
def replaceChar(statement, old, new):
# if statement contains no characters return nothing.
if statement == '':
return ''
# if the character in the string is the same as the specified character
# then replace it with the new character and call the function recursively.
if statement[0] == old:
return new + replaceChar(statement[1:], old, new)
return statement[0] + replaceChar(statement[1:], old, new)
#old character
old = 'n'
# new character
new = '*'
# call and print the result of replacing the specified character in the statement
print(replaceChar("Recursion is not rocket surgery", 'n', '*')) | # 5. Replace a given character with '*'. Given a string, and a character to replace,
# return a string where each occurance of the character is replaced with '*'.
# statement
statement = "Recursion is not rocket surgery"
# takes in statement, old character, new character
def replaceChar(statement, old, new):
# if statement contains no characters return nothing.
if statement == '':
return ''
# if the character in the string is the same as the specified character
# then replace it with the new character and call the function recursively.
if statement[0] == old:
return new + replaceChar(statement[1:], old, new)
return statement[0] + replaceChar(statement[1:], old, new)
#old character
old = 'n'
# new character
new = '*'
# call and print the result of replacing the specified character in the statement
print(replaceChar("Recursion is not rocket surgery", 'n', '*')) | en | 0.878216 | # 5. Replace a given character with '*'. Given a string, and a character to replace, # return a string where each occurance of the character is replaced with '*'. # statement # takes in statement, old character, new character # if statement contains no characters return nothing. # if the character in the string is the same as the specified character # then replace it with the new character and call the function recursively. #old character # new character # call and print the result of replacing the specified character in the statement | 4.548612 | 5 |
src/701_800/0733_flood-fill/flood-fill.py | himichael/LeetCode | 1 | 6614196 | class Solution(object):
def floodFill(self, image, sr, sc, newColor):
"""
:type image: List[List[int]]
:type sr: int
:type sc: int
:type newColor: int
:rtype: List[List[int]]
"""
if not image:
return image
n = len(image)
m = len(image[0])
val = image[sr][sc]
def dfs(i,j):
if 0<=i<n and 0<=j<m and image[i][j]==val:
image[i][j] = newColor
dfs(i,j+1)
dfs(i,j-1)
dfs(i+1,j)
dfs(i-1,j)
if newColor!=val:
dfs(sr,sc)
return image | class Solution(object):
def floodFill(self, image, sr, sc, newColor):
"""
:type image: List[List[int]]
:type sr: int
:type sc: int
:type newColor: int
:rtype: List[List[int]]
"""
if not image:
return image
n = len(image)
m = len(image[0])
val = image[sr][sc]
def dfs(i,j):
if 0<=i<n and 0<=j<m and image[i][j]==val:
image[i][j] = newColor
dfs(i,j+1)
dfs(i,j-1)
dfs(i+1,j)
dfs(i-1,j)
if newColor!=val:
dfs(sr,sc)
return image | en | 0.197573 | :type image: List[List[int]] :type sr: int :type sc: int :type newColor: int :rtype: List[List[int]] | 3.309824 | 3 |
pythonProject/company.py | NaseerAslamKhan/Salesman-Web-Application | 0 | 6614197 | <reponame>NaseerAslamKhan/Salesman-Web-Application
class Company:
def __init__(self):
f = open("company.txt", "r")
self.name = f.readline()
self.address = f.readline()
self.phone = f.readline()
self.email = f.readline()
self.lowStockLimit = f.readline()
self.excessStockLimit = f.readline()
self.tax = f.readline()
self.discount = f.readline()
self.shippingFee = f.readline()
f.close()
def set(self, name, address, phone, email, low, excess, tax, discount, shippingFee):
f = open("company.txt", "w")
self.name = name
self.address = address
self.phone = phone
self.email = email
self.lowStockLimit = low
self.excessStockLimit = excess
self.tax = tax
self.discount = discount
self.shippingFee = shippingFee
f.write(name+"\n"+address+"\n"+phone+"\n"+email+"\n"+low+"\n"+excess+"\n"+tax+"\n"+discount+"\n"+shippingFee )
f.close() | class Company:
def __init__(self):
f = open("company.txt", "r")
self.name = f.readline()
self.address = f.readline()
self.phone = f.readline()
self.email = f.readline()
self.lowStockLimit = f.readline()
self.excessStockLimit = f.readline()
self.tax = f.readline()
self.discount = f.readline()
self.shippingFee = f.readline()
f.close()
def set(self, name, address, phone, email, low, excess, tax, discount, shippingFee):
f = open("company.txt", "w")
self.name = name
self.address = address
self.phone = phone
self.email = email
self.lowStockLimit = low
self.excessStockLimit = excess
self.tax = tax
self.discount = discount
self.shippingFee = shippingFee
f.write(name+"\n"+address+"\n"+phone+"\n"+email+"\n"+low+"\n"+excess+"\n"+tax+"\n"+discount+"\n"+shippingFee )
f.close() | none | 1 | 3.322245 | 3 | |
floodsystem/geo.py | JamesDht0/hd465 | 0 | 6614198 | # Copyright (C) 2018 <NAME>
#
# SPDX-License-Identifier: MIT
"""This module contains a collection of functions related to
geographical data.
"""
def sorted_by_key(x, i, reverse=False):
"""For a list of lists/tuples, return list sorted by the ith
component of the list/tuple, E.g.
Sort on first entry of tuple:
> sorted_by_key([(1, 2), (5, 1]), 0)
>>> [(1, 2), (5, 1)]
Sort on second entry of tuple:
> sorted_by_key([(1, 2), (5, 1]), 1)
>>> [(5, 1), (1, 2)]
"""
# Sort by distance
def key(element):
return element[i]
return sorted(x, key=key, reverse=reverse)
#from .utils import sorted_by_key # noqa
def rivers_with_station(stations):
#this function gives the set of rivers the input stations are along
river_station = set()
for station in stations:
river_station.add (station.river)
return river_station
def stations_by_river(stations):
#this function gives the dictionary of stations along each river
station_river = {}
for station in stations:
if station.river in station_river.keys():
river = station_river[station.river]
river.append (station.name)
station_river.update({station.river : river})
else:
temp = list()
temp.append(station.name)
station_river.update({station.river :temp})
return station_river
def rivers_by_station_number(stations, N):
unarranged_rivers = list()
river_dict = stations_by_river(stations)
for x in river_dict:
river_tuple = (x , len(river_dict[x]))
unarranged_rivers.append(river_tuple)
arranged_rivers = sorted_by_key(unarranged_rivers,1,reverse=True)
top_N=arranged_rivers[:10]
print(top_N)
n = N
while arranged_rivers[n+1][1] == arranged_rivers[N][1]:
top_N.append(arranged_rivers[n])
n+=1
return top_N
| # Copyright (C) 2018 <NAME>
#
# SPDX-License-Identifier: MIT
"""This module contains a collection of functions related to
geographical data.
"""
def sorted_by_key(x, i, reverse=False):
"""For a list of lists/tuples, return list sorted by the ith
component of the list/tuple, E.g.
Sort on first entry of tuple:
> sorted_by_key([(1, 2), (5, 1]), 0)
>>> [(1, 2), (5, 1)]
Sort on second entry of tuple:
> sorted_by_key([(1, 2), (5, 1]), 1)
>>> [(5, 1), (1, 2)]
"""
# Sort by distance
def key(element):
return element[i]
return sorted(x, key=key, reverse=reverse)
#from .utils import sorted_by_key # noqa
def rivers_with_station(stations):
#this function gives the set of rivers the input stations are along
river_station = set()
for station in stations:
river_station.add (station.river)
return river_station
def stations_by_river(stations):
#this function gives the dictionary of stations along each river
station_river = {}
for station in stations:
if station.river in station_river.keys():
river = station_river[station.river]
river.append (station.name)
station_river.update({station.river : river})
else:
temp = list()
temp.append(station.name)
station_river.update({station.river :temp})
return station_river
def rivers_by_station_number(stations, N):
unarranged_rivers = list()
river_dict = stations_by_river(stations)
for x in river_dict:
river_tuple = (x , len(river_dict[x]))
unarranged_rivers.append(river_tuple)
arranged_rivers = sorted_by_key(unarranged_rivers,1,reverse=True)
top_N=arranged_rivers[:10]
print(top_N)
n = N
while arranged_rivers[n+1][1] == arranged_rivers[N][1]:
top_N.append(arranged_rivers[n])
n+=1
return top_N
| en | 0.6917 | # Copyright (C) 2018 <NAME> # # SPDX-License-Identifier: MIT This module contains a collection of functions related to geographical data. For a list of lists/tuples, return list sorted by the ith component of the list/tuple, E.g. Sort on first entry of tuple: > sorted_by_key([(1, 2), (5, 1]), 0) >>> [(1, 2), (5, 1)] Sort on second entry of tuple: > sorted_by_key([(1, 2), (5, 1]), 1) >>> [(5, 1), (1, 2)] # Sort by distance #from .utils import sorted_by_key # noqa #this function gives the set of rivers the input stations are along #this function gives the dictionary of stations along each river | 4.480607 | 4 |
main.py | bitspilanigroup2/heartdisease | 1 | 6614199 | <reponame>bitspilanigroup2/heartdisease<gh_stars>1-10
import fire
import src.models.predict_model as predictor
from src.models.train_model import Train
class HeartDisease:
def __init__(self):
"""[Class Initialization]
"""
def trainModel(self):
"""[to train the model which includes multiple algorithms like Logistic Regression, SVM]
"""
train = Train()
train.trainModel()
def predictModel(self):
"""[to predict the model]
"""
predictor.Predict()
if __name__ == '__main__':
heartdisease = HeartDisease()
fire.Fire(heartdisease)
| import fire
import src.models.predict_model as predictor
from src.models.train_model import Train
class HeartDisease:
def __init__(self):
"""[Class Initialization]
"""
def trainModel(self):
"""[to train the model which includes multiple algorithms like Logistic Regression, SVM]
"""
train = Train()
train.trainModel()
def predictModel(self):
"""[to predict the model]
"""
predictor.Predict()
if __name__ == '__main__':
heartdisease = HeartDisease()
fire.Fire(heartdisease) | en | 0.908654 | [Class Initialization] [to train the model which includes multiple algorithms like Logistic Regression, SVM] [to predict the model] | 2.862526 | 3 |
peri/test/analyze.py | Jdudre/peri | 9 | 6614200 | from builtins import range, str
import os
import itertools
import re
import glob
import json
from collections import OrderedDict
import numpy as np
import scipy as sp
import scipy.ndimage as nd
import scipy.optimize as opt
from peri import states
from peri.priors import overlap
from peri.util import Tile
from peri.comp.objs import PlatonicSpheresCollection
from peri.logger import log
def sorted_files(globber, num_sort=True, num_indices=None, return_num=False):
"""
Give a globbing expression of files to find. They will be sorted upon return.
This function is most useful when sorting does not provide numerical order,
e.g.:
9 -> 12 returned as 10 11 12 9 by string sort
In this case use num_sort=True, and it will be sorted by numbers whose index
is given by num_indices (possibly None for all numbers) then by string.
"""
files = glob.glob(globber)
files.sort()
if not num_sort:
return files
# sort by numbers if desired
num_indices = num_indices or np.s_[:]
allfiles = []
for fn in files:
nums = re.findall(r'\d+', fn)
data = [int(n) for n in nums[num_indices]] + [fn]
allfiles.append(data)
allfiles = sorted(allfiles)
if return_num:
return allfiles
return [f[-1] for f in allfiles]
def dict_to_pos_rad(d):
"""Given a dictionary of a states params:values, returns the pos & rad."""
p, r = [], []
for i in itertools.count():
try:
p.append([d['sph-{}-{}'.format(i, c)] for c in 'zyx'])
r.append(d['sph-{}-a'.format(i)])
except KeyError:
break
return np.array(p), np.array(r)
def state_to_ordereddict(st, include_iminfo=True):
"""Represents a state as an OrderedDict
Parameters
----------
st : :class:``peri.states.State``
The state to represent.
include_iminfo : Bool, optional
If set, includes two additional keys, ``'image.filename'`` and
``'image.tile'`` with corresponding info about the image.
Default is True.
Returns
-------
``collections.OrderedDict``
"""
od = OrderedDict()
for p in st.params:
od.update({p:st.state[p]})
if include_iminfo:
od.update({ 'image.filename':st.image.filename,
'image.tile':str(st.image.tile)})
return od
def save_as_dict(st, save_name, include_iminfo=True, align_text=True):
"""Saves a state as a json dict file, in a human-readable order.
Parameters
---------
st : :class:``peri.states.State``
The state to save.
save_name : string
Complete filename to save as.
include_iminfo : Bool, optional
If set, includes two additional keys, ``'image.filename'`` and
``'image.tile'`` with corresponding info about the image.
Default is True.
align_text : Bool, optional
Changes json separators to include a newline and tab, to make
the saved dict easier to read by humans. Default is True.
See Also
--------
state_to_ordereddict
batch_saveasdict
"""
if align_text:
separators=(',\n', ':\t')
else:
separators=(', ', ': ')
with open(save_name, 'wb') as f:
json.dump(state_to_ordereddict(st, include_iminfo=include_iminfo),
f, separators=separators)
def batch_saveasdict(load_dir, load_names, save_dir, align_text=True,
include_iminfo=True):
"""
Batch loads state, transforms to an OrderedDict, saves as a json with
extension ``.json``.
Parameters
---------
load_dir : String
The name of the directory to load the states from.
load_names : Iterable
Names of the states to load, without the ``.pkl`` extension.
save_dir: String
The name of the directory to save the json dicts to.
align_text : Bool, optional
Changes json separators to include a newline and tab, to make
the saved dict easier to read by humans. Default is True.
include_iminfo : Bool, optional
If set, includes two additional keys, ``'image.filename'`` and
``'image.tile'`` with corresponding info about the image.
Default is True.
"""
os.chdir(load_dir)
for nm in load_names:
save_name = os.path.join(save_dir, nm + '.json')
try:
st = states.load(nm+'.pkl')
except IOError:
log.error('Missing {}'.format(nm))
continue
log.error('Saving {}'.format(nm))
save_as_dict(st, save_name, include_iminfo=include_iminfo, align_text=
align_text)
def parse_json(filename, inbox=True, inboxrad=False, fullinbox=False):
"""
Parse a json file as saved by batch_saveasdict into positions & radii
Parameters
----------
filename : String
The file name of the json dict to load.
inbox : Bool, optional
Whether to only return particles inside the image. Requires a
key ``'image.tile'`` in the saved json dictionary. Default is
True.
inboxrad : Bool, optional
Whether to only return particles that at least partially
overlap the image. Requires a key ``'image.tile'`` in the saved
json dictionary. Default is False.
fullinbox : Bool, optional
Whether to only return particles completely inside the image.
Requires a key ``'image.tile'`` in the saved json dictionary.
Default is False.
Returns
-------
pos, rad : numpy.ndarray
The particle positions [N, [z,y,x]] and radii [N,].
"""
dct = json.load(open(filename, 'rb'))
#1. Get the particles:
zyxr = []
for a in itertools.count():
try:
zyxr.append([dct['sph-{}-{}'.format(a, c)] for c in 'zyxa'])
except KeyError:
break
zyxr = np.array(zyxr)
pos = zyxr[:,:3].copy()
rad = zyxr[:,-1].copy()
if inbox or inboxrad or fullinbox:
try:
imtile = dct['image.tile']
#using the fact the tile repr is enclosed in ()'s:
ishape_l = eval(imtile.split('(')[-1].split(')')[0])
ishape = np.array(ishape_l)
#alternatively the tile shape could be better saved
except KeyError:
raise KeyError('image.tile not saved in json file.')
mask = good_particles(None, inbox=inbox, inboxrad=inboxrad,
fullinbox=fullinbox, pos=pos, rad=rad, ishape=ishape)
pos = pos[mask].copy()
rad = rad[mask].copy()
return pos, rad
def good_particles(state, inbox=True, inboxrad=False, fullinbox=False,
pos=None, rad=None, ishape=None):
"""
Returns a mask of `good' particles as defined by
* radius > 0
* position inside box
Parameters
----------
state : :class:`peri.states.ImageState`
The state to identify the good particles. If pos, rad, and ishape
are provided, then this does not need to be passed.
inbox : Bool
Whether to only count particle centers within the image. Default
is True.
inboxrad : Bool
Whether to only count particles that overlap the image at all.
Default is False.
fullinbox : Bool
Whether to only include particles which are entirely in the
image. Default is False
pos : [3,N] np.ndarray or None
If not None, the particles' positions.
rad : [N] element numpy.ndarray or None
If not None, the particles' radii.
ishape : 3-element list-like or None
If not None, the inner region of the state.
Returns
-------
mask : np.ndarray of bools
A boolean mask of which particles are good (True) or bad.
See Also
--------
trim_box
"""
if pos is None:
pos = state.obj_get_positions()
if rad is None:
rad = state.obj_get_radii()
mask = rad > 0
if (inbox | inboxrad | fullinbox):
if fullinbox:
mask &= trim_box(state, pos, rad=-rad, ishape=ishape)
elif inboxrad:
mask &= trim_box(state, pos, rad=rad, ishape=ishape)
else:
mask &= trim_box(state, pos, rad=None, ishape=ishape)
return mask
def trim_box(state, p, rad=None, ishape=None):
"""
Returns particles within the image.
If rad is provided, then particles that intersect the image at all
(p-r) > edge are returned.
Parameters
----------
state : :class:`peri.states.ImageState`
The state to analyze.
p : numpy.ndarray
The particle positions
rad : numpy.ndarray or None, optional
Set to a numpy.ndarray to include all particles within `rad`
of the image edge. Default is None, only including particles
within the image.
ishape : list-like or None, optional
3-element list of the region of the interior image. Default is
None, which uses state.ishape.shape (the interior image shape)
Returns
-------
numpy.ndarray
Boolean mask, True for indices of good particle positions.
See Also
--------
good_particles
"""
if ishape is None:
ishape = state.ishape.shape
if rad is None:
return ((p > 0) & (p < np.array(ishape))).all(axis=-1)
return ((p+rad[:,None] > 0) & (p-rad[:,None] < np.array(ishape))).all(axis=-1)
def nearest(p0, p1, cutoff=None):
"""
Correlate closest particles with each other (within cutoff).
Returns ind0, ind1 so that p0[ind0] is close to p1[ind1].
Parameters
----------
p0, p1 : numpy.ndarray
The particle positions.
cutoff : Float or None, optional
If not None, only returns particle indices with distance less
than `cutoff`. Default is None.
Returns
-------
ind0, ind1 : List
The lists of particle indices, p0[ind0] is close to p1[ind1].
"""
ind0, ind1 = [], []
for i in range(len(p0)):
dist = np.sqrt(((p0[i] - p1)**2).sum(axis=-1))
if cutoff is None:
ind1.append(dist.argmin())
elif dist.min() < cutoff:
ind0.append(i)
ind1.append(dist.argmin())
if cutoff is None:
return ind1
return ind0, ind1
def gofr_normal(pos, rad, zscale):
N = rad.shape[0]
z = np.array([zscale, 1, 1])
seps = []
for i in range(N-1):
o = np.arange(0, N)
d = np.sqrt( ((z*(pos[i] - pos[o]))**2).sum(axis=-1) )
seps.extend(d[d!=0])
return np.array(seps)
def gofr_surfaces(pos, rad, zscale):
N = rad.shape[0]
z = np.array([zscale, 1, 1])
seps = []
for i in range(N-1):
o = np.arange(0, N)
d = np.sqrt( ((z*(pos[i] - pos[o]))**2).sum(axis=-1) )
r = rad[i] + rad[o]
diff = (d-r)
seps.extend(diff[diff != 0])
return np.array(seps)
def gofr(pos, rad, zscale, diameter=None, resolution=3e-2, rmax=10, method='normal',
normalize=None, mask_start=None, phi_method='const', phi=None, state=None):
"""
Pair correlation function calculation from 0 to rmax particle diameters
method : str ['normal', 'surface']
represents the gofr calculation method
normalize : boolean
if None, determined by method, otherwise 1/r^2 norm
phi_method : str ['obj', 'state']
which data to use to calculate the packing_fraction.
-- 'pos' : (not stable) calculate based on fractional spheres in
a cube, do not use
-- 'const' : the volume fraction is provided by the user via
the variable phi
-- 'state' : the volume is calculated by using the platonic sphere
image of a given state. must provide argument state
"""
diameter = diameter or 2*rad.mean()
vol_particle = 4./3*np.pi*(diameter)**3
if phi_method == 'const':
phi = phi or 1
if phi_method == 'state':
phi = packing_fraction_state(state)
num_density = phi / vol_particle
if method == 'normal':
normalize = normalize or True
o = gofr_normal(pos, rad, zscale)
rmin = 0
if method == 'surface':
normalize = normalize or False
o = diameter*gofr_surfaces(pos, rad, zscale)
rmin = -1
bins = np.linspace(rmin, diameter*rmax, diameter*rmax/resolution, endpoint=False)
y,x = np.histogram(o, bins=bins)
x = (x[1:] + x[:-1])/2
if mask_start is not None:
mask = x > mask_start
x = x[mask]
y = y[mask]
if normalize:
y = y/(4*np.pi*x**2)
return x/diameter, y/(resolution * num_density * float(len(rad)))
def packing_fraction_obj(pos, rad, shape, inner, zscale=1):
"""
Calculates the packing fraction of a group of spheres.
Operates by creating an accurate, volume-conserving image of spheres
and finding the volume fraction in that image. This correctly deals
with edge-effects.
Parameters
----------
pos : numpy.ndarray
[N,3] array of particle positions. Only the ones inside
shape[inner] are counted.
rad : numpy.ndarray
N-element array of particle radii.
shape : List-like
3-element list-like of the image shape.
inner :
Returns
-------
Float
The volume fraction
"""
obj = PlatonicSpheresCollection(pos, rad, shape=shape, zscale=zscale)
return obj.get()[inner].mean()
def packing_fraction_state(state):
"""
Calculates the packing fraction of a state.
Parameters
----------
state : :class:`peri.states.ImageState`
Returns
-------
Float
The volume fraction
"""
return state.get('obj').get()[state.inner].mean()
def average_packing_fraction(state, samples):
"""
Calculates the packing fraction of a state with a collection of sampled
positions and radii.
Using a collection of sampled radii alows an estimate of the error in
the packing fraction.
Parameters
----------
state : :class:`peri.states.ImageState`
samples : Iterable
List/iterator/generator of the positions and radii at each
independent sample. samples[i] = [pos, rad]
Returns
-------
phi : Float
The mean volume fraction across all samples.
err : Float
The standard error of the mean from the sampling;
phis.std() / sqrt(len(phis))
"""
phi = []
for p,r in iter_pos_rad(state, samples):
phi.append(packing_fraction(p,r,state=state))
phi = np.array(phi)
return phi.mean(axis=0)[0], phi.std(axis=0)[0]/np.sqrt(len(phi))
| from builtins import range, str
import os
import itertools
import re
import glob
import json
from collections import OrderedDict
import numpy as np
import scipy as sp
import scipy.ndimage as nd
import scipy.optimize as opt
from peri import states
from peri.priors import overlap
from peri.util import Tile
from peri.comp.objs import PlatonicSpheresCollection
from peri.logger import log
def sorted_files(globber, num_sort=True, num_indices=None, return_num=False):
"""
Give a globbing expression of files to find. They will be sorted upon return.
This function is most useful when sorting does not provide numerical order,
e.g.:
9 -> 12 returned as 10 11 12 9 by string sort
In this case use num_sort=True, and it will be sorted by numbers whose index
is given by num_indices (possibly None for all numbers) then by string.
"""
files = glob.glob(globber)
files.sort()
if not num_sort:
return files
# sort by numbers if desired
num_indices = num_indices or np.s_[:]
allfiles = []
for fn in files:
nums = re.findall(r'\d+', fn)
data = [int(n) for n in nums[num_indices]] + [fn]
allfiles.append(data)
allfiles = sorted(allfiles)
if return_num:
return allfiles
return [f[-1] for f in allfiles]
def dict_to_pos_rad(d):
"""Given a dictionary of a states params:values, returns the pos & rad."""
p, r = [], []
for i in itertools.count():
try:
p.append([d['sph-{}-{}'.format(i, c)] for c in 'zyx'])
r.append(d['sph-{}-a'.format(i)])
except KeyError:
break
return np.array(p), np.array(r)
def state_to_ordereddict(st, include_iminfo=True):
"""Represents a state as an OrderedDict
Parameters
----------
st : :class:``peri.states.State``
The state to represent.
include_iminfo : Bool, optional
If set, includes two additional keys, ``'image.filename'`` and
``'image.tile'`` with corresponding info about the image.
Default is True.
Returns
-------
``collections.OrderedDict``
"""
od = OrderedDict()
for p in st.params:
od.update({p:st.state[p]})
if include_iminfo:
od.update({ 'image.filename':st.image.filename,
'image.tile':str(st.image.tile)})
return od
def save_as_dict(st, save_name, include_iminfo=True, align_text=True):
"""Saves a state as a json dict file, in a human-readable order.
Parameters
---------
st : :class:``peri.states.State``
The state to save.
save_name : string
Complete filename to save as.
include_iminfo : Bool, optional
If set, includes two additional keys, ``'image.filename'`` and
``'image.tile'`` with corresponding info about the image.
Default is True.
align_text : Bool, optional
Changes json separators to include a newline and tab, to make
the saved dict easier to read by humans. Default is True.
See Also
--------
state_to_ordereddict
batch_saveasdict
"""
if align_text:
separators=(',\n', ':\t')
else:
separators=(', ', ': ')
with open(save_name, 'wb') as f:
json.dump(state_to_ordereddict(st, include_iminfo=include_iminfo),
f, separators=separators)
def batch_saveasdict(load_dir, load_names, save_dir, align_text=True,
include_iminfo=True):
"""
Batch loads state, transforms to an OrderedDict, saves as a json with
extension ``.json``.
Parameters
---------
load_dir : String
The name of the directory to load the states from.
load_names : Iterable
Names of the states to load, without the ``.pkl`` extension.
save_dir: String
The name of the directory to save the json dicts to.
align_text : Bool, optional
Changes json separators to include a newline and tab, to make
the saved dict easier to read by humans. Default is True.
include_iminfo : Bool, optional
If set, includes two additional keys, ``'image.filename'`` and
``'image.tile'`` with corresponding info about the image.
Default is True.
"""
os.chdir(load_dir)
for nm in load_names:
save_name = os.path.join(save_dir, nm + '.json')
try:
st = states.load(nm+'.pkl')
except IOError:
log.error('Missing {}'.format(nm))
continue
log.error('Saving {}'.format(nm))
save_as_dict(st, save_name, include_iminfo=include_iminfo, align_text=
align_text)
def parse_json(filename, inbox=True, inboxrad=False, fullinbox=False):
"""
Parse a json file as saved by batch_saveasdict into positions & radii
Parameters
----------
filename : String
The file name of the json dict to load.
inbox : Bool, optional
Whether to only return particles inside the image. Requires a
key ``'image.tile'`` in the saved json dictionary. Default is
True.
inboxrad : Bool, optional
Whether to only return particles that at least partially
overlap the image. Requires a key ``'image.tile'`` in the saved
json dictionary. Default is False.
fullinbox : Bool, optional
Whether to only return particles completely inside the image.
Requires a key ``'image.tile'`` in the saved json dictionary.
Default is False.
Returns
-------
pos, rad : numpy.ndarray
The particle positions [N, [z,y,x]] and radii [N,].
"""
dct = json.load(open(filename, 'rb'))
#1. Get the particles:
zyxr = []
for a in itertools.count():
try:
zyxr.append([dct['sph-{}-{}'.format(a, c)] for c in 'zyxa'])
except KeyError:
break
zyxr = np.array(zyxr)
pos = zyxr[:,:3].copy()
rad = zyxr[:,-1].copy()
if inbox or inboxrad or fullinbox:
try:
imtile = dct['image.tile']
#using the fact the tile repr is enclosed in ()'s:
ishape_l = eval(imtile.split('(')[-1].split(')')[0])
ishape = np.array(ishape_l)
#alternatively the tile shape could be better saved
except KeyError:
raise KeyError('image.tile not saved in json file.')
mask = good_particles(None, inbox=inbox, inboxrad=inboxrad,
fullinbox=fullinbox, pos=pos, rad=rad, ishape=ishape)
pos = pos[mask].copy()
rad = rad[mask].copy()
return pos, rad
def good_particles(state, inbox=True, inboxrad=False, fullinbox=False,
pos=None, rad=None, ishape=None):
"""
Returns a mask of `good' particles as defined by
* radius > 0
* position inside box
Parameters
----------
state : :class:`peri.states.ImageState`
The state to identify the good particles. If pos, rad, and ishape
are provided, then this does not need to be passed.
inbox : Bool
Whether to only count particle centers within the image. Default
is True.
inboxrad : Bool
Whether to only count particles that overlap the image at all.
Default is False.
fullinbox : Bool
Whether to only include particles which are entirely in the
image. Default is False
pos : [3,N] np.ndarray or None
If not None, the particles' positions.
rad : [N] element numpy.ndarray or None
If not None, the particles' radii.
ishape : 3-element list-like or None
If not None, the inner region of the state.
Returns
-------
mask : np.ndarray of bools
A boolean mask of which particles are good (True) or bad.
See Also
--------
trim_box
"""
if pos is None:
pos = state.obj_get_positions()
if rad is None:
rad = state.obj_get_radii()
mask = rad > 0
if (inbox | inboxrad | fullinbox):
if fullinbox:
mask &= trim_box(state, pos, rad=-rad, ishape=ishape)
elif inboxrad:
mask &= trim_box(state, pos, rad=rad, ishape=ishape)
else:
mask &= trim_box(state, pos, rad=None, ishape=ishape)
return mask
def trim_box(state, p, rad=None, ishape=None):
"""
Returns particles within the image.
If rad is provided, then particles that intersect the image at all
(p-r) > edge are returned.
Parameters
----------
state : :class:`peri.states.ImageState`
The state to analyze.
p : numpy.ndarray
The particle positions
rad : numpy.ndarray or None, optional
Set to a numpy.ndarray to include all particles within `rad`
of the image edge. Default is None, only including particles
within the image.
ishape : list-like or None, optional
3-element list of the region of the interior image. Default is
None, which uses state.ishape.shape (the interior image shape)
Returns
-------
numpy.ndarray
Boolean mask, True for indices of good particle positions.
See Also
--------
good_particles
"""
if ishape is None:
ishape = state.ishape.shape
if rad is None:
return ((p > 0) & (p < np.array(ishape))).all(axis=-1)
return ((p+rad[:,None] > 0) & (p-rad[:,None] < np.array(ishape))).all(axis=-1)
def nearest(p0, p1, cutoff=None):
"""
Correlate closest particles with each other (within cutoff).
Returns ind0, ind1 so that p0[ind0] is close to p1[ind1].
Parameters
----------
p0, p1 : numpy.ndarray
The particle positions.
cutoff : Float or None, optional
If not None, only returns particle indices with distance less
than `cutoff`. Default is None.
Returns
-------
ind0, ind1 : List
The lists of particle indices, p0[ind0] is close to p1[ind1].
"""
ind0, ind1 = [], []
for i in range(len(p0)):
dist = np.sqrt(((p0[i] - p1)**2).sum(axis=-1))
if cutoff is None:
ind1.append(dist.argmin())
elif dist.min() < cutoff:
ind0.append(i)
ind1.append(dist.argmin())
if cutoff is None:
return ind1
return ind0, ind1
def gofr_normal(pos, rad, zscale):
N = rad.shape[0]
z = np.array([zscale, 1, 1])
seps = []
for i in range(N-1):
o = np.arange(0, N)
d = np.sqrt( ((z*(pos[i] - pos[o]))**2).sum(axis=-1) )
seps.extend(d[d!=0])
return np.array(seps)
def gofr_surfaces(pos, rad, zscale):
N = rad.shape[0]
z = np.array([zscale, 1, 1])
seps = []
for i in range(N-1):
o = np.arange(0, N)
d = np.sqrt( ((z*(pos[i] - pos[o]))**2).sum(axis=-1) )
r = rad[i] + rad[o]
diff = (d-r)
seps.extend(diff[diff != 0])
return np.array(seps)
def gofr(pos, rad, zscale, diameter=None, resolution=3e-2, rmax=10, method='normal',
normalize=None, mask_start=None, phi_method='const', phi=None, state=None):
"""
Pair correlation function calculation from 0 to rmax particle diameters
method : str ['normal', 'surface']
represents the gofr calculation method
normalize : boolean
if None, determined by method, otherwise 1/r^2 norm
phi_method : str ['obj', 'state']
which data to use to calculate the packing_fraction.
-- 'pos' : (not stable) calculate based on fractional spheres in
a cube, do not use
-- 'const' : the volume fraction is provided by the user via
the variable phi
-- 'state' : the volume is calculated by using the platonic sphere
image of a given state. must provide argument state
"""
diameter = diameter or 2*rad.mean()
vol_particle = 4./3*np.pi*(diameter)**3
if phi_method == 'const':
phi = phi or 1
if phi_method == 'state':
phi = packing_fraction_state(state)
num_density = phi / vol_particle
if method == 'normal':
normalize = normalize or True
o = gofr_normal(pos, rad, zscale)
rmin = 0
if method == 'surface':
normalize = normalize or False
o = diameter*gofr_surfaces(pos, rad, zscale)
rmin = -1
bins = np.linspace(rmin, diameter*rmax, diameter*rmax/resolution, endpoint=False)
y,x = np.histogram(o, bins=bins)
x = (x[1:] + x[:-1])/2
if mask_start is not None:
mask = x > mask_start
x = x[mask]
y = y[mask]
if normalize:
y = y/(4*np.pi*x**2)
return x/diameter, y/(resolution * num_density * float(len(rad)))
def packing_fraction_obj(pos, rad, shape, inner, zscale=1):
"""
Calculates the packing fraction of a group of spheres.
Operates by creating an accurate, volume-conserving image of spheres
and finding the volume fraction in that image. This correctly deals
with edge-effects.
Parameters
----------
pos : numpy.ndarray
[N,3] array of particle positions. Only the ones inside
shape[inner] are counted.
rad : numpy.ndarray
N-element array of particle radii.
shape : List-like
3-element list-like of the image shape.
inner :
Returns
-------
Float
The volume fraction
"""
obj = PlatonicSpheresCollection(pos, rad, shape=shape, zscale=zscale)
return obj.get()[inner].mean()
def packing_fraction_state(state):
"""
Calculates the packing fraction of a state.
Parameters
----------
state : :class:`peri.states.ImageState`
Returns
-------
Float
The volume fraction
"""
return state.get('obj').get()[state.inner].mean()
def average_packing_fraction(state, samples):
"""
Calculates the packing fraction of a state with a collection of sampled
positions and radii.
Using a collection of sampled radii alows an estimate of the error in
the packing fraction.
Parameters
----------
state : :class:`peri.states.ImageState`
samples : Iterable
List/iterator/generator of the positions and radii at each
independent sample. samples[i] = [pos, rad]
Returns
-------
phi : Float
The mean volume fraction across all samples.
err : Float
The standard error of the mean from the sampling;
phis.std() / sqrt(len(phis))
"""
phi = []
for p,r in iter_pos_rad(state, samples):
phi.append(packing_fraction(p,r,state=state))
phi = np.array(phi)
return phi.mean(axis=0)[0], phi.std(axis=0)[0]/np.sqrt(len(phi))
| en | 0.731493 | Give a globbing expression of files to find. They will be sorted upon return. This function is most useful when sorting does not provide numerical order, e.g.: 9 -> 12 returned as 10 11 12 9 by string sort In this case use num_sort=True, and it will be sorted by numbers whose index is given by num_indices (possibly None for all numbers) then by string. # sort by numbers if desired Given a dictionary of a states params:values, returns the pos & rad. Represents a state as an OrderedDict Parameters ---------- st : :class:``peri.states.State`` The state to represent. include_iminfo : Bool, optional If set, includes two additional keys, ``'image.filename'`` and ``'image.tile'`` with corresponding info about the image. Default is True. Returns ------- ``collections.OrderedDict`` Saves a state as a json dict file, in a human-readable order. Parameters --------- st : :class:``peri.states.State`` The state to save. save_name : string Complete filename to save as. include_iminfo : Bool, optional If set, includes two additional keys, ``'image.filename'`` and ``'image.tile'`` with corresponding info about the image. Default is True. align_text : Bool, optional Changes json separators to include a newline and tab, to make the saved dict easier to read by humans. Default is True. See Also -------- state_to_ordereddict batch_saveasdict Batch loads state, transforms to an OrderedDict, saves as a json with extension ``.json``. Parameters --------- load_dir : String The name of the directory to load the states from. load_names : Iterable Names of the states to load, without the ``.pkl`` extension. save_dir: String The name of the directory to save the json dicts to. align_text : Bool, optional Changes json separators to include a newline and tab, to make the saved dict easier to read by humans. Default is True. include_iminfo : Bool, optional If set, includes two additional keys, ``'image.filename'`` and ``'image.tile'`` with corresponding info about the image. Default is True. Parse a json file as saved by batch_saveasdict into positions & radii Parameters ---------- filename : String The file name of the json dict to load. inbox : Bool, optional Whether to only return particles inside the image. Requires a key ``'image.tile'`` in the saved json dictionary. Default is True. inboxrad : Bool, optional Whether to only return particles that at least partially overlap the image. Requires a key ``'image.tile'`` in the saved json dictionary. Default is False. fullinbox : Bool, optional Whether to only return particles completely inside the image. Requires a key ``'image.tile'`` in the saved json dictionary. Default is False. Returns ------- pos, rad : numpy.ndarray The particle positions [N, [z,y,x]] and radii [N,]. #1. Get the particles: #using the fact the tile repr is enclosed in ()'s: #alternatively the tile shape could be better saved Returns a mask of `good' particles as defined by * radius > 0 * position inside box Parameters ---------- state : :class:`peri.states.ImageState` The state to identify the good particles. If pos, rad, and ishape are provided, then this does not need to be passed. inbox : Bool Whether to only count particle centers within the image. Default is True. inboxrad : Bool Whether to only count particles that overlap the image at all. Default is False. fullinbox : Bool Whether to only include particles which are entirely in the image. Default is False pos : [3,N] np.ndarray or None If not None, the particles' positions. rad : [N] element numpy.ndarray or None If not None, the particles' radii. ishape : 3-element list-like or None If not None, the inner region of the state. Returns ------- mask : np.ndarray of bools A boolean mask of which particles are good (True) or bad. See Also -------- trim_box Returns particles within the image. If rad is provided, then particles that intersect the image at all (p-r) > edge are returned. Parameters ---------- state : :class:`peri.states.ImageState` The state to analyze. p : numpy.ndarray The particle positions rad : numpy.ndarray or None, optional Set to a numpy.ndarray to include all particles within `rad` of the image edge. Default is None, only including particles within the image. ishape : list-like or None, optional 3-element list of the region of the interior image. Default is None, which uses state.ishape.shape (the interior image shape) Returns ------- numpy.ndarray Boolean mask, True for indices of good particle positions. See Also -------- good_particles Correlate closest particles with each other (within cutoff). Returns ind0, ind1 so that p0[ind0] is close to p1[ind1]. Parameters ---------- p0, p1 : numpy.ndarray The particle positions. cutoff : Float or None, optional If not None, only returns particle indices with distance less than `cutoff`. Default is None. Returns ------- ind0, ind1 : List The lists of particle indices, p0[ind0] is close to p1[ind1]. Pair correlation function calculation from 0 to rmax particle diameters method : str ['normal', 'surface'] represents the gofr calculation method normalize : boolean if None, determined by method, otherwise 1/r^2 norm phi_method : str ['obj', 'state'] which data to use to calculate the packing_fraction. -- 'pos' : (not stable) calculate based on fractional spheres in a cube, do not use -- 'const' : the volume fraction is provided by the user via the variable phi -- 'state' : the volume is calculated by using the platonic sphere image of a given state. must provide argument state Calculates the packing fraction of a group of spheres. Operates by creating an accurate, volume-conserving image of spheres and finding the volume fraction in that image. This correctly deals with edge-effects. Parameters ---------- pos : numpy.ndarray [N,3] array of particle positions. Only the ones inside shape[inner] are counted. rad : numpy.ndarray N-element array of particle radii. shape : List-like 3-element list-like of the image shape. inner : Returns ------- Float The volume fraction Calculates the packing fraction of a state. Parameters ---------- state : :class:`peri.states.ImageState` Returns ------- Float The volume fraction Calculates the packing fraction of a state with a collection of sampled positions and radii. Using a collection of sampled radii alows an estimate of the error in the packing fraction. Parameters ---------- state : :class:`peri.states.ImageState` samples : Iterable List/iterator/generator of the positions and radii at each independent sample. samples[i] = [pos, rad] Returns ------- phi : Float The mean volume fraction across all samples. err : Float The standard error of the mean from the sampling; phis.std() / sqrt(len(phis)) | 2.506292 | 3 |
tests/__init__.py | ismael-mendoza/BlendingToolKit | 0 | 6614201 | """Test suite for the btk package."""
| """Test suite for the btk package."""
| en | 0.474085 | Test suite for the btk package. | 0.931745 | 1 |
api.py | Soumitra-Mandal/Book-Review-REST-API | 1 | 6614202 | # -*- coding: utf-8 -*-
"""
Created on Fri Jun 26 10:55:19 2020
@author: Soumitra
"""
from bson import json_util
import json
import pprint
from pymongo import MongoClient #python module MongoDb
url = 'mongodb://localhost:27017/' #url for connecting to mongo server
client = MongoClient(url)
db = client.bookreview #this is a database
doc = db.doc #this is a table/collection
from flask import Flask,request, redirect, url_for, jsonify, render_template
app = Flask(__name__)
@app.route('/books', methods = ['GET'])
def indexget():
view = db.doc.find()
l = []
for i in view:
i.pop("_id")
l.append(i)
return jsonify(l)
#return render_template("viewer.html",content = view, p = json.dumps)
@app.route('/books', methods = ['POST'])
def indexpost():
args = request.args
data = {"Name":args.get("name"),"Book":args.get("book"),"Review":args.get("review"),"Rating":args.get("rating")}
doc.insert_one(data)
return "<h1>Successfully posted new review.</h1>"
@app.route('/books', methods = ['PUT'])
def indexput():
return "<h1>put operation not possible</h1>"
@app.route('/books', methods = ['DELETE'])
def indexdelete():
db.doc.drop()
return "<h1>Deleting all book reivews</h1>"
@app.route('/books/<username>',methods = ["GET"])
def get(username):
data = db.doc.find_one({"Name":username})
if(data==None):
return f'<h1>Data for {username} does not exist!</h1>'
else:
data.pop("_id")
print(f"successfully retrieved review for user {username}!")
return data
@app.route('/books/<username>', methods = ['POST'])
def post(username):
args = request.args
data = {"Name":username,"Book":args.get("book"),"Review":args.get("review"),"Rating":args.get("rating")}
doc.insert_one(data)
return f"<h1>Successfully posted new review for user {username}</h1>"
@app.route('/books/<username>', methods = ['PUT'])
def put(username):
args = request.args
result = db.doc.update_one({'Name':username},{'$set':{'Review':args.get("review"),"Rating":args.get("rating")}})
if(result.matched_count == 1 and result.modified_count == 1):
return f"<h1>Successfully updated review for user {username}!</h1>"
else:
return "<h1>Failed to update!</h1>"
@app.route('/books/<username>', methods = ['DELETE'])
def delete(username):
result = db.doc.delete_one({'Name':username})
if(result.deleted_count == 1):
return f"<h1>Successfully deleted review for user {username}!</h1>"
else:
return "<h1>Failed to update.</h1>"
if __name__ == '__main__':
app.run(debug = True)
| # -*- coding: utf-8 -*-
"""
Created on Fri Jun 26 10:55:19 2020
@author: Soumitra
"""
from bson import json_util
import json
import pprint
from pymongo import MongoClient #python module MongoDb
url = 'mongodb://localhost:27017/' #url for connecting to mongo server
client = MongoClient(url)
db = client.bookreview #this is a database
doc = db.doc #this is a table/collection
from flask import Flask,request, redirect, url_for, jsonify, render_template
app = Flask(__name__)
@app.route('/books', methods = ['GET'])
def indexget():
view = db.doc.find()
l = []
for i in view:
i.pop("_id")
l.append(i)
return jsonify(l)
#return render_template("viewer.html",content = view, p = json.dumps)
@app.route('/books', methods = ['POST'])
def indexpost():
args = request.args
data = {"Name":args.get("name"),"Book":args.get("book"),"Review":args.get("review"),"Rating":args.get("rating")}
doc.insert_one(data)
return "<h1>Successfully posted new review.</h1>"
@app.route('/books', methods = ['PUT'])
def indexput():
return "<h1>put operation not possible</h1>"
@app.route('/books', methods = ['DELETE'])
def indexdelete():
db.doc.drop()
return "<h1>Deleting all book reivews</h1>"
@app.route('/books/<username>',methods = ["GET"])
def get(username):
data = db.doc.find_one({"Name":username})
if(data==None):
return f'<h1>Data for {username} does not exist!</h1>'
else:
data.pop("_id")
print(f"successfully retrieved review for user {username}!")
return data
@app.route('/books/<username>', methods = ['POST'])
def post(username):
args = request.args
data = {"Name":username,"Book":args.get("book"),"Review":args.get("review"),"Rating":args.get("rating")}
doc.insert_one(data)
return f"<h1>Successfully posted new review for user {username}</h1>"
@app.route('/books/<username>', methods = ['PUT'])
def put(username):
args = request.args
result = db.doc.update_one({'Name':username},{'$set':{'Review':args.get("review"),"Rating":args.get("rating")}})
if(result.matched_count == 1 and result.modified_count == 1):
return f"<h1>Successfully updated review for user {username}!</h1>"
else:
return "<h1>Failed to update!</h1>"
@app.route('/books/<username>', methods = ['DELETE'])
def delete(username):
result = db.doc.delete_one({'Name':username})
if(result.deleted_count == 1):
return f"<h1>Successfully deleted review for user {username}!</h1>"
else:
return "<h1>Failed to update.</h1>"
if __name__ == '__main__':
app.run(debug = True)
| en | 0.720992 | # -*- coding: utf-8 -*- Created on Fri Jun 26 10:55:19 2020
@author: Soumitra #python module MongoDb #url for connecting to mongo server #this is a database #this is a table/collection #return render_template("viewer.html",content = view, p = json.dumps) | 3.164949 | 3 |
test/international_street/candidate_test.py | jasonrfarkas/smartystreets-python-sdk | 19 | 6614203 | import unittest
from smartystreets_python_sdk import NativeSerializer
from smartystreets_python_sdk.international_street import Candidate
class TestCandidate(unittest.TestCase):
def test_all_fields_filled_correctly(self):
response_payload = "[{\"input_id\":\"12345678\",\"organization\":\"1\",\"address1\":\"2\",\"address2\":\"3\","\
"\"address3\":\"4\",\"address4\":\"5\",\"address5\":\"6\",\"address6\":\"7\",\"address7\":\"8\","\
"\"address8\":\"9\",\"address9\":\"10\",\"address10\":\"11\",\"address11\":\"12\",\"address12\":\"13\","\
"\"components\":{\"country_iso_3\":\"14\",\"super_administrative_area\":\"15\","\
"\"administrative_area\":\"16\",\"sub_administrative_area\":\"17\",\"dependent_locality\":\"18\","\
"\"dependent_locality_name\":\"19\",\"double_dependent_locality\":\"20\",\"locality\":\"21\","\
"\"postal_code\":\"22\",\"postal_code_short\":\"23\",\"postal_code_extra\":\"24\","\
"\"premise\":\"25\",\"premise_extra\":\"26\",\"premise_number\":\"27\"," \
"\"premise_prefix_number\":\"27.5\",\"premise_type\":\"28\","\
"\"thoroughfare\":\"29\",\"thoroughfare_predirection\":\"30\",\"thoroughfare_postdirection\":\"31\","\
"\"thoroughfare_name\":\"32\",\"thoroughfare_trailing_type\":\"33\",\"thoroughfare_type\":\"34\","\
"\"dependent_thoroughfare\":\"35\",\"dependent_thoroughfare_predirection\":\"36\","\
"\"dependent_thoroughfare_postdirection\":\"37\",\"dependent_thoroughfare_name\":\"38\","\
"\"dependent_thoroughfare_trailing_type\":\"39\",\"dependent_thoroughfare_type\":\"40\","\
"\"building\":\"41\",\"building_leading_type\":\"42\",\"building_name\":\"43\","\
"\"building_trailing_type\":\"44\",\"sub_building_type\":\"45\",\"sub_building_number\":\"46\","\
"\"sub_building_name\":\"47\",\"sub_building\":\"48\",\"post_box\":\"49\",\"post_box_type\":\"50\","\
"\"post_box_number\":\"51\"},\"metadata\":{\"latitude\":52.0,\"longitude\":53.0,"\
"\"geocode_precision\":\"54\",\"max_geocode_precision\":\"55\",\"address_format\":\"56\"},"\
"\"analysis\":{\"verification_status\":\"57\",\"address_precision\":\"58\","\
"\"max_address_precision\":\"59\",\"changes\":{\"organization\":\"60\","\
"\"address1\":\"61\",\"address2\":\"62\",\"address3\":\"63\",\"address4\":\"64\",\"address5\":\"65\","\
"\"address6\":\"66\",\"address7\":\"67\",\"address8\":\"68\",\"address9\":\"69\",\"address10\":\"70\","\
"\"address11\":\"71\",\"address12\":\"72\",\"components\":{\"super_administrative_area\":\"73\","\
"\"administrative_area\":\"74\",\"sub_administrative_area\":\"75\",\"building\":\"76\","\
"\"dependent_locality\":\"77\",\"dependent_locality_name\":\"78\",\"double_dependent_locality\":\"79\","\
"\"country_iso_3\":\"80\",\"locality\":\"81\",\"postal_code\":\"82\",\"postal_code_short\":\"83\","\
"\"postal_code_extra\":\"84\",\"premise\":\"85\",\"premise_extra\":\"86\",\"premise_number\":\"87\","\
"\"premise_type\":\"88\",\"premise_prefix_number\":\"89\",\"thoroughfare\":\"90\","\
"\"thoroughfare_predirection\":\"91\",\"thoroughfare_postdirection\":\"92\","\
"\"thoroughfare_name\":\"93\",\"thoroughfare_trailing_type\":\"94\",\"thoroughfare_type\":\"95\","\
"\"dependent_thoroughfare\":\"96\",\"dependent_thoroughfare_predirection\":\"97\","\
"\"dependent_thoroughfare_postdirection\":\"98\",\"dependent_thoroughfare_name\":\"99\","\
"\"dependent_thoroughfare_trailing_type\":\"100\",\"dependent_thoroughfare_type\":\"101\","\
"\"building_leading_type\":\"102\",\"building_name\":\"103\",\"building_trailing_type\":\"104\","\
"\"sub_building_type\":\"105\",\"sub_building_number\":\"106\",\"sub_building_name\":\"107\","\
"\"sub_building\":\"108\",\"post_box\":\"109\",\"post_box_type\":\"110\",\"post_box_number\":\"111\"}}}}]"
serializer = NativeSerializer()
candidate = Candidate(serializer.deserialize(response_payload)[0])
self.assertEqual("12345678", candidate.input_id)
self.assertEqual("1", candidate.organization)
self.assertEqual("2", candidate.address1)
self.assertEqual("3", candidate.address2)
self.assertEqual("4", candidate.address3)
self.assertEqual("5", candidate.address4)
self.assertEqual("6", candidate.address5)
self.assertEqual("7", candidate.address6)
self.assertEqual("8", candidate.address7)
self.assertEqual("9", candidate.address8)
self.assertEqual("10", candidate.address9)
self.assertEqual("11", candidate.address10)
self.assertEqual("12", candidate.address11)
self.assertEqual("13", candidate.address12)
components = candidate.components
self.assertIsNotNone(components)
self.assertEqual("14", components.country_iso_3)
self.assertEqual("15", components.super_administrative_area)
self.assertEqual("16", components.administrative_area)
self.assertEqual("17", components.sub_administrative_area)
self.assertEqual("18", components.dependent_locality)
self.assertEqual("19", components.dependent_locality_name)
self.assertEqual("20", components.double_dependent_locality)
self.assertEqual("21", components.locality)
self.assertEqual("22", components.postal_code)
self.assertEqual("23", components.postal_code_short)
self.assertEqual("24", components.postal_code_extra)
self.assertEqual("25", components.premise)
self.assertEqual("26", components.premise_extra)
self.assertEqual("27", components.premise_number)
self.assertEqual("27.5", components.premise_prefix_number)
self.assertEqual("28", components.premise_type)
self.assertEqual("29", components.thoroughfare)
self.assertEqual("30", components.thoroughfare_predirection)
self.assertEqual("31", components.thoroughfare_postdirection)
self.assertEqual("32", components.thoroughfare_name)
self.assertEqual("33", components.thoroughfare_trailing_type)
self.assertEqual("34", components.thoroughfare_type)
self.assertEqual("35", components.dependent_thoroughfare)
self.assertEqual("36", components.dependent_thoroughfare_predirection)
self.assertEqual("37", components.dependent_thoroughfare_postdirection)
self.assertEqual("38", components.dependent_thoroughfare_name)
self.assertEqual("39", components.dependent_thoroughfare_trailing_type)
self.assertEqual("40", components.dependent_thoroughfare_type)
self.assertEqual("41", components.building)
self.assertEqual("42", components.building_leading_type)
self.assertEqual("43", components.building_name)
self.assertEqual("44", components.building_trailing_type)
self.assertEqual("45", components.sub_building_type)
self.assertEqual("46", components.sub_building_number)
self.assertEqual("47", components.sub_building_name)
self.assertEqual("48", components.sub_building)
self.assertEqual("49", components.post_box)
self.assertEqual("50", components.post_box_type)
self.assertEqual("51", components.post_box_number)
metadata = candidate.metadata
self.assertIsNotNone(metadata)
self.assertEqual(52, metadata.latitude, 0.001)
self.assertEqual(53, metadata.longitude, 0.001)
self.assertEqual("54", metadata.geocode_precision)
self.assertEqual("55", metadata.max_geocode_precision)
self.assertEqual("56", metadata.address_format)
analysis = candidate.analysis
self.assertIsNotNone(analysis)
self.assertEqual("57", analysis.verification_status)
self.assertEqual("58", analysis.address_precision)
self.assertEqual("59", analysis.max_address_precision)
changes = analysis.changes
self.assertIsNotNone(changes)
self.assertEqual("60", changes.organization)
self.assertEqual("61", changes.address1)
self.assertEqual("62", changes.address2)
self.assertEqual("63", changes.address3)
self.assertEqual("64", changes.address4)
self.assertEqual("65", changes.address5)
self.assertEqual("66", changes.address6)
self.assertEqual("67", changes.address7)
self.assertEqual("68", changes.address8)
self.assertEqual("69", changes.address9)
self.assertEqual("70", changes.address10)
self.assertEqual("71", changes.address11)
self.assertEqual("72", changes.address12)
components = changes.components
self.assertIsNotNone(components)
self.assertEqual("73", components.super_administrative_area)
self.assertEqual("74", components.administrative_area)
self.assertEqual("75", components.sub_administrative_area)
self.assertEqual("76", components.building)
self.assertEqual("77", components.dependent_locality)
self.assertEqual("78", components.dependent_locality_name)
self.assertEqual("79", components.double_dependent_locality)
self.assertEqual("80", components.country_iso_3)
self.assertEqual("81", components.locality)
self.assertEqual("82", components.postal_code)
self.assertEqual("83", components.postal_code_short)
self.assertEqual("84", components.postal_code_extra)
self.assertEqual("85", components.premise)
self.assertEqual("86", components.premise_extra)
self.assertEqual("87", components.premise_number)
self.assertEqual("88", components.premise_type)
self.assertEqual("89", components.premise_prefix_number)
self.assertEqual("90", components.thoroughfare)
self.assertEqual("91", components.thoroughfare_predirection)
self.assertEqual("92", components.thoroughfare_postdirection)
self.assertEqual("93", components.thoroughfare_name)
self.assertEqual("94", components.thoroughfare_trailing_type)
self.assertEqual("95", components.thoroughfare_type)
self.assertEqual("96", components.dependent_thoroughfare)
self.assertEqual("97", components.dependent_thoroughfare_predirection)
self.assertEqual("98", components.dependent_thoroughfare_postdirection)
self.assertEqual("99", components.dependent_thoroughfare_name)
self.assertEqual("100", components.dependent_thoroughfare_trailing_type)
self.assertEqual("101", components.dependent_thoroughfare_type)
self.assertEqual("102", components.building_leading_type)
self.assertEqual("103", components.building_name)
self.assertEqual("104", components.building_trailing_type)
self.assertEqual("105", components.sub_building_type)
self.assertEqual("106", components.sub_building_number)
self.assertEqual("107", components.sub_building_name)
self.assertEqual("108", components.sub_building)
self.assertEqual("109", components.post_box)
self.assertEqual("110", components.post_box_type)
self.assertEqual("111", components.post_box_number)
| import unittest
from smartystreets_python_sdk import NativeSerializer
from smartystreets_python_sdk.international_street import Candidate
class TestCandidate(unittest.TestCase):
def test_all_fields_filled_correctly(self):
response_payload = "[{\"input_id\":\"12345678\",\"organization\":\"1\",\"address1\":\"2\",\"address2\":\"3\","\
"\"address3\":\"4\",\"address4\":\"5\",\"address5\":\"6\",\"address6\":\"7\",\"address7\":\"8\","\
"\"address8\":\"9\",\"address9\":\"10\",\"address10\":\"11\",\"address11\":\"12\",\"address12\":\"13\","\
"\"components\":{\"country_iso_3\":\"14\",\"super_administrative_area\":\"15\","\
"\"administrative_area\":\"16\",\"sub_administrative_area\":\"17\",\"dependent_locality\":\"18\","\
"\"dependent_locality_name\":\"19\",\"double_dependent_locality\":\"20\",\"locality\":\"21\","\
"\"postal_code\":\"22\",\"postal_code_short\":\"23\",\"postal_code_extra\":\"24\","\
"\"premise\":\"25\",\"premise_extra\":\"26\",\"premise_number\":\"27\"," \
"\"premise_prefix_number\":\"27.5\",\"premise_type\":\"28\","\
"\"thoroughfare\":\"29\",\"thoroughfare_predirection\":\"30\",\"thoroughfare_postdirection\":\"31\","\
"\"thoroughfare_name\":\"32\",\"thoroughfare_trailing_type\":\"33\",\"thoroughfare_type\":\"34\","\
"\"dependent_thoroughfare\":\"35\",\"dependent_thoroughfare_predirection\":\"36\","\
"\"dependent_thoroughfare_postdirection\":\"37\",\"dependent_thoroughfare_name\":\"38\","\
"\"dependent_thoroughfare_trailing_type\":\"39\",\"dependent_thoroughfare_type\":\"40\","\
"\"building\":\"41\",\"building_leading_type\":\"42\",\"building_name\":\"43\","\
"\"building_trailing_type\":\"44\",\"sub_building_type\":\"45\",\"sub_building_number\":\"46\","\
"\"sub_building_name\":\"47\",\"sub_building\":\"48\",\"post_box\":\"49\",\"post_box_type\":\"50\","\
"\"post_box_number\":\"51\"},\"metadata\":{\"latitude\":52.0,\"longitude\":53.0,"\
"\"geocode_precision\":\"54\",\"max_geocode_precision\":\"55\",\"address_format\":\"56\"},"\
"\"analysis\":{\"verification_status\":\"57\",\"address_precision\":\"58\","\
"\"max_address_precision\":\"59\",\"changes\":{\"organization\":\"60\","\
"\"address1\":\"61\",\"address2\":\"62\",\"address3\":\"63\",\"address4\":\"64\",\"address5\":\"65\","\
"\"address6\":\"66\",\"address7\":\"67\",\"address8\":\"68\",\"address9\":\"69\",\"address10\":\"70\","\
"\"address11\":\"71\",\"address12\":\"72\",\"components\":{\"super_administrative_area\":\"73\","\
"\"administrative_area\":\"74\",\"sub_administrative_area\":\"75\",\"building\":\"76\","\
"\"dependent_locality\":\"77\",\"dependent_locality_name\":\"78\",\"double_dependent_locality\":\"79\","\
"\"country_iso_3\":\"80\",\"locality\":\"81\",\"postal_code\":\"82\",\"postal_code_short\":\"83\","\
"\"postal_code_extra\":\"84\",\"premise\":\"85\",\"premise_extra\":\"86\",\"premise_number\":\"87\","\
"\"premise_type\":\"88\",\"premise_prefix_number\":\"89\",\"thoroughfare\":\"90\","\
"\"thoroughfare_predirection\":\"91\",\"thoroughfare_postdirection\":\"92\","\
"\"thoroughfare_name\":\"93\",\"thoroughfare_trailing_type\":\"94\",\"thoroughfare_type\":\"95\","\
"\"dependent_thoroughfare\":\"96\",\"dependent_thoroughfare_predirection\":\"97\","\
"\"dependent_thoroughfare_postdirection\":\"98\",\"dependent_thoroughfare_name\":\"99\","\
"\"dependent_thoroughfare_trailing_type\":\"100\",\"dependent_thoroughfare_type\":\"101\","\
"\"building_leading_type\":\"102\",\"building_name\":\"103\",\"building_trailing_type\":\"104\","\
"\"sub_building_type\":\"105\",\"sub_building_number\":\"106\",\"sub_building_name\":\"107\","\
"\"sub_building\":\"108\",\"post_box\":\"109\",\"post_box_type\":\"110\",\"post_box_number\":\"111\"}}}}]"
serializer = NativeSerializer()
candidate = Candidate(serializer.deserialize(response_payload)[0])
self.assertEqual("12345678", candidate.input_id)
self.assertEqual("1", candidate.organization)
self.assertEqual("2", candidate.address1)
self.assertEqual("3", candidate.address2)
self.assertEqual("4", candidate.address3)
self.assertEqual("5", candidate.address4)
self.assertEqual("6", candidate.address5)
self.assertEqual("7", candidate.address6)
self.assertEqual("8", candidate.address7)
self.assertEqual("9", candidate.address8)
self.assertEqual("10", candidate.address9)
self.assertEqual("11", candidate.address10)
self.assertEqual("12", candidate.address11)
self.assertEqual("13", candidate.address12)
components = candidate.components
self.assertIsNotNone(components)
self.assertEqual("14", components.country_iso_3)
self.assertEqual("15", components.super_administrative_area)
self.assertEqual("16", components.administrative_area)
self.assertEqual("17", components.sub_administrative_area)
self.assertEqual("18", components.dependent_locality)
self.assertEqual("19", components.dependent_locality_name)
self.assertEqual("20", components.double_dependent_locality)
self.assertEqual("21", components.locality)
self.assertEqual("22", components.postal_code)
self.assertEqual("23", components.postal_code_short)
self.assertEqual("24", components.postal_code_extra)
self.assertEqual("25", components.premise)
self.assertEqual("26", components.premise_extra)
self.assertEqual("27", components.premise_number)
self.assertEqual("27.5", components.premise_prefix_number)
self.assertEqual("28", components.premise_type)
self.assertEqual("29", components.thoroughfare)
self.assertEqual("30", components.thoroughfare_predirection)
self.assertEqual("31", components.thoroughfare_postdirection)
self.assertEqual("32", components.thoroughfare_name)
self.assertEqual("33", components.thoroughfare_trailing_type)
self.assertEqual("34", components.thoroughfare_type)
self.assertEqual("35", components.dependent_thoroughfare)
self.assertEqual("36", components.dependent_thoroughfare_predirection)
self.assertEqual("37", components.dependent_thoroughfare_postdirection)
self.assertEqual("38", components.dependent_thoroughfare_name)
self.assertEqual("39", components.dependent_thoroughfare_trailing_type)
self.assertEqual("40", components.dependent_thoroughfare_type)
self.assertEqual("41", components.building)
self.assertEqual("42", components.building_leading_type)
self.assertEqual("43", components.building_name)
self.assertEqual("44", components.building_trailing_type)
self.assertEqual("45", components.sub_building_type)
self.assertEqual("46", components.sub_building_number)
self.assertEqual("47", components.sub_building_name)
self.assertEqual("48", components.sub_building)
self.assertEqual("49", components.post_box)
self.assertEqual("50", components.post_box_type)
self.assertEqual("51", components.post_box_number)
metadata = candidate.metadata
self.assertIsNotNone(metadata)
self.assertEqual(52, metadata.latitude, 0.001)
self.assertEqual(53, metadata.longitude, 0.001)
self.assertEqual("54", metadata.geocode_precision)
self.assertEqual("55", metadata.max_geocode_precision)
self.assertEqual("56", metadata.address_format)
analysis = candidate.analysis
self.assertIsNotNone(analysis)
self.assertEqual("57", analysis.verification_status)
self.assertEqual("58", analysis.address_precision)
self.assertEqual("59", analysis.max_address_precision)
changes = analysis.changes
self.assertIsNotNone(changes)
self.assertEqual("60", changes.organization)
self.assertEqual("61", changes.address1)
self.assertEqual("62", changes.address2)
self.assertEqual("63", changes.address3)
self.assertEqual("64", changes.address4)
self.assertEqual("65", changes.address5)
self.assertEqual("66", changes.address6)
self.assertEqual("67", changes.address7)
self.assertEqual("68", changes.address8)
self.assertEqual("69", changes.address9)
self.assertEqual("70", changes.address10)
self.assertEqual("71", changes.address11)
self.assertEqual("72", changes.address12)
components = changes.components
self.assertIsNotNone(components)
self.assertEqual("73", components.super_administrative_area)
self.assertEqual("74", components.administrative_area)
self.assertEqual("75", components.sub_administrative_area)
self.assertEqual("76", components.building)
self.assertEqual("77", components.dependent_locality)
self.assertEqual("78", components.dependent_locality_name)
self.assertEqual("79", components.double_dependent_locality)
self.assertEqual("80", components.country_iso_3)
self.assertEqual("81", components.locality)
self.assertEqual("82", components.postal_code)
self.assertEqual("83", components.postal_code_short)
self.assertEqual("84", components.postal_code_extra)
self.assertEqual("85", components.premise)
self.assertEqual("86", components.premise_extra)
self.assertEqual("87", components.premise_number)
self.assertEqual("88", components.premise_type)
self.assertEqual("89", components.premise_prefix_number)
self.assertEqual("90", components.thoroughfare)
self.assertEqual("91", components.thoroughfare_predirection)
self.assertEqual("92", components.thoroughfare_postdirection)
self.assertEqual("93", components.thoroughfare_name)
self.assertEqual("94", components.thoroughfare_trailing_type)
self.assertEqual("95", components.thoroughfare_type)
self.assertEqual("96", components.dependent_thoroughfare)
self.assertEqual("97", components.dependent_thoroughfare_predirection)
self.assertEqual("98", components.dependent_thoroughfare_postdirection)
self.assertEqual("99", components.dependent_thoroughfare_name)
self.assertEqual("100", components.dependent_thoroughfare_trailing_type)
self.assertEqual("101", components.dependent_thoroughfare_type)
self.assertEqual("102", components.building_leading_type)
self.assertEqual("103", components.building_name)
self.assertEqual("104", components.building_trailing_type)
self.assertEqual("105", components.sub_building_type)
self.assertEqual("106", components.sub_building_number)
self.assertEqual("107", components.sub_building_name)
self.assertEqual("108", components.sub_building)
self.assertEqual("109", components.post_box)
self.assertEqual("110", components.post_box_type)
self.assertEqual("111", components.post_box_number)
| none | 1 | 2.52678 | 3 | |
auxiliary/gen_var.py | manuhuth/Replication-of-Bailey-2010- | 1 | 6614204 | import pandas as pd
import numpy as np
import warnings as wn
def gen_var(agegroup_type_Bailey = True):
"""Function to create the relevant categorials from scratch.
Args:
-------
Returns:
-------
A data frame containing the variables needed for the analysis.
"""
wn.filterwarnings("ignore")
#1. 1955 GAF
#Read dta file 1955 GAF
df_55 = pd.read_stata('data/gaf55_1.dta', convert_categoricals = False)
#generate dummy: 1 if fertile and 0 if not
df_55['_fecund'] = 0
df_55.loc[ (df_55['fec_code'] == 4) | (df_55['fec_code'] == 5), '_fecund' ] = 1
#generate dummy if ever used method of contraception
df_55['_everuse'] = 0
df_55.loc[ (df_55['meth_everuse'] == 1), '_everuse' ] = 1
#generate dummy if ever used method of contraception or as douche
df_55['_everuse_d'] = 0
df_55.loc[(df_55['meth_everuse'] == 1) | (df_55['meth_everuse'] == 2), '_everuse_d'] = 1
#generate dummy if ever used condom or diaphragma
df_55['_barrier'] = 0
df_55.loc[ (df_55['con_use'] == 1) | (df_55['dia_use'] == 1), '_barrier'] = 1
#generate dummy whether either condom, diaphragma, helly, vagsupp, foamtab,
#tampon or any other method was ever used
df_55['_supplies'] = 0
df_55.loc[ (df_55['con_use']==1)|(df_55['dia_use']==1)|(df_55['jelly_use']==1)|(df_55['vagsupp_use']==1) \
|(df_55['foamtab_use']==1)|(df_55['tampon_use']==1)|(df_55['othmeth_use']==1), '_supplies'] = 1
#generate dummy, if ever used oral contraception (not possible in 1955)
df_55['_oral'] = 0
#generate dummy wgt
df_55['wgt'] = 1
#generate year
df_55['year'] = 1955
#2. 1965 NFS
#read .dta file 1965 NFS
df_65 = pd.read_stata('data/nfs65_1.dta', convert_categoricals = False)
#generate dummy for fertility, one means fertile
df_65['_fecund'] = 0
df_65.loc[ (df_65['fecund'] == 8), '_fecund'] = 1
#generate dummy if ever used method of contraception or as douche
df_65['_everuse_d'] = 0
df_65.loc[(df_65['preg1_meth1_4'] == 1) | (df_65['preg1_meth1_5'] == 1)\
| (df_65['preg1_meth1_6'] == 1) | (df_65['preg1_meth1_7']==1) \
| (df_65['preg1_meth1_8']==1) |(df_65['preg1_meth1_12']==1) | (df_65['preg1_meth1_9']==1) \
| (df_65['preg1_meth1_10']==1) | (df_65['preg1_meth1_11']==1) |(df_65['preg1_meth1_13']==1) \
| (df_65['preg1_meth1_14']==1)|(df_65['preg1_meth1_15']==1) | (df_65['preg1_meth1_16']==1), '_everuse_d'] = 1
#generate dummy whether a contraception method was used before the first pregnancy
df_65['_everuse2_mjb'] = 0
df_65.loc[df_65['preg1_meth1_3'] == 0, '_everuse2_mjb'] = 1 #1 if not used before first pregnancy
df_65.loc[df_65['preg1_meth1_2'] == 1, '_everuse2_mjb'] = np.NaN # no answer to question of contraception used before first pregnancy
#generate dummy if ever used method of contraception (exclusive douche)
df_65['_everuse3_mjb'] = df_65['_everuse_d']
df_65.loc[ (df_65['preg1_meth1_13']==1) & (df_65['preg1_meth1_1']==0) & (df_65['preg1_meth1_2']==0) \
& (df_65['preg1_meth1_3']==0) & (df_65['preg1_meth1_4']==0) & (df_65['preg1_meth1_5']==0) \
& (df_65['preg1_meth1_6']==0) & (df_65['preg1_meth1_7']==0) & (df_65['preg1_meth1_8']==0) \
& (df_65['preg1_meth1_9']==0) & (df_65['preg1_meth1_10']==0) & (df_65['preg1_meth1_11']==0) \
& (df_65['preg1_meth1_12']==0) & (df_65['preg1_meth1_14']==0) & (df_65['preg1_meth1_15']==0) \
& (df_65['preg1_meth1_16'] == 0), '_everuse3_mjb' ] = 0
#genrate dummy if a barrier method (condom, diaphragma) was ever used
df_65['_barrier'] = 0
df_65.loc[ (df_65['preg1_meth1_5'] == 1) | (df_65['preg1_meth1_7'] == 1), '_barrier' ] = 1
#generate dummy if any supply methods were ever used (condoms, diaphragma, pill, jelly, foam, douche, IUD, Sponge )
df_65['_supplies'] = 0
df_65.loc[ (df_65['preg1_meth1_5'] == 1) | (df_65['preg1_meth1_7'] == 1)|(df_65['preg1_meth1_8'] == 1) \
| (df_65['preg1_meth1_9'] == 1) | (df_65['preg1_meth1_10'] == 1) | (df_65['preg1_meth1_11']==1) \
| (df_65['preg1_meth1_13']==1) |(df_65['preg1_meth1_14']==1) | (df_65['preg1_meth1_16']==1), '_supplies' ] = 1
#generate dummy if oral contraception was used (pill)
df_65['_oral'] = 0
df_65.loc[ df_65['preg1_meth1_8'] == 1, '_oral' ] = 1
#repeat this for any different A-types of pregi_meth1_j
for i in range(0,21):
df_65.loc[ (df_65['preg{}_meth1_4'.format(i)] == 1) | (df_65['preg{}_meth1_5'.format(i)] == 1) \
| (df_65['preg{}_meth1_6'.format(i)] == 1) | (df_65['preg{}_meth1_7'.format(i)]==1) \
| (df_65['preg{}_meth1_8'.format(i)]==1) |(df_65['preg{}_meth1_12'.format(i)]==1) | (df_65['preg{}_meth1_9'.format(i)]==1) \
| (df_65['preg{}_meth1_10'.format(i)]==1) | (df_65['preg{}_meth1_11'.format(i)]==1) |(df_65['preg{}_meth1_13'.format(i)]==1) \
| (df_65['preg{}_meth1_14'.format(i)]==1)|(df_65['preg{}_meth1_15'.format(i)]==1) | (df_65['preg{}_meth1_16'.format(i)]==1), '_everuse_d'] = 1
df_65.loc[df_65['preg{}_meth1_3'.format(i)] == 0, '_everuse2_mjb'] = 1
df_65['_everuse3_mjb'] = df_65 ['_everuse_d']
df_65.loc[ (df_65['preg{}_meth1_13'.format(i)]==1) & (df_65['preg{}_meth1_1'.format(i)]==0) & (df_65['preg{}_meth1_2'.format(i)]==0) \
& (df_65['preg{}_meth1_3'.format(i)]==0) & (df_65['preg{}_meth1_4'.format(i)]==0) & (df_65['preg{}_meth1_5'.format(i)]==0) \
& (df_65['preg{}_meth1_6'.format(i)]==0) & (df_65['preg{}_meth1_7'.format(i)]==0) & (df_65['preg{}_meth1_8'.format(i)]==0) \
& (df_65['preg{}_meth1_9'.format(i)]==0) & (df_65['preg{}_meth1_10'.format(i)]==0) & (df_65['preg{}_meth1_11'.format(i)]==0) \
& (df_65['preg{}_meth1_12'.format(i)]==0) & (df_65['preg{}_meth1_14'.format(i)]==0) & (df_65['preg{}_meth1_15'.format(i)]==0) \
& (df_65['preg{}_meth1_16'.format(i)] == 0), '_everuse3_mjb' ] = 0
df_65.loc[ (df_65['preg{}_meth1_5'.format(i)] == 1) | (df_65['preg{}_meth1_7'.format(i)] == 1), '_barrier' ] = 1
df_65.loc[ (df_65['preg{}_meth1_5'.format(i)] == 1) | (df_65['preg{}_meth1_7'.format(i)] == 1)|(df_65['preg{}_meth1_8'.format(i)] == 1) \
| (df_65['preg{}_meth1_9'.format(i)] == 1) | (df_65['preg{}_meth1_10'.format(i)] == 1) | (df_65['preg{}_meth1_11'.format(i)]==1) \
| (df_65['preg{}_meth1_13'.format(i)]==1) |(df_65['preg{}_meth1_14'.format(i)]==1) | (df_65['preg{}_meth1_16'.format(i)]==1), '_supplies' ] = 1
df_65.loc[ df_65['preg{}_meth1_8'.format(i)] == 1, '_oral' ] = 1
#print(i)
df_65 = df_65[['_barrier', '_supplies', 'preg0_coitfr', '_oral', '_fecund', '_everuse_d','_everuse2_mjb','_everuse3_mjb', \
'H_emp_inc65', 'fam_idealch', 'att_idealch', 'res_popdens', 'res_reg', 'statefip', 'statename', 'int_num', 'per_race', \
'_age', 'ed_higrade', 'rel_pref', 'dob', 'fec_sterilop1', 'wgt', 'ch_totlb']]
df_65['year'] = 1965
#3. 1970 NFS
#read .dta file 1970 NFS
df_70 = pd.read_stata('data/nfs70_1.dta', convert_categoricals = False)
#generate dummy if ever used method of contraception or as douche
df_70['_everuse_d'] = 0
df_70.loc[ (df_70['preg1_meth_any'] == 1) | (df_70['dia_everuse'] == 1) | (df_70['iud_everuse'] == 1) \
| (df_70['_bcp_everuse'] == 1), '_everuse_d'] = 1
#genrate dummy if a barrier method (condom, diaphragma) was ever used
df_70['_barrier'] = 0
df_70.loc[ (df_70['preg1_meth_1'] == 3) | (df_70['preg1_meth_1'] == 5) | (df_70['dia_everuse'] == 1), '_barrier' ] = 1
#generate dummy if any supply methods were ever used (condoms, diaphragma, pill, jelly, foam, douche, IUD, Sponge )
df_70['_supplies'] = 0
df_70.loc[ (df_70['preg1_meth_1'] == 3) | (df_70['preg1_meth_1'] == 5) | (df_70['preg1_meth_1'] == 6) \
| (df_70['preg1_meth_1'] == 7) | (df_70['preg1_meth_1'] == 8) | (df_70['preg1_meth_1'] == 9) \
| (df_70['preg1_meth_1'] == 10) | (df_70['preg1_meth_1'] == 11) | (df_70['preg1_meth_1'] == 13) \
| (df_70['dia_everuse'] == 1) | (df_70['iud_everuse'] == 1) | (df_70['_bcp_everuse'] == 1), '_supplies'] = 1
#generate dummy if oral contraception was used (pill)
df_70['_oral'] = 0
df_70.loc[ (df_70['preg1_meth_1'] == 6) | (df_70['_bcp_everuse'] == 1), '_oral' ] = 1
# rename variable to make it suitable for loop
df_70 = df_70.rename(columns={'preg0_meth': 'preg0_meth_1'})
#df_70['preg0_meth_1'] = df_70['preg0_meth']
for i in range(0,20):
if i == 0 :
j = 1
df_70.loc[ df_70['preg0_meth1'] == 1, '_everuse_d' ] = 1
df_70.loc[ (df_70['preg0_meth_{}'.format(j)] == 3) | (df_70['preg0_meth_{}'.format(j)] == 5), '_barrier'] = 1
df_70.loc[ (df_70['preg0_meth_{}'.format(j)] == 3) | (df_70['preg0_meth_{}'.format(j)] == 5) | (df_70['preg0_meth_{}'.format(j)] == 6) \
| (df_70['preg0_meth_{}'.format(j)] == 7) | (df_70['preg0_meth_{}'.format(j)] == 8) | (df_70['preg0_meth_{}'.format(j)] == 9) \
| (df_70['preg0_meth_{}'.format(j)] == 10) | (df_70['preg0_meth_{}'.format(j)] == 11) | (df_70['preg0_meth_{}'.format(j)] == 13), '_supplies' ] = 1
df_70.loc[ (df_70['preg0_meth_{}'.format(j)] == 6), '_oral' ] = 1
else:
df_70.loc[ (df_70['preg{}_meth_any'.format(i)] == 1), '_everuse_d' ] = 1
for j in range(1,7):
df_70.loc[ (df_70['preg{}_meth_{}'.format(i,j)] == 3) | (df_70['preg{}_meth_{}'.format(i,j)] == 5), '_barrier'] = 1
df_70.loc[ (df_70['preg{}_meth_{}'.format(i,j)] == 3) | (df_70['preg{}_meth_{}'.format(i,j)] == 5) | (df_70['preg{}_meth_{}'.format(i,j)] == 6) \
| (df_70['preg{}_meth_{}'.format(i,j)] == 7) | (df_70['preg{}_meth_{}'.format(i,j)] == 8) | (df_70['preg{}_meth_{}'.format(i,j)] == 9) \
| (df_70['preg{}_meth_{}'.format(i,j)] == 10) | (df_70['preg{}_meth_{}'.format(i,j)] == 11) | (df_70['preg{}_meth_{}'.format(i,j)] == 13), '_supplies' ] = 1
df_70.loc[df_70['preg{}_meth_{}'.format(i,j)] == 6, '_oral'] = 1
#print(i)
df_70 = df_70[['_barrier', '_supplies', '_oral', 'preg0_coitfr', '_everuse_d', 'H_emp_inc70', 'fam_idealch', 'att_idealch',
'statefip', 'statename', 'int_LAN', 'int_LAN_size', 'int_LAN_region', 'int_num', 'per_race', 'wgt', '_age',
'mar_stat', 'ed_total', 'rel_pref', 'dob', 'fec_sterilop1', 'ch_totlb' ]]
df_70['year'] = 1970
#append data frames
df = df_55
df = df.append(df_65, ignore_index = True)
df = df.append(df_70, ignore_index = True)
#4. Harmonize definitions of sample variables
#Race
df['_White'] = 0
df.loc[df['year'] == 1955, '_White'] = 1
df.loc[(df['year'] == 1965) & (df['per_race'] == 1), '_White'] = 1
df.loc[(df['year'] == 1970) & (df['per_race'] == 2), '_White'] = 1
#Marital Status
df['_Married'] = 0
df.loc[(df['year'] == 1955) | (df['year'] == 1965), '_Married'] = 1
df.loc[(df['year'] == 1970) & (df['mar_stat'] == 1), '_Married'] = 1
#Education
df['_ed_cat'] = np.NaN
lis = [0,9,12,13,16,18]
df.loc[(df['year'] == 1965) & (df['ed_higrade'] == 0), '_ed_cat'] = 0
for i in range(1,len(lis)):
#print(i)
df.loc[ (df['year'] == 1965) & ( lis[i-1] <= df['ed_higrade'] ) & (df['ed_higrade'] < lis[i]), '_ed_cat' ] = lis[i-1]
df.loc[ (df['ed_total'] == i), 'ed_total'] = lis[i-1]
df.loc[ (df['year'] == 1970), '_ed_cat'] = df['ed_total']
df.loc[ (df['ed'] <= 4) & (df['ed'] >= 1), 'ed'] = 0
df.loc[ (df['ed'] == 8) | (df['ed'] == 9),'ed'] = 16
df.loc[ (df['ed'] == 5), 'ed'] = 9
df.loc[ (df['ed'] == 6), 'ed'] = 12
df.loc[ (df['ed'] == 7), 'ed'] = 13
df.loc[ (df['year'] == 1955), '_ed_cat'] = df['ed']
#Catholic
df['_Catholic'] = 0
df.loc[ ((df['year'] == 1955) & (df['rel_pref'] == 10)) | ((df['year'] == 1965) & (df['rel_pref'] == 21)) | \
((df['year'] == 1970) & (df['rel_pref'] == 21)), '_Catholic'] = 1
#Birth Cohort
df['_yob'] = np.NaN
lis = range(0,870,12)
for i in lis:
df.loc[ ((df['year'] == 1970) | (df['year'] == 1965)) & (df['dob'] >= i) & (df['dob'] < i + 12), '_yob'] = i /12 + 1900
df.loc[ ((df['year'] == 1970) | (df['year'] == 1965)) & (df['dob'] > 900), '_yob'] = df['dob'] + 1000
df.loc[ (df['year'] == 1955), '_yob' ] = df['dob_y'] + 1900
df['_yobcat'] = np.NaN
lis = range(1910,1960, 5)
for i in lis:
df.loc[ (df['_yob'] >= i) & (df['_yob'] < i + 5), '_yobcat'] = i
#age
df['_age'] = np.NaN
df['_age'] = df['year'] - df['_yob']
df['_agecat'] = np.NaN
lis = range(15,60,5)
for i in lis:
df.loc[ (df['_age'] >= i) & (df['_age'] < i + 5), '_agecat'] = i
#Surgically sterilized
df['_sterilop'] = 0
df.loc[ (df['year'] == 1955) & (df['fec_ster1'] != 0) & (df['fec_ster1'] != 6), '_sterilop' ] = 1
df.loc[ (df['year'] == 1965) & (df['fec_sterilop1'] == 1), '_sterilop' ] = 1
df.loc[ (df['year'] == 1970) & (df['fec_sterilop1'] == 1), '_sterilop' ] = 1
#ideal number of children for american family
df['_att_idealch'] = np.NaN #create variable to standardize variables.
df.loc[(df['att_idealch'] < 99) & (df['year'] == 1955), '_att_idealch'] = df['att_idealch']/10
df.loc[ (df['att_idealch'] > 90) & (df['att_idealch'] <= 130) & (df['year'] == 1965), 'att_idealch' ] = 90 #fix coding bug
df.loc[ ((df['att_idealch'] <= 90) & (df['year'] == 1965)) \
| ((df['att_idealch'] < 96) & (df['year'] == 1970)), '_att_idealch'] = df['att_idealch']/10
df['_idealcat'] = np.NaN
lis = [0,2,3,4,5,10,1000] #1000 can be an arbitrary high value. Just to make loop suitable
for i in range(0, (len(lis)-1)):
#print(i)
df.loc[ (lis[i] <= df['_att_idealch']) & (df['_att_idealch'] < lis[i+1]), '_idealcat' ] = lis[i]
#Husbands income
df['h_empinc65'] = np.NaN
df.loc[ (df['year'] == 1965), 'h_empinc65' ] = df['H_emp_inc65']
df.loc[ (df['h_empinc65'] != 0) & (df['h_empinc65'] < 10), 'h_empinc65' ] = df['h_empinc65']*1000+500
df.loc[(df['h_empinc65'] == 10), 'h_empinc65' ] = 11000
df.loc[(df['h_empinc65'] == 20), 'h_empinc65' ] = 13500
df.loc[ (df['h_empinc65'] == 30), 'h_empinc65' ] = 21000
df.loc[(df['h_empinc65'] == 88) | (df['h_empinc65'] == 99), 'h_empinc65' ] = np.NaN
df['h_empinc70'] = np.NaN
df.loc[(df['year'] == 1970), 'h_empinc70' ] = df['H_emp_inc70']
df.loc[ (df['h_empinc70'] != 0) & (df['h_empinc70'] < 10), 'h_empinc70' ] = df['h_empinc70']*1000+500
df.loc[ (df['h_empinc70'] == 10), 'h_empinc70' ] = 12000
df.loc[ (df['h_empinc70'] == 11), 'h_empinc70' ] = 13500
df.loc[ (df['h_empinc70'] == 12), 'h_empinc70' ] = 21000
df.loc[ (df['h_empinc70'] == 88) | (df['h_empinc70'] == 99), 'h_empinc70' ] = np.NaN
df['h_empinc55'] = np.NaN
df.loc[ (df['year'] == 1955), 'h_empinc55' ] = df['h_emp_inc']
df.loc[ (df['h_empinc55'] != 0) & (df['h_empinc55'] < 9), 'h_empinc55' ] = (df['h_empinc55']-1)*1000+500
df.loc[ (df['h_empinc55'] == 9), 'h_empinc55' ] = 9000
df.loc[ (df['h_empinc55'] == 10), 'h_empinc55' ] = 14000
df.loc[ (df['h_empinc55'] == 88) | (df['h_empinc55'] == 99), 'h_empinc55' ] = np.NaN
df['_h_empinc'] = np.NaN
df.loc[(df['year'] == 1955), '_h_empinc'] = (36.7/26.9)*df['h_empinc55'] #in 1969 US Dollar
df.loc[(df['year'] == 1965), '_h_empinc'] = (36.7/31)*df['h_empinc65'] #in 1969 US Dollar
df.loc[(df['year'] == 1970), '_h_empinc'] = df['h_empinc70'] #in 1969 US Dollar
df['_hinccat'] = np.NaN
df.loc[(0 <=df['_h_empinc']) & (df['_h_empinc'] <= 4500), '_hinccat'] = 0
df.loc[(4500 < df['_h_empinc']) & (df['_h_empinc'] <= 6500), '_hinccat'] = 1
df.loc[(6500 < df['_h_empinc']) & (df['_h_empinc'] <= 8400), '_hinccat'] = 2
df.loc[ (8400 < df['_h_empinc']) & (df['_h_empinc'] <= 12000), '_hinccat'] = 3
df.loc[(12000 <= df['_h_empinc']) & (df['_h_empinc'] <= 25000), '_hinccat'] = 4
#Attitudes on family planning
df['_approvefp55'] = np.NaN
df.loc[(df['year'] == 1955), '_approvefp55'] = 0
df.loc[(df['year'] == 1955) & (df['att_famplan'] <= 2), '_approvefp55' ] = 1
#Region
df.loc[( (df['int_LAN_region'] == 1) | (df['int_LAN_region'] == 2) ) & (df['year'] == 1970), 'res_reg' ] = 1
df.loc[( (df['int_LAN_region'] == 3) | (df['int_LAN_region'] == 4) ) & (df['year'] == 1970), 'res_reg' ] = 2
df.loc[( (df['int_LAN_region'] == 5) | (df['int_LAN_region'] == 6) | (df['int_LAN_region'] == 7) ) & (df['year'] == 1970), 'res_reg' ] = 3
df.loc[( (df['int_LAN_region'] == 8) | (df['int_LAN_region'] == 9) ) & (df['year'] == 1970), 'res_reg' ] = 4
df.loc[(df['int_LAN'] >= 54002) & (df['int_LAN'] <= 54013) & (df['year'] == 1970), 'res_reg' ] = 1
df.loc[ (df['statefip'] == 11) & (df['year'] == 1970), 'res_reg' ] = 3
df.loc[ (df['year'] == 1955), 'res_reg' ] = df['_region']
df = df.drop(columns=['_region'])
df = df.rename(columns={'res_reg': '_region'}) #see codebokkNFS65
#Live births
df.loc[ df['ch_totlb'] > 12, 'ch_totlb' ] = 12
#coital frequency
df['_coit_freq'] = np.NaN
df.loc[df['preg0_coitfr'] < 98, '_coit_freq'] = df['preg0_coitfr']
#5. Merge to Statenames sice some states have the name with a space ' ' in th beginning
sn = pd.read_stata('data/temp.dta', convert_categoricals = False)
lis = sn['statefip']
for i in lis:
L = len(df['statename'][df['statefip'] == i])
df['statename'][ df['statefip'] == i] = np.repeat(sn['statename'][ sn['statefip'] == i], L)
#df.loc[ df['statefip'] == i, 'statename'] = np.repeat(sn['statename'][ sn['statefip'] == i], L)
#6. Merge to Griswold Laws
gl = pd.read_stata('data/griswoldlaws5.dta', convert_categoricals = False)
df = df[df.statefip != 11] #delete columbia
df['sales'] = np.NaN
df['any'] = np.NaN
df['_Phys'] = np.NaN
df['cstck'] = np.NaN
df['_Phy_LB'] = np.NaN
lis = gl['statefip']
indexcol = ['sales', 'any', '_Phys', 'cstck', '_Phy_LB']
for column in indexcol:
#print(column)
for i in lis:
L = len(df[column][df['statefip'] == i])
df[column][df['statefip'] == i] = np.repeat(gl[column][ gl['statefip'] == i], L)
df['__yobcat'] = np.NaN
if agegroup_type_Bailey is True:
lis = range(1910,1950,20)
else:
lis = range(1910,1960,20)
for i in lis:
#print(i)
df.loc[ (df['_yobcat'] >= i) & (df['_yobcat'] < i + 20), '__yobcat'] = i #maybe error in stata code (values above 1950 are set as missing)
return df
| import pandas as pd
import numpy as np
import warnings as wn
def gen_var(agegroup_type_Bailey = True):
"""Function to create the relevant categorials from scratch.
Args:
-------
Returns:
-------
A data frame containing the variables needed for the analysis.
"""
wn.filterwarnings("ignore")
#1. 1955 GAF
#Read dta file 1955 GAF
df_55 = pd.read_stata('data/gaf55_1.dta', convert_categoricals = False)
#generate dummy: 1 if fertile and 0 if not
df_55['_fecund'] = 0
df_55.loc[ (df_55['fec_code'] == 4) | (df_55['fec_code'] == 5), '_fecund' ] = 1
#generate dummy if ever used method of contraception
df_55['_everuse'] = 0
df_55.loc[ (df_55['meth_everuse'] == 1), '_everuse' ] = 1
#generate dummy if ever used method of contraception or as douche
df_55['_everuse_d'] = 0
df_55.loc[(df_55['meth_everuse'] == 1) | (df_55['meth_everuse'] == 2), '_everuse_d'] = 1
#generate dummy if ever used condom or diaphragma
df_55['_barrier'] = 0
df_55.loc[ (df_55['con_use'] == 1) | (df_55['dia_use'] == 1), '_barrier'] = 1
#generate dummy whether either condom, diaphragma, helly, vagsupp, foamtab,
#tampon or any other method was ever used
df_55['_supplies'] = 0
df_55.loc[ (df_55['con_use']==1)|(df_55['dia_use']==1)|(df_55['jelly_use']==1)|(df_55['vagsupp_use']==1) \
|(df_55['foamtab_use']==1)|(df_55['tampon_use']==1)|(df_55['othmeth_use']==1), '_supplies'] = 1
#generate dummy, if ever used oral contraception (not possible in 1955)
df_55['_oral'] = 0
#generate dummy wgt
df_55['wgt'] = 1
#generate year
df_55['year'] = 1955
#2. 1965 NFS
#read .dta file 1965 NFS
df_65 = pd.read_stata('data/nfs65_1.dta', convert_categoricals = False)
#generate dummy for fertility, one means fertile
df_65['_fecund'] = 0
df_65.loc[ (df_65['fecund'] == 8), '_fecund'] = 1
#generate dummy if ever used method of contraception or as douche
df_65['_everuse_d'] = 0
df_65.loc[(df_65['preg1_meth1_4'] == 1) | (df_65['preg1_meth1_5'] == 1)\
| (df_65['preg1_meth1_6'] == 1) | (df_65['preg1_meth1_7']==1) \
| (df_65['preg1_meth1_8']==1) |(df_65['preg1_meth1_12']==1) | (df_65['preg1_meth1_9']==1) \
| (df_65['preg1_meth1_10']==1) | (df_65['preg1_meth1_11']==1) |(df_65['preg1_meth1_13']==1) \
| (df_65['preg1_meth1_14']==1)|(df_65['preg1_meth1_15']==1) | (df_65['preg1_meth1_16']==1), '_everuse_d'] = 1
#generate dummy whether a contraception method was used before the first pregnancy
df_65['_everuse2_mjb'] = 0
df_65.loc[df_65['preg1_meth1_3'] == 0, '_everuse2_mjb'] = 1 #1 if not used before first pregnancy
df_65.loc[df_65['preg1_meth1_2'] == 1, '_everuse2_mjb'] = np.NaN # no answer to question of contraception used before first pregnancy
#generate dummy if ever used method of contraception (exclusive douche)
df_65['_everuse3_mjb'] = df_65['_everuse_d']
df_65.loc[ (df_65['preg1_meth1_13']==1) & (df_65['preg1_meth1_1']==0) & (df_65['preg1_meth1_2']==0) \
& (df_65['preg1_meth1_3']==0) & (df_65['preg1_meth1_4']==0) & (df_65['preg1_meth1_5']==0) \
& (df_65['preg1_meth1_6']==0) & (df_65['preg1_meth1_7']==0) & (df_65['preg1_meth1_8']==0) \
& (df_65['preg1_meth1_9']==0) & (df_65['preg1_meth1_10']==0) & (df_65['preg1_meth1_11']==0) \
& (df_65['preg1_meth1_12']==0) & (df_65['preg1_meth1_14']==0) & (df_65['preg1_meth1_15']==0) \
& (df_65['preg1_meth1_16'] == 0), '_everuse3_mjb' ] = 0
#genrate dummy if a barrier method (condom, diaphragma) was ever used
df_65['_barrier'] = 0
df_65.loc[ (df_65['preg1_meth1_5'] == 1) | (df_65['preg1_meth1_7'] == 1), '_barrier' ] = 1
#generate dummy if any supply methods were ever used (condoms, diaphragma, pill, jelly, foam, douche, IUD, Sponge )
df_65['_supplies'] = 0
df_65.loc[ (df_65['preg1_meth1_5'] == 1) | (df_65['preg1_meth1_7'] == 1)|(df_65['preg1_meth1_8'] == 1) \
| (df_65['preg1_meth1_9'] == 1) | (df_65['preg1_meth1_10'] == 1) | (df_65['preg1_meth1_11']==1) \
| (df_65['preg1_meth1_13']==1) |(df_65['preg1_meth1_14']==1) | (df_65['preg1_meth1_16']==1), '_supplies' ] = 1
#generate dummy if oral contraception was used (pill)
df_65['_oral'] = 0
df_65.loc[ df_65['preg1_meth1_8'] == 1, '_oral' ] = 1
#repeat this for any different A-types of pregi_meth1_j
for i in range(0,21):
df_65.loc[ (df_65['preg{}_meth1_4'.format(i)] == 1) | (df_65['preg{}_meth1_5'.format(i)] == 1) \
| (df_65['preg{}_meth1_6'.format(i)] == 1) | (df_65['preg{}_meth1_7'.format(i)]==1) \
| (df_65['preg{}_meth1_8'.format(i)]==1) |(df_65['preg{}_meth1_12'.format(i)]==1) | (df_65['preg{}_meth1_9'.format(i)]==1) \
| (df_65['preg{}_meth1_10'.format(i)]==1) | (df_65['preg{}_meth1_11'.format(i)]==1) |(df_65['preg{}_meth1_13'.format(i)]==1) \
| (df_65['preg{}_meth1_14'.format(i)]==1)|(df_65['preg{}_meth1_15'.format(i)]==1) | (df_65['preg{}_meth1_16'.format(i)]==1), '_everuse_d'] = 1
df_65.loc[df_65['preg{}_meth1_3'.format(i)] == 0, '_everuse2_mjb'] = 1
df_65['_everuse3_mjb'] = df_65 ['_everuse_d']
df_65.loc[ (df_65['preg{}_meth1_13'.format(i)]==1) & (df_65['preg{}_meth1_1'.format(i)]==0) & (df_65['preg{}_meth1_2'.format(i)]==0) \
& (df_65['preg{}_meth1_3'.format(i)]==0) & (df_65['preg{}_meth1_4'.format(i)]==0) & (df_65['preg{}_meth1_5'.format(i)]==0) \
& (df_65['preg{}_meth1_6'.format(i)]==0) & (df_65['preg{}_meth1_7'.format(i)]==0) & (df_65['preg{}_meth1_8'.format(i)]==0) \
& (df_65['preg{}_meth1_9'.format(i)]==0) & (df_65['preg{}_meth1_10'.format(i)]==0) & (df_65['preg{}_meth1_11'.format(i)]==0) \
& (df_65['preg{}_meth1_12'.format(i)]==0) & (df_65['preg{}_meth1_14'.format(i)]==0) & (df_65['preg{}_meth1_15'.format(i)]==0) \
& (df_65['preg{}_meth1_16'.format(i)] == 0), '_everuse3_mjb' ] = 0
df_65.loc[ (df_65['preg{}_meth1_5'.format(i)] == 1) | (df_65['preg{}_meth1_7'.format(i)] == 1), '_barrier' ] = 1
df_65.loc[ (df_65['preg{}_meth1_5'.format(i)] == 1) | (df_65['preg{}_meth1_7'.format(i)] == 1)|(df_65['preg{}_meth1_8'.format(i)] == 1) \
| (df_65['preg{}_meth1_9'.format(i)] == 1) | (df_65['preg{}_meth1_10'.format(i)] == 1) | (df_65['preg{}_meth1_11'.format(i)]==1) \
| (df_65['preg{}_meth1_13'.format(i)]==1) |(df_65['preg{}_meth1_14'.format(i)]==1) | (df_65['preg{}_meth1_16'.format(i)]==1), '_supplies' ] = 1
df_65.loc[ df_65['preg{}_meth1_8'.format(i)] == 1, '_oral' ] = 1
#print(i)
df_65 = df_65[['_barrier', '_supplies', 'preg0_coitfr', '_oral', '_fecund', '_everuse_d','_everuse2_mjb','_everuse3_mjb', \
'H_emp_inc65', 'fam_idealch', 'att_idealch', 'res_popdens', 'res_reg', 'statefip', 'statename', 'int_num', 'per_race', \
'_age', 'ed_higrade', 'rel_pref', 'dob', 'fec_sterilop1', 'wgt', 'ch_totlb']]
df_65['year'] = 1965
#3. 1970 NFS
#read .dta file 1970 NFS
df_70 = pd.read_stata('data/nfs70_1.dta', convert_categoricals = False)
#generate dummy if ever used method of contraception or as douche
df_70['_everuse_d'] = 0
df_70.loc[ (df_70['preg1_meth_any'] == 1) | (df_70['dia_everuse'] == 1) | (df_70['iud_everuse'] == 1) \
| (df_70['_bcp_everuse'] == 1), '_everuse_d'] = 1
#genrate dummy if a barrier method (condom, diaphragma) was ever used
df_70['_barrier'] = 0
df_70.loc[ (df_70['preg1_meth_1'] == 3) | (df_70['preg1_meth_1'] == 5) | (df_70['dia_everuse'] == 1), '_barrier' ] = 1
#generate dummy if any supply methods were ever used (condoms, diaphragma, pill, jelly, foam, douche, IUD, Sponge )
df_70['_supplies'] = 0
df_70.loc[ (df_70['preg1_meth_1'] == 3) | (df_70['preg1_meth_1'] == 5) | (df_70['preg1_meth_1'] == 6) \
| (df_70['preg1_meth_1'] == 7) | (df_70['preg1_meth_1'] == 8) | (df_70['preg1_meth_1'] == 9) \
| (df_70['preg1_meth_1'] == 10) | (df_70['preg1_meth_1'] == 11) | (df_70['preg1_meth_1'] == 13) \
| (df_70['dia_everuse'] == 1) | (df_70['iud_everuse'] == 1) | (df_70['_bcp_everuse'] == 1), '_supplies'] = 1
#generate dummy if oral contraception was used (pill)
df_70['_oral'] = 0
df_70.loc[ (df_70['preg1_meth_1'] == 6) | (df_70['_bcp_everuse'] == 1), '_oral' ] = 1
# rename variable to make it suitable for loop
df_70 = df_70.rename(columns={'preg0_meth': 'preg0_meth_1'})
#df_70['preg0_meth_1'] = df_70['preg0_meth']
for i in range(0,20):
if i == 0 :
j = 1
df_70.loc[ df_70['preg0_meth1'] == 1, '_everuse_d' ] = 1
df_70.loc[ (df_70['preg0_meth_{}'.format(j)] == 3) | (df_70['preg0_meth_{}'.format(j)] == 5), '_barrier'] = 1
df_70.loc[ (df_70['preg0_meth_{}'.format(j)] == 3) | (df_70['preg0_meth_{}'.format(j)] == 5) | (df_70['preg0_meth_{}'.format(j)] == 6) \
| (df_70['preg0_meth_{}'.format(j)] == 7) | (df_70['preg0_meth_{}'.format(j)] == 8) | (df_70['preg0_meth_{}'.format(j)] == 9) \
| (df_70['preg0_meth_{}'.format(j)] == 10) | (df_70['preg0_meth_{}'.format(j)] == 11) | (df_70['preg0_meth_{}'.format(j)] == 13), '_supplies' ] = 1
df_70.loc[ (df_70['preg0_meth_{}'.format(j)] == 6), '_oral' ] = 1
else:
df_70.loc[ (df_70['preg{}_meth_any'.format(i)] == 1), '_everuse_d' ] = 1
for j in range(1,7):
df_70.loc[ (df_70['preg{}_meth_{}'.format(i,j)] == 3) | (df_70['preg{}_meth_{}'.format(i,j)] == 5), '_barrier'] = 1
df_70.loc[ (df_70['preg{}_meth_{}'.format(i,j)] == 3) | (df_70['preg{}_meth_{}'.format(i,j)] == 5) | (df_70['preg{}_meth_{}'.format(i,j)] == 6) \
| (df_70['preg{}_meth_{}'.format(i,j)] == 7) | (df_70['preg{}_meth_{}'.format(i,j)] == 8) | (df_70['preg{}_meth_{}'.format(i,j)] == 9) \
| (df_70['preg{}_meth_{}'.format(i,j)] == 10) | (df_70['preg{}_meth_{}'.format(i,j)] == 11) | (df_70['preg{}_meth_{}'.format(i,j)] == 13), '_supplies' ] = 1
df_70.loc[df_70['preg{}_meth_{}'.format(i,j)] == 6, '_oral'] = 1
#print(i)
df_70 = df_70[['_barrier', '_supplies', '_oral', 'preg0_coitfr', '_everuse_d', 'H_emp_inc70', 'fam_idealch', 'att_idealch',
'statefip', 'statename', 'int_LAN', 'int_LAN_size', 'int_LAN_region', 'int_num', 'per_race', 'wgt', '_age',
'mar_stat', 'ed_total', 'rel_pref', 'dob', 'fec_sterilop1', 'ch_totlb' ]]
df_70['year'] = 1970
#append data frames
df = df_55
df = df.append(df_65, ignore_index = True)
df = df.append(df_70, ignore_index = True)
#4. Harmonize definitions of sample variables
#Race
df['_White'] = 0
df.loc[df['year'] == 1955, '_White'] = 1
df.loc[(df['year'] == 1965) & (df['per_race'] == 1), '_White'] = 1
df.loc[(df['year'] == 1970) & (df['per_race'] == 2), '_White'] = 1
#Marital Status
df['_Married'] = 0
df.loc[(df['year'] == 1955) | (df['year'] == 1965), '_Married'] = 1
df.loc[(df['year'] == 1970) & (df['mar_stat'] == 1), '_Married'] = 1
#Education
df['_ed_cat'] = np.NaN
lis = [0,9,12,13,16,18]
df.loc[(df['year'] == 1965) & (df['ed_higrade'] == 0), '_ed_cat'] = 0
for i in range(1,len(lis)):
#print(i)
df.loc[ (df['year'] == 1965) & ( lis[i-1] <= df['ed_higrade'] ) & (df['ed_higrade'] < lis[i]), '_ed_cat' ] = lis[i-1]
df.loc[ (df['ed_total'] == i), 'ed_total'] = lis[i-1]
df.loc[ (df['year'] == 1970), '_ed_cat'] = df['ed_total']
df.loc[ (df['ed'] <= 4) & (df['ed'] >= 1), 'ed'] = 0
df.loc[ (df['ed'] == 8) | (df['ed'] == 9),'ed'] = 16
df.loc[ (df['ed'] == 5), 'ed'] = 9
df.loc[ (df['ed'] == 6), 'ed'] = 12
df.loc[ (df['ed'] == 7), 'ed'] = 13
df.loc[ (df['year'] == 1955), '_ed_cat'] = df['ed']
#Catholic
df['_Catholic'] = 0
df.loc[ ((df['year'] == 1955) & (df['rel_pref'] == 10)) | ((df['year'] == 1965) & (df['rel_pref'] == 21)) | \
((df['year'] == 1970) & (df['rel_pref'] == 21)), '_Catholic'] = 1
#Birth Cohort
df['_yob'] = np.NaN
lis = range(0,870,12)
for i in lis:
df.loc[ ((df['year'] == 1970) | (df['year'] == 1965)) & (df['dob'] >= i) & (df['dob'] < i + 12), '_yob'] = i /12 + 1900
df.loc[ ((df['year'] == 1970) | (df['year'] == 1965)) & (df['dob'] > 900), '_yob'] = df['dob'] + 1000
df.loc[ (df['year'] == 1955), '_yob' ] = df['dob_y'] + 1900
df['_yobcat'] = np.NaN
lis = range(1910,1960, 5)
for i in lis:
df.loc[ (df['_yob'] >= i) & (df['_yob'] < i + 5), '_yobcat'] = i
#age
df['_age'] = np.NaN
df['_age'] = df['year'] - df['_yob']
df['_agecat'] = np.NaN
lis = range(15,60,5)
for i in lis:
df.loc[ (df['_age'] >= i) & (df['_age'] < i + 5), '_agecat'] = i
#Surgically sterilized
df['_sterilop'] = 0
df.loc[ (df['year'] == 1955) & (df['fec_ster1'] != 0) & (df['fec_ster1'] != 6), '_sterilop' ] = 1
df.loc[ (df['year'] == 1965) & (df['fec_sterilop1'] == 1), '_sterilop' ] = 1
df.loc[ (df['year'] == 1970) & (df['fec_sterilop1'] == 1), '_sterilop' ] = 1
#ideal number of children for american family
df['_att_idealch'] = np.NaN #create variable to standardize variables.
df.loc[(df['att_idealch'] < 99) & (df['year'] == 1955), '_att_idealch'] = df['att_idealch']/10
df.loc[ (df['att_idealch'] > 90) & (df['att_idealch'] <= 130) & (df['year'] == 1965), 'att_idealch' ] = 90 #fix coding bug
df.loc[ ((df['att_idealch'] <= 90) & (df['year'] == 1965)) \
| ((df['att_idealch'] < 96) & (df['year'] == 1970)), '_att_idealch'] = df['att_idealch']/10
df['_idealcat'] = np.NaN
lis = [0,2,3,4,5,10,1000] #1000 can be an arbitrary high value. Just to make loop suitable
for i in range(0, (len(lis)-1)):
#print(i)
df.loc[ (lis[i] <= df['_att_idealch']) & (df['_att_idealch'] < lis[i+1]), '_idealcat' ] = lis[i]
#Husbands income
df['h_empinc65'] = np.NaN
df.loc[ (df['year'] == 1965), 'h_empinc65' ] = df['H_emp_inc65']
df.loc[ (df['h_empinc65'] != 0) & (df['h_empinc65'] < 10), 'h_empinc65' ] = df['h_empinc65']*1000+500
df.loc[(df['h_empinc65'] == 10), 'h_empinc65' ] = 11000
df.loc[(df['h_empinc65'] == 20), 'h_empinc65' ] = 13500
df.loc[ (df['h_empinc65'] == 30), 'h_empinc65' ] = 21000
df.loc[(df['h_empinc65'] == 88) | (df['h_empinc65'] == 99), 'h_empinc65' ] = np.NaN
df['h_empinc70'] = np.NaN
df.loc[(df['year'] == 1970), 'h_empinc70' ] = df['H_emp_inc70']
df.loc[ (df['h_empinc70'] != 0) & (df['h_empinc70'] < 10), 'h_empinc70' ] = df['h_empinc70']*1000+500
df.loc[ (df['h_empinc70'] == 10), 'h_empinc70' ] = 12000
df.loc[ (df['h_empinc70'] == 11), 'h_empinc70' ] = 13500
df.loc[ (df['h_empinc70'] == 12), 'h_empinc70' ] = 21000
df.loc[ (df['h_empinc70'] == 88) | (df['h_empinc70'] == 99), 'h_empinc70' ] = np.NaN
df['h_empinc55'] = np.NaN
df.loc[ (df['year'] == 1955), 'h_empinc55' ] = df['h_emp_inc']
df.loc[ (df['h_empinc55'] != 0) & (df['h_empinc55'] < 9), 'h_empinc55' ] = (df['h_empinc55']-1)*1000+500
df.loc[ (df['h_empinc55'] == 9), 'h_empinc55' ] = 9000
df.loc[ (df['h_empinc55'] == 10), 'h_empinc55' ] = 14000
df.loc[ (df['h_empinc55'] == 88) | (df['h_empinc55'] == 99), 'h_empinc55' ] = np.NaN
df['_h_empinc'] = np.NaN
df.loc[(df['year'] == 1955), '_h_empinc'] = (36.7/26.9)*df['h_empinc55'] #in 1969 US Dollar
df.loc[(df['year'] == 1965), '_h_empinc'] = (36.7/31)*df['h_empinc65'] #in 1969 US Dollar
df.loc[(df['year'] == 1970), '_h_empinc'] = df['h_empinc70'] #in 1969 US Dollar
df['_hinccat'] = np.NaN
df.loc[(0 <=df['_h_empinc']) & (df['_h_empinc'] <= 4500), '_hinccat'] = 0
df.loc[(4500 < df['_h_empinc']) & (df['_h_empinc'] <= 6500), '_hinccat'] = 1
df.loc[(6500 < df['_h_empinc']) & (df['_h_empinc'] <= 8400), '_hinccat'] = 2
df.loc[ (8400 < df['_h_empinc']) & (df['_h_empinc'] <= 12000), '_hinccat'] = 3
df.loc[(12000 <= df['_h_empinc']) & (df['_h_empinc'] <= 25000), '_hinccat'] = 4
#Attitudes on family planning
df['_approvefp55'] = np.NaN
df.loc[(df['year'] == 1955), '_approvefp55'] = 0
df.loc[(df['year'] == 1955) & (df['att_famplan'] <= 2), '_approvefp55' ] = 1
#Region
df.loc[( (df['int_LAN_region'] == 1) | (df['int_LAN_region'] == 2) ) & (df['year'] == 1970), 'res_reg' ] = 1
df.loc[( (df['int_LAN_region'] == 3) | (df['int_LAN_region'] == 4) ) & (df['year'] == 1970), 'res_reg' ] = 2
df.loc[( (df['int_LAN_region'] == 5) | (df['int_LAN_region'] == 6) | (df['int_LAN_region'] == 7) ) & (df['year'] == 1970), 'res_reg' ] = 3
df.loc[( (df['int_LAN_region'] == 8) | (df['int_LAN_region'] == 9) ) & (df['year'] == 1970), 'res_reg' ] = 4
df.loc[(df['int_LAN'] >= 54002) & (df['int_LAN'] <= 54013) & (df['year'] == 1970), 'res_reg' ] = 1
df.loc[ (df['statefip'] == 11) & (df['year'] == 1970), 'res_reg' ] = 3
df.loc[ (df['year'] == 1955), 'res_reg' ] = df['_region']
df = df.drop(columns=['_region'])
df = df.rename(columns={'res_reg': '_region'}) #see codebokkNFS65
#Live births
df.loc[ df['ch_totlb'] > 12, 'ch_totlb' ] = 12
#coital frequency
df['_coit_freq'] = np.NaN
df.loc[df['preg0_coitfr'] < 98, '_coit_freq'] = df['preg0_coitfr']
#5. Merge to Statenames sice some states have the name with a space ' ' in th beginning
sn = pd.read_stata('data/temp.dta', convert_categoricals = False)
lis = sn['statefip']
for i in lis:
L = len(df['statename'][df['statefip'] == i])
df['statename'][ df['statefip'] == i] = np.repeat(sn['statename'][ sn['statefip'] == i], L)
#df.loc[ df['statefip'] == i, 'statename'] = np.repeat(sn['statename'][ sn['statefip'] == i], L)
#6. Merge to Griswold Laws
gl = pd.read_stata('data/griswoldlaws5.dta', convert_categoricals = False)
df = df[df.statefip != 11] #delete columbia
df['sales'] = np.NaN
df['any'] = np.NaN
df['_Phys'] = np.NaN
df['cstck'] = np.NaN
df['_Phy_LB'] = np.NaN
lis = gl['statefip']
indexcol = ['sales', 'any', '_Phys', 'cstck', '_Phy_LB']
for column in indexcol:
#print(column)
for i in lis:
L = len(df[column][df['statefip'] == i])
df[column][df['statefip'] == i] = np.repeat(gl[column][ gl['statefip'] == i], L)
df['__yobcat'] = np.NaN
if agegroup_type_Bailey is True:
lis = range(1910,1950,20)
else:
lis = range(1910,1960,20)
for i in lis:
#print(i)
df.loc[ (df['_yobcat'] >= i) & (df['_yobcat'] < i + 20), '__yobcat'] = i #maybe error in stata code (values above 1950 are set as missing)
return df
| en | 0.705004 | Function to create the relevant categorials from scratch.
Args:
-------
Returns:
-------
A data frame containing the variables needed for the analysis. #1. 1955 GAF #Read dta file 1955 GAF #generate dummy: 1 if fertile and 0 if not #generate dummy if ever used method of contraception #generate dummy if ever used method of contraception or as douche #generate dummy if ever used condom or diaphragma #generate dummy whether either condom, diaphragma, helly, vagsupp, foamtab, #tampon or any other method was ever used #generate dummy, if ever used oral contraception (not possible in 1955) #generate dummy wgt #generate year #2. 1965 NFS #read .dta file 1965 NFS #generate dummy for fertility, one means fertile #generate dummy if ever used method of contraception or as douche #generate dummy whether a contraception method was used before the first pregnancy #1 if not used before first pregnancy # no answer to question of contraception used before first pregnancy #generate dummy if ever used method of contraception (exclusive douche) #genrate dummy if a barrier method (condom, diaphragma) was ever used #generate dummy if any supply methods were ever used (condoms, diaphragma, pill, jelly, foam, douche, IUD, Sponge ) #generate dummy if oral contraception was used (pill) #repeat this for any different A-types of pregi_meth1_j #print(i) #3. 1970 NFS #read .dta file 1970 NFS #generate dummy if ever used method of contraception or as douche #genrate dummy if a barrier method (condom, diaphragma) was ever used #generate dummy if any supply methods were ever used (condoms, diaphragma, pill, jelly, foam, douche, IUD, Sponge ) #generate dummy if oral contraception was used (pill) # rename variable to make it suitable for loop #df_70['preg0_meth_1'] = df_70['preg0_meth'] #print(i) #append data frames #4. Harmonize definitions of sample variables #Race #Marital Status #Education #print(i) #Catholic #Birth Cohort #age #Surgically sterilized #ideal number of children for american family #create variable to standardize variables. #fix coding bug #1000 can be an arbitrary high value. Just to make loop suitable #print(i) #Husbands income #in 1969 US Dollar #in 1969 US Dollar #in 1969 US Dollar #Attitudes on family planning #Region #see codebokkNFS65 #Live births #coital frequency #5. Merge to Statenames sice some states have the name with a space ' ' in th beginning #df.loc[ df['statefip'] == i, 'statename'] = np.repeat(sn['statename'][ sn['statefip'] == i], L) #6. Merge to Griswold Laws #delete columbia #print(column) #print(i) #maybe error in stata code (values above 1950 are set as missing) | 2.995849 | 3 |
run.py | cvython/vython1 | 24 | 6614205 | <reponame>cvython/vython1
import os
class ExecuteScript(object):
def __init__(self,
filename=None,
from_file=True,
content=None,
error=None,
lexer=None,
parser=None):
self.filename = filename
self.from_file = from_file
self.content = content
self.error = error
self.lexer = lexer
self.parser = parser
if self.from_file:
if not os.path.isfile(self.filename):
if self.error:
self.error(f'{self.filename} is not a file')
with open(self.filename, 'r') as file_content_reader:
self.content = file_content_reader.read()
self.execute_script()
def execute_script(self):
tokens = self.lexer.lex(self.content)
parser = self.parser.parse(tokens)
| import os
class ExecuteScript(object):
def __init__(self,
filename=None,
from_file=True,
content=None,
error=None,
lexer=None,
parser=None):
self.filename = filename
self.from_file = from_file
self.content = content
self.error = error
self.lexer = lexer
self.parser = parser
if self.from_file:
if not os.path.isfile(self.filename):
if self.error:
self.error(f'{self.filename} is not a file')
with open(self.filename, 'r') as file_content_reader:
self.content = file_content_reader.read()
self.execute_script()
def execute_script(self):
tokens = self.lexer.lex(self.content)
parser = self.parser.parse(tokens) | none | 1 | 3.141675 | 3 | |
tests/data_model/test_abstract_model.py | cybercamp18isecurity/iSecurity | 4 | 6614206 | <gh_stars>1-10
import pytest
from data_model.abstract_model import AbstractModel
from data_model.model import Model
class ModelTest(AbstractModel):
def __init__(self, elasticsearch):
self.data_type = "test"
AbstractModel.__init__(self, elasticsearch, self.data_type)
@pytest.fixture()
def model_test(elk_host):
model = Model(elk_host, 9200)
test_model = ModelTest(model._elk)
return test_model
def test_get(model_test):
data = model_test.get(1)
assert int(data['_id']) == 1
def test_search(model_test):
data = model_test.search("id_external", "1234")
assert int(data[0]['_id']) == 1
def test_query(model_test):
query = {
"query": {
"term": {
"id_external": "1234"
}
}
}
data = model_test.query(query)
assert data[0]['_source']['id_external'] == "1234"
def test_create(model_test):
data = {
"id_external": "4321",
"type": "0",
"status": 0
}
id = "2"
data = model_test.create(id, data)
assert data == str(2)
def test_update(model_test):
data = {
"id_external": "2222",
"type": "0",
"status": 0
}
id = "3"
data = model_test.create(id, data)
assert data == id
update_data = {
"criticity": 1
}
data = model_test.update(id, update_data)
assert data == id
data_get = model_test.get(id)
data = data_get["_source"]
assert data['criticity'] == 1
assert data['status'] == 0
assert data['type'] == "0"
assert data['id_external'] == "2222"
| import pytest
from data_model.abstract_model import AbstractModel
from data_model.model import Model
class ModelTest(AbstractModel):
def __init__(self, elasticsearch):
self.data_type = "test"
AbstractModel.__init__(self, elasticsearch, self.data_type)
@pytest.fixture()
def model_test(elk_host):
model = Model(elk_host, 9200)
test_model = ModelTest(model._elk)
return test_model
def test_get(model_test):
data = model_test.get(1)
assert int(data['_id']) == 1
def test_search(model_test):
data = model_test.search("id_external", "1234")
assert int(data[0]['_id']) == 1
def test_query(model_test):
query = {
"query": {
"term": {
"id_external": "1234"
}
}
}
data = model_test.query(query)
assert data[0]['_source']['id_external'] == "1234"
def test_create(model_test):
data = {
"id_external": "4321",
"type": "0",
"status": 0
}
id = "2"
data = model_test.create(id, data)
assert data == str(2)
def test_update(model_test):
data = {
"id_external": "2222",
"type": "0",
"status": 0
}
id = "3"
data = model_test.create(id, data)
assert data == id
update_data = {
"criticity": 1
}
data = model_test.update(id, update_data)
assert data == id
data_get = model_test.get(id)
data = data_get["_source"]
assert data['criticity'] == 1
assert data['status'] == 0
assert data['type'] == "0"
assert data['id_external'] == "2222" | none | 1 | 2.419612 | 2 | |
setup.py | hjweide/a-star | 96 | 6614207 | <filename>setup.py
import setuptools
from distutils.core import Extension
from setuptools import dist
dist.Distribution().fetch_build_eggs(["numpy"])
import numpy
astar_module = Extension(
'pyastar2d.astar', sources=['src/cpp/astar.cpp', 'src/cpp/experimental_heuristics.cpp'],
include_dirs=[
numpy.get_include(), # for numpy/arrayobject.h
'src/cpp' # for experimental_heuristics.h
],
extra_compile_args=["-O3", "-Wall", "-shared", "-fpic"],
)
with open("requirements.txt", "r") as fh:
install_requires = fh.readlines()
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="pyastar2d",
version="1.0.6",
author="<NAME>",
author_email="<EMAIL>",
description=(
"A simple implementation of the A* algorithm for "
"path-finding on a two-dimensional grid."),
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/hjweide/pyastar2d",
install_requires=install_requires,
packages=setuptools.find_packages(where="src", exclude=("tests",)),
package_dir={"": "src"},
ext_modules=[astar_module],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.7',
)
| <filename>setup.py
import setuptools
from distutils.core import Extension
from setuptools import dist
dist.Distribution().fetch_build_eggs(["numpy"])
import numpy
astar_module = Extension(
'pyastar2d.astar', sources=['src/cpp/astar.cpp', 'src/cpp/experimental_heuristics.cpp'],
include_dirs=[
numpy.get_include(), # for numpy/arrayobject.h
'src/cpp' # for experimental_heuristics.h
],
extra_compile_args=["-O3", "-Wall", "-shared", "-fpic"],
)
with open("requirements.txt", "r") as fh:
install_requires = fh.readlines()
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="pyastar2d",
version="1.0.6",
author="<NAME>",
author_email="<EMAIL>",
description=(
"A simple implementation of the A* algorithm for "
"path-finding on a two-dimensional grid."),
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/hjweide/pyastar2d",
install_requires=install_requires,
packages=setuptools.find_packages(where="src", exclude=("tests",)),
package_dir={"": "src"},
ext_modules=[astar_module],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
],
python_requires='>=3.7',
)
| en | 0.436683 | # for numpy/arrayobject.h # for experimental_heuristics.h | 1.951826 | 2 |
Diena_1_4_thonny/d4_f1_u1.py | edzya/Python_RTU_08_20 | 8 | 6614208 | # fizz = "Fizz"
# buzz = "Buzz"
# fiz_num = 5
# buzz_num = 7
# for n in range (1,101):
# if n % fiz_num == 0 and n % buzz_num == 0:
# print(fizz+buzz)
# elif n % fiz_num == 0:
# print(fizz)
# elif n % buzz_num == 0:
# print(buzz)
# else:
# print(n)
for i in range(1,101):
if i%5 == 0:
print("Fizz",end="")
if i%7 == 0:
print("Buzz",end="")
if i%5 !=0 and i%7 != 0:
print(i, end="")
if i < 100:
print(",", end="")
| # fizz = "Fizz"
# buzz = "Buzz"
# fiz_num = 5
# buzz_num = 7
# for n in range (1,101):
# if n % fiz_num == 0 and n % buzz_num == 0:
# print(fizz+buzz)
# elif n % fiz_num == 0:
# print(fizz)
# elif n % buzz_num == 0:
# print(buzz)
# else:
# print(n)
for i in range(1,101):
if i%5 == 0:
print("Fizz",end="")
if i%7 == 0:
print("Buzz",end="")
if i%5 !=0 and i%7 != 0:
print(i, end="")
if i < 100:
print(",", end="")
| en | 0.515362 | # fizz = "Fizz" # buzz = "Buzz" # fiz_num = 5 # buzz_num = 7 # for n in range (1,101): # if n % fiz_num == 0 and n % buzz_num == 0: # print(fizz+buzz) # elif n % fiz_num == 0: # print(fizz) # elif n % buzz_num == 0: # print(buzz) # else: # print(n) | 3.589918 | 4 |
trojsten/rules/fx.py | MvonK/web | 5 | 6614209 | <filename>trojsten/rules/fx.py
from .default import CompetitionRules
class FXRules(CompetitionRules):
pass
| <filename>trojsten/rules/fx.py
from .default import CompetitionRules
class FXRules(CompetitionRules):
pass
| none | 1 | 1.083519 | 1 | |
M1_Retinal_Image_quality_EyePACS/merge_quality_assessment.py | rmaphoh/AutoMorph | 1 | 6614210 | import numpy as np
import pandas as pd
import shutil
import os
result_Eyepacs = './test_outside/results_ensemble.csv'
if not os.path.exists('../Results/M1/Good_quality/'):
os.makedirs('../Results/M1/Good_quality/')
if not os.path.exists('../Results/M1/Bad_quality/'):
os.makedirs('../Results/M1/Bad_quality/')
result_Eyepacs_ = pd.read_csv(result_Eyepacs)
Eyepacs_pre = result_Eyepacs_['Prediction']
Eyepacs_bad_mean = result_Eyepacs_['softmax_bad']
Eyepacs_usable_sd = result_Eyepacs_['usable_sd']
name_list = result_Eyepacs_['Name']
Eye_good = 0
Eye_bad = 0
for i in range(len(name_list)):
if Eyepacs_pre[i]==0:
Eye_good+=1
shutil.copy(name_list[i], '../Results/M1/Good_quality/')
elif (Eyepacs_pre[i]==1) and (Eyepacs_bad_mean[i]<0.25):
#elif (Eyepacs_pre[i]==1) and (Eyepacs_bad_mean[i]<0.25) and (Eyepacs_usable_sd[i]<0.1):
Eye_good+=1
shutil.copy(name_list[i], '../Results/M1/Good_quality/')
else:
Eye_bad+=1
shutil.copy(name_list[i], '../Results/M1/Bad_quality/')
#shutil.copy(name_list[i], '../Results/M1/Good_quality/')
print('Gradable cases by EyePACS_QA is {} '.format(Eye_good))
print('Ungradable cases by EyePACS_QA is {} '.format(Eye_bad))
| import numpy as np
import pandas as pd
import shutil
import os
result_Eyepacs = './test_outside/results_ensemble.csv'
if not os.path.exists('../Results/M1/Good_quality/'):
os.makedirs('../Results/M1/Good_quality/')
if not os.path.exists('../Results/M1/Bad_quality/'):
os.makedirs('../Results/M1/Bad_quality/')
result_Eyepacs_ = pd.read_csv(result_Eyepacs)
Eyepacs_pre = result_Eyepacs_['Prediction']
Eyepacs_bad_mean = result_Eyepacs_['softmax_bad']
Eyepacs_usable_sd = result_Eyepacs_['usable_sd']
name_list = result_Eyepacs_['Name']
Eye_good = 0
Eye_bad = 0
for i in range(len(name_list)):
if Eyepacs_pre[i]==0:
Eye_good+=1
shutil.copy(name_list[i], '../Results/M1/Good_quality/')
elif (Eyepacs_pre[i]==1) and (Eyepacs_bad_mean[i]<0.25):
#elif (Eyepacs_pre[i]==1) and (Eyepacs_bad_mean[i]<0.25) and (Eyepacs_usable_sd[i]<0.1):
Eye_good+=1
shutil.copy(name_list[i], '../Results/M1/Good_quality/')
else:
Eye_bad+=1
shutil.copy(name_list[i], '../Results/M1/Bad_quality/')
#shutil.copy(name_list[i], '../Results/M1/Good_quality/')
print('Gradable cases by EyePACS_QA is {} '.format(Eye_good))
print('Ungradable cases by EyePACS_QA is {} '.format(Eye_bad))
| en | 0.377313 | #elif (Eyepacs_pre[i]==1) and (Eyepacs_bad_mean[i]<0.25) and (Eyepacs_usable_sd[i]<0.1): #shutil.copy(name_list[i], '../Results/M1/Good_quality/') | 2.255149 | 2 |
task_04/task.py | prashnts/advent-of-code--2021 | 0 | 6614211 | <filename>task_04/task.py
import os
import re
__here__ = os.path.dirname(__file__)
TEST_DATA = '''\
7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1
22 13 17 11 0
8 2 23 4 24
21 9 14 16 7
6 10 3 18 5
1 12 20 15 19
3 15 0 2 22
9 18 13 17 5
19 8 7 25 23
20 11 10 24 4
14 21 16 12 6
14 21 17 24 4
10 16 15 9 19
18 8 23 26 20
22 11 13 6 5
2 0 12 3 7\
'''
def decode_input(data):
# begin with splitting data by lines.
lines = data.split('\n')
# The first line of the data is our random numbers.
rand_numbers = lines.pop(0)
yield [int(x) for x in rand_numbers.split(',')]
boards_coded = [line for line in lines if line]
for i in range(len(boards_coded) // 5):
rows = boards_coded[i * 5:(i + 1) * 5]
split_nums = lambda row: re.split(r'\s+', row.strip())
make_cells = lambda row: [[int(x), False] for x in row]
board = [make_cells(split_nums(row)) for row in rows]
yield board
def mark_board(board, num):
# make a copy of the board.
board = [row[:] for row in board]
for i, row in enumerate(board):
for j, cell in enumerate(row):
cell_num, _ = cell
if cell_num == num:
board[i][j][1] = True
return board
def is_winning(board):
# we need to check if either a row-wise or a column-wise direction is
# marked true.
check_line = lambda line: all([x[1] for x in line])
row_wise = any([check_line(row) for row in board])
column_wise = any([check_line(col) for col in zip(*board)])
return row_wise or column_wise
def sum_unmarked(board):
total = 0
for row in board:
for cell_num, state in row:
if not state:
total += cell_num
return total
def calculate_1(data):
decoder = decode_input(data)
rands = next(decoder)
boards = list(decoder)
for num in rands:
for i, board in enumerate(boards):
new_board = mark_board(board, num)
boards[i] = new_board
# now check all boards for winner.
for board in boards:
if is_winning(board):
return sum_unmarked(board) * num
def calculate_2(data):
decoder = decode_input(data)
rands = next(decoder)
boards = list(decoder)
for num in rands:
for i, board in enumerate(boards):
new_board = mark_board(board, num)
boards[i] = new_board
# Only one board should be left after eliminating winning boards.
if len(boards) == 1 and is_winning(boards[0]):
return sum_unmarked(boards[0]) * num
# Eliminate boards that are winning.
boards = [board for board in boards if not is_winning(board)]
if __name__ == '__main__':
assert calculate_1(TEST_DATA) == 4512
assert calculate_2(TEST_DATA) == 1924
with open(os.path.join(__here__, 'input.txt'), 'r') as fp:
data = fp.read()
answer_1 = calculate_1(data)
answer_2 = calculate_2(data)
print(f'{answer_1=}')
print(f'{answer_2=}')
| <filename>task_04/task.py
import os
import re
__here__ = os.path.dirname(__file__)
TEST_DATA = '''\
7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1
22 13 17 11 0
8 2 23 4 24
21 9 14 16 7
6 10 3 18 5
1 12 20 15 19
3 15 0 2 22
9 18 13 17 5
19 8 7 25 23
20 11 10 24 4
14 21 16 12 6
14 21 17 24 4
10 16 15 9 19
18 8 23 26 20
22 11 13 6 5
2 0 12 3 7\
'''
def decode_input(data):
# begin with splitting data by lines.
lines = data.split('\n')
# The first line of the data is our random numbers.
rand_numbers = lines.pop(0)
yield [int(x) for x in rand_numbers.split(',')]
boards_coded = [line for line in lines if line]
for i in range(len(boards_coded) // 5):
rows = boards_coded[i * 5:(i + 1) * 5]
split_nums = lambda row: re.split(r'\s+', row.strip())
make_cells = lambda row: [[int(x), False] for x in row]
board = [make_cells(split_nums(row)) for row in rows]
yield board
def mark_board(board, num):
# make a copy of the board.
board = [row[:] for row in board]
for i, row in enumerate(board):
for j, cell in enumerate(row):
cell_num, _ = cell
if cell_num == num:
board[i][j][1] = True
return board
def is_winning(board):
# we need to check if either a row-wise or a column-wise direction is
# marked true.
check_line = lambda line: all([x[1] for x in line])
row_wise = any([check_line(row) for row in board])
column_wise = any([check_line(col) for col in zip(*board)])
return row_wise or column_wise
def sum_unmarked(board):
total = 0
for row in board:
for cell_num, state in row:
if not state:
total += cell_num
return total
def calculate_1(data):
decoder = decode_input(data)
rands = next(decoder)
boards = list(decoder)
for num in rands:
for i, board in enumerate(boards):
new_board = mark_board(board, num)
boards[i] = new_board
# now check all boards for winner.
for board in boards:
if is_winning(board):
return sum_unmarked(board) * num
def calculate_2(data):
decoder = decode_input(data)
rands = next(decoder)
boards = list(decoder)
for num in rands:
for i, board in enumerate(boards):
new_board = mark_board(board, num)
boards[i] = new_board
# Only one board should be left after eliminating winning boards.
if len(boards) == 1 and is_winning(boards[0]):
return sum_unmarked(boards[0]) * num
# Eliminate boards that are winning.
boards = [board for board in boards if not is_winning(board)]
if __name__ == '__main__':
assert calculate_1(TEST_DATA) == 4512
assert calculate_2(TEST_DATA) == 1924
with open(os.path.join(__here__, 'input.txt'), 'r') as fp:
data = fp.read()
answer_1 = calculate_1(data)
answer_2 = calculate_2(data)
print(f'{answer_1=}')
print(f'{answer_2=}')
| en | 0.766702 | \ 7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1 22 13 17 11 0 8 2 23 4 24 21 9 14 16 7 6 10 3 18 5 1 12 20 15 19 3 15 0 2 22 9 18 13 17 5 19 8 7 25 23 20 11 10 24 4 14 21 16 12 6 14 21 17 24 4 10 16 15 9 19 18 8 23 26 20 22 11 13 6 5 2 0 12 3 7\ # begin with splitting data by lines. # The first line of the data is our random numbers. # make a copy of the board. # we need to check if either a row-wise or a column-wise direction is # marked true. # now check all boards for winner. # Only one board should be left after eliminating winning boards. # Eliminate boards that are winning. | 3.100058 | 3 |
justanunsuspectingmodule/__init__.py | Igor-Sviridov/justanunsuspectingmodule | 0 | 6614212 | from justanunsuspectingmodule.model_class import model
| from justanunsuspectingmodule.model_class import model
| none | 1 | 1.110154 | 1 | |
storage/team17/DataBase.py | gstavosanchez/tytus | 0 | 6614213 | <reponame>gstavosanchez/tytus
class DB():
def __init__(self):
self.dicDB = {}
self.dicTB = {}
#---------------------FUNCIONES BASES DE DATOS----------------------#
# CREAR BASE DE DATOS
def createDatabase(self, database):
if self.identify(database):
ready = False
if self.searchDB(database):
return 2
else:
self.dicDB[database] = self.dicTB
ready = True
if ready:
return 0
else:
return 1
else:
return 1
# LISTA DE BASES DE DATOS ALMACENADAS
def showDatabases(self):
keys = list()
for key in self.dicDB:
keys.append(key)
print(keys)
return keys
# CAMBIAR NOMBRE DE UNA BASE DE DATOS
def alterDatabase(self, databaseOld, databseNew):
if self.identify(databaseOld) and self.identify(databseNew):
ready = False
if self.searchDB(databaseOld):
if self.searchDB(databseNew):
return 3
else:
tmp = {}
for key, value in self.dicDB.items():
if key == databaseOld:
key = databseNew
tmp[key] = value
self.dicDB = tmp
ready = True
else:
return 2
if ready:
return 0
else:
return 1
else:
return 1
# ELIMINAR BASE DE DATOS
def dropDatabase(self, database):
if self.identify(database):
ready = False
if self.searchDB(database):
self.dicDB.pop(database)
ready = True
else:
return 2
if ready:
return 0
else:
return 1
else:
return 1
# ---------------------FUNCIONES TABLAS----------------------#
#--------------------UTILIDADES--------------------#
# VALIDA EL NOMBRE CON LAS REGLAS DE IDENTIFICADORES DE SQL
def identify(self, id):
special = ["[","@", "_", "o", "#"]
if id[0].isalpha():
return True
else:
if id[0].isdigit():
return False
elif id[0] in special:
if id[0] != '"' and id[0] != '[':
return True
else:
if id[0] == "[":
if id[len(id) - 1] == "]":
return True
else:
return False
else:
return False
# BUSCAR SI EXISTE LA BASE DE DATOS
def searchDB(self, key):
if key in self.dicDB.keys():
return True
else:
return False
# ---------------------EXTRAS----------------------#
# CREAR Y AÑADIR UNA TABLA
def addTable(self, key, name, content):
if self.searchDB(key):
if self.dicDB.get(key):
if self.searchTB(key, name):
print("Ya existe una tabla con ese nombre")
else:
dict2 = self.dicDB.get(key)
dict2[name] = content
self.dicDB[key] = dict2
else:
self.dicDB[key] = {name:content}
else:
print("No existe la base de datos")
# BUSCAR SI EXISTE LA TABLA EN UNA BASE DE DATOS
def searchTB(self, key, name):
if name in self.dicDB.get(key).keys():
return True
else:
False
# ELIMINAR TABLA DE UNA BASE DE DATOS
def deleteTB(self, key, name):
self.dicDB.get(key).pop(name)
# MOSTRAR BASES DE DATOS ALMACENADAS
def print(self):
n = 0
for key in self.dicDB:
print("[" + str(n) + "]","Base:", key, "| Tablas:", self.dicDB.get(key))
n +=1
# MOSTRAR TABLAS ALMACENDAS
def print(self):
n = 0
for key in self.dicDB.keys():
print(key + ":")
for i in self.dicDB.get(key).keys():
print(" "+i + ":")
for j in self.dicDB.get(key).get(i).keys():
print(" "+j+":")
for k in self.dicDB.get(key).get(i).get(j):
print(" "+str(k))
| class DB():
def __init__(self):
self.dicDB = {}
self.dicTB = {}
#---------------------FUNCIONES BASES DE DATOS----------------------#
# CREAR BASE DE DATOS
def createDatabase(self, database):
if self.identify(database):
ready = False
if self.searchDB(database):
return 2
else:
self.dicDB[database] = self.dicTB
ready = True
if ready:
return 0
else:
return 1
else:
return 1
# LISTA DE BASES DE DATOS ALMACENADAS
def showDatabases(self):
keys = list()
for key in self.dicDB:
keys.append(key)
print(keys)
return keys
# CAMBIAR NOMBRE DE UNA BASE DE DATOS
def alterDatabase(self, databaseOld, databseNew):
if self.identify(databaseOld) and self.identify(databseNew):
ready = False
if self.searchDB(databaseOld):
if self.searchDB(databseNew):
return 3
else:
tmp = {}
for key, value in self.dicDB.items():
if key == databaseOld:
key = databseNew
tmp[key] = value
self.dicDB = tmp
ready = True
else:
return 2
if ready:
return 0
else:
return 1
else:
return 1
# ELIMINAR BASE DE DATOS
def dropDatabase(self, database):
if self.identify(database):
ready = False
if self.searchDB(database):
self.dicDB.pop(database)
ready = True
else:
return 2
if ready:
return 0
else:
return 1
else:
return 1
# ---------------------FUNCIONES TABLAS----------------------#
#--------------------UTILIDADES--------------------#
# VALIDA EL NOMBRE CON LAS REGLAS DE IDENTIFICADORES DE SQL
def identify(self, id):
special = ["[","@", "_", "o", "#"]
if id[0].isalpha():
return True
else:
if id[0].isdigit():
return False
elif id[0] in special:
if id[0] != '"' and id[0] != '[':
return True
else:
if id[0] == "[":
if id[len(id) - 1] == "]":
return True
else:
return False
else:
return False
# BUSCAR SI EXISTE LA BASE DE DATOS
def searchDB(self, key):
if key in self.dicDB.keys():
return True
else:
return False
# ---------------------EXTRAS----------------------#
# CREAR Y AÑADIR UNA TABLA
def addTable(self, key, name, content):
if self.searchDB(key):
if self.dicDB.get(key):
if self.searchTB(key, name):
print("Ya existe una tabla con ese nombre")
else:
dict2 = self.dicDB.get(key)
dict2[name] = content
self.dicDB[key] = dict2
else:
self.dicDB[key] = {name:content}
else:
print("No existe la base de datos")
# BUSCAR SI EXISTE LA TABLA EN UNA BASE DE DATOS
def searchTB(self, key, name):
if name in self.dicDB.get(key).keys():
return True
else:
False
# ELIMINAR TABLA DE UNA BASE DE DATOS
def deleteTB(self, key, name):
self.dicDB.get(key).pop(name)
# MOSTRAR BASES DE DATOS ALMACENADAS
def print(self):
n = 0
for key in self.dicDB:
print("[" + str(n) + "]","Base:", key, "| Tablas:", self.dicDB.get(key))
n +=1
# MOSTRAR TABLAS ALMACENDAS
def print(self):
n = 0
for key in self.dicDB.keys():
print(key + ":")
for i in self.dicDB.get(key).keys():
print(" "+i + ":")
for j in self.dicDB.get(key).get(i).keys():
print(" "+j+":")
for k in self.dicDB.get(key).get(i).get(j):
print(" "+str(k)) | es | 0.24488 | #---------------------FUNCIONES BASES DE DATOS----------------------# # CREAR BASE DE DATOS # LISTA DE BASES DE DATOS ALMACENADAS # CAMBIAR NOMBRE DE UNA BASE DE DATOS # ELIMINAR BASE DE DATOS # ---------------------FUNCIONES TABLAS----------------------# #--------------------UTILIDADES--------------------# # VALIDA EL NOMBRE CON LAS REGLAS DE IDENTIFICADORES DE SQL # BUSCAR SI EXISTE LA BASE DE DATOS # ---------------------EXTRAS----------------------# # CREAR Y AÑADIR UNA TABLA # BUSCAR SI EXISTE LA TABLA EN UNA BASE DE DATOS # ELIMINAR TABLA DE UNA BASE DE DATOS # MOSTRAR BASES DE DATOS ALMACENADAS # MOSTRAR TABLAS ALMACENDAS | 3.744639 | 4 |
vivid/estimators/kneighbor.py | blacktanktop/vivid | 39 | 6614214 | # coding: utf-8
"""
"""
from optuna.trial import Trial
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
from .base import MetaBlock, TunerBlock
class KNNClassifierBlock(MetaBlock):
model_class = KNeighborsClassifier
initial_params = {
'n_neighbors': 5
}
class KNNRegressorBlock(MetaBlock):
model_class = KNeighborsRegressor
initial_params = {
'n_neighbors': 5
}
class TunedKNNRegressorBlock(TunerBlock):
model_class = KNeighborsRegressor
def generate_model_class_try_params(self, trial: Trial):
params = {
'weights': trial.suggest_categorical('weights', ['distance', 'uniform']),
'p': trial.suggest_uniform('p', 1, 4),
'n_neighbors': int(trial.suggest_int('n_neighbors', 5, 30)),
'algorithm': trial.suggest_categorical('algorithm', ['ball_tree', 'kd_tree'])
}
if 'tree' in params.get('algorithm', None):
params['leaf_size'] = int(trial.suggest_int('leaf_size', 10, 200))
return params
| # coding: utf-8
"""
"""
from optuna.trial import Trial
from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor
from .base import MetaBlock, TunerBlock
class KNNClassifierBlock(MetaBlock):
model_class = KNeighborsClassifier
initial_params = {
'n_neighbors': 5
}
class KNNRegressorBlock(MetaBlock):
model_class = KNeighborsRegressor
initial_params = {
'n_neighbors': 5
}
class TunedKNNRegressorBlock(TunerBlock):
model_class = KNeighborsRegressor
def generate_model_class_try_params(self, trial: Trial):
params = {
'weights': trial.suggest_categorical('weights', ['distance', 'uniform']),
'p': trial.suggest_uniform('p', 1, 4),
'n_neighbors': int(trial.suggest_int('n_neighbors', 5, 30)),
'algorithm': trial.suggest_categorical('algorithm', ['ball_tree', 'kd_tree'])
}
if 'tree' in params.get('algorithm', None):
params['leaf_size'] = int(trial.suggest_int('leaf_size', 10, 200))
return params
| en | 0.833554 | # coding: utf-8 | 2.254062 | 2 |
app/strava/views.py | AartGoossens/sweaty-reports | 1 | 6614215 | import shutil
from datetime import datetime
from pathlib import Path
from fastapi import BackgroundTasks, Depends
from orm import exceptions as orm_exceptions
from starlette.responses import RedirectResponse
from starlette.requests import Request
from stravalib import Client, exc as stravalib_exceptions
from ..auth import create_jwt_token, is_admin
from ..config import APP_URL, STRAVA_CLIENT_ID, STRAVA_CLIENT_SECRET
from ..main import app
from .models import StravaAthlete
from .schemas import Activity, Event
from .tasks import handle_event, new_athlete, process_activity
from .utils import refresh_access_token
@app.get('/strava/login')
def strava_login():
client = Client()
authorize_url = client.authorization_url(
client_id=STRAVA_CLIENT_ID,
redirect_uri=f'{APP_URL}/strava/callback')
return RedirectResponse(authorize_url)
@app.get('/strava/callback')
async def strava_callback(background_task: BackgroundTasks, code: str, scope: str, state: str = None):
client = Client()
token_response = client.exchange_code_for_token(
client_id=STRAVA_CLIENT_ID, client_secret=STRAVA_CLIENT_SECRET,
code=code)
client = Client(access_token=token_response['access_token'])
athlete = client.get_athlete()
try:
strava_athlete = await StravaAthlete.objects.get(id=athlete.id)
except orm_exceptions.NoMatch:
strava_athlete = await StravaAthlete.objects.create(
id=athlete.id,
access_token=token_response['access_token'],
refresh_token=token_response['refresh_token'],
token_expiration_datetime=datetime.utcfromtimestamp(token_response['expires_at']).isoformat())
background_task.add_task(new_athlete, strava_athlete)
response = RedirectResponse('/reports')
jwt_token = create_jwt_token(sub=strava_athlete.id)
response.set_cookie(
key="jwt_token",
value=jwt_token,
httponly=True)
return response
@app.post('/strava/subscription')
def strava_create_subscription(admin: bool = Depends(is_admin)):
# @TODO add secret to the callback url to prevent abuse
client = Client()
response = client.create_subscription(
client_id=STRAVA_CLIENT_ID,
client_secret=STRAVA_CLIENT_SECRET,
callback_url=f'{APP_URL}/strava/webhook',
verify_token='some verify token')
return response
@app.delete('/strava/subscription')
def strava_delete_subscription(admin: bool = Depends(is_admin)):
client = Client()
subscriptions = client.list_subscriptions(
client_id=STRAVA_CLIENT_ID,
client_secret=STRAVA_CLIENT_SECRET)
i = 0
for subscription in subscriptions:
client.delete_subscription(
subscription_id=subscription.id,
client_id=STRAVA_CLIENT_ID,
client_secret=STRAVA_CLIENT_SECRET)
i += 1
return {'message': f'deleted {i} subscriptions'}
@app.get('/strava/webhook')
def strava_webhook_validation(request: Request):
'''
So Strava is fucking around with query param standards in a way that FastAPI cannot handle them natively.
There is no other way then to go back in time and parse the query params ourselves.
Shoot me.
'''
# @TODO add authorization
hub_challenge = request.query_params['hub.challenge']
hub_verify_token = request.query_params.get('hub.verify_token', None)
return {'hub.challenge': hub_challenge}
@app.post('/strava/webhook')
def strava_webhook(event: Event, background_task: BackgroundTasks):
# @TODO add a secret to this path to prevent abuse
background_task.add_task(handle_event, event)
return {'message': 'ok'}
@app.get('/strava/athletes')
async def list_strava_athletes(admin: bool = Depends(is_admin)):
strava_athletes = await StravaAthlete.objects.all()
return strava_athletes
@app.get('/strava/athletes/{strava_athlete_id}')
async def get_strava_athlete(strava_athlete_id: int, admin: bool = Depends(is_admin)):
strava_athlete = await StravaAthlete.objects.get(id=strava_athlete_id)
return strava_athlete
@app.delete('/strava/athletes/{strava_athlete_id}')
async def delete_strava_athletes(strava_athlete_id: int, admin: bool = Depends(is_admin)):
strava_athlete = await StravaAthlete.objects.get(id=strava_athlete_id)
client = Client(strava_athlete.access_token)
try:
client.deauthorize()
except stravalib_exceptions.AccessUnauthorized:
strava_athlete = await refresh_access_token(strava_athlete)
client = Client(strava_athlete.access_token)
client.deauthorize()
await strava_athlete.delete()
return strava_athlete
@app.post('/strava/athletes/{strava_athlete_id}/process_activity', status_code=202)
async def post_process_activity(activity: Activity, strava_athlete_id: int,
background_task: BackgroundTasks, admin: bool = Depends(is_admin)):
strava_athlete = await StravaAthlete.objects.get(id=strava_athlete_id)
background_task.add_task(process_activity, strava_athlete, activity.id)
return {'message': 'ok'}
| import shutil
from datetime import datetime
from pathlib import Path
from fastapi import BackgroundTasks, Depends
from orm import exceptions as orm_exceptions
from starlette.responses import RedirectResponse
from starlette.requests import Request
from stravalib import Client, exc as stravalib_exceptions
from ..auth import create_jwt_token, is_admin
from ..config import APP_URL, STRAVA_CLIENT_ID, STRAVA_CLIENT_SECRET
from ..main import app
from .models import StravaAthlete
from .schemas import Activity, Event
from .tasks import handle_event, new_athlete, process_activity
from .utils import refresh_access_token
@app.get('/strava/login')
def strava_login():
client = Client()
authorize_url = client.authorization_url(
client_id=STRAVA_CLIENT_ID,
redirect_uri=f'{APP_URL}/strava/callback')
return RedirectResponse(authorize_url)
@app.get('/strava/callback')
async def strava_callback(background_task: BackgroundTasks, code: str, scope: str, state: str = None):
client = Client()
token_response = client.exchange_code_for_token(
client_id=STRAVA_CLIENT_ID, client_secret=STRAVA_CLIENT_SECRET,
code=code)
client = Client(access_token=token_response['access_token'])
athlete = client.get_athlete()
try:
strava_athlete = await StravaAthlete.objects.get(id=athlete.id)
except orm_exceptions.NoMatch:
strava_athlete = await StravaAthlete.objects.create(
id=athlete.id,
access_token=token_response['access_token'],
refresh_token=token_response['refresh_token'],
token_expiration_datetime=datetime.utcfromtimestamp(token_response['expires_at']).isoformat())
background_task.add_task(new_athlete, strava_athlete)
response = RedirectResponse('/reports')
jwt_token = create_jwt_token(sub=strava_athlete.id)
response.set_cookie(
key="jwt_token",
value=jwt_token,
httponly=True)
return response
@app.post('/strava/subscription')
def strava_create_subscription(admin: bool = Depends(is_admin)):
# @TODO add secret to the callback url to prevent abuse
client = Client()
response = client.create_subscription(
client_id=STRAVA_CLIENT_ID,
client_secret=STRAVA_CLIENT_SECRET,
callback_url=f'{APP_URL}/strava/webhook',
verify_token='some verify token')
return response
@app.delete('/strava/subscription')
def strava_delete_subscription(admin: bool = Depends(is_admin)):
client = Client()
subscriptions = client.list_subscriptions(
client_id=STRAVA_CLIENT_ID,
client_secret=STRAVA_CLIENT_SECRET)
i = 0
for subscription in subscriptions:
client.delete_subscription(
subscription_id=subscription.id,
client_id=STRAVA_CLIENT_ID,
client_secret=STRAVA_CLIENT_SECRET)
i += 1
return {'message': f'deleted {i} subscriptions'}
@app.get('/strava/webhook')
def strava_webhook_validation(request: Request):
'''
So Strava is fucking around with query param standards in a way that FastAPI cannot handle them natively.
There is no other way then to go back in time and parse the query params ourselves.
Shoot me.
'''
# @TODO add authorization
hub_challenge = request.query_params['hub.challenge']
hub_verify_token = request.query_params.get('hub.verify_token', None)
return {'hub.challenge': hub_challenge}
@app.post('/strava/webhook')
def strava_webhook(event: Event, background_task: BackgroundTasks):
# @TODO add a secret to this path to prevent abuse
background_task.add_task(handle_event, event)
return {'message': 'ok'}
@app.get('/strava/athletes')
async def list_strava_athletes(admin: bool = Depends(is_admin)):
strava_athletes = await StravaAthlete.objects.all()
return strava_athletes
@app.get('/strava/athletes/{strava_athlete_id}')
async def get_strava_athlete(strava_athlete_id: int, admin: bool = Depends(is_admin)):
strava_athlete = await StravaAthlete.objects.get(id=strava_athlete_id)
return strava_athlete
@app.delete('/strava/athletes/{strava_athlete_id}')
async def delete_strava_athletes(strava_athlete_id: int, admin: bool = Depends(is_admin)):
strava_athlete = await StravaAthlete.objects.get(id=strava_athlete_id)
client = Client(strava_athlete.access_token)
try:
client.deauthorize()
except stravalib_exceptions.AccessUnauthorized:
strava_athlete = await refresh_access_token(strava_athlete)
client = Client(strava_athlete.access_token)
client.deauthorize()
await strava_athlete.delete()
return strava_athlete
@app.post('/strava/athletes/{strava_athlete_id}/process_activity', status_code=202)
async def post_process_activity(activity: Activity, strava_athlete_id: int,
background_task: BackgroundTasks, admin: bool = Depends(is_admin)):
strava_athlete = await StravaAthlete.objects.get(id=strava_athlete_id)
background_task.add_task(process_activity, strava_athlete, activity.id)
return {'message': 'ok'}
| en | 0.860391 | # @TODO add secret to the callback url to prevent abuse So Strava is fucking around with query param standards in a way that FastAPI cannot handle them natively. There is no other way then to go back in time and parse the query params ourselves. Shoot me. # @TODO add authorization # @TODO add a secret to this path to prevent abuse | 2.055148 | 2 |
tests/models/programdb/program_info/program_info_unit_test.py | weibullguy/ramstk | 4 | 6614216 | # pylint: skip-file
# type: ignore
# -*- coding: utf-8 -*-
#
# tests.controllers.program_info.program_info_unit_test.py is part of The RAMSTK
# Project
#
# All rights reserved.
# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com
"""Test class for testing Program Information module algorithms and models."""
# Standard Library Imports
from datetime import date
# Third Party Imports
import pytest
from pubsub import pub
from treelib import Tree
# RAMSTK Package Imports
from ramstk.models.dbrecords import RAMSTKProgramInfoRecord
from ramstk.models.dbtables import RAMSTKProgramInfoTable
from tests import (
MockDAO,
UnitTestDeleteMethods,
UnitTestGetterSetterMethods,
UnitTestInsertMethods,
UnitTestSelectMethods,
)
@pytest.mark.usefixtures("test_record_model", "unit_test_table_model")
class TestCreateProgramInfoModels:
"""Class for unit testing Program Information model __init__() methods.
Because each table model contains unique attributes, these methods must be
local to the module being tested.
"""
__test__ = True
@pytest.mark.unit
def test_record_model_create(self, test_record_model):
"""Should return a Program Information record model instance."""
assert isinstance(test_record_model, RAMSTKProgramInfoRecord)
# Verify class attributes are properly initialized.
assert test_record_model.__tablename__ == "ramstk_program_info"
assert test_record_model.revision_id == 1
assert test_record_model.function_active == 1
assert test_record_model.requirement_active == 1
assert test_record_model.hardware_active == 1
assert test_record_model.software_active == 0
assert test_record_model.rcm_active == 0
assert test_record_model.testing_active == 0
assert test_record_model.incident_active == 0
assert test_record_model.survival_active == 0
assert test_record_model.vandv_active == 1
assert test_record_model.hazard_active == 1
assert test_record_model.stakeholder_active == 1
assert test_record_model.allocation_active == 1
assert test_record_model.similar_item_active == 1
assert test_record_model.fmea_active == 1
assert test_record_model.pof_active == 1
assert test_record_model.rbd_active == 0
assert test_record_model.fta_active == 0
assert test_record_model.created_on == date.today()
assert test_record_model.created_by == ""
assert test_record_model.last_saved == date.today()
assert test_record_model.last_saved_by == ""
@pytest.mark.unit
def test_data_manager_create(self, unit_test_table_model):
"""Return a Program Information table model instance."""
assert isinstance(unit_test_table_model, RAMSTKProgramInfoTable)
assert isinstance(unit_test_table_model.tree, Tree)
assert isinstance(unit_test_table_model.dao, MockDAO)
assert unit_test_table_model._tag == "preference"
assert unit_test_table_model._root == 0
assert pub.isSubscribed(
unit_test_table_model.do_select_all, "request_program_preferences"
)
assert pub.isSubscribed(
unit_test_table_model.do_update, "request_update_preference"
)
assert pub.isSubscribed(
unit_test_table_model.do_get_attributes, "request_get_preference_attributes"
)
assert pub.isSubscribed(
unit_test_table_model.do_get_tree, "request_get_preference_tree"
)
assert pub.isSubscribed(
unit_test_table_model.do_set_attributes, "request_set_preference_attributes"
)
@pytest.mark.usefixtures("test_attributes", "unit_test_table_model")
class TestSelectProgramInfo(UnitTestSelectMethods):
"""Class for unit testing Program Info table do_select() and do_select_all()."""
__test__ = True
_record = RAMSTKProgramInfoRecord
_tag = "preference"
@pytest.mark.usefixtures("test_attributes", "test_record_model")
class TestGetterSetterProgramInfo(UnitTestGetterSetterMethods):
"""Class for unit testing Program Information table methods that get or set."""
__test__ = True
_id_columns = [
"revision_id",
]
_test_attr = "created_on"
_test_default_value = date.today()
@pytest.mark.unit
def test_get_record_model_attributes(self, test_record_model):
"""Should return a dict of attribute key:value pairs.
This method must be local because the attributes are different for each
database record model.
"""
_attributes = test_record_model.get_attributes()
assert isinstance(_attributes, dict)
assert _attributes["function_active"] == 1
assert _attributes["requirement_active"] == 1
assert _attributes["hardware_active"] == 1
assert _attributes["software_active"] == 0
assert _attributes["rcm_active"] == 0
assert _attributes["testing_active"] == 0
assert _attributes["incident_active"] == 0
assert _attributes["survival_active"] == 0
assert _attributes["vandv_active"] == 1
assert _attributes["hazard_active"] == 1
assert _attributes["stakeholder_active"] == 1
assert _attributes["allocation_active"] == 1
assert _attributes["similar_item_active"] == 1
assert _attributes["fmea_active"] == 1
assert _attributes["pof_active"] == 1
assert _attributes["rbd_active"] == 0
assert _attributes["fta_active"] == 0
assert _attributes["created_on"] == date.today()
assert _attributes["created_by"] == ""
assert _attributes["last_saved"] == date.today()
assert _attributes["last_saved_by"] == ""
| # pylint: skip-file
# type: ignore
# -*- coding: utf-8 -*-
#
# tests.controllers.program_info.program_info_unit_test.py is part of The RAMSTK
# Project
#
# All rights reserved.
# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com
"""Test class for testing Program Information module algorithms and models."""
# Standard Library Imports
from datetime import date
# Third Party Imports
import pytest
from pubsub import pub
from treelib import Tree
# RAMSTK Package Imports
from ramstk.models.dbrecords import RAMSTKProgramInfoRecord
from ramstk.models.dbtables import RAMSTKProgramInfoTable
from tests import (
MockDAO,
UnitTestDeleteMethods,
UnitTestGetterSetterMethods,
UnitTestInsertMethods,
UnitTestSelectMethods,
)
@pytest.mark.usefixtures("test_record_model", "unit_test_table_model")
class TestCreateProgramInfoModels:
"""Class for unit testing Program Information model __init__() methods.
Because each table model contains unique attributes, these methods must be
local to the module being tested.
"""
__test__ = True
@pytest.mark.unit
def test_record_model_create(self, test_record_model):
"""Should return a Program Information record model instance."""
assert isinstance(test_record_model, RAMSTKProgramInfoRecord)
# Verify class attributes are properly initialized.
assert test_record_model.__tablename__ == "ramstk_program_info"
assert test_record_model.revision_id == 1
assert test_record_model.function_active == 1
assert test_record_model.requirement_active == 1
assert test_record_model.hardware_active == 1
assert test_record_model.software_active == 0
assert test_record_model.rcm_active == 0
assert test_record_model.testing_active == 0
assert test_record_model.incident_active == 0
assert test_record_model.survival_active == 0
assert test_record_model.vandv_active == 1
assert test_record_model.hazard_active == 1
assert test_record_model.stakeholder_active == 1
assert test_record_model.allocation_active == 1
assert test_record_model.similar_item_active == 1
assert test_record_model.fmea_active == 1
assert test_record_model.pof_active == 1
assert test_record_model.rbd_active == 0
assert test_record_model.fta_active == 0
assert test_record_model.created_on == date.today()
assert test_record_model.created_by == ""
assert test_record_model.last_saved == date.today()
assert test_record_model.last_saved_by == ""
@pytest.mark.unit
def test_data_manager_create(self, unit_test_table_model):
"""Return a Program Information table model instance."""
assert isinstance(unit_test_table_model, RAMSTKProgramInfoTable)
assert isinstance(unit_test_table_model.tree, Tree)
assert isinstance(unit_test_table_model.dao, MockDAO)
assert unit_test_table_model._tag == "preference"
assert unit_test_table_model._root == 0
assert pub.isSubscribed(
unit_test_table_model.do_select_all, "request_program_preferences"
)
assert pub.isSubscribed(
unit_test_table_model.do_update, "request_update_preference"
)
assert pub.isSubscribed(
unit_test_table_model.do_get_attributes, "request_get_preference_attributes"
)
assert pub.isSubscribed(
unit_test_table_model.do_get_tree, "request_get_preference_tree"
)
assert pub.isSubscribed(
unit_test_table_model.do_set_attributes, "request_set_preference_attributes"
)
@pytest.mark.usefixtures("test_attributes", "unit_test_table_model")
class TestSelectProgramInfo(UnitTestSelectMethods):
"""Class for unit testing Program Info table do_select() and do_select_all()."""
__test__ = True
_record = RAMSTKProgramInfoRecord
_tag = "preference"
@pytest.mark.usefixtures("test_attributes", "test_record_model")
class TestGetterSetterProgramInfo(UnitTestGetterSetterMethods):
"""Class for unit testing Program Information table methods that get or set."""
__test__ = True
_id_columns = [
"revision_id",
]
_test_attr = "created_on"
_test_default_value = date.today()
@pytest.mark.unit
def test_get_record_model_attributes(self, test_record_model):
"""Should return a dict of attribute key:value pairs.
This method must be local because the attributes are different for each
database record model.
"""
_attributes = test_record_model.get_attributes()
assert isinstance(_attributes, dict)
assert _attributes["function_active"] == 1
assert _attributes["requirement_active"] == 1
assert _attributes["hardware_active"] == 1
assert _attributes["software_active"] == 0
assert _attributes["rcm_active"] == 0
assert _attributes["testing_active"] == 0
assert _attributes["incident_active"] == 0
assert _attributes["survival_active"] == 0
assert _attributes["vandv_active"] == 1
assert _attributes["hazard_active"] == 1
assert _attributes["stakeholder_active"] == 1
assert _attributes["allocation_active"] == 1
assert _attributes["similar_item_active"] == 1
assert _attributes["fmea_active"] == 1
assert _attributes["pof_active"] == 1
assert _attributes["rbd_active"] == 0
assert _attributes["fta_active"] == 0
assert _attributes["created_on"] == date.today()
assert _attributes["created_by"] == ""
assert _attributes["last_saved"] == date.today()
assert _attributes["last_saved_by"] == ""
| en | 0.692257 | # pylint: skip-file # type: ignore # -*- coding: utf-8 -*- # # tests.controllers.program_info.program_info_unit_test.py is part of The RAMSTK # Project # # All rights reserved. # Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com Test class for testing Program Information module algorithms and models. # Standard Library Imports # Third Party Imports # RAMSTK Package Imports Class for unit testing Program Information model __init__() methods. Because each table model contains unique attributes, these methods must be local to the module being tested. Should return a Program Information record model instance. # Verify class attributes are properly initialized. Return a Program Information table model instance. Class for unit testing Program Info table do_select() and do_select_all(). Class for unit testing Program Information table methods that get or set. Should return a dict of attribute key:value pairs. This method must be local because the attributes are different for each database record model. | 2.321019 | 2 |
nicos_mlz/dns/setups/chopper.py | jkrueger1/nicos | 0 | 6614217 | <filename>nicos_mlz/dns/setups/chopper.py
# -*- coding: utf-8 -*-
description = 'New DNS chopper'
group = 'optional'
tango_base = 'tango://phys.dns.frm2:10000/dns/chopper/_'
devices = dict(
chopper_rpm = device('nicos.devices.entangle.AnalogOutput',
description = 'Chopper speed',
tangodevice = tango_base + 'drehzahl',
fmtstr = '%.1f',
),
chopper_current = device('nicos.devices.entangle.AnalogInput',
description = 'Motor current',
tangodevice = tango_base + 'motorstrom',
fmtstr = '%.2f',
unit = 'A',
),
chopper_temp = device('nicos.devices.entangle.AnalogInput',
description = 'Motor temperature',
tangodevice = tango_base + 'motortemperatur',
fmtstr = '%.1f',
warnlimits = (0, 60),
),
chopper_vacuum = device('nicos.devices.entangle.AnalogInput',
description = 'Pressure in chopper housing',
tangodevice = tango_base + 'vakuumdruck',
fmtstr = '%.2g',
),
chopper_imbalance = device('nicos.devices.entangle.AnalogInput',
description = 'Chopper vibration',
tangodevice = tango_base + 'unwucht',
fmtstr = '%.4f',
warnlimits = (-1, 0.0009),
),
chopper_bearing1 = device('nicos.devices.entangle.AnalogInput',
description = 'Bearing unit condition of bearing 1',
tangodevice = tango_base + 'lager1kennzahl',
fmtstr = '%.2f',
warnlimits = (-1, 4.9),
),
chopper_bearing2 = device('nicos.devices.entangle.AnalogInput',
description = 'Bearing unit condition of bearing 2',
tangodevice = tango_base + 'lager2kennzahl',
fmtstr = '%.2f',
warnlimits = (-1, 4.9),
),
)
| <filename>nicos_mlz/dns/setups/chopper.py
# -*- coding: utf-8 -*-
description = 'New DNS chopper'
group = 'optional'
tango_base = 'tango://phys.dns.frm2:10000/dns/chopper/_'
devices = dict(
chopper_rpm = device('nicos.devices.entangle.AnalogOutput',
description = 'Chopper speed',
tangodevice = tango_base + 'drehzahl',
fmtstr = '%.1f',
),
chopper_current = device('nicos.devices.entangle.AnalogInput',
description = 'Motor current',
tangodevice = tango_base + 'motorstrom',
fmtstr = '%.2f',
unit = 'A',
),
chopper_temp = device('nicos.devices.entangle.AnalogInput',
description = 'Motor temperature',
tangodevice = tango_base + 'motortemperatur',
fmtstr = '%.1f',
warnlimits = (0, 60),
),
chopper_vacuum = device('nicos.devices.entangle.AnalogInput',
description = 'Pressure in chopper housing',
tangodevice = tango_base + 'vakuumdruck',
fmtstr = '%.2g',
),
chopper_imbalance = device('nicos.devices.entangle.AnalogInput',
description = 'Chopper vibration',
tangodevice = tango_base + 'unwucht',
fmtstr = '%.4f',
warnlimits = (-1, 0.0009),
),
chopper_bearing1 = device('nicos.devices.entangle.AnalogInput',
description = 'Bearing unit condition of bearing 1',
tangodevice = tango_base + 'lager1kennzahl',
fmtstr = '%.2f',
warnlimits = (-1, 4.9),
),
chopper_bearing2 = device('nicos.devices.entangle.AnalogInput',
description = 'Bearing unit condition of bearing 2',
tangodevice = tango_base + 'lager2kennzahl',
fmtstr = '%.2f',
warnlimits = (-1, 4.9),
),
)
| en | 0.769321 | # -*- coding: utf-8 -*- | 1.737491 | 2 |
button.py | sugar-activities/4552-activity | 0 | 6614218 | import gobject
import gtk
from gettext import gettext as _
from sugar.graphics.palette import Palette
from sugar.graphics.tray import TrayButton
import constants
import utils
class RecdButton(TrayButton):
__gsignals__ = {
'remove-requested': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
'copy-clipboard-requested': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
}
def __init__(self, recd):
super(RecdButton, self).__init__()
self._recd = recd
self.set_icon_widget(self.get_image())
self._copy_menu_item_handler = None
palette = Palette(recd.title)
self.set_palette(palette)
self._rem_menu_item = gtk.MenuItem(_('Remove'))
self._rem_menu_item_handler = self._rem_menu_item.connect('activate', self._remove_clicked)
palette.menu.append(self._rem_menu_item)
self._rem_menu_item.show()
self._add_copy_menu_item()
def _add_copy_menu_item( self ):
if self._recd.buddy and not self._recd.downloadedFromBuddy:
return
self._copy_menu_item = gtk.MenuItem(_('Copy to clipboard'))
self._copy_menu_item_handler = self._copy_menu_item.connect('activate', self._copy_clipboard_clicked)
self.get_palette().menu.append(self._copy_menu_item)
self._copy_menu_item.show()
def get_recd(self):
return self._recd
def get_image(self):
img = gtk.Image()
ipb = self._recd.getThumbPixbuf()
if self._recd.type == constants.TYPE_PHOTO:
path = 'object-photo.svg'
elif self._recd.type == constants.TYPE_VIDEO:
path = 'object-video.svg'
elif self._recd.type == constants.TYPE_AUDIO:
path = 'object-audio.svg'
pixbuf = utils.load_colored_svg(path, self._recd.colorStroke, self._recd.colorFill)
if ipb:
ipb.composite(pixbuf, 8, 8, ipb.get_width(), ipb.get_height(), 8, 8, 1, 1, gtk.gdk.INTERP_BILINEAR, 255)
img.set_from_pixbuf(pixbuf)
img.show()
return img
def cleanup(self):
self._rem_menu_item.disconnect(self._rem_menu_item_handler)
if self._copy_menu_item_handler != None:
self._copy_menu_item.disconnect(self._copy_menu_item_handler)
def _remove_clicked(self, widget):
self.emit('remove-requested')
def _copy_clipboard_clicked(self, widget):
self.emit('copy-clipboard-requested')
| import gobject
import gtk
from gettext import gettext as _
from sugar.graphics.palette import Palette
from sugar.graphics.tray import TrayButton
import constants
import utils
class RecdButton(TrayButton):
__gsignals__ = {
'remove-requested': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
'copy-clipboard-requested': (gobject.SIGNAL_RUN_LAST, gobject.TYPE_NONE, ()),
}
def __init__(self, recd):
super(RecdButton, self).__init__()
self._recd = recd
self.set_icon_widget(self.get_image())
self._copy_menu_item_handler = None
palette = Palette(recd.title)
self.set_palette(palette)
self._rem_menu_item = gtk.MenuItem(_('Remove'))
self._rem_menu_item_handler = self._rem_menu_item.connect('activate', self._remove_clicked)
palette.menu.append(self._rem_menu_item)
self._rem_menu_item.show()
self._add_copy_menu_item()
def _add_copy_menu_item( self ):
if self._recd.buddy and not self._recd.downloadedFromBuddy:
return
self._copy_menu_item = gtk.MenuItem(_('Copy to clipboard'))
self._copy_menu_item_handler = self._copy_menu_item.connect('activate', self._copy_clipboard_clicked)
self.get_palette().menu.append(self._copy_menu_item)
self._copy_menu_item.show()
def get_recd(self):
return self._recd
def get_image(self):
img = gtk.Image()
ipb = self._recd.getThumbPixbuf()
if self._recd.type == constants.TYPE_PHOTO:
path = 'object-photo.svg'
elif self._recd.type == constants.TYPE_VIDEO:
path = 'object-video.svg'
elif self._recd.type == constants.TYPE_AUDIO:
path = 'object-audio.svg'
pixbuf = utils.load_colored_svg(path, self._recd.colorStroke, self._recd.colorFill)
if ipb:
ipb.composite(pixbuf, 8, 8, ipb.get_width(), ipb.get_height(), 8, 8, 1, 1, gtk.gdk.INTERP_BILINEAR, 255)
img.set_from_pixbuf(pixbuf)
img.show()
return img
def cleanup(self):
self._rem_menu_item.disconnect(self._rem_menu_item_handler)
if self._copy_menu_item_handler != None:
self._copy_menu_item.disconnect(self._copy_menu_item_handler)
def _remove_clicked(self, widget):
self.emit('remove-requested')
def _copy_clipboard_clicked(self, widget):
self.emit('copy-clipboard-requested')
| none | 1 | 1.996024 | 2 | |
src/licma/query/jquery.py | stg-tud/licma | 5 | 6614219 | from abc import ABC
from licma.query.query import Query
from licma.query.qtypes import get_type
from licma.query.qtypes import Types
from licma.query.value_parameter import ValueParameter
from licma.progress_log.log import logger
class JQuery(Query, ABC):
def method_of_instantiation(self, syntax_tree, instantiation, parameter_name):
method_names = []
query = instantiation + "[@token='" + parameter_name + "']/ancestor::MethodDeclaration/name/SimpleName/@token"
methods = syntax_tree.tree.filter(query)
for method in methods:
method_name = method.token
#method_names.append(method.get()["@token"])
query_class_name = "/CompilationUnit/types//MethodDeclaration/name/SimpleName[@token='" + method_name + "']" \
"/ancestor::name/ancestor::MethodDeclaration/ancestor::TypeDeclaration/name/SimpleName/@token"
class_name = list(syntax_tree.tree.filter(query_class_name))[0].token
method_names.append((class_name, method_name))
return method_names
def method_of_invocation(self):
pass
def caller_arguments(self, syntax_tree, caller, called, parameter_index):
query = "/CompilationUnit/types//MethodDeclaration/name/SimpleName[@token='" + caller + "']" \
"/parent::name/parent::MethodDeclaration//MethodInvocation/name" \
"/SimpleName[@token='" + called + "']/parent::name/parent::MethodInvocation/arguments/*["+ str(parameter_index) + "]//@token"
arguments = set()
for argument in syntax_tree.tree.filter(query):
arguments.add(ValueParameter(get_type(argument.internal_type),
argument.token,
syntax_tree.file,
argument.start_position.line))
return arguments
def caller_of(self, syntax_tree, method):
query = "/CompilationUnit/types//MethodInvocation//*[@role='Call' and @role='Callee' " \
"and @token='" + method + "']/ancestor::MethodDeclaration/name/SimpleName/@token"
callers = set()
for caller in syntax_tree.tree.filter(query):
callers.add(caller.get()["@token"])
return callers
def method_parameter(self, syntax_tree, method):
query = "/CompilationUnit/types//SimpleName[@token='" + method + "']" \
"/parent::name/parent::MethodDeclaration/parameters//name/SimpleName" \
"[@role='Identifier' and @role='Argument']/@token"
return list(syntax_tree.tree.filter(query))
def method_parameter_index(self, syntax_tree, method_name, parameter_name):
n = 1
for parameter in self.method_parameter(syntax_tree, method_name):
if parameter_name == parameter.token:
return n
else:
n = n + 1
return -1
def substitute_p(self, syntax_tree, method, parameter_e):
value_parameter = set()
parameter_index = self.method_parameter_index(syntax_tree, method, parameter_e)
if parameter_index == -1:
return value_parameter
for parameter_a in self.method_parameter(syntax_tree, method):
if parameter_e == parameter_a.get()["@token"]:
callers = self.caller_of(syntax_tree, method)
if len(callers) == 0:
value_parameter.add(ValueParameter(Types.Unknown, "UNKNOWN", syntax_tree.file, parameter_a.start_position.line))
else:
for caller in callers:
arguments = self.caller_arguments(syntax_tree, caller, method, parameter_index)
for argument in arguments:
if argument.type == Types.StringLiteral or argument.type == Types.NumberLiteral:
value_parameter.add(argument)
elif argument.type == Types.SimpleName:
value_parameter = value_parameter.union(self.substitute_v(syntax_tree, caller, argument.value))
elif argument.type == Types.Method:
logger.debug("not implemented yet!")
return value_parameter
def substitute_v(self, syntax_tree, method, variable):
"""
substitute variable
:return:
"""
parameter_values = set()
# string value for variable can be found
query = "/CompilationUnit/types//SimpleName[@token='" + method + "']" \
"/ancestor::MethodDeclaration//VariableDeclarationFragment/name/SimpleName[@token='" + variable + "']" \
"/parent::name/parent::VariableDeclarationFragment/initializer/StringLiteral/@token"
parameter_values = parameter_values.union(self.value_assignment(syntax_tree, query))
#if len(parameter_values) > 0: return parameter_values
# int value for variable can be found
query = "/CompilationUnit/types//SimpleName[@token='" + method + "']" \
"/ancestor::MethodDeclaration//VariableDeclarationFragment/name/SimpleName[@token='" + variable + "']" \
"/parent::name/parent::VariableDeclarationFragment/initializer/NumberLiteral/@token"
parameter_values = parameter_values.union(self.int_assignment(syntax_tree, query))
#if len(parameter_values) > 0: return parameter_values
# value assignment for byte array with = {'a', 'b', 'c', ... }
query = "/CompilationUnit/types//SimpleName[@token='" + method + "']" \
"/ancestor::MethodDeclaration//VariableDeclarationFragment/name/SimpleName[@token='" + variable + "']" \
"/parent::name/parent::VariableDeclarationFragment/initializer/ArrayInitializer/expressions/" \
"CharacterLiteral"
parameter_values = parameter_values.union(self.array_assignment(syntax_tree, query))
#if len(parameter_values) > 0: return parameter_values
# value assignment for byte array with = {(byte) 0x00, (byte) 0x01, (byte) 0x02, ... }
query = "/CompilationUnit/types//SimpleName[@token='" + method + "']" \
"/ancestor::MethodDeclaration//VariableDeclarationFragment/name/SimpleName[@token='" + variable + "']" \
"/parent::name/parent::VariableDeclarationFragment/initializer/ArrayInitializer/" \
"expressions//NumberLiteral"
parameter_values = parameter_values.union(self.array_assignment(syntax_tree, query, ", "))
#if len(parameter_values) > 0: return parameter_values
# value assignment for byte array with {getBytes()}
query = "/CompilationUnit/types//SimpleName[@token='" + method + "']" \
"/ancestor::MethodDeclaration//VariableDeclarationFragment/name/SimpleName[@token='" + variable + "']" \
"/parent::name/parent::VariableDeclarationFragment/initializer//expression/StringLiteral/@token"
parameter_values = parameter_values.union(self.value_assignment(syntax_tree, query))
#if len(parameter_values) > 0: return parameter_values
# number value for variable can be found
query = "/CompilationUnit/types//SimpleName[@token='" + method + "']" \
"/ancestor::MethodDeclaration//VariableDeclarationFragment/name/SimpleName[@token='" + variable + "']" \
"/parent::name/parent::VariableDeclarationFragment/initializer/NumberLiteral/@token"
parameter_values = parameter_values.union(self.value_assignment(syntax_tree, query))
#if len(parameter_values) > 0: return parameter_values
# check for nested variables
query = "/CompilationUnit/types//bodyDeclarations/MethodDeclaration/name/" \
"SimpleName[@token='" + method + "']/ancestor::MethodDeclaration/body//statements/" \
"VariableDeclarationStatement/fragments//name/SimpleName[@token='" + variable + "']" \
"/ancestor::VariableDeclarationStatement/fragments//initializer/SimpleName"
for nested_variable in [hit.token for hit in syntax_tree.tree.filter(query)]:
parameter_values = parameter_values.union(self.substitute_v(syntax_tree, method, nested_variable))
# check for method parameters
parameter_values = parameter_values.union(self.substitute_p(syntax_tree, method, variable))
if len(parameter_values) > 0: return parameter_values
# check for field value
parameter_values = parameter_values.union((self.substitute_f(syntax_tree, variable)))
return parameter_values
def substitute_f(self, syntax_tree, name):
query_f = "/CompilationUnit/types//bodyDeclarations//FieldDeclaration/fragments//name/SimpleName[@token='" + name + "']"
query_f_string = query_f + "/ancestor::FieldDeclaration/type//name/" \
"SimpleName[@token='String']" \
"/ancestor::FieldDeclaration/fragments//initializer/StringLiteral"
query_f_int = query_f + "/ancestor::FieldDeclaration/type/PrimitiveType[@token='int']" \
"/ancestor::FieldDeclaration/fragments//initializer/NumberLiteral"
query_f_char_array1 = query_f + "/ancestor::FieldDeclaration/type/ArrayType/elementType/" \
"PrimitiveType[@token='byte']/ancestor::FieldDeclaration/" \
"fragments//initializer/ArrayInitializer/expressions/CharacterLiteral"
query_f_char_array2 = query_f + "/ancestor::FieldDeclaration/type/ArrayType/elementType/" \
"PrimitiveType[@token='byte']/ancestor::FieldDeclaration/" \
"fragments//initializer//StringLiteral"
query_f_char_array3 = query_f + "/ancestor::FieldDeclaration/type/ArrayType/elementType/" \
"PrimitiveType[@token='byte']/ancestor::FieldDeclaration/" \
"fragments//initializer//NumberLiteral"
# check if there is any corresponding field
try:
next(syntax_tree.tree.filter(query_f))
except StopIteration:
return set()
# determine field value
# string assignment
value = self.iterator_get_next(syntax_tree, query_f_string)
if not value is None:
return set([ValueParameter(Types.StringLiteral, value.token, syntax_tree.file, value.start_position.line)])
# int assignment
value = self.iterator_get_next(syntax_tree, query_f_int)
if not value is None:
return set([ValueParameter(Types.NumberLiteral, value.token, syntax_tree.file, value.start_position.line)])
# byte array initialization = {'a', 'b', 'c', ... }
array_values = self.array_assignment(syntax_tree, query_f_char_array1)
if len(array_values) > 0:
return array_values
# byte array initialization = "a string".getBytes()
value = self.iterator_get_next(syntax_tree, query_f_char_array2)
if not value is None:
return set([ValueParameter(Types.StringLiteral, value.token, syntax_tree.file, value.start_position.line)])
# byte array initialization = {(byte) 0x00, (byte) 0x01, (byte) 0x02, ... }
array_values = self.array_assignment(syntax_tree, query_f_char_array3, ", ")
if len(array_values) > 0:
return array_values
return set()
def substitute_m(self):
"""substitute method"""
def cm(self, syntax_tree, class_type, method_name, parameter_index):
"""
call method
:return:
"""
value_parameters = set()
base_query = "/CompilationUnit/types//VariableDeclarationStatement/type//name/SimpleName[@token='" + class_type + "']/ancestor::VariableDeclarationStatement/fragments/VariableDeclarationFragment/name/SimpleName/@token"
objects = syntax_tree.tree.filter(base_query)
for object in objects:
value_parameters = value_parameters.union(self.csm(syntax_tree, object.token, method_name, parameter_index))
return value_parameters
def csm(self, syntax_tree, class_type, method_name, parameter_index):
"""
call static method
:return:
"""
value_parameters = set()
base_query = "/CompilationUnit/types//MethodInvocation//" \
"*[@role='Call' and @role='Callee' and @token='" + method_name + "']/" \
"ancestor::MethodInvocation/expression/SimpleName[@token='" + class_type + "']/" \
"ancestor::MethodInvocation/arguments/*[" + str(parameter_index) + "]"
# StringLiteral
#query_s = base_query + "//StringLiteral/@token"
#for string in syntax_tree.filter(query_s):
# value_parameters.add(ValueParameter(Types.StringLiteral, string.token, "File", string.start_position.line, class_type + "." + method_name + "(...) -> hard coded string"))
return self.query_parameter_value(syntax_tree, base_query, class_type + "." + method_name)
#return value_parameters
def ci(self, syntax_tree, type_name, parameter_index, operator=None, value=None):
"""
create instance
:param syntax_tree:
:param type_name:
:param parameter_index:
:param operator:
:param value:
:return:
"""
value_parameters = set()
base_query = "/CompilationUnit/types//ClassInstanceCreation/type//name" \
"/SimpleName[@token='" + type_name + "']/ancestor::ClassInstanceCreation/arguments/*["\
+ str(parameter_index) + "]"
return self.query_parameter_value(syntax_tree, base_query, type_name)
def query_parameter_value(self, syntax_tree, base_query, parameter_receiver):
value_parameters = set()
# new Byte[] { '.', '.', ... }
query_array_char = base_query + "//ArrayInitializer/expressions/CharacterLiteral"
for value_parameter in self.array_assignment(syntax_tree, query_array_char):
value_parameter.init_misuse_position(parameter_receiver + " -> hard coded array", value_parameter.line)
value_parameters.add(value_parameter)
# new Byte[] {(byte) 0x01, (byte) 0x02, ... )
query_array_int = base_query + "//ArrayInitializer/expressions//NumberLiteral"
int_arrays = self.array_assignment(syntax_tree, query_array_int, ",")
for value_parameter in int_arrays:
value_parameter.init_misuse_position(parameter_receiver + " -> hard coded array", value_parameter.line)
value_parameters.add(value_parameter)
if int_arrays is None or len(int_arrays) < 1:
# NumberLiteral
query_n = base_query + "//NumberLiteral/@token"
for string in syntax_tree.tree.filter(query_n):
value_parameters.add(
ValueParameter(Types.NumberLiteral, string.token, syntax_tree.file, string.start_position.line,
parameter_receiver + " -> hard coded int", string.start_position.line))
# StringLiteral
query_s = base_query + "//StringLiteral/@token"
for string in syntax_tree.tree.filter(query_s):
value_parameters.add(ValueParameter(Types.StringLiteral, string.token, syntax_tree.file, string.start_position.line, parameter_receiver + " -> hard coded string", string.start_position.line))
# parameter is variable
query_v = base_query + "//SimpleName[@role='Identifier' and @role='Receiver' or @role='Argument']"
for variable in syntax_tree.tree.filter(query_v + "/@token"):
variable_name = variable.token
methods = self.method_of_instantiation(syntax_tree, query_v, variable_name)
for method in methods:
value_parameters_substituted = self.substitute_v(syntax_tree, method[1], variable_name)
# determine line number of analysed method call
query_line = query_v + "[ancestor::MethodDeclaration/name/SimpleName[@token = '" + method[1] + "']]"
misuse_line = next(syntax_tree.tree.filter(query_line)).start_position.line
for value_parameter in value_parameters_substituted:
value_parameter.init_misuse_position(method[0] + "." + method[1] + "." + parameter_receiver, misuse_line)
value_parameters = value_parameters.union(value_parameters_substituted)
return value_parameters
# TODO: possible improvements
# parameter is variable with method call e.g. string.getBytes()
# query_vm = base_query + "//MethodInvocation/expression/SimpleName/@token"
# parameter is method return value
# query_m = base_query + "//MethodInvocation[@expression]/name/SimpleName/@token"
# ClassInstanceCreation
# query_c = "//ClassInstanceCreateion"
| from abc import ABC
from licma.query.query import Query
from licma.query.qtypes import get_type
from licma.query.qtypes import Types
from licma.query.value_parameter import ValueParameter
from licma.progress_log.log import logger
class JQuery(Query, ABC):
def method_of_instantiation(self, syntax_tree, instantiation, parameter_name):
method_names = []
query = instantiation + "[@token='" + parameter_name + "']/ancestor::MethodDeclaration/name/SimpleName/@token"
methods = syntax_tree.tree.filter(query)
for method in methods:
method_name = method.token
#method_names.append(method.get()["@token"])
query_class_name = "/CompilationUnit/types//MethodDeclaration/name/SimpleName[@token='" + method_name + "']" \
"/ancestor::name/ancestor::MethodDeclaration/ancestor::TypeDeclaration/name/SimpleName/@token"
class_name = list(syntax_tree.tree.filter(query_class_name))[0].token
method_names.append((class_name, method_name))
return method_names
def method_of_invocation(self):
pass
def caller_arguments(self, syntax_tree, caller, called, parameter_index):
query = "/CompilationUnit/types//MethodDeclaration/name/SimpleName[@token='" + caller + "']" \
"/parent::name/parent::MethodDeclaration//MethodInvocation/name" \
"/SimpleName[@token='" + called + "']/parent::name/parent::MethodInvocation/arguments/*["+ str(parameter_index) + "]//@token"
arguments = set()
for argument in syntax_tree.tree.filter(query):
arguments.add(ValueParameter(get_type(argument.internal_type),
argument.token,
syntax_tree.file,
argument.start_position.line))
return arguments
def caller_of(self, syntax_tree, method):
query = "/CompilationUnit/types//MethodInvocation//*[@role='Call' and @role='Callee' " \
"and @token='" + method + "']/ancestor::MethodDeclaration/name/SimpleName/@token"
callers = set()
for caller in syntax_tree.tree.filter(query):
callers.add(caller.get()["@token"])
return callers
def method_parameter(self, syntax_tree, method):
query = "/CompilationUnit/types//SimpleName[@token='" + method + "']" \
"/parent::name/parent::MethodDeclaration/parameters//name/SimpleName" \
"[@role='Identifier' and @role='Argument']/@token"
return list(syntax_tree.tree.filter(query))
def method_parameter_index(self, syntax_tree, method_name, parameter_name):
n = 1
for parameter in self.method_parameter(syntax_tree, method_name):
if parameter_name == parameter.token:
return n
else:
n = n + 1
return -1
def substitute_p(self, syntax_tree, method, parameter_e):
value_parameter = set()
parameter_index = self.method_parameter_index(syntax_tree, method, parameter_e)
if parameter_index == -1:
return value_parameter
for parameter_a in self.method_parameter(syntax_tree, method):
if parameter_e == parameter_a.get()["@token"]:
callers = self.caller_of(syntax_tree, method)
if len(callers) == 0:
value_parameter.add(ValueParameter(Types.Unknown, "UNKNOWN", syntax_tree.file, parameter_a.start_position.line))
else:
for caller in callers:
arguments = self.caller_arguments(syntax_tree, caller, method, parameter_index)
for argument in arguments:
if argument.type == Types.StringLiteral or argument.type == Types.NumberLiteral:
value_parameter.add(argument)
elif argument.type == Types.SimpleName:
value_parameter = value_parameter.union(self.substitute_v(syntax_tree, caller, argument.value))
elif argument.type == Types.Method:
logger.debug("not implemented yet!")
return value_parameter
def substitute_v(self, syntax_tree, method, variable):
"""
substitute variable
:return:
"""
parameter_values = set()
# string value for variable can be found
query = "/CompilationUnit/types//SimpleName[@token='" + method + "']" \
"/ancestor::MethodDeclaration//VariableDeclarationFragment/name/SimpleName[@token='" + variable + "']" \
"/parent::name/parent::VariableDeclarationFragment/initializer/StringLiteral/@token"
parameter_values = parameter_values.union(self.value_assignment(syntax_tree, query))
#if len(parameter_values) > 0: return parameter_values
# int value for variable can be found
query = "/CompilationUnit/types//SimpleName[@token='" + method + "']" \
"/ancestor::MethodDeclaration//VariableDeclarationFragment/name/SimpleName[@token='" + variable + "']" \
"/parent::name/parent::VariableDeclarationFragment/initializer/NumberLiteral/@token"
parameter_values = parameter_values.union(self.int_assignment(syntax_tree, query))
#if len(parameter_values) > 0: return parameter_values
# value assignment for byte array with = {'a', 'b', 'c', ... }
query = "/CompilationUnit/types//SimpleName[@token='" + method + "']" \
"/ancestor::MethodDeclaration//VariableDeclarationFragment/name/SimpleName[@token='" + variable + "']" \
"/parent::name/parent::VariableDeclarationFragment/initializer/ArrayInitializer/expressions/" \
"CharacterLiteral"
parameter_values = parameter_values.union(self.array_assignment(syntax_tree, query))
#if len(parameter_values) > 0: return parameter_values
# value assignment for byte array with = {(byte) 0x00, (byte) 0x01, (byte) 0x02, ... }
query = "/CompilationUnit/types//SimpleName[@token='" + method + "']" \
"/ancestor::MethodDeclaration//VariableDeclarationFragment/name/SimpleName[@token='" + variable + "']" \
"/parent::name/parent::VariableDeclarationFragment/initializer/ArrayInitializer/" \
"expressions//NumberLiteral"
parameter_values = parameter_values.union(self.array_assignment(syntax_tree, query, ", "))
#if len(parameter_values) > 0: return parameter_values
# value assignment for byte array with {getBytes()}
query = "/CompilationUnit/types//SimpleName[@token='" + method + "']" \
"/ancestor::MethodDeclaration//VariableDeclarationFragment/name/SimpleName[@token='" + variable + "']" \
"/parent::name/parent::VariableDeclarationFragment/initializer//expression/StringLiteral/@token"
parameter_values = parameter_values.union(self.value_assignment(syntax_tree, query))
#if len(parameter_values) > 0: return parameter_values
# number value for variable can be found
query = "/CompilationUnit/types//SimpleName[@token='" + method + "']" \
"/ancestor::MethodDeclaration//VariableDeclarationFragment/name/SimpleName[@token='" + variable + "']" \
"/parent::name/parent::VariableDeclarationFragment/initializer/NumberLiteral/@token"
parameter_values = parameter_values.union(self.value_assignment(syntax_tree, query))
#if len(parameter_values) > 0: return parameter_values
# check for nested variables
query = "/CompilationUnit/types//bodyDeclarations/MethodDeclaration/name/" \
"SimpleName[@token='" + method + "']/ancestor::MethodDeclaration/body//statements/" \
"VariableDeclarationStatement/fragments//name/SimpleName[@token='" + variable + "']" \
"/ancestor::VariableDeclarationStatement/fragments//initializer/SimpleName"
for nested_variable in [hit.token for hit in syntax_tree.tree.filter(query)]:
parameter_values = parameter_values.union(self.substitute_v(syntax_tree, method, nested_variable))
# check for method parameters
parameter_values = parameter_values.union(self.substitute_p(syntax_tree, method, variable))
if len(parameter_values) > 0: return parameter_values
# check for field value
parameter_values = parameter_values.union((self.substitute_f(syntax_tree, variable)))
return parameter_values
def substitute_f(self, syntax_tree, name):
query_f = "/CompilationUnit/types//bodyDeclarations//FieldDeclaration/fragments//name/SimpleName[@token='" + name + "']"
query_f_string = query_f + "/ancestor::FieldDeclaration/type//name/" \
"SimpleName[@token='String']" \
"/ancestor::FieldDeclaration/fragments//initializer/StringLiteral"
query_f_int = query_f + "/ancestor::FieldDeclaration/type/PrimitiveType[@token='int']" \
"/ancestor::FieldDeclaration/fragments//initializer/NumberLiteral"
query_f_char_array1 = query_f + "/ancestor::FieldDeclaration/type/ArrayType/elementType/" \
"PrimitiveType[@token='byte']/ancestor::FieldDeclaration/" \
"fragments//initializer/ArrayInitializer/expressions/CharacterLiteral"
query_f_char_array2 = query_f + "/ancestor::FieldDeclaration/type/ArrayType/elementType/" \
"PrimitiveType[@token='byte']/ancestor::FieldDeclaration/" \
"fragments//initializer//StringLiteral"
query_f_char_array3 = query_f + "/ancestor::FieldDeclaration/type/ArrayType/elementType/" \
"PrimitiveType[@token='byte']/ancestor::FieldDeclaration/" \
"fragments//initializer//NumberLiteral"
# check if there is any corresponding field
try:
next(syntax_tree.tree.filter(query_f))
except StopIteration:
return set()
# determine field value
# string assignment
value = self.iterator_get_next(syntax_tree, query_f_string)
if not value is None:
return set([ValueParameter(Types.StringLiteral, value.token, syntax_tree.file, value.start_position.line)])
# int assignment
value = self.iterator_get_next(syntax_tree, query_f_int)
if not value is None:
return set([ValueParameter(Types.NumberLiteral, value.token, syntax_tree.file, value.start_position.line)])
# byte array initialization = {'a', 'b', 'c', ... }
array_values = self.array_assignment(syntax_tree, query_f_char_array1)
if len(array_values) > 0:
return array_values
# byte array initialization = "a string".getBytes()
value = self.iterator_get_next(syntax_tree, query_f_char_array2)
if not value is None:
return set([ValueParameter(Types.StringLiteral, value.token, syntax_tree.file, value.start_position.line)])
# byte array initialization = {(byte) 0x00, (byte) 0x01, (byte) 0x02, ... }
array_values = self.array_assignment(syntax_tree, query_f_char_array3, ", ")
if len(array_values) > 0:
return array_values
return set()
def substitute_m(self):
"""substitute method"""
def cm(self, syntax_tree, class_type, method_name, parameter_index):
"""
call method
:return:
"""
value_parameters = set()
base_query = "/CompilationUnit/types//VariableDeclarationStatement/type//name/SimpleName[@token='" + class_type + "']/ancestor::VariableDeclarationStatement/fragments/VariableDeclarationFragment/name/SimpleName/@token"
objects = syntax_tree.tree.filter(base_query)
for object in objects:
value_parameters = value_parameters.union(self.csm(syntax_tree, object.token, method_name, parameter_index))
return value_parameters
def csm(self, syntax_tree, class_type, method_name, parameter_index):
"""
call static method
:return:
"""
value_parameters = set()
base_query = "/CompilationUnit/types//MethodInvocation//" \
"*[@role='Call' and @role='Callee' and @token='" + method_name + "']/" \
"ancestor::MethodInvocation/expression/SimpleName[@token='" + class_type + "']/" \
"ancestor::MethodInvocation/arguments/*[" + str(parameter_index) + "]"
# StringLiteral
#query_s = base_query + "//StringLiteral/@token"
#for string in syntax_tree.filter(query_s):
# value_parameters.add(ValueParameter(Types.StringLiteral, string.token, "File", string.start_position.line, class_type + "." + method_name + "(...) -> hard coded string"))
return self.query_parameter_value(syntax_tree, base_query, class_type + "." + method_name)
#return value_parameters
def ci(self, syntax_tree, type_name, parameter_index, operator=None, value=None):
"""
create instance
:param syntax_tree:
:param type_name:
:param parameter_index:
:param operator:
:param value:
:return:
"""
value_parameters = set()
base_query = "/CompilationUnit/types//ClassInstanceCreation/type//name" \
"/SimpleName[@token='" + type_name + "']/ancestor::ClassInstanceCreation/arguments/*["\
+ str(parameter_index) + "]"
return self.query_parameter_value(syntax_tree, base_query, type_name)
def query_parameter_value(self, syntax_tree, base_query, parameter_receiver):
value_parameters = set()
# new Byte[] { '.', '.', ... }
query_array_char = base_query + "//ArrayInitializer/expressions/CharacterLiteral"
for value_parameter in self.array_assignment(syntax_tree, query_array_char):
value_parameter.init_misuse_position(parameter_receiver + " -> hard coded array", value_parameter.line)
value_parameters.add(value_parameter)
# new Byte[] {(byte) 0x01, (byte) 0x02, ... )
query_array_int = base_query + "//ArrayInitializer/expressions//NumberLiteral"
int_arrays = self.array_assignment(syntax_tree, query_array_int, ",")
for value_parameter in int_arrays:
value_parameter.init_misuse_position(parameter_receiver + " -> hard coded array", value_parameter.line)
value_parameters.add(value_parameter)
if int_arrays is None or len(int_arrays) < 1:
# NumberLiteral
query_n = base_query + "//NumberLiteral/@token"
for string in syntax_tree.tree.filter(query_n):
value_parameters.add(
ValueParameter(Types.NumberLiteral, string.token, syntax_tree.file, string.start_position.line,
parameter_receiver + " -> hard coded int", string.start_position.line))
# StringLiteral
query_s = base_query + "//StringLiteral/@token"
for string in syntax_tree.tree.filter(query_s):
value_parameters.add(ValueParameter(Types.StringLiteral, string.token, syntax_tree.file, string.start_position.line, parameter_receiver + " -> hard coded string", string.start_position.line))
# parameter is variable
query_v = base_query + "//SimpleName[@role='Identifier' and @role='Receiver' or @role='Argument']"
for variable in syntax_tree.tree.filter(query_v + "/@token"):
variable_name = variable.token
methods = self.method_of_instantiation(syntax_tree, query_v, variable_name)
for method in methods:
value_parameters_substituted = self.substitute_v(syntax_tree, method[1], variable_name)
# determine line number of analysed method call
query_line = query_v + "[ancestor::MethodDeclaration/name/SimpleName[@token = '" + method[1] + "']]"
misuse_line = next(syntax_tree.tree.filter(query_line)).start_position.line
for value_parameter in value_parameters_substituted:
value_parameter.init_misuse_position(method[0] + "." + method[1] + "." + parameter_receiver, misuse_line)
value_parameters = value_parameters.union(value_parameters_substituted)
return value_parameters
# TODO: possible improvements
# parameter is variable with method call e.g. string.getBytes()
# query_vm = base_query + "//MethodInvocation/expression/SimpleName/@token"
# parameter is method return value
# query_m = base_query + "//MethodInvocation[@expression]/name/SimpleName/@token"
# ClassInstanceCreation
# query_c = "//ClassInstanceCreateion"
| en | 0.209577 | #method_names.append(method.get()["@token"]) substitute variable :return: # string value for variable can be found #if len(parameter_values) > 0: return parameter_values # int value for variable can be found #if len(parameter_values) > 0: return parameter_values # value assignment for byte array with = {'a', 'b', 'c', ... } #if len(parameter_values) > 0: return parameter_values # value assignment for byte array with = {(byte) 0x00, (byte) 0x01, (byte) 0x02, ... } #if len(parameter_values) > 0: return parameter_values # value assignment for byte array with {getBytes()} #if len(parameter_values) > 0: return parameter_values # number value for variable can be found #if len(parameter_values) > 0: return parameter_values # check for nested variables # check for method parameters # check for field value # check if there is any corresponding field # determine field value # string assignment # int assignment # byte array initialization = {'a', 'b', 'c', ... } # byte array initialization = "a string".getBytes() # byte array initialization = {(byte) 0x00, (byte) 0x01, (byte) 0x02, ... } substitute method call method :return: call static method :return: # StringLiteral #query_s = base_query + "//StringLiteral/@token" #for string in syntax_tree.filter(query_s): # value_parameters.add(ValueParameter(Types.StringLiteral, string.token, "File", string.start_position.line, class_type + "." + method_name + "(...) -> hard coded string")) #return value_parameters create instance :param syntax_tree: :param type_name: :param parameter_index: :param operator: :param value: :return: # new Byte[] { '.', '.', ... } # new Byte[] {(byte) 0x01, (byte) 0x02, ... ) # NumberLiteral # StringLiteral # parameter is variable # determine line number of analysed method call # TODO: possible improvements # parameter is variable with method call e.g. string.getBytes() # query_vm = base_query + "//MethodInvocation/expression/SimpleName/@token" # parameter is method return value # query_m = base_query + "//MethodInvocation[@expression]/name/SimpleName/@token" # ClassInstanceCreation # query_c = "//ClassInstanceCreateion" | 2.159143 | 2 |
tuxart/sources/tuxmodifier.py | 0xmre/tuxart | 3 | 6614220 | from xml.dom.minidom import parse
import xml.dom.minidom
import re
import xml.sax
import xml.dom
import colorengine
import configparser
import os
# Path to local files
path = os.path.dirname(os.path.realpath(__file__))
home = os.path.expanduser("~")
pathtomod = os.path.join(home,"Pictures/tux_mod.svg")
#
# Declaration of the different body part of the tux
#
bodypart = ['head','beak','left_eye','right_eye','body','torso','left_palm','right_palm']
# These arrays are fill with the different part of the tux to modify
head = ['skin_between_eyes', 'head_skin', 'forehead_reflection', 'right_eyebrows', 'left_eyebrows', ]
beak = ['smile', 'beak_shadow_on_eyes', 'beak_bottom_part', 'beak_bottom_part_reflection', 'beak_upper_part', 'beak_upper_part_reflection', 'right_nostril', 'left_nostril', 'beak_right_end']
left_eye = ['white_left_eye', 'left_pupil', 'left_pupil_reflection', 'left_eyelid']
right_eye = ['white_right_eye', 'right_pupil', 'right_pupil_reflection_1', 'right_pupil_reflection_2', 'right_eyelid']
body = ['skin', 'right_leg', 'left_leg', 'right_arm', 'right_arm_reflection', 'neck_reflection', 'skin_reflection', 'right_hand', 'right_hand_reflection_1', 'right_hand_reflection_2', 'left_arm', 'left_arm_reflection']
torso = ['belly', 'torso_shadow', 'shadow_under_beak', 'chest_left_shadow', 'chest_right_shadow', 'chest_middle_shadow', 'belly_shadow']
left_palm = ['left_palm', 'left_palm_shadow_1', 'left_palm_shadow_2', 'left_palm_reflection']
right_palm = ['right_palm_shadow_1', 'right_palm_shadow_2', 'right_palm_shadow_3', 'right_palm', 'right_palm_reflection', 'right_arm_shadow_1', 'right_arm_shadow_2']
# Accesory adder
def accessoryhandler():
# index in both lists links an item with a configuration
configs = ["CONFIG_FTRACE","CONFIG_CPU_FREQ_DEFAULT_GOV_USERSPACE","CONFIG_CPU_FREQ_DEFAULT_GOV_PERFORMANCE","CONFIG_CPU_FREQ_DEFAULT_GOV_CONSERVATIVE","CONFIG_ENCRYPTED_KEYS","CONFIG_USB_USBNET"]
items = ["tattoo1","helmet1","helmet2","helmet3","shield","cape"]
for config, item in zip(configs,items):
if configparser.isconfigenabled(config):
addaccessory(item)
# Color every part of the tux
def tuxcolorizer():
for key in bodypart:
if "left_eye" in key:
color1 = colorengine.hexformat('system')
color2 = colorengine.modifycolor(color1,-30)
color3 = colorengine.modifycolor(color1,10)
reflection = colorengine.reflectioncolor(color1)
for zone in left_eye:
if 'left_pupil' in zone:
modify(color2, zone)
elif 'reflection' in zone:
modify(reflection,zone)
elif 'white' in zone:
modify(reflection, zone)
else:
modify(color1, zone)
elif "right_eye" in key:
color1 = colorengine.hexformat('system')
color2 = colorengine.modifycolor(color1,-30)
color3 = colorengine.modifycolor(color1,10)
reflection = colorengine.reflectioncolor(color1)
for zone in right_eye:
if 'right_pupil' in zone:
modify(color2, zone)
elif 'reflection' in zone:
modify(reflection,zone)
elif 'white' in zone:
modify(reflection, zone)
else:
modify(color1, zone)
elif "beak" in key:
color1 = colorengine.hexformat('river')
color2 = colorengine.modifycolor(color1,-40)
reflection = colorengine.reflectioncolor(color1)
shadow = colorengine.shadowcolor(color1)
for zone in beak:
if 'nostril' in zone:
modify(color1,zone)
elif 'smile' in zone:
modify(colorengine.hexformat('Kernel'), zone)
elif 'shadow' in zone:
modify(shadow, zone)
else:
modify(color2, zone)
elif "head" in key:
color1 = colorengine.hexformat('sensors')
color2 = colorengine.modifycolor(color1,25)
color3 = colorengine.shadowcolor(color2)
reflection = colorengine.reflectioncolor(color2)
for zone in head:
if 'reflection' in zone:
modify(reflection, zone)
elif 'eyebrows' in zone:
modify(color1, zone)
elif 'eyes' in zone:
modify(color3, zone)
else:
modify(color2, zone)
elif "body" in key:
color1 = colorengine.hexformat('CPU')
color2 = colorengine.modifycolor(color1,20)
color3 = colorengine.modifycolor(color1,-10)
shadow = colorengine.shadowcolor(color1)
reflection = colorengine.reflectioncolor(color1)
for zone in body:
if 'reflection' in zone:
modify(reflection, zone)
if 'leg' in zone:
modify(color2, zone)
elif 'skin' in zone:
modify(color3, zone)
else:
modify(color1, zone)
elif "torso" in key:
color1 = colorengine.hexformat('Net')
color2 = colorengine.modifycolor(color1,40)
shadow = colorengine.shadowcolor(color1)
for zone in torso:
if 'shadow' in zone:
modify(shadow, zone)
elif 'belly' in zone:
modify(color2, zone)
else:
modify(color1, zone)
elif "left_palm" in key:
color1 = colorengine.hexformat('USB')
color2 = colorengine.modifycolor(color1,-50)
reflection = colorengine.reflectioncolor(color1)
shadow = colorengine.shadowcolor(color1)
for zone in left_palm:
if 'reflection' in zone:
modify(reflection, zone)
elif 'shadow_1' in zone:
modify(shadow, zone)
elif 'shadow_2' in zone:
modify(color2, zone)
else:
modify(color1, zone)
elif "right_palm" in key:
color1 = colorengine.hexformat('support')
color2 = colorengine.modifycolor(color1,20)
reflection = colorengine.reflectioncolor(color1)
shadow = colorengine.shadowcolor(color1)
for zone in right_palm:
if 'reflection' in zone:
modify(reflection, zone)
elif 'shadow_1' in zone:
modify(shadow, zone)
elif 'shadow' in zone:
modify(reflection, zone)
else:
modify(color1, zone)
# Add argument item to tux_mod.svg
def addaccessory(item):
"""
takes the name of an item and add it to the specified file
"""
global pathtomod
global path
DOMTree = parse(pathtomod)
f=open(pathtomod, "w")
svg = DOMTree.documentElement
newElement = DOMTree.createElement("g")
newElement.setAttribute("id","mark")
svg.appendChild(newElement);
f.write(DOMTree.toprettyxml())
f.close()
f=open(pathtomod, "r")
regex="<g id=\"mark\"/>"
regex=re.escape(regex)
matches=re.split(regex, f.read(), 1)
tuxSvg1=matches[0]
tuxSvg2=matches[1]
f.close()
pathtoitem = os.path.join(path, "sprays/")
f=open(pathtoitem+item+".svg", "r")
regex="id=\""+item+"\""
regex=re.escape(regex)
tuxSvg1=tuxSvg1+"<g\n\t\t\t"+regex
matches=re.split(regex, f.read(), 1)
match=matches[1]
regex="<g id=\"mark\"/>"
regex=re.escape(regex)
matches=re.split(regex, match, 1)
f.close()
f=open(pathtomod, "w")
f.write(tuxSvg1+matches[0]+tuxSvg2)
f.close()
# Apply color in hexadecimal to bodypart
def modify(hexacolor, bodypart):
"""
modify the bodypart with the color given
"""
global pathtomod
DOMTree = xml.dom.minidom.parse(pathtomod)
f=open(pathtomod, "w")
svg = DOMTree.documentElement
paths = svg.getElementsByTagName("path")
for path in paths:
if path.getAttribute("id")==bodypart:
if path.hasAttribute("style"):
style = path.getAttribute("style")
regex="fill:"
matches=re.split(regex, style, 1)
newStyle=matches[0]+"fill:"
regex=";"
style=matches[1]
matches=re.split(regex, style, 1)
newStyle=newStyle+"#"+hexacolor+";"+matches[1]
path.setAttribute("style", newStyle)
else:
print(bodypart+" : <style> not found")
f.write(DOMTree.toprettyxml())
f.close()
# Initialize tux_mod.svg
def tuxinit():
"""
go back to the original Tux
"""
global path
global pathtomod
pathtotux = os.path.join(path, "sprays/original_tux.svg")
tux = open(pathtotux).read()
f=open(pathtomod, "w+")
f.write(tux)
f.close()
| from xml.dom.minidom import parse
import xml.dom.minidom
import re
import xml.sax
import xml.dom
import colorengine
import configparser
import os
# Path to local files
path = os.path.dirname(os.path.realpath(__file__))
home = os.path.expanduser("~")
pathtomod = os.path.join(home,"Pictures/tux_mod.svg")
#
# Declaration of the different body part of the tux
#
bodypart = ['head','beak','left_eye','right_eye','body','torso','left_palm','right_palm']
# These arrays are fill with the different part of the tux to modify
head = ['skin_between_eyes', 'head_skin', 'forehead_reflection', 'right_eyebrows', 'left_eyebrows', ]
beak = ['smile', 'beak_shadow_on_eyes', 'beak_bottom_part', 'beak_bottom_part_reflection', 'beak_upper_part', 'beak_upper_part_reflection', 'right_nostril', 'left_nostril', 'beak_right_end']
left_eye = ['white_left_eye', 'left_pupil', 'left_pupil_reflection', 'left_eyelid']
right_eye = ['white_right_eye', 'right_pupil', 'right_pupil_reflection_1', 'right_pupil_reflection_2', 'right_eyelid']
body = ['skin', 'right_leg', 'left_leg', 'right_arm', 'right_arm_reflection', 'neck_reflection', 'skin_reflection', 'right_hand', 'right_hand_reflection_1', 'right_hand_reflection_2', 'left_arm', 'left_arm_reflection']
torso = ['belly', 'torso_shadow', 'shadow_under_beak', 'chest_left_shadow', 'chest_right_shadow', 'chest_middle_shadow', 'belly_shadow']
left_palm = ['left_palm', 'left_palm_shadow_1', 'left_palm_shadow_2', 'left_palm_reflection']
right_palm = ['right_palm_shadow_1', 'right_palm_shadow_2', 'right_palm_shadow_3', 'right_palm', 'right_palm_reflection', 'right_arm_shadow_1', 'right_arm_shadow_2']
# Accesory adder
def accessoryhandler():
# index in both lists links an item with a configuration
configs = ["CONFIG_FTRACE","CONFIG_CPU_FREQ_DEFAULT_GOV_USERSPACE","CONFIG_CPU_FREQ_DEFAULT_GOV_PERFORMANCE","CONFIG_CPU_FREQ_DEFAULT_GOV_CONSERVATIVE","CONFIG_ENCRYPTED_KEYS","CONFIG_USB_USBNET"]
items = ["tattoo1","helmet1","helmet2","helmet3","shield","cape"]
for config, item in zip(configs,items):
if configparser.isconfigenabled(config):
addaccessory(item)
# Color every part of the tux
def tuxcolorizer():
for key in bodypart:
if "left_eye" in key:
color1 = colorengine.hexformat('system')
color2 = colorengine.modifycolor(color1,-30)
color3 = colorengine.modifycolor(color1,10)
reflection = colorengine.reflectioncolor(color1)
for zone in left_eye:
if 'left_pupil' in zone:
modify(color2, zone)
elif 'reflection' in zone:
modify(reflection,zone)
elif 'white' in zone:
modify(reflection, zone)
else:
modify(color1, zone)
elif "right_eye" in key:
color1 = colorengine.hexformat('system')
color2 = colorengine.modifycolor(color1,-30)
color3 = colorengine.modifycolor(color1,10)
reflection = colorengine.reflectioncolor(color1)
for zone in right_eye:
if 'right_pupil' in zone:
modify(color2, zone)
elif 'reflection' in zone:
modify(reflection,zone)
elif 'white' in zone:
modify(reflection, zone)
else:
modify(color1, zone)
elif "beak" in key:
color1 = colorengine.hexformat('river')
color2 = colorengine.modifycolor(color1,-40)
reflection = colorengine.reflectioncolor(color1)
shadow = colorengine.shadowcolor(color1)
for zone in beak:
if 'nostril' in zone:
modify(color1,zone)
elif 'smile' in zone:
modify(colorengine.hexformat('Kernel'), zone)
elif 'shadow' in zone:
modify(shadow, zone)
else:
modify(color2, zone)
elif "head" in key:
color1 = colorengine.hexformat('sensors')
color2 = colorengine.modifycolor(color1,25)
color3 = colorengine.shadowcolor(color2)
reflection = colorengine.reflectioncolor(color2)
for zone in head:
if 'reflection' in zone:
modify(reflection, zone)
elif 'eyebrows' in zone:
modify(color1, zone)
elif 'eyes' in zone:
modify(color3, zone)
else:
modify(color2, zone)
elif "body" in key:
color1 = colorengine.hexformat('CPU')
color2 = colorengine.modifycolor(color1,20)
color3 = colorengine.modifycolor(color1,-10)
shadow = colorengine.shadowcolor(color1)
reflection = colorengine.reflectioncolor(color1)
for zone in body:
if 'reflection' in zone:
modify(reflection, zone)
if 'leg' in zone:
modify(color2, zone)
elif 'skin' in zone:
modify(color3, zone)
else:
modify(color1, zone)
elif "torso" in key:
color1 = colorengine.hexformat('Net')
color2 = colorengine.modifycolor(color1,40)
shadow = colorengine.shadowcolor(color1)
for zone in torso:
if 'shadow' in zone:
modify(shadow, zone)
elif 'belly' in zone:
modify(color2, zone)
else:
modify(color1, zone)
elif "left_palm" in key:
color1 = colorengine.hexformat('USB')
color2 = colorengine.modifycolor(color1,-50)
reflection = colorengine.reflectioncolor(color1)
shadow = colorengine.shadowcolor(color1)
for zone in left_palm:
if 'reflection' in zone:
modify(reflection, zone)
elif 'shadow_1' in zone:
modify(shadow, zone)
elif 'shadow_2' in zone:
modify(color2, zone)
else:
modify(color1, zone)
elif "right_palm" in key:
color1 = colorengine.hexformat('support')
color2 = colorengine.modifycolor(color1,20)
reflection = colorengine.reflectioncolor(color1)
shadow = colorengine.shadowcolor(color1)
for zone in right_palm:
if 'reflection' in zone:
modify(reflection, zone)
elif 'shadow_1' in zone:
modify(shadow, zone)
elif 'shadow' in zone:
modify(reflection, zone)
else:
modify(color1, zone)
# Add argument item to tux_mod.svg
def addaccessory(item):
"""
takes the name of an item and add it to the specified file
"""
global pathtomod
global path
DOMTree = parse(pathtomod)
f=open(pathtomod, "w")
svg = DOMTree.documentElement
newElement = DOMTree.createElement("g")
newElement.setAttribute("id","mark")
svg.appendChild(newElement);
f.write(DOMTree.toprettyxml())
f.close()
f=open(pathtomod, "r")
regex="<g id=\"mark\"/>"
regex=re.escape(regex)
matches=re.split(regex, f.read(), 1)
tuxSvg1=matches[0]
tuxSvg2=matches[1]
f.close()
pathtoitem = os.path.join(path, "sprays/")
f=open(pathtoitem+item+".svg", "r")
regex="id=\""+item+"\""
regex=re.escape(regex)
tuxSvg1=tuxSvg1+"<g\n\t\t\t"+regex
matches=re.split(regex, f.read(), 1)
match=matches[1]
regex="<g id=\"mark\"/>"
regex=re.escape(regex)
matches=re.split(regex, match, 1)
f.close()
f=open(pathtomod, "w")
f.write(tuxSvg1+matches[0]+tuxSvg2)
f.close()
# Apply color in hexadecimal to bodypart
def modify(hexacolor, bodypart):
"""
modify the bodypart with the color given
"""
global pathtomod
DOMTree = xml.dom.minidom.parse(pathtomod)
f=open(pathtomod, "w")
svg = DOMTree.documentElement
paths = svg.getElementsByTagName("path")
for path in paths:
if path.getAttribute("id")==bodypart:
if path.hasAttribute("style"):
style = path.getAttribute("style")
regex="fill:"
matches=re.split(regex, style, 1)
newStyle=matches[0]+"fill:"
regex=";"
style=matches[1]
matches=re.split(regex, style, 1)
newStyle=newStyle+"#"+hexacolor+";"+matches[1]
path.setAttribute("style", newStyle)
else:
print(bodypart+" : <style> not found")
f.write(DOMTree.toprettyxml())
f.close()
# Initialize tux_mod.svg
def tuxinit():
"""
go back to the original Tux
"""
global path
global pathtomod
pathtotux = os.path.join(path, "sprays/original_tux.svg")
tux = open(pathtotux).read()
f=open(pathtomod, "w+")
f.write(tux)
f.close()
| en | 0.632754 | # Path to local files # # Declaration of the different body part of the tux # # These arrays are fill with the different part of the tux to modify # Accesory adder # index in both lists links an item with a configuration # Color every part of the tux # Add argument item to tux_mod.svg takes the name of an item and add it to the specified file # Apply color in hexadecimal to bodypart modify the bodypart with the color given # Initialize tux_mod.svg go back to the original Tux | 2.073729 | 2 |
setup.py | cloudblue/connect-python-sdk | 13 | 6614221 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of the Ingram Micro Cloud Blue Connect SDK.
# Copyright (c) 2019-2020 Ingram Micro. All Rights Reserved.
from os.path import exists
from setuptools import find_packages, setup
import pathlib
import pkg_resources
# noinspection PyTypeChecker
with pathlib.Path('requirements/sdk.txt').open() as requirements_txt:
install_reqs = [
str(requirement)
for requirement
in pkg_resources.parse_requirements(requirements_txt)
]
PACKAGES = find_packages(exclude=['tests*'])
DOC = ''
if exists('README.md'):
DOC = open('README.md', 'r').read()
setup(
name='connect-sdk',
author='<NAME>',
keywords='sdk connect connect automation',
packages=PACKAGES,
description='Connect Python SDK',
long_description=DOC,
long_description_content_type='text/markdown',
url='https://github.com/ingrammicro/connect-python-sdk',
license='Apache Software License',
include_package_data=True,
install_requires=install_reqs,
setup_requires=['setuptools_scm', 'pytest-runner', 'wheel'],
use_scm_version=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Operating System :: OS Independent',
'Operating System :: POSIX',
'Operating System :: MacOS',
'Operating System :: Unix',
],
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of the Ingram Micro Cloud Blue Connect SDK.
# Copyright (c) 2019-2020 Ingram Micro. All Rights Reserved.
from os.path import exists
from setuptools import find_packages, setup
import pathlib
import pkg_resources
# noinspection PyTypeChecker
with pathlib.Path('requirements/sdk.txt').open() as requirements_txt:
install_reqs = [
str(requirement)
for requirement
in pkg_resources.parse_requirements(requirements_txt)
]
PACKAGES = find_packages(exclude=['tests*'])
DOC = ''
if exists('README.md'):
DOC = open('README.md', 'r').read()
setup(
name='connect-sdk',
author='<NAME>',
keywords='sdk connect connect automation',
packages=PACKAGES,
description='Connect Python SDK',
long_description=DOC,
long_description_content_type='text/markdown',
url='https://github.com/ingrammicro/connect-python-sdk',
license='Apache Software License',
include_package_data=True,
install_requires=install_reqs,
setup_requires=['setuptools_scm', 'pytest-runner', 'wheel'],
use_scm_version=True,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: Apache Software License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Programming Language :: Python :: 3.7',
'Operating System :: OS Independent',
'Operating System :: POSIX',
'Operating System :: MacOS',
'Operating System :: Unix',
],
)
| en | 0.656952 | #!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of the Ingram Micro Cloud Blue Connect SDK. # Copyright (c) 2019-2020 Ingram Micro. All Rights Reserved. # noinspection PyTypeChecker | 1.42389 | 1 |
ex042.py | almmessias/CursoPython | 0 | 6614222 | <gh_stars>0
r1 = float (input ('Primeiro lado: '))
r2 = float (input ('Segundo lado: '))
r3 = float (input ('Terceiro lado: '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print ('Os lados acima podem formar um triangulo')
if r1 == r2 == r3:
print ('O triângulo é um Equilátero: todos os lado são iguais')
elif r1 == r2 or r1 == r3 or r2 == r3:
print ('O triângulo é um Isósceles: dois lados iguais')
elif r1 != r2 != r3 != r1:
print ('O triângulo é um Escaleno: todos os lados diferentes')
else:
print ('Os lados não formam um triângulo')
| r1 = float (input ('Primeiro lado: '))
r2 = float (input ('Segundo lado: '))
r3 = float (input ('Terceiro lado: '))
if r1 < r2 + r3 and r2 < r1 + r3 and r3 < r1 + r2:
print ('Os lados acima podem formar um triangulo')
if r1 == r2 == r3:
print ('O triângulo é um Equilátero: todos os lado são iguais')
elif r1 == r2 or r1 == r3 or r2 == r3:
print ('O triângulo é um Isósceles: dois lados iguais')
elif r1 != r2 != r3 != r1:
print ('O triângulo é um Escaleno: todos os lados diferentes')
else:
print ('Os lados não formam um triângulo') | none | 1 | 4.014755 | 4 | |
pumping_history_identification/main_ui.py | offglitch/GUI-pyPCGA | 2 | 6614223 | <reponame>offglitch/GUI-pyPCGA<gh_stars>1-10
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("pyPCGA")
MainWindow.resize(1440, 855)
#----------------------------------------------
# Setting the frame
#----------------------------------------------
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.frame = QtWidgets.QFrame(self.centralwidget)
self.frame.setGeometry(QtCore.QRect(730, 20, 701, 511))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.frame.setFont(font)
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.layoutWidget = QtWidgets.QWidget(self.centralwidget)
self.layoutWidget.setGeometry(QtCore.QRect(730, 545, 701, 91))
self.layoutWidget.setObjectName("layoutWidget")
self.gridLayout_6 = QtWidgets.QGridLayout(self.layoutWidget)
self.gridLayout_6.setContentsMargins(0, 0, 0, 0)
self.gridLayout_6.setObjectName("gridLayout_6")
self.export_settings = QtWidgets.QPushButton(self.layoutWidget)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.export_settings.setFont(font)
self.export_settings.setObjectName("export_settings")
self.gridLayout_6.addWidget(self.export_settings, 0, 1, 1, 1)
self.import_settings = QtWidgets.QPushButton(self.layoutWidget)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.import_settings.setFont(font)
self.import_settings.setObjectName("import_settings")
self.gridLayout_6.addWidget(self.import_settings, 0, 2, 1, 1)
self.execute_button = QtWidgets.QPushButton(self.layoutWidget)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.execute_button.setFont(font)
self.execute_button.setObjectName("execute_button")
self.gridLayout_6.addWidget(self.execute_button, 0, 0, 1, 1)
#----------------------------------------------
# added an execute button
#----------------------------------------------
# self.execute_button.clicked.connect(self.execute)
#----------------------------------------------
# restart button
#----------------------------------------------
self.restart_button = QtWidgets.QPushButton(self.layoutWidget)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.restart_button.setFont(font)
self.restart_button.setObjectName("restart_button")
self.gridLayout_6.addWidget(self.restart_button, 1, 1, 1, 1)
# self.restart_button.clicked.connect(self.restartFunction)
#----------------------------------------------
# check values button
#----------------------------------------------
self.check_button = QtWidgets.QPushButton(self.layoutWidget)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.check_button.setFont(font)
self.check_button.setObjectName("check_button")
self.gridLayout_6.addWidget(self.check_button, 1, 0, 1, 1)
# self.check_button.clicked.connect(self.switchFunction)
#----------------------------------------------
# Setting object names and sizing for main frame labels
#----------------------------------------------
self.fname_label = QtWidgets.QLabel(self.centralwidget)
self.fname_label.setGeometry(QtCore.QRect(11, 60, 400, 16))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.fname_label.setFont(font)
self.fname_label.setObjectName("fname_label")
self.dimension_label = QtWidgets.QLabel(self.centralwidget)
self.dimension_label.setGeometry(QtCore.QRect(569, 60, 72, 16))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.dimension_label.setFont(font)
self.dimension_label.setObjectName("dimension_label")
self.dim_box = QtWidgets.QSpinBox(self.centralwidget)
self.dim_box.setGeometry(QtCore.QRect(651, 60, 39, 24))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.dim_box.setFont(font)
self.dim_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly|QtCore.Qt.ImhPreferNumbers)
self.dim_box.setMaximum(0)
self.dim_box.setObjectName("dim_box")
self.module1_label = QtWidgets.QLabel(self.centralwidget)
self.module1_label.setGeometry(QtCore.QRect(11, 94, 691, 16))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(16)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.module1_label.setFont(font)
self.module1_label.setAutoFillBackground(False)
self.module1_label.setObjectName("module1_label")
#----------------------------------------------
# Setting Module 1's frame and grid layout
#----------------------------------------------
self.Module1Frame = QtWidgets.QFrame(self.centralwidget)
self.Module1Frame.setGeometry(QtCore.QRect(11, 114, 691, 181))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.Module1Frame.setFont(font)
self.Module1Frame.setAutoFillBackground(True)
self.Module1Frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.Module1Frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.Module1Frame.setObjectName("Module1Frame")
self.gridLayout = QtWidgets.QGridLayout(self.Module1Frame)
self.gridLayout.setObjectName("gridLayout")
#----------------------------------------------
# Module 1 labels and boxes start here
#----------------------------------------------
self.x0_label = QtWidgets.QLabel(self.Module1Frame)
self.x0_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.x0_label.setFont(font)
self.x0_label.setObjectName("x0_label")
self.gridLayout.addWidget(self.x0_label, 0, 0, 1, 1)
self.x0_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.x0_box.sizePolicy().hasHeightForWidth())
self.x0_box.setSizePolicy(sizePolicy)
self.x0_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.x0_box.setFont(font)
self.x0_box.setAcceptDrops(True)
self.x0_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.x0_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.x0_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.x0_box.setTabStopWidth(5)
self.x0_box.setObjectName("x0_box")
self.gridLayout.addWidget(self.x0_box, 0, 1, 1, 1)
self.y0_label = QtWidgets.QLabel(self.Module1Frame)
self.y0_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.y0_label.setFont(font)
self.y0_label.setObjectName("y0_label")
self.gridLayout.addWidget(self.y0_label, 0, 2, 1, 1)
self.y0_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.y0_box.sizePolicy().hasHeightForWidth())
self.y0_box.setSizePolicy(sizePolicy)
self.y0_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.y0_box.setFont(font)
self.y0_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.y0_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.y0_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.y0_box.setObjectName("y0_box")
self.gridLayout.addWidget(self.y0_box, 0, 3, 1, 1)
self.z0_label = QtWidgets.QLabel(self.Module1Frame)
self.z0_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.z0_label.setFont(font)
self.z0_label.setObjectName("z0_label")
self.gridLayout.addWidget(self.z0_label, 0, 4, 1, 1)
self.z0_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.z0_box.sizePolicy().hasHeightForWidth())
self.z0_box.setSizePolicy(sizePolicy)
self.z0_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.z0_box.setFont(font)
self.z0_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.z0_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.z0_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.z0_box.setObjectName("z0_box")
self.gridLayout.addWidget(self.z0_box, 0, 5, 1, 1)
self.lx_label = QtWidgets.QLabel(self.Module1Frame)
self.lx_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.lx_label.setFont(font)
self.lx_label.setObjectName("lx_label")
self.gridLayout.addWidget(self.lx_label, 1, 0, 1, 1)
self.lx_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lx_box.sizePolicy().hasHeightForWidth())
self.lx_box.setSizePolicy(sizePolicy)
self.lx_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.lx_box.setFont(font)
self.lx_box.setAcceptDrops(True)
self.lx_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.lx_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.lx_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.lx_box.setTabStopWidth(5)
self.lx_box.setObjectName("lx_box")
self.gridLayout.addWidget(self.lx_box, 1, 1, 1, 1)
self.ly_label = QtWidgets.QLabel(self.Module1Frame)
self.ly_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.ly_label.setFont(font)
self.ly_label.setObjectName("ly_label")
self.gridLayout.addWidget(self.ly_label, 1, 2, 1, 1)
self.ly_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.ly_box.sizePolicy().hasHeightForWidth())
self.ly_box.setSizePolicy(sizePolicy)
self.ly_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.ly_box.setFont(font)
self.ly_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.ly_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.ly_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.ly_box.setObjectName("ly_box")
self.gridLayout.addWidget(self.ly_box, 1, 3, 1, 1)
self.lz_label = QtWidgets.QLabel(self.Module1Frame)
self.lz_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.lz_label.setFont(font)
self.lz_label.setObjectName("lz_label")
self.gridLayout.addWidget(self.lz_label, 1, 4, 1, 1)
self.lz_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lz_box.sizePolicy().hasHeightForWidth())
self.lz_box.setSizePolicy(sizePolicy)
self.lz_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.lz_box.setFont(font)
self.lz_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.lz_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.lz_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.lz_box.setObjectName("lz_box")
self.gridLayout.addWidget(self.lz_box, 1, 5, 1, 1)
self.dxx_label = QtWidgets.QLabel(self.Module1Frame)
self.dxx_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.dxx_label.setFont(font)
self.dxx_label.setObjectName("dxx_label")
self.gridLayout.addWidget(self.dxx_label, 2, 0, 1, 1)
self.dxx_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.dxx_box.sizePolicy().hasHeightForWidth())
self.dxx_box.setSizePolicy(sizePolicy)
self.dxx_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.dxx_box.setFont(font)
self.dxx_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.dxx_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.dxx_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.dxx_box.setObjectName("dxx_box")
self.gridLayout.addWidget(self.dxx_box, 2, 1, 1, 1)
self.dyy_label = QtWidgets.QLabel(self.Module1Frame)
self.dyy_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.dyy_label.setFont(font)
self.dyy_label.setObjectName("dyy_label")
self.gridLayout.addWidget(self.dyy_label, 2, 2, 1, 1)
self.dyy_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.dyy_box.sizePolicy().hasHeightForWidth())
self.dyy_box.setSizePolicy(sizePolicy)
self.dyy_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.dyy_box.setFont(font)
self.dyy_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.dyy_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.dyy_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.dyy_box.setObjectName("dyy_box")
self.gridLayout.addWidget(self.dyy_box, 2, 3, 1, 1)
self.dzz_label = QtWidgets.QLabel(self.Module1Frame)
self.dzz_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.dzz_label.setFont(font)
self.dzz_label.setObjectName("dzz_label")
self.gridLayout.addWidget(self.dzz_label, 2, 4, 1, 1)
self.dz_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.dz_box.sizePolicy().hasHeightForWidth())
self.dz_box.setSizePolicy(sizePolicy)
self.dz_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.dz_box.setFont(font)
self.dz_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.dz_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.dz_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.dz_box.setObjectName("dz_box")
self.gridLayout.addWidget(self.dz_box, 2, 5, 1, 1)
self.s_true_label = QtWidgets.QLabel(self.Module1Frame)
self.s_true_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.s_true_label.setFont(font)
self.s_true_label.setObjectName("s_true_label")
self.gridLayout.addWidget(self.s_true_label, 3, 0, 1, 1)
#
self.s_true_button = QtWidgets.QToolButton(self.Module1Frame)
self.s_true_button.setMinimumSize(QtCore.QSize(130, 25))
self.s_true_button.setMaximumSize(QtCore.QSize(130, 25))
self.s_true_button.setPopupMode(QtWidgets.QToolButton.DelayedPopup)
self.s_true_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
self.s_true_button.setAutoRaise(True)
self.s_true_button.setObjectName("s_true_button")
self.gridLayout.addWidget(self.s_true_button, 3, 1, 1, 1)
# self.s_true_button.clicked.connect(self.openFileNameDialog)
# self.m_output_label = QtWidgets.QLabel(self.Module1Frame)
# self.m_output_label.setMaximumSize(QtCore.QSize(50, 20))
# font = QtGui.QFont()
# font.setFamily("Helvetica")
# font.setPointSize(15)
# self.m_output_label.setFont(font)
# self.m_output_label.setObjectName("m_output_label")
# self.gridLayout.addWidget(self.m_output_label, 4, 2, 1, 1)
# self.m_output = QtWidgets.QLabel(self.Module1Frame)
# self.m_output.setMaximumSize(QtCore.QSize(130, 25))
# font = QtGui.QFont()
# font.setFamily("Helvetica")
# font.setPointSize(15)
# self.m_output.setFont(font)
# self.m_output.setText("")
# self.m_output.setObjectName("m_output")
# self.gridLayout.addWidget(self.m_output, 4, 3, 1, 1)
# self.s_init_box = QtWidgets.QTextEdit(self.Module1Frame)
# sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
# sizePolicy.setHorizontalStretch(0)
# sizePolicy.setVerticalStretch(0)
# sizePolicy.setHeightForWidth(self.s_init_box.sizePolicy().hasHeightForWidth())
# self.s_init_box.setSizePolicy(sizePolicy)
# self.s_init_box.setMaximumSize(QtCore.QSize(130, 25))
# font = QtGui.QFont()
# font.setFamily("Helvetica")
# self.s_init_box.setFont(font)
# self.s_init_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
# self.s_init_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
# self.s_init_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
# self.s_init_box.setObjectName("s_init_box")
self.s_init_box = QtWidgets.QToolButton(self.Module1Frame)
self.s_init_box.setMinimumSize(QtCore.QSize(130, 25))
self.s_init_box.setMaximumSize(QtCore.QSize(130, 25))
self.s_init_box.setPopupMode(QtWidgets.QToolButton.DelayedPopup)
self.s_init_box.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
self.s_init_box.setAutoRaise(True)
self.s_init_box.setObjectName("s_init_box")
self.gridLayout.addWidget(self.s_init_box, 4, 1, 1, 1)
# self.s_init_box.clicked.connect(self.openFileNameDialog)
self.s_init_label = QtWidgets.QLabel(self.Module1Frame)
self.s_init_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.s_init_label.setFont(font)
self.s_init_label.setObjectName("s_init_label")
self.gridLayout.addWidget(self.s_init_label, 4, 0, 1, 1)
self.fname_output = QtWidgets.QLabel(self.centralwidget)
self.fname_output.setGeometry(QtCore.QRect(11, 150, 16, 16))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.fname_output.setFont(font)
self.fname_output.setText("")
self.fname_output.setObjectName("fname_output")
#----------------------------------------------
# Setting Module 2's labels and boxes
#----------------------------------------------
self.module2_label = QtWidgets.QLabel(self.centralwidget)
# Adjusted to fix bleed issue
self.module2_label.setGeometry(QtCore.QRect(11, 311, 300, 16))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(16)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.module2_label.setFont(font)
self.module2_label.setAutoFillBackground(False)
self.module2_label.setWordWrap(False)
self.module2_label.setObjectName("module2_label")
self.Module1Frame_2 = QtWidgets.QFrame(self.centralwidget)
self.Module1Frame_2.setGeometry(QtCore.QRect(11, 343, 689, 80))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.Module1Frame_2.setFont(font)
self.Module1Frame_2.setAutoFillBackground(True)
self.Module1Frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.Module1Frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
self.Module1Frame_2.setObjectName("Module1Frame_2")
self.forward_model = QtWidgets.QComboBox(self.Module1Frame_2)
self.forward_model.setGeometry(QtCore.QRect(164, 11, 123, 25))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.forward_model.sizePolicy().hasHeightForWidth())
self.forward_model.setSizePolicy(sizePolicy)
self.forward_model.setMaximumSize(QtCore.QSize(200, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.forward_model.setFont(font)
self.forward_model.setObjectName("forward_model")
self.forward_model.addItem("")
self.forward_model.addItem("")
self.forward_model.addItem("")
self.source_label = QtWidgets.QLabel(self.Module1Frame_2)
self.source_label.setGeometry(QtCore.QRect(13, 42, 50, 16))
self.source_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.source_label.setFont(font)
self.source_label.setObjectName("source_label")
self.forward_model_label = QtWidgets.QLabel(self.Module1Frame_2)
self.forward_model_label.setGeometry(QtCore.QRect(13, 13, 104, 16))
self.forward_model_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.forward_model_label.setFont(font)
self.forward_model_label.setObjectName("forward_model_label")
self.log_check = QtWidgets.QCheckBox(self.Module1Frame_2)
self.log_check.setGeometry(QtCore.QRect(605, 14, 19, 18))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.log_check.setFont(font)
self.log_check.setText("")
self.log_check.setObjectName("log_check")
self.log_label = QtWidgets.QLabel(self.Module1Frame_2)
self.log_label.setGeometry(QtCore.QRect(530, 13, 25, 16))
self.log_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.log_label.setFont(font)
self.log_label.setObjectName("log_label")
self.source_button = QtWidgets.QToolButton(self.Module1Frame_2)
self.source_button.setGeometry(QtCore.QRect(90, 42, 200, 25))
self.source_button.setMinimumSize(QtCore.QSize(130, 25))
self.source_button.setMaximumSize(QtCore.QSize(130, 25))
self.source_button.setPopupMode(QtWidgets.QToolButton.DelayedPopup)
self.source_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
self.source_button.setAutoRaise(True)
self.source_button.setObjectName("source_button")
#----------------------------------------------
# Setting Module 3's labels and boxes
#----------------------------------------------
self.module3_label = QtWidgets.QLabel(self.centralwidget)
self.module3_label.setGeometry(QtCore.QRect(11, 439, 691, 16))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(16)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.module3_label.setFont(font)
self.module3_label.setAutoFillBackground(False)
self.module3_label.setObjectName("module3_label")
self.Module1Frame_3 = QtWidgets.QFrame(self.centralwidget)
self.Module1Frame_3.setGeometry(QtCore.QRect(11, 471, 691, 86))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.Module1Frame_3.setFont(font)
self.Module1Frame_3.setAutoFillBackground(True)
self.Module1Frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.Module1Frame_3.setFrameShadow(QtWidgets.QFrame.Raised)
self.Module1Frame_3.setObjectName("Module1Frame_3")
self.gridLayout_3 = QtWidgets.QGridLayout(self.Module1Frame_3)
self.gridLayout_3.setObjectName("gridLayout_3")
self.n_module3_label = QtWidgets.QLabel(self.Module1Frame_3)
self.n_module3_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.n_module3_label.setFont(font)
self.n_module3_label.setObjectName("n_module3_label")
self.gridLayout_3.addWidget(self.n_module3_label, 0, 2, 1, 1)
self.obs_label = QtWidgets.QLabel(self.Module1Frame_3)
self.obs_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.obs_label.setFont(font)
self.obs_label.setObjectName("obs_label")
# Fix Grid positioning for the label and the box
self.gridLayout_3.addWidget(self.obs_label, 0, 0, 0, 0)
self.Obs_button = QtWidgets.QToolButton(self.Module1Frame_3)
self.Obs_button.setMinimumSize(QtCore.QSize(130, 25))
self.Obs_button.setMaximumSize(QtCore.QSize(130, 25))
self.Obs_button.setPopupMode(QtWidgets.QToolButton.DelayedPopup)
self.Obs_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
self.Obs_button.setAutoRaise(True)
self.Obs_button.setObjectName("Obs_button")
self.gridLayout_3.addWidget(self.Obs_button, 0, 0, 0, 0)
# self.Obs_button.clicked.connect(self.openFileNameDialog)
#----------------------------------------------
# Setting Module 4's labels and boxes
#----------------------------------------------
self.module4_label = QtWidgets.QLabel(self.centralwidget)
self.module4_label.setGeometry(QtCore.QRect(11, 573, 241, 16))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(16)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.module4_label.setFont(font)
self.module4_label.setAutoFillBackground(False)
self.module4_label.setObjectName("module4_label")
self.Module1Frame_4 = QtWidgets.QFrame(self.centralwidget)
self.Module1Frame_4.setGeometry(QtCore.QRect(11, 605, 691, 156))
self.Module1Frame_4.setMaximumSize(QtCore.QSize(700, 180))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.Module1Frame_4.setFont(font)
self.Module1Frame_4.setAutoFillBackground(True)
self.Module1Frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.Module1Frame_4.setFrameShadow(QtWidgets.QFrame.Raised)
self.Module1Frame_4.setObjectName("Module1Frame_4")
self.gridLayout_4 = QtWidgets.QGridLayout(self.Module1Frame_4)
self.gridLayout_4.setObjectName("gridLayout_4")
self.x_module4_label = QtWidgets.QLabel(self.Module1Frame_4)
self.x_module4_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.x_module4_label.setFont(font)
self.x_module4_label.setObjectName("x_module4_label")
self.gridLayout_4.addWidget(self.x_module4_label, 0, 0, 1, 1)
self.x_select = QtWidgets.QComboBox(self.Module1Frame_4)
self.x_select.setMaximumSize(QtCore.QSize(130, 30))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.x_select.setFont(font)
self.x_select.setObjectName("x_select")
self.x_select.addItem("")
self.x_select.addItem("")
self.x_select.addItem("")
self.gridLayout_4.addWidget(self.x_select, 0, 1, 1, 1)
self.lambda_x_label = QtWidgets.QLabel(self.Module1Frame_4)
self.lambda_x_label.setMaximumSize(QtCore.QSize(80, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.lambda_x_label.setFont(font)
self.lambda_x_label.setObjectName("lambda_x_label")
self.gridLayout_4.addWidget(self.lambda_x_label, 0, 2, 1, 1)
self.precision_label = QtWidgets.QTextEdit(self.Module1Frame_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.precision_label.sizePolicy().hasHeightForWidth())
self.precision_label.setSizePolicy(sizePolicy)
self.precision_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.precision_label.setFont(font)
self.precision_label.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.precision_label.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.precision_label.setObjectName("precision_label")
self.gridLayout_4.addWidget(self.precision_label, 0, 3, 1, 1)
self.kernel_label = QtWidgets.QLabel(self.Module1Frame_4)
self.kernel_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.kernel_label.setFont(font)
self.kernel_label.setObjectName("kernel_label")
self.gridLayout_4.addWidget(self.kernel_label, 0, 4, 1, 1)
self.kernel_box = QtWidgets.QComboBox(self.Module1Frame_4)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.kernel_box.setFont(font)
self.kernel_box.setObjectName("kernel_box")
self.kernel_box.addItem("")
self.kernel_box.addItem("")
self.gridLayout_4.addWidget(self.kernel_box, 0, 5, 1, 2)
self.n_pc_label = QtWidgets.QLabel(self.Module1Frame_4)
self.n_pc_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.n_pc_label.setFont(font)
self.n_pc_label.setObjectName("n_pc_label")
self.gridLayout_4.addWidget(self.n_pc_label, 1, 0, 1, 1)
self.n_pc_box = QtWidgets.QTextEdit(self.Module1Frame_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.n_pc_box.sizePolicy().hasHeightForWidth())
self.n_pc_box.setSizePolicy(sizePolicy)
self.n_pc_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.n_pc_box.setFont(font)
self.n_pc_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.n_pc_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.n_pc_box.setObjectName("n_pc_box")
self.gridLayout_4.addWidget(self.n_pc_box, 1, 1, 1, 1)
self.matvec_label = QtWidgets.QLabel(self.Module1Frame_4)
self.matvec_label.setMaximumSize(QtCore.QSize(80, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.matvec_label.setFont(font)
self.matvec_label.setObjectName("matvec_label")
self.gridLayout_4.addWidget(self.matvec_label, 1, 2, 1, 1)
self.matvec_box = QtWidgets.QComboBox(self.Module1Frame_4)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.matvec_box.setFont(font)
self.matvec_box.setObjectName("matvec_box")
self.matvec_box.addItem("")
self.matvec_box.addItem("")
self.matvec_box.addItem("")
self.matvec_box.addItem("")
self.gridLayout_4.addWidget(self.matvec_box, 1, 3, 1, 1)
self.prior_std_label = QtWidgets.QLabel(self.Module1Frame_4)
self.prior_std_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.prior_std_label.setFont(font)
self.prior_std_label.setObjectName("prior_std_label")
self.gridLayout_4.addWidget(self.prior_std_label, 2, 0, 1, 1)
self.r_label = QtWidgets.QTextEdit(self.Module1Frame_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.r_label.sizePolicy().hasHeightForWidth())
self.r_label.setSizePolicy(sizePolicy)
self.r_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.r_label.setFont(font)
self.r_label.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.r_label.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.r_label.setObjectName("r_label")
self.gridLayout_4.addWidget(self.r_label, 2, 1, 1, 1)
self.maxiter_label = QtWidgets.QLabel(self.Module1Frame_4)
self.maxiter_label.setMaximumSize(QtCore.QSize(80, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.maxiter_label.setFont(font)
self.maxiter_label.setObjectName("maxiter_label")
self.gridLayout_4.addWidget(self.maxiter_label, 2, 2, 1, 1)
self.maxiter_label = QtWidgets.QTextEdit(self.Module1Frame_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.maxiter_label.sizePolicy().hasHeightForWidth())
self.maxiter_label.setSizePolicy(sizePolicy)
self.maxiter_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.maxiter_label.setFont(font)
self.maxiter_label.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.maxiter_label.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.maxiter_label.setObjectName("maxiter_label")
self.gridLayout_4.addWidget(self.maxiter_label, 2, 3, 1, 1)
self.restol_label = QtWidgets.QLabel(self.Module1Frame_4)
self.restol_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.restol_label.setFont(font)
self.restol_label.setObjectName("restol_label")
self.gridLayout_4.addWidget(self.restol_label, 2, 4, 1, 1)
self.restol_label = QtWidgets.QTextEdit(self.Module1Frame_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.restol_label.sizePolicy().hasHeightForWidth())
self.restol_label.setSizePolicy(sizePolicy)
self.restol_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.restol_label.setFont(font)
self.restol_label.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.restol_label.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.restol_label.setObjectName("restol_label")
self.gridLayout_4.addWidget(self.restol_label, 2, 5, 1, 2)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.lm_label = QtWidgets.QLabel(self.Module1Frame_4)
self.lm_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.lm_label.setFont(font)
self.lm_label.setObjectName("lm_label")
self.gridLayout_4.addWidget(self.lm_label, 3, 2, 1, 1)
self.lm_check = QtWidgets.QCheckBox(self.Module1Frame_4)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.lm_check.setFont(font)
self.lm_check.setText("")
self.lm_check.setObjectName("lm_check")
self.gridLayout_4.addWidget(self.lm_check, 3, 3, 1, 1)
self.linesearch_label = QtWidgets.QLabel(self.Module1Frame_4)
self.linesearch_label.setMaximumSize(QtCore.QSize(150, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.linesearch_label.setFont(font)
self.linesearch_label.setObjectName("linesearch_label")
self.gridLayout_4.addWidget(self.linesearch_label, 3, 4, 1, 2)
self.line_search = QtWidgets.QCheckBox(self.Module1Frame_4)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.line_search.setFont(font)
self.line_search.setText("")
self.line_search.setObjectName("line_search")
self.gridLayout_4.addWidget(self.line_search, 3, 6, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1440, 22))
self.menubar.setObjectName("menubar")
self.menupyPCGA = QtWidgets.QMenu(self.menubar)
self.menupyPCGA.setObjectName("menupyPCGA")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionNew = QtWidgets.QAction(MainWindow)
self.actionNew.setObjectName("actionNew")
self.actionSave = QtWidgets.QAction(MainWindow)
self.actionSave.setObjectName("actionSave")
self.actionDownload = QtWidgets.QAction(MainWindow)
self.actionDownload.setObjectName("actionDownload")
self.actionImport = QtWidgets.QAction(MainWindow)
self.actionImport.setObjectName("actionImport")
self.menupyPCGA.addAction(self.actionNew)
self.menupyPCGA.addAction(self.actionSave)
self.menupyPCGA.addAction(self.actionDownload)
self.menupyPCGA.addAction(self.actionImport)
self.menubar.addAction(self.menupyPCGA.menuAction())
#----------------------------------------------
# Setting the graphing frames
#----------------------------------------------
self.frame = QtWidgets.QWidget(self.centralwidget)
self.frame.setGeometry(QtCore.QRect(760, 30, 651, 511))
self.frame.setObjectName("frame")
self.fig, self.axs = plt.subplots(2, constrained_layout=True)
self.plotWidget = FigureCanvas(self.fig)
self.plotWidget.setParent(self.frame)
#----------------------------------------------
# Calls retranslateUi
#----------------------------------------------
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
MainWindow.setTabOrder(self.lx_box, self.ly_box)
MainWindow.setTabOrder(self.ly_box, self.lz_box)
MainWindow.setTabOrder(self.lz_box, self.dxx_box)
MainWindow.setTabOrder(self.dxx_box, self.dyy_box)
MainWindow.setTabOrder(self.dyy_box, self.dz_box)
# MainWindow.setTabOrder(self.dz_box, self.n_label)
# MainWindow.setTabOrder(self.n_label, self.nlocs_label)
MainWindow.setTabOrder(self.x_select, self.precision_label)
MainWindow.setTabOrder(self.precision_label, self.kernel_box)
MainWindow.setTabOrder(self.kernel_box, self.n_pc_label)
MainWindow.setTabOrder(self.n_pc_label, self.matvec_box)
MainWindow.setTabOrder(self.matvec_box, self.r_label)
MainWindow.setTabOrder(self.r_label, self.maxiter_label)
MainWindow.setTabOrder(self.maxiter_label, self.restol_label)
MainWindow.setTabOrder(self.restol_label, self.execute_button)
MainWindow.setTabOrder(self.execute_button, self.export_settings)
MainWindow.setTabOrder(self.export_settings, self.import_settings)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "pyPCGA"))
self.export_settings.setText(_translate("MainWindow", "Export Settings"))
self.import_settings.setText(_translate("MainWindow", "Import Settings"))
self.execute_button.setText(_translate("MainWindow", "Execute"))
self.restart_button.setText(_translate("MainWindow", "Restart"))
self.check_button.setText(_translate("MainWindow", "Check"))
#self.progress_bar_label.setText(_translate("MainWindow", "Progress Bar"))
self.fname_label.setText(_translate("MainWindow", "File Name: Pumping History Identification"))
self.dimension_label.setText(_translate("MainWindow", "Dimensions:"))
self.module1_label.setText(_translate("MainWindow", "Module 1: Domain Parameters"))
self.x0_label.setText(_translate("MainWindow", "x0:"))
self.x0_box.setPlaceholderText(_translate("MainWindow", "0 ~ any real number"))
self.y0_label.setText(_translate("MainWindow", "y0:"))
self.y0_box.setPlaceholderText(_translate("MainWindow", "0 ~ any real number"))
self.z0_label.setText(_translate("MainWindow", "z0:"))
self.z0_box.setPlaceholderText(_translate("MainWindow", "0 ~ any real number"))
self.lx_label.setText(_translate("MainWindow", "Lx:"))
self.lx_box.setPlaceholderText(_translate("MainWindow", "0 ~ any real number"))
self.ly_label.setText(_translate("MainWindow", "Ly:"))
self.ly_box.setPlaceholderText(_translate("MainWindow", "0 ~ any real number"))
self.lz_label.setText(_translate("MainWindow", "Lz:"))
self.lz_box.setPlaceholderText(_translate("MainWindow", "0 ~ any real number"))
self.dxx_label.setText(_translate("MainWindow", "dxx:"))
self.dxx_box.setPlaceholderText(_translate("MainWindow", "0 - 200"))
self.dyy_label.setText(_translate("MainWindow", "dyy:"))
self.dyy_box.setPlaceholderText(_translate("MainWindow", "0 - 200"))
self.dzz_label.setText(_translate("MainWindow", "dzz:"))
self.dz_box.setPlaceholderText(_translate("MainWindow", "0 - 200"))
self.s_true_label.setText(_translate("MainWindow", "s_true:"))
self.s_true_button.setText(_translate("MainWindow", "Select File"))
#self.n_module3_label.setText(_translate("MainWindow", "N:"))
#self.m_output_label.setText(_translate("MainWindow", "M:"))
self.s_init_box.setText(_translate("MainWindow", "Select File"))
self.s_init_label.setText(_translate("MainWindow", "s_init:"))
self.module2_label.setText(_translate("MainWindow", "Module 2: Forward Model Parameters"))
self.forward_model.setItemText(0, _translate("MainWindow", "MODFLOW"))
self.forward_model.setItemText(1, _translate("MainWindow", "Matrix"))
self.forward_model.setItemText(2, _translate("MainWindow", "Tough"))
self.source_label.setText(_translate("MainWindow", "source:"))
self.forward_model_label.setText(_translate("MainWindow", "forward_model:"))
self.log_label.setText(_translate("MainWindow", "log:"))
self.source_button.setText(_translate("MainWindow", "Select File"))
self.module3_label.setText(_translate("MainWindow", "Module 3: Observations"))
self.n_module3_label.setText(_translate("MainWindow", "n:"))
self.obs_label.setText(_translate("MainWindow", "Obs:"))
self.Obs_button.setText(_translate("MainWindow", "Select File"))
self.module4_label.setText(_translate("MainWindow", "Module 4: Inversion Parameters"))
self.x_module4_label.setText(_translate("MainWindow", "x:"))
self.x_select.setItemText(0, _translate("MainWindow", "Unit"))
self.x_select.setItemText(1, _translate("MainWindow", "Constant"))
self.x_select.setItemText(2, _translate("MainWindow", "Linear"))
self.lambda_x_label.setText(_translate("MainWindow", "λx:"))
self.kernel_label.setText(_translate("MainWindow", "kernel:"))
self.kernel_box.setItemText(0, _translate("MainWindow", "Gaussian"))
self.kernel_box.setItemText(1, _translate("MainWindow", "Exponential"))
self.n_pc_label.setText(_translate("MainWindow", "n pc:"))
self.matvec_label.setText(_translate("MainWindow", "matvec:"))
self.matvec_box.setItemText(0, _translate("MainWindow", "FFT"))
self.matvec_box.setItemText(1, _translate("MainWindow", "Dense"))
self.matvec_box.setItemText(2, _translate("MainWindow", "Hmatrix"))
self.matvec_box.setItemText(3, _translate("MainWindow", "FMM"))
self.prior_std_label.setText(_translate("MainWindow", "prior_std"))
self.maxiter_label.setText(_translate("MainWindow", "maxiter:"))
self.restol_label.setText(_translate("MainWindow", "restol:"))
self.lm_label.setText(_translate("MainWindow", "LM:"))
self.linesearch_label.setText(_translate("MainWindow", "Linesearch:"))
self.menupyPCGA.setTitle(_translate("MainWindow", "File"))
self.actionNew.setText(_translate("MainWindow", "New"))
self.actionSave.setText(_translate("MainWindow", "Save"))
self.actionDownload.setText(_translate("MainWindow", "Download"))
self.actionImport.setText(_translate("MainWindow", "Import")) | from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("pyPCGA")
MainWindow.resize(1440, 855)
#----------------------------------------------
# Setting the frame
#----------------------------------------------
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.frame = QtWidgets.QFrame(self.centralwidget)
self.frame.setGeometry(QtCore.QRect(730, 20, 701, 511))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.frame.setFont(font)
self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.frame.setObjectName("frame")
self.layoutWidget = QtWidgets.QWidget(self.centralwidget)
self.layoutWidget.setGeometry(QtCore.QRect(730, 545, 701, 91))
self.layoutWidget.setObjectName("layoutWidget")
self.gridLayout_6 = QtWidgets.QGridLayout(self.layoutWidget)
self.gridLayout_6.setContentsMargins(0, 0, 0, 0)
self.gridLayout_6.setObjectName("gridLayout_6")
self.export_settings = QtWidgets.QPushButton(self.layoutWidget)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.export_settings.setFont(font)
self.export_settings.setObjectName("export_settings")
self.gridLayout_6.addWidget(self.export_settings, 0, 1, 1, 1)
self.import_settings = QtWidgets.QPushButton(self.layoutWidget)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.import_settings.setFont(font)
self.import_settings.setObjectName("import_settings")
self.gridLayout_6.addWidget(self.import_settings, 0, 2, 1, 1)
self.execute_button = QtWidgets.QPushButton(self.layoutWidget)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.execute_button.setFont(font)
self.execute_button.setObjectName("execute_button")
self.gridLayout_6.addWidget(self.execute_button, 0, 0, 1, 1)
#----------------------------------------------
# added an execute button
#----------------------------------------------
# self.execute_button.clicked.connect(self.execute)
#----------------------------------------------
# restart button
#----------------------------------------------
self.restart_button = QtWidgets.QPushButton(self.layoutWidget)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.restart_button.setFont(font)
self.restart_button.setObjectName("restart_button")
self.gridLayout_6.addWidget(self.restart_button, 1, 1, 1, 1)
# self.restart_button.clicked.connect(self.restartFunction)
#----------------------------------------------
# check values button
#----------------------------------------------
self.check_button = QtWidgets.QPushButton(self.layoutWidget)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.check_button.setFont(font)
self.check_button.setObjectName("check_button")
self.gridLayout_6.addWidget(self.check_button, 1, 0, 1, 1)
# self.check_button.clicked.connect(self.switchFunction)
#----------------------------------------------
# Setting object names and sizing for main frame labels
#----------------------------------------------
self.fname_label = QtWidgets.QLabel(self.centralwidget)
self.fname_label.setGeometry(QtCore.QRect(11, 60, 400, 16))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.fname_label.setFont(font)
self.fname_label.setObjectName("fname_label")
self.dimension_label = QtWidgets.QLabel(self.centralwidget)
self.dimension_label.setGeometry(QtCore.QRect(569, 60, 72, 16))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.dimension_label.setFont(font)
self.dimension_label.setObjectName("dimension_label")
self.dim_box = QtWidgets.QSpinBox(self.centralwidget)
self.dim_box.setGeometry(QtCore.QRect(651, 60, 39, 24))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.dim_box.setFont(font)
self.dim_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly|QtCore.Qt.ImhPreferNumbers)
self.dim_box.setMaximum(0)
self.dim_box.setObjectName("dim_box")
self.module1_label = QtWidgets.QLabel(self.centralwidget)
self.module1_label.setGeometry(QtCore.QRect(11, 94, 691, 16))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(16)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.module1_label.setFont(font)
self.module1_label.setAutoFillBackground(False)
self.module1_label.setObjectName("module1_label")
#----------------------------------------------
# Setting Module 1's frame and grid layout
#----------------------------------------------
self.Module1Frame = QtWidgets.QFrame(self.centralwidget)
self.Module1Frame.setGeometry(QtCore.QRect(11, 114, 691, 181))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.Module1Frame.setFont(font)
self.Module1Frame.setAutoFillBackground(True)
self.Module1Frame.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.Module1Frame.setFrameShadow(QtWidgets.QFrame.Raised)
self.Module1Frame.setObjectName("Module1Frame")
self.gridLayout = QtWidgets.QGridLayout(self.Module1Frame)
self.gridLayout.setObjectName("gridLayout")
#----------------------------------------------
# Module 1 labels and boxes start here
#----------------------------------------------
self.x0_label = QtWidgets.QLabel(self.Module1Frame)
self.x0_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.x0_label.setFont(font)
self.x0_label.setObjectName("x0_label")
self.gridLayout.addWidget(self.x0_label, 0, 0, 1, 1)
self.x0_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.x0_box.sizePolicy().hasHeightForWidth())
self.x0_box.setSizePolicy(sizePolicy)
self.x0_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.x0_box.setFont(font)
self.x0_box.setAcceptDrops(True)
self.x0_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.x0_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.x0_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.x0_box.setTabStopWidth(5)
self.x0_box.setObjectName("x0_box")
self.gridLayout.addWidget(self.x0_box, 0, 1, 1, 1)
self.y0_label = QtWidgets.QLabel(self.Module1Frame)
self.y0_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.y0_label.setFont(font)
self.y0_label.setObjectName("y0_label")
self.gridLayout.addWidget(self.y0_label, 0, 2, 1, 1)
self.y0_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.y0_box.sizePolicy().hasHeightForWidth())
self.y0_box.setSizePolicy(sizePolicy)
self.y0_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.y0_box.setFont(font)
self.y0_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.y0_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.y0_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.y0_box.setObjectName("y0_box")
self.gridLayout.addWidget(self.y0_box, 0, 3, 1, 1)
self.z0_label = QtWidgets.QLabel(self.Module1Frame)
self.z0_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.z0_label.setFont(font)
self.z0_label.setObjectName("z0_label")
self.gridLayout.addWidget(self.z0_label, 0, 4, 1, 1)
self.z0_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.z0_box.sizePolicy().hasHeightForWidth())
self.z0_box.setSizePolicy(sizePolicy)
self.z0_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.z0_box.setFont(font)
self.z0_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.z0_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.z0_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.z0_box.setObjectName("z0_box")
self.gridLayout.addWidget(self.z0_box, 0, 5, 1, 1)
self.lx_label = QtWidgets.QLabel(self.Module1Frame)
self.lx_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.lx_label.setFont(font)
self.lx_label.setObjectName("lx_label")
self.gridLayout.addWidget(self.lx_label, 1, 0, 1, 1)
self.lx_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lx_box.sizePolicy().hasHeightForWidth())
self.lx_box.setSizePolicy(sizePolicy)
self.lx_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.lx_box.setFont(font)
self.lx_box.setAcceptDrops(True)
self.lx_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.lx_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.lx_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.lx_box.setTabStopWidth(5)
self.lx_box.setObjectName("lx_box")
self.gridLayout.addWidget(self.lx_box, 1, 1, 1, 1)
self.ly_label = QtWidgets.QLabel(self.Module1Frame)
self.ly_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.ly_label.setFont(font)
self.ly_label.setObjectName("ly_label")
self.gridLayout.addWidget(self.ly_label, 1, 2, 1, 1)
self.ly_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.ly_box.sizePolicy().hasHeightForWidth())
self.ly_box.setSizePolicy(sizePolicy)
self.ly_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.ly_box.setFont(font)
self.ly_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.ly_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.ly_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.ly_box.setObjectName("ly_box")
self.gridLayout.addWidget(self.ly_box, 1, 3, 1, 1)
self.lz_label = QtWidgets.QLabel(self.Module1Frame)
self.lz_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.lz_label.setFont(font)
self.lz_label.setObjectName("lz_label")
self.gridLayout.addWidget(self.lz_label, 1, 4, 1, 1)
self.lz_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.lz_box.sizePolicy().hasHeightForWidth())
self.lz_box.setSizePolicy(sizePolicy)
self.lz_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.lz_box.setFont(font)
self.lz_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.lz_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.lz_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.lz_box.setObjectName("lz_box")
self.gridLayout.addWidget(self.lz_box, 1, 5, 1, 1)
self.dxx_label = QtWidgets.QLabel(self.Module1Frame)
self.dxx_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.dxx_label.setFont(font)
self.dxx_label.setObjectName("dxx_label")
self.gridLayout.addWidget(self.dxx_label, 2, 0, 1, 1)
self.dxx_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.dxx_box.sizePolicy().hasHeightForWidth())
self.dxx_box.setSizePolicy(sizePolicy)
self.dxx_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.dxx_box.setFont(font)
self.dxx_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.dxx_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.dxx_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.dxx_box.setObjectName("dxx_box")
self.gridLayout.addWidget(self.dxx_box, 2, 1, 1, 1)
self.dyy_label = QtWidgets.QLabel(self.Module1Frame)
self.dyy_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.dyy_label.setFont(font)
self.dyy_label.setObjectName("dyy_label")
self.gridLayout.addWidget(self.dyy_label, 2, 2, 1, 1)
self.dyy_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.dyy_box.sizePolicy().hasHeightForWidth())
self.dyy_box.setSizePolicy(sizePolicy)
self.dyy_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.dyy_box.setFont(font)
self.dyy_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.dyy_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.dyy_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.dyy_box.setObjectName("dyy_box")
self.gridLayout.addWidget(self.dyy_box, 2, 3, 1, 1)
self.dzz_label = QtWidgets.QLabel(self.Module1Frame)
self.dzz_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.dzz_label.setFont(font)
self.dzz_label.setObjectName("dzz_label")
self.gridLayout.addWidget(self.dzz_label, 2, 4, 1, 1)
self.dz_box = QtWidgets.QTextEdit(self.Module1Frame)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.dz_box.sizePolicy().hasHeightForWidth())
self.dz_box.setSizePolicy(sizePolicy)
self.dz_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.dz_box.setFont(font)
self.dz_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
self.dz_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.dz_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.dz_box.setObjectName("dz_box")
self.gridLayout.addWidget(self.dz_box, 2, 5, 1, 1)
self.s_true_label = QtWidgets.QLabel(self.Module1Frame)
self.s_true_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.s_true_label.setFont(font)
self.s_true_label.setObjectName("s_true_label")
self.gridLayout.addWidget(self.s_true_label, 3, 0, 1, 1)
#
self.s_true_button = QtWidgets.QToolButton(self.Module1Frame)
self.s_true_button.setMinimumSize(QtCore.QSize(130, 25))
self.s_true_button.setMaximumSize(QtCore.QSize(130, 25))
self.s_true_button.setPopupMode(QtWidgets.QToolButton.DelayedPopup)
self.s_true_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
self.s_true_button.setAutoRaise(True)
self.s_true_button.setObjectName("s_true_button")
self.gridLayout.addWidget(self.s_true_button, 3, 1, 1, 1)
# self.s_true_button.clicked.connect(self.openFileNameDialog)
# self.m_output_label = QtWidgets.QLabel(self.Module1Frame)
# self.m_output_label.setMaximumSize(QtCore.QSize(50, 20))
# font = QtGui.QFont()
# font.setFamily("Helvetica")
# font.setPointSize(15)
# self.m_output_label.setFont(font)
# self.m_output_label.setObjectName("m_output_label")
# self.gridLayout.addWidget(self.m_output_label, 4, 2, 1, 1)
# self.m_output = QtWidgets.QLabel(self.Module1Frame)
# self.m_output.setMaximumSize(QtCore.QSize(130, 25))
# font = QtGui.QFont()
# font.setFamily("Helvetica")
# font.setPointSize(15)
# self.m_output.setFont(font)
# self.m_output.setText("")
# self.m_output.setObjectName("m_output")
# self.gridLayout.addWidget(self.m_output, 4, 3, 1, 1)
# self.s_init_box = QtWidgets.QTextEdit(self.Module1Frame)
# sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
# sizePolicy.setHorizontalStretch(0)
# sizePolicy.setVerticalStretch(0)
# sizePolicy.setHeightForWidth(self.s_init_box.sizePolicy().hasHeightForWidth())
# self.s_init_box.setSizePolicy(sizePolicy)
# self.s_init_box.setMaximumSize(QtCore.QSize(130, 25))
# font = QtGui.QFont()
# font.setFamily("Helvetica")
# self.s_init_box.setFont(font)
# self.s_init_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly)
# self.s_init_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
# self.s_init_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
# self.s_init_box.setObjectName("s_init_box")
self.s_init_box = QtWidgets.QToolButton(self.Module1Frame)
self.s_init_box.setMinimumSize(QtCore.QSize(130, 25))
self.s_init_box.setMaximumSize(QtCore.QSize(130, 25))
self.s_init_box.setPopupMode(QtWidgets.QToolButton.DelayedPopup)
self.s_init_box.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
self.s_init_box.setAutoRaise(True)
self.s_init_box.setObjectName("s_init_box")
self.gridLayout.addWidget(self.s_init_box, 4, 1, 1, 1)
# self.s_init_box.clicked.connect(self.openFileNameDialog)
self.s_init_label = QtWidgets.QLabel(self.Module1Frame)
self.s_init_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.s_init_label.setFont(font)
self.s_init_label.setObjectName("s_init_label")
self.gridLayout.addWidget(self.s_init_label, 4, 0, 1, 1)
self.fname_output = QtWidgets.QLabel(self.centralwidget)
self.fname_output.setGeometry(QtCore.QRect(11, 150, 16, 16))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.fname_output.setFont(font)
self.fname_output.setText("")
self.fname_output.setObjectName("fname_output")
#----------------------------------------------
# Setting Module 2's labels and boxes
#----------------------------------------------
self.module2_label = QtWidgets.QLabel(self.centralwidget)
# Adjusted to fix bleed issue
self.module2_label.setGeometry(QtCore.QRect(11, 311, 300, 16))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(16)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.module2_label.setFont(font)
self.module2_label.setAutoFillBackground(False)
self.module2_label.setWordWrap(False)
self.module2_label.setObjectName("module2_label")
self.Module1Frame_2 = QtWidgets.QFrame(self.centralwidget)
self.Module1Frame_2.setGeometry(QtCore.QRect(11, 343, 689, 80))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.Module1Frame_2.setFont(font)
self.Module1Frame_2.setAutoFillBackground(True)
self.Module1Frame_2.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.Module1Frame_2.setFrameShadow(QtWidgets.QFrame.Raised)
self.Module1Frame_2.setObjectName("Module1Frame_2")
self.forward_model = QtWidgets.QComboBox(self.Module1Frame_2)
self.forward_model.setGeometry(QtCore.QRect(164, 11, 123, 25))
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.forward_model.sizePolicy().hasHeightForWidth())
self.forward_model.setSizePolicy(sizePolicy)
self.forward_model.setMaximumSize(QtCore.QSize(200, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.forward_model.setFont(font)
self.forward_model.setObjectName("forward_model")
self.forward_model.addItem("")
self.forward_model.addItem("")
self.forward_model.addItem("")
self.source_label = QtWidgets.QLabel(self.Module1Frame_2)
self.source_label.setGeometry(QtCore.QRect(13, 42, 50, 16))
self.source_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.source_label.setFont(font)
self.source_label.setObjectName("source_label")
self.forward_model_label = QtWidgets.QLabel(self.Module1Frame_2)
self.forward_model_label.setGeometry(QtCore.QRect(13, 13, 104, 16))
self.forward_model_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.forward_model_label.setFont(font)
self.forward_model_label.setObjectName("forward_model_label")
self.log_check = QtWidgets.QCheckBox(self.Module1Frame_2)
self.log_check.setGeometry(QtCore.QRect(605, 14, 19, 18))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.log_check.setFont(font)
self.log_check.setText("")
self.log_check.setObjectName("log_check")
self.log_label = QtWidgets.QLabel(self.Module1Frame_2)
self.log_label.setGeometry(QtCore.QRect(530, 13, 25, 16))
self.log_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.log_label.setFont(font)
self.log_label.setObjectName("log_label")
self.source_button = QtWidgets.QToolButton(self.Module1Frame_2)
self.source_button.setGeometry(QtCore.QRect(90, 42, 200, 25))
self.source_button.setMinimumSize(QtCore.QSize(130, 25))
self.source_button.setMaximumSize(QtCore.QSize(130, 25))
self.source_button.setPopupMode(QtWidgets.QToolButton.DelayedPopup)
self.source_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
self.source_button.setAutoRaise(True)
self.source_button.setObjectName("source_button")
#----------------------------------------------
# Setting Module 3's labels and boxes
#----------------------------------------------
self.module3_label = QtWidgets.QLabel(self.centralwidget)
self.module3_label.setGeometry(QtCore.QRect(11, 439, 691, 16))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(16)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.module3_label.setFont(font)
self.module3_label.setAutoFillBackground(False)
self.module3_label.setObjectName("module3_label")
self.Module1Frame_3 = QtWidgets.QFrame(self.centralwidget)
self.Module1Frame_3.setGeometry(QtCore.QRect(11, 471, 691, 86))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.Module1Frame_3.setFont(font)
self.Module1Frame_3.setAutoFillBackground(True)
self.Module1Frame_3.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.Module1Frame_3.setFrameShadow(QtWidgets.QFrame.Raised)
self.Module1Frame_3.setObjectName("Module1Frame_3")
self.gridLayout_3 = QtWidgets.QGridLayout(self.Module1Frame_3)
self.gridLayout_3.setObjectName("gridLayout_3")
self.n_module3_label = QtWidgets.QLabel(self.Module1Frame_3)
self.n_module3_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.n_module3_label.setFont(font)
self.n_module3_label.setObjectName("n_module3_label")
self.gridLayout_3.addWidget(self.n_module3_label, 0, 2, 1, 1)
self.obs_label = QtWidgets.QLabel(self.Module1Frame_3)
self.obs_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.obs_label.setFont(font)
self.obs_label.setObjectName("obs_label")
# Fix Grid positioning for the label and the box
self.gridLayout_3.addWidget(self.obs_label, 0, 0, 0, 0)
self.Obs_button = QtWidgets.QToolButton(self.Module1Frame_3)
self.Obs_button.setMinimumSize(QtCore.QSize(130, 25))
self.Obs_button.setMaximumSize(QtCore.QSize(130, 25))
self.Obs_button.setPopupMode(QtWidgets.QToolButton.DelayedPopup)
self.Obs_button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
self.Obs_button.setAutoRaise(True)
self.Obs_button.setObjectName("Obs_button")
self.gridLayout_3.addWidget(self.Obs_button, 0, 0, 0, 0)
# self.Obs_button.clicked.connect(self.openFileNameDialog)
#----------------------------------------------
# Setting Module 4's labels and boxes
#----------------------------------------------
self.module4_label = QtWidgets.QLabel(self.centralwidget)
self.module4_label.setGeometry(QtCore.QRect(11, 573, 241, 16))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(16)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
self.module4_label.setFont(font)
self.module4_label.setAutoFillBackground(False)
self.module4_label.setObjectName("module4_label")
self.Module1Frame_4 = QtWidgets.QFrame(self.centralwidget)
self.Module1Frame_4.setGeometry(QtCore.QRect(11, 605, 691, 156))
self.Module1Frame_4.setMaximumSize(QtCore.QSize(700, 180))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.Module1Frame_4.setFont(font)
self.Module1Frame_4.setAutoFillBackground(True)
self.Module1Frame_4.setFrameShape(QtWidgets.QFrame.StyledPanel)
self.Module1Frame_4.setFrameShadow(QtWidgets.QFrame.Raised)
self.Module1Frame_4.setObjectName("Module1Frame_4")
self.gridLayout_4 = QtWidgets.QGridLayout(self.Module1Frame_4)
self.gridLayout_4.setObjectName("gridLayout_4")
self.x_module4_label = QtWidgets.QLabel(self.Module1Frame_4)
self.x_module4_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.x_module4_label.setFont(font)
self.x_module4_label.setObjectName("x_module4_label")
self.gridLayout_4.addWidget(self.x_module4_label, 0, 0, 1, 1)
self.x_select = QtWidgets.QComboBox(self.Module1Frame_4)
self.x_select.setMaximumSize(QtCore.QSize(130, 30))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.x_select.setFont(font)
self.x_select.setObjectName("x_select")
self.x_select.addItem("")
self.x_select.addItem("")
self.x_select.addItem("")
self.gridLayout_4.addWidget(self.x_select, 0, 1, 1, 1)
self.lambda_x_label = QtWidgets.QLabel(self.Module1Frame_4)
self.lambda_x_label.setMaximumSize(QtCore.QSize(80, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.lambda_x_label.setFont(font)
self.lambda_x_label.setObjectName("lambda_x_label")
self.gridLayout_4.addWidget(self.lambda_x_label, 0, 2, 1, 1)
self.precision_label = QtWidgets.QTextEdit(self.Module1Frame_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.precision_label.sizePolicy().hasHeightForWidth())
self.precision_label.setSizePolicy(sizePolicy)
self.precision_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.precision_label.setFont(font)
self.precision_label.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.precision_label.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.precision_label.setObjectName("precision_label")
self.gridLayout_4.addWidget(self.precision_label, 0, 3, 1, 1)
self.kernel_label = QtWidgets.QLabel(self.Module1Frame_4)
self.kernel_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.kernel_label.setFont(font)
self.kernel_label.setObjectName("kernel_label")
self.gridLayout_4.addWidget(self.kernel_label, 0, 4, 1, 1)
self.kernel_box = QtWidgets.QComboBox(self.Module1Frame_4)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.kernel_box.setFont(font)
self.kernel_box.setObjectName("kernel_box")
self.kernel_box.addItem("")
self.kernel_box.addItem("")
self.gridLayout_4.addWidget(self.kernel_box, 0, 5, 1, 2)
self.n_pc_label = QtWidgets.QLabel(self.Module1Frame_4)
self.n_pc_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.n_pc_label.setFont(font)
self.n_pc_label.setObjectName("n_pc_label")
self.gridLayout_4.addWidget(self.n_pc_label, 1, 0, 1, 1)
self.n_pc_box = QtWidgets.QTextEdit(self.Module1Frame_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.n_pc_box.sizePolicy().hasHeightForWidth())
self.n_pc_box.setSizePolicy(sizePolicy)
self.n_pc_box.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.n_pc_box.setFont(font)
self.n_pc_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.n_pc_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.n_pc_box.setObjectName("n_pc_box")
self.gridLayout_4.addWidget(self.n_pc_box, 1, 1, 1, 1)
self.matvec_label = QtWidgets.QLabel(self.Module1Frame_4)
self.matvec_label.setMaximumSize(QtCore.QSize(80, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.matvec_label.setFont(font)
self.matvec_label.setObjectName("matvec_label")
self.gridLayout_4.addWidget(self.matvec_label, 1, 2, 1, 1)
self.matvec_box = QtWidgets.QComboBox(self.Module1Frame_4)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.matvec_box.setFont(font)
self.matvec_box.setObjectName("matvec_box")
self.matvec_box.addItem("")
self.matvec_box.addItem("")
self.matvec_box.addItem("")
self.matvec_box.addItem("")
self.gridLayout_4.addWidget(self.matvec_box, 1, 3, 1, 1)
self.prior_std_label = QtWidgets.QLabel(self.Module1Frame_4)
self.prior_std_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.prior_std_label.setFont(font)
self.prior_std_label.setObjectName("prior_std_label")
self.gridLayout_4.addWidget(self.prior_std_label, 2, 0, 1, 1)
self.r_label = QtWidgets.QTextEdit(self.Module1Frame_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.r_label.sizePolicy().hasHeightForWidth())
self.r_label.setSizePolicy(sizePolicy)
self.r_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.r_label.setFont(font)
self.r_label.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.r_label.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.r_label.setObjectName("r_label")
self.gridLayout_4.addWidget(self.r_label, 2, 1, 1, 1)
self.maxiter_label = QtWidgets.QLabel(self.Module1Frame_4)
self.maxiter_label.setMaximumSize(QtCore.QSize(80, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.maxiter_label.setFont(font)
self.maxiter_label.setObjectName("maxiter_label")
self.gridLayout_4.addWidget(self.maxiter_label, 2, 2, 1, 1)
self.maxiter_label = QtWidgets.QTextEdit(self.Module1Frame_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.maxiter_label.sizePolicy().hasHeightForWidth())
self.maxiter_label.setSizePolicy(sizePolicy)
self.maxiter_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.maxiter_label.setFont(font)
self.maxiter_label.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.maxiter_label.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.maxiter_label.setObjectName("maxiter_label")
self.gridLayout_4.addWidget(self.maxiter_label, 2, 3, 1, 1)
self.restol_label = QtWidgets.QLabel(self.Module1Frame_4)
self.restol_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.restol_label.setFont(font)
self.restol_label.setObjectName("restol_label")
self.gridLayout_4.addWidget(self.restol_label, 2, 4, 1, 1)
self.restol_label = QtWidgets.QTextEdit(self.Module1Frame_4)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.restol_label.sizePolicy().hasHeightForWidth())
self.restol_label.setSizePolicy(sizePolicy)
self.restol_label.setMaximumSize(QtCore.QSize(130, 25))
font = QtGui.QFont()
font.setFamily("Helvetica")
self.restol_label.setFont(font)
self.restol_label.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.restol_label.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.restol_label.setObjectName("restol_label")
self.gridLayout_4.addWidget(self.restol_label, 2, 5, 1, 2)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.lm_label = QtWidgets.QLabel(self.Module1Frame_4)
self.lm_label.setMaximumSize(QtCore.QSize(50, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.lm_label.setFont(font)
self.lm_label.setObjectName("lm_label")
self.gridLayout_4.addWidget(self.lm_label, 3, 2, 1, 1)
self.lm_check = QtWidgets.QCheckBox(self.Module1Frame_4)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.lm_check.setFont(font)
self.lm_check.setText("")
self.lm_check.setObjectName("lm_check")
self.gridLayout_4.addWidget(self.lm_check, 3, 3, 1, 1)
self.linesearch_label = QtWidgets.QLabel(self.Module1Frame_4)
self.linesearch_label.setMaximumSize(QtCore.QSize(150, 20))
font = QtGui.QFont()
font.setFamily("Helvetica")
font.setPointSize(15)
self.linesearch_label.setFont(font)
self.linesearch_label.setObjectName("linesearch_label")
self.gridLayout_4.addWidget(self.linesearch_label, 3, 4, 1, 2)
self.line_search = QtWidgets.QCheckBox(self.Module1Frame_4)
font = QtGui.QFont()
font.setFamily("Helvetica")
self.line_search.setFont(font)
self.line_search.setText("")
self.line_search.setObjectName("line_search")
self.gridLayout_4.addWidget(self.line_search, 3, 6, 1, 1)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1440, 22))
self.menubar.setObjectName("menubar")
self.menupyPCGA = QtWidgets.QMenu(self.menubar)
self.menupyPCGA.setObjectName("menupyPCGA")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.actionNew = QtWidgets.QAction(MainWindow)
self.actionNew.setObjectName("actionNew")
self.actionSave = QtWidgets.QAction(MainWindow)
self.actionSave.setObjectName("actionSave")
self.actionDownload = QtWidgets.QAction(MainWindow)
self.actionDownload.setObjectName("actionDownload")
self.actionImport = QtWidgets.QAction(MainWindow)
self.actionImport.setObjectName("actionImport")
self.menupyPCGA.addAction(self.actionNew)
self.menupyPCGA.addAction(self.actionSave)
self.menupyPCGA.addAction(self.actionDownload)
self.menupyPCGA.addAction(self.actionImport)
self.menubar.addAction(self.menupyPCGA.menuAction())
#----------------------------------------------
# Setting the graphing frames
#----------------------------------------------
self.frame = QtWidgets.QWidget(self.centralwidget)
self.frame.setGeometry(QtCore.QRect(760, 30, 651, 511))
self.frame.setObjectName("frame")
self.fig, self.axs = plt.subplots(2, constrained_layout=True)
self.plotWidget = FigureCanvas(self.fig)
self.plotWidget.setParent(self.frame)
#----------------------------------------------
# Calls retranslateUi
#----------------------------------------------
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
MainWindow.setTabOrder(self.lx_box, self.ly_box)
MainWindow.setTabOrder(self.ly_box, self.lz_box)
MainWindow.setTabOrder(self.lz_box, self.dxx_box)
MainWindow.setTabOrder(self.dxx_box, self.dyy_box)
MainWindow.setTabOrder(self.dyy_box, self.dz_box)
# MainWindow.setTabOrder(self.dz_box, self.n_label)
# MainWindow.setTabOrder(self.n_label, self.nlocs_label)
MainWindow.setTabOrder(self.x_select, self.precision_label)
MainWindow.setTabOrder(self.precision_label, self.kernel_box)
MainWindow.setTabOrder(self.kernel_box, self.n_pc_label)
MainWindow.setTabOrder(self.n_pc_label, self.matvec_box)
MainWindow.setTabOrder(self.matvec_box, self.r_label)
MainWindow.setTabOrder(self.r_label, self.maxiter_label)
MainWindow.setTabOrder(self.maxiter_label, self.restol_label)
MainWindow.setTabOrder(self.restol_label, self.execute_button)
MainWindow.setTabOrder(self.execute_button, self.export_settings)
MainWindow.setTabOrder(self.export_settings, self.import_settings)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "pyPCGA"))
self.export_settings.setText(_translate("MainWindow", "Export Settings"))
self.import_settings.setText(_translate("MainWindow", "Import Settings"))
self.execute_button.setText(_translate("MainWindow", "Execute"))
self.restart_button.setText(_translate("MainWindow", "Restart"))
self.check_button.setText(_translate("MainWindow", "Check"))
#self.progress_bar_label.setText(_translate("MainWindow", "Progress Bar"))
self.fname_label.setText(_translate("MainWindow", "File Name: Pumping History Identification"))
self.dimension_label.setText(_translate("MainWindow", "Dimensions:"))
self.module1_label.setText(_translate("MainWindow", "Module 1: Domain Parameters"))
self.x0_label.setText(_translate("MainWindow", "x0:"))
self.x0_box.setPlaceholderText(_translate("MainWindow", "0 ~ any real number"))
self.y0_label.setText(_translate("MainWindow", "y0:"))
self.y0_box.setPlaceholderText(_translate("MainWindow", "0 ~ any real number"))
self.z0_label.setText(_translate("MainWindow", "z0:"))
self.z0_box.setPlaceholderText(_translate("MainWindow", "0 ~ any real number"))
self.lx_label.setText(_translate("MainWindow", "Lx:"))
self.lx_box.setPlaceholderText(_translate("MainWindow", "0 ~ any real number"))
self.ly_label.setText(_translate("MainWindow", "Ly:"))
self.ly_box.setPlaceholderText(_translate("MainWindow", "0 ~ any real number"))
self.lz_label.setText(_translate("MainWindow", "Lz:"))
self.lz_box.setPlaceholderText(_translate("MainWindow", "0 ~ any real number"))
self.dxx_label.setText(_translate("MainWindow", "dxx:"))
self.dxx_box.setPlaceholderText(_translate("MainWindow", "0 - 200"))
self.dyy_label.setText(_translate("MainWindow", "dyy:"))
self.dyy_box.setPlaceholderText(_translate("MainWindow", "0 - 200"))
self.dzz_label.setText(_translate("MainWindow", "dzz:"))
self.dz_box.setPlaceholderText(_translate("MainWindow", "0 - 200"))
self.s_true_label.setText(_translate("MainWindow", "s_true:"))
self.s_true_button.setText(_translate("MainWindow", "Select File"))
#self.n_module3_label.setText(_translate("MainWindow", "N:"))
#self.m_output_label.setText(_translate("MainWindow", "M:"))
self.s_init_box.setText(_translate("MainWindow", "Select File"))
self.s_init_label.setText(_translate("MainWindow", "s_init:"))
self.module2_label.setText(_translate("MainWindow", "Module 2: Forward Model Parameters"))
self.forward_model.setItemText(0, _translate("MainWindow", "MODFLOW"))
self.forward_model.setItemText(1, _translate("MainWindow", "Matrix"))
self.forward_model.setItemText(2, _translate("MainWindow", "Tough"))
self.source_label.setText(_translate("MainWindow", "source:"))
self.forward_model_label.setText(_translate("MainWindow", "forward_model:"))
self.log_label.setText(_translate("MainWindow", "log:"))
self.source_button.setText(_translate("MainWindow", "Select File"))
self.module3_label.setText(_translate("MainWindow", "Module 3: Observations"))
self.n_module3_label.setText(_translate("MainWindow", "n:"))
self.obs_label.setText(_translate("MainWindow", "Obs:"))
self.Obs_button.setText(_translate("MainWindow", "Select File"))
self.module4_label.setText(_translate("MainWindow", "Module 4: Inversion Parameters"))
self.x_module4_label.setText(_translate("MainWindow", "x:"))
self.x_select.setItemText(0, _translate("MainWindow", "Unit"))
self.x_select.setItemText(1, _translate("MainWindow", "Constant"))
self.x_select.setItemText(2, _translate("MainWindow", "Linear"))
self.lambda_x_label.setText(_translate("MainWindow", "λx:"))
self.kernel_label.setText(_translate("MainWindow", "kernel:"))
self.kernel_box.setItemText(0, _translate("MainWindow", "Gaussian"))
self.kernel_box.setItemText(1, _translate("MainWindow", "Exponential"))
self.n_pc_label.setText(_translate("MainWindow", "n pc:"))
self.matvec_label.setText(_translate("MainWindow", "matvec:"))
self.matvec_box.setItemText(0, _translate("MainWindow", "FFT"))
self.matvec_box.setItemText(1, _translate("MainWindow", "Dense"))
self.matvec_box.setItemText(2, _translate("MainWindow", "Hmatrix"))
self.matvec_box.setItemText(3, _translate("MainWindow", "FMM"))
self.prior_std_label.setText(_translate("MainWindow", "prior_std"))
self.maxiter_label.setText(_translate("MainWindow", "maxiter:"))
self.restol_label.setText(_translate("MainWindow", "restol:"))
self.lm_label.setText(_translate("MainWindow", "LM:"))
self.linesearch_label.setText(_translate("MainWindow", "Linesearch:"))
self.menupyPCGA.setTitle(_translate("MainWindow", "File"))
self.actionNew.setText(_translate("MainWindow", "New"))
self.actionSave.setText(_translate("MainWindow", "Save"))
self.actionDownload.setText(_translate("MainWindow", "Download"))
self.actionImport.setText(_translate("MainWindow", "Import")) | en | 0.157319 | #---------------------------------------------- # Setting the frame #---------------------------------------------- #---------------------------------------------- # added an execute button #---------------------------------------------- # self.execute_button.clicked.connect(self.execute) #---------------------------------------------- # restart button #---------------------------------------------- # self.restart_button.clicked.connect(self.restartFunction) #---------------------------------------------- # check values button #---------------------------------------------- # self.check_button.clicked.connect(self.switchFunction) #---------------------------------------------- # Setting object names and sizing for main frame labels #---------------------------------------------- #---------------------------------------------- # Setting Module 1's frame and grid layout #---------------------------------------------- #---------------------------------------------- # Module 1 labels and boxes start here #---------------------------------------------- # # self.s_true_button.clicked.connect(self.openFileNameDialog) # self.m_output_label = QtWidgets.QLabel(self.Module1Frame) # self.m_output_label.setMaximumSize(QtCore.QSize(50, 20)) # font = QtGui.QFont() # font.setFamily("Helvetica") # font.setPointSize(15) # self.m_output_label.setFont(font) # self.m_output_label.setObjectName("m_output_label") # self.gridLayout.addWidget(self.m_output_label, 4, 2, 1, 1) # self.m_output = QtWidgets.QLabel(self.Module1Frame) # self.m_output.setMaximumSize(QtCore.QSize(130, 25)) # font = QtGui.QFont() # font.setFamily("Helvetica") # font.setPointSize(15) # self.m_output.setFont(font) # self.m_output.setText("") # self.m_output.setObjectName("m_output") # self.gridLayout.addWidget(self.m_output, 4, 3, 1, 1) # self.s_init_box = QtWidgets.QTextEdit(self.Module1Frame) # sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) # sizePolicy.setHorizontalStretch(0) # sizePolicy.setVerticalStretch(0) # sizePolicy.setHeightForWidth(self.s_init_box.sizePolicy().hasHeightForWidth()) # self.s_init_box.setSizePolicy(sizePolicy) # self.s_init_box.setMaximumSize(QtCore.QSize(130, 25)) # font = QtGui.QFont() # font.setFamily("Helvetica") # self.s_init_box.setFont(font) # self.s_init_box.setInputMethodHints(QtCore.Qt.ImhDigitsOnly) # self.s_init_box.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) # self.s_init_box.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) # self.s_init_box.setObjectName("s_init_box") # self.s_init_box.clicked.connect(self.openFileNameDialog) #---------------------------------------------- # Setting Module 2's labels and boxes #---------------------------------------------- # Adjusted to fix bleed issue #---------------------------------------------- # Setting Module 3's labels and boxes #---------------------------------------------- # Fix Grid positioning for the label and the box # self.Obs_button.clicked.connect(self.openFileNameDialog) #---------------------------------------------- # Setting Module 4's labels and boxes #---------------------------------------------- #---------------------------------------------- # Setting the graphing frames #---------------------------------------------- #---------------------------------------------- # Calls retranslateUi #---------------------------------------------- # MainWindow.setTabOrder(self.dz_box, self.n_label) # MainWindow.setTabOrder(self.n_label, self.nlocs_label) #self.progress_bar_label.setText(_translate("MainWindow", "Progress Bar")) #self.n_module3_label.setText(_translate("MainWindow", "N:")) #self.m_output_label.setText(_translate("MainWindow", "M:")) | 2.453761 | 2 |
pj_13.py | luisalvaradoar/pj_euler | 0 | 6614224 | lista = '3710728753390210279879799822083759024651013574025046376937677490009712\
6481248969700780504170182605387432498619952474105947423330951305812372\
6617309629919422133635741615725224305633018110724061549082502306758820\
7539346171171980310421047513778063246676892616706966236338201363784183\
8368417873436172675728112879812849979408065481931592621691275889832738\
4427422891743252032192358942287679648767027218931847451445736001306439\
0911672168568445887116031532767038648610584302543993961982891759366568\
6757934951621764571418565606295021572231965867550793241933316490635246\
2741904929101432445813822663347944758178925758677183372176619637515905\
7923972824559883840758203565325359399008402633568948830189458628227828\
8018119938482628201427819413994056758715117009439035398664372827112653\
8299872407844730531901042935868651550600629586486153207527337195919142\
0517255829716938887077154664991155934876035329217149700569385437007057\
6826684624621495650076471787294438377604532826541087568284431911906346\
9403785521777929514536123272525000296071075082563815656710885258350721\
4587657617241097644733911060721826523687722363604517423706905851860660\
4482076212098132878607339694128114266041808683061932846081119106155694\
0512689692519343254517283886419180470492932150586425630494836246722164\
8435076201727918039944693004732956340691157324443869081257945140890577\
0622942919710792820955037687525678773091862540744969844508330393682126\
1833638482533015468619612434876768129753437594651580386287592878490201\
5216855548287172012192577669547818283375799310361474035685644909552709\
7864797581167263201004368978425535399209318374414978068609844840309812\
9077791799088218795327364475675590848030870869875513927118545170785441\
6185242432069315033259959406895756536782107074926966537676326235447210\
6979395067965269474259770973916669376304263398708541052684708299085211\
3994273657341161827603150012716537860736150108085700914993951255702819\
8746004375358290353174347173269321235781549826297425527373079495375976\
5105305946966067683156574377167401875275889028025717332296191766687138\
1993181104877019027125267680276078003013678680992525463401061632866526\
3627021854049770558562994658063623799314074625596224074486908231174977\
7923654662572469233228109171419143028819710328859780666976089293863828\
5025333403344130655780161278159218150055618688364684200904702305308117\
2816430487623791969842487255036638784583114876969321549028104240201383\
3512446218144177347063783299490636259666498587618221225225512486764533\
6772018697169854431241957240991395900895231005882295548255300263520781\
5322967962494816419538682187747608532713228572311042480345612486769706\
4507995236377742425354112916842768655389262050249103265729672370191327\
5725675285653248258265463092207058596522297988602722583319131263751473\
4199488953476574550118495701454879288984856827726077713721403798879715\
3829820378303147352772158034814451349137322665138134829543829199918180\
2789165224310273922511228695394095795306640523263253804410005965493915\
9879593635297461521855023713076422551211836938035803885849034169811622\
2072977186158236678424689157993532961922624679571944012690438771072750\
4810239089552359745723189706772547915061505504953922979530901129967519\
8618808822587531452958409925120382900940777077567211306739708304724483\
8165338735023408456470580773088295917476714036319800818712901187549131\
0547126581976233310448183862695154563349263665728975634005004284628018\
3517070527831839425882145521227251250327551216035469812005817621652128\
2765275169129689778932238195734329339946437501907836945765883352399886\
7550616496518477518073816883786109152735792970133762177842752192623401\
9423996391680449839931733127313292418570714734956691667468763466091503\
5914677504995186714302352196288948901024233251169136196266227326746080\
0591547471830798392868535206946944540724768418225246744171615140364279\
8227334805555621481897142617910342598647204516893989422179826088076852\
8778364618279934631376775430780936333301898264209010848802521674670883\
2151201858835432238128769527867132961247478246453863699300904931036361\
9763878039621840735723997942234062353938083396513274080111166662789198\
1488087797941876876144230030984490851411606618262936828367647447792391\
8033511098906979071485786944089552990653640447425576083659976645795096\
6602439640990538960712019821997604759949019723029764913982680032973156\
0371200413779037855660850892521673093931987275027546890690370753941304\
2652315011948093772450487951509541009216458637547105984367917863916702\
1187492431995700641917969777599028300699153687137119366149528113058763\
8027841075444973307840789923115535562561142322423255033685442488917353\
4488991150144064802036906806396067232219320414953541503128880339536053\
2993403680069777106505666319548123488067321014673905856855793458140362\
7822703280826165707739483275922328459417065250945123252306082291880205\
8777319719839450180888072429661980811197771585425020165450904132458097\
8688277894872185961772107838435069186155435662884062257473692284509516\
2084960398013400172393067166682355524525280460972253503534226472524250\
874054075591789781264330331690'
'''Ya que el string 'lista' tiene a todos los numeros de cincuenta digitos
concatenados, se recorre cada 50 el string para tomar cada numero
eso hace la parte [50 * (i - 1) : 50 * i], osea multiplos consecutivos de 50'''
suma = 0
for i in range(1,101):
suma += int(lista[50 * (i - 1) : 50 * i])
print(str(suma)[0:10]) | lista = '3710728753390210279879799822083759024651013574025046376937677490009712\
6481248969700780504170182605387432498619952474105947423330951305812372\
6617309629919422133635741615725224305633018110724061549082502306758820\
7539346171171980310421047513778063246676892616706966236338201363784183\
8368417873436172675728112879812849979408065481931592621691275889832738\
4427422891743252032192358942287679648767027218931847451445736001306439\
0911672168568445887116031532767038648610584302543993961982891759366568\
6757934951621764571418565606295021572231965867550793241933316490635246\
2741904929101432445813822663347944758178925758677183372176619637515905\
7923972824559883840758203565325359399008402633568948830189458628227828\
8018119938482628201427819413994056758715117009439035398664372827112653\
8299872407844730531901042935868651550600629586486153207527337195919142\
0517255829716938887077154664991155934876035329217149700569385437007057\
6826684624621495650076471787294438377604532826541087568284431911906346\
9403785521777929514536123272525000296071075082563815656710885258350721\
4587657617241097644733911060721826523687722363604517423706905851860660\
4482076212098132878607339694128114266041808683061932846081119106155694\
0512689692519343254517283886419180470492932150586425630494836246722164\
8435076201727918039944693004732956340691157324443869081257945140890577\
0622942919710792820955037687525678773091862540744969844508330393682126\
1833638482533015468619612434876768129753437594651580386287592878490201\
5216855548287172012192577669547818283375799310361474035685644909552709\
7864797581167263201004368978425535399209318374414978068609844840309812\
9077791799088218795327364475675590848030870869875513927118545170785441\
6185242432069315033259959406895756536782107074926966537676326235447210\
6979395067965269474259770973916669376304263398708541052684708299085211\
3994273657341161827603150012716537860736150108085700914993951255702819\
8746004375358290353174347173269321235781549826297425527373079495375976\
5105305946966067683156574377167401875275889028025717332296191766687138\
1993181104877019027125267680276078003013678680992525463401061632866526\
3627021854049770558562994658063623799314074625596224074486908231174977\
7923654662572469233228109171419143028819710328859780666976089293863828\
5025333403344130655780161278159218150055618688364684200904702305308117\
2816430487623791969842487255036638784583114876969321549028104240201383\
3512446218144177347063783299490636259666498587618221225225512486764533\
6772018697169854431241957240991395900895231005882295548255300263520781\
5322967962494816419538682187747608532713228572311042480345612486769706\
4507995236377742425354112916842768655389262050249103265729672370191327\
5725675285653248258265463092207058596522297988602722583319131263751473\
4199488953476574550118495701454879288984856827726077713721403798879715\
3829820378303147352772158034814451349137322665138134829543829199918180\
2789165224310273922511228695394095795306640523263253804410005965493915\
9879593635297461521855023713076422551211836938035803885849034169811622\
2072977186158236678424689157993532961922624679571944012690438771072750\
4810239089552359745723189706772547915061505504953922979530901129967519\
8618808822587531452958409925120382900940777077567211306739708304724483\
8165338735023408456470580773088295917476714036319800818712901187549131\
0547126581976233310448183862695154563349263665728975634005004284628018\
3517070527831839425882145521227251250327551216035469812005817621652128\
2765275169129689778932238195734329339946437501907836945765883352399886\
7550616496518477518073816883786109152735792970133762177842752192623401\
9423996391680449839931733127313292418570714734956691667468763466091503\
5914677504995186714302352196288948901024233251169136196266227326746080\
0591547471830798392868535206946944540724768418225246744171615140364279\
8227334805555621481897142617910342598647204516893989422179826088076852\
8778364618279934631376775430780936333301898264209010848802521674670883\
2151201858835432238128769527867132961247478246453863699300904931036361\
9763878039621840735723997942234062353938083396513274080111166662789198\
1488087797941876876144230030984490851411606618262936828367647447792391\
8033511098906979071485786944089552990653640447425576083659976645795096\
6602439640990538960712019821997604759949019723029764913982680032973156\
0371200413779037855660850892521673093931987275027546890690370753941304\
2652315011948093772450487951509541009216458637547105984367917863916702\
1187492431995700641917969777599028300699153687137119366149528113058763\
8027841075444973307840789923115535562561142322423255033685442488917353\
4488991150144064802036906806396067232219320414953541503128880339536053\
2993403680069777106505666319548123488067321014673905856855793458140362\
7822703280826165707739483275922328459417065250945123252306082291880205\
8777319719839450180888072429661980811197771585425020165450904132458097\
8688277894872185961772107838435069186155435662884062257473692284509516\
2084960398013400172393067166682355524525280460972253503534226472524250\
874054075591789781264330331690'
'''Ya que el string 'lista' tiene a todos los numeros de cincuenta digitos
concatenados, se recorre cada 50 el string para tomar cada numero
eso hace la parte [50 * (i - 1) : 50 * i], osea multiplos consecutivos de 50'''
suma = 0
for i in range(1,101):
suma += int(lista[50 * (i - 1) : 50 * i])
print(str(suma)[0:10]) | es | 0.908887 | Ya que el string 'lista' tiene a todos los numeros de cincuenta digitos concatenados, se recorre cada 50 el string para tomar cada numero eso hace la parte [50 * (i - 1) : 50 * i], osea multiplos consecutivos de 50 | 1.618857 | 2 |
app.py | m0by314/raspberry_pi_home_security_system | 9 | 6614225 | #!/usr/bin/env python
"""
Home surveillance application
"""
import time
from lib.camera import Camera
from lib.telebot import Telebot
from lib.pir import MotionDetector
from config import TOKEN_ID, REGISTRATION_FOLDER, VIDEO_TIME, CHAT_ID
camera = Camera(REGISTRATION_FOLDER)
bot = Telebot(TOKEN_ID, CHAT_ID)
pir = MotionDetector()
@bot.handler("/start")
def on_start():
"""
command /start: start bot
"""
bot.is_listen = True
return bot.send_message("Bot start")
@bot.handler("/stop")
def on_stop():
"""
command /stop: stop bot
"""
bot.is_listen = False
return bot.send_message("Bot stop")
@bot.handler("/status")
def on_status():
"""
command /status: show bot status
"""
return bot.send_message("Listening Motion run") \
if bot.is_listen else bot.send_message("Listen Motion doesn't run")
@bot.handler("/photo")
def on_photo():
"""
command /photo: take a photo
"""
return bot.send_photo(camera.take_photo(), "photo")
@bot.handler("/video")
def on_video(*args):
"""
command /video: record a video
:param args: arguments of the bot's command
"""
delay = args[0] if args else VIDEO_TIME
bot.send_message("Recording start")
return bot.send_video(camera.start_recording(delay), "video")
@bot.handler("/help")
def on_help():
"""
command /help: show help
:return: string
"""
msg = "command usage:\n"
msg += "\t/start : start the home monitoring system \n"
msg += "\t/stop : stop the home monitoring system\n"
msg += "\t/status : show the status of the monitoring system \n"
msg += "\t/photo : take a picture\n"
msg += "\t/video <delay> : records a video, by default delay is " + str(VIDEO_TIME) + "s \n"
msg += "\t/clean : remove all files in video folder\n"
msg += "\t/help : show help\n"
return bot.send_message(msg)
@bot.handler("/clean")
def on_clean():
"""
command /clean: remove file in REGISTRATION_FOLDER
"""
return bot.send_message(camera.purge_records())
print('I am listening ...')
try:
while True:
if bot.is_listen and pir.movement_detected():
bot.send_video(camera.start_recording(VIDEO_TIME), 'motion detected')
else:
time.sleep(1)
except KeyboardInterrupt:
del camera
| #!/usr/bin/env python
"""
Home surveillance application
"""
import time
from lib.camera import Camera
from lib.telebot import Telebot
from lib.pir import MotionDetector
from config import TOKEN_ID, REGISTRATION_FOLDER, VIDEO_TIME, CHAT_ID
camera = Camera(REGISTRATION_FOLDER)
bot = Telebot(TOKEN_ID, CHAT_ID)
pir = MotionDetector()
@bot.handler("/start")
def on_start():
"""
command /start: start bot
"""
bot.is_listen = True
return bot.send_message("Bot start")
@bot.handler("/stop")
def on_stop():
"""
command /stop: stop bot
"""
bot.is_listen = False
return bot.send_message("Bot stop")
@bot.handler("/status")
def on_status():
"""
command /status: show bot status
"""
return bot.send_message("Listening Motion run") \
if bot.is_listen else bot.send_message("Listen Motion doesn't run")
@bot.handler("/photo")
def on_photo():
"""
command /photo: take a photo
"""
return bot.send_photo(camera.take_photo(), "photo")
@bot.handler("/video")
def on_video(*args):
"""
command /video: record a video
:param args: arguments of the bot's command
"""
delay = args[0] if args else VIDEO_TIME
bot.send_message("Recording start")
return bot.send_video(camera.start_recording(delay), "video")
@bot.handler("/help")
def on_help():
"""
command /help: show help
:return: string
"""
msg = "command usage:\n"
msg += "\t/start : start the home monitoring system \n"
msg += "\t/stop : stop the home monitoring system\n"
msg += "\t/status : show the status of the monitoring system \n"
msg += "\t/photo : take a picture\n"
msg += "\t/video <delay> : records a video, by default delay is " + str(VIDEO_TIME) + "s \n"
msg += "\t/clean : remove all files in video folder\n"
msg += "\t/help : show help\n"
return bot.send_message(msg)
@bot.handler("/clean")
def on_clean():
"""
command /clean: remove file in REGISTRATION_FOLDER
"""
return bot.send_message(camera.purge_records())
print('I am listening ...')
try:
while True:
if bot.is_listen and pir.movement_detected():
bot.send_video(camera.start_recording(VIDEO_TIME), 'motion detected')
else:
time.sleep(1)
except KeyboardInterrupt:
del camera
| en | 0.385214 | #!/usr/bin/env python Home surveillance application command /start: start bot command /stop: stop bot command /status: show bot status command /photo: take a photo command /video: record a video :param args: arguments of the bot's command command /help: show help :return: string command /clean: remove file in REGISTRATION_FOLDER | 2.676472 | 3 |
poetry/version/helpers.py | batisteo/poetry | 0 | 6614226 | <gh_stars>0
from poetry.semver.constraints import MultiConstraint
from poetry.semver.version_parser import VersionParser
PYTHON_VERSION = [
'2.7.*',
'3.0.*', '3.1.*', '3.2.*', '3.3.*', '3.4.*',
'3.5.*', '3.6.*', '3.7.*', '3.8.*',
]
def format_python_constraint(constraint):
"""
This helper will help in transforming
disjunctive constraint into proper constraint.
"""
if not isinstance(constraint, MultiConstraint):
return str(constraint)
has_disjunctive = False
for c in constraint.constraints:
if isinstance(c, MultiConstraint) and c.is_disjunctive():
has_disjunctive = True
break
parser = VersionParser()
formatted = []
accepted = []
if not constraint.is_disjunctive() and not has_disjunctive:
return str(constraint)
for version in PYTHON_VERSION:
version_constraint = parser.parse_constraints(version)
matches = constraint.matches(version_constraint)
if not matches:
formatted.append('!=' + version)
else:
accepted.append(version)
# Checking lower bound
low = accepted[0]
formatted.insert(0, '>=' + '.'.join(low.split('.')[:2]))
return ', '.join(formatted)
| from poetry.semver.constraints import MultiConstraint
from poetry.semver.version_parser import VersionParser
PYTHON_VERSION = [
'2.7.*',
'3.0.*', '3.1.*', '3.2.*', '3.3.*', '3.4.*',
'3.5.*', '3.6.*', '3.7.*', '3.8.*',
]
def format_python_constraint(constraint):
"""
This helper will help in transforming
disjunctive constraint into proper constraint.
"""
if not isinstance(constraint, MultiConstraint):
return str(constraint)
has_disjunctive = False
for c in constraint.constraints:
if isinstance(c, MultiConstraint) and c.is_disjunctive():
has_disjunctive = True
break
parser = VersionParser()
formatted = []
accepted = []
if not constraint.is_disjunctive() and not has_disjunctive:
return str(constraint)
for version in PYTHON_VERSION:
version_constraint = parser.parse_constraints(version)
matches = constraint.matches(version_constraint)
if not matches:
formatted.append('!=' + version)
else:
accepted.append(version)
# Checking lower bound
low = accepted[0]
formatted.insert(0, '>=' + '.'.join(low.split('.')[:2]))
return ', '.join(formatted) | en | 0.764641 | This helper will help in transforming disjunctive constraint into proper constraint. # Checking lower bound | 3.050938 | 3 |
classicrack/fitness/chi_squared.py | starkfire/classicrack | 1 | 6614227 | <filename>classicrack/fitness/chi_squared.py
from classicrack.utils.common import frequency, probability_distribution
def chi_squared(texts: list, fd: dict):
"""
Uses chi-squared test to calculate the fitness of a plaintext.
texts (list): a list of texts
fd (dict): reference frequency distribution (e.g. English alphabet distribution)
"""
pd = probability_distribution(fd)
fd = [frequency(texts[x]) for x in range(len(texts))]
chi_sq = {}
for x in range(len(fd)):
csq = 0
for y in texts[x]:
observed = fd[x]
expected = pd[y.upper()] * len(texts[x])
csq += pow((observed[y] - expected), 2) / expected
chi_sq.update({texts[x] : csq})
return chi_sq | <filename>classicrack/fitness/chi_squared.py
from classicrack.utils.common import frequency, probability_distribution
def chi_squared(texts: list, fd: dict):
"""
Uses chi-squared test to calculate the fitness of a plaintext.
texts (list): a list of texts
fd (dict): reference frequency distribution (e.g. English alphabet distribution)
"""
pd = probability_distribution(fd)
fd = [frequency(texts[x]) for x in range(len(texts))]
chi_sq = {}
for x in range(len(fd)):
csq = 0
for y in texts[x]:
observed = fd[x]
expected = pd[y.upper()] * len(texts[x])
csq += pow((observed[y] - expected), 2) / expected
chi_sq.update({texts[x] : csq})
return chi_sq | en | 0.685427 | Uses chi-squared test to calculate the fitness of a plaintext. texts (list): a list of texts fd (dict): reference frequency distribution (e.g. English alphabet distribution) | 3.108206 | 3 |
Others/code_festival/CODE_FESTIVAL_2016_qual_A/b.py | KATO-Hiro/AtCoder | 2 | 6614228 | <filename>Others/code_festival/CODE_FESTIVAL_2016_qual_A/b.py
# -*- coding: utf-8 -*-
if __name__ == '__main__':
n = int(input())
a = list(map(lambda x: int(x) - 1, input().split()))
count = 0
# See:
# http://code-festival-2016-quala.contest.atcoder.jp/data/other/code-festival-2016-quala/editorial.pdf
for i in range(len(a)):
if i == a[a[i]]:
count += 1
print(count // 2)
| <filename>Others/code_festival/CODE_FESTIVAL_2016_qual_A/b.py
# -*- coding: utf-8 -*-
if __name__ == '__main__':
n = int(input())
a = list(map(lambda x: int(x) - 1, input().split()))
count = 0
# See:
# http://code-festival-2016-quala.contest.atcoder.jp/data/other/code-festival-2016-quala/editorial.pdf
for i in range(len(a)):
if i == a[a[i]]:
count += 1
print(count // 2)
| en | 0.410983 | # -*- coding: utf-8 -*- # See: # http://code-festival-2016-quala.contest.atcoder.jp/data/other/code-festival-2016-quala/editorial.pdf | 3.158874 | 3 |
monolith-api/cart.py | sebsto/monotomicro | 1 | 6614229 | from flask import request
from flask_restful import Resource
class Cart(Resource):
cart = []
def get(self):
return { "status" : "success", "cart" : self.cart }
def put(self):
# no attempt made to interpret the data, storing the string as-is
jsonData = request.json
# check if item.id already exist in cart, when it does just add quantity
item = list(filter(lambda c: jsonData['item']['id'] == c['item']['id'], self.cart))
if len(item) == 1:
item[0]['quantity'] += jsonData['quantity']
else:
self.cart.append(jsonData)
# return the current cart
return { "status" : "success", "cart" : self.cart }
| from flask import request
from flask_restful import Resource
class Cart(Resource):
cart = []
def get(self):
return { "status" : "success", "cart" : self.cart }
def put(self):
# no attempt made to interpret the data, storing the string as-is
jsonData = request.json
# check if item.id already exist in cart, when it does just add quantity
item = list(filter(lambda c: jsonData['item']['id'] == c['item']['id'], self.cart))
if len(item) == 1:
item[0]['quantity'] += jsonData['quantity']
else:
self.cart.append(jsonData)
# return the current cart
return { "status" : "success", "cart" : self.cart }
| en | 0.617159 | # no attempt made to interpret the data, storing the string as-is # check if item.id already exist in cart, when it does just add quantity # return the current cart | 2.966136 | 3 |
server.py | DuckyMomo20012/Simple-webpage | 0 | 6614230 | import mimetypes
import socket
from datetime import datetime
class HttpServer:
def __init__(self, host = '0.0.0.0', port = 8080):
self.HOST = host
self.PORT = port
self.request = str()
self.request_header = dict()
self.request_body = dict()
self.response = list()
self.status_code = str()
self.s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.s.bind((self.HOST, self.PORT))
print(f'Listening on host: "{self.HOST}", port: "{self.PORT}"')
self.s.listen(5)
def serve_forever(self):
while True:
conn, address = self.s.accept()
try:
self.request = conn.recv(1024).decode('utf-8')
self.translate_path()
if self.request_body:
print(self.request_body)
today = datetime.today().strftime("%d/%b/%Y")
time = datetime.now().strftime("%H:%M:%S")
self.handle()
print('[%s % s] -- "%s" %s -' % (today, time, self.request[0], self.status_code))
conn.send(b"".join(self.response))
self.response = []
finally:
conn.close()
def send_response(self, status_code):
self.status_code = status_code
self.response.append(b"%s %s\r\n" % (b"HTTP/1.1", status_code.encode("utf-8")))
def send_header(self, keyword, value):
self.response.append(b"%s: %s\r\n" % (keyword.encode("utf-8"), value.encode("utf-8")))
def end_header(self):
self.response.append(b"\r\n")
def translate_path(self):
self.request = self.request.split("\r\n")
parts: str
for parts in self.request[1:]: # ignore 'Method "GET" or "POST"'
if "&" not in parts:
line = parts.split(" ")
if line[0] != "":
self.request_header.update({line[0][:-1]: line[1]}) # remove ":"
else:
line = parts.split("&") # get request body
for pairs in line:
pairs = pairs.split("=")
self.request_body.update({pairs[0]: pairs[1]})
def handle(self):
request_line = self.request[0].split(" ")
try:
f = str(request_line[1])
if f == '/':
path = 'index.html'
else:
path = f[1:] # ignore first dash
if request_line[0] == "GET":
self.do_GET(path)
if request_line[0] == "POST":
self.do_POST(path)
except OSError:
print("error")
# if request_line[0] == "OPTIONS":
# self.do_OPTION()
def do_GET(self, path):
f = None
filetype = self.guess_type(path)
if "&" in path:
query = path.split("&")
username = query[0].split("=")[1]
password = query[1].split("=")[1]
print("username:%s - password:%s" % (username, password))
if username == "admin" and password == "<PASSWORD>":
path = "info.html"
else:
path = "404.html"
self.send_response("301 MOVED PERMANENTLY")
self.send_header("Location", "%s" % path)
return None
try:
f = open(path, 'rb')
self.send_response("200 OK")
self.send_header("Connection", "keep-alive")
self.send_header("Content-type", filetype)
except OSError:
f = open('404.html', 'rb')
self.send_response('404 NOT FOUND')
self.send_header("Connection", "keep-alive")
self.send_header("Content-type", filetype)
finally:
self.send_file(f, filetype)
def do_POST(self, path):
if len(self.request_body) != 0:
if "username" and "pass" in self.request_body:
filetype = self.guess_type(path)
username = self.request_body["username"]
password = self.request_body["pass"]
print("username:%s - password:%s" % (username, password))
if username == "admin" and password == "<PASSWORD>":
path = "info.html"
else:
path = "404.html"
self.send_response("301 MOVED PERMANENTLY")
self.send_header("Location", "%s" % path)
self.send_header("Connection", "keep-alive")
self.send_header("Content-type", filetype)
f = open(path, 'rb')
self.send_file(f, filetype)
# def do_OPTION(self):
# self.send_response("204 NO CONTENT")
# self.send_header("Access-Control-Allow-Origin", self.request_header["Origin"])
# self.send_header("Access-Control-Allow-Methods", "%s, %s, %s" % ("GET", "POST", "OPTIONS"))
# self.send_header("Connection", "keep-alive")
def guess_type(self, path):
guess, _ = mimetypes.guess_type(path)
if guess:
return guess
return 'application/octet-stream'
def chunk_send(self, f):
self.send_header("Transfer-Encoding", "chunked")
self.end_header()
try:
chunk_size = 1024
while True:
buf = f.read(chunk_size)
if not buf:
self.response.append(b'0\r\n\r\n')
break
self.response.append(b"%s\r\n%s\r\n" % (hex(len(buf))[2:].encode("ascii"), buf))
finally:
f.close()
# print('"%s": %s' % (f.name, "chunk send"))
def content_length_send(self, f):
response = []
COPY_BUFFERSIZE = 10485760
try:
while True:
buf = f.read(COPY_BUFFERSIZE)
if not buf:
break
response.append(b"%s" % buf)
self.send_header("Content-length", str(len(b"".join(response))))
self.end_header()
self.response.extend(response)
finally:
f.close()
# print('"%s": %s' % (f.name, "content-length send"))
def send_file(self, f, filetype):
try:
if filetype == "text/html" or filetype == "text/css":
self.content_length_send(f)
else:
self.chunk_send(f)
except:
print('There was an error')
else:
pass
# print(f"{f.name} sent")
# server = HttpServer("127.0.0.1", 80)
server = HttpServer()
server.serve_forever()
| import mimetypes
import socket
from datetime import datetime
class HttpServer:
def __init__(self, host = '0.0.0.0', port = 8080):
self.HOST = host
self.PORT = port
self.request = str()
self.request_header = dict()
self.request_body = dict()
self.response = list()
self.status_code = str()
self.s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.s.bind((self.HOST, self.PORT))
print(f'Listening on host: "{self.HOST}", port: "{self.PORT}"')
self.s.listen(5)
def serve_forever(self):
while True:
conn, address = self.s.accept()
try:
self.request = conn.recv(1024).decode('utf-8')
self.translate_path()
if self.request_body:
print(self.request_body)
today = datetime.today().strftime("%d/%b/%Y")
time = datetime.now().strftime("%H:%M:%S")
self.handle()
print('[%s % s] -- "%s" %s -' % (today, time, self.request[0], self.status_code))
conn.send(b"".join(self.response))
self.response = []
finally:
conn.close()
def send_response(self, status_code):
self.status_code = status_code
self.response.append(b"%s %s\r\n" % (b"HTTP/1.1", status_code.encode("utf-8")))
def send_header(self, keyword, value):
self.response.append(b"%s: %s\r\n" % (keyword.encode("utf-8"), value.encode("utf-8")))
def end_header(self):
self.response.append(b"\r\n")
def translate_path(self):
self.request = self.request.split("\r\n")
parts: str
for parts in self.request[1:]: # ignore 'Method "GET" or "POST"'
if "&" not in parts:
line = parts.split(" ")
if line[0] != "":
self.request_header.update({line[0][:-1]: line[1]}) # remove ":"
else:
line = parts.split("&") # get request body
for pairs in line:
pairs = pairs.split("=")
self.request_body.update({pairs[0]: pairs[1]})
def handle(self):
request_line = self.request[0].split(" ")
try:
f = str(request_line[1])
if f == '/':
path = 'index.html'
else:
path = f[1:] # ignore first dash
if request_line[0] == "GET":
self.do_GET(path)
if request_line[0] == "POST":
self.do_POST(path)
except OSError:
print("error")
# if request_line[0] == "OPTIONS":
# self.do_OPTION()
def do_GET(self, path):
f = None
filetype = self.guess_type(path)
if "&" in path:
query = path.split("&")
username = query[0].split("=")[1]
password = query[1].split("=")[1]
print("username:%s - password:%s" % (username, password))
if username == "admin" and password == "<PASSWORD>":
path = "info.html"
else:
path = "404.html"
self.send_response("301 MOVED PERMANENTLY")
self.send_header("Location", "%s" % path)
return None
try:
f = open(path, 'rb')
self.send_response("200 OK")
self.send_header("Connection", "keep-alive")
self.send_header("Content-type", filetype)
except OSError:
f = open('404.html', 'rb')
self.send_response('404 NOT FOUND')
self.send_header("Connection", "keep-alive")
self.send_header("Content-type", filetype)
finally:
self.send_file(f, filetype)
def do_POST(self, path):
if len(self.request_body) != 0:
if "username" and "pass" in self.request_body:
filetype = self.guess_type(path)
username = self.request_body["username"]
password = self.request_body["pass"]
print("username:%s - password:%s" % (username, password))
if username == "admin" and password == "<PASSWORD>":
path = "info.html"
else:
path = "404.html"
self.send_response("301 MOVED PERMANENTLY")
self.send_header("Location", "%s" % path)
self.send_header("Connection", "keep-alive")
self.send_header("Content-type", filetype)
f = open(path, 'rb')
self.send_file(f, filetype)
# def do_OPTION(self):
# self.send_response("204 NO CONTENT")
# self.send_header("Access-Control-Allow-Origin", self.request_header["Origin"])
# self.send_header("Access-Control-Allow-Methods", "%s, %s, %s" % ("GET", "POST", "OPTIONS"))
# self.send_header("Connection", "keep-alive")
def guess_type(self, path):
guess, _ = mimetypes.guess_type(path)
if guess:
return guess
return 'application/octet-stream'
def chunk_send(self, f):
self.send_header("Transfer-Encoding", "chunked")
self.end_header()
try:
chunk_size = 1024
while True:
buf = f.read(chunk_size)
if not buf:
self.response.append(b'0\r\n\r\n')
break
self.response.append(b"%s\r\n%s\r\n" % (hex(len(buf))[2:].encode("ascii"), buf))
finally:
f.close()
# print('"%s": %s' % (f.name, "chunk send"))
def content_length_send(self, f):
response = []
COPY_BUFFERSIZE = 10485760
try:
while True:
buf = f.read(COPY_BUFFERSIZE)
if not buf:
break
response.append(b"%s" % buf)
self.send_header("Content-length", str(len(b"".join(response))))
self.end_header()
self.response.extend(response)
finally:
f.close()
# print('"%s": %s' % (f.name, "content-length send"))
def send_file(self, f, filetype):
try:
if filetype == "text/html" or filetype == "text/css":
self.content_length_send(f)
else:
self.chunk_send(f)
except:
print('There was an error')
else:
pass
# print(f"{f.name} sent")
# server = HttpServer("127.0.0.1", 80)
server = HttpServer()
server.serve_forever()
| en | 0.314493 | # ignore 'Method "GET" or "POST"' # remove ":" # get request body # ignore first dash # if request_line[0] == "OPTIONS": # self.do_OPTION() # def do_OPTION(self): # self.send_response("204 NO CONTENT") # self.send_header("Access-Control-Allow-Origin", self.request_header["Origin"]) # self.send_header("Access-Control-Allow-Methods", "%s, %s, %s" % ("GET", "POST", "OPTIONS")) # self.send_header("Connection", "keep-alive") # print('"%s": %s' % (f.name, "chunk send")) # print('"%s": %s' % (f.name, "content-length send")) # print(f"{f.name} sent") # server = HttpServer("127.0.0.1", 80) | 3.033984 | 3 |
setup.py | wbcchsyn/unix_daemon | 1 | 6614231 | <reponame>wbcchsyn/unix_daemon<filename>setup.py<gh_stars>1-10
# -*- coding: utf-8 -*-
'''
Copyright 2014 <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 sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
class Tox(TestCommand):
user_options = [('tox-args=', 'a', 'Arguments to pass to tox')]
def initialize_options(self):
TestCommand.initialize_options(self)
self.tox_args = None
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import tox
import shlex
if self.tox_args:
errno = tox.cmdline(args=shlex.split(self.tox_args))
else:
errno = tox.cmdline(self.test_args)
sys.exit(errno)
long_description = open('docs/README.rst').read()
classifiers = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.1",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries",
"Topic :: Software Development :: Libraries :: Python Modules",
]
setup(
name='unix_daemon',
version='1.0.0',
description='Function emulating Daemon(3) on Linux and Unix OS.',
long_description=long_description,
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/wbcchsyn/unix_daemon',
platforms=['linux', 'unix'],
py_modules=['unix_daemon'],
package_dir={"": "src"},
license=['Apache License 2.0'],
classifiers=classifiers,
tests_require=['tox'],
cmdclass={'test': Tox},
)
| # -*- coding: utf-8 -*-
'''
Copyright 2014 <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 sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
class Tox(TestCommand):
user_options = [('tox-args=', 'a', 'Arguments to pass to tox')]
def initialize_options(self):
TestCommand.initialize_options(self)
self.tox_args = None
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
import tox
import shlex
if self.tox_args:
errno = tox.cmdline(args=shlex.split(self.tox_args))
else:
errno = tox.cmdline(self.test_args)
sys.exit(errno)
long_description = open('docs/README.rst').read()
classifiers = [
"Development Status :: 5 - Production/Stable",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.1",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: Software Development",
"Topic :: Software Development :: Libraries",
"Topic :: Software Development :: Libraries :: Python Modules",
]
setup(
name='unix_daemon',
version='1.0.0',
description='Function emulating Daemon(3) on Linux and Unix OS.',
long_description=long_description,
author='<NAME>',
author_email='<EMAIL>',
url='https://github.com/wbcchsyn/unix_daemon',
platforms=['linux', 'unix'],
py_modules=['unix_daemon'],
package_dir={"": "src"},
license=['Apache License 2.0'],
classifiers=classifiers,
tests_require=['tox'],
cmdclass={'test': Tox},
) | en | 0.85534 | # -*- coding: utf-8 -*- Copyright 2014 <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. | 1.816602 | 2 |
scripts/test.py | mattdutson/mobilenet | 0 | 6614232 | #!/usr/bin/env python3
import argparse
import tensorflow as tf
from tensorflow.keras.models import load_model
from mobilenet.dataset import imagenet
def main(args):
model = load_model(args.model_file)
data, steps = imagenet('test', tuple(args.size))
model.evaluate(x=data, steps=steps)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
add_help=False)
parser.add_argument(
'model-file',
help='The filename (.h5 file) of the model to test.')
parser.add_argument(
'-h', '--help', action='help',
help='Display this help message and exit.')
parser.add_argument(
'-s', '--size', nargs=2, default=[320, 320], type=int,
help='The height and width (in that order) to which images '
'should be resized.')
# This strategy splits batches over the available GPUs
with tf.distribute.MirroredStrategy().scope():
main(parser.parse_args())
| #!/usr/bin/env python3
import argparse
import tensorflow as tf
from tensorflow.keras.models import load_model
from mobilenet.dataset import imagenet
def main(args):
model = load_model(args.model_file)
data, steps = imagenet('test', tuple(args.size))
model.evaluate(x=data, steps=steps)
if __name__ == '__main__':
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
add_help=False)
parser.add_argument(
'model-file',
help='The filename (.h5 file) of the model to test.')
parser.add_argument(
'-h', '--help', action='help',
help='Display this help message and exit.')
parser.add_argument(
'-s', '--size', nargs=2, default=[320, 320], type=int,
help='The height and width (in that order) to which images '
'should be resized.')
# This strategy splits batches over the available GPUs
with tf.distribute.MirroredStrategy().scope():
main(parser.parse_args())
| en | 0.445548 | #!/usr/bin/env python3 # This strategy splits batches over the available GPUs | 2.404797 | 2 |
tests/datasets/__init__.py | chrisPiemonte/polimorfo | 3 | 6614233 | """Unit test package for poliform."""
| """Unit test package for poliform."""
| en | 0.727514 | Unit test package for poliform. | 0.90379 | 1 |
titanic/code.py | A-I-Research-Facility/Kaggle-Titanic-challenge | 1 | 6614234 | from google.colab import files
uploaded = files.upload()
import pandas as pd
trainData = pd.read_csv('train.csv')
testData = pd.read_csv('test.csv')
trainData.head()
trainData.shape
trainData.drop(['PassengerId', 'Name', 'SibSp', 'Parch', 'Ticket', 'Cabin', 'Embarked'], axis=1, inplace=True)
trainData.head()
trainData.isnull().sum()
trainData['Age'].describe()
trainData['Age'].fillna(trainData['Age'].mean(), inplace=True)
trainData.isnull().sum()
dum1 = pd.get_dummies(trainData['Sex'], drop_first=True)
trainData = pd.concat([trainData, dum1], axis=1)
trainData.head()
trainData.drop(['Sex'], axis=1, inplace=True)
from sklearn.preprocessing import StandardScaler
slr = StandardScaler()
scaleList = ['Age', 'Fare']
trainData[scaleList] = slr.fit_transform(trainData[scaleList])
trainData.head()
X = trainData.drop(['Survived'], axis=1)
y = trainData['Survived']
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
models = {
'DecisionTreeClassifier' : {
'model' : DecisionTreeClassifier(),
'param' : {
'criterion' : ['gini', 'entropy']
}
},
'KNeighborsClassifier' : {
'model' : KNeighborsClassifier(),
'param' : {
'n_neighbors' : [5, 10, 15, 20, 25]
}
},
'SVC' : {
'model' : SVC(),
'param' : {
'kernel' : ['rbf', 'linear', 'sigmoid'],
'C' : [0.1, 1, 10, 100]
}
},
}
accu = []
for model, p in models.items():
modelSelect = GridSearchCV(estimator=p['model'], param_grid=p['param'], cv=5, return_train_score=False)
modelSelect.fit(X, y)
accu.append({
'model' : model,
'best_score' : modelSelect.best_score_,
'best_params' : modelSelect.best_params_
})
df_score = pd.DataFrame(accu, columns=['model', 'best_score', 'best_params'])
df_score
svcModel = SVC(C=100, kernel='rbf')
svcModel.fit(X, y)
test1 = testData.drop(['PassengerId', 'Name', 'SibSp', 'Parch', 'Ticket', 'Cabin', 'Embarked'], axis=1)
test1.isnull().sum()
test1['Age'].fillna(test1['Age'].mean(), inplace=True)
test1['Fare'].fillna(test1['Fare'].mean(), inplace=True)
dum2 = pd.get_dummies(test1['Sex'], drop_first=True)
test1 = pd.concat([test1, dum2], axis=1)
test1.drop(['Sex'], axis=1, inplace=True)
test1[scaleList] = slr.fit_transform(test1[scaleList])
test1.head()
"""Now all we need to do is predict."""
predictValue = svcModel.predict(test1)
answer = pd.DataFrame({
'PassengerId' : testData['PassengerId'],
'Survived' : predictValue
})
answer.to_csv('solution.csv', index=False)
| from google.colab import files
uploaded = files.upload()
import pandas as pd
trainData = pd.read_csv('train.csv')
testData = pd.read_csv('test.csv')
trainData.head()
trainData.shape
trainData.drop(['PassengerId', 'Name', 'SibSp', 'Parch', 'Ticket', 'Cabin', 'Embarked'], axis=1, inplace=True)
trainData.head()
trainData.isnull().sum()
trainData['Age'].describe()
trainData['Age'].fillna(trainData['Age'].mean(), inplace=True)
trainData.isnull().sum()
dum1 = pd.get_dummies(trainData['Sex'], drop_first=True)
trainData = pd.concat([trainData, dum1], axis=1)
trainData.head()
trainData.drop(['Sex'], axis=1, inplace=True)
from sklearn.preprocessing import StandardScaler
slr = StandardScaler()
scaleList = ['Age', 'Fare']
trainData[scaleList] = slr.fit_transform(trainData[scaleList])
trainData.head()
X = trainData.drop(['Survived'], axis=1)
y = trainData['Survived']
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
models = {
'DecisionTreeClassifier' : {
'model' : DecisionTreeClassifier(),
'param' : {
'criterion' : ['gini', 'entropy']
}
},
'KNeighborsClassifier' : {
'model' : KNeighborsClassifier(),
'param' : {
'n_neighbors' : [5, 10, 15, 20, 25]
}
},
'SVC' : {
'model' : SVC(),
'param' : {
'kernel' : ['rbf', 'linear', 'sigmoid'],
'C' : [0.1, 1, 10, 100]
}
},
}
accu = []
for model, p in models.items():
modelSelect = GridSearchCV(estimator=p['model'], param_grid=p['param'], cv=5, return_train_score=False)
modelSelect.fit(X, y)
accu.append({
'model' : model,
'best_score' : modelSelect.best_score_,
'best_params' : modelSelect.best_params_
})
df_score = pd.DataFrame(accu, columns=['model', 'best_score', 'best_params'])
df_score
svcModel = SVC(C=100, kernel='rbf')
svcModel.fit(X, y)
test1 = testData.drop(['PassengerId', 'Name', 'SibSp', 'Parch', 'Ticket', 'Cabin', 'Embarked'], axis=1)
test1.isnull().sum()
test1['Age'].fillna(test1['Age'].mean(), inplace=True)
test1['Fare'].fillna(test1['Fare'].mean(), inplace=True)
dum2 = pd.get_dummies(test1['Sex'], drop_first=True)
test1 = pd.concat([test1, dum2], axis=1)
test1.drop(['Sex'], axis=1, inplace=True)
test1[scaleList] = slr.fit_transform(test1[scaleList])
test1.head()
"""Now all we need to do is predict."""
predictValue = svcModel.predict(test1)
answer = pd.DataFrame({
'PassengerId' : testData['PassengerId'],
'Survived' : predictValue
})
answer.to_csv('solution.csv', index=False)
| en | 0.977045 | Now all we need to do is predict. | 2.951138 | 3 |
pinger_runner.py | clarke/pinger | 0 | 6614235 | #!/usr/bin/env python3
import pinger.runner
pinger.runner.run_checks()
| #!/usr/bin/env python3
import pinger.runner
pinger.runner.run_checks()
| fr | 0.221828 | #!/usr/bin/env python3 | 1.17642 | 1 |
examples/min_max_scaler.py | yutayamazaki/Machine-Learning-Scratch | 0 | 6614236 | <gh_stars>0
import sys
import numpy as np
sys.path.append('../')
from mlscratch.preprocessing import MinMaxScaler
if __name__ == "__main__":
mat = np.array([
[0, 1, 2],
[5, 0, 1]
])
scaled = MinMaxScaler().fit_transform(mat)
print(scaled)
| import sys
import numpy as np
sys.path.append('../')
from mlscratch.preprocessing import MinMaxScaler
if __name__ == "__main__":
mat = np.array([
[0, 1, 2],
[5, 0, 1]
])
scaled = MinMaxScaler().fit_transform(mat)
print(scaled) | none | 1 | 2.253581 | 2 | |
Unet.py | killermyth/lungCancer | 0 | 6614237 | <reponame>killermyth/lungCancer
#!/usr/bin/env python
# encoding: utf-8
"""
训练uNet网络用来切割疑似结节
"""
import numpy as np
from keras.models import Model
from keras.layers import Input, merge, Convolution2D, MaxPooling2D, UpSampling2D, Dropout, Cropping2D
from keras.optimizers import Adam
from keras.optimizers import SGD
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras import backend as K
img_rows = 512
img_cols = 512
smooth = 1.
train_npy_path = './train_npy/'
test_npy_path = './test_npy/'
train_imgs = 'lung_img_LKDS-00001.npy'
train_masks = 'nodule_mask_LKDS-00001.npy'
test_imgs = 'lung_img_LKDS-00012.npy'
test_masks = 'lung_mask_LKDS-00012.npy'
use_existing = True
class Unet(object):
def __init__(self):
print 123
def get_crop_shape(self, target, refer):
# width, the 3rd dimension
cw = (target.get_shape()[2] - refer.get_shape()[2]).value
assert (cw >= 0)
if cw % 2 != 0:
cw1, cw2 = int(cw / 2), int(cw / 2) + 1
else:
cw1, cw2 = int(cw / 2), int(cw / 2)
# height, the 2nd dimension
ch = (target.get_shape()[1] - refer.get_shape()[1]).value
assert (ch >= 0)
if ch % 2 != 0:
ch1, ch2 = int(ch / 2), int(ch / 2) + 1
else:
ch1, ch2 = int(ch / 2), int(ch / 2)
return (ch1, ch2), (cw1, cw2)
def dice_coef(self, y_true, y_pred):
y_true_f = K.flatten(y_true)
y_pred_f = K.flatten(y_pred)
intersection = K.sum(y_true_f * y_pred_f)
return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
def dice_coef_loss(self, y_true, y_pred):
return -self.dice_coef(y_true, y_pred)
def get_unet(self):
inputs = Input((1, 512, 512))
conv1 = Convolution2D(64, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(inputs)
conv1 = Dropout(0.2)(conv1)
conv1 = Convolution2D(64, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv1)
pool1 = MaxPooling2D(pool_size=(2, 2), dim_ordering="th")(conv1)
conv2 = Convolution2D(128, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(pool1)
conv2 = Dropout(0.2)(conv2)
conv2 = Convolution2D(128, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv2)
pool2 = MaxPooling2D(pool_size=(2, 2), dim_ordering="th")(conv2)
conv3 = Convolution2D(256, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(pool2)
conv3 = Dropout(0.2)(conv3)
conv3 = Convolution2D(256, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv3)
pool3 = MaxPooling2D(pool_size=(2, 2), dim_ordering="th")(conv3)
conv4 = Convolution2D(512, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(pool3)
conv4 = Dropout(0.2)(conv4)
conv4 = Convolution2D(512, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv4)
pool4 = MaxPooling2D(pool_size=(2, 2), dim_ordering="th")(conv4)
conv5 = Convolution2D(1024, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(pool4)
conv5 = Dropout(0.2)(conv5)
conv5 = Convolution2D(1024, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv5)
up_conv5 = UpSampling2D(size=(2, 2))(conv5)
ch, cw = self.get_crop_shape(conv4, up_conv5)
crop_conv4 = Cropping2D(cropping=(ch, cw), dim_ordering="th")(conv4)
up6 = merge([up_conv5, crop_conv4], mode='concat', concat_axis=1)
conv6 = Convolution2D(512, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(up6)
conv6 = Dropout(0.2)(conv6)
conv6 = Convolution2D(512, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv6)
up_conv6 = UpSampling2D(size=(2, 2), dim_ordering="th")(conv6)
ch, cw = self.get_crop_shape(conv3, up_conv6)
crop_conv3 = Cropping2D(cropping=(ch, cw), dim_ordering="th")(conv3)
up7 = merge([up_conv6, crop_conv3], mode='concat', concat_axis=1)
conv7 = Convolution2D(256, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(up7)
conv7 = Dropout(0.2)(conv7)
conv7 = Convolution2D(256, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv7)
up_conv7 = UpSampling2D(size=(2, 2), dim_ordering="th")(conv7)
ch, cw = self.get_crop_shape(conv2, up_conv7)
crop_conv2 = Cropping2D(cropping=(ch, cw), dim_ordering="th")(conv2)
up8 = merge([up_conv7, crop_conv2], mode='concat', concat_axis=1)
conv8 = Convolution2D(128, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(up8)
conv8 = Dropout(0.2)(conv8)
conv8 = Convolution2D(128, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv8)
up_conv8 = UpSampling2D(size=(2, 2), dim_ordering="th")(conv8)
ch, cw = self.get_crop_shape(conv1, up_conv8)
crop_conv1 = Cropping2D(cropping=(ch, cw), dim_ordering="th")(conv1)
up9 = merge([up_conv8, crop_conv1], mode='concat', concat_axis=1)
conv9 = Convolution2D(64, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(up9)
conv9 = Dropout(0.2)(conv9)
conv9 = Convolution2D(64, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv9)
conv10 = Convolution2D(1, 1, 1, activation='sigmoid', dim_ordering="th")(conv9)
model = Model(input=inputs, output=conv10)
model.summary()
model.compile(optimizer=Adam(lr=1e-5), loss=dice_coef_loss, metrics=[dice_coef])
return model
def train_predict(self):
imgs_train = np.load(train_npy_path + train_imgs).astype(np.float32)
imgs_mask_train = np.load(train_npy_path + train_masks).astype(np.float32)
imgs_test = np.load(test_npy_path + test_imgs).astype(np.float32)
# imgs_mask_test_true = np.load(test_masks).astype(np.float32)
mean = np.mean(imgs_train) # mean for data centering
std = np.std(imgs_train) # std for data normalization
imgs_train -= mean # images should already be standardized, but just in case
imgs_train /= std
print('-' * 30)
print('Creating and compiling model...')
print('-' * 30)
model = self.get_unet()
# Saving weights to unet.hdf5 at checkpoints
model_checkpoint = ModelCheckpoint('unet.hdf5', monitor='loss', save_best_only=True)
#
# Should we load existing weights?
# Set argument for call to train_and_predict to true at end of script
if use_existing:
model.load_weights('./unet.hdf5')
#
# The final results for this tutorial were produced using a multi-GPU
# machine using TitanX's.
# For a home GPU computation benchmark, on my home set up with a GTX970
# I was able to run 20 epochs with a training set size of 320 and
# batch size of 2 in about an hour. I started getting reseasonable masks
# after about 3 hours of training.
#
print('-' * 30)
print('Fitting model...')
print('-' * 30)
model.fit(imgs_train, imgs_mask_train, batch_size=2, nb_epoch=20, verbose=1, shuffle=True,
callbacks=[model_checkpoint])
# loading best weights from training session
print('-' * 30)
print('Loading saved weights...')
print('-' * 30)
model.load_weights('./unet.hdf5')
print('-' * 30)
print('Predicting masks on test data...')
print('-' * 30)
num_test = len(imgs_test)
imgs_mask_test = np.ndarray([num_test, 1, 512, 512], dtype=np.float32)
for i in range(num_test):
imgs_mask_test[i] = model.predict([imgs_test[i:i + 1]], verbose=0)[0]
np.save('masksTestPredicted.npy', imgs_mask_test)
# mean = 0.0
# for i in range(num_test):
# mean += self.dice_coef_np(imgs_mask_test_true[i, 0], imgs_mask_test[i, 0])
# mean /= num_test
# print("Mean Dice Coeff : ", mean)
if __name__ == '__main__':
unet = Unet()
unet.train_predict()
| #!/usr/bin/env python
# encoding: utf-8
"""
训练uNet网络用来切割疑似结节
"""
import numpy as np
from keras.models import Model
from keras.layers import Input, merge, Convolution2D, MaxPooling2D, UpSampling2D, Dropout, Cropping2D
from keras.optimizers import Adam
from keras.optimizers import SGD
from keras.callbacks import ModelCheckpoint, LearningRateScheduler
from keras import backend as K
img_rows = 512
img_cols = 512
smooth = 1.
train_npy_path = './train_npy/'
test_npy_path = './test_npy/'
train_imgs = 'lung_img_LKDS-00001.npy'
train_masks = 'nodule_mask_LKDS-00001.npy'
test_imgs = 'lung_img_LKDS-00012.npy'
test_masks = 'lung_mask_LKDS-00012.npy'
use_existing = True
class Unet(object):
def __init__(self):
print 123
def get_crop_shape(self, target, refer):
# width, the 3rd dimension
cw = (target.get_shape()[2] - refer.get_shape()[2]).value
assert (cw >= 0)
if cw % 2 != 0:
cw1, cw2 = int(cw / 2), int(cw / 2) + 1
else:
cw1, cw2 = int(cw / 2), int(cw / 2)
# height, the 2nd dimension
ch = (target.get_shape()[1] - refer.get_shape()[1]).value
assert (ch >= 0)
if ch % 2 != 0:
ch1, ch2 = int(ch / 2), int(ch / 2) + 1
else:
ch1, ch2 = int(ch / 2), int(ch / 2)
return (ch1, ch2), (cw1, cw2)
def dice_coef(self, y_true, y_pred):
y_true_f = K.flatten(y_true)
y_pred_f = K.flatten(y_pred)
intersection = K.sum(y_true_f * y_pred_f)
return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
def dice_coef_loss(self, y_true, y_pred):
return -self.dice_coef(y_true, y_pred)
def get_unet(self):
inputs = Input((1, 512, 512))
conv1 = Convolution2D(64, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(inputs)
conv1 = Dropout(0.2)(conv1)
conv1 = Convolution2D(64, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv1)
pool1 = MaxPooling2D(pool_size=(2, 2), dim_ordering="th")(conv1)
conv2 = Convolution2D(128, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(pool1)
conv2 = Dropout(0.2)(conv2)
conv2 = Convolution2D(128, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv2)
pool2 = MaxPooling2D(pool_size=(2, 2), dim_ordering="th")(conv2)
conv3 = Convolution2D(256, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(pool2)
conv3 = Dropout(0.2)(conv3)
conv3 = Convolution2D(256, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv3)
pool3 = MaxPooling2D(pool_size=(2, 2), dim_ordering="th")(conv3)
conv4 = Convolution2D(512, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(pool3)
conv4 = Dropout(0.2)(conv4)
conv4 = Convolution2D(512, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv4)
pool4 = MaxPooling2D(pool_size=(2, 2), dim_ordering="th")(conv4)
conv5 = Convolution2D(1024, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(pool4)
conv5 = Dropout(0.2)(conv5)
conv5 = Convolution2D(1024, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv5)
up_conv5 = UpSampling2D(size=(2, 2))(conv5)
ch, cw = self.get_crop_shape(conv4, up_conv5)
crop_conv4 = Cropping2D(cropping=(ch, cw), dim_ordering="th")(conv4)
up6 = merge([up_conv5, crop_conv4], mode='concat', concat_axis=1)
conv6 = Convolution2D(512, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(up6)
conv6 = Dropout(0.2)(conv6)
conv6 = Convolution2D(512, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv6)
up_conv6 = UpSampling2D(size=(2, 2), dim_ordering="th")(conv6)
ch, cw = self.get_crop_shape(conv3, up_conv6)
crop_conv3 = Cropping2D(cropping=(ch, cw), dim_ordering="th")(conv3)
up7 = merge([up_conv6, crop_conv3], mode='concat', concat_axis=1)
conv7 = Convolution2D(256, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(up7)
conv7 = Dropout(0.2)(conv7)
conv7 = Convolution2D(256, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv7)
up_conv7 = UpSampling2D(size=(2, 2), dim_ordering="th")(conv7)
ch, cw = self.get_crop_shape(conv2, up_conv7)
crop_conv2 = Cropping2D(cropping=(ch, cw), dim_ordering="th")(conv2)
up8 = merge([up_conv7, crop_conv2], mode='concat', concat_axis=1)
conv8 = Convolution2D(128, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(up8)
conv8 = Dropout(0.2)(conv8)
conv8 = Convolution2D(128, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv8)
up_conv8 = UpSampling2D(size=(2, 2), dim_ordering="th")(conv8)
ch, cw = self.get_crop_shape(conv1, up_conv8)
crop_conv1 = Cropping2D(cropping=(ch, cw), dim_ordering="th")(conv1)
up9 = merge([up_conv8, crop_conv1], mode='concat', concat_axis=1)
conv9 = Convolution2D(64, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(up9)
conv9 = Dropout(0.2)(conv9)
conv9 = Convolution2D(64, 3, 3, activation='relu', border_mode='same', dim_ordering="th")(conv9)
conv10 = Convolution2D(1, 1, 1, activation='sigmoid', dim_ordering="th")(conv9)
model = Model(input=inputs, output=conv10)
model.summary()
model.compile(optimizer=Adam(lr=1e-5), loss=dice_coef_loss, metrics=[dice_coef])
return model
def train_predict(self):
imgs_train = np.load(train_npy_path + train_imgs).astype(np.float32)
imgs_mask_train = np.load(train_npy_path + train_masks).astype(np.float32)
imgs_test = np.load(test_npy_path + test_imgs).astype(np.float32)
# imgs_mask_test_true = np.load(test_masks).astype(np.float32)
mean = np.mean(imgs_train) # mean for data centering
std = np.std(imgs_train) # std for data normalization
imgs_train -= mean # images should already be standardized, but just in case
imgs_train /= std
print('-' * 30)
print('Creating and compiling model...')
print('-' * 30)
model = self.get_unet()
# Saving weights to unet.hdf5 at checkpoints
model_checkpoint = ModelCheckpoint('unet.hdf5', monitor='loss', save_best_only=True)
#
# Should we load existing weights?
# Set argument for call to train_and_predict to true at end of script
if use_existing:
model.load_weights('./unet.hdf5')
#
# The final results for this tutorial were produced using a multi-GPU
# machine using TitanX's.
# For a home GPU computation benchmark, on my home set up with a GTX970
# I was able to run 20 epochs with a training set size of 320 and
# batch size of 2 in about an hour. I started getting reseasonable masks
# after about 3 hours of training.
#
print('-' * 30)
print('Fitting model...')
print('-' * 30)
model.fit(imgs_train, imgs_mask_train, batch_size=2, nb_epoch=20, verbose=1, shuffle=True,
callbacks=[model_checkpoint])
# loading best weights from training session
print('-' * 30)
print('Loading saved weights...')
print('-' * 30)
model.load_weights('./unet.hdf5')
print('-' * 30)
print('Predicting masks on test data...')
print('-' * 30)
num_test = len(imgs_test)
imgs_mask_test = np.ndarray([num_test, 1, 512, 512], dtype=np.float32)
for i in range(num_test):
imgs_mask_test[i] = model.predict([imgs_test[i:i + 1]], verbose=0)[0]
np.save('masksTestPredicted.npy', imgs_mask_test)
# mean = 0.0
# for i in range(num_test):
# mean += self.dice_coef_np(imgs_mask_test_true[i, 0], imgs_mask_test[i, 0])
# mean /= num_test
# print("Mean Dice Coeff : ", mean)
if __name__ == '__main__':
unet = Unet()
unet.train_predict() | en | 0.821451 | #!/usr/bin/env python # encoding: utf-8 训练uNet网络用来切割疑似结节 # width, the 3rd dimension # height, the 2nd dimension # imgs_mask_test_true = np.load(test_masks).astype(np.float32) # mean for data centering # std for data normalization # images should already be standardized, but just in case # Saving weights to unet.hdf5 at checkpoints # # Should we load existing weights? # Set argument for call to train_and_predict to true at end of script # # The final results for this tutorial were produced using a multi-GPU # machine using TitanX's. # For a home GPU computation benchmark, on my home set up with a GTX970 # I was able to run 20 epochs with a training set size of 320 and # batch size of 2 in about an hour. I started getting reseasonable masks # after about 3 hours of training. # # loading best weights from training session # mean = 0.0 # for i in range(num_test): # mean += self.dice_coef_np(imgs_mask_test_true[i, 0], imgs_mask_test[i, 0]) # mean /= num_test # print("Mean Dice Coeff : ", mean) | 2.352659 | 2 |
delong_functions/calc_and_graph_functions.py | braddelong/22-jupyter-ps01 | 1 | 6614238 | <reponame>braddelong/22-jupyter-ps01
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats
import pandas as pd
plt.style.use('seaborn-whitegrid')
matplotlib.rc("font", family="Verdana")
fig_size = plt.rcParams["figure.figsize"]
fig_size[0] = 6
fig_size[1] = 6
plt.rcParams["figure.figsize"] = fig_size
plt.close('all')
def draw_demand_line(maximum_willingness_to_pay, demand_slope):
"""Draw a linear demand curve when provided with paratmeters in
slope-intercept form.
Parameters
==========
maximum_willingness_to_pay : float
the y-axis (price axis) intercept of the demand curve; the
highest willingness-to-pay for a unit of the commodity found
in the marketplace
demand_slope: float
how many extra units must be purchased to lower the outstanding
highest unsatisfied willingness-to-pay by one dollar; the slope of the
demand curve
Returns
=======
None
"""
axes = plt.gca()
x_vals = np.array(axes.get_xlim())
y_vals = maximum_willingness_to_pay - demand_slope * x_vals
plt.plot(x_vals, y_vals, color = "blue", label = "Demand")
def draw_supply_line(minimum_opportunity_cost, supply_slope):
"""Draw a supply demand curve when provided with paratmeters in
slope-intercept form.
Parameters
==========
minimum_opportunity_cost : float
the y-axis (price axis) intercept of the supply curve; the
lowest price at which the first producer finds it profitable
to produce and sell a unit of the commodity in the marketplace;
the minimum opportunity cost found among producers
supply: float
how many extra units must be purchased to raise the outstanding
lowest remaining opportunity cost by one dollar; the slope of the
supply curve
Returns
=======
None
"""
axes = plt.gca()
x_vals = np.array(axes.get_xlim())
y_vals = minimum_opportunity_cost + supply_slope * x_vals
plt.plot(x_vals, y_vals, color = "green", label = "Supply")
def print_market_summary(consumer_surplus, producer_surplus, equilibrium_price,
equilibrium_quantity, market_for_title):
"""Function to print the crude table of the four market summary equilibrium
summary statistics
Parameters
==========
consumer_surplus : float
the difference between the sum of satisfied willingnesses-to-pay by
purchasers and the sum of prices they paid to suppliers; the maximum
amount that could ever be extracted from purchasers by a threat to close
the market down; calculated in standard_supply_and_demand_graph() and passed
to print_market_summary()
producer_surplus: float
the difference between the sum of revenue earned by suppliers and the
sum of incurred opportunity costs by suppliers; the maximum amount that
could ever be extracted from suppliers by a threat to close the market
down; calculated in standard_supply_and_demand_graph() and passed to
print_market_summary()
equilibrium_price: float
the market price at which quantity supplied is equal to quantity
demanded; calculated in standard_supply_and_demand_graph() and passed
to print_market_summary()
equilibrium_quantity: float
the quantity produced and sold at which quantity supplied is equal to
quantity demanded; calculated in standard_supply_and_demand_graph() and passed
to print_market_summary()
market_for_title : string
the market and commodity of the supply-and-demand equilibrium— for
example: "Lattes at Euphoric State"; passed to standard_supply_and_demand_graph()
and then passed to print_market_summary()
Returns
=======
None
"""
print("")
print("")
print("SUMMARY: MARKET FOR " + market_for_title.upper())
print("")
print(round(consumer_surplus, 3), "= consumer surplus")
print(round(producer_surplus, 3), "= producer surplus")
print(round(equilibrium_price, 3), "= equilibrium price")
print(round(equilibrium_quantity, 3), "= equilibrium quantity")
print("")
print("")
def standard_supply_and_demand_graph(maximum_willingness_to_pay, demand_slope,
minimum_opportunity_cost, supply_slope, market_for_title):
"""
Function to calculate a graph and summary market statistics from slope-intercept
linear descriptions of supply and demand. Requires four floats for **maximum
willingness to pay** on the part of potential demanders, **minimum opportunity
cost** on the part of potential suppliers, demand and supply slopes, and a string
identifying the market and commodity. Returns a matplotlib figure object, an ax
subplots object, and a dictionary of market equilibrium summary statistics
Parameters
==========
consumer_surplus : float
the difference between the sum of satisfied willingnesses-to-pay by
purchasers and the sum of prices they paid to suppliers; the maximum
amount that could ever be extracted from purchasers by a threat to close
the market down; calculated in standard_supply_and_demand_graph() and passed
to print_market_summary()
producer_surplus: float
the difference between the sum of revenue earned by suppliers and the
sum of incurred opportunity costs by suppliers; the maximum amount that
could ever be extracted from suppliers by a threat to close the market
down; calculated in standard_supply_and_demand_graph() and passed to
print_market_summary()
equilibrium_price: float
the market price at which quantity supplied is equal to quantity
demanded; calculated in standard_supply_and_demand_graph() and passed
to print_market_summary()
equilibrium_quantity: float
the quantity produced and sold at which quantity supplied is equal to
quantity demanded; calculated in standard_supply_and_demand_graph() and passed
to print_market_summary()
market_for_title : string
the market and commodity of the supply-and-demand equilibrium— for
example: "Lattes at Euphoric State"; passed to standard_supply_and_demand_graph()
and then passed to print_market_summary()
Returns
=======
fig, ax, eqiilibrium
fig : matplotlib.figure.Figure
the graph drawn by the function: the standard supply-and-demand graph with
title, labels, legend, and annotated equilibrium point
ax : matplotlib.axes._subplots.AxesSubplot
equilibrium : dict
A Python dictionary containing a string identifying the commodity market for
which equilibrium has been calculated, and floats for thefour key market summary
statistics calculated in order to draw the supply-and-demand graph; all
for further reference. The keys to the dictionary are all strings:
"Equilibrium Price"—the market price at which quantity supplied is equal
to quantity demanded; calculated in standard_supply_and_demand_graph()
"Equilibrium Quantity"—the quantity produced and sold at which quantity
supplied is equal to quantity demanded; calculated in
standard_supply_and_demand_graph()
"Consumer Surplus"—the difference between the sum of satisfied
willingnesses-to-pay by purchasers and the sum of prices they paid
to suppliers; the maximum amount that could ever be extracted from
purchasers by a threat to close the market down; calculated in
standard_supply_and_demand_graph()
"Producer Surplus"—the difference between the sum of revenue earned
by suppliers and the sum of incurred opportunity costs by suppliers;
the maximum amount that could ever be extracted from suppliers by any
threat to close the market down; calculated in
standard_supply_and_demand_graph(): producer_surplus,
"Market"—the market and commodity of the supply-and-demand equilibrium—
for example: "Lattes at Euphoric State"; passed to
standard_supply_and_demand_graph()
"""
equilibrium_quantity = ((maximum_willingness_to_pay - minimum_opportunity_cost)/
(supply_slope + demand_slope))
equilibrium_price = (maximum_willingness_to_pay - equilibrium_quantity * demand_slope)
consumer_surplus = ((maximum_willingness_to_pay - equilibrium_price) *
equilibrium_quantity/2)
producer_surplus = ((equilibrium_price - minimum_opportunity_cost) *
equilibrium_quantity/2)
fig, ax = plt.subplots()
max_x_lim = 1.5 * equilibrium_quantity
max_y_lim = 1.2 * maximum_willingness_to_pay
fig.suptitle("Supply and Demand Graph: \n" + market_for_title, size = "20")
ax.set_xlim(0, max_x_lim)
ax.set_ylim(0, max_y_lim)
plt.plot(equilibrium_quantity, equilibrium_price, marker='o',
markersize=8, color="red")
plt.text(equilibrium_quantity, 1.1 * equilibrium_price,
"Market Equilibrium: \n" + "Quantity = " +
str(round(equilibrium_quantity, 2)) + "\nPrice = " +
str(round(equilibrium_price, 2)), size = "8")
plt.xlabel("Number of " + market_for_title, size = "10")
plt.ylabel("Price/Value of " + market_for_title, size = "10")
draw_demand_line(maximum_willingness_to_pay, demand_slope)
draw_supply_line(minimum_opportunity_cost, supply_slope)
plt.legend()
fig.canvas.draw()
equilibrium = {"Equilibrium Price": equilibrium_price,
"Equilibrium Quantity": equilibrium_quantity,
"Consumer Surplus": consumer_surplus,
"Producer Surplus": producer_surplus,
"Market": market_for_title}
print_market_summary(consumer_surplus, producer_surplus, equilibrium_price,
equilibrium_quantity, market_for_title)
return fig, ax, equilibrium
# ----
#
# These are calculation and graphics functions for Brad DeLong's jupyter notebooks.
# Should exist in two copies, one each inside the delong_functions directories
# of Brad DeLong's private jupyter notebook backup github repository and of
# Brad DeLong's public eblog-support github repository.
#
# Use: from delong_functions.calc_and_graph_functions import * | import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats
import pandas as pd
plt.style.use('seaborn-whitegrid')
matplotlib.rc("font", family="Verdana")
fig_size = plt.rcParams["figure.figsize"]
fig_size[0] = 6
fig_size[1] = 6
plt.rcParams["figure.figsize"] = fig_size
plt.close('all')
def draw_demand_line(maximum_willingness_to_pay, demand_slope):
"""Draw a linear demand curve when provided with paratmeters in
slope-intercept form.
Parameters
==========
maximum_willingness_to_pay : float
the y-axis (price axis) intercept of the demand curve; the
highest willingness-to-pay for a unit of the commodity found
in the marketplace
demand_slope: float
how many extra units must be purchased to lower the outstanding
highest unsatisfied willingness-to-pay by one dollar; the slope of the
demand curve
Returns
=======
None
"""
axes = plt.gca()
x_vals = np.array(axes.get_xlim())
y_vals = maximum_willingness_to_pay - demand_slope * x_vals
plt.plot(x_vals, y_vals, color = "blue", label = "Demand")
def draw_supply_line(minimum_opportunity_cost, supply_slope):
"""Draw a supply demand curve when provided with paratmeters in
slope-intercept form.
Parameters
==========
minimum_opportunity_cost : float
the y-axis (price axis) intercept of the supply curve; the
lowest price at which the first producer finds it profitable
to produce and sell a unit of the commodity in the marketplace;
the minimum opportunity cost found among producers
supply: float
how many extra units must be purchased to raise the outstanding
lowest remaining opportunity cost by one dollar; the slope of the
supply curve
Returns
=======
None
"""
axes = plt.gca()
x_vals = np.array(axes.get_xlim())
y_vals = minimum_opportunity_cost + supply_slope * x_vals
plt.plot(x_vals, y_vals, color = "green", label = "Supply")
def print_market_summary(consumer_surplus, producer_surplus, equilibrium_price,
equilibrium_quantity, market_for_title):
"""Function to print the crude table of the four market summary equilibrium
summary statistics
Parameters
==========
consumer_surplus : float
the difference between the sum of satisfied willingnesses-to-pay by
purchasers and the sum of prices they paid to suppliers; the maximum
amount that could ever be extracted from purchasers by a threat to close
the market down; calculated in standard_supply_and_demand_graph() and passed
to print_market_summary()
producer_surplus: float
the difference between the sum of revenue earned by suppliers and the
sum of incurred opportunity costs by suppliers; the maximum amount that
could ever be extracted from suppliers by a threat to close the market
down; calculated in standard_supply_and_demand_graph() and passed to
print_market_summary()
equilibrium_price: float
the market price at which quantity supplied is equal to quantity
demanded; calculated in standard_supply_and_demand_graph() and passed
to print_market_summary()
equilibrium_quantity: float
the quantity produced and sold at which quantity supplied is equal to
quantity demanded; calculated in standard_supply_and_demand_graph() and passed
to print_market_summary()
market_for_title : string
the market and commodity of the supply-and-demand equilibrium— for
example: "Lattes at Euphoric State"; passed to standard_supply_and_demand_graph()
and then passed to print_market_summary()
Returns
=======
None
"""
print("")
print("")
print("SUMMARY: MARKET FOR " + market_for_title.upper())
print("")
print(round(consumer_surplus, 3), "= consumer surplus")
print(round(producer_surplus, 3), "= producer surplus")
print(round(equilibrium_price, 3), "= equilibrium price")
print(round(equilibrium_quantity, 3), "= equilibrium quantity")
print("")
print("")
def standard_supply_and_demand_graph(maximum_willingness_to_pay, demand_slope,
minimum_opportunity_cost, supply_slope, market_for_title):
"""
Function to calculate a graph and summary market statistics from slope-intercept
linear descriptions of supply and demand. Requires four floats for **maximum
willingness to pay** on the part of potential demanders, **minimum opportunity
cost** on the part of potential suppliers, demand and supply slopes, and a string
identifying the market and commodity. Returns a matplotlib figure object, an ax
subplots object, and a dictionary of market equilibrium summary statistics
Parameters
==========
consumer_surplus : float
the difference between the sum of satisfied willingnesses-to-pay by
purchasers and the sum of prices they paid to suppliers; the maximum
amount that could ever be extracted from purchasers by a threat to close
the market down; calculated in standard_supply_and_demand_graph() and passed
to print_market_summary()
producer_surplus: float
the difference between the sum of revenue earned by suppliers and the
sum of incurred opportunity costs by suppliers; the maximum amount that
could ever be extracted from suppliers by a threat to close the market
down; calculated in standard_supply_and_demand_graph() and passed to
print_market_summary()
equilibrium_price: float
the market price at which quantity supplied is equal to quantity
demanded; calculated in standard_supply_and_demand_graph() and passed
to print_market_summary()
equilibrium_quantity: float
the quantity produced and sold at which quantity supplied is equal to
quantity demanded; calculated in standard_supply_and_demand_graph() and passed
to print_market_summary()
market_for_title : string
the market and commodity of the supply-and-demand equilibrium— for
example: "Lattes at Euphoric State"; passed to standard_supply_and_demand_graph()
and then passed to print_market_summary()
Returns
=======
fig, ax, eqiilibrium
fig : matplotlib.figure.Figure
the graph drawn by the function: the standard supply-and-demand graph with
title, labels, legend, and annotated equilibrium point
ax : matplotlib.axes._subplots.AxesSubplot
equilibrium : dict
A Python dictionary containing a string identifying the commodity market for
which equilibrium has been calculated, and floats for thefour key market summary
statistics calculated in order to draw the supply-and-demand graph; all
for further reference. The keys to the dictionary are all strings:
"Equilibrium Price"—the market price at which quantity supplied is equal
to quantity demanded; calculated in standard_supply_and_demand_graph()
"Equilibrium Quantity"—the quantity produced and sold at which quantity
supplied is equal to quantity demanded; calculated in
standard_supply_and_demand_graph()
"Consumer Surplus"—the difference between the sum of satisfied
willingnesses-to-pay by purchasers and the sum of prices they paid
to suppliers; the maximum amount that could ever be extracted from
purchasers by a threat to close the market down; calculated in
standard_supply_and_demand_graph()
"Producer Surplus"—the difference between the sum of revenue earned
by suppliers and the sum of incurred opportunity costs by suppliers;
the maximum amount that could ever be extracted from suppliers by any
threat to close the market down; calculated in
standard_supply_and_demand_graph(): producer_surplus,
"Market"—the market and commodity of the supply-and-demand equilibrium—
for example: "Lattes at Euphoric State"; passed to
standard_supply_and_demand_graph()
"""
equilibrium_quantity = ((maximum_willingness_to_pay - minimum_opportunity_cost)/
(supply_slope + demand_slope))
equilibrium_price = (maximum_willingness_to_pay - equilibrium_quantity * demand_slope)
consumer_surplus = ((maximum_willingness_to_pay - equilibrium_price) *
equilibrium_quantity/2)
producer_surplus = ((equilibrium_price - minimum_opportunity_cost) *
equilibrium_quantity/2)
fig, ax = plt.subplots()
max_x_lim = 1.5 * equilibrium_quantity
max_y_lim = 1.2 * maximum_willingness_to_pay
fig.suptitle("Supply and Demand Graph: \n" + market_for_title, size = "20")
ax.set_xlim(0, max_x_lim)
ax.set_ylim(0, max_y_lim)
plt.plot(equilibrium_quantity, equilibrium_price, marker='o',
markersize=8, color="red")
plt.text(equilibrium_quantity, 1.1 * equilibrium_price,
"Market Equilibrium: \n" + "Quantity = " +
str(round(equilibrium_quantity, 2)) + "\nPrice = " +
str(round(equilibrium_price, 2)), size = "8")
plt.xlabel("Number of " + market_for_title, size = "10")
plt.ylabel("Price/Value of " + market_for_title, size = "10")
draw_demand_line(maximum_willingness_to_pay, demand_slope)
draw_supply_line(minimum_opportunity_cost, supply_slope)
plt.legend()
fig.canvas.draw()
equilibrium = {"Equilibrium Price": equilibrium_price,
"Equilibrium Quantity": equilibrium_quantity,
"Consumer Surplus": consumer_surplus,
"Producer Surplus": producer_surplus,
"Market": market_for_title}
print_market_summary(consumer_surplus, producer_surplus, equilibrium_price,
equilibrium_quantity, market_for_title)
return fig, ax, equilibrium
# ----
#
# These are calculation and graphics functions for Brad DeLong's jupyter notebooks.
# Should exist in two copies, one each inside the delong_functions directories
# of Brad DeLong's private jupyter notebook backup github repository and of
# Brad DeLong's public eblog-support github repository.
#
# Use: from delong_functions.calc_and_graph_functions import * | en | 0.888675 | Draw a linear demand curve when provided with paratmeters in slope-intercept form. Parameters ========== maximum_willingness_to_pay : float the y-axis (price axis) intercept of the demand curve; the highest willingness-to-pay for a unit of the commodity found in the marketplace demand_slope: float how many extra units must be purchased to lower the outstanding highest unsatisfied willingness-to-pay by one dollar; the slope of the demand curve Returns ======= None Draw a supply demand curve when provided with paratmeters in slope-intercept form. Parameters ========== minimum_opportunity_cost : float the y-axis (price axis) intercept of the supply curve; the lowest price at which the first producer finds it profitable to produce and sell a unit of the commodity in the marketplace; the minimum opportunity cost found among producers supply: float how many extra units must be purchased to raise the outstanding lowest remaining opportunity cost by one dollar; the slope of the supply curve Returns ======= None Function to print the crude table of the four market summary equilibrium summary statistics Parameters ========== consumer_surplus : float the difference between the sum of satisfied willingnesses-to-pay by purchasers and the sum of prices they paid to suppliers; the maximum amount that could ever be extracted from purchasers by a threat to close the market down; calculated in standard_supply_and_demand_graph() and passed to print_market_summary() producer_surplus: float the difference between the sum of revenue earned by suppliers and the sum of incurred opportunity costs by suppliers; the maximum amount that could ever be extracted from suppliers by a threat to close the market down; calculated in standard_supply_and_demand_graph() and passed to print_market_summary() equilibrium_price: float the market price at which quantity supplied is equal to quantity demanded; calculated in standard_supply_and_demand_graph() and passed to print_market_summary() equilibrium_quantity: float the quantity produced and sold at which quantity supplied is equal to quantity demanded; calculated in standard_supply_and_demand_graph() and passed to print_market_summary() market_for_title : string the market and commodity of the supply-and-demand equilibrium— for example: "Lattes at Euphoric State"; passed to standard_supply_and_demand_graph() and then passed to print_market_summary() Returns ======= None Function to calculate a graph and summary market statistics from slope-intercept linear descriptions of supply and demand. Requires four floats for **maximum willingness to pay** on the part of potential demanders, **minimum opportunity cost** on the part of potential suppliers, demand and supply slopes, and a string identifying the market and commodity. Returns a matplotlib figure object, an ax subplots object, and a dictionary of market equilibrium summary statistics Parameters ========== consumer_surplus : float the difference between the sum of satisfied willingnesses-to-pay by purchasers and the sum of prices they paid to suppliers; the maximum amount that could ever be extracted from purchasers by a threat to close the market down; calculated in standard_supply_and_demand_graph() and passed to print_market_summary() producer_surplus: float the difference between the sum of revenue earned by suppliers and the sum of incurred opportunity costs by suppliers; the maximum amount that could ever be extracted from suppliers by a threat to close the market down; calculated in standard_supply_and_demand_graph() and passed to print_market_summary() equilibrium_price: float the market price at which quantity supplied is equal to quantity demanded; calculated in standard_supply_and_demand_graph() and passed to print_market_summary() equilibrium_quantity: float the quantity produced and sold at which quantity supplied is equal to quantity demanded; calculated in standard_supply_and_demand_graph() and passed to print_market_summary() market_for_title : string the market and commodity of the supply-and-demand equilibrium— for example: "Lattes at Euphoric State"; passed to standard_supply_and_demand_graph() and then passed to print_market_summary() Returns ======= fig, ax, eqiilibrium fig : matplotlib.figure.Figure the graph drawn by the function: the standard supply-and-demand graph with title, labels, legend, and annotated equilibrium point ax : matplotlib.axes._subplots.AxesSubplot equilibrium : dict A Python dictionary containing a string identifying the commodity market for which equilibrium has been calculated, and floats for thefour key market summary statistics calculated in order to draw the supply-and-demand graph; all for further reference. The keys to the dictionary are all strings: "Equilibrium Price"—the market price at which quantity supplied is equal to quantity demanded; calculated in standard_supply_and_demand_graph() "Equilibrium Quantity"—the quantity produced and sold at which quantity supplied is equal to quantity demanded; calculated in standard_supply_and_demand_graph() "Consumer Surplus"—the difference between the sum of satisfied willingnesses-to-pay by purchasers and the sum of prices they paid to suppliers; the maximum amount that could ever be extracted from purchasers by a threat to close the market down; calculated in standard_supply_and_demand_graph() "Producer Surplus"—the difference between the sum of revenue earned by suppliers and the sum of incurred opportunity costs by suppliers; the maximum amount that could ever be extracted from suppliers by any threat to close the market down; calculated in standard_supply_and_demand_graph(): producer_surplus, "Market"—the market and commodity of the supply-and-demand equilibrium— for example: "Lattes at Euphoric State"; passed to standard_supply_and_demand_graph() # ---- # # These are calculation and graphics functions for Brad DeLong's jupyter notebooks. # Should exist in two copies, one each inside the delong_functions directories # of Brad DeLong's private jupyter notebook backup github repository and of # Brad DeLong's public eblog-support github repository. # # Use: from delong_functions.calc_and_graph_functions import * | 3.798036 | 4 |
tprmp/demonstrations/trajectory.py | anindex/tp-rmp | 7 | 6614239 | <filename>tprmp/demonstrations/trajectory.py
import numpy as np
from tprmp.demonstrations.manifold import Manifold
def compute_traj_derivatives(traj, dt, manifold=None, smooth=False):
"""
Estimate the trajectory dynamics.
Parameters
----------
:param traj (np.array of shape (dim_M, length)): trajectory.
:param smooth (boolean): whether smoothing is applied to traj first.
Returns
----------
:return traj (np.array of shape (dim_M, length)): pose trajectory without/with smoothing.
:return d_traj (np.array of shape (dim_T, length)): first derivative of traj.
:return dd_traj (np.array of shape (dim_T, length)): second derivative of traj.
"""
dim_M = traj.shape[0]
if not manifold:
# if no manifold specified, Euclidean manifold is used.
manifold = Manifold.get_euclidean_manifold(dim_M)
# smoothing first
if smooth:
traj = smooth_traj(traj, manifold=manifold)
# compute derivatives
d_traj = compute_traj_velocity(traj, dt, manifold=manifold)
dd_traj = compute_traj_velocity(d_traj, dt)
# copy the last 2 entries (corner case)
dd_traj[:, -2] = dd_traj[:, -3]
dd_traj[:, -1] = dd_traj[:, -3]
return traj, d_traj, dd_traj
def smooth_traj(traj, manifold=None, window_length=30, beta=14):
"""
Smooth the pose using the kaiser window np.kaiser(window_length, beta).
Parameters
----------
:param traj (np.array of shape (dim_M, length)): trajectory.
:param window_length (int): the length of the window. (Default: 30).
:param beta (float): shape parameter for the kaiser window. (Default: 14).
Returns
----------
:return smooth_traj (np.array of shape (M, length)): pose trajectory after smoothing.
"""
dim_M, length = traj.shape[:]
if not manifold:
manifold = Manifold.get_euclidean_manifold(dim_M)
if dim_M != manifold.dim_M:
raise ValueError('[Trajectory]: Input X shape %s is not consistent with manifold.dim_M %s' % (dim_M, manifold.dim_M))
# apply kaiser filter
half_wl = int(window_length / 2)
window = np.kaiser(2 * half_wl, beta)
smooth_traj = traj.copy()
for t in range(length):
weights = window[max(half_wl - t, 0):(2 * half_wl - max(0, t + half_wl - length))]
smooth_traj[:, t] = manifold.mean(smooth_traj[:, max(t - half_wl, 0):(t + half_wl)], weights=weights)
if smooth_traj.shape != traj.shape:
raise ValueError('[Trajectory]: Shape of smoothed_traj is different from input traj')
return smooth_traj
def compute_traj_velocity(traj, dt, manifold=None):
"""
Estimate the first derivative of input trajectory traj.
Parameters
----------
:param traj (np.array of shape (dim_M, length)): trajectory.
:param dt (float): sampling time associated with traj.
Returns
----------
:return d_traj (np.array of shape (dim_T, length)): first derivative of traj.
"""
dim_M, length = traj.shape[:]
if not manifold:
manifold = Manifold.get_euclidean_manifold(dim_M)
if dim_M != manifold.dim_M:
raise ValueError('[Trajectory]: Input X shape %s is not consistent with manifold.dim_M %s' % (dim_M, manifold.dim_M))
# estimate d_traj
d_traj = []
for t in range(length - 1):
d_traj_t = manifold.log_map(traj[:, t + 1], base=traj[:, t]) / dt
d_traj.append(d_traj_t)
d_traj.append(d_traj_t)
d_traj = np.array(d_traj).T
names = np.array(manifold.name.split(' x '))
if 'S^3' in names:
indices = np.where(names == 'S^3')[0]
for i in indices:
d_traj[i * 3:i * 3 + 3] *= 2 # convert to angular
if d_traj.shape[0] != manifold.dim_T:
raise ValueError('[Trajectory]: d_traj shape %s is not consistent with manifold.dim_T %s' % (d_traj.shape[0], manifold.dim_T))
if d_traj.shape[1] != length:
raise ValueError('[Trajectory]: Length of d_traj %s is not consistent with input traj length %s' % (d_traj.shape[1], length))
return d_traj
def interpolate(p1, p2, d_param, dist):
""" interpolate between points """
alpha = min(max(d_param / dist, 0.), 1.)
return (1. - alpha) * p1 + alpha * p2
| <filename>tprmp/demonstrations/trajectory.py
import numpy as np
from tprmp.demonstrations.manifold import Manifold
def compute_traj_derivatives(traj, dt, manifold=None, smooth=False):
"""
Estimate the trajectory dynamics.
Parameters
----------
:param traj (np.array of shape (dim_M, length)): trajectory.
:param smooth (boolean): whether smoothing is applied to traj first.
Returns
----------
:return traj (np.array of shape (dim_M, length)): pose trajectory without/with smoothing.
:return d_traj (np.array of shape (dim_T, length)): first derivative of traj.
:return dd_traj (np.array of shape (dim_T, length)): second derivative of traj.
"""
dim_M = traj.shape[0]
if not manifold:
# if no manifold specified, Euclidean manifold is used.
manifold = Manifold.get_euclidean_manifold(dim_M)
# smoothing first
if smooth:
traj = smooth_traj(traj, manifold=manifold)
# compute derivatives
d_traj = compute_traj_velocity(traj, dt, manifold=manifold)
dd_traj = compute_traj_velocity(d_traj, dt)
# copy the last 2 entries (corner case)
dd_traj[:, -2] = dd_traj[:, -3]
dd_traj[:, -1] = dd_traj[:, -3]
return traj, d_traj, dd_traj
def smooth_traj(traj, manifold=None, window_length=30, beta=14):
"""
Smooth the pose using the kaiser window np.kaiser(window_length, beta).
Parameters
----------
:param traj (np.array of shape (dim_M, length)): trajectory.
:param window_length (int): the length of the window. (Default: 30).
:param beta (float): shape parameter for the kaiser window. (Default: 14).
Returns
----------
:return smooth_traj (np.array of shape (M, length)): pose trajectory after smoothing.
"""
dim_M, length = traj.shape[:]
if not manifold:
manifold = Manifold.get_euclidean_manifold(dim_M)
if dim_M != manifold.dim_M:
raise ValueError('[Trajectory]: Input X shape %s is not consistent with manifold.dim_M %s' % (dim_M, manifold.dim_M))
# apply kaiser filter
half_wl = int(window_length / 2)
window = np.kaiser(2 * half_wl, beta)
smooth_traj = traj.copy()
for t in range(length):
weights = window[max(half_wl - t, 0):(2 * half_wl - max(0, t + half_wl - length))]
smooth_traj[:, t] = manifold.mean(smooth_traj[:, max(t - half_wl, 0):(t + half_wl)], weights=weights)
if smooth_traj.shape != traj.shape:
raise ValueError('[Trajectory]: Shape of smoothed_traj is different from input traj')
return smooth_traj
def compute_traj_velocity(traj, dt, manifold=None):
"""
Estimate the first derivative of input trajectory traj.
Parameters
----------
:param traj (np.array of shape (dim_M, length)): trajectory.
:param dt (float): sampling time associated with traj.
Returns
----------
:return d_traj (np.array of shape (dim_T, length)): first derivative of traj.
"""
dim_M, length = traj.shape[:]
if not manifold:
manifold = Manifold.get_euclidean_manifold(dim_M)
if dim_M != manifold.dim_M:
raise ValueError('[Trajectory]: Input X shape %s is not consistent with manifold.dim_M %s' % (dim_M, manifold.dim_M))
# estimate d_traj
d_traj = []
for t in range(length - 1):
d_traj_t = manifold.log_map(traj[:, t + 1], base=traj[:, t]) / dt
d_traj.append(d_traj_t)
d_traj.append(d_traj_t)
d_traj = np.array(d_traj).T
names = np.array(manifold.name.split(' x '))
if 'S^3' in names:
indices = np.where(names == 'S^3')[0]
for i in indices:
d_traj[i * 3:i * 3 + 3] *= 2 # convert to angular
if d_traj.shape[0] != manifold.dim_T:
raise ValueError('[Trajectory]: d_traj shape %s is not consistent with manifold.dim_T %s' % (d_traj.shape[0], manifold.dim_T))
if d_traj.shape[1] != length:
raise ValueError('[Trajectory]: Length of d_traj %s is not consistent with input traj length %s' % (d_traj.shape[1], length))
return d_traj
def interpolate(p1, p2, d_param, dist):
""" interpolate between points """
alpha = min(max(d_param / dist, 0.), 1.)
return (1. - alpha) * p1 + alpha * p2
| en | 0.578026 | Estimate the trajectory dynamics. Parameters ---------- :param traj (np.array of shape (dim_M, length)): trajectory. :param smooth (boolean): whether smoothing is applied to traj first. Returns ---------- :return traj (np.array of shape (dim_M, length)): pose trajectory without/with smoothing. :return d_traj (np.array of shape (dim_T, length)): first derivative of traj. :return dd_traj (np.array of shape (dim_T, length)): second derivative of traj. # if no manifold specified, Euclidean manifold is used. # smoothing first # compute derivatives # copy the last 2 entries (corner case) Smooth the pose using the kaiser window np.kaiser(window_length, beta). Parameters ---------- :param traj (np.array of shape (dim_M, length)): trajectory. :param window_length (int): the length of the window. (Default: 30). :param beta (float): shape parameter for the kaiser window. (Default: 14). Returns ---------- :return smooth_traj (np.array of shape (M, length)): pose trajectory after smoothing. # apply kaiser filter Estimate the first derivative of input trajectory traj. Parameters ---------- :param traj (np.array of shape (dim_M, length)): trajectory. :param dt (float): sampling time associated with traj. Returns ---------- :return d_traj (np.array of shape (dim_T, length)): first derivative of traj. # estimate d_traj # convert to angular interpolate between points | 2.982407 | 3 |
modules/libraries/roll.py | HeercoGrond/Cha5ebot | 0 | 6614240 | from random import randint
import re
def roll_dice(argument):
"""Rolls dice based on a {x}d{y}+{z} pattern where the only necessary argument is at the very least a d{y}.
This will return a message that can be sent.
"""
result = [0, ""]
detailed = "detailed" in argument
firstcheck = re.search(r'[0-9]+d[0-9]+[+][0-9]+', argument)
if firstcheck:
outcomeList = "{"
matchString = str(firstcheck.group())
argsList = matchString.split('d')
splitArg = argsList[1].split('+')
diceAmount = int(argsList[0])
diceEyes = int(splitArg[0])
bonus = int(splitArg[1])
outcome = 0
for _ in range(1, diceAmount + 1):
randomNumber = randint(1, diceEyes)
if detailed:
outcomeList += str(randomNumber) + " , "
outcome += randomNumber
outcome += bonus
message = "Rolled " + str(diceAmount) + " d" + str(diceEyes) + " with a bonus of " + str(bonus) + " for a total count of: " + str(outcome)
if detailed:
message += " | Details on the rolls: " + outcomeList + " }"
result[0] = outcome
result[1] = message
else:
secondCheck = re.search(r'[0-9]+d[0-9]+', argument)
if secondCheck:
outcomeList = "{ "
matchedString = str(secondCheck.group())
argsList = matchedString.split('d')
diceAmount = int(argsList[0])
diceEyes = int(argsList[1])
outcome = 0
for _ in range(1, diceAmount + 1):
randomNumber = randint(1, diceEyes)
if detailed:
outcomeList += str(randomNumber) + " , "
outcome += randomNumber
message = "Rolled " + str(diceAmount) + " d" + str(diceEyes) + " for a total count of: " + str(outcome)
if detailed:
message += " | Details on the rolls: " + outcomeList + " }"
result[0] = outcome
result[1] = message
else:
tertiaryCheck = re.search(r'd[0-9]+', argument)
if tertiaryCheck:
matchedString = str(tertiaryCheck.group())
argsList = matchedString.split('d')
diceEyes = int(argsList[1])
outcome = randint(1, diceEyes)
message = "Rolled a d" + str(diceEyes) + " for: " + str(outcome)
result[0] = outcome
result[1] = message
else:
message = "That is not a valid die. Proper formatting is `>roll {x]d{y}+{z}`, `>roll {x]d{y}` or `>roll d{x}`"
result[1] = message
return result
| from random import randint
import re
def roll_dice(argument):
"""Rolls dice based on a {x}d{y}+{z} pattern where the only necessary argument is at the very least a d{y}.
This will return a message that can be sent.
"""
result = [0, ""]
detailed = "detailed" in argument
firstcheck = re.search(r'[0-9]+d[0-9]+[+][0-9]+', argument)
if firstcheck:
outcomeList = "{"
matchString = str(firstcheck.group())
argsList = matchString.split('d')
splitArg = argsList[1].split('+')
diceAmount = int(argsList[0])
diceEyes = int(splitArg[0])
bonus = int(splitArg[1])
outcome = 0
for _ in range(1, diceAmount + 1):
randomNumber = randint(1, diceEyes)
if detailed:
outcomeList += str(randomNumber) + " , "
outcome += randomNumber
outcome += bonus
message = "Rolled " + str(diceAmount) + " d" + str(diceEyes) + " with a bonus of " + str(bonus) + " for a total count of: " + str(outcome)
if detailed:
message += " | Details on the rolls: " + outcomeList + " }"
result[0] = outcome
result[1] = message
else:
secondCheck = re.search(r'[0-9]+d[0-9]+', argument)
if secondCheck:
outcomeList = "{ "
matchedString = str(secondCheck.group())
argsList = matchedString.split('d')
diceAmount = int(argsList[0])
diceEyes = int(argsList[1])
outcome = 0
for _ in range(1, diceAmount + 1):
randomNumber = randint(1, diceEyes)
if detailed:
outcomeList += str(randomNumber) + " , "
outcome += randomNumber
message = "Rolled " + str(diceAmount) + " d" + str(diceEyes) + " for a total count of: " + str(outcome)
if detailed:
message += " | Details on the rolls: " + outcomeList + " }"
result[0] = outcome
result[1] = message
else:
tertiaryCheck = re.search(r'd[0-9]+', argument)
if tertiaryCheck:
matchedString = str(tertiaryCheck.group())
argsList = matchedString.split('d')
diceEyes = int(argsList[1])
outcome = randint(1, diceEyes)
message = "Rolled a d" + str(diceEyes) + " for: " + str(outcome)
result[0] = outcome
result[1] = message
else:
message = "That is not a valid die. Proper formatting is `>roll {x]d{y}+{z}`, `>roll {x]d{y}` or `>roll d{x}`"
result[1] = message
return result
| en | 0.810372 | Rolls dice based on a {x}d{y}+{z} pattern where the only necessary argument is at the very least a d{y}. This will return a message that can be sent. | 3.455001 | 3 |
gradgpad/tools/visualization/histogram/split_by_level_mode.py | acostapazo/gradgpad | 9 | 6614241 | from enum import Enum
from typing import List
class SplitByLabelMode(Enum):
NONE = "none"
PAS = "presentation_attack_scenario"
SEX = "sex"
AGE = "age"
SKIN_TONE = "skin_tone"
DATASET = "dataset"
DATASET_GENUINE = "dataset_genuine"
DATASET_PAS_TYPE_I = "dataset_pas_type_I"
DATASET_PAS_TYPE_II = "dataset_pas_type_II"
DATASET_PAS_TYPE_III = "dataset_pas_type_III"
@staticmethod
def options() -> List:
return [
SplitByLabelMode.NONE,
SplitByLabelMode.PAS,
SplitByLabelMode.SEX,
SplitByLabelMode.AGE,
SplitByLabelMode.SKIN_TONE,
SplitByLabelMode.DATASET,
SplitByLabelMode.DATASET_GENUINE,
SplitByLabelMode.DATASET_PAS_TYPE_I,
SplitByLabelMode.DATASET_PAS_TYPE_II,
SplitByLabelMode.DATASET_PAS_TYPE_III,
]
@staticmethod
def options_for_curves():
return [
SplitByLabelMode.NONE,
SplitByLabelMode.SEX,
SplitByLabelMode.AGE,
SplitByLabelMode.SKIN_TONE,
SplitByLabelMode.PAS,
]
| from enum import Enum
from typing import List
class SplitByLabelMode(Enum):
NONE = "none"
PAS = "presentation_attack_scenario"
SEX = "sex"
AGE = "age"
SKIN_TONE = "skin_tone"
DATASET = "dataset"
DATASET_GENUINE = "dataset_genuine"
DATASET_PAS_TYPE_I = "dataset_pas_type_I"
DATASET_PAS_TYPE_II = "dataset_pas_type_II"
DATASET_PAS_TYPE_III = "dataset_pas_type_III"
@staticmethod
def options() -> List:
return [
SplitByLabelMode.NONE,
SplitByLabelMode.PAS,
SplitByLabelMode.SEX,
SplitByLabelMode.AGE,
SplitByLabelMode.SKIN_TONE,
SplitByLabelMode.DATASET,
SplitByLabelMode.DATASET_GENUINE,
SplitByLabelMode.DATASET_PAS_TYPE_I,
SplitByLabelMode.DATASET_PAS_TYPE_II,
SplitByLabelMode.DATASET_PAS_TYPE_III,
]
@staticmethod
def options_for_curves():
return [
SplitByLabelMode.NONE,
SplitByLabelMode.SEX,
SplitByLabelMode.AGE,
SplitByLabelMode.SKIN_TONE,
SplitByLabelMode.PAS,
]
| none | 1 | 2.943174 | 3 | |
Shoutout/apps.py | Poornartha/Odonata | 0 | 6614242 | <reponame>Poornartha/Odonata
from django.apps import AppConfig
class ShoutoutConfig(AppConfig):
name = 'Shoutout'
| from django.apps import AppConfig
class ShoutoutConfig(AppConfig):
name = 'Shoutout' | none | 1 | 1.005543 | 1 | |
week3/ex2_gradient_descent_with_minimize.py | ankyhe/coursera-quiz-assignment | 0 | 6614243 | <reponame>ankyhe/coursera-quiz-assignment
import numpy as np
from scipy.optimize import minimize
import matplotlib.pyplot as plt
from utils import sigmoid, load_data, plot_data, feature_map
epsilon = 1e-5
def cost_function_reg(theta, reg, *args):
#print('args\n{0}\naaa'.format(args))
y = args[1]
X = args[0]
m = y.size
h = sigmoid.sigmoid(X.dot(theta))
J = -1 * (1 / m) * (np.log(h + epsilon).T.dot(y) + np.log(1 - h + epsilon).T.dot(1 - y)) + (reg/(2*m))*np.sum(np.square(theta[1:]))
return J[0]
def gradient_reg(theta, reg, *args):
y = args[1]
X = args[0]
m = y.size
h = sigmoid.sigmoid(X.dot(theta.reshape(-1, 1)))
grad = (1 / m) * X.T.dot(h - y) + (reg/m) * np.r_[[[0]], theta[1:].reshape(-1, 1)]
return grad.flatten()
def predict(theta, X, threshold=0.5):
p = sigmoid.sigmoid(X.dot(theta.T)) >= threshold
return(p.astype('int'))
def plotData(data, label_x, label_y, label_pos, label_neg, axes=None):
# Get indexes for class 0 and class 1
neg = data[:, 2] == 0
pos = data[:, 2] == 1
# If no specific axes object has been passed, get the current axes.
if axes == None:
axes = plt.gca()
axes.scatter(data[pos][:, 0], data[pos][:, 1], marker='+', c='k', s=60, linewidth=2, label=label_pos)
axes.scatter(data[neg][:, 0], data[neg][:, 1], c='y', s=60, label=label_neg)
axes.set_xlabel(label_x)
axes.set_ylabel(label_y)
axes.legend(frameon=True, fancybox=True);
def main():
fig, axes = plt.subplots(1, 3, sharey=True, figsize=(17, 5))
data = load_data.load('data2.txt', dtype = np.float128)
X = data[:, 0:2]
X_map = feature_map.map(X)
y = data[:, 2].reshape(-1, 1)
initial_theta = np.zeros(X_map.shape[1])
#C = 0
#res = minimize(cost_function_reg, initial_theta, args=(C, X_map, y), method=None, jac=gradient_reg, options={'maxiter': 3000})
#print(res)
for i, C in enumerate([0, 1, 100]):
# Optimize costFunctionReg
res2 = minimize(cost_function_reg, initial_theta, args=(C, X_map, y), method=None, jac=gradient_reg,options={'maxiter': 3000})
accuracy = 100 * sum(predict(res2.x, X_map) == y.ravel()) / y.size
plotData(data, 'Microchip Test 1', 'Microchip Test 2', 'y = 1', 'y = 0', axes.flatten()[i])
# Plot decisionboundary
x1_min, x1_max = X[:, 0].min(), X[:, 0].max(),
x2_min, x2_max = X[:, 1].min(), X[:, 1].max(),
xx1, xx2 = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max))
h = sigmoid.sigmoid(feature_map.map(np.c_[xx1.ravel(), xx2.ravel()]).dot(res2.x.reshape(-1, 1)))
h = h.reshape(xx1.shape)
axes.flatten()[i].contour(xx1, xx2, h, [0.5], linewidths=1, colors='g');
axes.flatten()[i].set_title('Train accuracy {}% with Lambda = {}'.format(np.round(accuracy, decimals=2), C))
plt.show()
if __name__ == '__main__':
main()
| import numpy as np
from scipy.optimize import minimize
import matplotlib.pyplot as plt
from utils import sigmoid, load_data, plot_data, feature_map
epsilon = 1e-5
def cost_function_reg(theta, reg, *args):
#print('args\n{0}\naaa'.format(args))
y = args[1]
X = args[0]
m = y.size
h = sigmoid.sigmoid(X.dot(theta))
J = -1 * (1 / m) * (np.log(h + epsilon).T.dot(y) + np.log(1 - h + epsilon).T.dot(1 - y)) + (reg/(2*m))*np.sum(np.square(theta[1:]))
return J[0]
def gradient_reg(theta, reg, *args):
y = args[1]
X = args[0]
m = y.size
h = sigmoid.sigmoid(X.dot(theta.reshape(-1, 1)))
grad = (1 / m) * X.T.dot(h - y) + (reg/m) * np.r_[[[0]], theta[1:].reshape(-1, 1)]
return grad.flatten()
def predict(theta, X, threshold=0.5):
p = sigmoid.sigmoid(X.dot(theta.T)) >= threshold
return(p.astype('int'))
def plotData(data, label_x, label_y, label_pos, label_neg, axes=None):
# Get indexes for class 0 and class 1
neg = data[:, 2] == 0
pos = data[:, 2] == 1
# If no specific axes object has been passed, get the current axes.
if axes == None:
axes = plt.gca()
axes.scatter(data[pos][:, 0], data[pos][:, 1], marker='+', c='k', s=60, linewidth=2, label=label_pos)
axes.scatter(data[neg][:, 0], data[neg][:, 1], c='y', s=60, label=label_neg)
axes.set_xlabel(label_x)
axes.set_ylabel(label_y)
axes.legend(frameon=True, fancybox=True);
def main():
fig, axes = plt.subplots(1, 3, sharey=True, figsize=(17, 5))
data = load_data.load('data2.txt', dtype = np.float128)
X = data[:, 0:2]
X_map = feature_map.map(X)
y = data[:, 2].reshape(-1, 1)
initial_theta = np.zeros(X_map.shape[1])
#C = 0
#res = minimize(cost_function_reg, initial_theta, args=(C, X_map, y), method=None, jac=gradient_reg, options={'maxiter': 3000})
#print(res)
for i, C in enumerate([0, 1, 100]):
# Optimize costFunctionReg
res2 = minimize(cost_function_reg, initial_theta, args=(C, X_map, y), method=None, jac=gradient_reg,options={'maxiter': 3000})
accuracy = 100 * sum(predict(res2.x, X_map) == y.ravel()) / y.size
plotData(data, 'Microchip Test 1', 'Microchip Test 2', 'y = 1', 'y = 0', axes.flatten()[i])
# Plot decisionboundary
x1_min, x1_max = X[:, 0].min(), X[:, 0].max(),
x2_min, x2_max = X[:, 1].min(), X[:, 1].max(),
xx1, xx2 = np.meshgrid(np.linspace(x1_min, x1_max), np.linspace(x2_min, x2_max))
h = sigmoid.sigmoid(feature_map.map(np.c_[xx1.ravel(), xx2.ravel()]).dot(res2.x.reshape(-1, 1)))
h = h.reshape(xx1.shape)
axes.flatten()[i].contour(xx1, xx2, h, [0.5], linewidths=1, colors='g');
axes.flatten()[i].set_title('Train accuracy {}% with Lambda = {}'.format(np.round(accuracy, decimals=2), C))
plt.show()
if __name__ == '__main__':
main() | en | 0.426072 | #print('args\n{0}\naaa'.format(args)) # Get indexes for class 0 and class 1 # If no specific axes object has been passed, get the current axes. #C = 0 #res = minimize(cost_function_reg, initial_theta, args=(C, X_map, y), method=None, jac=gradient_reg, options={'maxiter': 3000}) #print(res) # Optimize costFunctionReg # Plot decisionboundary | 2.981797 | 3 |
unittest_reinvent/scoring_tests/scoring_components/fixtures.py | MolecularAI/reinvent-scoring | 0 | 6614244 | <filename>unittest_reinvent/scoring_tests/scoring_components/fixtures.py
from typing import List
import numpy as np
from rdkit import Chem
from reinvent_scoring import ComponentParameters, TanimotoSimilarity, ScoringFunctionComponentNameEnum, JaccardDistance
from reinvent_scoring.scoring.score_components import BaseScoreComponent
from unittest_reinvent.fixtures.test_data import BUTANE, CELECOXIB
def instantiate_component(smiles: List[str] = None, specific_parameters: dict = None):
if specific_parameters is None:
specific_parameters = {}
if smiles is None:
smiles = [BUTANE, CELECOXIB]
specific_parameters['smiles'] = smiles
return TanimotoSimilarity(ComponentParameters(
component_type=ScoringFunctionComponentNameEnum().TANIMOTO_SIMILARITY,
name="tanimoto_similarity",
weight=1.,
specific_parameters=specific_parameters))
def instantiate_jaccard_component(smiles: List[str] = None, specific_parameters: dict = None):
if specific_parameters is None:
specific_parameters = {}
if smiles is None:
smiles = [BUTANE, CELECOXIB]
specific_parameters['smiles'] = smiles
return JaccardDistance(
ComponentParameters(
component_type=ScoringFunctionComponentNameEnum().JACCARD_DISTANCE,
name="jaccard_distance",
weight=1.0,
specific_parameters=specific_parameters,
)
)
def score(component: BaseScoreComponent, smiles: List[str]) -> np.array:
"""Calculates score for a list of SMILES strings."""
mols = [Chem.MolFromSmiles(s) for s in smiles]
score = component.calculate_score(mols)
return score.total_score
def score_single(component: BaseScoreComponent, smi: str) -> float:
"""Calculates score for a single SMILES string."""
mol = Chem.MolFromSmiles(smi)
score = component.calculate_score([mol])
return score.total_score[0]
| <filename>unittest_reinvent/scoring_tests/scoring_components/fixtures.py
from typing import List
import numpy as np
from rdkit import Chem
from reinvent_scoring import ComponentParameters, TanimotoSimilarity, ScoringFunctionComponentNameEnum, JaccardDistance
from reinvent_scoring.scoring.score_components import BaseScoreComponent
from unittest_reinvent.fixtures.test_data import BUTANE, CELECOXIB
def instantiate_component(smiles: List[str] = None, specific_parameters: dict = None):
if specific_parameters is None:
specific_parameters = {}
if smiles is None:
smiles = [BUTANE, CELECOXIB]
specific_parameters['smiles'] = smiles
return TanimotoSimilarity(ComponentParameters(
component_type=ScoringFunctionComponentNameEnum().TANIMOTO_SIMILARITY,
name="tanimoto_similarity",
weight=1.,
specific_parameters=specific_parameters))
def instantiate_jaccard_component(smiles: List[str] = None, specific_parameters: dict = None):
if specific_parameters is None:
specific_parameters = {}
if smiles is None:
smiles = [BUTANE, CELECOXIB]
specific_parameters['smiles'] = smiles
return JaccardDistance(
ComponentParameters(
component_type=ScoringFunctionComponentNameEnum().JACCARD_DISTANCE,
name="jaccard_distance",
weight=1.0,
specific_parameters=specific_parameters,
)
)
def score(component: BaseScoreComponent, smiles: List[str]) -> np.array:
"""Calculates score for a list of SMILES strings."""
mols = [Chem.MolFromSmiles(s) for s in smiles]
score = component.calculate_score(mols)
return score.total_score
def score_single(component: BaseScoreComponent, smi: str) -> float:
"""Calculates score for a single SMILES string."""
mol = Chem.MolFromSmiles(smi)
score = component.calculate_score([mol])
return score.total_score[0]
| en | 0.725651 | Calculates score for a list of SMILES strings. Calculates score for a single SMILES string. | 2.461021 | 2 |
smd/data/__init__.py | qlemaire22/speech-music-detection | 71 | 6614245 | """Module for all functions related to the data."""
from __future__ import absolute_import
from . import data_generator
from . import dataset_loader
__all__ = ['data_generator', 'dataset_loader']
| """Module for all functions related to the data."""
from __future__ import absolute_import
from . import data_generator
from . import dataset_loader
__all__ = ['data_generator', 'dataset_loader']
| en | 0.572513 | Module for all functions related to the data. | 1.129221 | 1 |
linebot/models/message.py | tominaga443/globalbot | 2 | 6614246 | <reponame>tominaga443/globalbot<gh_stars>1-10
from collections import namedtuple
from linebot.models.line_types import ContentType
from linebot.models.line_response import LineResponse
Location = namedtuple("Location", ["title", "address", "latitude", "longitude"])
class Message():
def __init__(self,
message_id="",
content_type=ContentType.text,
from_mid="",
created_time=0,
to_mids=(),
to_type=1,
content_metadata=None,
text="",
location=None):
self.message_id = message_id
self.content_type = content_type
self.from_mid = from_mid
self.created_time = created_time # todo: to datetime
self.to_mids = list(to_mids)
self.to_type = to_type
self.content_metadata = content_metadata
self.text = text
self.location = location
@classmethod
def parse(cls, body):
instance = Message(
body["id"],
ContentType(int(body["contentType"])),
body["from"],
body["createdTime"],
body["to"],
body["toType"],
body["contentMetadata"],
body["text"]
)
if "location" in body and body["location"] is not None:
loc = body["location"]
instance.location = Location(loc["title"], loc["address"], loc["latitude"], loc["longitude"])
return instance
def reply(self) -> LineResponse:
resp = LineResponse(self.from_mid)
return resp
| from collections import namedtuple
from linebot.models.line_types import ContentType
from linebot.models.line_response import LineResponse
Location = namedtuple("Location", ["title", "address", "latitude", "longitude"])
class Message():
def __init__(self,
message_id="",
content_type=ContentType.text,
from_mid="",
created_time=0,
to_mids=(),
to_type=1,
content_metadata=None,
text="",
location=None):
self.message_id = message_id
self.content_type = content_type
self.from_mid = from_mid
self.created_time = created_time # todo: to datetime
self.to_mids = list(to_mids)
self.to_type = to_type
self.content_metadata = content_metadata
self.text = text
self.location = location
@classmethod
def parse(cls, body):
instance = Message(
body["id"],
ContentType(int(body["contentType"])),
body["from"],
body["createdTime"],
body["to"],
body["toType"],
body["contentMetadata"],
body["text"]
)
if "location" in body and body["location"] is not None:
loc = body["location"]
instance.location = Location(loc["title"], loc["address"], loc["latitude"], loc["longitude"])
return instance
def reply(self) -> LineResponse:
resp = LineResponse(self.from_mid)
return resp | pt | 0.356277 | # todo: to datetime | 2.581297 | 3 |
tests/test_shuffle.py | ytoren/pysimscale | 2 | 6614247 | import pytest
from numpy import allclose, array
from scipy.sparse import csr_matrix, issparse
from pysimscale import row_shuffle_matrix, sim_matrix_shuffle
def test_wrong_permutation1():
with pytest.raises(ValueError):
sim_matrix_shuffle(
array([[1.0, 0.0], [0.0, 1.0]]),
[0,1,2,3],
check=True
)
def test_wrong_permutation2s():
with pytest.raises(ValueError):
sim_matrix_shuffle(
array([[1.0, 0.0], [0.0, 1.0]]),
[0,2],
check=True
)
def test_row_shuffle_matrix():
expected_shuffle_matrix = array([
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 0]
])
assert allclose(row_shuffle_matrix([0, 5, 2, 3, 4, 1]).toarray(), expected_shuffle_matrix)
def test_sparse_output():
m = csr_matrix(array([
[1.0, 0.9, 0.0],
[0.9, 1.0, 0.6],
[0.0, 0.6, 1.0],
]))
assert issparse(sim_matrix_shuffle(m, row_order=[1,0,2]))
def test_same_order():
m = array([
[1.0, 0.9, 0.0],
[0.9, 1.0, 0.6],
[0.0, 0.6, 1.0],
])
assert allclose(sim_matrix_shuffle(m, row_order=[0,1,2]), m)
def test_sim_matrix_shuffle():
m = csr_matrix(array([
[1.0, 0.9, 0.0, 0.2, 0.0, 0.1],
[0.9, 1.0, 0.6, 0.0, 0.0, 0.0],
[0.0, 0.6, 1.0, 0.0, 0.5, 0.0],
[0.2, 0.0, 0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 0.5, 0.0, 1.0, 0.8],
[0.1, 0.0, 0.0, 0.0, 0.8, 1.0]
]))
expected = array([
[1.0, 0.1, 0.0, 0.2, 0.0, 0.9],
[0.1, 1.0, 0.0, 0.0, 0.8, 0.0],
[0.0, 0.0, 1.0, 0.0, 0.5, 0.6],
[0.2, 0.0, 0.0, 1.0, 0.0, 0.0],
[0.0, 0.8, 0.5, 0.0, 1.0, 0.0],
[0.9, 0.0, 0.6, 0.0, 0.0, 1.0]
])
m_shuffled = sim_matrix_shuffle(m, row_order=[0, 5, 2, 3, 4, 1])
assert allclose(m_shuffled.todense(), expected)
| import pytest
from numpy import allclose, array
from scipy.sparse import csr_matrix, issparse
from pysimscale import row_shuffle_matrix, sim_matrix_shuffle
def test_wrong_permutation1():
with pytest.raises(ValueError):
sim_matrix_shuffle(
array([[1.0, 0.0], [0.0, 1.0]]),
[0,1,2,3],
check=True
)
def test_wrong_permutation2s():
with pytest.raises(ValueError):
sim_matrix_shuffle(
array([[1.0, 0.0], [0.0, 1.0]]),
[0,2],
check=True
)
def test_row_shuffle_matrix():
expected_shuffle_matrix = array([
[1, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1],
[0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 0]
])
assert allclose(row_shuffle_matrix([0, 5, 2, 3, 4, 1]).toarray(), expected_shuffle_matrix)
def test_sparse_output():
m = csr_matrix(array([
[1.0, 0.9, 0.0],
[0.9, 1.0, 0.6],
[0.0, 0.6, 1.0],
]))
assert issparse(sim_matrix_shuffle(m, row_order=[1,0,2]))
def test_same_order():
m = array([
[1.0, 0.9, 0.0],
[0.9, 1.0, 0.6],
[0.0, 0.6, 1.0],
])
assert allclose(sim_matrix_shuffle(m, row_order=[0,1,2]), m)
def test_sim_matrix_shuffle():
m = csr_matrix(array([
[1.0, 0.9, 0.0, 0.2, 0.0, 0.1],
[0.9, 1.0, 0.6, 0.0, 0.0, 0.0],
[0.0, 0.6, 1.0, 0.0, 0.5, 0.0],
[0.2, 0.0, 0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 0.5, 0.0, 1.0, 0.8],
[0.1, 0.0, 0.0, 0.0, 0.8, 1.0]
]))
expected = array([
[1.0, 0.1, 0.0, 0.2, 0.0, 0.9],
[0.1, 1.0, 0.0, 0.0, 0.8, 0.0],
[0.0, 0.0, 1.0, 0.0, 0.5, 0.6],
[0.2, 0.0, 0.0, 1.0, 0.0, 0.0],
[0.0, 0.8, 0.5, 0.0, 1.0, 0.0],
[0.9, 0.0, 0.6, 0.0, 0.0, 1.0]
])
m_shuffled = sim_matrix_shuffle(m, row_order=[0, 5, 2, 3, 4, 1])
assert allclose(m_shuffled.todense(), expected)
| none | 1 | 2.211605 | 2 | |
app/api/queries.py | metamapper-io/metamapper | 3 | 6614248 | # -*- coding: utf-8 -*-
import graphene
from app.api.schema import ApiTokenType
from app.authorization.fields import AuthConnectionField
from app.authorization import permissions as auth_perms
class Query(graphene.ObjectType):
"""Queries related to the api models.
"""
api_tokens = AuthConnectionField(ApiTokenType)
@auth_perms.permissions_required((auth_perms.WorkspaceOwnersOnly,))
def resolve_api_tokens(self, info, *args, **kwargs):
"""Retrieve the API tokens associated with this workspace.
"""
return info.context.workspace.api_tokens.order_by('created_at')
| # -*- coding: utf-8 -*-
import graphene
from app.api.schema import ApiTokenType
from app.authorization.fields import AuthConnectionField
from app.authorization import permissions as auth_perms
class Query(graphene.ObjectType):
"""Queries related to the api models.
"""
api_tokens = AuthConnectionField(ApiTokenType)
@auth_perms.permissions_required((auth_perms.WorkspaceOwnersOnly,))
def resolve_api_tokens(self, info, *args, **kwargs):
"""Retrieve the API tokens associated with this workspace.
"""
return info.context.workspace.api_tokens.order_by('created_at')
| en | 0.863806 | # -*- coding: utf-8 -*- Queries related to the api models. Retrieve the API tokens associated with this workspace. | 2.345629 | 2 |
src/adult.py | fferrara/interpretable-classification | 0 | 6614249 | <reponame>fferrara/interpretable-classification
import pandas as pd
import numpy as np
from pandas.api.types import is_numeric_dtype
from sklearn.metrics import roc_auc_score
from sklearn.preprocessing import OrdinalEncoder, LabelEncoder
from sklearn.model_selection import cross_val_score
from skopt import gp_minimize
from skopt.space import Real, Integer
from skopt.utils import use_named_args
import xgboost
from pdpbox.pdp import pdp_isolate, pdp_plot
import warnings
class AdultIncome:
def __init__(self, path=None):
train_path = path and path + '/adult.data' or 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data'
test_path = path and path + '/adult.test' or 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test'
df = pd.read_csv(train_path,
header=None,
na_values="?")
df_test = pd.read_csv(test_path,
header=None, skiprows=1,
na_values="?")
df.columns = ['age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status', 'occupation',
'relationship', 'race', 'sex', 'capital-gain', 'capital-loss', 'hours-per-week', 'native-country',
'target']
le = LabelEncoder()
self.y = pd.Series(le.fit_transform(df.target))
self.X = df.drop('target', axis=1)
self.X_train = None
self.fitted_model = None
df_test.columns = df.columns
df_test['target'] = df_test.target.str.rstrip('.')
self.test = df_test.drop('target', axis=1)
self.y_test = le.transform(df_test.target)
self.X_test = None
self.search_iterations = 10
self.search_space = [
Integer(20, 81, name='n_estimators'),
Integer(3, 10, name='max_depth'),
Integer(1, 12, name='min_child_weight'),
Real(0, 0.3, "uniform", name='gamma'),
Real(0.5, 0.9, "uniform", name='subsample'),
Real(0.5, 0.9, "uniform", name='colsample_bytree')
]
def _repr_html_(self):
print('------ Features -------')
print(self.X.info())
print()
print('------ Target distribution ----')
print(self.y.hist())
def preprocess(self):
X_train = self.X.copy()
X_test = self.test.copy()
columns_missing_values = self.X.columns[self.X.isnull().any()]
for column in columns_missing_values:
# X_train[column + '_missing'] = X[column].isnull()
if is_numeric_dtype(self.X[column].dtype):
X_train[column] = self.X[column].fillna(self.X[column].mean())
else:
X_train[column] = self.X[column].fillna('missing')
columns_missing_values = self.test.columns[self.test.isnull().any()]
for column in columns_missing_values:
# X_train[column + '_missing'] = X[column].isnull()
if is_numeric_dtype(self.test[column].dtype):
X_test[column] = self.test[column].fillna(self.test[column].mean())
else:
X_test[column] = self.test[column].fillna('missing')
self.categorical = X_train.select_dtypes(include=np.object)
categories = [list(self.X[c].dropna().unique()) for c in self.categorical]
for i, c in enumerate(self.categorical):
categories[i].extend(X_test[c].dropna().unique())
categories[i].append('missing')
categories = [sorted(set(c)) for c in categories]
self.encoder = OrdinalEncoder(categories)
self.encoder.handle_unknown = 'ignore'
encoded = self.encoder.fit_transform(self.categorical)
for i, column in enumerate(self.categorical.columns):
X_train[column] = encoded[:, i]
test_categorical = X_test.select_dtypes(include=np.object)
encoded = self.encoder.transform(test_categorical)
for i, column in enumerate(test_categorical.columns):
X_test[column] = encoded[:, i]
self.X_train = X_train
self.X_test = X_test
return X_train
def fit(self):
if self.X_train is None or len(self.X.columns) < len(self.X_train.columns):
self.preprocess()
if self.fitted_model is None:
self.monotonic = [0] * len(self.X_train.columns)
estimator = xgboost.XGBClassifier(
learning_rate=0.1, max_features='sqrt', monotone_constraints=str(tuple(self.monotonic)), random_state=666,
scale_pos_weight=sum(self.y == 0) / sum(self.y == 1), base_score=self.y.mean())
@use_named_args(self.search_space)
def objective(**params):
estimator.set_params(**params)
scores = cross_val_score(estimator, self.X_train, self.y, cv=5, n_jobs=-1, scoring='roc_auc')
return -np.mean(scores)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
result = gp_minimize(
objective,
self.search_space,
n_points=1000,
n_calls=self.search_iterations,
n_random_starts=10,
acq_optimizer='lbfgs',
n_jobs=-1,
callback=self._show_progress,
random_state=666)
best_params = {f.name: value for (f, value) in zip(self.search_space, result.x)}
model = xgboost.XGBClassifier(
learning_rate=0.1, max_features='sqrt', monotone_constraints=str(tuple(self.monotonic)), random_state=666,
scale_pos_weight=sum(self.y == 0) / sum(self.y == 1), base_score=self.y.mean(), **best_params)
model.fit(self.X_train, self.y)
self.fitted_model = model
return model
def _show_progress(self, optim_result):
iteration = len(optim_result.func_vals)
value = round(-optim_result.fun, 4)
best_value = round(-min(optim_result.func_vals), 4)
print("Iteration %s of %s: value %s, best score: %s" % (iteration, self.search_iterations, value, best_value),
end='')
print('\r', end='')
def drop_feature(self, feature_name):
self.X.drop(feature_name, axis=1, inplace=True)
self.test.drop(feature_name, axis=1, inplace=True)
def evaluate_test(self):
test_probas = self.fitted_model.predict_proba(self.X_test)
return roc_auc_score(self.y_test, test_probas)
def force_monotonicity(self, feature, direction):
self.monotonic[self.X_train.columns.get_loc(feature)] = int(direction)
def feature_importances(self):
xgboost.plot_importance(self.fitted_model)
def show_pdp(self, feature_name):
if self.fitted_model is None:
self.fit()
partial_dependence = pdp_isolate(self.fitted_model, self.X_train, self.X_train.columns, feature_name)
x_quantile = True
if feature_name in self.categorical: # encoded feature
partial_dependence.display_columns = self.encoder.categories_[self.categorical.columns.get_loc(feature_name)]
x_quantile = False
pdp_plot(partial_dependence, feature_name, center=False, plot_lines=True, x_quantile=x_quantile, frac_to_plot=0.05)
| import pandas as pd
import numpy as np
from pandas.api.types import is_numeric_dtype
from sklearn.metrics import roc_auc_score
from sklearn.preprocessing import OrdinalEncoder, LabelEncoder
from sklearn.model_selection import cross_val_score
from skopt import gp_minimize
from skopt.space import Real, Integer
from skopt.utils import use_named_args
import xgboost
from pdpbox.pdp import pdp_isolate, pdp_plot
import warnings
class AdultIncome:
def __init__(self, path=None):
train_path = path and path + '/adult.data' or 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.data'
test_path = path and path + '/adult.test' or 'https://archive.ics.uci.edu/ml/machine-learning-databases/adult/adult.test'
df = pd.read_csv(train_path,
header=None,
na_values="?")
df_test = pd.read_csv(test_path,
header=None, skiprows=1,
na_values="?")
df.columns = ['age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status', 'occupation',
'relationship', 'race', 'sex', 'capital-gain', 'capital-loss', 'hours-per-week', 'native-country',
'target']
le = LabelEncoder()
self.y = pd.Series(le.fit_transform(df.target))
self.X = df.drop('target', axis=1)
self.X_train = None
self.fitted_model = None
df_test.columns = df.columns
df_test['target'] = df_test.target.str.rstrip('.')
self.test = df_test.drop('target', axis=1)
self.y_test = le.transform(df_test.target)
self.X_test = None
self.search_iterations = 10
self.search_space = [
Integer(20, 81, name='n_estimators'),
Integer(3, 10, name='max_depth'),
Integer(1, 12, name='min_child_weight'),
Real(0, 0.3, "uniform", name='gamma'),
Real(0.5, 0.9, "uniform", name='subsample'),
Real(0.5, 0.9, "uniform", name='colsample_bytree')
]
def _repr_html_(self):
print('------ Features -------')
print(self.X.info())
print()
print('------ Target distribution ----')
print(self.y.hist())
def preprocess(self):
X_train = self.X.copy()
X_test = self.test.copy()
columns_missing_values = self.X.columns[self.X.isnull().any()]
for column in columns_missing_values:
# X_train[column + '_missing'] = X[column].isnull()
if is_numeric_dtype(self.X[column].dtype):
X_train[column] = self.X[column].fillna(self.X[column].mean())
else:
X_train[column] = self.X[column].fillna('missing')
columns_missing_values = self.test.columns[self.test.isnull().any()]
for column in columns_missing_values:
# X_train[column + '_missing'] = X[column].isnull()
if is_numeric_dtype(self.test[column].dtype):
X_test[column] = self.test[column].fillna(self.test[column].mean())
else:
X_test[column] = self.test[column].fillna('missing')
self.categorical = X_train.select_dtypes(include=np.object)
categories = [list(self.X[c].dropna().unique()) for c in self.categorical]
for i, c in enumerate(self.categorical):
categories[i].extend(X_test[c].dropna().unique())
categories[i].append('missing')
categories = [sorted(set(c)) for c in categories]
self.encoder = OrdinalEncoder(categories)
self.encoder.handle_unknown = 'ignore'
encoded = self.encoder.fit_transform(self.categorical)
for i, column in enumerate(self.categorical.columns):
X_train[column] = encoded[:, i]
test_categorical = X_test.select_dtypes(include=np.object)
encoded = self.encoder.transform(test_categorical)
for i, column in enumerate(test_categorical.columns):
X_test[column] = encoded[:, i]
self.X_train = X_train
self.X_test = X_test
return X_train
def fit(self):
if self.X_train is None or len(self.X.columns) < len(self.X_train.columns):
self.preprocess()
if self.fitted_model is None:
self.monotonic = [0] * len(self.X_train.columns)
estimator = xgboost.XGBClassifier(
learning_rate=0.1, max_features='sqrt', monotone_constraints=str(tuple(self.monotonic)), random_state=666,
scale_pos_weight=sum(self.y == 0) / sum(self.y == 1), base_score=self.y.mean())
@use_named_args(self.search_space)
def objective(**params):
estimator.set_params(**params)
scores = cross_val_score(estimator, self.X_train, self.y, cv=5, n_jobs=-1, scoring='roc_auc')
return -np.mean(scores)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
result = gp_minimize(
objective,
self.search_space,
n_points=1000,
n_calls=self.search_iterations,
n_random_starts=10,
acq_optimizer='lbfgs',
n_jobs=-1,
callback=self._show_progress,
random_state=666)
best_params = {f.name: value for (f, value) in zip(self.search_space, result.x)}
model = xgboost.XGBClassifier(
learning_rate=0.1, max_features='sqrt', monotone_constraints=str(tuple(self.monotonic)), random_state=666,
scale_pos_weight=sum(self.y == 0) / sum(self.y == 1), base_score=self.y.mean(), **best_params)
model.fit(self.X_train, self.y)
self.fitted_model = model
return model
def _show_progress(self, optim_result):
iteration = len(optim_result.func_vals)
value = round(-optim_result.fun, 4)
best_value = round(-min(optim_result.func_vals), 4)
print("Iteration %s of %s: value %s, best score: %s" % (iteration, self.search_iterations, value, best_value),
end='')
print('\r', end='')
def drop_feature(self, feature_name):
self.X.drop(feature_name, axis=1, inplace=True)
self.test.drop(feature_name, axis=1, inplace=True)
def evaluate_test(self):
test_probas = self.fitted_model.predict_proba(self.X_test)
return roc_auc_score(self.y_test, test_probas)
def force_monotonicity(self, feature, direction):
self.monotonic[self.X_train.columns.get_loc(feature)] = int(direction)
def feature_importances(self):
xgboost.plot_importance(self.fitted_model)
def show_pdp(self, feature_name):
if self.fitted_model is None:
self.fit()
partial_dependence = pdp_isolate(self.fitted_model, self.X_train, self.X_train.columns, feature_name)
x_quantile = True
if feature_name in self.categorical: # encoded feature
partial_dependence.display_columns = self.encoder.categories_[self.categorical.columns.get_loc(feature_name)]
x_quantile = False
pdp_plot(partial_dependence, feature_name, center=False, plot_lines=True, x_quantile=x_quantile, frac_to_plot=0.05) | en | 0.428627 | # X_train[column + '_missing'] = X[column].isnull() # X_train[column + '_missing'] = X[column].isnull() # encoded feature | 2.514469 | 3 |
tests/unit/entrypoints/test_commandlineproc.py | pacilab/Longbow | 17 | 6614250 | <filename>tests/unit/entrypoints/test_commandlineproc.py<gh_stars>10-100
# BSD 3-Clause License
#
# Copyright (c) 2017, Science and Technology Facilities Council and
# The University of Nottingham
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * 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.
#
# * 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.
"""
This testing module contains the tests for the commandlineproc method within
the entrypoint module.
"""
import pytest
import longbow.exceptions as exceptions
from longbow.entrypoints import _commandlineproc
ALLLONGBOWARGS = [
"-about",
"--about",
"-debug",
"--debug",
"-disconnect",
"--disconnect",
"-examples",
"--examples",
"-h",
"-help",
"--help",
"-hosts",
"--hosts",
"-job",
"--job",
"-jobname",
"--jobname",
"-log",
"--log",
"-maxtime",
"--maxtime",
"-nochecks",
"--nochecks",
"-recover",
"--recover",
"-resource",
"--resource",
"-replicates",
"--replicates",
"-V",
"-verbose",
"--verbose",
"-version",
"--version"
]
def test_cmdlineproc_test1():
"""
Test that if there is nothing on the command-line that nothing happens.
"""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = []
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == ""
assert parameters["executableargs"] == ""
assert longbowargs == []
def test_cmdlineproc_test2():
"""Test a single dashed longbow arg."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["-about"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == ""
assert parameters["executableargs"] == ""
assert longbowargs == ["-about"]
def test_cmdlineproc_test3():
"""Test a double dashed longbow arg."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["--about"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == ""
assert parameters["executableargs"] == ""
assert longbowargs == ["--about"]
def test_cmdlineproc_test4():
"""Test multiple Longbow arguments."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["--hosts", "hosts.file", "--jobname", "test",
"--replicates", "1000", "--disconnect"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == ""
assert parameters["executableargs"] == ""
assert longbowargs == ["--hosts", "hosts.file", "--jobname", "test",
"--replicates", "1000", "--disconnect"]
def test_cmdlineproc_test5():
"""Test executable with Longbow args."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["--hosts", "hosts.file", "--jobname", "test",
"--replicates", "1000", "--disconnect", "pmemd.MPI"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == "pmemd.MPI"
assert parameters["executableargs"] == ""
assert longbowargs == ["--hosts", "hosts.file", "--jobname", "test",
"--replicates", "1000", "--disconnect"]
def test_cmdlineproc_test6():
"""Test executable with Longbow args and executable args."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["--hosts", "hosts.file", "--jobname", "test",
"--maxtime", "01:00", "--replicates", "1000",
"--disconnect", "pmemd.MPI", "-O", "-i", "ex.in", "-c",
"ex.min", "-p", "ex.top", "-o", "ex.out"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == "pmemd.MPI"
assert parameters["executableargs"] == \
"-O -i ex.in -c ex.min -p ex.top -o ex.out"
assert longbowargs == ["--hosts", "hosts.file", "--jobname", "test",
"--maxtime", "01:00", "--replicates", "1000",
"--disconnect"]
def test_cmdlineproc_test7():
"""Test unknown executable with Longbow args."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["--hosts", "hosts.file", "--jobname", "test",
"--replicates", "1000", "--disconnect", "test.exe"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == "test.exe"
assert parameters["executableargs"] == ""
assert longbowargs == ["--hosts", "hosts.file", "--jobname", "test",
"--replicates", "1000", "--disconnect"]
def test_cmdlineproc_test8():
"""
Test unknown executable with Longbow args and exec args.
"""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["--hosts", "hosts.file", "--jobname", "test",
"--replicates", "1000", "--disconnect", "test.exe",
"-i", "input.file", "param1", "--someflag"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == "test.exe"
assert parameters["executableargs"] == "-i input.file param1 --someflag"
assert longbowargs == ["--hosts", "hosts.file", "--jobname", "test",
"--replicates", "1000", "--disconnect"]
def test_cmdlineproc_test9():
"""
Test unknown executable with Longbow args and exec args, this one tests
when longbow args ends with a param of type --flag <value>
"""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["--hosts", "hosts.file", "--jobname", "test",
"--disconnect", "--replicates", "1000", "test.exe",
"-i", "input.file", "param1", "--someflag"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == "test.exe"
assert parameters["executableargs"] == "-i input.file param1 --someflag"
assert longbowargs == ["--hosts", "hosts.file", "--jobname", "test",
"--disconnect", "--replicates", "1000"]
def test_cmdlineproc_test10():
"""Test unknown executable with just the executable."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["test.exe"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == "test.exe"
assert parameters["executableargs"] == ""
assert longbowargs == []
def test_cmdlineproc_test11():
"""Test unknown executable without Longbow args and with exec args."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["test.exe", "-i", "input.file", "param1", "--someflag"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == "test.exe"
assert parameters["executableargs"] == "-i input.file param1 --someflag"
assert longbowargs == []
def test_cmdlineproc_test12():
"""Test for bogus command-line flags."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["--hosts", "hosts.file", "--bogus", "--jobname", "test",
"--replicates", "1000", "--disconnect", "pmemd.MPI",
"-O", "-i", "ex.in", "-c", "ex.min", "-p", "ex.top",
"-o", "ex.out"]
with pytest.raises(exceptions.CommandlineargsError):
_commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
| <filename>tests/unit/entrypoints/test_commandlineproc.py<gh_stars>10-100
# BSD 3-Clause License
#
# Copyright (c) 2017, Science and Technology Facilities Council and
# The University of Nottingham
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * 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.
#
# * 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.
"""
This testing module contains the tests for the commandlineproc method within
the entrypoint module.
"""
import pytest
import longbow.exceptions as exceptions
from longbow.entrypoints import _commandlineproc
ALLLONGBOWARGS = [
"-about",
"--about",
"-debug",
"--debug",
"-disconnect",
"--disconnect",
"-examples",
"--examples",
"-h",
"-help",
"--help",
"-hosts",
"--hosts",
"-job",
"--job",
"-jobname",
"--jobname",
"-log",
"--log",
"-maxtime",
"--maxtime",
"-nochecks",
"--nochecks",
"-recover",
"--recover",
"-resource",
"--resource",
"-replicates",
"--replicates",
"-V",
"-verbose",
"--verbose",
"-version",
"--version"
]
def test_cmdlineproc_test1():
"""
Test that if there is nothing on the command-line that nothing happens.
"""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = []
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == ""
assert parameters["executableargs"] == ""
assert longbowargs == []
def test_cmdlineproc_test2():
"""Test a single dashed longbow arg."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["-about"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == ""
assert parameters["executableargs"] == ""
assert longbowargs == ["-about"]
def test_cmdlineproc_test3():
"""Test a double dashed longbow arg."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["--about"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == ""
assert parameters["executableargs"] == ""
assert longbowargs == ["--about"]
def test_cmdlineproc_test4():
"""Test multiple Longbow arguments."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["--hosts", "hosts.file", "--jobname", "test",
"--replicates", "1000", "--disconnect"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == ""
assert parameters["executableargs"] == ""
assert longbowargs == ["--hosts", "hosts.file", "--jobname", "test",
"--replicates", "1000", "--disconnect"]
def test_cmdlineproc_test5():
"""Test executable with Longbow args."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["--hosts", "hosts.file", "--jobname", "test",
"--replicates", "1000", "--disconnect", "pmemd.MPI"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == "pmemd.MPI"
assert parameters["executableargs"] == ""
assert longbowargs == ["--hosts", "hosts.file", "--jobname", "test",
"--replicates", "1000", "--disconnect"]
def test_cmdlineproc_test6():
"""Test executable with Longbow args and executable args."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["--hosts", "hosts.file", "--jobname", "test",
"--maxtime", "01:00", "--replicates", "1000",
"--disconnect", "pmemd.MPI", "-O", "-i", "ex.in", "-c",
"ex.min", "-p", "ex.top", "-o", "ex.out"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == "pmemd.MPI"
assert parameters["executableargs"] == \
"-O -i ex.in -c ex.min -p ex.top -o ex.out"
assert longbowargs == ["--hosts", "hosts.file", "--jobname", "test",
"--maxtime", "01:00", "--replicates", "1000",
"--disconnect"]
def test_cmdlineproc_test7():
"""Test unknown executable with Longbow args."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["--hosts", "hosts.file", "--jobname", "test",
"--replicates", "1000", "--disconnect", "test.exe"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == "test.exe"
assert parameters["executableargs"] == ""
assert longbowargs == ["--hosts", "hosts.file", "--jobname", "test",
"--replicates", "1000", "--disconnect"]
def test_cmdlineproc_test8():
"""
Test unknown executable with Longbow args and exec args.
"""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["--hosts", "hosts.file", "--jobname", "test",
"--replicates", "1000", "--disconnect", "test.exe",
"-i", "input.file", "param1", "--someflag"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == "test.exe"
assert parameters["executableargs"] == "-i input.file param1 --someflag"
assert longbowargs == ["--hosts", "hosts.file", "--jobname", "test",
"--replicates", "1000", "--disconnect"]
def test_cmdlineproc_test9():
"""
Test unknown executable with Longbow args and exec args, this one tests
when longbow args ends with a param of type --flag <value>
"""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["--hosts", "hosts.file", "--jobname", "test",
"--disconnect", "--replicates", "1000", "test.exe",
"-i", "input.file", "param1", "--someflag"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == "test.exe"
assert parameters["executableargs"] == "-i input.file param1 --someflag"
assert longbowargs == ["--hosts", "hosts.file", "--jobname", "test",
"--disconnect", "--replicates", "1000"]
def test_cmdlineproc_test10():
"""Test unknown executable with just the executable."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["test.exe"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == "test.exe"
assert parameters["executableargs"] == ""
assert longbowargs == []
def test_cmdlineproc_test11():
"""Test unknown executable without Longbow args and with exec args."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["test.exe", "-i", "input.file", "param1", "--someflag"]
longbowargs = _commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
assert parameters["executable"] == "test.exe"
assert parameters["executableargs"] == "-i input.file param1 --someflag"
assert longbowargs == []
def test_cmdlineproc_test12():
"""Test for bogus command-line flags."""
parameters = {
"debug": False,
"disconnect": False,
"executable": "",
"executableargs": "",
"hosts": "",
"job": "",
"jobname": "",
"log": "",
"recover": "",
"resource": "",
"replicates": "",
"verbose": False
}
commandlineargs = ["--hosts", "hosts.file", "--bogus", "--jobname", "test",
"--replicates", "1000", "--disconnect", "pmemd.MPI",
"-O", "-i", "ex.in", "-c", "ex.min", "-p", "ex.top",
"-o", "ex.out"]
with pytest.raises(exceptions.CommandlineargsError):
_commandlineproc(ALLLONGBOWARGS, commandlineargs, parameters)
| en | 0.733305 | # BSD 3-Clause License # # Copyright (c) 2017, Science and Technology Facilities Council and # The University of Nottingham # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * 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. # # * 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. This testing module contains the tests for the commandlineproc method within the entrypoint module. Test that if there is nothing on the command-line that nothing happens. Test a single dashed longbow arg. Test a double dashed longbow arg. Test multiple Longbow arguments. Test executable with Longbow args. Test executable with Longbow args and executable args. Test unknown executable with Longbow args. Test unknown executable with Longbow args and exec args. Test unknown executable with Longbow args and exec args, this one tests when longbow args ends with a param of type --flag <value> Test unknown executable with just the executable. Test unknown executable without Longbow args and with exec args. Test for bogus command-line flags. | 1.528736 | 2 |