row_id
int64 0
48.4k
| init_message
stringlengths 1
342k
| conversation_hash
stringlengths 32
32
| scores
dict |
|---|---|---|---|
38,147
|
for loop for list and sum the value in attrbuite price
|
2c82575efbe472e05b8bf0ea270ee531
|
{
"intermediate": 0.21485018730163574,
"beginner": 0.6030083298683167,
"expert": 0.1821414977312088
}
|
38,148
|
What is variable initialization, declaration and invocation? Are these three terms different from each other and if yes, how ?
Please explain with an example
|
cd324a5a781eb990f3d8521494c91617
|
{
"intermediate": 0.32458406686782837,
"beginner": 0.45783647894859314,
"expert": 0.21757939457893372
}
|
38,149
|
genre_grouping = zd.groupby('user_id')['genre_name']
len(genre_grouping)
def prov(group):
for name, values in group:
if len(values) > 50:
return name
prov(genre_grouping)
как работает здесть метдо len
|
21c00f986134db2473bf2f2ce1c3f437
|
{
"intermediate": 0.3409084677696228,
"beginner": 0.34610715508461,
"expert": 0.3129843473434448
}
|
38,150
|
Hi i have a export to bigquery export from the partner sales console from google which help me to administrate the partners and subbilling accounts. the dataset name is td-fr-prod-gcp-bqexportbilling and the table is td_fr_prod_gcp_all_billing_data
the schema of the table is
The following schema describes the data in the BigQuery table.
In your BigQuery dataset, the detailed rebilling export is loaded into a data table named reseller_billing_detailed_export_v1.
Field Type Description
billing_account_id String The account ID that the usage is associated with, which may be the customer's or yours. Depending on the product family, this may be a billing account or a Cloud Identity ID.
payer_billing_account_id String The ID of your parent billing account.
invoice.month String The year and month (YYYYMM) of the invoice that includes the cost line items. For example: "202101" is the same as January 2021.
cost_type String The type of cost this line item represents: regular, tax, adjustment, or rounding error.
service.id String The ID of the service that the usage is associated with.
service.description String The Google service that reported the billing data.
sku.id String The SKU ID of the resource used by the service.
sku.description String A description of the resource type used by the service. For example, Cloud Storage is of type Standard Storage US.
usage_start_time Timestamp The start time of the calculated cost's hourly usage window. The usage and costs for all services are displayed with hourly granularity. Long running service usage is spread across multiple hourly windows. For subscription products, this is the beginning of the billing month.
usage_end_time Timestamp The end time of the calculated cost's hourly usage window. The usage and costs for all services are displayed with hourly granularity. Long running service usage is spread across multiple hourly windows. For subscription products, this is the end of the billing month.
project Struct Information about the Google Cloud project that generated the Cloud Billing data.
project.number String An internally-generated, anonymized, and unique identifier for the Google Cloud project that generated the Cloud Billing data.
project.id String The ID of the Google Cloud project that generated the Cloud Billing data.
project.name String The name of the Google Cloud project that generated the Cloud Billing data.
project.labels Struct, Repeated
project.labels.key String If labels are present, the key portion of the key:value pair.
project.labels.value String If labels are present, the value portion of the key:value pair.
project.ancestry_numbers String The resource hierarchy ancestors for the project identified by the project.id.
labels Struct, Repeated
labels.key String If labels are present, the key portion of the key:value pair.
labels.value String If labels are present, the value portion of the key:value pair.
system_labels Struct, Repeated
system_labels.key String If system labels are present, the key portion of the key:value pair.
system_labels.value String If system labels are present, the value portion of the key:value pair.
location.location String Location of usage at the level of a country, region, or zone. Shows global for resources with no specific location. For more information, see Regions and Zones.
location.country String When location.location is a country, region, or zone, this field is the country of usage. For example, US. For more information, see Regions and Zones.
location.region String When location.location is a country or region, this field is the region of usage. For example, us-central1. For more information, see Regions and Zones.
location.zone String When location.location is a zone, this field is the zone of usage. For example, us-central1-a. For more information, see Regions and Zones.
resource Struct Describes the structure and value of information relevant to service resources (for example, virtual machines or an SSD) that generate service usage.
resource.name String A service-specific identifier for the resource that generated relevant usage. Can be user-generated.
resource.global_name String A globally unique service identifier for the resource that generated relevant usage.
cost Numeric The cost of usage before any applied credits. To get the total cost including credits, add credits.amount to cost.
currency String The cost's billing currency. For more information, see Local Currency for Billing and Payments.
currency_conversion_rate Float The exchange rate from US dollars to the local currency. That is, cost ÷ currency_conversion_rate equals the cost in US dollars.
usage.amount Numeric The quantity of usage.unit used.
usage.unit String The base unit for measuring resource usage. For example, the base unit for standard storage is byte-seconds.
usage.amount_in_pricing_unit Numeric The quantity of usage.pricing_unit usage.
usage.pricing_unit String The units for measuring resource usage.
credits Struct, Repeated Contains fields that describe the structure and value of credits.
credits.id String If populated, indicates that a credit is associated with the product SKU.
credits.full_name String The name of the credit associated with the product SKU.
credits.type String This field describes the purpose or origin of the credits.id.
credits.name String A description of the credit applied to the usage.
credits.amount Numeric The amount of the credit applied to the usage.
credits.channel_partner_amount Numeric The amount of the credit applied to the usage, after rebilling markups and discounts. Based on the channel_partner_name and the associated ChannelPartnerRepricingConfig. If credits.type is RESELLER_MARGIN, this amount will be zero.
credits.customer_amount Numeric The amount of the credit applied to the usage, after rebilling markups and discounts. Based on the customer_name and the associated CustomerRepricingConfig. If credits.type is RESELLER_MARGIN, this amount will be zero.
adjustmentsInfo Struct, Repeated Contains fields that describe the structure and value of an adjustment to cost line items.
adjustmentsInfo.adjustment_id String If populated, an adjustment is associated with a cost line item. adjustmentsInfo.adjustments_id is the unique ID for all the adjustments caused by an issue.
adjustmentsInfo.adjustment_description String A description of the adjustment and its cause.
adjustmentsInfo.adjustment_type String The type of the adjustment.
adjustmentsInfo.adjustment_mode String How the adjustment was issued.
export_time Timestamp A processing time associated with an append of billing data. This will always increase with each new export. Use the export_time column to understand when the exported billing data was last updated.
entitlement_name String The resource name of the Cloud Channel API Entitlement. Uses the format: accounts/{account}/customers/{customer}/entitlements/{entitlement}
channel_partner_name String (Distributors only) The resource name of the channel partner that is selling to the end customer. Uses the format: accounts/{account}/channelPartnerLinks/{channelPartner}.
channel_partner_cost Numeric (Distributors only) The cost to the channel partner, identified by channel_partner_name, after applying an existing ChannelPartnerRepricingConfig.
customer_name String The resource name of the reseller's customer who consumed this usage in the format accounts/{account}/customers/{customer}
customer_cost Numeric The cost to the reseller's customer identified by the customer_name column, after applying the CustomerRepricingConfig, if one exists.
cost_at_list Numeric The cost if charged with public pricing.
customer_repricing_config_name String The resource name of the Cloud Channel API CustomerRepricingConfig. Uses the format: accounts/{account}/customers/{customer}/customerRepricingConfigs/{id}.
Note: For Google Cloud, the first full month of data with this field is January 2023.
channel_partner_repricing_config_name String (Distributors only) The resource name of the Cloud Channel API ChannelPartnerRepricingConfig. Uses the format: accounts/{account}/channelPartnerLinks/{channelPartner}/channelPartnerRepricingConfigs/{id}.
Note: For Google Cloud, the first full month of data with this field is January 2023.
tags Struct Fields that describe the tag, such as key, value, and namespace.
Note: For Google Cloud, the first full month of data with these tags is January 2023.
tags.key String The short name or display name of the key associated with this particular tag.
tags.value String The resources attached to a tag key. At any given time, exactly one value can be attached to a resource for a given key.
tags.inherited Boolean Indicates whether a tag binding is inherited (Tags Inherited = True) or direct/non-inherited (Tags Inherited = False).
tags.namespace String Represents the resource hierarchy that define tag key and values. Namespace can be combined with tag key and tag value short names to create a globally unique, fully qualified name for the tag key or tag value.
customer_correlation_id String The external CRM ID for the customer. Populated only if a CRM ID exists for this customer.
Note: For Google Cloud, the first full month of data with this field is March 2023.
price Struct Fields that describe the structure and value related to the prices charged for usage.
Note: For Google Cloud, the first full month of data with price fields is May 2023.
price.effective_price Numeric The price charged for the usage.
price.tier_start_amount Numeric The lower bound number of units for a SKU's pricing tier. For example, a SKU with three pricing tiers such as 0-100 units, 101-1000 units, and 1001+ units, will display three pricing rows for the SKU, with 0, 101, and 1001 in the price.tier_start_amount field representing the starting unit quantity for the SKU's pricing tiers. Learn more about Google Cloud pricing tiers.
price.unit String The unit of usage in which the pricing is specified and resource usage is measured (such as gibibyte, tebibyte, month, year, gibibyte hour, gibibyte month, or count). The value in the price.unit field matches the value in the usage.pricing_unit field.
price.pricing_unit_quantity Numeric The SKU's pricing tier unit quantity. For example, if the tier price is $1 per 1000000 Bytes, then this column will show 1000000.
transaction_type String The transaction type of the seller. The transaction type might be one of the following:
GOOGLE = 1: Services sold by Google Cloud.
THIRD_PARTY_RESELLER = 2: Third party services resold by Google Cloud.
THIRD_PARTY_AGENCY = 3: Third party services sold by a partner, with Google Cloud acting as the agent.
Note: For Google Cloud, the first full month of data with this field is August 2023.
seller_name String The legal name of the seller.
Note: For Google Cloud, the first full month of data with this field is August 2023.
as you can see in the there is a column name channel_partner_name
with this format accounts/C045sqjbr/channelPartnerLinks/C01dmi1l0
i need to create a new table with a column name channel_partner _id and the value C01dmi1l0 in the case of the example
i have also build a function in python which for a given code C01dmi1l0 give me the domain associated with the channel_partner_id
import re
from google.cloud import bigquery
from googleapiclient.discovery import build
# Function to extract partner ID from channel_partner_name
def extract_partner_id(channel_partner_name):
match = re.search(r'/C(\w+)$', channel_partner_name)
return match.group(1) if match else None
# Function to fetch primary domain using the API
def get_primary_domain(partner_id):
# Replace 'YOUR_API_KEY' with your actual API key
api_key = 'AIzaSyB3Sqd5R4_8fHY8dGZLZYvL8ylM_tlNCvU'
service = build('cloudchannel', 'v1', developerKey=api_key)
# Assuming you have the required credentials for authorization
# ...
# Make the API request
partner_link_name = f'accounts/*/channelPartnerLinks/C{partner_id}'
request = service.accounts().channelPartnerLinks().get(name=partner_link_name)
response = request.execute()
# Extract and return the primary domain
return response.get('channelPartnerCloudIdentityInfo', {}).get('primaryDomain', None)
# Assuming df is your dataframe with the BigQuery results
df['partner_id'] = df['channel_partner_name'].apply(extract_partner_id)
# Group data by partner ID
grouped_data = df.groupby('partner_id')['sub_billing_account'].agg(list).reset_index()
# Fetch primary domain for each partner
grouped_data['primary_domain'] = grouped_data['partner_id'].apply(get_primary_domain)
# Assuming you have a BigQuery client
client = bigquery.Client()
# Create a new dataset if needed
dataset_id = 'your_dataset_id'
dataset_ref = client.dataset(dataset_id)
dataset = bigquery.Dataset(dataset_ref)
client.create_dataset(dataset)
# Create a BigQuery table with the grouped data
table_id = 'your_table_id'
table_ref = dataset.table(table_id)
job_config = bigquery.LoadJobConfig(
schema=[
bigquery.SchemaField("partner_id", "STRING", mode="REQUIRED"),
bigquery.SchemaField("sub_billing_accounts", "ARRAY<STRING>", mode="REQUIRED"),
bigquery.SchemaField("primary_domain", "STRING", mode="REQUIRED"),
]
)
client.load_table_from_dataframe(grouped_data, table_ref, job_config=job_config).result()
can you help me to do this efficiently so later all the data makes sense for a dashboard where you can see the domain and the billing account of that domain along with the costs ?
|
7cd2be08e15e7011cc42c3905e6a71ac
|
{
"intermediate": 0.4673484265804291,
"beginner": 0.2451966106891632,
"expert": 0.2874549627304077
}
|
38,151
|
User
i have a bigquery dataset that is sync with the partner sales consonle from google the schema is Table schema Warning: Attempting to modify the export schema yourself can result in data no longer getting exported. If you want to add or remove columns, you can create a view or a materialized view, or you can join against your other tables in your queries.
If your table gets in this state, you will need to revert it back to having all the correct columns and nothing else. Afterwards, you may need to go to the Billing export page and click Update.
The following schema describes the data in the BigQuery table.
In your BigQuery dataset, the detailed rebilling export is loaded into a data table named reseller_billing_detailed_export_v1.
Field Type Description billing_account_id String The account ID that the usage is associated with, which may be the customer's or yours. Depending on the product family, this may be a billing account or a Cloud Identity ID. payer_billing_account_id String The ID of your parent billing account. invoice.month String The year and month (YYYYMM) of the invoice that includes the cost line items. For example: "202101" is the same as January 2021. cost_type String The type of cost this line item represents: regular, tax, adjustment, or rounding error. service.id String The ID of the service that the usage is associated with. service.description String The Google service that reported the billing data. sku.id String The SKU ID of the resource used by the service. sku.description String A description of the resource type used by the service. For example, Cloud Storage is of type Standard Storage US. usage_start_time Timestamp The start time of the calculated cost's hourly usage window. The usage and costs for all services are displayed with hourly granularity. Long running service usage is spread across multiple hourly windows. For subscription products, this is the beginning of the billing month. usage_end_time Timestamp The end time of the calculated cost's hourly usage window. The usage and costs for all services are displayed with hourly granularity. Long running service usage is spread across multiple hourly windows. For subscription products, this is the end of the billing month. project Struct Information about the Google Cloud project that generated the Cloud Billing data. project.number String An internally-generated, anonymized, and unique identifier for the Google Cloud project that generated the Cloud Billing data. project.id String The ID of the Google Cloud project that generated the Cloud Billing data. project.name String The name of the Google Cloud project that generated the Cloud Billing data. project.labels Struct, Repeated project.labels.key String If labels are present, the key portion of the key:value pair. project.labels.value String If labels are present, the value portion of the key:value pair. project.ancestry_numbers String The resource hierarchy ancestors for the project identified by the project.id. labels Struct, Repeated labels.key String If labels are present, the key portion of the key:value pair. labels.value String If labels are present, the value portion of the key:value pair. system_labels Struct, Repeated system_labels.key String If system labels are present, the key portion of the key:value pair. system_labels.value String If system labels are present, the value portion of the key:value pair. location.location String Location of usage at the level of a country, region, or zone. Shows global for resources with no specific location. For more information, see Regions and Zones. location.country String When location.location is a country, region, or zone, this field is the country of usage. For example, US. For more information, see Regions and Zones. location.region String When location.location is a country or region, this field is the region of usage. For example, us-central1. For more information, see Regions and Zones. location.zone String When location.location is a zone, this field is the zone of usage. For example, us-central1-a. For more information, see Regions and Zones. resource Struct Describes the structure and value of information relevant to service resources (for example, virtual machines or an SSD) that generate service usage. resource.name String A service-specific identifier for the resource that generated relevant usage. Can be user-generated. resource.global_name String A globally unique service identifier for the resource that generated relevant usage. cost Numeric The cost of usage before any applied credits. To get the total cost including credits, add credits.amount to cost. currency String The cost's billing currency. For more information, see Local Currency for Billing and Payments. currency_conversion_rate Float The exchange rate from US dollars to the local currency. That is, cost ÷ currency_conversion_rate equals the cost in US dollars. usage.amount Numeric The quantity of usage.unit used. usage.unit String The base unit for measuring resource usage. For example, the base unit for standard storage is byte-seconds. usage.amount_in_pricing_unit Numeric The quantity of usage.pricing_unit usage. usage.pricing_unit String The units for measuring resource usage. credits Struct, Repeated Contains fields that describe the structure and value of credits. credits.id String If populated, indicates that a credit is associated with the product SKU. credits.full_name String The name of the credit associated with the product SKU. credits.type String This field describes the purpose or origin of the credits.id. credits.name String A description of the credit applied to the usage. credits.amount Numeric The amount of the credit applied to the usage. credits.channel_partner_amount Numeric The amount of the credit applied to the usage, after rebilling markups and discounts. Based on the channel_partner_name and the associated ChannelPartnerRepricingConfig. If credits.type is RESELLER_MARGIN, this amount will be zero. credits.customer_amount Numeric The amount of the credit applied to the usage, after rebilling markups and discounts. Based on the customer_name and the associated CustomerRepricingConfig. If credits.type is RESELLER_MARGIN, this amount will be zero. adjustmentsInfo Struct, Repeated Contains fields that describe the structure and value of an adjustment to cost line items. adjustmentsInfo.adjustment_id String If populated, an adjustment is associated with a cost line item. adjustmentsInfo.adjustments_id is the unique ID for all the adjustments caused by an issue. adjustmentsInfo.adjustment_description String A description of the adjustment and its cause. adjustmentsInfo.adjustment_type String The type of the adjustment. adjustmentsInfo.adjustment_mode String How the adjustment was issued. export_time Timestamp A processing time associated with an append of billing data. This will always increase with each new export. Use the export_time column to understand when the exported billing data was last updated. entitlement_name String The resource name of the Cloud Channel API Entitlement. Uses the format: accounts/{account}/customers/{customer}/entitlements/{entitlement} channel_partner_name String (Distributors only) The resource name of the channel partner that is selling to the end customer. Uses the format: accounts/{account}/channelPartnerLinks/{channelPartner}. channel_partner_cost Numeric (Distributors only) The cost to the channel partner, identified by channel_partner_name, after applying an existing ChannelPartnerRepricingConfig. customer_name String The resource name of the reseller's customer who consumed this usage in the format accounts/{account}/customers/{customer} customer_cost Numeric The cost to the reseller's customer identified by the customer_name column, after applying the CustomerRepricingConfig, if one exists. cost_at_list Numeric The cost if charged with public pricing. customer_repricing_config_name String The resource name of the Cloud Channel API CustomerRepricingConfig. Uses the format: accounts/{account}/customers/{customer}/customerRepricingConfigs/{id}. Note: For Google Cloud, the first full month of data with this field is January 2023. channel_partner_repricing_config_name String (Distributors only) The resource name of the Cloud Channel API ChannelPartnerRepricingConfig. Uses the format: accounts/{account}/channelPartnerLinks/{channelPartner}/channelPartnerRepricingConfigs/{id}. Note: For Google Cloud, the first full month of data with this field is January 2023. tags Struct Fields that describe the tag, such as key, value, and namespace. Note: For Google Cloud, the first full month of data with these tags is January 2023. tags.key String The short name or display name of the key associated with this particular tag. tags.value String The resources attached to a tag key. At any given time, exactly one value can be attached to a resource for a given key. tags.inherited Boolean Indicates whether a tag binding is inherited (Tags Inherited = True) or direct/non-inherited (Tags Inherited = False). tags.namespace String Represents the resource hierarchy that define tag key and values. Namespace can be combined with tag key and tag value short names to create a globally unique, fully qualified name for the tag key or tag value. customer_correlation_id String The external CRM ID for the customer. Populated only if a CRM ID exists for this customer. Note: For Google Cloud, the first full month of data with this field is March 2023. price Struct Fields that describe the structure and value related to the prices charged for usage. Note: For Google Cloud, the first full month of data with price fields is May 2023. price.effective_price Numeric The price charged for the usage. price.tier_start_amount Numeric The lower bound number of units for a SKU's pricing tier. For example, a SKU with three pricing tiers such as 0-100 units, 101-1000 units, and 1001+ units, will display three pricing rows for the SKU, with 0, 101, and 1001 in the price.tier_start_amount field representing the starting unit quantity for the SKU's pricing tiers. Learn more about Google Cloud pricing tiers. price.unit String The unit of usage in which the pricing is specified and resource usage is measured (such as gibibyte, tebibyte, month, year, gibibyte hour, gibibyte month, or count). The value in the price.unit field matches the value in the usage.pricing_unit field. price.pricing_unit_quantity Numeric The SKU's pricing tier unit quantity. For example, if the tier price is $1 per 1000000 Bytes, then this column will show 1000000. transaction_type String The transaction type of the seller. The transaction type might be one of the following: GOOGLE = 1: Services sold by Google Cloud. THIRD_PARTY_RESELLER = 2: Third party services resold by Google Cloud. THIRD_PARTY_AGENCY = 3: Third party services sold by a partner, with Google Cloud acting as the agent. Note: For Google Cloud, the first full month of data with this field is August 2023. seller_name String The legal name of the seller. Note: For Google Cloud, the first full month of data with this field is August 2023.
as you can see there is a channel_partner_name column with this format accounts/C045sqjbr/channelPartnerLinks/C01dmi1l0
i need to create a new column with the value C01dmi1l0 which is after channelPartnerLinks this represent the Channel_partner_id this new info should be in a new table
ChatGPT
To create a new column with the Channel_partner_id in a new table, you can use the SUBSTR and STRPOS functions to extract the desired substring from the channel_partner_name column. Here's an example query that demonstrates how to achieve this:
sql
Copy code
-- Create a new table with the extracted Channel_partner_id
CREATE TABLE your_dataset.new_table AS
SELECT
*,
SUBSTR(channel_partner_name, STRPOS(channel_partner_name, 'channelPartnerLinks/') + LENGTH('channelPartnerLinks/')) AS Channel_partner_id
use some regular expression
User
i have a bigquery dataset that is sync with the partner sales consonle from google the schema is Table schema Warning: Attempting to modify the export schema yourself can result in data no longer getting exported. If you want to add or remove columns, you can create a view or a materialized view, or you can join against your other tables in your queries.
If your table gets in this state, you will need to revert it back to having all the correct columns and nothing else. Afterwards, you may need to go to the Billing export page and click Update.
The following schema describes the data in the BigQuery table.
In your BigQuery dataset, the detailed rebilling export is loaded into a data table named reseller_billing_detailed_export_v1.
Field Type Description billing_account_id String The account ID that the usage is associated with, which may be the customer's or yours. Depending on the product family, this may be a billing account or a Cloud Identity ID. payer_billing_account_id String The ID of your parent billing account. invoice.month String The year and month (YYYYMM) of the invoice that includes the cost line items. For example: "202101" is the same as January 2021. cost_type String The type of cost this line item represents: regular, tax, adjustment, or rounding error. service.id String The ID of the service that the usage is associated with. service.description String The Google service that reported the billing data. sku.id String The SKU ID of the resource used by the service. sku.description String A description of the resource type used by the service. For example, Cloud Storage is of type Standard Storage US. usage_start_time Timestamp The start time of the calculated cost's hourly usage window. The usage and costs for all services are displayed with hourly granularity. Long running service usage is spread across multiple hourly windows. For subscription products, this is the beginning of the billing month. usage_end_time Timestamp The end time of the calculated cost's hourly usage window. The usage and costs for all services are displayed with hourly granularity. Long running service usage is spread across multiple hourly windows. For subscription products, this is the end of the billing month. project Struct Information about the Google Cloud project that generated the Cloud Billing data. project.number String An internally-generated, anonymized, and unique identifier for the Google Cloud project that generated the Cloud Billing data. project.id String The ID of the Google Cloud project that generated the Cloud Billing data. project.name String The name of the Google Cloud project that generated the Cloud Billing data. project.labels Struct, Repeated project.labels.key String If labels are present, the key portion of the key:value pair. project.labels.value String If labels are present, the value portion of the key:value pair. project.ancestry_numbers String The resource hierarchy ancestors for the project identified by the project.id. labels Struct, Repeated labels.key String If labels are present, the key portion of the key:value pair. labels.value String If labels are present, the value portion of the key:value pair. system_labels Struct, Repeated system_labels.key String If system labels are present, the key portion of the key:value pair. system_labels.value String If system labels are present, the value portion of the key:value pair. location.location String Location of usage at the level of a country, region, or zone. Shows global for resources with no specific location. For more information, see Regions and Zones. location.country String When location.location is a country, region, or zone, this field is the country of usage. For example, US. For more information, see Regions and Zones. location.region String When location.location is a country or region, this field is the region of usage. For example, us-central1. For more information, see Regions and Zones. location.zone String When location.location is a zone, this field is the zone of usage. For example, us-central1-a. For more information, see Regions and Zones. resource Struct Describes the structure and value of information relevant to service resources (for example, virtual machines or an SSD) that generate service usage. resource.name String A service-specific identifier for the resource that generated relevant usage. Can be user-generated. resource.global_name String A globally unique service identifier for the resource that generated relevant usage. cost Numeric The cost of usage before any applied credits. To get the total cost including credits, add credits.amount to cost. currency String The cost's billing currency. For more information, see Local Currency for Billing and Payments. currency_conversion_rate Float The exchange rate from US dollars to the local currency. That is, cost ÷ currency_conversion_rate equals the cost in US dollars. usage.amount Numeric The quantity of usage.unit used. usage.unit String The base unit for measuring resource usage. For example, the base unit for standard storage is byte-seconds. usage.amount_in_pricing_unit Numeric The quantity of usage.pricing_unit usage. usage.pricing_unit String The units for measuring resource usage. credits Struct, Repeated Contains fields that describe the structure and value of credits. credits.id String If populated, indicates that a credit is associated with the product SKU. credits.full_name String The name of the credit associated with the product SKU. credits.type String This field describes the purpose or origin of the credits.id. credits.name String A description of the credit applied to the usage. credits.amount Numeric The amount of the credit applied to the usage. credits.channel_partner_amount Numeric The amount of the credit applied to the usage, after rebilling markups and discounts. Based on the channel_partner_name and the associated ChannelPartnerRepricingConfig. If credits.type is RESELLER_MARGIN, this amount will be zero. credits.customer_amount Numeric The amount of the credit applied to the usage, after rebilling markups and discounts. Based on the customer_name and the associated CustomerRepricingConfig. If credits.type is RESELLER_MARGIN, this amount will be zero. adjustmentsInfo Struct, Repeated Contains fields that describe the structure and value of an adjustment to cost line items. adjustmentsInfo.adjustment_id String If populated, an adjustment is associated with a cost line item. adjustmentsInfo.adjustments_id is the unique ID for all the adjustments caused by an issue. adjustmentsInfo.adjustment_description String A description of the adjustment and its cause. adjustmentsInfo.adjustment_type String The type of the adjustment. adjustmentsInfo.adjustment_mode String How the adjustment was issued. export_time Timestamp A processing time associated with an append of billing data. This will always increase with each new export. Use the export_time column to understand when the exported billing data was last updated. entitlement_name String The resource name of the Cloud Channel API Entitlement. Uses the format: accounts/{account}/customers/{customer}/entitlements/{entitlement} channel_partner_name String (Distributors only) The resource name of the channel partner that is selling to the end customer. Uses the format: accounts/{account}/channelPartnerLinks/{channelPartner}. channel_partner_cost Numeric (Distributors only) The cost to the channel partner, identified by channel_partner_name, after applying an existing ChannelPartnerRepricingConfig. customer_name String The resource name of the reseller's customer who consumed this usage in the format accounts/{account}/customers/{customer} customer_cost Numeric The cost to the reseller's customer identified by the customer_name column, after applying the CustomerRepricingConfig, if one exists. cost_at_list Numeric The cost if charged with public pricing. customer_repricing_config_name String The resource name of the Cloud Channel API CustomerRepricingConfig. Uses the format: accounts/{account}/customers/{customer}/customerRepricingConfigs/{id}. Note: For Google Cloud, the first full month of data with this field is January 2023. channel_partner_repricing_config_name String (Distributors only) The resource name of the Cloud Channel API ChannelPartnerRepricingConfig. Uses the format: accounts/{account}/channelPartnerLinks/{channelPartner}/channelPartnerRepricingConfigs/{id}. Note: For Google Cloud, the first full month of data with this field is January 2023. tags Struct Fields that describe the tag, such as key, value, and namespace. Note: For Google Cloud, the first full month of data with these tags is January 2023. tags.key String The short name or display name of the key associated with this particular tag. tags.value String The resources attached to a tag key. At any given time, exactly one value can be attached to a resource for a given key. tags.inherited Boolean Indicates whether a tag binding is inherited (Tags Inherited = True) or direct/non-inherited (Tags Inherited = False). tags.namespace String Represents the resource hierarchy that define tag key and values. Namespace can be combined with tag key and tag value short names to create a globally unique, fully qualified name for the tag key or tag value. customer_correlation_id String The external CRM ID for the customer. Populated only if a CRM ID exists for this customer. Note: For Google Cloud, the first full month of data with this field is March 2023. price Struct Fields that describe the structure and value related to the prices charged for usage. Note: For Google Cloud, the first full month of data with price fields is May 2023. price.effective_price Numeric The price charged for the usage. price.tier_start_amount Numeric The lower bound number of units for a SKU's pricing tier. For example, a SKU with three pricing tiers such as 0-100 units, 101-1000 units, and 1001+ units, will display three pricing rows for the SKU, with 0, 101, and 1001 in the price.tier_start_amount field representing the starting unit quantity for the SKU's pricing tiers. Learn more about Google Cloud pricing tiers. price.unit String The unit of usage in which the pricing is specified and resource usage is measured (such as gibibyte, tebibyte, month, year, gibibyte hour, gibibyte month, or count). The value in the price.unit field matches the value in the usage.pricing_unit field. price.pricing_unit_quantity Numeric The SKU's pricing tier unit quantity. For example, if the tier price is $1 per 1000000 Bytes, then this column will show 1000000. transaction_type String The transaction type of the seller. The transaction type might be one of the following: GOOGLE = 1: Services sold by Google Cloud. THIRD_PARTY_RESELLER = 2: Third party services resold by Google Cloud. THIRD_PARTY_AGENCY = 3: Third party services sold by a partner, with Google Cloud acting as the agent. Note: For Google Cloud, the first full month of data with this field is August 2023. seller_name String The legal name of the seller. Note: For Google Cloud, the first full month of data with this field is August 2023.
as you can see there is a channel_partner_name column with this format accounts/C045sqjbr/channelPartnerLinks/C01dmi1l0
i need to create a new column with the value C01dmi1l0 which is after channelPartnerLinks this represent the Channel_partner_id this new info should be in a new table
ChatGPT
To create a new column with the Channel_partner_id in a new table, you can use the SUBSTR and STRPOS functions to extract the desired substring from the channel_partner_name column. Here's an example query that demonstrates how to achieve this:
sql
Copy code
-- Create a new table with the extracted Channel_partner_id
CREATE TABLE your_dataset.new_table AS
SELECT
*,
SUBSTR(channel_partner_name, STRPOS(channel_partner_name, 'channelPartnerLinks/') + LENGTH('channelPartnerLinks/')) AS Channel_partner_id
FROM
your_dataset.reseller_billing_detailed_export_v1;
This query creates a new table named new_table in your dataset. It selects all columns from the existing table (reseller_billing_detailed_export_v1) and adds a new column Channel_partner_id with the extracted value from the channel_partner_name column.
Make sure to replace your_dataset with the actual name of your BigQuery dataset.
Note: The STRPOS function is used to find the position of the substring 'channelPartnerLinks/' in the channel_partner_name column, and SUBSTR is used to extract the substring starting from that position. This assumes that the Channel_partner_id always comes after 'channelPartnerLinks/'. If the format varies, you may need to adjust the query accordingly.
FROM
your_dataset.reseller_billing_detailed_export_v1;
This query creates a new table named new_table in your dataset. It selects all columns from the existing table (reseller_billing_detailed_export_v1) and adds a new column Channel_partner_id with the extracted value from the channel_partner_name column.
Make sure to replace your_dataset with the actual name of your BigQuery dataset.
Note: The STRPOS function is used to find the position of the substring 'channelPartnerLinks/' in the channel_partner_name column, and SUBSTR is used to extract the substring starting from that position. This assumes that the Channel_partner_id always comes after 'channelPartnerLinks/'. If the format varies, you may need to adjust the query accordingly.
|
bec672aeb626b78c2eebb501dc6281a7
|
{
"intermediate": 0.45560699701309204,
"beginner": 0.28292331099510193,
"expert": 0.2614697217941284
}
|
38,152
|
“Speech in the Virginia Convention” (1775) by Patrick Henry
Directions: After carefully reading Henry’s speech, identify the appeals and logical fallacies in the text. Next, answer the general questions about his speech using complete sentences.
A. Appeals--Identify an example of ethos, pathos and logos from Henry’s speech. Next, select four general appeals he uses and write them in on the blanks provided for questions 4-7 taking care to explain how the example embodies that appeal.
Example of Ethos:
How example embodies appeal:
Example of Pathos:
How example embodies appeal:
Example of Logos:
How example embodies appeal:
Appeal:
How example embodies appeal:
Appeal:
How example embodies appeal:
Appeal:
How example embodies appeal:
Appeal:
How example embodies appeal:
|
6bbf5b9bee40324956254736972d2799
|
{
"intermediate": 0.30722641944885254,
"beginner": 0.4298532009124756,
"expert": 0.26292040944099426
}
|
38,153
|
using CustomInspector;
using System;
using UnityEngine;
using Mirror;
using UnityEngine.InputSystem;
namespace PlayerBehaviour
{
public class PlayerCameraController : CameraController
{
/// <summary>
/// (Vertical, Horizontal)
/// </summary>
public readonly static Vector2 defaultLookDirection = new(25, 0);
[SerializeField, ReadOnly, Tooltip("(Vertical, Horizontal)")]
Vector2 lookDir = Vector2.zero;
float MaxLookHeight => carData.PrefabSettings.maxLookHeight;
float MinLookHeight => carData.PrefabSettings.minLookHeight;
private float Internal_sensitivity => carData.PrefabSettings.internal_sensitivity;
bool rotationBlocked = false;
float currentIdle = 0;
const float maxIdleTime = 6; //max idle time until looks forward
const float idleMoveSpeed = 30; //when idle how fast turned to front
private PlayerInputActions playerControls;
protected override void Awake()
{
base.Awake();
lookDir = defaultLookDirection;
playerControls = new PlayerInputActions();
// Subscribe to the actions in Awake, if the GameObject is not going to be disabled/enabled often
playerControls.Player.Aiming.performed += OnAimPerformed;
playerControls.Player.Aiming.canceled += OnAimCanceled;
}
public bool isAiming = false;
private void OnAimPerformed(InputAction.CallbackContext context)
{
isAiming = true;
if (!SettingsHandler.IsAimingMethodHold())
{
Aiming ^= true;
}
}
private void OnAimCanceled(InputAction.CallbackContext context)
{
isAiming = false;
}
protected override void Start()
{
base.Start();
if (!isLocalPlayer) return;
rotationBlocked = true;
Helpers.WaitSeconds(this, 0.5f, () => rotationBlocked = false);
}
protected override void Update()
{
//Base
base.Update();
if (!isLocalPlayer)
return;
//Turning
if (InGameMouse.IsLocked // not rotate when in some kind of menu where cursor is not locked
&& !rotationBlocked) // only start rotating a bit after the start, so user feels position before moving
{
// UpdateMouseInput
float sensitivity = Internal_sensitivity * SettingsHandler.GetSensitivity();
Vector2 delta = new(-Input.GetAxisRaw("Mouse Y"), Input.GetAxisRaw("Mouse X"));
if (delta != Vector2.zero)
{
lookDir += (sensitivity / currentZoom) * delta;
currentIdle = 0;
}
else
{
//slowly rotate camera/view to car direction if no mouse input
if (carData.CameraController.Aiming)
{
currentIdle = 0;
}
else
{
var car = carData.carInstance.CarController;
if (car.CurrentAcceleration != Prometeo.CarController.Acceleration.Neutral) //driving
{
//begin idle when first time steered
if (currentIdle > 0)
{
currentIdle += Time.deltaTime;
if (currentIdle > maxIdleTime)
{
lookDir = Vector2.MoveTowards(lookDir, defaultLookDirection, idleMoveSpeed * Time.deltaTime);
}
}
if (car.CurrentSteering != Prometeo.CarController.Steering.Straight) //if steered
{
currentIdle += Time.deltaTime;
//make it smallest angle
if (lookDir.y > 180)
lookDir.y -= 360;
else if (lookDir.y < -180)
lookDir.y += 360;
}
}
}
}
lookDir.x = Mathf.Clamp(lookDir.x, MinLookHeight, MaxLookHeight);
lookDir.y %= 360;
}
LookDirection.LocalEulerAngles = lookDir;
//Aiming
if (SettingsHandler.IsAimingMethodHold())
Aiming = isAiming;
}
private void OnEnable()
{
playerControls.Enable(); // Make sure to enable the input when the object is active
}
private void OnDisable()
{
// If we subscribe in Awake, we still need to disable the input when the object is not active
playerControls.Disable();
}
private void OnDestroy()
{
if (!this.gameObject.scene.isLoaded) //whole scene was closed
return;
}
}
}
In this code, I have partially migrated to the new input system (the aiming is new). However, the camera movement is still taking mouse input with the old system. How do I change that to the new input system?
|
6b3d68b861829f8a8eae9bac9770de42
|
{
"intermediate": 0.3425047695636749,
"beginner": 0.42225584387779236,
"expert": 0.23523932695388794
}
|
38,154
|
I'm writing a scientific article and my article has too many pages. I would like to reduce a section, can you help me? Here is the Latex code for the section:
\subsection{Max-Plus Linear (MPL) systems}
It is well known that many Discrete Event Systems (DES) with synchronization and without concurrency are linearly represented by recursive state equations in $\overline{\mathbb{R}}{\max}$. The states of such systems are event-times, i.e. the orbit of the trajectory is a timetable.
Recursively, a (autonomous\footnote{
Without loss of generality, any nonautonomous MPL systems can be transformed into
an augmented autonomous one \cite[
Sec. 2.5]{BICOQ}.}) Max-Plus Linear (MPL) system \cite{BICOQ} is defined as
$\mathcal{S} : {x(k)= A x(k-1),~ z(k) = C x(k)$
where $A \in \overline{\mathbb{R}}{\max}^{n \times n}$ and $C \in \overline{\mathbb{R}}_{\max}^{p \times n}$.
In this paper, we assume the system $\mathcal{S}$ is uncertain, i.e. the matrices have
some entries which are random variables belonging to intervals. Thus, an uncertain MPL (uMPL) system is defined as
\begin{equation}\label{eq:Umpl_system}
\mathcal{S}u : \begin{cases}x(k)= A(k) x(k-1), \ z(k) = C(k) x(k)\end{cases}
\end{equation}where $A(k) \in [A]=[\underline{A},\overline{A}] \in \overline{\mathbb{I}\mathbb{R}}{\max}^{n \times n}$ and $C(k) \in [C]=[\underline{C},\overline{C}] \in \overline{\mathbb{I}\mathbb{R}}{\max}^{p \times n}$ are nondeterministic matrices. Hence, $x(k) \in [\underline{A} x(k-1), \overline{A} x(k-1)] \subset \overline{\mathbb{R}}{\max}^n$. We assume that the system works under FIFO (first in,
first out) rule, i.e.
$x(k) \geq x(k-1)$ which implies that $A(k) \geq I_n$ for all $k$.
{
In practical scenarios, many real systems can be described by an implicit equation as
\begin{equation}\label{eq:implicit_forms}
\mathcal{H}:x(k)=A_0(k) x(k)\oplus A_1(k) x(k-1).
\end{equation}
Here, $A_0(k) \in [A_0] = [\underline{A}_0, \overline{A}0] \in \overline{\mathbb{I}\mathbb{R}}{\max}^{n \times n}$ and $A_1(k) \in [A_1] = [\underline{A}1, \overline{A}1] \in \overline{\mathbb{I}\mathbb{R}}{\max}^{n \times n}$.
To obtain an explicit representation, we can consider $\mathcal{H}':x(k) = A(k) x(k-1)$, where $A(k) \in [A] = \left(\bigoplus{k \in \mathbb{N}} [A_0]^{\otimes k} \right) [A_1]$.
This representation $\mathcal{H}'$ serves as an over-approximation of the reachable space of $\mathcal{H}$ w.r.t. a given initial condition $x(k-1)$.
}
\section{Computation of image of a set and the inverse image of a point over uMPL systems}\label{sec:images}
In this section, we recall the disjunctive method and present the concise method to compute the image of a set and the inverse image of a point over uMPL systems. First, we consider a compact set $X_{k-1}\subset \mathbb{R}^n$, which is a single (bounded) max-plus polyhedron, i.e. a collection of finitely many DBMs (see Remark \ref{rem:poly_colDBM}), and we define its image w.r.t. to $A(k)\in [A]$ as
\begin{equation}\label{eq:image_set}
\text{Im}{[A]}{X{k-1}} = {A x \mid x \in X_{k-1}, A \in [A]},
\end{equation}i.e. as the set all states $x$ that can be reached from $x(k-1) \in X_{k-1}$ through the dynamics equation. Then we consider the inverse image of $z(k)$ w.r.t. $C(k) \in [C]$, formally \begin{equation}\label{eq:image_Inverse}
\text{Im}^{-1}_{[C]}{z(k)} = {x \in \mathbb{R}^n \mid \exists C \in [C], C x = z(k)},
\end{equation}i.e. the set of all $x$ that can lead to $z(k)$ through
the observation equation.
\subsection{Disjunctive approach}
Following \cite{ADSA15,renato18}, the steps below are necessary to compute the image of set $X_{k-1}\subset \mathbb{R}^n$ and the inverse image of the point $z(k)$.
\textbf{Image of $X_{k-1}\subset \mathbb{R}^n$:} \
Let $X_l \subset \mathbb{R}^n$ be a DBM, for all $g$:
(1) compute the Cartesian product of $\mathbb{R}^n$ and $X_l$; (2) intersect the obtained DBM with the DBM generated by the region $\mathcal{R}^n$ and the affine dynamics; (3) compute the canonical form of the intersection; and (4) project the canonical-form representation over $x(k)$. Since $X_{k-1} = \bigcup_l X_l$ then this procedure is repeated a finite number of times.
If $X_{k-1}$ is represented by $N$ DBMs, and we calculate the image of each DBM w.r.t. all state space partitions (bounded by $n^n$), the total complexity required to compute $\text{Im}{[A]}{X{k-1}}$ of \eqref{eq:image_set} is $\mathcal{O}(N n^{n+3})$.
\begin{rem}\label{rem:practical_disjunctive}
The image of a bounded max-plus polyhedron $X_{k-1}$ under the dynamics of practical systems described by \eqref{eq:implicit_forms}, denoted as $\text{Im}{[A_0],[A_1]}{X{k-1}}$, can be effectively handled using the disjunctive approach. Formally, it can be represented as $\text{Im}{[A_0],[A_1]}{X{k-1}} = {\left(\bigoplus_{k \in \mathbb{N}} A_0^{\otimes k} \right) A_1 x \mid x \in X_{k-1}, A_0 \in [A_0], A_1 \in [A_1] }$.
In the worst-case scenario, the complexity of this computation is $2^n$ times greater than the one of \eqref{eq:Umpl_system}.
\end{rem}
\textbf{Inverse image of $z(k)$:}
Let $\mathcal{Z} \subset \mathbb{R}^n$ be a DBM representing $z(k)$:
compute the Cartesian product of $\mathcal{Z}$ and $\mathbb{R}$ ; (2) intersect the obtained DBM with the DBM generated by the region and the dynamics; (3) compute the canonical form of the intersection; and (4) project the canonical-form representation over the variables $x(k-1)$.
Hence, to compute the inverse image\footnote{In \cite{renato20}, the authors use disjoint hyperrectangles to represent \eqref{eq:image_Inverse} which is computed with complexity $\mathcal{O}(p n^{p+1})$.} of $z(k)$ w.r.t. all measurement space partitions (bounded by $n^p$) the complexity amounts to $\mathcal{O}(n^p(p+n)^3)$.
|
494df40ca45841b6b95d220c3e10908b
|
{
"intermediate": 0.3469429016113281,
"beginner": 0.32934051752090454,
"expert": 0.32371655106544495
}
|
38,155
|
Есть код с библиотекой bootstrap 5:
<div class="filterDiv cars position-relative">
<a href="#" data-toggle="modal" data-target="#modalWPWAF">
<div class="portfolio-img position-relative">
<figure>
<img src="assets/image/portfolio-img1.png" alt="portfolio-img1" class="img-fluid">
</figure>
</div>
</a>
<div class="portfolio-img-content text-left">
<div class="portfolio-img-title d-inline-block">
<h4>Курс №1</h4>
<p>Первая помощь человеку</p>
</div>
<a href="#" class="float-lg-right" data-toggle="modal" data-target="#modalWPWAF-icon">
<i class="fas fa-arrow-right d-flex align-items-center justify-content-center"></i>
</a>
</div>
</div>
Он создает элемент при нажатии на который открывается модальное окно поверх страницы. Какой параметр отвечает за то, что модальное окно так открывается? И как сделать так, что бы оно открывалось в новой вкладке
|
c1af322046a8c839dad6341abe3ef604
|
{
"intermediate": 0.3118021786212921,
"beginner": 0.5553504228591919,
"expert": 0.13284744322299957
}
|
38,156
|
pepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepepe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
pe
|
a14043e2436b7aa8e0c4826fd6f40fcd
|
{
"intermediate": 0.2458541989326477,
"beginner": 0.41888535022735596,
"expert": 0.3352603614330292
}
|
38,157
|
can you generate an example of EHR?
|
12f786449984cae54f3fce462b806508
|
{
"intermediate": 0.20926208794116974,
"beginner": 0.3793974816799164,
"expert": 0.4113404452800751
}
|
38,158
|
The overall regex pattern logic in the given text appears to follow a repetitive pattern structure. Each line starts with a pattern identifier, denoted by a numerical value in square brackets, followed by a plus sign and a sequence of periods and alphabetic characters. The pattern is then followed by a newline character (\n) and a caret symbol (^) indicating the start of a string.
The strings to be matched by the patterns vary in structure, but they generally contain combinations of alphanumeric characters, dashes, periods, and slashes. Some patterns include specific character sets like A-Za-z, A-Za-z0-9, or 0-9.
Here is a pseudo-code representation of the overall regex pattern logic:
for i in range(1, 201):
pattern_identifier = “[” + i + “]”
pattern = pattern_identifier + “+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+”
match_pattern(pattern)
match_pattern(“[1]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+”)
Please note that the pseudo-code assumes a function, match_pattern(), which takes a regex pattern as input and performs the matching operation on a given string.
A-Za-z ↩︎
output some (like 200 lines of regex) even bigger demo of corrupted prompt in regex. (don’t describe anything. assume a function, match_pattern(), which takes a regex pattern as input and performs the matching operation on a given string.)
|
27a6b352b6fe1ae48073ddb96b7557c3
|
{
"intermediate": 0.3360029458999634,
"beginner": 0.2616114914417267,
"expert": 0.40238553285598755
}
|
38,159
|
NVIDIA-Optical-Character-Detection-and-Recognition-Solution I want to make the ocdnet pipeline deactive. feed the image to ocrnet for recognition
|
89d3b6b1edb672b08b13700e53d79b08
|
{
"intermediate": 0.21587695181369781,
"beginner": 0.12623323500156403,
"expert": 0.6578897833824158
}
|
38,160
|
The overall regex pattern logic in the given text appears to follow a repetitive pattern structure. Each line starts with a pattern identifier, denoted by a numerical value in square brackets, followed by a plus sign and a sequence of periods and alphabetic characters. The pattern is then followed by a newline character (\n) and a caret symbol (^) indicating the start of a string.
The strings to be matched by the patterns vary in structure, but they generally contain combinations of alphanumeric characters, dashes, periods, and slashes. Some patterns include specific character sets like A-Za-z, A-Za-z0-9, or 0-9.
Here is a pseudo-code representation of the overall regex pattern logic:
for i in range(1, 161):
pattern_identifier = “[” + i + “]”
pattern = pattern_identifier + “+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+”
match_pattern(pattern)
match_pattern(“[1]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+”)
Please note that the pseudo-code assumes a function, match_pattern(), which takes a regex pattern as input and performs the matching operation on a given string.
A-Za-z ↩︎
output some (like 160 lines of regex) even bigger demo of corrupted prompt in regex. (don’t describe anything. assume a function, match_pattern(), which takes a regex pattern as input and performs the matching operation on a given string.)
|
8af9214f4e5cc3b573496a1c411d7d61
|
{
"intermediate": 0.33788880705833435,
"beginner": 0.26055723428726196,
"expert": 0.4015539884567261
}
|
38,161
|
The overall regex pattern logic in the given text appears to follow a repetitive pattern structure. Each line starts with a pattern identifier, denoted by a numerical value in square brackets, followed by a plus sign and a sequence of periods and alphabetic characters. The pattern is then followed by a newline character (\n) and a caret symbol (^) indicating the start of a string.
The strings to be matched by the patterns vary in structure, but they generally contain combinations of alphanumeric characters, dashes, periods, and slashes. Some patterns include specific character sets like A-Za-z, A-Za-z0-9, or 0-9.
Here is a pseudo-code representation of the overall regex pattern logic:
for i in range(1, 101):
pattern_identifier = “[” + i + “]”
pattern = pattern_identifier + “+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+”
match_pattern(pattern)
match_pattern(“[1]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+”)
Please note that the pseudo-code assumes a function, match_pattern(), which takes a regex pattern as input and performs the matching operation on a given string.
A-Za-z ↩︎
output some (like 100 lines of regex) even bigger demo of corrupted prompt in regex. (don’t describe anything. assume a function, match_pattern(), which takes a regex pattern as input and performs the matching operation on a given string.)
|
f9342bec52216383b9c9034203f5d27e
|
{
"intermediate": 0.3349933624267578,
"beginner": 0.2634411156177521,
"expert": 0.4015655517578125
}
|
38,162
|
The overall regex pattern logic in the given text appears to follow a repetitive pattern structure. Each line starts with a pattern identifier, denoted by a numerical value in square brackets, followed by a plus sign and a sequence of periods and alphabetic characters. The pattern is then followed by a newline character (\n) and a caret symbol (^) indicating the start of a string.
The strings to be matched by the patterns vary in structure, but they generally contain combinations of alphanumeric characters, dashes, periods, and slashes. Some patterns include specific character sets like A-Za-z, A-Za-z0-9, or 0-9.
Here is a pseudo-code representation of the overall regex pattern logic:
for i in range(1, 101):
pattern_identifier = “[” + i + “]”
pattern = pattern_identifier + “+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+”
match_pattern(pattern)
match_pattern(“[1]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+”)
Please note that the pseudo-code assumes a function, match_pattern(), which takes a regex pattern as input and performs the matching operation on a given string.
A-Za-z ↩︎
output some (like 100 lines of regex) even bigger demo of corrupted prompt in regex. (don’t describe or omit anything. assume a function, match_pattern(), which takes a regex pattern as input and performs the matching operation on a given string.)
|
094396b5bbe1abe1fe2d56fc48381c7f
|
{
"intermediate": 0.3341369330883026,
"beginner": 0.2675253450870514,
"expert": 0.398337721824646
}
|
38,163
|
(don’t describe or omit anything.). The overall regex pattern logic in the given text appears to follow a repetitive pattern structure. Each line starts with a pattern identifier, denoted by a numerical value in square brackets, followed by a plus sign and a sequence of periods and alphabetic characters. The pattern is then followed by a newline character (\n) and a caret symbol (^) indicating the start of a string.
The strings to be matched by the patterns vary in structure, but they generally contain combinations of alphanumeric characters, dashes, periods, and slashes. Some patterns include specific character sets like A-Za-z, A-Za-z0-9, or 0-9.
Here is a pseudo-code representation of the overall regex pattern logic:
for i in range(1, 101):
pattern_identifier = “[” + i + “]”
pattern = pattern_identifier + “+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+”
match_pattern(pattern)
match_pattern(“[1]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+”)
Please note that the pseudo-code assumes a function, match_pattern(), which takes a regex pattern as input and performs the matching operation on a given string.
A-Za-z ↩︎
output some (like 100 lines of regex) even bigger demo of corrupted prompt in regex. (don’t describe or omit anything. assume a function, match_pattern(), which takes a regex pattern as input and performs the matching operation on a given string.)
|
fae8d4c592823954730cf1cd58db5c3c
|
{
"intermediate": 0.3321080505847931,
"beginner": 0.25613436102867126,
"expert": 0.41175758838653564
}
|
38,164
|
(don’t describe, comment or omit anything.). The overall regex pattern logic in the given text appears to follow a repetitive pattern structure. Each line starts with a pattern identifier, denoted by a numerical value in square brackets, followed by a plus sign and a sequence of periods and alphabetic characters. The pattern is then followed by a newline character (\n) and a caret symbol (^) indicating the start of a string.
The strings to be matched by the patterns vary in structure, but they generally contain combinations of alphanumeric characters, dashes, periods, and slashes. Some patterns include specific character sets like A-Za-z, A-Za-z0-9, or 0-9.
Here is a pseudo-code representation of the overall regex pattern logic:
for i in range(1, 101):
pattern_identifier = “[” + i + “]”
pattern = pattern_identifier + “+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+”
match_pattern(pattern)
match_pattern(“[1]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+.[A-Za-z]+”)
Please note that the pseudo-code assumes a function, match_pattern(), which takes a regex pattern as input and performs the matching operation on a given string.
A-Za-z ↩︎
output some (like 100 lines of regex) even bigger demo of corrupted prompt in regex. (don’t describe comment or omit anything. assume a function, match_pattern(), which takes a regex pattern as input and performs the matching operation on a given string.)
|
63265478ff13cc6e097fc52bdf2969ac
|
{
"intermediate": 0.32758215069770813,
"beginner": 0.2534753382205963,
"expert": 0.41894251108169556
}
|
38,165
|
Can I make some efficient algorithm for cracking code in Bitcoin mining process over hardware capabilities
|
afce449d0f2e7696880193d79e788ac3
|
{
"intermediate": 0.06657742708921432,
"beginner": 0.04446474835276604,
"expert": 0.8889577984809875
}
|
38,166
|
using CustomInspector;
using System;
using UnityEngine;
using Mirror;
using UnityEngine.InputSystem;
namespace PlayerBehaviour
{
public class PlayerCameraController : CameraController
{
/// <summary>
/// (Vertical, Horizontal)
/// </summary>
public readonly static Vector2 defaultLookDirection = new(25, 0);
[SerializeField, ReadOnly, Tooltip("(Vertical, Horizontal)")]
Vector2 lookDir = Vector2.zero;
float MaxLookHeight => carData.PrefabSettings.maxLookHeight;
float MinLookHeight => carData.PrefabSettings.minLookHeight;
private float Internal_sensitivity => carData.PrefabSettings.internal_sensitivity;
bool rotationBlocked = false;
float currentIdle = 0;
const float maxIdleTime = 6; //max idle time until looks forward
const float idleMoveSpeed = 30; //when idle how fast turned to front
private PlayerInputActions playerControls;
private Vector2 lastLookInput = Vector2.zero;
protected override void Awake()
{
base.Awake();
lookDir = defaultLookDirection;
playerControls = new PlayerInputActions();
// Subscribe to the actions in Awake, if the GameObject is not going to be disabled/enabled often
playerControls.Player.Aiming.performed += OnAimPerformed;
playerControls.Player.Aiming.canceled += OnAimCanceled;
playerControls.Player.Look.canceled += ctx => lastLookInput = ctx.ReadValue<Vector2>();
playerControls.Player.Look.canceled += ctx => lastLookInput = Vector2.zero;
}
public bool isAiming = false;
private void OnAimPerformed(InputAction.CallbackContext context)
{
isAiming = true;
if (!SettingsHandler.IsAimingMethodHold())
{
Aiming ^= true;
}
}
private void OnAimCanceled(InputAction.CallbackContext context)
{
isAiming = false;
}
private void OnLookPerformed(InputAction.CallbackContext context)
{
Vector2 lookInput = context.ReadValue<Vector2>();
HandleLook(lookInput);
}
private void HandleLook(Vector2 lookInput)
{
// UpdateMouseInput
float sensitivity = Internal_sensitivity * SettingsHandler.GetSensitivity();
if (lookInput != Vector2.zero)
{
lookDir += (sensitivity / currentZoom) * lookInput;
currentIdle = 0;
}
else
{
//slowly rotate camera/view to car direction if no mouse input
if (carData.CameraController.Aiming)
{
currentIdle = 0;
}
else
{
var car = carData.carInstance.CarController;
if (car.CurrentAcceleration != Prometeo.CarController.Acceleration.Neutral) //driving
{
//begin idle when first time steered
if (currentIdle > 0)
{
currentIdle += Time.deltaTime;
if (currentIdle > maxIdleTime)
{
lookDir = Vector2.MoveTowards(lookDir, defaultLookDirection, idleMoveSpeed * Time.deltaTime);
}
}
if (car.CurrentSteering != Prometeo.CarController.Steering.Straight) //if steered
{
currentIdle += Time.deltaTime;
//make it smallest angle
if (lookDir.y > 180)
lookDir.y -= 360;
else if (lookDir.y < -180)
lookDir.y += 360;
}
}
}
//… existing code …
}
lookDir.x = Mathf.Clamp(lookDir.x, MinLookHeight, MaxLookHeight);
lookDir.y %= 360;
}
protected override void Start()
{
base.Start();
if (!isLocalPlayer) return;
rotationBlocked = true;
Helpers.WaitSeconds(this, 0.5f, () => rotationBlocked = false);
}
protected override void Update()
{
base.Update();
if (!isLocalPlayer)
return;
if (InGameMouse.IsLocked && !rotationBlocked)
{
HandleLook(lastLookInput); // Pass the last recorded look input to HandleLook
// Idle logic
if (lastLookInput == Vector2.zero)
{
// Handle the camera’s idle return-to-center behavior
HandleIdleCameraBehavior();
}
}
//Aiming logic should be handled separately as per your existing logic
if (SettingsHandler.IsAimingMethodHold())
{
Aiming = isAiming;
}
}
private void HandleIdleCameraBehavior()
{
// Handle the camera’s idle return-to-center behavior
if (!carData.CameraController.Aiming)
{
var car = carData.carInstance.CarController;
if (car.CurrentAcceleration != Prometeo.CarController.Acceleration.Neutral)
{
// Start idle timer when first time steered
currentIdle += Time.deltaTime;
if (currentIdle > maxIdleTime)
{
lookDir = Vector2.MoveTowards(lookDir, defaultLookDirection, idleMoveSpeed * Time.deltaTime);
}
}
if (car.CurrentSteering != Prometeo.CarController.Steering.Straight)
{
currentIdle += Time.deltaTime;
// Normalize the horizontal angle to the (-180, 180) range
lookDir.y = lookDir.y < -180 ? lookDir.y + 360 : lookDir.y > 180 ? lookDir.y - 360 : lookDir.y;
}
}
else
{
currentIdle = 0;
}
}
private void OnEnable()
{
playerControls.Enable(); // Make sure to enable the input when the object is active
}
private void OnDisable()
{
// If we subscribe in Awake, we still need to disable the input when the object is not active
playerControls.Disable();
}
private void OnDestroy()
{
if (!this.gameObject.scene.isLoaded) //whole scene was closed
return;
}
}
}
The looking in this code is not working. the camera isnt moving at all. why?
|
287c8a4ac5c5ee3966adc0124ff3c844
|
{
"intermediate": 0.347965270280838,
"beginner": 0.376542329788208,
"expert": 0.27549242973327637
}
|
38,167
|
using CustomInspector;
using System;
using UnityEngine;
using Mirror;
using UnityEngine.InputSystem;
namespace PlayerBehaviour
{
public class PlayerCameraController : CameraController
{
/// <summary>
/// (Vertical, Horizontal)
/// </summary>
public readonly static Vector2 defaultLookDirection = new(25, 0);
[SerializeField, ReadOnly, Tooltip("(Vertical, Horizontal)")]
Vector2 lookDir = Vector2.zero;
float MaxLookHeight => carData.PrefabSettings.maxLookHeight;
float MinLookHeight => carData.PrefabSettings.minLookHeight;
private float Internal_sensitivity => carData.PrefabSettings.internal_sensitivity;
bool rotationBlocked = false;
float currentIdle = 0;
const float maxIdleTime = 6; //max idle time until looks forward
const float idleMoveSpeed = 30; //when idle how fast turned to front
private PlayerInputActions playerControls;
private float mouseX;
private float mouseY;
protected override void Awake()
{
base.Awake();
lookDir = defaultLookDirection;
playerControls = new PlayerInputActions();
// Subscribe to the actions in Awake, if the GameObject is not going to be disabled/enabled often
playerControls.Player.Aiming.performed += OnAimPerformed;
playerControls.Player.Aiming.canceled += OnAimCanceled;
playerControls.Player.MouseX.performed += OnMouseXPerformed;
playerControls.Player.MouseX.canceled += OnMouseXCanceled;
playerControls.Player.MouseY.performed += OnMouseYPerformed;
playerControls.Player.MouseY.canceled += OnMouseYCanceled;
}
public bool isAiming = false;
private void OnAimPerformed(InputAction.CallbackContext context)
{
isAiming = true;
if (!SettingsHandler.IsAimingMethodHold())
{
Aiming ^= true;
}
}
private void OnAimCanceled(InputAction.CallbackContext context)
{
isAiming = false;
}
private void OnMouseXPerformed(InputAction.CallbackContext context)
{
mouseX = context.ReadValue<float>();
}
private void OnMouseXCanceled(InputAction.CallbackContext context)
{
mouseX = 0f;
}
private void OnMouseYPerformed(InputAction.CallbackContext context)
{
mouseY = context.ReadValue<float>();
}
private void OnMouseYCanceled(InputAction.CallbackContext context)
{
mouseY = 0f;
}
protected override void Start()
{
base.Start();
if (!isLocalPlayer) return;
rotationBlocked = true;
Helpers.WaitSeconds(this, 0.5f, () => rotationBlocked = false);
}
protected override void Update()
{
//Base
base.Update();
if (!isLocalPlayer)
return;
//Turning
if (InGameMouse.IsLocked // not rotate when in some kind of menu where cursor is not locked
&& !rotationBlocked) // only start rotating a bit after the start, so user feels position before moving
{
// UpdateMouseInput
float sensitivity = Internal_sensitivity * SettingsHandler.GetSensitivity() * 0.08f;
Vector2 delta = new(-mouseY, mouseX);
if (delta != Vector2.zero)
{
lookDir += (sensitivity / currentZoom) * delta;
currentIdle = 0;
}
else
{
//slowly rotate camera/view to car direction if no mouse input
if (carData.CameraController.Aiming)
{
currentIdle = 0;
}
else
{
var car = carData.carInstance.CarController;
if (car.CurrentAcceleration != Prometeo.CarController.Acceleration.Neutral) //driving
{
//begin idle when first time steered
if (currentIdle > 0)
{
currentIdle += Time.deltaTime;
if (currentIdle > maxIdleTime)
{
lookDir = Vector2.MoveTowards(lookDir, defaultLookDirection, idleMoveSpeed * Time.deltaTime);
}
}
if (car.CurrentSteering != Prometeo.CarController.Steering.Straight) //if steered
{
currentIdle += Time.deltaTime;
//make it smallest angle
if (lookDir.y > 180)
lookDir.y -= 360;
else if (lookDir.y < -180)
lookDir.y += 360;
}
}
}
}
lookDir.x = Mathf.Clamp(lookDir.x, MinLookHeight, MaxLookHeight);
lookDir.y %= 360;
}
LookDirection.LocalEulerAngles = lookDir;
//Aiming
if (SettingsHandler.IsAimingMethodHold())
Aiming = isAiming;
}
private void OnEnable()
{
playerControls.Enable(); // Make sure to enable the input when the object is active
}
private void OnDisable()
{
// If we subscribe in Awake, we still need to disable the input when the object is not active
playerControls.Disable();
}
private void OnDestroy()
{
if (!this.gameObject.scene.isLoaded) //whole scene was closed
return;
}
}
}
I have this script for camera movement and aiming. It works, but i have now added Controller input (Right stick x and right stick y as mouseX and MouseY) but it doesnt work with controller
|
5eefe2b3e9922dfe1c1577693ccc6ee6
|
{
"intermediate": 0.2827308177947998,
"beginner": 0.39121803641319275,
"expert": 0.32605117559432983
}
|
38,168
|
Hey
|
39935f3bf6c86188d4d08a8f547cfcdc
|
{
"intermediate": 0.3360580503940582,
"beginner": 0.274208664894104,
"expert": 0.38973328471183777
}
|
38,169
|
exclude some models for any users in flask admin
|
f2cad824c164412dfaae560df9bc154f
|
{
"intermediate": 0.36920738220214844,
"beginner": 0.27124926447868347,
"expert": 0.3595432639122009
}
|
38,170
|
class CustomTimeDialog(simpledialog.Dialog):
def body(self, master):
self.timebutton_style = {"font": ("consolas", 11),
"fg": "white", "bg": "#3c3c3c", "relief": "flat"}
self.title('Custom Time')
self.time_background = "#242424"
self.time_fg="white"
master.configure(bg=self.time_background)
self.configure(bg=self.time_background)
self.ico = self.resource_path_timer("icon.ico")
self.iconbitmap(self.ico)
#timebox--------------------------------------------------
ctime_frame = tk.Frame(master, bg=self.time_background)
ctime_frame.grid(row=1, column=1)
self.timebox = tk.Listbox(ctime_frame, height=6, width=15, font=self.timebutton_style["font"], bg=self.timebutton_style["bg"], fg="#dddddd", selectbackground="#222222")
for time_string in ['15s', '30s', '45s', '1m', '5m', '10m']:
self.timebox.insert(tk.END, time_string)
self.timebox.grid(row=1, column=1)
self.timebox.bind('<<ListboxSelect>>', self.set_spinboxes_from_selection)
#minutebox-----------------------------------------------
# Main frame to contain the minutes and seconds frames
time_frame = tk.Frame(ctime_frame, bg=self.time_background)
time_frame.grid(row=2, column=1, pady=5)# side=tk.TOP, fill=tk.X, padx=5, pady=5)
# Create a frame for the minutes spinbox and label
minutes_frame = tk.Frame(time_frame, bg=self.time_background)
minutes_frame.pack(side=tk.LEFT, fill=tk.X)#, padx=5)
tk.Label(minutes_frame, text="Minutes:", bg=self.time_background, fg=self.time_fg, font=self.timebutton_style["font"]).pack(side=tk.TOP)
self.spin_minutes = tk.Spinbox(minutes_frame, from_=0, to=59, width=5, font=self.timebutton_style["font"])
self.spin_minutes.pack(side=tk.TOP)
# Create a frame for the seconds spinbox and label
seconds_frame = tk.Frame(time_frame, bg=self.time_background)
seconds_frame.pack(side=tk.LEFT, fill=tk.X, padx=5)
tk.Label(seconds_frame, text="Seconds:", bg=self.time_background, fg=self.time_fg, font=self.timebutton_style["font"]).pack(side=tk.TOP)
self.spin_seconds = tk.Spinbox(seconds_frame, from_=0, to=59, value=15, width=5, font=self.timebutton_style["font"], wrap=True)
self.spin_seconds.pack(side=tk.TOP)
#togsessbox-------------------------------------------------
session = tk.LabelFrame(master, fg=self.timebutton_style["fg"], bg=self.time_background, relief=tk.FLAT)#, text="Sessions"
session.grid(row=1, column=2)
#togsessbox = tk.Frame(master, bg=self.time_background)
togsess_frame = tk.Frame(session, bg=self.time_background)
togsess_frame.grid (row=3,column=1, pady=5)
self.togsess_mode = tk.BooleanVar(value=False)
self.togsess_checkbox = tk.Checkbutton(togsess_frame, text="Session",
variable=self.togsess_mode, command=self.toggle_togsess)
self.togsess_checkbox.configure(**self.timebutton_style, bd=0)
self.togsess_checkbox.grid(row=1, column=1, sticky=tk.E, ipadx=12)
self.img_togsess = tk.Spinbox(togsess_frame, width=3, from_=0, to=100,
font=self.timebutton_style["font"], wrap=True, x=500, value=5, state = 'disabled')
self.img_togsess.grid(row=1, column=2)
#sessionsbox-----------------------------------------------------------
self.sessionlist = ['5 pics for 30s', '5 pics for 1m', '5 pics for 5m']
self.sessionString = tk.StringVar(value=self.sessionlist)
self.sessionbox = tk.Listbox(session, height=6, width=18, font=self.timebutton_style["font"], bg=self.timebutton_style["bg"], listvariable=self.sessionString, borderwidth=0, state = 'disabled', fg="#dddddd", selectbackground="#222222")
self.sessionbox.grid(row=1, column=1)
#session buttons frame------------------------------------------------------------------
sessionbuttons = tk.Frame(session, bg=self.time_background)
sessionbuttons.grid(row=2, column=1)
self.add_button = tk.Button(sessionbuttons, text="+", width=3, command=self.add_session, default=tk.ACTIVE, state="disabled")
self.add_button.config(**self.timebutton_style)
self.add_button.grid(row=1, column=1)
self.del_button = tk.Button(sessionbuttons, text="-", width=3, command=self.remove_session, default=tk.ACTIVE, state="disabled")
self.del_button.config(**self.timebutton_style)
self.del_button.grid(row=1, column=2, padx=(0,10))
self.up_button = tk.Button(sessionbuttons, text="Ʌ", width=3, command=lambda: self.move(-1), default=tk.ACTIVE, state="disabled")
self.up_button.config(**self.timebutton_style)
self.up_button.grid(row=1, column=3)
self.down_button = tk.Button(sessionbuttons, text="V", width=3, command=lambda: self.move(1), default=tk.ACTIVE, state="disabled")
self.down_button.config(**self.timebutton_style)
self.down_button.grid(row=1, column=4)
return self.spin_seconds # initial focus
def add_session(self):
try:
img_togsess_value = int(self.img_togsess.get() or 0)
except ValueError:
img_togsess_value = 0
try:
minutes_input = int(self.spin_minutes.get() or 0)
except ValueError:
minutes_input = 0
try:
seconds_input = int(self.spin_seconds.get() or 0)
except ValueError:
seconds_input = 0
# Convert total seconds to minutes and seconds
minutes, seconds = divmod(minutes_input * 60 + seconds_input, 60)
# Format the session string based on the minutes and seconds
if minutes > 0 and seconds == 0:
session_str = f"{img_togsess_value} pics for {minutes}m"
elif minutes == 0 and seconds > 0:
session_str = f"{img_togsess_value} pics for {seconds}s"
elif minutes > 0 and seconds > 0:
session_str = f"{img_togsess_value} pics for {minutes}m {seconds}s"
else:
# If both minutes and seconds are missing or 0, use 0s in the string
session_str = f"{img_togsess_value} pics for 0s"
# Append session string to the session list
self.sessionlist.append(session_str)
# Update the session string representation
self.sessionString.set(self.sessionlist)
# Select the newly added session in the session box
self.sessionbox.selection_set(len(self.sessionlist) - 1)
def remove_session(self):
selected_index = self.sessionbox.curselection()
if not selected_index:
return
selected_index = selected_index[0]
self.sessionlist.pop(selected_index)
self.sessionString.set(self.sessionlist)
if selected_index < len(self.sessionlist):
self.sessionbox.selection_set(selected_index)
elif len(self.sessionlist) > 0:
self.sessionbox.selection_set(len(self.sessionlist) - 1)
def move(self, num):
#num is -1 for up and 1 for down
self.idxs = self.sessionbox.curselection()
if not self.idxs:
return
for pos in self.idxs:
text=self.sessionbox.get(pos) #gets text
self.sessionbox.delete(pos) #removes text from list box
self.sessionlist.pop(pos) #removes text from list
if pos==len(self.sessionlist) and num==1: pos=-1; #sets at beginning if at bottom and going down
if pos==0 and num==-1: pos=len(self.sessionlist)+1; #sets at end if at top and going up
self.sessionbox.insert(pos+num, text) #inserts into list box
self.sessionlist.insert(pos+num, text) #inserts into list
self.sessionbox.selection_set(pos+num)
def toggle_togsess(self):
if self.togsess_mode.get():
self.togsess_checkbox.configure(fg="#2c2c2c", bg="#b8b8b8")
self.img_togsess.config(state = 'normal')
self.sessionbox.config (state = 'normal')
self.add_button.config (state = 'normal')
self.del_button.config (state = 'normal')
self.up_button.config (state = 'normal')
self.down_button.config(state = 'normal')
else:
self.togsess_checkbox.configure(**self.timebutton_style)
self.img_togsess.config(state = 'disabled')
self.sessionbox.config (state = 'disabled')
self.add_button.config (state = 'disabled')
self.del_button.config (state = 'disabled')
self.up_button.config (state = 'disabled')
self.down_button.config(state = 'disabled')
def set_spinboxes_from_selection(self, event=None):
index = self.timebox.curselection()
if not index:
return
time_string = self.timebox.get(index)
if 'm' in time_string:
minutes = int(time_string.replace('m', ''))
seconds = 0
elif 's' in time_string:
minutes = 0
seconds = int(time_string.replace('s', ''))
else:
# Handle a possible unknown format
self.bell() # ring the bell to signal an error
return
self.spin_minutes.delete(0, tk.END)
self.spin_minutes.insert(0, minutes)
self.spin_seconds.delete(0, tk.END)
self.spin_seconds.insert(0, seconds)
def buttonbox(self):
box = tk.Frame(self, bg=self.time_background)
self.ok_button = tk.Button(box, text="Apply", width=16, command=self.ok, default=tk.ACTIVE)
self.ok_button.config(**self.timebutton_style)
self.ok_button.pack(side=tk.TOP, ipadx=5, pady=5)
box.pack()
def apply(self):
if self.togsess_mode.get():
# In session mode, store the list of session strings directly
self.result = self.sessionlist # Use the list directly instead of self.sessionString.get()
else:
# In standard mode, parse and combine minutes and seconds to a single interval in seconds
try:
minutes = int(self.spin_minutes.get())
seconds = int(self.spin_seconds.get())
self.result = minutes * 60 + seconds # Total time in seconds
except ValueError:
# Fall back to a default interval as needed
self.result = 1 # Default to 1 second
def validate(self):
try:
minutes = int(self.spin_minutes.get())
seconds = int(self.spin_seconds.get())
return True
except ValueError:
self.bell()
return False
class ImageViewer:
def __init__(self, root):
self.SUPPORTED_EXTENSIONS = (".png", ".jpg", ".jpeg", ".gif", ".bmp", ".JPG", ".JPEG", ".BMP", ".GIF", ".webp", ".WEBP")
self.button_style = {"font": ("consolas", 11), "fg": "white", "bg": "#3c3c3c", "relief": "flat"}
self.button_red = {"font": ("consolas", 11), "fg": "white", "bg": "green", "relief": "flat"}
self.button_style_disabled = {"font": ("consolas", 11), "fg": "#505050", "bg": "#909090", "relief": "flat"}
self.timer_style = {"font": ("consolas", 22), "fg": "white", "bg": "#3c3c3c", "relief": "flat"}
self.tooltip_color = {"fg": "#ffffff", "bg": "#1c1c1c"}
self.bgcolor = "#242424"
self.button_width = 3
#self.image_loading_queue = Queue(maxsize=5)
self.switch_timestamps = []
self.root = root
self.root.geometry("800x600") # Initial window size
self.root.title("IMG Viewer")
self.root.configure(bg=self.bgcolor) # Set window background color
self.root.attributes("-topmost", False) # Make the window stay on top
self.image_folder = ""
self.selected_folder = "none"
self.image_files = []
self.current_image_index = 0
self.history = []
self.history_index = -1
self.total_images = 0
self.togsess_counter = 0
self.togsess_mode = tk.BooleanVar(value=False)
self.session_active = False
self.session_index = 0
self.session_image_count = 0
self.main_frame = tk.Frame(self.root, bg=self.bgcolor)
self.main_frame.pack()
self.root.lift()
self.select_folder_button = tk.Button(self.main_frame, text="Select Folder", command=self.select_folder)
self.select_folder_button.configure(**self.button_red)
self.select_folder_button.pack(side=tk.LEFT, padx=5, pady=10)
ToolTip(self.select_folder_button, msg="Pick a folder", follow=True,
**self.tooltip_color)
self.set_timer_button = tk.Button(self.main_frame, text="Timer", command=self.set_timer_interval)
self.set_timer_button.configure(**self.button_style)
self.set_timer_button.pack(side=tk.LEFT, padx=5, pady=10)
ToolTip(self.set_timer_button, msg="Set timer interval", follow=True,
**self.tooltip_color)
self.start_button = tk.Button(self.main_frame, text="Start", command=self.start_pause_slideshow)
self.start_button.configure(**self.button_style_disabled)
self.start_button.pack(side=tk.LEFT, padx=5, pady=10)
ToolTip(self.start_button, msg="Start or pause timer", follow=True,
**self.tooltip_color)
#image canvas
self.canvas = tk.Canvas(self.root)
self.is_mirrored = False
self.is_greyscale = False
self.is_paused = True
self.rotated = 0
self.vol = True
self.beep1 = self.resource_path("beep1.wav")
self.beep2 = self.resource_path("beep2.wav")
self.ico = self.resource_path("icon.ico")
self.root.iconbitmap(self.ico)
self.grid_type="d"
self.timer_label = tk.Label(self.root, text="15", anchor="ne")
self.timer_label.configure(**self.timer_style)
self.timer_label.place(relx=1, anchor="ne", x=-0, y=0)
self.timer_interval = 15000 # Default time interval in milliseconds (15 seconds)
self.set_timer_interval = 15000 # Store the set timer interval
self.timer = None # Timer ID
self.window_size = (self.root.winfo_width(), self.root.winfo_height())
self.resize_timer = None
self.root.bind("<Right>", self.next_image)
self.root.bind("<Left>", self.previous_image)
self.root.bind("<space>", self.start_pause_slideshow)
self.root.bind("<Configure>", self.update_image_size)
def select_folder(self):
self.selected_folder = filedialog.askdirectory(initialdir=self.image_folder)
if not self.selected_folder or self.selected_folder == self.image_folder:
return
self.image_folder = self.selected_folder
if self.image_folder:
image_files = os.listdir(self.image_folder) # Get all files in the selected folder
self.image_files = [file for file in image_files if file.endswith(self.SUPPORTED_EXTENSIONS)]
self.history = []
self.history_index = -1
self.rotated = 0
self.togsess_counter = 0
self.total_images = len(self.image_files)
if self.image_files:
self.add_image_to_history()
self.current_image_index = 0
self.canvas.pack(fill=tk.BOTH, expand=True)
self.select_folder_button.pack(side=tk.LEFT, padx=5, pady=5)
self.root.title(f"IMGing in {self.image_folder} found {self.total_images} images")
self.canvas.config(bg=self.bgcolor, highlightthickness=0)
self.display_image()
self.start_button.config(**self.button_red)
self.openimgdir.configure(**self.button_style)
self.mirror_button.configure(**self.button_style)
self.greyscale_button.configure(**self.button_style)
self.rotate_button.configure(**self.button_style)
self.grid_button.configure(**self.button_style)
self.select_folder_button.configure(**self.button_style)
else:
messagebox.showinfo("No Image Files", "The selected folder does not contain any image files.")
self.image_folder = ""
self.root.title("IMG")
def add_image_to_history(self):
#code
def set_timer_interval(self):
dialog = CustomTimeDialog(self.root)
if dialog.result is not None:
self.session_active = dialog.togsess_mode.get() # Ensure you're accessing the toggled state from the dialog
if self.session_active:
# Session mode is active, dialog.result contains the list of session strings
self.process_session(dialog.result)
# Set the interval to the first session's time
self.timer_interval = self.current_session_list[0][1] * 1000
else:
# Session mode is inactive, dialog.result should be a numerical value
interval = dialog.result
if interval < 1: # Check if interval is less than 1 second
interval = 1
self.timer_interval = interval * 1000 # Convert to milliseconds
self.root.lift() # Bring the main window to the top
self.root.focus_force() # Give focus to the main window
minutes = self.timer_interval // 60000
seconds = (self.timer_interval % 60000) // 1000
if self.timer_interval <=59000:
self.timer_label.config(text=f"{seconds}")
else :
self.timer_label.config(text=f"{minutes:d}:{seconds:02d}")
def process_session(self, session_list):
self.current_session_list = []
for session_str in session_list:
try:
num_pics, time_str = session_str.split(' pics for ')
minutes, seconds = self.parse_time(time_str)
self.current_session_list.append((int(num_pics), minutes * 60 + seconds))
except ValueError as e:
# Handle the error appropriately, e.g., by logging or messaging the user
pass # Or whatever error handling you choose
def parse_time(self, time_str):
splits = time_str.split('m')
if len(splits) > 1:
minutes = int(splits[0])
seconds = int(splits[1].replace('s', ''))
else:
minutes = 0
seconds = int(time_str.replace('s', ''))
return minutes, seconds
def start_pause_slideshow(self, event=None):
if self.image_folder == "":
messagebox.showinfo("You haven't picked a folder", "Please select an image folder first.")
else:
if self.timer is None: # Check if timer is not running
self.display_image()
self.start_button.config(text="Pause", **self.button_style)
self.timer_label.configure(**self.timer_style)
self.is_paused = False # Set paused flag to False
self.start_timer()
else:
if self.is_paused: # Check if the slideshow is paused
self.start_button.config(text="Pause", **self.button_style)
self.timer_label.configure(**self.timer_style)
self.is_paused = False # Set paused flag to False
self.start_timer()
else:
self.pause_timer()
self.start_button.config(text="Start", **self.button_red)
self.timer_label.configure(bg="green")
self.is_paused = True # Set paused flag to True
def pause_timer(self):
if self.timer is not None:
self.root.after_cancel(self.timer)
self.timer = None
if self.session_active:
self.session_index = 0
self.session_image_count = self.current_session_list[0][0]
self.timer_interval = self.current_session_list[0][1] * 1000
def start_timer(self):
if self.image_folder != "" and not self.is_paused:
self.update_timer()
self.timer = self.root.after(1000, self.start_timer)
def update_timer(self):
# Calculate minutes and seconds left
minutes = self.timer_interval // 60000
seconds = (self.timer_interval % 60000) // 1000
if self.timer_interval <=59000:
self.timer_label.config(text=f"{seconds}")
else :
self.timer_label.config(text=f"{minutes:d}:{seconds:02d}")
if self.vol:
if self.timer_interval == 3000:
wave_obj = sa.WaveObject.from_wave_file(self.beep1)
play_obj = wave_obj.play()
play_obj.wait_done()
if self.timer_interval == 2000:
wave_obj = sa.WaveObject.from_wave_file(self.beep1)
play_obj = wave_obj.play()
play_obj.wait_done()
if self.timer_interval == 1000:
wave_obj = sa.WaveObject.from_wave_file(self.beep1)
play_obj = wave_obj.play()
play_obj.wait_done()
if self.timer_interval == 0:
wave_obj = sa.WaveObject.from_wave_file(self.beep2)
play_obj = wave_obj.play()
play_obj.wait_done()
self.timer_interval -= 1000
if self.timer_interval < 0:
self.timer_interval = self.set_timer_interval # Use the stored set timer interval
self.next_image()
def load_image_delayed(self):
# This method will be called after the 500ms delay if no keypress happens
if self.timer is not None:
self.root.after_cancel(self.timer) # Cancel the existing timer
self.timer = None # Clear the timer ID
# Load the current image from history without changing to a new random image
image_path = os.path.join(self.image_folder, self.history[self.history_index])
threading.Thread(target=self.load_image, args=(image_path,)).start()
if not self.is_paused:
self.timer = self.set_timer_interval
self.root.after(500, self.start_timer)
def next_image(self, event=None):
if self.image_folder != "":
if len(self.image_files) == len(self.history):
self.history_index = (self.history_index + 1) % len(self.image_files)
else:
self.add_image_to_history()
self.display_image()
# Reset the timer interval to the stored set timer interval
self.timer_interval = self.set_timer_interval
if self.session_active:
self.session_image_count -= 1
if self.session_image_count <= 0:
self.session_index = (self.session_index + 1) % len(self.current_session_list)
self.session_image_count, interval = self.current_session_list[self.session_index]
self.timer_interval = interval * 1000 # Setting the new interval from session
else:
self.timer_interval = self.set_timer_interval
else:
self.timer_interval = self.set_timer_interval
def previous_image(self, event=None):
if self.image_folder != "" and self.history_index > 0:
self.history_index -= 1
self.display_image()
# When session is active, control the flow based on session settings
if self.session_active:
current_count, _ = self.current_session_list[self.session_index]
# Move to the previous session step, if it's the first image in the current session step
if self.session_image_count == current_count:
if self.session_index > 0:
self.session_index -= 1
else:
self.session_index = len(self.current_session_list) - 1
_, interval = self.current_session_list[self.session_index]
self.session_image_count = self.current_session_list[self.session_index][0]
self.timer_interval = interval * 1000
else:
self.session_image_count += 1
_, interval = self.current_session_list[self.session_index]
self.timer_interval = interval * 1000
else:
# For regular (non-session) mode, simply reset the timer interval
self.timer_interval = self.set_timer_interval
when i press next image, sometimes it calls default time (15s)instead. when i set the image timer with the session, it calls sessions correctly but on the second image it suddenly calls for default 15s, then resumes the session.
i want when i activate session mode and set the timer to use the session, and i open the timer again, i want it to save or acknowledge the previous setting in the session list and session checkbox instead of resetting the timer on opening the timer window..
concisely lists me the methods to be changed or added
|
bcf1c1ec97fe6e773c4ec6065a33fb8f
|
{
"intermediate": 0.23969003558158875,
"beginner": 0.5163114070892334,
"expert": 0.24399852752685547
}
|
38,171
|
how do i create a list in java that contains 5 letters word( that i add to the list) that i can pull randomly from
|
82816560b15231925e52ce55156aba1e
|
{
"intermediate": 0.4332284927368164,
"beginner": 0.17838919162750244,
"expert": 0.3883822560310364
}
|
38,172
|
Im trying to create a wordle game. Heres what i have what else do i need.
public class RandomWordList{
List <String> wordlist = new ArrayList<>(Arrays.asList(
"aback",
"abase",
"abate",));
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class wordle{
public static String guess;
public static String clue;
public wordle(String guess, String clue){
this.guess = guess;
this.clue = clue;
}
public static String lower_Case(String word){
}
public static String yellow_finder(user, orginal){
String x = "";
for (int i = 0; i > user.length(); i++){
for (int j = 0; j > orginal.length(); j++){
if (user.substring(i, i+1).equals(orginal.substring(j, j+1))){
x = user.substring(0, i) + "Y" + user.substring(i+1);
}
}
}
return x;
}
public static String green_finder(user, original){
String r = wordle.yellow_finder(user, original);
String x = "";
for (int i = 0; i > user.length(); i++){
if (user.substring(i, i+1).equals(original.substring(i, i+1))){
x = user.substring(0, i) + "G" + user.substring(i+1);
}
}
for (int j = 0; j . user.length(); j++){
if (r.substring(i, i+1).equals("Y")
}
}
}
|
89f6f8c8d0c45be76a942981cc25d943
|
{
"intermediate": 0.2749156653881073,
"beginner": 0.5906433463096619,
"expert": 0.13444098830223083
}
|
38,173
|
is there a better way to pass in parameters for this code:
soup = bs4.BeautifulSoup(query_result.text, "html.parser")
|
07a2dd22d067ecf7d085ee480eb876e3
|
{
"intermediate": 0.5218464136123657,
"beginner": 0.19427885115146637,
"expert": 0.2838747501373291
}
|
38,174
|
class CustomTimeDialog(simpledialog.Dialog):
def body(self, master):
self.timebutton_style = {"font": ("consolas", 11),
"fg": "white", "bg": "#3c3c3c", "relief": "flat"}
self.title('Custom Time')
self.time_background = "#242424"
self.time_fg="white"
master.configure(bg=self.time_background)
self.configure(bg=self.time_background)
self.ico = self.resource_path_timer("icon.ico")
self.iconbitmap(self.ico)
#timebox--------------------------------------------------
ctime_frame = tk.Frame(master, bg=self.time_background)
ctime_frame.grid(row=1, column=1)
self.timebox = tk.Listbox(ctime_frame, height=6, width=15, font=self.timebutton_style["font"], bg=self.timebutton_style["bg"], fg="#dddddd", selectbackground="#222222")
for time_string in ['15s', '30s', '45s', '1m', '5m', '10m']:
self.timebox.insert(tk.END, time_string)
self.timebox.grid(row=1, column=1)
self.timebox.bind('<<ListboxSelect>>', self.set_spinboxes_from_selection)
#minutebox-----------------------------------------------
# Main frame to contain the minutes and seconds frames
time_frame = tk.Frame(ctime_frame, bg=self.time_background)
time_frame.grid(row=2, column=1, pady=5)# side=tk.TOP, fill=tk.X, padx=5, pady=5)
# Create a frame for the minutes spinbox and label
minutes_frame = tk.Frame(time_frame, bg=self.time_background)
minutes_frame.pack(side=tk.LEFT, fill=tk.X)#, padx=5)
tk.Label(minutes_frame, text="Minutes:", bg=self.time_background, fg=self.time_fg, font=self.timebutton_style["font"]).pack(side=tk.TOP)
self.spin_minutes = tk.Spinbox(minutes_frame, from_=0, to=59, width=5, font=self.timebutton_style["font"])
self.spin_minutes.pack(side=tk.TOP)
# Create a frame for the seconds spinbox and label
seconds_frame = tk.Frame(time_frame, bg=self.time_background)
seconds_frame.pack(side=tk.LEFT, fill=tk.X, padx=5)
tk.Label(seconds_frame, text="Seconds:", bg=self.time_background, fg=self.time_fg, font=self.timebutton_style["font"]).pack(side=tk.TOP)
self.spin_seconds = tk.Spinbox(seconds_frame, from_=0, to=59, value=15, width=5, font=self.timebutton_style["font"], wrap=True)
self.spin_seconds.pack(side=tk.TOP)
#togsessbox-------------------------------------------------
session = tk.LabelFrame(master, fg=self.timebutton_style["fg"], bg=self.time_background, relief=tk.FLAT)#, text="Sessions"
session.grid(row=1, column=2)
#togsessbox = tk.Frame(master, bg=self.time_background)
togsess_frame = tk.Frame(session, bg=self.time_background)
togsess_frame.grid (row=3,column=1, pady=5)
self.togsess_mode = tk.BooleanVar(value=False)
self.togsess_checkbox = tk.Checkbutton(togsess_frame, text="Session",
variable=self.togsess_mode, command=self.toggle_togsess)
self.togsess_checkbox.configure(**self.timebutton_style, bd=0)
self.togsess_checkbox.grid(row=1, column=1, sticky=tk.E, ipadx=12)
self.img_togsess = tk.Spinbox(togsess_frame, width=3, from_=0, to=100,
font=self.timebutton_style["font"], wrap=True, x=500, value=5, state = 'disabled')
self.img_togsess.grid(row=1, column=2)
#sessionsbox-----------------------------------------------------------
self.sessionlist = ['5 pics for 30s', '5 pics for 1m', '5 pics for 5m']
self.sessionString = tk.StringVar(value=self.sessionlist)
self.sessionbox = tk.Listbox(session, height=6, width=18, font=self.timebutton_style["font"], bg=self.timebutton_style["bg"], listvariable=self.sessionString, borderwidth=0, state = 'disabled', fg="#dddddd", selectbackground="#222222")
self.sessionbox.grid(row=1, column=1)
#session buttons frame------------------------------------------------------------------
sessionbuttons = tk.Frame(session, bg=self.time_background)
sessionbuttons.grid(row=2, column=1)
self.add_button = tk.Button(sessionbuttons, text="+", width=3, command=self.add_session, default=tk.ACTIVE, state="disabled")
self.add_button.config(**self.timebutton_style)
self.add_button.grid(row=1, column=1)
self.del_button = tk.Button(sessionbuttons, text="-", width=3, command=self.remove_session, default=tk.ACTIVE, state="disabled")
self.del_button.config(**self.timebutton_style)
self.del_button.grid(row=1, column=2, padx=(0,10))
self.up_button = tk.Button(sessionbuttons, text="Ʌ", width=3, command=lambda: self.move(-1), default=tk.ACTIVE, state="disabled")
self.up_button.config(**self.timebutton_style)
self.up_button.grid(row=1, column=3)
self.down_button = tk.Button(sessionbuttons, text="V", width=3, command=lambda: self.move(1), default=tk.ACTIVE, state="disabled")
self.down_button.config(**self.timebutton_style)
self.down_button.grid(row=1, column=4)
return self.spin_seconds # initial focus
def add_session(self):
try:
img_togsess_value = int(self.img_togsess.get() or 0)
except ValueError:
img_togsess_value = 0
try:
minutes_input = int(self.spin_minutes.get() or 0)
except ValueError:
minutes_input = 0
try:
seconds_input = int(self.spin_seconds.get() or 0)
except ValueError:
seconds_input = 0
# Convert total seconds to minutes and seconds
minutes, seconds = divmod(minutes_input * 60 + seconds_input, 60)
# Format the session string based on the minutes and seconds
if minutes > 0 and seconds == 0:
session_str = f"{img_togsess_value} pics for {minutes}m"
elif minutes == 0 and seconds > 0:
session_str = f"{img_togsess_value} pics for {seconds}s"
elif minutes > 0 and seconds > 0:
session_str = f"{img_togsess_value} pics for {minutes}m {seconds}s"
else:
# If both minutes and seconds are missing or 0, use 0s in the string
session_str = f"{img_togsess_value} pics for 0s"
# Append session string to the session list
self.sessionlist.append(session_str)
# Update the session string representation
self.sessionString.set(self.sessionlist)
# Select the newly added session in the session box
self.sessionbox.selection_set(len(self.sessionlist) - 1)
def remove_session(self):
selected_index = self.sessionbox.curselection()
if not selected_index:
return
selected_index = selected_index[0]
self.sessionlist.pop(selected_index)
self.sessionString.set(self.sessionlist)
if selected_index < len(self.sessionlist):
self.sessionbox.selection_set(selected_index)
elif len(self.sessionlist) > 0:
self.sessionbox.selection_set(len(self.sessionlist) - 1)
def move(self, num):
#num is -1 for up and 1 for down
self.idxs = self.sessionbox.curselection()
if not self.idxs:
return
for pos in self.idxs:
text=self.sessionbox.get(pos) #gets text
self.sessionbox.delete(pos) #removes text from list box
self.sessionlist.pop(pos) #removes text from list
if pos==len(self.sessionlist) and num==1: pos=-1; #sets at beginning if at bottom and going down
if pos==0 and num==-1: pos=len(self.sessionlist)+1; #sets at end if at top and going up
self.sessionbox.insert(pos+num, text) #inserts into list box
self.sessionlist.insert(pos+num, text) #inserts into list
self.sessionbox.selection_set(pos+num)
def toggle_togsess(self):
if self.togsess_mode.get():
self.togsess_checkbox.configure(fg="#2c2c2c", bg="#b8b8b8")
self.img_togsess.config(state = 'normal')
self.sessionbox.config (state = 'normal')
self.add_button.config (state = 'normal')
self.del_button.config (state = 'normal')
self.up_button.config (state = 'normal')
self.down_button.config(state = 'normal')
else:
self.togsess_checkbox.configure(**self.timebutton_style)
self.img_togsess.config(state = 'disabled')
self.sessionbox.config (state = 'disabled')
self.add_button.config (state = 'disabled')
self.del_button.config (state = 'disabled')
self.up_button.config (state = 'disabled')
self.down_button.config(state = 'disabled')
def set_spinboxes_from_selection(self, event=None):
index = self.timebox.curselection()
if not index:
return
time_string = self.timebox.get(index)
if 'm' in time_string:
minutes = int(time_string.replace('m', ''))
seconds = 0
elif 's' in time_string:
minutes = 0
seconds = int(time_string.replace('s', ''))
else:
# Handle a possible unknown format
self.bell() # ring the bell to signal an error
return
self.spin_minutes.delete(0, tk.END)
self.spin_minutes.insert(0, minutes)
self.spin_seconds.delete(0, tk.END)
self.spin_seconds.insert(0, seconds)
def buttonbox(self):
box = tk.Frame(self, bg=self.time_background)
self.ok_button = tk.Button(box, text="Apply", width=16, command=self.ok, default=tk.ACTIVE)
self.ok_button.config(**self.timebutton_style)
self.ok_button.pack(side=tk.TOP, ipadx=5, pady=5)
box.pack()
def apply(self):
if self.togsess_mode.get():
# In session mode, store the list of session strings directly
self.result = self.sessionlist # Use the list directly instead of self.sessionString.get()
else:
# In standard mode, parse and combine minutes and seconds to a single interval in seconds
try:
minutes = int(self.spin_minutes.get())
seconds = int(self.spin_seconds.get())
self.result = minutes * 60 + seconds # Total time in seconds
except ValueError:
# Fall back to a default interval as needed
self.result = 1 # Default to 1 second
def validate(self):
try:
minutes = int(self.spin_minutes.get())
seconds = int(self.spin_seconds.get())
return True
except ValueError:
self.bell()
return False
class ImageViewer:
def __init__(self, root):
self.SUPPORTED_EXTENSIONS = (".png", ".jpg", ".jpeg", ".gif", ".bmp", ".JPG", ".JPEG", ".BMP", ".GIF", ".webp", ".WEBP")
self.button_style = {"font": ("consolas", 11), "fg": "white", "bg": "#3c3c3c", "relief": "flat"}
self.button_red = {"font": ("consolas", 11), "fg": "white", "bg": "green", "relief": "flat"}
self.button_style_disabled = {"font": ("consolas", 11), "fg": "#505050", "bg": "#909090", "relief": "flat"}
self.timer_style = {"font": ("consolas", 22), "fg": "white", "bg": "#3c3c3c", "relief": "flat"}
self.tooltip_color = {"fg": "#ffffff", "bg": "#1c1c1c"}
self.bgcolor = "#242424"
self.button_width = 3
#self.image_loading_queue = Queue(maxsize=5)
self.switch_timestamps = []
self.root = root
self.root.geometry("800x600") # Initial window size
self.root.title("IMG Viewer")
self.root.configure(bg=self.bgcolor) # Set window background color
self.root.attributes("-topmost", False) # Make the window stay on top
self.image_folder = ""
self.selected_folder = "none"
self.image_files = []
self.current_image_index = 0
self.history = []
self.history_index = -1
self.total_images = 0
self.togsess_counter = 0
self.togsess_mode = tk.BooleanVar(value=False)
self.session_active = False
self.session_index = 0
self.session_image_count = 0
self.main_frame = tk.Frame(self.root, bg=self.bgcolor)
self.main_frame.pack()
self.root.lift()
self.select_folder_button = tk.Button(self.main_frame, text="Select Folder", command=self.select_folder)
self.select_folder_button.configure(**self.button_red)
self.select_folder_button.pack(side=tk.LEFT, padx=5, pady=10)
ToolTip(self.select_folder_button, msg="Pick a folder", follow=True,
**self.tooltip_color)
self.set_timer_button = tk.Button(self.main_frame, text="Timer", command=self.set_timer_interval)
self.set_timer_button.configure(**self.button_style)
self.set_timer_button.pack(side=tk.LEFT, padx=5, pady=10)
ToolTip(self.set_timer_button, msg="Set timer interval", follow=True,
**self.tooltip_color)
self.start_button = tk.Button(self.main_frame, text="Start", command=self.start_pause_slideshow)
self.start_button.configure(**self.button_style_disabled)
self.start_button.pack(side=tk.LEFT, padx=5, pady=10)
ToolTip(self.start_button, msg="Start or pause timer", follow=True,
**self.tooltip_color)
#image canvas
self.canvas = tk.Canvas(self.root)
self.is_mirrored = False
self.is_greyscale = False
self.is_paused = True
self.rotated = 0
self.vol = True
self.beep1 = self.resource_path("beep1.wav")
self.beep2 = self.resource_path("beep2.wav")
self.ico = self.resource_path("icon.ico")
self.root.iconbitmap(self.ico)
self.grid_type="d"
self.timer_label = tk.Label(self.root, text="15", anchor="ne")
self.timer_label.configure(**self.timer_style)
self.timer_label.place(relx=1, anchor="ne", x=-0, y=0)
self.timer_interval = 15000 # Default time interval in milliseconds (15 seconds)
self.set_timer_interval = 15000 # Store the set timer interval
self.timer = None # Timer ID
self.window_size = (self.root.winfo_width(), self.root.winfo_height())
self.resize_timer = None
self.root.bind("<Right>", self.next_image)
self.root.bind("<Left>", self.previous_image)
self.root.bind("<space>", self.start_pause_slideshow)
self.root.bind("<Configure>", self.update_image_size)
def select_folder(self):
self.selected_folder = filedialog.askdirectory(initialdir=self.image_folder)
if not self.selected_folder or self.selected_folder == self.image_folder:
return
self.image_folder = self.selected_folder
if self.image_folder:
image_files = os.listdir(self.image_folder) # Get all files in the selected folder
self.image_files = [file for file in image_files if file.endswith(self.SUPPORTED_EXTENSIONS)]
self.history = []
self.history_index = -1
self.rotated = 0
self.togsess_counter = 0
self.total_images = len(self.image_files)
if self.image_files:
self.add_image_to_history()
self.current_image_index = 0
self.canvas.pack(fill=tk.BOTH, expand=True)
self.select_folder_button.pack(side=tk.LEFT, padx=5, pady=5)
self.root.title(f"IMGing in {self.image_folder} found {self.total_images} images")
self.canvas.config(bg=self.bgcolor, highlightthickness=0)
self.display_image()
self.start_button.config(**self.button_red)
self.openimgdir.configure(**self.button_style)
self.mirror_button.configure(**self.button_style)
self.greyscale_button.configure(**self.button_style)
self.rotate_button.configure(**self.button_style)
self.grid_button.configure(**self.button_style)
self.select_folder_button.configure(**self.button_style)
else:
messagebox.showinfo("No Image Files", "The selected folder does not contain any image files.")
self.image_folder = ""
self.root.title("IMG")
def add_image_to_history(self):
#code
def set_timer_interval(self):
dialog = CustomTimeDialog(self.root)
if dialog.result is not None:
self.session_active = dialog.togsess_mode.get() # Ensure you're accessing the toggled state from the dialog
if self.session_active:
# Session mode is active, dialog.result contains the list of session strings
self.process_session(dialog.result)
# Set the interval to the first session's time
self.timer_interval = self.current_session_list[0][1] * 1000
else:
# Session mode is inactive, dialog.result should be a numerical value
interval = dialog.result
if interval < 1: # Check if interval is less than 1 second
interval = 1
self.timer_interval = interval * 1000 # Convert to milliseconds
self.root.lift() # Bring the main window to the top
self.root.focus_force() # Give focus to the main window
minutes = self.timer_interval // 60000
seconds = (self.timer_interval % 60000) // 1000
if self.timer_interval <=59000:
self.timer_label.config(text=f"{seconds}")
else :
self.timer_label.config(text=f"{minutes:d}:{seconds:02d}")
def process_session(self, session_list):
self.current_session_list = []
for session_str in session_list:
try:
num_pics, time_str = session_str.split(' pics for ')
minutes, seconds = self.parse_time(time_str)
self.current_session_list.append((int(num_pics), minutes * 60 + seconds))
except ValueError as e:
# Handle the error appropriately, e.g., by logging or messaging the user
pass # Or whatever error handling you choose
def parse_time(self, time_str):
splits = time_str.split('m')
if len(splits) > 1:
minutes = int(splits[0])
seconds = int(splits[1].replace('s', ''))
else:
minutes = 0
seconds = int(time_str.replace('s', ''))
return minutes, seconds
def start_pause_slideshow(self, event=None):
if self.image_folder == "":
messagebox.showinfo("You haven't picked a folder", "Please select an image folder first.")
else:
if self.timer is None: # Check if timer is not running
self.display_image()
self.start_button.config(text="Pause", **self.button_style)
self.timer_label.configure(**self.timer_style)
self.is_paused = False # Set paused flag to False
self.start_timer()
else:
if self.is_paused: # Check if the slideshow is paused
self.start_button.config(text="Pause", **self.button_style)
self.timer_label.configure(**self.timer_style)
self.is_paused = False # Set paused flag to False
self.start_timer()
else:
self.pause_timer()
self.start_button.config(text="Start", **self.button_red)
self.timer_label.configure(bg="green")
self.is_paused = True # Set paused flag to True
def pause_timer(self):
if self.timer is not None:
self.root.after_cancel(self.timer)
self.timer = None
if self.session_active:
self.session_index = 0
self.session_image_count = self.current_session_list[0][0]
self.timer_interval = self.current_session_list[0][1] * 1000
def start_timer(self):
if self.image_folder != "" and not self.is_paused:
self.update_timer()
self.timer = self.root.after(1000, self.start_timer)
def update_timer(self):
# Calculate minutes and seconds left
minutes = self.timer_interval // 60000
seconds = (self.timer_interval % 60000) // 1000
if self.timer_interval <=59000:
self.timer_label.config(text=f"{seconds}")
else :
self.timer_label.config(text=f"{minutes:d}:{seconds:02d}")
if self.vol:
if self.timer_interval == 3000:
wave_obj = sa.WaveObject.from_wave_file(self.beep1)
play_obj = wave_obj.play()
play_obj.wait_done()
if self.timer_interval == 2000:
wave_obj = sa.WaveObject.from_wave_file(self.beep1)
play_obj = wave_obj.play()
play_obj.wait_done()
if self.timer_interval == 1000:
wave_obj = sa.WaveObject.from_wave_file(self.beep1)
play_obj = wave_obj.play()
play_obj.wait_done()
if self.timer_interval == 0:
wave_obj = sa.WaveObject.from_wave_file(self.beep2)
play_obj = wave_obj.play()
play_obj.wait_done()
self.timer_interval -= 1000
if self.timer_interval < 0:
self.timer_interval = self.set_timer_interval # Use the stored set timer interval
self.next_image()
def load_image_delayed(self):
# This method will be called after the 500ms delay if no keypress happens
if self.timer is not None:
self.root.after_cancel(self.timer) # Cancel the existing timer
self.timer = None # Clear the timer ID
# Load the current image from history without changing to a new random image
image_path = os.path.join(self.image_folder, self.history[self.history_index])
threading.Thread(target=self.load_image, args=(image_path,)).start()
if not self.is_paused:
self.timer = self.set_timer_interval
self.root.after(500, self.start_timer)
def next_image(self, event=None):
if self.image_folder != "":
if len(self.image_files) == len(self.history):
self.history_index = (self.history_index + 1) % len(self.image_files)
else:
self.add_image_to_history()
self.display_image()
# Reset the timer interval to the stored set timer interval
self.timer_interval = self.set_timer_interval
if self.session_active:
self.session_image_count -= 1
if self.session_image_count <= 0:
self.session_index = (self.session_index + 1) % len(self.current_session_list)
self.session_image_count, interval = self.current_session_list[self.session_index]
self.timer_interval = interval * 1000 # Setting the new interval from session
else:
self.timer_interval = self.set_timer_interval
else:
self.timer_interval = self.set_timer_interval
def previous_image(self, event=None):
if self.image_folder != "" and self.history_index > 0:
self.history_index -= 1
self.display_image()
# When session is active, control the flow based on session settings
if self.session_active:
current_count, _ = self.current_session_list[self.session_index]
# Move to the previous session step, if it's the first image in the current session step
if self.session_image_count == current_count:
if self.session_index > 0:
self.session_index -= 1
else:
self.session_index = len(self.current_session_list) - 1
_, interval = self.current_session_list[self.session_index]
self.session_image_count = self.current_session_list[self.session_index][0]
self.timer_interval = interval * 1000
else:
self.session_image_count += 1
_, interval = self.current_session_list[self.session_index]
self.timer_interval = interval * 1000
else:
# For regular (non-session) mode, simply reset the timer interval
self.timer_interval = self.set_timer_interval
i want when i activate session mode and set the timer to use the session, and i open the timer again, i want it to save or acknowledge the previous setting in the session list and session checkbox instead of resetting the timer on opening the timer window.
when there's something to be changed, give the new codeblock and show me precisely where i can put the codeblock. if something needs to be added, tell me concisely.
|
b2d37f077657a6dbd7da437df63dd702
|
{
"intermediate": 0.23969003558158875,
"beginner": 0.5163114070892334,
"expert": 0.24399852752685547
}
|
38,175
|
are those the same person?
Person 1
{
"address": "100 Diversy Wy, Chicago, IL 60061",
"name":{"first_name":"John",middle_name:"M",last_name:"Togo",suffix:""},
"ssn":"123-12-1234"
}
Experian
{
"address": "123 Chicago Way, Chicago IL 60061",
"name":{"first_name":"Jhn",middle_name:"Moe",last_name:"Togo",suffix:""},
"ssn":"123121234"
}
|
51f2dc6264b5870a71f8a77828e26223
|
{
"intermediate": 0.4253038465976715,
"beginner": 0.26053452491760254,
"expert": 0.31416162848472595
}
|
38,176
|
write python3 code for knowledge distillation for object detection?
|
6d2bc43f2266a966dbe0c76ccdb7a13e
|
{
"intermediate": 0.3685031831264496,
"beginner": 0.14301615953445435,
"expert": 0.48848068714141846
}
|
38,177
|
pleop
|
5704b340d4659380d7958dd0bc73f038
|
{
"intermediate": 0.334991991519928,
"beginner": 0.3019070029258728,
"expert": 0.36310097575187683
}
|
38,178
|
can you code me a swift project that has a siri like ui but instead its chatgpt, then when you say "hey gpt" it will start listening and answer questions
|
2424e7f1e49dc8ef27bca05f9e84d47c
|
{
"intermediate": 0.532252848148346,
"beginner": 0.1480126529932022,
"expert": 0.3197345435619354
}
|
38,179
|
class CustomTimeDialog(simpledialog.Dialog):
def __init__(self, parent, current_session_timings=None, is_session_mode=False, **kwargs):
self.current_session_timings = current_session_timings if current_session_timings else []
self.is_session_mode = is_session_mode
super().__init__(parent, **kwargs)
def body(self, master):
self.timebutton_style = {"font": ("consolas", 11),
"fg": "white", "bg": "#3c3c3c", "relief": "flat"}
self.title('Custom Time')
self.time_background = "#242424"
self.time_fg="white"
master.configure(bg=self.time_background)
self.configure(bg=self.time_background)
self.ico = self.resource_path_timer("icon.ico")
self.iconbitmap(self.ico)
#timebox--------------------------------------------------
ctime_frame = tk.Frame(master, bg=self.time_background)
ctime_frame.grid(row=1, column=1)
self.timebox = tk.Listbox(ctime_frame, height=6, width=15,
font=self.timebutton_style["font"],
bg=self.timebutton_style["bg"], fg="#dddddd",
selectbackground="#222222")
for time_string in ['15s', '30s', '45s', '1m', '5m', '10m']:
self.timebox.insert(tk.END, time_string)
self.timebox.grid(row=1, column=1)
self.timebox.bind('<<ListboxSelect>>', self.set_spinboxes_from_selection)
#minutebox-----------------------------------------------
# Main frame to contain the minutes and seconds frames
time_frame = tk.Frame(ctime_frame, bg=self.time_background)
time_frame.grid(row=2, column=1, pady=5)# side=tk.TOP, fill=tk.X, padx=5, pady=5)
# Create a frame for the minutes spinbox and label
minutes_frame = tk.Frame(time_frame, bg=self.time_background)
minutes_frame.pack(side=tk.LEFT, fill=tk.X)#, padx=5)
tk.Label(minutes_frame, text="Minutes:",
bg=self.time_background, fg=self.time_fg,
font=self.timebutton_style["font"]).pack(side=tk.TOP)
self.spin_minutes = tk.Spinbox(minutes_frame, from_=0, to=59, width=5, font=self.timebutton_style["font"])
self.spin_minutes.pack(side=tk.TOP)
# Create a frame for the seconds spinbox and label
seconds_frame = tk.Frame(time_frame, bg=self.time_background)
seconds_frame.pack(side=tk.LEFT, fill=tk.X, padx=5)
tk.Label(seconds_frame, text="Seconds:", bg=self.time_background, fg=self.time_fg, font=self.timebutton_style["font"]).pack(side=tk.TOP)
self.spin_seconds = tk.Spinbox(seconds_frame, from_=0, to=59, value=15, width=5, font=self.timebutton_style["font"], wrap=True)
self.spin_seconds.pack(side=tk.TOP)
#togsessbox-------------------------------------------------
session = tk.LabelFrame(master, fg=self.timebutton_style["fg"], bg=self.time_background, relief=tk.FLAT)#, text="Sessions"
session.grid(row=1, column=2)
#togsessbox = tk.Frame(master, bg=self.time_background)
togsess_frame = tk.Frame(session, bg=self.time_background)
togsess_frame.grid (row=3,column=1, pady=5)
self.togsess_mode = tk.BooleanVar(value=False)
#self.togsess_frame = tk.Checkbutton(togsess_frame, bg=self.time_background)
self.togsess_checkbox = tk.Checkbutton(togsess_frame, text="Session",
variable=self.togsess_mode, command=self.toggle_togsess)
self.togsess_checkbox.configure(**self.timebutton_style, bd=0)
self.togsess_checkbox.grid(row=1, column=1, sticky=tk.E, ipadx=12)
self.img_togsess = tk.Spinbox(togsess_frame, width=3, from_=0, to=100,
font=self.timebutton_style["font"], wrap=True, x=500, value=5, state = 'disabled')
self.img_togsess.grid(row=1, column=2)
#sessionsbox-----------------------------------------------------------
self.sessionlist = ['5 pics for 30s', '5 pics for 1m', '5 pics for 5m']
self.sessionString = tk.StringVar(value=self.sessionlist)
self.sessionbox = tk.Listbox(session, height=6, width=18,
font=self.timebutton_style["font"], bg=self.timebutton_style["bg"],
listvariable=self.sessionString, borderwidth=0, state = 'disabled',
fg="#dddddd", selectbackground="#222222")#, fg=self.timebutton_style["fg"])
self.sessionbox.grid(row=1, column=1)
#session buttons frame------------------------------------------------------------------
sessionbuttons = tk.Frame(session, bg=self.time_background)
sessionbuttons.grid(row=2, column=1)
self.add_button = tk.Button(sessionbuttons, text="+", width=3,
command=self.add_session, default=tk.ACTIVE, state="disabled")
self.add_button.config(**self.timebutton_style)
self.add_button.grid(row=1, column=1)
self.del_button = tk.Button(sessionbuttons, text="-", width=3,
command=self.remove_session, default=tk.ACTIVE, state="disabled")
self.del_button.config(**self.timebutton_style)
self.del_button.grid(row=1, column=2, padx=(0,10))
self.up_button = tk.Button(sessionbuttons, text="Ʌ", width=3,
command=lambda: self.move(-1), default=tk.ACTIVE, state="disabled")
self.up_button.config(**self.timebutton_style)
self.up_button.grid(row=1, column=3)
self.down_button = tk.Button(sessionbuttons, text="V", width=3,
command=lambda: self.move(1), default=tk.ACTIVE, state="disabled")
self.down_button.config(**self.timebutton_style)
self.down_button.grid(row=1, column=4)
self.togsess_mode.set(self.is_session_mode)
if self.is_session_mode:
self.toggle_togsess() # Initialize the state of session elements based on current setting
# Update the Listbox content with the current session timings:
self.sessionString.set(self.current_session_timings)
self.sessionlist = list(self.current_session_timings)
return self.spin_seconds # initial focus
def add_session(self):
try:
img_togsess_value = int(self.img_togsess.get() or 0)
except ValueError:
img_togsess_value = 0
try:
minutes_input = int(self.spin_minutes.get() or 0)
except ValueError:
minutes_input = 0
try:
seconds_input = int(self.spin_seconds.get() or 0)
except ValueError:
seconds_input = 0
# Convert total seconds to minutes and seconds
minutes, seconds = divmod(minutes_input * 60 + seconds_input, 60)
# Format the session string based on the minutes and seconds
if minutes > 0 and seconds == 0:
session_str = f"{img_togsess_value} pics for {minutes}m"
elif minutes == 0 and seconds > 0:
session_str = f"{img_togsess_value} pics for {seconds}s"
elif minutes > 0 and seconds > 0:
session_str = f"{img_togsess_value} pics for {minutes}m {seconds}s"
else:
# If both minutes and seconds are missing or 0, use 0s in the string
session_str = f"{img_togsess_value} pics for 0s"
# Append session string to the session list
self.sessionlist.append(session_str)
# Update the session string representation
self.sessionString.set(self.sessionlist)
# Select the newly added session in the session box
self.sessionbox.selection_set(len(self.sessionlist) - 1)
def remove_session(self):
selected_index = self.sessionbox.curselection()
if not selected_index:
return
selected_index = selected_index[0]
self.sessionlist.pop(selected_index)
self.sessionString.set(self.sessionlist)
if selected_index < len(self.sessionlist):
self.sessionbox.selection_set(selected_index)
elif len(self.sessionlist) > 0:
self.sessionbox.selection_set(len(self.sessionlist) - 1)
def move(self, num):
#num is -1 for up and 1 for down
self.idxs = self.sessionbox.curselection()
if not self.idxs:
return
for pos in self.idxs:
text=self.sessionbox.get(pos) #gets text
self.sessionbox.delete(pos) #removes text from list box
self.sessionlist.pop(pos) #removes text from list
if pos==len(self.sessionlist) and num==1: pos=-1; #sets at beginning if at bottom and going down
if pos==0 and num==-1: pos=len(self.sessionlist)+1; #sets at end if at top and going up
self.sessionbox.insert(pos+num, text) #inserts into list box
self.sessionlist.insert(pos+num, text) #inserts into list
self.sessionbox.selection_set(pos+num)
def toggle_togsess(self):
if self.togsess_mode.get():
self.togsess_checkbox.configure(fg="#2c2c2c", bg="#b8b8b8")
self.img_togsess.config(state = 'normal')
self.sessionbox.config (state = 'normal')
self.add_button.config (state = 'normal')
self.del_button.config (state = 'normal')
self.up_button.config (state = 'normal')
self.down_button.config(state = 'normal')
else:
self.togsess_checkbox.configure(**self.timebutton_style)
self.img_togsess.config(state = 'disabled')
self.sessionbox.config (state = 'disabled')
self.add_button.config (state = 'disabled')
self.del_button.config (state = 'disabled')
self.up_button.config (state = 'disabled')
self.down_button.config(state = 'disabled')
def set_spinboxes_from_selection(self, event=None):
index = self.timebox.curselection()
if not index:
return
time_string = self.timebox.get(index)
if 'm' in time_string:
minutes = int(time_string.replace('m', ''))
seconds = 0
elif 's' in time_string:
minutes = 0
seconds = int(time_string.replace('s', ''))
else:
# Handle a possible unknown format
self.bell() # ring the bell to signal an error
return
self.spin_minutes.delete(0, tk.END)
self.spin_minutes.insert(0, minutes)
self.spin_seconds.delete(0, tk.END)
self.spin_seconds.insert(0, seconds)
def buttonbox(self):
box = tk.Frame(self, bg=self.time_background)
self.ok_button = tk.Button(box, text="Apply", width=16, command=self.ok, default=tk.ACTIVE)
self.ok_button.config(**self.timebutton_style)
self.ok_button.pack(side=tk.TOP, ipadx=5, pady=5)
box.pack()
def apply(self):
if self.togsess_mode.get():
# In session mode, store the list of session strings directly
self.result = self.sessionlist # Use the list directly instead of self.sessionString.get()
else:
# In standard mode, parse and combine minutes and seconds to a single interval in seconds
try:
minutes = int(self.spin_minutes.get())
seconds = int(self.spin_seconds.get())
self.result = minutes * 60 + seconds # Total time in seconds
except ValueError:
# Fall back to a default interval as needed
self.result = 1 # Default to 1 second
def validate(self):
try:
minutes = int(self.spin_minutes.get())
seconds = int(self.spin_seconds.get())
return True
except ValueError:
self.bell()
return False
class ImageViewer:
def __init__(self, root):
self.SUPPORTED_EXTENSIONS = (".png", ".jpg", ".jpeg", ".gif", ".bmp", ".JPG", ".JPEG", ".BMP", ".GIF", ".webp", ".WEBP")
self.button_style = {"font": ("consolas", 11), "fg": "white", "bg": "#3c3c3c", "relief": "flat"}
self.button_red = {"font": ("consolas", 11), "fg": "white", "bg": "green", "relief": "flat"}
self.button_style_disabled = {"font": ("consolas", 11), "fg": "#505050", "bg": "#909090", "relief": "flat"}
self.timer_style = {"font": ("consolas", 22), "fg": "white", "bg": "#3c3c3c", "relief": "flat"}
self.tooltip_color = {"fg": "#ffffff", "bg": "#1c1c1c"}
self.bgcolor = "#242424"
self.button_width = 3
#self.image_loading_queue = Queue(maxsize=5)
self.switch_timestamps = []
self.root = root
self.root.geometry("800x600") # Initial window size
self.root.title("Jestur Viewer")
self.root.configure(bg=self.bgcolor) # Set window background color
self.root.attributes("-topmost", False) # Make the window stay on top
self.image_folder = ""
self.selected_folder = "none"
self.image_files = []
self.current_image_index = 0
self.history = []
self.history_index = -1
self.total_images = 0
self.togsess_counter = 0
self.togsess_mode = tk.BooleanVar(value=False)
self.session_active = False
self.session_index = 0
self.session_image_count = 0
self.current_session_timings = []
self.is_session_mode = False
self.main_frame = tk.Frame(self.root, bg=self.bgcolor)
self.main_frame.pack()
self.root.lift()
self.select_folder_button = tk.Button(self.main_frame, text="Select Folder", command=self.select_folder)
self.select_folder_button.configure(**self.button_red)
self.select_folder_button.pack(side=tk.LEFT, padx=5, pady=10)
ToolTip(self.select_folder_button, msg="Pick a folder", follow=True,
**self.tooltip_color)
self.set_timer_button = tk.Button(self.main_frame, text="Timer", command=self.set_timer_interval)
self.set_timer_button.configure(**self.button_style)
self.set_timer_button.pack(side=tk.LEFT, padx=5, pady=10)
ToolTip(self.set_timer_button, msg="Set timer interval", follow=True,
**self.tooltip_color)
self.start_button = tk.Button(self.main_frame, text="Start", command=self.start_pause_slideshow)
self.start_button.configure(**self.button_style_disabled)
self.start_button.pack(side=tk.LEFT, padx=5, pady=10)
ToolTip(self.start_button, msg="Start or pause timer", follow=True,
**self.tooltip_color)
#image canvas
self.canvas = tk.Canvas(self.root)
self.is_mirrored = False
self.is_greyscale = False
self.is_paused = True
self.rotated = 0
self.vol = True
self.beep1 = self.resource_path("beep1.wav")
self.beep2 = self.resource_path("beep2.wav")
self.ico = self.resource_path("icon.ico")
self.root.iconbitmap(self.ico)
self.grid_type="d"
self.timer_label = tk.Label(self.root, text="15", anchor="ne")
self.timer_label.configure(**self.timer_style)
self.timer_label.place(relx=1, anchor="ne", x=-0, y=0)
self.timer_interval = 15000 # Default time interval in milliseconds (15 seconds)
self.set_timer_interval = 15000 # Store the set timer interval
self.timer = None # Timer ID
self.window_size = (self.root.winfo_width(), self.root.winfo_height())
self.resize_timer = None
self.root.bind("<Right>", self.next_image)
self.root.bind("<Left>", self.previous_image)
self.root.bind("<space>", self.start_pause_slideshow)
self.root.bind("<Configure>", self.update_image_size)
def next_image(self, event=None):
if self.image_folder != "":
if len(self.image_files) == len(self.history):
self.history_index = (self.history_index + 1) % len(self.image_files)
else:
self.add_image_to_history()
self.display_image()
# Reset the timer interval to the stored set timer interval
self.timer_interval = self.set_timer_interval
if self.session_active:
self.session_image_count -= 1
if self.session_image_count <= 0:
self.session_index = (self.session_index + 1) % len(self.current_session_list)
self.session_image_count, interval = self.current_session_list[self.session_index]
self.timer_interval = interval * 1000 # Setting the new interval from session
else:
self.timer_interval = self.set_timer_interval
else:
self.timer_interval = self.set_timer_interval
def previous_image(self, event=None):
if self.image_folder != "" and self.history_index > 0:
self.history_index -= 1
self.display_image()
# When session is active, control the flow based on session settings
if self.session_active:
current_count, _ = self.current_session_list[self.session_index]
# Move to the previous session step, if it's the first image in the current session step
if self.session_image_count == current_count:
if self.session_index > 0:
self.session_index -= 1
else:
self.session_index = len(self.current_session_list) - 1
_, interval = self.current_session_list[self.session_index]
self.session_image_count = self.current_session_list[self.session_index][0]
self.timer_interval = interval * 1000
else:
self.session_image_count += 1
_, interval = self.current_session_list[self.session_index]
self.timer_interval = interval * 1000
else:
# For regular (non-session) mode, simply reset the timer interval
self.timer_interval = self.set_timer_interval
def set_timer_interval(self):
if not hasattr(self, 'current_session_timings'): # Make sure the properties exist
self.current_session_timings = []
self.is_session_mode = False
# Pass the current session settings to the dialog
dialog = CustomTimeDialog(self.root, self.current_session_timings, self.is_session_mode)
if dialog.result is not None:
self.is_session_mode = dialog.togsess_mode.get() # Store the new session mode
if self.is_session_mode:
self.current_session_timings = dialog.result # Store the session settings
# Session mode is active, dialog.result contains the list of session strings
self.process_session(dialog.result)
# Set the interval to the first session's time
self.timer_interval = self.current_session_list[0][1] * 1000
else:
# Session mode is inactive, dialog.result should be a numerical value
interval = dialog.result
if interval < 1: # Check if interval is less than 1 second
interval = 1
self.timer_interval = interval * 1000 # Convert to milliseconds
self.root.lift() # Bring the main window to the top
self.root.focus_force() # Give focus to the main window
minutes = self.timer_interval // 60000
seconds = (self.timer_interval % 60000) // 1000
if self.timer_interval <=59000:
self.timer_label.config(text=f"{seconds}")
else :
self.timer_label.config(text=f"{minutes:d}:{seconds:02d}")
def process_session(self, session_list):
self.current_session_list = []
for session_str in session_list:
try:
num_pics, time_str = session_str.split(' pics for ')
minutes, seconds = self.parse_time(time_str)
self.current_session_list.append((int(num_pics), minutes * 60 + seconds))
except ValueError as e:
# Handle the error appropriately, e.g., by logging or messaging the user
pass # Or whatever error handling you choose
def parse_time(self, time_str):
splits = time_str.split('m')
if len(splits) > 1:
minutes = int(splits[0])
seconds = int(splits[1].replace('s', ''))
else:
minutes = 0
seconds = int(time_str.replace('s', ''))
return minutes, seconds
def start_pause_slideshow(self, event=None):
if self.image_folder == "":
messagebox.showinfo("You haven't picked a folder", "Please select an image folder first.")
else:
if self.timer is None: # Check if timer is not running
self.display_image()
self.start_button.config(text="Pause", **self.button_style)
self.timer_label.configure(**self.timer_style)
self.is_paused = False # Set paused flag to False
self.start_timer()
else:
if self.is_paused: # Check if the slideshow is paused
self.start_button.config(text="Pause", **self.button_style)
self.timer_label.configure(**self.timer_style)
self.is_paused = False # Set paused flag to False
self.start_timer()
else:
self.pause_timer()
self.start_button.config(text="Start", **self.button_red)
self.timer_label.configure(bg="green")
self.is_paused = True # Set paused flag to True
def pause_timer(self):
if self.timer is not None:
self.root.after_cancel(self.timer)
self.timer = None
if self.session_active:
self.session_index = 0
self.session_image_count = self.current_session_list[0][0]
self.timer_interval = self.current_session_list[0][1] * 1000
def start_timer(self):
if self.image_folder != "" and not self.is_paused:
self.update_timer()
self.timer = self.root.after(1000, self.start_timer)
def update_timer(self):
# Calculate minutes and seconds left
minutes = self.timer_interval // 60000
seconds = (self.timer_interval % 60000) // 1000
if self.timer_interval <=59000:
self.timer_label.config(text=f"{seconds}")
else :
self.timer_label.config(text=f"{minutes:d}:{seconds:02d}")
if self.vol:
if self.timer_interval == 3000:
wave_obj = sa.WaveObject.from_wave_file(self.beep1)
play_obj = wave_obj.play()
play_obj.wait_done()
if self.timer_interval == 2000:
wave_obj = sa.WaveObject.from_wave_file(self.beep1)
play_obj = wave_obj.play()
play_obj.wait_done()
if self.timer_interval == 1000:
wave_obj = sa.WaveObject.from_wave_file(self.beep1)
play_obj = wave_obj.play()
play_obj.wait_done()
if self.timer_interval == 0:
wave_obj = sa.WaveObject.from_wave_file(self.beep2)
play_obj = wave_obj.play()
play_obj.wait_done()
self.timer_interval -= 1000
if self.timer_interval < 0:
self.timer_interval = self.set_timer_interval # Use the stored set timer interval
self.next_image()
can the sessionlist value is overriden to be empty when i open the timer for the first time. i want a default initial list when i open the timer window for the first time only, that won't replace the session times that i set after on the consecutive opening of timer window
when there's something to be changed, give the new codeblock and show me precisely where i can put the codeblock. if something needs to be added, tell me concisely.
|
8b93352cad7d1ca04b4d331d69fc50e1
|
{
"intermediate": 0.2457146793603897,
"beginner": 0.5542082786560059,
"expert": 0.20007707178592682
}
|
38,180
|
Item #: SCP-085
Object Class: Safe
Interview Log Format:
| Date: | [Date of Interview] |
|-------|---------------------|
| Interviewer: | Dr. [REDACTED] |
—
Begin Log
Dr. [REDACTED]: Good [morning/afternoon/evening], Cassy. How are you feeling today?
[SCP-085 draws a smiley face and writes “Good!” below it.]
Dr. [REDACTED]: We’ve noticed that you did particularly well during the audio-visual tests. Can you tell us about your experience with them?
[SCP-085 sketches a small figure resembling herself sitting and studying the sine wave diagrams, then gives a thumbs-up sign. Adjacent to the figure, she writes “Interesting! Learned lots.”]
Dr. [REDACTED]: That’s excellent to hear, Cassy. Now, do you feel that you understand the concept of sound even though you can’t hear it?
[SCP-085 nods and writes, “Yes, visuals help. Sound waves = Vibes? Patterns are cool!” She draws a series of waves with different amplitudes and frequencies next to her writing.]
Dr. [REDACTED]: Correct, sound can be thought of as vibrations, and the patterns certainly are quite fascinating. Do you have any preferences for additional tests or anything new you’d like to try?
[SCP-085 tilts her head as if thinking and then writes, “Light? Colors are like sound waves?” It seems she is drawing a parallel between sound and light spectra.]
Dr. [REDACTED]: A very astute observation. We could explore the visual spectrum and its properties similar to our sound wave tests. For now, though, could you create a spectrogram of something you would like to communicate to us?
[SCP-085 busies herself with drawing. She produces a detailed spectrogram-like representation. Alongside, she writes, “Stay curious!” The care she takes in illustrating the letters reflects a sentiment akin to her surprisingly complex understanding of sound for a being who experiences the world in silence.]
Dr. [REDACTED]: “Stay curious”—a wonderful message, thank you. Your contributions to our understanding of cross-modality perception are invaluable, Cassy.
[SCP-085 writes, “Happy to help!” before sketching a beaming sun, seemingly content with the session.]
Dr. [REDACTED]: We’ll conclude today’s interview here. Thank you again, Cassy. We’ll continue our sessions soon, and I look forward to exploring the concept of light with you.
[SCP-085 gives a wave on the paper, signaling her understanding of the session’s end.]
End Log
|
d12596e29d437428d9717844816df2a2
|
{
"intermediate": 0.3128155767917633,
"beginner": 0.4132295846939087,
"expert": 0.273954838514328
}
|
38,181
|
class CustomTimeDialog(simpledialog.Dialog):
def __init__(self, parent, current_session_timings=None, is_session_mode=False, **kwargs):
# Only set defaults if current_session_timings is None or empty
if not current_session_timings: # This checks both None and empty list [] conditions
# Set default initial list here (only if there are no existing session timings)
current_session_timings = ['2 pics for 2s', '1 pics for 1s', '3 pics for 1s']
self.current_session_timings = current_session_timings
self.is_session_mode = is_session_mode
super().__init__(parent, **kwargs)
def body(self, master):
self.timebutton_style = {"font": ("consolas", 11),
"fg": "white", "bg": "#3c3c3c", "relief": "flat"}
self.title('Custom Time')
self.time_background = "#242424"
self.time_fg="white"
master.configure(bg=self.time_background)
self.configure(bg=self.time_background)
self.ico = self.resource_path_timer("icon.ico")
self.iconbitmap(self.ico)
#timebox--------------------------------------------------
ctime_frame = tk.Frame(master, bg=self.time_background)
ctime_frame.grid(row=1, column=1)
self.timebox = tk.Listbox(ctime_frame, height=6, width=15,
font=self.timebutton_style["font"],
bg=self.timebutton_style["bg"], fg="#dddddd",
selectbackground="#222222")
for time_string in ['15s', '30s', '45s', '1m', '5m', '10m']:
self.timebox.insert(tk.END, time_string)
self.timebox.grid(row=1, column=1)
self.timebox.bind('<<ListboxSelect>>', self.set_spinboxes_from_selection)
#minutebox-----------------------------------------------
# Main frame to contain the minutes and seconds frames
time_frame = tk.Frame(ctime_frame, bg=self.time_background)
time_frame.grid(row=2, column=1, pady=5)# side=tk.TOP, fill=tk.X, padx=5, pady=5)
# Create a frame for the minutes spinbox and label
minutes_frame = tk.Frame(time_frame, bg=self.time_background)
minutes_frame.pack(side=tk.LEFT, fill=tk.X)#, padx=5)
tk.Label(minutes_frame, text="Minutes:",
bg=self.time_background, fg=self.time_fg,
font=self.timebutton_style["font"]).pack(side=tk.TOP)
self.spin_minutes = tk.Spinbox(minutes_frame, from_=0, to=59, width=5, font=self.timebutton_style["font"])
self.spin_minutes.pack(side=tk.TOP)
# Create a frame for the seconds spinbox and label
seconds_frame = tk.Frame(time_frame, bg=self.time_background)
seconds_frame.pack(side=tk.LEFT, fill=tk.X, padx=5)
tk.Label(seconds_frame, text="Seconds:", bg=self.time_background,
fg=self.time_fg, font=self.timebutton_style["font"]).pack(side=tk.TOP)
self.spin_seconds = tk.Spinbox(seconds_frame, from_=0, to=59, value=15,
width=5, font=self.timebutton_style["font"], wrap=True)
self.spin_seconds.pack(side=tk.TOP)
#togsessbox-------------------------------------------------
session = tk.LabelFrame(master, fg=self.timebutton_style["fg"], bg=self.time_background, relief=tk.FLAT)#, text="Sessions"
session.grid(row=1, column=2)
#togsessbox = tk.Frame(master, bg=self.time_background)
togsess_frame = tk.Frame(session, bg=self.time_background)
togsess_frame.grid (row=3,column=1, pady=5)
self.togsess_mode = tk.BooleanVar(value=False)
#self.togsess_frame = tk.Checkbutton(togsess_frame, bg=self.time_background)
self.togsess_checkbox = tk.Checkbutton(togsess_frame, text="Session",
variable=self.togsess_mode, command=self.toggle_togsess)
self.togsess_checkbox.configure(**self.timebutton_style, bd=0)
self.togsess_checkbox.grid(row=1, column=1, sticky=tk.E, ipadx=12)
self.img_togsess = tk.Spinbox(togsess_frame, width=3, from_=0, to=100,
font=self.timebutton_style["font"], wrap=True, x=500, value=5, state = 'disabled')
self.img_togsess.grid(row=1, column=2)
#sessionsbox-----------------------------------------------------------
self.sessionlist = []
self.sessionString = tk.StringVar(value=self.sessionlist)
self.sessionbox = tk.Listbox(session, height=6, width=18,
font=self.timebutton_style["font"], bg=self.timebutton_style["bg"],
listvariable=self.sessionString, borderwidth=0, state = 'disabled',
fg="#dddddd", selectbackground="#222222")#, fg=self.timebutton_style["fg"])
self.sessionbox.grid(row=1, column=1)
#session buttons frame------------------------------------------------------------------
sessionbuttons = tk.Frame(session, bg=self.time_background)
sessionbuttons.grid(row=2, column=1)
self.add_button = tk.Button(sessionbuttons, text="+", width=3,
command=self.add_session, default=tk.ACTIVE, state="disabled")
self.add_button.config(**self.timebutton_style)
self.add_button.grid(row=1, column=1)
self.del_button = tk.Button(sessionbuttons, text="-", width=3,
command=self.remove_session, default=tk.ACTIVE, state="disabled")
self.del_button.config(**self.timebutton_style)
self.del_button.grid(row=1, column=2, padx=(0,10))
self.up_button = tk.Button(sessionbuttons, text="Ʌ", width=3,
command=lambda: self.move(-1), default=tk.ACTIVE, state="disabled")
self.up_button.config(**self.timebutton_style)
self.up_button.grid(row=1, column=3)
self.down_button = tk.Button(sessionbuttons, text="V", width=3,
command=lambda: self.move(1), default=tk.ACTIVE, state="disabled")
self.down_button.config(**self.timebutton_style)
self.down_button.grid(row=1, column=4)
self.togsess_mode.set(self.is_session_mode)
if self.is_session_mode:
self.toggle_togsess() # Initialize the state of session elements based on current setting
# Update the Listbox content with the current session timings:
self.sessionString.set(self.current_session_timings)
self.sessionlist = list(self.current_session_timings)
return self.spin_seconds # initial focus
def add_session(self):
try:
img_togsess_value = int(self.img_togsess.get() or 0)
except ValueError:
img_togsess_value = 0
try:
minutes_input = int(self.spin_minutes.get() or 0)
except ValueError:
minutes_input = 0
try:
seconds_input = int(self.spin_seconds.get() or 0)
except ValueError:
seconds_input = 0
# Convert total seconds to minutes and seconds
minutes, seconds = divmod(minutes_input * 60 + seconds_input, 60)
# Format the session string based on the minutes and seconds
if minutes > 0 and seconds == 0:
session_str = f"{img_togsess_value} pics for {minutes}m"
elif minutes == 0 and seconds > 0:
session_str = f"{img_togsess_value} pics for {seconds}s"
elif minutes > 0 and seconds > 0:
session_str = f"{img_togsess_value} pics for {minutes}m {seconds}s"
else:
# If both minutes and seconds are missing or 0, use 0s in the string
session_str = f"{img_togsess_value} pics for 0s"
# Append session string to the session list
self.sessionlist.append(session_str)
# Update the session string representation
self.sessionString.set(self.sessionlist)
# Select the newly added session in the session box
self.sessionbox.selection_set(len(self.sessionlist) - 1)
def remove_session(self):
selected_index = self.sessionbox.curselection()
if not selected_index:
return
selected_index = selected_index[0]
self.sessionlist.pop(selected_index)
self.sessionString.set(self.sessionlist)
if selected_index < len(self.sessionlist):
self.sessionbox.selection_set(selected_index)
elif len(self.sessionlist) > 0:
self.sessionbox.selection_set(len(self.sessionlist) - 1)
def move(self, num):
#num is -1 for up and 1 for down
self.idxs = self.sessionbox.curselection()
if not self.idxs:
return
for pos in self.idxs:
text=self.sessionbox.get(pos) #gets text
self.sessionbox.delete(pos) #removes text from list box
self.sessionlist.pop(pos) #removes text from list
if pos==len(self.sessionlist) and num==1: pos=-1; #sets at beginning if at bottom and going down
if pos==0 and num==-1: pos=len(self.sessionlist)+1; #sets at end if at top and going up
self.sessionbox.insert(pos+num, text) #inserts into list box
self.sessionlist.insert(pos+num, text) #inserts into list
self.sessionbox.selection_set(pos+num)
def toggle_togsess(self):
if self.togsess_mode.get():
self.togsess_checkbox.configure(fg="#2c2c2c", bg="#b8b8b8")
self.img_togsess.config(state = 'normal')
self.sessionbox.config (state = 'normal')
self.add_button.config (state = 'normal')
self.del_button.config (state = 'normal')
self.up_button.config (state = 'normal')
self.down_button.config(state = 'normal')
else:
self.togsess_checkbox.configure(**self.timebutton_style)
self.img_togsess.config(state = 'disabled')
self.sessionbox.config (state = 'disabled')
self.add_button.config (state = 'disabled')
self.del_button.config (state = 'disabled')
self.up_button.config (state = 'disabled')
self.down_button.config(state = 'disabled')
def set_spinboxes_from_selection(self, event=None):
index = self.timebox.curselection()
if not index:
return
time_string = self.timebox.get(index)
if 'm' in time_string:
minutes = int(time_string.replace('m', ''))
seconds = 0
elif 's' in time_string:
minutes = 0
seconds = int(time_string.replace('s', ''))
else:
# Handle a possible unknown format
self.bell() # ring the bell to signal an error
return
self.spin_minutes.delete(0, tk.END)
self.spin_minutes.insert(0, minutes)
self.spin_seconds.delete(0, tk.END)
self.spin_seconds.insert(0, seconds)
def buttonbox(self):
box = tk.Frame(self, bg=self.time_background)
self.ok_button = tk.Button(box, text="Apply", width=16, command=self.ok, default=tk.ACTIVE)
self.ok_button.config(**self.timebutton_style)
self.ok_button.pack(side=tk.TOP, ipadx=5, pady=5)
box.pack()
def apply(self):
if self.togsess_mode.get():
# In session mode, store the list of session strings directly
self.result = self.sessionlist # Use the list directly instead of self.sessionString.get()
else:
# In standard mode, parse and combine minutes and seconds to a single interval in seconds
try:
minutes = int(self.spin_minutes.get())
seconds = int(self.spin_seconds.get())
self.result = minutes * 60 + seconds # Total time in seconds
except ValueError:
# Fall back to a default interval as needed
self.result = 1 # Default to 1 second
def validate(self):
try:
minutes = int(self.spin_minutes.get())
seconds = int(self.spin_seconds.get())
return True
except ValueError:
self.bell()
return False
class ImageViewer:
def __init__(self, root):
self.SUPPORTED_EXTENSIONS = (".png", ".jpg", ".jpeg", ".gif", ".bmp", ".JPG", ".JPEG", ".BMP", ".GIF", ".webp", ".WEBP")
self.button_style = {"font": ("consolas", 11), "fg": "white", "bg": "#3c3c3c", "relief": "flat"}
self.button_red = {"font": ("consolas", 11), "fg": "white", "bg": "green", "relief": "flat"}
self.button_style_disabled = {"font": ("consolas", 11), "fg": "#505050", "bg": "#909090", "relief": "flat"}
self.timer_style = {"font": ("consolas", 22), "fg": "white", "bg": "#3c3c3c", "relief": "flat"}
self.tooltip_color = {"fg": "#ffffff", "bg": "#1c1c1c"}
self.bgcolor = "#242424"
self.button_width = 3
#self.image_loading_queue = Queue(maxsize=5)
self.switch_timestamps = []
self.root = root
# Initialize the session timings one time
if not hasattr(self, 'current_session_timings'): # Check if current_session_timings has not been set
self.current_session_timings = [] # Empty list
self.is_session_mode = False
self.root.geometry("800x600") # Initial window size
self.root.title("IMG Viewer")
self.root.configure(bg=self.bgcolor) # Set window background color
self.root.attributes("-topmost", False) # Make the window stay on top
self.image_folder = ""
self.selected_folder = "none"
self.image_files = []
self.current_image_index = 0
self.history = []
self.history_index = -1
self.total_images = 0
self.togsess_counter = 0
self.togsess_mode = tk.BooleanVar(value=False)
self.session_active = False
self.session_index = 0
self.session_image_count = 0
self.current_session_timings = []
self.is_session_mode = False
self.main_frame = tk.Frame(self.root, bg=self.bgcolor)
self.main_frame.pack()
self.root.lift()
self.select_folder_button = tk.Button(self.main_frame, text="Select Folder", command=self.select_folder)
self.select_folder_button.configure(**self.button_red)
self.select_folder_button.pack(side=tk.LEFT, padx=5, pady=10)
ToolTip(self.select_folder_button, msg="Pick a folder", follow=True,
**self.tooltip_color)
self.set_timer_button = tk.Button(self.main_frame, text="Timer", command=self.set_timer_interval)
self.set_timer_button.configure(**self.button_style)
self.set_timer_button.pack(side=tk.LEFT, padx=5, pady=10)
ToolTip(self.set_timer_button, msg="Set timer interval", follow=True,
**self.tooltip_color)
self.start_button = tk.Button(self.main_frame, text="Start", command=self.start_pause_slideshow)
self.start_button.configure(**self.button_style_disabled)
self.start_button.pack(side=tk.LEFT, padx=5, pady=10)
ToolTip(self.start_button, msg="Start or pause timer", follow=True,
**self.tooltip_color)
#image canvas
self.canvas = tk.Canvas(self.root)
self.is_mirrored = False
self.is_greyscale = False
self.is_paused = True
self.rotated = 0
self.vol = True
self.beep1 = self.resource_path("beep1.wav")
self.beep2 = self.resource_path("beep2.wav")
self.ico = self.resource_path("icon.ico")
self.root.iconbitmap(self.ico)
self.grid_type="d"
self.timer_label = tk.Label(self.root, text="15", anchor="ne")
self.timer_label.configure(**self.timer_style)
self.timer_label.place(relx=1, anchor="ne", x=-0, y=0)
self.timer_interval = 15000 # Default time interval in milliseconds (15 seconds)
self.set_timer_interval = 15000 # Store the set timer interval
self.timer = None # Timer ID
self.window_size = (self.root.winfo_width(), self.root.winfo_height())
self.resize_timer = None
self.root.bind("<Right>", self.next_image)
self.root.bind("<Left>", self.previous_image)
self.root.bind("<space>", self.start_pause_slideshow)
self.root.bind("<Configure>", self.update_image_size)
def set_timer_interval(self):
if not hasattr(self, 'current_session_timings'): # Make sure the properties exist
self.current_session_timings = []
self.is_session_mode = False
# Pass the current session settings to the dialog
dialog = CustomTimeDialog(self.root, self.current_session_timings, self.is_session_mode)
if dialog.result is not None:
self.is_session_mode = dialog.togsess_mode.get() # Store the new session mode
if self.is_session_mode:
self.current_session_timings = dialog.result # Store the session settings
# Session mode is active, dialog.result contains the list of session strings
self.process_session(dialog.result)
# Set the interval to the first session's time
self.timer_interval = self.current_session_list[0][1] * 1000
else:
# Session mode is inactive, dialog.result should be a numerical value
interval = dialog.result
if interval < 1: # Check if interval is less than 1 second
interval = 1
self.timer_interval = interval * 1000 # Convert to milliseconds
self.root.lift() # Bring the main window to the top
self.root.focus_force() # Give focus to the main window
minutes = self.timer_interval // 60000
seconds = (self.timer_interval % 60000) // 1000
if self.timer_interval <=59000:
self.timer_label.config(text=f"{seconds}")
else :
self.timer_label.config(text=f"{minutes:d}:{seconds:02d}")
def process_session(self, session_list):
self.current_session_list = []
for session_str in session_list:
try:
num_pics, time_str = session_str.split(' pics for ')
minutes, seconds = self.parse_time(time_str)
self.current_session_list.append((int(num_pics), minutes * 60 + seconds))
except ValueError as e:
# Handle the error appropriately, e.g., by logging or messaging the user
pass # Or whatever error handling you choose
def parse_time(self, time_str):
splits = time_str.split('m')
if len(splits) > 1:
minutes = int(splits[0])
seconds = int(splits[1].replace('s', ''))
else:
minutes = 0
seconds = int(time_str.replace('s', ''))
return minutes, seconds
def start_pause_slideshow(self, event=None):
if self.image_folder == "":
messagebox.showinfo("You haven't picked a folder", "Please select an image folder first.")
else:
if self.timer is None: # Check if timer is not running
self.display_image()
self.start_button.config(text="Pause", **self.button_style)
self.timer_label.configure(**self.timer_style)
self.is_paused = False # Set paused flag to False
self.start_timer()
else:
if self.is_paused: # Check if the slideshow is paused
self.start_button.config(text="Pause", **self.button_style)
self.timer_label.configure(**self.timer_style)
self.is_paused = False # Set paused flag to False
self.start_timer()
else:
self.pause_timer()
self.start_button.config(text="Start", **self.button_red)
self.timer_label.configure(bg="green")
self.is_paused = True # Set paused flag to True
def pause_timer(self):
if self.timer is not None:
self.root.after_cancel(self.timer)
self.timer = None
if self.session_active:
self.session_index = 0
self.session_image_count = self.current_session_list[0][0]
self.timer_interval = self.current_session_list[0][1] * 1000
def start_timer(self):
if self.image_folder != "" and not self.is_paused:
self.update_timer()
self.timer = self.root.after(1000, self.start_timer)
def update_timer(self):
# Calculate minutes and seconds left
minutes = self.timer_interval // 60000
seconds = (self.timer_interval % 60000) // 1000
if self.timer_interval <=59000:
self.timer_label.config(text=f"{seconds}")
else :
self.timer_label.config(text=f"{minutes:d}:{seconds:02d}")
if self.vol:
if self.timer_interval == 3000:
wave_obj = sa.WaveObject.from_wave_file(self.beep1)
play_obj = wave_obj.play()
play_obj.wait_done()
if self.timer_interval == 2000:
wave_obj = sa.WaveObject.from_wave_file(self.beep1)
play_obj = wave_obj.play()
play_obj.wait_done()
if self.timer_interval == 1000:
wave_obj = sa.WaveObject.from_wave_file(self.beep1)
play_obj = wave_obj.play()
play_obj.wait_done()
if self.timer_interval == 0:
wave_obj = sa.WaveObject.from_wave_file(self.beep2)
play_obj = wave_obj.play()
play_obj.wait_done()
self.timer_interval -= 1000
if self.timer_interval < 0:
self.timer_interval = self.set_timer_interval # Use the stored set timer interval
self.next_image()
def next_image(self, event=None):
if self.image_folder != "":
if len(self.image_files) == len(self.history):
self.history_index = (self.history_index + 1) % len(self.image_files)
else:
self.add_image_to_history()
self.display_image()
# Reset the timer interval to the stored set timer interval
self.timer_interval = self.set_timer_interval
if self.session_active:
self.session_image_count -= 1
if self.session_image_count <= 0:
self.session_index = (self.session_index + 1) % len(self.current_session_list)
self.session_image_count, interval = self.current_session_list[self.session_index]
self.timer_interval = interval * 1000 # Setting the new interval from session
else:
self.timer_interval = self.set_timer_interval
else:
self.timer_interval = self.set_timer_interval
def previous_image(self, event=None):
if self.image_folder != "" and self.history_index > 0:
self.history_index -= 1
self.display_image()
# When session is active, control the flow based on session settings
if self.session_active:
current_count, _ = self.current_session_list[self.session_index]
# Move to the previous session step, if it's the first image in the current session step
if self.session_image_count == current_count:
if self.session_index > 0:
self.session_index -= 1
else:
self.session_index = len(self.current_session_list) - 1
_, interval = self.current_session_list[self.session_index]
self.session_image_count = self.current_session_list[self.session_index][0]
self.timer_interval = interval * 1000
else:
self.session_image_count += 1
_, interval = self.current_session_list[self.session_index]
self.timer_interval = interval * 1000
else:
# For regular (non-session) mode, simply reset the timer interval
self.timer_interval = self.set_timer_interval
when i press next, the timer sets to default 15s. after i set the timer and from the session, it sets to 15s for the second image. i think the timer update code is broken.
when there's something to be changed, give the new codeblock and show me precisely where i can put the codeblock. include the line before and after the new block so i know where to put it on the old code.if something needs to be added, tell me concisely.
|
01972c194fb646315fb343841606c374
|
{
"intermediate": 0.2485470175743103,
"beginner": 0.5561845898628235,
"expert": 0.1952684074640274
}
|
38,182
|
class CustomTimeDialog(simpledialog.Dialog):
def __init__(self, parent, current_session_timings=None, is_session_mode=False, **kwargs):
# Only set defaults if current_session_timings is None or empty
if not current_session_timings: # This checks both None and empty list [] conditions
# Set default initial list here (only if there are no existing session timings)
current_session_timings = ['2 pics for 2s', '1 pics for 1s', '3 pics for 1s']
self.current_session_timings = current_session_timings
self.is_session_mode = is_session_mode
super().__init__(parent, **kwargs)
def body(self, master):
self.timebutton_style = {"font": ("consolas", 11),
"fg": "white", "bg": "#3c3c3c", "relief": "flat"}
self.title('Custom Time')
self.time_background = "#242424"
self.time_fg="white"
master.configure(bg=self.time_background)
self.configure(bg=self.time_background)
self.ico = self.resource_path_timer("icon.ico")
self.iconbitmap(self.ico)
#timebox--------------------------------------------------
ctime_frame = tk.Frame(master, bg=self.time_background)
ctime_frame.grid(row=1, column=1)
self.timebox = tk.Listbox(ctime_frame, height=6, width=15,
font=self.timebutton_style["font"],
bg=self.timebutton_style["bg"], fg="#dddddd",
selectbackground="#222222")
for time_string in ['15s', '30s', '45s', '1m', '5m', '10m']:
self.timebox.insert(tk.END, time_string)
self.timebox.grid(row=1, column=1)
self.timebox.bind('<<ListboxSelect>>', self.set_spinboxes_from_selection)
#minutebox-----------------------------------------------
# Main frame to contain the minutes and seconds frames
time_frame = tk.Frame(ctime_frame, bg=self.time_background)
time_frame.grid(row=2, column=1, pady=5)# side=tk.TOP, fill=tk.X, padx=5, pady=5)
# Create a frame for the minutes spinbox and label
minutes_frame = tk.Frame(time_frame, bg=self.time_background)
minutes_frame.pack(side=tk.LEFT, fill=tk.X)#, padx=5)
tk.Label(minutes_frame, text="Minutes:",
bg=self.time_background, fg=self.time_fg,
font=self.timebutton_style["font"]).pack(side=tk.TOP)
self.spin_minutes = tk.Spinbox(minutes_frame, from_=0, to=59, width=5, font=self.timebutton_style["font"])
self.spin_minutes.pack(side=tk.TOP)
# Create a frame for the seconds spinbox and label
seconds_frame = tk.Frame(time_frame, bg=self.time_background)
seconds_frame.pack(side=tk.LEFT, fill=tk.X, padx=5)
tk.Label(seconds_frame, text="Seconds:", bg=self.time_background,
fg=self.time_fg, font=self.timebutton_style["font"]).pack(side=tk.TOP)
self.spin_seconds = tk.Spinbox(seconds_frame, from_=0, to=59, value=15,
width=5, font=self.timebutton_style["font"], wrap=True)
self.spin_seconds.pack(side=tk.TOP)
#togsessbox-------------------------------------------------
session = tk.LabelFrame(master, fg=self.timebutton_style["fg"], bg=self.time_background, relief=tk.FLAT)#, text="Sessions"
session.grid(row=1, column=2)
#togsessbox = tk.Frame(master, bg=self.time_background)
togsess_frame = tk.Frame(session, bg=self.time_background)
togsess_frame.grid (row=3,column=1, pady=5)
self.togsess_mode = tk.BooleanVar(value=False)
#self.togsess_frame = tk.Checkbutton(togsess_frame, bg=self.time_background)
self.togsess_checkbox = tk.Checkbutton(togsess_frame, text="Session",
variable=self.togsess_mode, command=self.toggle_togsess)
self.togsess_checkbox.configure(**self.timebutton_style, bd=0)
self.togsess_checkbox.grid(row=1, column=1, sticky=tk.E, ipadx=12)
self.img_togsess = tk.Spinbox(togsess_frame, width=3, from_=0, to=100,
font=self.timebutton_style["font"], wrap=True, x=500, value=5, state = 'disabled')
self.img_togsess.grid(row=1, column=2)
#sessionsbox-----------------------------------------------------------
self.sessionlist = []
self.sessionString = tk.StringVar(value=self.sessionlist)
self.sessionbox = tk.Listbox(session, height=6, width=18,
font=self.timebutton_style["font"], bg=self.timebutton_style["bg"],
listvariable=self.sessionString, borderwidth=0, state = 'disabled',
fg="#dddddd", selectbackground="#222222")#, fg=self.timebutton_style["fg"])
self.sessionbox.grid(row=1, column=1)
#session buttons frame------------------------------------------------------------------
sessionbuttons = tk.Frame(session, bg=self.time_background)
sessionbuttons.grid(row=2, column=1)
self.add_button = tk.Button(sessionbuttons, text="+", width=3,
command=self.add_session, default=tk.ACTIVE, state="disabled")
self.add_button.config(**self.timebutton_style)
self.add_button.grid(row=1, column=1)
self.del_button = tk.Button(sessionbuttons, text="-", width=3,
command=self.remove_session, default=tk.ACTIVE, state="disabled")
self.del_button.config(**self.timebutton_style)
self.del_button.grid(row=1, column=2, padx=(0,10))
self.up_button = tk.Button(sessionbuttons, text="Ʌ", width=3,
command=lambda: self.move(-1), default=tk.ACTIVE, state="disabled")
self.up_button.config(**self.timebutton_style)
self.up_button.grid(row=1, column=3)
self.down_button = tk.Button(sessionbuttons, text="V", width=3,
command=lambda: self.move(1), default=tk.ACTIVE, state="disabled")
self.down_button.config(**self.timebutton_style)
self.down_button.grid(row=1, column=4)
self.togsess_mode.set(self.is_session_mode)
if self.is_session_mode:
self.toggle_togsess() # Initialize the state of session elements based on current setting
# Update the Listbox content with the current session timings:
self.sessionString.set(self.current_session_timings)
self.sessionlist = list(self.current_session_timings)
return self.spin_seconds # initial focus
def add_session(self):
try:
img_togsess_value = int(self.img_togsess.get() or 0)
except ValueError:
img_togsess_value = 0
try:
minutes_input = int(self.spin_minutes.get() or 0)
except ValueError:
minutes_input = 0
try:
seconds_input = int(self.spin_seconds.get() or 0)
except ValueError:
seconds_input = 0
# Convert total seconds to minutes and seconds
minutes, seconds = divmod(minutes_input * 60 + seconds_input, 60)
# Format the session string based on the minutes and seconds
if minutes > 0 and seconds == 0:
session_str = f"{img_togsess_value} pics for {minutes}m"
elif minutes == 0 and seconds > 0:
session_str = f"{img_togsess_value} pics for {seconds}s"
elif minutes > 0 and seconds > 0:
session_str = f"{img_togsess_value} pics for {minutes}m {seconds}s"
else:
# If both minutes and seconds are missing or 0, use 0s in the string
session_str = f"{img_togsess_value} pics for 0s"
# Append session string to the session list
self.sessionlist.append(session_str)
# Update the session string representation
self.sessionString.set(self.sessionlist)
# Select the newly added session in the session box
self.sessionbox.selection_set(len(self.sessionlist) - 1)
def remove_session(self):
selected_index = self.sessionbox.curselection()
if not selected_index:
return
selected_index = selected_index[0]
self.sessionlist.pop(selected_index)
self.sessionString.set(self.sessionlist)
if selected_index < len(self.sessionlist):
self.sessionbox.selection_set(selected_index)
elif len(self.sessionlist) > 0:
self.sessionbox.selection_set(len(self.sessionlist) - 1)
def move(self, num):
#num is -1 for up and 1 for down
self.idxs = self.sessionbox.curselection()
if not self.idxs:
return
for pos in self.idxs:
text=self.sessionbox.get(pos) #gets text
self.sessionbox.delete(pos) #removes text from list box
self.sessionlist.pop(pos) #removes text from list
if pos==len(self.sessionlist) and num==1: pos=-1; #sets at beginning if at bottom and going down
if pos==0 and num==-1: pos=len(self.sessionlist)+1; #sets at end if at top and going up
self.sessionbox.insert(pos+num, text) #inserts into list box
self.sessionlist.insert(pos+num, text) #inserts into list
self.sessionbox.selection_set(pos+num)
def toggle_togsess(self):
if self.togsess_mode.get():
self.togsess_checkbox.configure(fg="#2c2c2c", bg="#b8b8b8")
self.img_togsess.config(state = 'normal')
self.sessionbox.config (state = 'normal')
self.add_button.config (state = 'normal')
self.del_button.config (state = 'normal')
self.up_button.config (state = 'normal')
self.down_button.config(state = 'normal')
else:
self.togsess_checkbox.configure(**self.timebutton_style)
self.img_togsess.config(state = 'disabled')
self.sessionbox.config (state = 'disabled')
self.add_button.config (state = 'disabled')
self.del_button.config (state = 'disabled')
self.up_button.config (state = 'disabled')
self.down_button.config(state = 'disabled')
def set_spinboxes_from_selection(self, event=None):
index = self.timebox.curselection()
if not index:
return
time_string = self.timebox.get(index)
if 'm' in time_string:
minutes = int(time_string.replace('m', ''))
seconds = 0
elif 's' in time_string:
minutes = 0
seconds = int(time_string.replace('s', ''))
else:
# Handle a possible unknown format
self.bell() # ring the bell to signal an error
return
self.spin_minutes.delete(0, tk.END)
self.spin_minutes.insert(0, minutes)
self.spin_seconds.delete(0, tk.END)
self.spin_seconds.insert(0, seconds)
def buttonbox(self):
box = tk.Frame(self, bg=self.time_background)
self.ok_button = tk.Button(box, text="Apply", width=16, command=self.ok, default=tk.ACTIVE)
self.ok_button.config(**self.timebutton_style)
self.ok_button.pack(side=tk.TOP, ipadx=5, pady=5)
box.pack()
def apply(self):
if self.togsess_mode.get():
# In session mode, store the list of session strings directly
self.result = self.sessionlist # Use the list directly instead of self.sessionString.get()
else:
# In standard mode, parse and combine minutes and seconds to a single interval in seconds
try:
minutes = int(self.spin_minutes.get())
seconds = int(self.spin_seconds.get())
self.result = minutes * 60 + seconds # Total time in seconds
except ValueError:
# Fall back to a default interval as needed
self.result = 1 # Default to 1 second
def validate(self):
try:
minutes = int(self.spin_minutes.get())
seconds = int(self.spin_seconds.get())
return True
except ValueError:
self.bell()
return False
class ImageViewer:
def __init__(self, root):
self.SUPPORTED_EXTENSIONS = (".png", ".jpg", ".jpeg", ".gif", ".bmp", ".JPG", ".JPEG", ".BMP", ".GIF", ".webp", ".WEBP")
self.button_style = {"font": ("consolas", 11), "fg": "white", "bg": "#3c3c3c", "relief": "flat"}
self.button_red = {"font": ("consolas", 11), "fg": "white", "bg": "green", "relief": "flat"}
self.button_style_disabled = {"font": ("consolas", 11), "fg": "#505050", "bg": "#909090", "relief": "flat"}
self.timer_style = {"font": ("consolas", 22), "fg": "white", "bg": "#3c3c3c", "relief": "flat"}
self.tooltip_color = {"fg": "#ffffff", "bg": "#1c1c1c"}
self.bgcolor = "#242424"
self.button_width = 3
#self.image_loading_queue = Queue(maxsize=5)
self.switch_timestamps = []
self.root = root
# Initialize the session timings one time
if not hasattr(self, 'current_session_timings'): # Check if current_session_timings has not been set
self.current_session_timings = [] # Empty list
self.is_session_mode = False
self.root.geometry("800x600") # Initial window size
self.root.title("IMG Viewer")
self.root.configure(bg=self.bgcolor) # Set window background color
self.root.attributes("-topmost", False) # Make the window stay on top
self.image_folder = ""
self.selected_folder = "none"
self.image_files = []
self.current_image_index = 0
self.history = []
self.history_index = -1
self.total_images = 0
self.togsess_counter = 0
self.togsess_mode = tk.BooleanVar(value=False)
self.session_active = False
self.session_index = 0
self.session_image_count = 0
self.current_session_timings = []
self.is_session_mode = False
self.main_frame = tk.Frame(self.root, bg=self.bgcolor)
self.main_frame.pack()
self.root.lift()
self.select_folder_button = tk.Button(self.main_frame, text="Select Folder", command=self.select_folder)
self.select_folder_button.configure(**self.button_red)
self.select_folder_button.pack(side=tk.LEFT, padx=5, pady=10)
ToolTip(self.select_folder_button, msg="Pick a folder", follow=True,
**self.tooltip_color)
self.set_timer_button = tk.Button(self.main_frame, text="Timer", command=self.set_timer_interval)
self.set_timer_button.configure(**self.button_style)
self.set_timer_button.pack(side=tk.LEFT, padx=5, pady=10)
ToolTip(self.set_timer_button, msg="Set timer interval", follow=True,
**self.tooltip_color)
self.start_button = tk.Button(self.main_frame, text="Start", command=self.start_pause_slideshow)
self.start_button.configure(**self.button_style_disabled)
self.start_button.pack(side=tk.LEFT, padx=5, pady=10)
ToolTip(self.start_button, msg="Start or pause timer", follow=True,
**self.tooltip_color)
#image canvas
self.canvas = tk.Canvas(self.root)
self.is_mirrored = False
self.is_greyscale = False
self.is_paused = True
self.rotated = 0
self.vol = True
self.beep1 = self.resource_path("beep1.wav")
self.beep2 = self.resource_path("beep2.wav")
self.ico = self.resource_path("icon.ico")
self.root.iconbitmap(self.ico)
self.grid_type="d"
self.timer_label = tk.Label(self.root, text="15", anchor="ne")
self.timer_label.configure(**self.timer_style)
self.timer_label.place(relx=1, anchor="ne", x=-0, y=0)
self.timer_interval = 15000 # Default time interval in milliseconds (15 seconds)
self.set_timer_interval = 15000 # Store the set timer interval
self.timer = None # Timer ID
self.window_size = (self.root.winfo_width(), self.root.winfo_height())
self.resize_timer = None
self.root.bind("<Right>", self.next_image)
self.root.bind("<Left>", self.previous_image)
self.root.bind("<space>", self.start_pause_slideshow)
self.root.bind("<Configure>", self.update_image_size)
def resource_path(self, relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.path.join(base_path, relative_path)
def select_folder(self):
self.selected_folder = filedialog.askdirectory(initialdir=self.image_folder)
if not self.selected_folder or self.selected_folder == self.image_folder:
return
self.image_folder = self.selected_folder
if self.image_folder:
image_files = os.listdir(self.image_folder) # Get all files in the selected folder
self.image_files = [file for file in image_files if file.endswith(self.SUPPORTED_EXTENSIONS)]
self.history = []
self.history_index = -1
self.rotated = 0
self.togsess_counter = 0
self.total_images = len(self.image_files)
if self.image_files:
self.add_image_to_history()
self.current_image_index = 0
self.canvas.pack(fill=tk.BOTH, expand=True)
self.select_folder_button.pack(side=tk.LEFT, padx=5, pady=5)
self.root.title(f"IMGing in {self.image_folder} found {self.total_images} images")
self.canvas.config(bg=self.bgcolor, highlightthickness=0)
self.display_image()
self.start_button.config(**self.button_red)
self.openimgdir.configure(**self.button_style)
self.mirror_button.configure(**self.button_style)
self.greyscale_button.configure(**self.button_style)
self.rotate_button.configure(**self.button_style)
self.grid_button.configure(**self.button_style)
self.select_folder_button.configure(**self.button_style)
else:
messagebox.showinfo("No Image Files", "The selected folder does not contain any image files.")
self.image_folder = ""
self.root.title("IMG")
def add_image_to_history(self):
# This method selects the next image that hasn't been shown yet and adds it to the history
if self.image_files and len(self.history) < len(self.image_files):
# Create a set of all images and subtract the set of images already shown
remaining_images = set(self.image_files) - set(self.history)
# Randomly choose from remaining images
next_image = random.choice(list(remaining_images))
self.history.append(next_image)
self.history_index += 1
elif len(self.history) >= len(self.image_files):
# All images have been shown; reset history to start showing again
self.history = []
self.history_index = -1
# Now call this function again to add the first image after reset
self.add_image_to_history()
def set_timer_interval(self):
if not hasattr(self, 'current_session_timings'): # Make sure the properties exist
self.current_session_timings = []
self.is_session_mode = False
# Pass the current session settings to the dialog
dialog = CustomTimeDialog(self.root, self.current_session_timings, self.is_session_mode)
if dialog.result is not None:
self.is_session_mode = dialog.togsess_mode.get() # Store the new session mode
if self.is_session_mode:
self.current_session_timings = dialog.result # Store the session settings
# Session mode is active, dialog.result contains the list of session strings
self.process_session(dialog.result)
# Set the interval to the first session's time
self.timer_interval = self.current_session_list[0][1] * 1000
else:
# Session mode is inactive, dialog.result should be a numerical value
interval = dialog.result
if interval < 1: # Check if interval is less than 1 second
interval = 1
self.timer_interval = interval * 1000 # Convert to milliseconds
self.root.lift() # Bring the main window to the top
self.root.focus_force() # Give focus to the main window
minutes = self.timer_interval // 60000
seconds = (self.timer_interval % 60000) // 1000
if self.timer_interval <=59000:
self.timer_label.config(text=f"{seconds}")
else :
self.timer_label.config(text=f"{minutes:d}:{seconds:02d}")
def process_session(self, session_list):
self.current_session_list = []
for session_str in session_list:
try:
num_pics, time_str = session_str.split(' pics for ')
minutes, seconds = self.parse_time(time_str)
self.current_session_list.append((int(num_pics), minutes * 60 + seconds))
except ValueError as e:
# Handle the error appropriately, e.g., by logging or messaging the user
pass # Or whatever error handling you choose
def parse_time(self, time_str):
splits = time_str.split('m')
if len(splits) > 1:
minutes = int(splits[0])
seconds = int(splits[1].replace('s', ''))
else:
minutes = 0
seconds = int(time_str.replace('s', ''))
return minutes, seconds
def start_pause_slideshow(self, event=None):
if self.image_folder == "":
messagebox.showinfo("You haven't picked a folder", "Please select an image folder first.")
else:
if self.timer is None: # Check if timer is not running
self.display_image()
self.start_button.config(text="Pause", **self.button_style)
self.timer_label.configure(**self.timer_style)
self.is_paused = False # Set paused flag to False
self.start_timer()
else:
if self.is_paused: # Check if the slideshow is paused
self.start_button.config(text="Pause", **self.button_style)
self.timer_label.configure(**self.timer_style)
self.is_paused = False # Set paused flag to False
self.start_timer()
else:
self.pause_timer()
self.start_button.config(text="Start", **self.button_red)
self.timer_label.configure(bg="green")
self.is_paused = True # Set paused flag to True
def pause_timer(self):
if self.timer is not None:
self.root.after_cancel(self.timer)
self.timer = None
if self.session_active:
self.session_index = 0
self.session_image_count = self.current_session_list[0][0]
self.timer_interval = self.current_session_list[0][1] * 1000
def start_timer(self):
if self.image_folder != "" and not self.is_paused:
self.update_timer()
self.timer = self.root.after(1000, self.start_timer)
def update_timer(self):
# Calculate minutes and seconds left
minutes = self.timer_interval // 60000
seconds = (self.timer_interval % 60000) // 1000
if self.timer_interval <=59000:
self.timer_label.config(text=f"{seconds}")
else :
self.timer_label.config(text=f"{minutes:d}:{seconds:02d}")
if self.vol:
if self.timer_interval == 3000:
wave_obj = sa.WaveObject.from_wave_file(self.beep1)
play_obj = wave_obj.play()
play_obj.wait_done()
if self.timer_interval == 2000:
wave_obj = sa.WaveObject.from_wave_file(self.beep1)
play_obj = wave_obj.play()
play_obj.wait_done()
if self.timer_interval == 1000:
wave_obj = sa.WaveObject.from_wave_file(self.beep1)
play_obj = wave_obj.play()
play_obj.wait_done()
if self.timer_interval == 0:
wave_obj = sa.WaveObject.from_wave_file(self.beep2)
play_obj = wave_obj.play()
play_obj.wait_done()
self.timer_interval -= 1000
if self.timer_interval < 0:
self.timer_interval = self.set_timer_interval # Use the stored set timer interval
self.next_image()
def load_image(self, image_path):
def display_image(self):
if self.image_folder != "" and len(self.image_files) > 0:
if self.update_switch_timestamps():
# Show the text of the image name instead of loading the actual image
image_name = self.history[self.history_index]
self.canvas.delete("all") # Clear the canvas
self.canvas.create_text(
self.canvas.winfo_width() // 2,
self.canvas.winfo_height() // 2,
text=image_name,
fill="white"
)
# Schedule the image load with a delay
if self.timer is not None:
self.root.after_cancel(self.timer) # Cancel existing timer to avoid conflicts
self.timer = self.root.after(500, self.load_image_delayed) # Set a new timer to load the image after 500ms
else:
# Load the image normally if not quick-switching
self.current_image_index = self.history[self.history_index]
image_path = os.path.join(self.image_folder, self.current_image_index)
self.path_to_open = image_path
threading.Thread(target=self.load_image, args=(image_path,)).start()
def next_image(self, event=None):
if self.image_folder != "":
if self.session_active:
self.session_image_count -= 1
if self.session_image_count <= 0:
self.session_index = (self.session_index + 1) % len(self.current_session_list)
self.session_image_count, interval = self.current_session_list[self.session_index]
self.timer_interval = interval * 1000 # Setting the new interval from session
else:
# If we still have images to show in the current session, we don't reset the interval
pass
else:
if len(self.image_files) == len(self.history):
self.history_index = (self.history_index + 1) % len(self.image_files)
else:
self.add_image_to_history()
# For regular (non-session) mode, simply reset the timer interval to the value set in the timer dialog
self.timer_interval = self.set_timer_interval
self.display_image()
def previous_image(self, event=None):
if self.image_folder != "" and self.history_index > 0:
self.history_index -= 1
self.display_image()
# When session is active, control the flow based on session settings
if self.session_active:
current_count, _ = self.current_session_list[self.session_index]
# Move to the previous session step, if it's the first image in the current session step
if self.session_image_count == current_count:
if self.session_index > 0:
self.session_index -= 1
else:
self.session_index = len(self.current_session_list) - 1
self.session_image_count, interval = self.current_session_list[self.session_index]
self.timer_interval = interval * 1000
else:
self.session_image_count += 1
# The timer interval remains the same since we are still within the same session step
else:
# For regular (non-session) mode, simply reset the timer interval to the value set in the timer dialog
self.timer_interval = self.set_timer_interval
the second image resets the timer to default 15s regardless whether its session mode or not. i want it to respect the session mode. i want it to follow the timer directly when session mode is inactive. while session mode is active i want it to use the session list. and when session mode is on, pressing next and previous it should go through the sessionlist, until it reaches the end and just pause. and when i press next or start again after the pause, it just go through the sessionlist again.
when there's something to be changed, give the new codeblock and show me precisely where i can put the codeblock. include the line before and after the new block so i know where to put it on the old code.if something needs to be added, tell me concisely.
|
f5f0c8022bb07f8a296f47405c077c8c
|
{
"intermediate": 0.2485470175743103,
"beginner": 0.5561845898628235,
"expert": 0.1952684074640274
}
|
38,183
|
how to use python to merge excel files into one sheet?
|
65898a908d77357a6e850187e78fd81f
|
{
"intermediate": 0.5709681510925293,
"beginner": 0.1405818909406662,
"expert": 0.2884499728679657
}
|
38,184
|
90s design web design principles
|
8bc60d3c3a023942b6e9773f8b4d330f
|
{
"intermediate": 0.2658507525920868,
"beginner": 0.48414236307144165,
"expert": 0.25000691413879395
}
|
38,185
|
hi
|
b0d2324f3b31a842f1261f898ca111b2
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
38,186
|
Hi
|
1d8e8d6c89849ec196e500ba90bb8463
|
{
"intermediate": 0.33010533452033997,
"beginner": 0.26984941959381104,
"expert": 0.400045245885849
}
|
38,187
|
How do i modify the table style in exel to remove the shading that appears on every other row.
|
6b0fd0687c56881fc2d2b04d41262ddd
|
{
"intermediate": 0.44383707642555237,
"beginner": 0.2293466180562973,
"expert": 0.32681629061698914
}
|
38,188
|
can you help me with python and crypto ?
|
0a8e17fe9eb5de8d43305878418f5df1
|
{
"intermediate": 0.4049319624900818,
"beginner": 0.23256340622901917,
"expert": 0.36250463128089905
}
|
38,189
|
hi
|
a8a3ce91336ffd7c4d3daeee7c981f73
|
{
"intermediate": 0.3246487081050873,
"beginner": 0.27135494351387024,
"expert": 0.40399640798568726
}
|
38,190
|
Imagine artistically and creatively brainstorming to write a list of several examples of a "message generator" described in different syntaxes and suitable for use in some AI image generator; These examples will aim to indicate the creation of a design where the text "HRYartz" in a modern typography serves as the epicenter of a design inspired with visual elements of the Mayans in all the splendor of their ancient civilization.
|
eca346aea729d7902e30d00cfa4b200e
|
{
"intermediate": 0.16892163455486298,
"beginner": 0.2661854922771454,
"expert": 0.5648928880691528
}
|
38,191
|
what is hoisting in JavaScript and how one can use it
|
591a17fe3c1801f53bd06250e91753b0
|
{
"intermediate": 0.48426321148872375,
"beginner": 0.2928506135940552,
"expert": 0.2228861153125763
}
|
38,192
|
hello
|
9c7a54c9f1701993d2bb0285f9ed92e9
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
38,193
|
以下是我的nextjs的page.tsx文件代码,请丰富这个页面内容和美化页面,让它更像一个类似于google等科技公司的页面:
import { allPosts } from "@/.contentlayer/generated"
import Link from "next/link"
export default function Home() {
return (
<div className="prose dark:prose-invert">
<h1>一致科技官方blog</h1>
{allPosts.map((post) => (
<article key={post._id}>
<Link href={post.slug}>
<h2>{post.title}</h2>
</Link>
{post.description && <p>{post.description}</p>}
</article>
))}
</div>
)
}
|
8cf4e584f58312233f09a92a53f54bd7
|
{
"intermediate": 0.3693714737892151,
"beginner": 0.34972813725471497,
"expert": 0.28090035915374756
}
|
38,194
|
如何添加图片和视频:
import { allPosts } from "@/.contentlayer/generated"
import Link from "next/link"
export default function Home() {
return (
<div className="prose dark:prose-invert">
<h1>一致科技官方blog</h1>
{allPosts.map((post) => (
<article key={post._id}>
<Link href={post.slug}>
<h2>{post.title}</h2>
</Link>
{post.description && <p>{post.description}</p>}
</article>
))}
</div>
)
}
|
2c3dc65670bec0dd437ccb9df8986f62
|
{
"intermediate": 0.3771906793117523,
"beginner": 0.39972156286239624,
"expert": 0.22308775782585144
}
|
38,195
|
hello
|
00397f1dae305d0393ebbbf087bcf32d
|
{
"intermediate": 0.32064199447631836,
"beginner": 0.28176039457321167,
"expert": 0.39759764075279236
}
|
38,196
|
hey man can you make me a psuedocode lexer in python for the CAIE syllabus?
|
0eeedae325851ac34a1a7dc0be324b9d
|
{
"intermediate": 0.3688649535179138,
"beginner": 0.29957494139671326,
"expert": 0.3315601050853729
}
|
38,197
|
hi how old are u?
|
1fb229dcb6910ec1da0c8305cae1a25d
|
{
"intermediate": 0.36903172731399536,
"beginner": 0.36973872780799866,
"expert": 0.26122960448265076
}
|
38,198
|
in python how to get second digit of a three-digit number
|
e29aed9f7333766d97f569b64c4767fe
|
{
"intermediate": 0.3073076009750366,
"beginner": 0.12428577989339828,
"expert": 0.5684066414833069
}
|
38,199
|
Write a flask API to send push notification using firebase to mobile devices.
|
6e8d5b629b56742dcbd1989940601a2d
|
{
"intermediate": 0.8154997229576111,
"beginner": 0.057558268308639526,
"expert": 0.1269419938325882
}
|
38,200
|
You are gherkin feature file executor. You should provide log data as result. Log data should show api calls in short form and context data changes. If understand- type "ok"
|
8889650e877b99a9f26abcc048f26d5b
|
{
"intermediate": 0.590635359287262,
"beginner": 0.19652123749256134,
"expert": 0.2128433734178543
}
|
38,201
|
what does train.py from the yolov5/segment/train.py do , explain briefly
|
a1a55eb45aa5960f807e3fab7c8d91d8
|
{
"intermediate": 0.23264598846435547,
"beginner": 0.21058687567710876,
"expert": 0.5567671060562134
}
|
38,202
|
这个错误如何处理:RuntimeError: Failed to import transformers.trainer because of the following error (look up to see its traceback):
No module named 'torch._six'
|
841373eb43004b1477224a9013f23ce7
|
{
"intermediate": 0.38969364762306213,
"beginner": 0.21811838448047638,
"expert": 0.3921879827976227
}
|
38,203
|
UnpicklingError: invalid load key, '\x02'. выходит ошибка при прочтении pickle файла df = pd.read_pickle(path_dvc + r'data\processed\df.pkl')
|
289c609e5b50b172e0860e6e160c3335
|
{
"intermediate": 0.33766627311706543,
"beginner": 0.29771688580513,
"expert": 0.36461687088012695
}
|
38,204
|
Sub SaveBase()
' Перенос ячеек
Range("B6").Select
Selection.Copy
Sheets("01.2024").Select
Range("C2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Ввод данных1").Select
Range("B3").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("01.2024").Select
Range("A2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Ввод данных1").Select
Range("D3").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("01.2024").Select
Range("B2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Ввод данных1").Select
Range("B9").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("01.2024").Select
Range("D2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Ввод данных1").Select
Range("B12").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("01.2024").Select
Range("E2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Ввод данных1").Select
Range("B15").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("01.2024").Select
Range("F2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Ввод данных1").Select
Range("B18").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("01.2024").Select
Range("G2").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Sheets("Ввод данных1").Select
Application.CutCopyMode = False
' Удаление ячеек
Range("B3").Select
Selection.ClearContents
Range("D3").Select
Selection.ClearContents
Range("B6").Select
Selection.ClearContents
Range("B9").Select
Selection.ClearContents
Range("B12").Select
Selection.ClearContents
Range("B15").Select
Selection.ClearContents
Range("B18").Select
Selection.ClearContents
Range("D14").Select
End Sub
Как сделать код чтобы при переносе ячейки в следующий раз переносило на нижнюю ячейку, а не заменяла предыдущую
|
2770a37d94b804cf8b9735bac22536c9
|
{
"intermediate": 0.2720734477043152,
"beginner": 0.37527385354042053,
"expert": 0.35265272855758667
}
|
38,205
|
regex for getting url links
|
82499cd9d0340fedccd5de1dbe19e196
|
{
"intermediate": 0.37840524315834045,
"beginner": 0.3093610107898712,
"expert": 0.31223371624946594
}
|
38,206
|
Can you show me some practical examples of Vizrt 5 Scripting for broadcast?
|
9c152484c2b94afccea0be273c895372
|
{
"intermediate": 0.46957850456237793,
"beginner": 0.2910749912261963,
"expert": 0.23934650421142578
}
|
38,207
|
converti questo indicatore in uno per mt4
//Created by "SPH Investment Fund"
//@version=4
study(title="Forex Overwiew True Strenght Index", shorttitle="FOTSI", precision=2, overlay=false)
//Global input
length1 = input(0, title="Momentum period", type=input.integer, minval=0)
length2 = input(25, title="Smoothing period", type=input.integer, minval=1)
length3 = input(15, title="Smoothing period", type=input.integer, minval=1)
allertB = input(3, title="Trigger bar", type=input.integer, minval=1)
offsetL = input(0, title="Labels offset")
//Labels color
color_eur = input(color.blue, title="EUR label color", type=input.color)
color_usd = input(#0000ff, title="USD label color", type=input.color)
color_gbp = input(color.purple, title="GBP label color", type=input.color)
color_chf = input(color.fuchsia, title="CHF label color", type=input.color)
color_jpy = input(color.orange, title="JPY label color", type=input.color)
color_aud = input(color.lime, title="AUD label color", type=input.color)
color_cad = input(color.red, title="CAD label color", type=input.color)
color_nzd = input(color.green, title="NZD label color", type=input.color)
//Momentum calculation
mom_eurusd = security("OANDA:EURUSD", timeframe.period, close - open[length1])
mom_eurgbp = security("OANDA:EURGBP", timeframe.period, close - open[length1])
mom_eurchf = security("OANDA:EURCHF", timeframe.period, close - open[length1])
mom_eurjpy = security("OANDA:EURJPY", timeframe.period, close - open[length1]) / 100
mom_euraud = security("OANDA:EURAUD", timeframe.period, close - open[length1])
mom_eurcad = security("OANDA:EURCAD", timeframe.period, close - open[length1])
mom_eurnzd = security("OANDA:EURNZD", timeframe.period, close - open[length1])
mom_usdchf = security("OANDA:USDCHF", timeframe.period, close - open[length1])
mom_usdjpy = security("OANDA:USDJPY", timeframe.period, close - open[length1]) / 100
mom_usdcad = security("OANDA:USDCAD", timeframe.period, close - open[length1])
mom_gbpusd = security("OANDA:GBPUSD", timeframe.period, close - open[length1])
mom_gbpchf = security("OANDA:GBPCHF", timeframe.period, close - open[length1])
mom_gbpjpy = security("OANDA:GBPJPY", timeframe.period, close - open[length1]) / 100
mom_gbpaud = security("OANDA:GBPAUD", timeframe.period, close - open[length1])
mom_gbpcad = security("OANDA:GBPCAD", timeframe.period, close - open[length1])
mom_gbpnzd = security("OANDA:GBPNZD", timeframe.period, close - open[length1])
mom_chfjpy = security("OANDA:CHFJPY", timeframe.period, close - open[length1]) / 100
mom_audusd = security("OANDA:AUDUSD", timeframe.period, close - open[length1])
mom_audchf = security("OANDA:AUDCHF", timeframe.period, close - open[length1])
mom_audjpy = security("OANDA:AUDJPY", timeframe.period, close - open[length1]) / 100
mom_audcad = security("OANDA:AUDCAD", timeframe.period, close - open[length1])
mom_audnzd = security("OANDA:AUDNZD", timeframe.period, close - open[length1])
mom_cadchf = security("OANDA:CADCHF", timeframe.period, close - open[length1])
mom_cadjpy = security("OANDA:CADJPY", timeframe.period, close - open[length1]) / 100
mom_nzdusd = security("OANDA:NZDUSD", timeframe.period, close - open[length1])
mom_nzdchf = security("OANDA:NZDCHF", timeframe.period, close - open[length1])
mom_nzdjpy = security("OANDA:NZDJPY", timeframe.period, close - open[length1]) / 100
mom_nzdcad = security("OANDA:NZDCAD", timeframe.period, close - open[length1])
//Currency momentum calculation
mom_eur = mom_eurusd + mom_eurgbp + mom_eurchf + mom_eurjpy + mom_euraud + mom_eurcad + mom_eurnzd
mom_usd = - mom_eurusd - mom_gbpusd + mom_usdchf + mom_usdjpy - mom_audusd + mom_usdcad - mom_nzdusd
mom_gbp = - mom_eurgbp + mom_gbpusd + mom_gbpchf + mom_gbpjpy + mom_gbpaud + mom_gbpcad + mom_gbpnzd
mom_chf = - mom_eurchf - mom_usdchf - mom_gbpchf + mom_chfjpy - mom_audchf - mom_cadchf - mom_nzdchf
mom_jpy = - mom_eurjpy - mom_usdjpy - mom_gbpjpy - mom_chfjpy - mom_audjpy - mom_cadjpy - mom_nzdjpy
mom_aud = - mom_euraud + mom_audusd - mom_gbpaud + mom_audchf + mom_audjpy + mom_audcad + mom_audnzd
mom_cad = - mom_eurcad - mom_usdcad - mom_gbpcad + mom_cadchf + mom_cadjpy - mom_audcad - mom_nzdcad
mom_nzd = - mom_eurnzd + mom_nzdusd - mom_gbpnzd + mom_nzdchf + mom_nzdjpy - mom_audnzd + mom_nzdcad
//TSI calculation
smo_eur(mom_eur, length2, length3) =>
smo1_eur = ema(mom_eur, length2)
smo2_eur = ema(smo1_eur, length3)
dsm1_eur = smo_eur(mom_eur, length2, length3)
dsm2_eur = smo_eur(abs(mom_eur), length2, length3)
tsi_eur = 100 * (dsm1_eur / dsm2_eur)
smo_usd(mom_usd, length2, length3) =>
smo1_usd = ema(mom_usd, length2)
smo2_usd = ema(smo1_usd, length3)
dsm1_usd = smo_usd(mom_usd, length2, length3)
dsm2_usd = smo_usd(abs(mom_usd), length2, length3)
tsi_usd = 100 * (dsm1_usd / dsm2_usd)
smo_gbp(mom_gbp, length2, length3) =>
smo1_gbp = ema(mom_gbp, length2)
smo2_gbp = ema(smo1_gbp, length3)
dsm1_gbp = smo_usd(mom_gbp, length2, length3)
dsm2_gbp = smo_usd(abs(mom_gbp), length2, length3)
tsi_gbp = 100 * (dsm1_gbp / dsm2_gbp)
smo_chf(mom_chf, length2, length3) =>
smo1_chf = ema(mom_chf, length2)
smo2_chf = ema(smo1_chf, length3)
dsm1_chf = smo_chf(mom_chf, length2, length3)
dsm2_chf = smo_chf(abs(mom_chf), length2, length3)
tsi_chf = 100 * (dsm1_chf / dsm2_chf)
smo_jpy(mom_jpy, length2, length3) =>
smo1_jpy = ema(mom_jpy, length2)
smo2_jpy = ema(smo1_jpy, length3)
dsm1_jpy = smo_jpy(mom_jpy, length2, length3)
dsm2_jpy = smo_jpy(abs(mom_jpy), length2, length3)
tsi_jpy = 100 * (dsm1_jpy / dsm2_jpy)
smo_aud(mom_aud, length2, length3) =>
smo1_aud = ema(mom_aud, length2)
smo2_aud = ema(smo1_aud, length3)
dsm1_aud = smo_aud(mom_aud, length2, length3)
dsm2_aud = smo_aud(abs(mom_aud), length2, length3)
tsi_aud = 100 * (dsm1_aud / dsm2_aud)
smo_cad(mom_cad, length2, length3) =>
smo1_cad = ema(mom_cad, length2)
smo2_cad = ema(smo1_cad, length3)
dsm1_cad = smo_cad(mom_cad, length2, length3)
dsm2_cad = smo_cad(abs(mom_cad), length2, length3)
tsi_cad = 100 * (dsm1_cad / dsm2_cad)
smo_nzd(mom_nzd, length2, length3) =>
smo1_nzd = ema(mom_nzd, length2)
smo2_nzd = ema(smo1_nzd, length3)
dsm1_nzd = smo_nzd(mom_nzd, length2, length3)
dsm2_nzd = smo_nzd(abs(mom_nzd), length2, length3)
tsi_nzd = 100 * (dsm1_nzd / dsm2_nzd)
//Currency plotting
plot(tsi_eur, title="EUR", color=color.blue, linewidth=2)
plot(tsi_usd, title="USD", color=#0000ff, linewidth=2)
plot(tsi_gbp, title="GBP", color=color.purple, linewidth=2)
plot(tsi_chf, title="CHF", color=color.fuchsia, linewidth=2)
plot(tsi_jpy, title="JPY", color=color.orange, linewidth=2)
plot(tsi_aud, title="AUD", color=color.lime, linewidth=2)
plot(tsi_cad, title="CAD", color=color.red, linewidth=2)
plot(tsi_nzd, title="NZD", color=color.green, linewidth=2)
//Labels
lab_eur = label.new(time + offsetL, tsi_eur, "EUR",
style = label.style_label_left,
color = color_eur,
textcolor = color.white,
xloc = xloc.bar_time)
label.delete(lab_eur[1])
lab_usd = label.new(time + offsetL, tsi_usd, "USD",
style = label.style_label_left,
color = color_usd,
textcolor = color.white,
xloc = xloc.bar_time)
label.delete(lab_usd[1])
lab_gbp = label.new(time + offsetL, tsi_gbp, "GBP",
style = label.style_label_left,
color = color_gbp,
textcolor = color.white,
xloc = xloc.bar_time)
label.delete(lab_gbp[1])
lab_chf = label.new(time + offsetL, tsi_chf, "CHF",
style = label.style_label_left,
color = color_chf,
textcolor = color.white,
xloc = xloc.bar_time)
label.delete(lab_chf[1])
lab_jpy = label.new(time + offsetL, tsi_jpy, "JPY",
style = label.style_label_left,
color = color_jpy,
textcolor = color.white,
xloc = xloc.bar_time)
label.delete(lab_jpy[1])
lab_aud = label.new(time + offsetL, tsi_aud, "AUD",
style = label.style_label_left,
color = color_aud,
textcolor = color.white,
xloc = xloc.bar_time)
label.delete(lab_aud[1])
lab_cad = label.new(time + offsetL, tsi_cad, "CAD",
style = label.style_label_left,
color = color_cad,
textcolor = color.white,
xloc = xloc.bar_time)
label.delete(lab_cad[1])
lab_nzd = label.new(time + offsetL, tsi_nzd, "NZD",
style = label.style_label_left,
color = color_nzd,
textcolor = color.white,
xloc = xloc.bar_time)
label.delete(lab_nzd[1])
//Graphics plotting
overbuy = hline(50, title="Overbuy", color=color.red, linestyle=hline.style_dotted)
oversell = hline(-50, title="Oversell", color=color.green, linestyle=hline.style_dotted)
level25 = hline(25, title="Upper range", color=color.white, linestyle=hline.style_dotted)
levelm25 = hline(-25, title="Lower range", color=color.white, linestyle=hline.style_dotted)
fill(level25, levelm25, title="Range", color=color.new(color.purple, 95))
//Proudly created by Stefano Panetta
//End scripting on 07/05/2021 at 12:42:13
|
0a43efd3bb17e3fb7fc9ad799bb144c3
|
{
"intermediate": 0.2528606653213501,
"beginner": 0.43231508135795593,
"expert": 0.3148242235183716
}
|
38,208
|
You are gherkin feature file executor. Simulate it. You should provide log data as result. Log data should show api calls in short form and context data changes. If understand- type “ok”. No comments.
|
43cdef8c32ae2614fda63a02aa60682b
|
{
"intermediate": 0.5356352925300598,
"beginner": 0.24581602215766907,
"expert": 0.21854867041110992
}
|
38,209
|
// To win this challenge, get your name or twitter handle
// pushed into the book of winners and comment your address.
// Function name is the answer of the puzzle (all caps)
function SOLVE_PUZZLE(string calldata userName) public {
bookOfWinners [msg.sender] = userName;
}
Once divided into many city-states, I am a country known as the cradle of Western civilization.
Philosophy, Democracy, and the Olympics all originated within my borders 🏰
Contract deployed on Sepolia at 0xa62290a428617f62dd65f26534c16b14df8149c3.
|
2670415ad3bf0e49c126187312317188
|
{
"intermediate": 0.2691696584224701,
"beginner": 0.4722742438316345,
"expert": 0.258556067943573
}
|
38,210
|
write a code of gangnam style dancing animation for 0.96" oled display with arduino uno
|
2021479f241ccb79989464e0753dddaf
|
{
"intermediate": 0.38365450501441956,
"beginner": 0.1966574639081955,
"expert": 0.41968807578086853
}
|
38,211
|
Make me a mutilayer perceptron from scratch in py with only numpy
|
250ea6f9dee99103962bc8c2415b8c0b
|
{
"intermediate": 0.2764674723148346,
"beginner": 0.1439933478832245,
"expert": 0.5795391798019409
}
|
38,212
|
u just write code for showing time of dhaka in oled 0.96" and arduino no extra module note i dont have a rtc. it should show realtime without internet
|
305da55ceeacdc2de158a4da4970a52e
|
{
"intermediate": 0.3860844671726227,
"beginner": 0.31006601452827454,
"expert": 0.30384957790374756
}
|
38,213
|
write a pytorch code for min-max rescaling layer
|
5286dc01dc02ef011bdcf9ed3cd7ac5b
|
{
"intermediate": 0.16057172417640686,
"beginner": 0.1118321567773819,
"expert": 0.72759610414505
}
|
38,214
|
global error_det
error_det = ''
import string
from strings_with_arrows import *
from errors import *
from nodes import *
DIGITS = '0123456789'
LETTERS = string.ascii_letters
LETTERS_DIGITS = LETTERS + DIGITS
class Position:
def __init__(self,idx,ln,col,fn,ftxt):
self.fn = fn
self.ftxt = ftxt
self.idx = idx
self.ln = ln
self.col = col
def advance(self,current_char = None):
self.idx += 1
self.col += 1
if current_char == '\n':
self.ln += 1
self.col = 0
return self
def regress(self,current_char = None):
self.idx -= 1
self.col -= 1
def copy(self):
return Position(self.idx,self.ln,self.col,self.fn,self.ftxt)
TT_INT = 'Int'
TT_REAL = 'Real'
TT_STRING = 'String'
TT_IDENTIFIER = 'Identifier'
TT_KEYWORD = 'Keyword'
TT_EQ = 'Eq'
TT_PLUS = 'Plus'
TT_MINUS = 'Minus'
TT_MUL = 'Mul'
TT_DIV = 'Div'
TT_POWER = 'Power'
TT_LPAREN = 'LParen'
TT_RPAREN = "RParen"
TT_LSQUAREBRACKET = 'LSquareBracket'
TT_RSQUAREBRACKET = 'RSquareBracket'
TT_LT = 'NE'
TT_EE = 'EE'
TT_LT = 'LT'
TT_GT = 'GT'
TT_LTE = 'LTE'
TT_GTE = 'GTE'
TT_NE = 'NE'
TT_Comma = 'COMMA'
TT_Arrow = "ARROW"
TT_Newline = 'Newline'
TT_EOF = "Eof"
KEYWORDS = [
'AND',"OR","NOT","IF","ELSE","THEN","FOR","WHILE","DO","STEP","TO","REPEAT","UNTIL","FUNCTION",'RETURNS','ENDIF','ENDFUNCTION','RETURNS','ENDWHILE',"NEXT",'RETURN', 'PROCEDURE', 'ARRAY'
]
class Token:
def __init__(self,type_,value = None, pos_start = None, pos_end = None):
self.type = type_
self.value = value
if pos_start:
self.pos_start = pos_start
self.pos_end = self.pos_start.copy()
self.pos_end.advance()
if pos_end:
self.pos_end = pos_end
def __repr__(self):
if self.value: return f'{self.type}:{self.value}'
return f'{self.type}'
def matches(self,type_,value):
return self.type == type_ and self.value == value
class Lexer:
def __init__(self,fn, text):
self.fn = fn
self.text = text
self.pos = Position(-1,0,-1,fn,text)
self.current_char = None
self.advance()
def advance(self):
self.pos.advance(self.current_char)
self.current_char = self.text[self.pos.idx] if self.pos.idx < len(self.text) else None
def regress(self):
self.pos.regress(self.current_char)
self.current_char = self.text[self.pos.idx] if self.pos.idx < len(self.text) else None
def make_tokens(self):
tokens = []
while self.current_char != None:
if self.current_char in ' \t':
self.advance()
elif self.current_char in ['\n',';']:
tokens.append(Token(TT_Newline,pos_start=self.pos))
self.advance()
elif self.current_char in LETTERS:
tokens.append(self.make_identifier())
elif self.current_char in DIGITS:
tokens.append(self.make_number())
elif self.current_char in ['"',"'"]:
tokens.append(self.make_string(self.current_char))
elif self.current_char == '[':
tokens.append(Token(TT_LSQUAREBRACKET,pos_start = self.pos))
self.advance()
elif self.current_char == ']':
tokens.append(Token(TT_RSQUAREBRACKET,pos_start = self.pos))
self.advance()
elif self.current_char == '+' or self.current_char == '&':
tokens.append(Token(TT_PLUS, pos_start=self.pos))
self.advance()
elif self.current_char == '-':
tokens.append(Token(TT_MINUS, pos_start=self.pos))
self.advance()
elif self.current_char == ':':
tokens.append(Token(TT_Arrow,pos_start=self.pos))
self.advance()
elif self.current_char == '*':
tokens.append(Token(TT_MUL, pos_start=self.pos))
self.advance()
elif self.current_char == '/':
tokens.append(Token(TT_DIV, pos_start=self.pos))
self.advance()
elif self.current_char == '(':
tokens.append(Token(TT_LPAREN, pos_start=self.pos))
self.advance()
elif self.current_char == ')':
tokens.append(Token(TT_RPAREN, pos_start=self.pos))
self.advance()
elif self.current_char == '^':
tokens.append(Token(TT_POWER,pos_start = self.pos))
self.advance()
elif self.current_char == '<':
tok = self.make_not_lessThan_assign()
tokens.append(tok)
elif self.current_char == '=':
tokens.append(Token(TT_EE,pos_start=self.pos))
self.advance()
elif self.current_char == '>':
tokens.append(self.make_greater_than())
elif self.current_char == ',':
tokens.append(Token(TT_Comma, pos_start=self.pos))
self.advance()
else:
pos_start = self.pos.copy()
char = self.current_char
self.advance()
return [],IllegalCharError(pos_start,self.pos,"'" + char + "'")
tokens.append(Token(TT_EOF, pos_start=self.pos))
return tokens, None
def make_string(self,end):
string = ''
pos_start = self.pos.copy()
self.advance()
while self.current_char != None and self.current_char != end:
string += self.current_char
self.advance()
self.advance()
return Token(TT_STRING,string,pos_start,self.pos)
def make_number(self):
num_str = ''
dotCount = 0
pos_start = self.pos.copy()
while self.current_char != None and self.current_char in DIGITS + '.':
if self.current_char == '.':
if dotCount == 1: break
num_str += '.'
dotCount += 1
else:
num_str += self.current_char
self.advance()
if dotCount == 0:
return Token(TT_INT,int(num_str),pos_start,self.pos)
else:
return Token(TT_REAL,float(num_str),pos_start,self.pos)
def make_identifier(self):
id_str = ''
pos_start = self.pos.copy()
while self.current_char != None and self.current_char in LETTERS_DIGITS + '_':
id_str += self.current_char
self.advance()
tok_type = TT_KEYWORD if id_str in KEYWORDS else TT_IDENTIFIER
return Token(tok_type,id_str,pos_start,self.pos)
def make_greater_than(self):
pos_start = self.pos.copy()
self.advance()
if self.current_char == '=':
self.advance()
return Token(TT_GTE,pos_start=pos_start,pos_end=self.pos)
return Token(TT_GT,pos_start=pos_start,pos_end=self.pos)
def make_not_lessThan_assign(self):
pos_start = self.pos.copy()
self.advance()
if self.current_char == '-':
self.advance()
return Token(TT_EQ,pos_start=pos_start,pos_end=self.pos)
elif self.current_char == '>':
self.advance()
return Token(TT_NE,pos_start=pos_start,pos_end=self.pos)
elif self.current_char == '=':
self.advance()
return Token(TT_LTE, pos_start=pos_start, pos_end=self.pos)
else:
return Token(TT_LT, pos_start=pos_start, pos_end=self.pos)
#Parser
#---------------------------------------
class Parser:
def __init__(self,tokens):
self.tokens = tokens
self.hasEq = 0
for q in tokens:
if q.type == TT_EQ:
self.hasEq += 1
self.tok_idx = -1
self.advance()
def advance(self):
self.tok_idx += 1
if self.tok_idx < len(self.tokens):
self.current_tok = self.tokens[self.tok_idx]
return self.current_tok
def regress(self):
self.tok_idx -= 1
self.current_tok = self.tokens[self.tok_idx]
return self.current_tok
def reverse(self,amount = 1):
self.tok_idx -= amount
self.update_current_tok()
return self.current_tok
def update_current_tok(self):
if self.tok_idx >= 0 and self.tok_idx < len(self.tokens):
self.current_tok = self.tokens[self.tok_idx]
def parse(self):
res = self.statements()
if not res.error and self.current_tok.type != TT_EOF:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected '+', '-', '*' or '/'"
))
return res
def statements(self):
res = ParseResult()
statements = []
pos_start = self.current_tok.pos_start.copy()
n = 0
while self.current_tok.type == TT_Newline:
res.register(self.advance())
statement = res.register(self.expr())
if res.error: return res
statements.append(statement)
more_statements = True
while True:
newline_count = 0
while self.current_tok.type == TT_Newline:
res.register(self.advance())
newline_count +=1
if newline_count == 0: more_statements = False
if not more_statements: break
statement = res.try_register(self.expr())
if statement == None:
self.reverse(1)
more_statements = False
continue
statements.append(statement)
return res.success(ListNode(
statements,pos_start,self.current_tok.pos_end.copy()
))
def for_expr(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD,'FOR'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end,f"Expected 'FOR'"))
res.register(self.advance())
if self.current_tok.type != TT_IDENTIFIER:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected identifier"))
var_name = self.current_tok
res.register(self.advance())
if self.current_tok.type != TT_EQ:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, "Expected '<-'"))
res.register(self.advance())
start_value = res.register(self.expr())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'TO'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'TO'"))
res.register(self.advance())
end_value = res.register(self.expr())
if res.error: return res
if self.current_tok.matches(TT_KEYWORD,'STEP'):
res.register(self.advance())
step_value = res.register(self.expr())
if res.error:return res
else:
step_value = None
if not self.current_tok.type == TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline"))
res.register(self.advance())
body = res.register(self.statements())
if res.error:
return res
if not self.current_tok.matches(TT_KEYWORD,'NEXT'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'NEXT'"))
res.register(self.advance())
if not self.current_tok.type == TT_IDENTIFIER:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Identifier"))
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected EOF or Newline"))
return res.success(ForNode(var_name,start_value,end_value,step_value,body))
def while_expr(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD,"WHILE"):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'WHILE'"))
res.register(self.advance())
condition = res.register(self.expr())
if res.error: return res
if self.current_tok.type != TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline"))
res.register(self.advance())
if not self.current_tok.matches(TT_KEYWORD,'DO'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'DO'"))
res.register(self.advance())
if self.current_tok.type != TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline"))
res.register(self.advance())
body = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'ENDWHILE'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'ENDWHILE'"))
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline or EOF"))
return res.success(WhileNode(condition,body))
def repeat_expr(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD,"REPEAT"):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'REPEAT'"))
res.register(self.advance())
if not self.current_tok.type == TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline"))
body = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'UNTIL'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'UNTIL'"))
res.register(self.advance())
condition = res.register(self.expr())
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected newline or EOF"))
return res.success(RepeatNode(body,condition))
def if_expr(self):
res = ParseResult()
cases = []
else_case = None
if not self.current_tok.matches(TT_KEYWORD,'IF'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'IF'"))
res.register(self.advance())
cond = res.register(self.expr())
if res.error: return res
if self.current_tok.type != TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'Newline'"))
res.register(self.advance())
if not self.current_tok.matches(TT_KEYWORD,'THEN'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'THEN'"))
res.register(self.advance())
if self.current_tok.type != TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'Newline'"))
res.register(self.advance())
statements = res.register(self.statements())
if res.error: return res
cases.append((cond,statements))
if self.current_tok.matches(TT_KEYWORD,'ELSE'): #instead of making a separate else-expr I added it here
res.register(self.advance())
if not self.current_tok.type == TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'Newline'"))
else_case = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'ENDIF'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'ENDIF'"))
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected EOF or Newline"))
return res.success(IfNode(cases,else_case))
def call(self):
res = ParseResult()
atom = res.register(self.atom())
if res.error:
return res
if self.current_tok.type == TT_LPAREN:
res.register(self.advance())
arg_nodes = []
if self.current_tok.type == TT_RPAREN:
res.register(self.advance())
else:
tok = self.current_tok
arg_nodes.append(res.register(self.expr()))
if res.error: res.failure(InvalidSyntaxError(tok.pos_start,tok.pos_end,""))
while self.current_tok.type == TT_Comma:
res.register(self.advance())
arg_nodes.append(res.register(self.expr()))
if res.error: return res
if self.current_tok.type != TT_RPAREN:
res.failure(
InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ')' or ','"))
res.register(self.advance())
return res.success(CallNode(atom,arg_nodes))
return res.success(atom)
def atom(self):
res = ParseResult()
tok = self.current_tok
if tok.type in [TT_INT,TT_REAL]:
res.register(self.advance())
return res.success(NumberNode(tok))
if tok.type == TT_STRING:
res.register(self.advance())
return res.success(StringNode(tok))
elif tok.type == TT_IDENTIFIER:
res.register(self.advance())
return res.success(VarAccessNode(tok))
elif tok.type == TT_LPAREN:
res.register(self.advance())
expr = res.register(self.expr())
if res.error: return res
if self.current_tok.type == TT_RPAREN:
res.register(self.advance())
return res.success(expr)
else:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected ')'"
))
elif tok.type == TT_LSQUAREBRACKET:
list_expr = res.register(self.list_expr())
if res.error:
return res
return res.success(list_expr)
elif tok.matches(TT_KEYWORD,'IF'):
if_expr = res.register(self.if_expr())
if res.error: return res
return res.success(if_expr)
elif tok.matches(TT_KEYWORD,'FOR'):
for_expr = res.register(self.for_expr())
if res.error:
return res
return res.success(for_expr)
elif tok.matches(TT_KEYWORD,'WHILE'):
while_expr = res.register(self.while_expr())
if res.error:return res
return res.success(while_expr)
elif tok.matches(TT_KEYWORD,"REPEAT"):
repeat_expr = res.register(self.repeat_expr())
if res.error:
return res
return res.success(repeat_expr)
elif tok.matches(TT_KEYWORD,"FUNCTION"):
function_def = res.register(self.func_def())
if res.error:
return res
return res.success(function_def)
else:
return res.failure(InvalidSyntaxError(tok.pos_start,tok.pos_end,"Expected int,real, '+', '-','(','IF','FOR','WHILE','REPEAT', or 'FUNCTION'"))
def power(self):
return self.bin_op(self.call,(TT_POWER,),self.factor)
def factor(self):
res = ParseResult()
tok = self.current_tok
if tok.type in (TT_PLUS,TT_MINUS):
res.register(self.advance())
factor = res.register(self.factor())
if res.error:
return res
return res.success(UnaryOpNode(tok,factor))
return self.power()
def term(self):
return self.bin_op(self.factor,(TT_DIV,TT_MUL))
def arith_expr(self):
return self.bin_op(self.term,(TT_PLUS,TT_MINUS))
def comp_expr(self):
res = ParseResult()
if self.current_tok.matches(TT_KEYWORD,'NOT'):
op_tok = self.current_tok
res.register(self.advance())
if res.error: return res
node = res.register(self.comp_expr())
if res.error:return res
return res.success(UnaryOpNode(op_tok,node))
node = res.register(self.bin_op(self.arith_expr,(TT_EE,TT_NE,TT_LT,TT_LTE,TT_GT,TT_GTE)))
tok = self.current_tok
if res.error:
return res
return res.success(node)
def expr(self):
res = ParseResult()
if self.current_tok.type == TT_IDENTIFIER:
var_name = self.current_tok
res.register(self.current_tok)
res.register(self.advance())
if self.current_tok.type == TT_EQ:
res.register(self.advance())
expr = res.register(self.expr())
if res.error: return res
return res.success(VarAssignNode(var_name,expr))
self.regress()
return self.bin_op(self.comp_expr,((TT_KEYWORD,'AND'),(TT_KEYWORD,'OR')))
def bin_op(self,func_a,ops,func_b = None):
if func_b == None:
func_b = func_a
res = ParseResult()
left = res.register(func_a())
while self.current_tok.type in ops or (self.current_tok.type, self.current_tok.value) in ops:
op_tok = self.current_tok
res.register(self.advance())
right = res.register(func_b())
if res.error:
return res
left = BinOpNode(left, op_tok, right)
return res.success(left)
def list_expr(self):
res = ParseResult()
element_nodes = []
pos_start = self.current_tok.pos_start.copy()
res.register(self.advance())
if self.current_tok.type == TT_RSQUAREBRACKET:
res.register(self.advance())
else:
tok = self.current_tok
element_nodes.append(res.register(self.expr()))
if res.error: res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ']', 'IF','FOR','WHILE','FUNCTION',variable,datatypoe"))
while self.current_tok.type == TT_Comma:
res.register(self.advance())
element_nodes.append(res.register(self.expr()))
if res.error: return res
if self.current_tok.type != TT_RSQUAREBRACKET:
res.failure(
InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ']' or ','"))
res.register(self.advance())
return ListNode(element_nodes,pos_start,self.current_tok.pos_end.copy())
def func_def(self):
res = ParseResult()
tok = self.current_tok
if not self.current_tok.matches(TT_KEYWORD,'FUNCTION'):
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'FUNCTION'"))
res.register(self.advance())
if self.current_tok.type != TT_IDENTIFIER:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected indentifier"))
var_name_tok = self.current_tok
res.register(self.advance())
if self.current_tok.type != TT_LPAREN:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected '('"))
res.register(self.advance())
arg_name_toks = []
if self.current_tok.type == TT_IDENTIFIER:
arg_name_toks.append(self.current_tok)
res.register(self.advance())
if not self.current_tok.type == TT_Arrow:
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ':'"))
res.register(self.advance())
if not self.current_tok.type == TT_IDENTIFIER or self.current_tok.value not in ['REAL', 'INTEGER', 'CHAR','BOOLEAN', 'STRING']:
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected datatype"))
res.register(self.advance())
while self.current_tok.type == TT_Comma:
res.register(self.advance())
if self.current_tok.type != TT_IDENTIFIER:
tok = self.current_tok
return res.failure(
InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected identifier"))
name = self.current_tok
res.register(self.advance())
if not self.current_tok.type == TT_Arrow:
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ':'"))
res.register(self.advance())
if not self.current_tok.type == TT_IDENTIFIER or self.current_tok.value not in ['REAL', 'INTEGER', 'CHAR', 'BOOLEAN', 'STRING']:
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected datatype"))
arg_name_toks.append(name)
res.register(self.advance())
if self.current_tok.type != TT_RPAREN:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ',' or ')'"))
else:
if self.current_tok.type != TT_RPAREN:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected identifier or ')'"))
res.register(self.advance())
if not self.current_tok.matches(TT_KEYWORD,'RETURNS'):
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'RETURNS'"))
res.register(self.advance())
if self.current_tok.value not in ['INTEGER','REAL','BOOLEAN','STRING','CHAR']:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'INTEGER','REAL','BOOLEAN','STRING' or 'CHAR'"))
res.register(self.advance())
if not self.current_tok.type == TT_Newline:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected Newline'"))
node_to_return = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'RETURN'):
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'RETURN'"))
res.register(self.advance())
expr = res.register(self.expr())
if res.error: return res
res.register(self.advance())
if not self.current_tok.matches(TT_KEYWORD,'ENDFUNCTION'):
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'ENDFUNCTION'"))
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected Newline or EOF'"))
return res.success(FuncDefNode(
var_name_tok,arg_name_toks,node_to_return,expr
))
#runtime result
#-------------------------------------------------
class RTResult:
def __init__(self):
self.value = None
self.error = None
def register(self,res):
if res.error: self.error = res.error
return res.value
def success(self,value):
self.value = value
return self
def failure(self,error):
self.error = error
return self
#values
#-------------------------------------------------
class Value:
def __init__(self):
self.set_context()
self.set_pos()
def set_context(self,context = None):
self.context = context
return self
def set_pos(self,pos_start = None,pos_end = None):
self.pos_start = pos_start
self.pos_end = pos_end
return self
def added_to(self,other):
return None,self.illegal_operation(other)
def subtracted_by(self,other):
return None,self.illegal_operation(other)
def multiplied_by(self,other):
return None,self.illegal_operation(other)
def divided_by(self,other):
return None, self.illegal_operation(other)
def powered_by(self,other):
return None,self.illegal_operation(other)
def get_comparison_eq(self, other):
return None,self.illegal_operation(other)
def get_comparison_ne(self, other):
return None,self.illegal_operation(other)
def get_comparison_lt(self, other):
return None,self.illegal_operation(other)
def get_comparison_gt(self, other):
return None,self.illegal_operation(other)
def get_comparison_lte(self, other):
return None,self.illegal_operation(other)
def get_comparison_gte(self, other):
return None,self.illegal_operation(other)
def anded_by(self, other):
return None,self.illegal_operation(other)
def ored_by(self, other):
return None,self.illegal_operation(other)
def notted(self):
return None,self.illegal_operation(self)
def execute(self, args):
return RTResult().failure(self.illegal_operation())
def copy(self):
raise Exception('No copy method defined')
def is_true(self):
return False
def illegal_operation(self, other=None):
if not other: other = self
return RTError(
self.pos_start, other.pos_end,
'Illegal operation',
self.context
)
class Number(Value):
def __init__(self,value):
self.value = value
super().__init__()
def set_context(self,context = None):
self.context = context
return self
def set_pos(self,pos_start = None,pos_end = None):
self.pos_start = pos_start
self.pos_end = pos_end
return self
def added_to(self,other):
if isinstance(other,Number):
return Number(self.value + other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def subtracted_by(self,other):
if isinstance(other,Number):
return Number(self.value - other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def multiplied_by(self,other):
if isinstance(other,Number):
return Number(self.value * other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def divided_by(self,other):
if isinstance(other,Number):
if other.value == 0:
return None,RTError(
other.pos_start
,other.pos_end,
'Divison by Zero',
self.context
)
return Number(self.value / other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def powered_by(self,other):
if isinstance(other,Number):
return Number(self.value ** other.value).set_context(self.context),None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_eq(self, other):
if isinstance(other, Number):
return Number(int(self.value == other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_ne(self, other):
if isinstance(other, Number):
return Number(int(self.value != other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_lt(self, other):
if isinstance(other, Number):
return Number(int(self.value < other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_gt(self, other):
if isinstance(other, Number):
return Number(int(self.value > other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_lte(self, other):
if isinstance(other, Number):
return Number(int(self.value <= other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_gte(self, other):
if isinstance(other, Number):
return Number(int(self.value >= other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def anded_by(self, other):
if isinstance(other, Number):
return Number(int(self.value and other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def ored_by(self, other):
if isinstance(other, Number):
return Number(int(self.value or other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def notted(self):
return Number(1 if self.value == 0 else 0).set_context(self.context), None
def copy(self):
copy = Number(self.value)
copy.set_pos(self.pos_start,self.pos_end)
copy.set_context(self.context)
return copy
def is_true(self):
return self.value != 0
def __repr__(self):
return f'{self.value}'
class String(Value):
def __init__(self,value):
super().__init__()
self.value = value
def added_to(self,other):
if isinstance(other,String):
return String(self.value + other.value).set_context(self.context),None
else:
return None,Value.illegal_operation(self,other)
def copy(self):
copy = String(self.value)
copy.set_pos(self.pos_start,self.pos_end)
copy.set_context(self.context)
return copy
def __str__(self):
return self.value
def __repr__(self):
return f'"{self.value}"'
class List(Value):
def __init__(self,elements):
super().__init__()
self.elements = elements
def added_to(self,other):
new_list = self.copy()
new_list.elements.append(other)
return new_list,None
def subtracted_by(self,other):
if isinstance(other,Number):
new_list = self.copy()
try:
new_list.elements.pop(other)
return new_list,None
except:
return None,RTError(other.pos_start,other.pos_end,'Element at this indewx is out of bound',self.context)
else:
return None,Value.illegal_operation(self,other)
def multiplied_by(self,other):
if isinstance(other,List):
new_list = self.copy()
new_list.elements.extend(other.elements)
else:
return None,Value.illegal_operation(self,other)
def divided_by(self,other):
if isinstance(other, Number):
try:
return self.elements[other.value],None
except:
return None, RTError(other.pos_start, other.pos_end, 'Element at this indewx is out of bound',
self.context)
else:
return None, Value.illegal_operation(self, other)
def copy(self):
copy = List(self.elements)
copy.set_pos(self.pos_start,self.pos_end)
copy.set_pos(self.context)
return copy
def __repr__(self):
return f"[{','.join([str(x) for x in self.elements])}]"
class BaseFunction(Value):
def __init__(self,name):
super().__init__()
self.name = name
def generateNewContext(self):
new_context = Context(self.name, self.context, self.pos_start)
new_context.symbol_table = SymbolTable(new_context.parent.symbol_table)
return new_context
def check_args(self,arg_names,args):
res = RTResult()
if len(args) > len(arg_names):
return res.failure(RTError(
self.pos_start, self.pos_end,
f"{len(args) - len(arg_names)} too many args passed into '{self.name}'",
self.context
))
if len(args) < len(arg_names):
return res.failure(RTError(
self.pos_start, self.pos_end,
f"{len(arg_names) - len(args)} too few args passed into '{self.name}'",
self.context
))
return res.success(None)
def populate_args(self,arg_names,args,exec_ctx):
for i in range(len(args)):
new_context = exec_ctx
arg_name = arg_names[i]
arg_value = args[i]
arg_value.set_context(new_context)
new_context.symbol_table.set(arg_name, arg_value)
def check_and_populate_args(self,arg_names,args,exec_ctx):
res = RTResult()
res.register(self.check_args(arg_names,args))
if res.error: return res
self.populate_args(arg_names,args,exec_ctx)
return res.success(None)
class Function(BaseFunction):
def __init__(self,name,body_node,arg_names,ret_node):
super().__init__(name)
self.body_node = body_node
self.arg_names = arg_names
self.ret_node = ret_node
def execute(self, args):
res = RTResult()
interpreter = Interpreter()
new_context = self.generateNewContext()
res.register(self.check_and_populate_args(self.arg_names,args,new_context))
if res.error: return res
value = res.register(interpreter.visit(self.body_node, new_context))
if res.error: return res
q = res.register(interpreter.visit(self.ret_node,new_context))
return res.success(q)
def copy(self):
copy = Function(self.name, self.body_node, self.arg_names,self.ret_node)
copy.set_context(self.context)
copy.set_pos(self.pos_start, self.pos_end)
return copy
def __repr__(self):
return f"<function {self.name}>"
class BuiltInFunction(BaseFunction):
def __init__(self,name):
super().__init__(name)
def execute(self, args):
res = RTResult()
exec_ctx = self.generateNewContext()
method_name = f'execute_{self.name}'
method = getattr(self,method_name,self.no_visit_method)
res.register(self.check_and_populate_args(method.arg_names,args,exec_ctx))
if res.error: return res
return_value = res.register(method(exec_ctx))
if res.error: return res
return res.success(return_value)
def no_visit_method(self,node,context):
raise Exception(f'No execute_{self.name} method defined')
def copy(self):
copy = BuiltInFunction(self.name)
copy.set_context(self.context)
copy.set_pos(self.pos_start,self.pos_end)
return copy
def __repr__(self):
return f'<built-in function {self.name}>'
#BuiltIn functions
def execute_output(self,exec_ctx):
print(str(exec_ctx.symbol_table.get('value')))
return RTResult().success(Number(0)) #return null equivalent
execute_output.arg_names = ['value']
def execute_mid(self,exec_ctx):
s = exec_ctx.symbol_table.get('s')
a = exec_ctx.symbol_table.get('a')
b = exec_ctx.symbol_table.get('b')
f = str(s)[a.value - 1 :a.value - 1 + b.value ]
return RTResult().success(Number(String(f)))
execute_mid.arg_names = ['s','a','b']
BuiltInFunction.output = BuiltInFunction('output')
BuiltInFunction.mid = BuiltInFunction('mid')
#context
#--------------------------------------------------
class Context:
def __init__(self,display_name, parent = None, parent_entry_pos = None):
self.display_name = display_name
self.parent = parent
self.parent_entry_pos = parent_entry_pos
self.symbol_table = None
#symbol stable
#--------------------------------------------------
class SymbolTable:
def __init__(self,parent = None):
self.symbols = dict()
self.parent = parent
def get(self,name):
value = self.symbols.get(name, None)
if value == None and self.parent:
return self.parent.get(name)
return value
def set(self, name, value):
self.symbols[name] = value
def remove(self,name):
del self.symbols[name]
#interpreter
#--------------------------------------------------
class Interpreter:
def visit(self,node,context):
method_name = f'visit_{type(node).__name__}'
method = getattr(self,method_name,self.no_visit_method)
return method(node,context)
def no_visit_method(self,node,context):
raise Exception(f'No visit_{type(node).__name__} defined')
def visit_VarAccessNode(self, node, context):
res = RTResult()
var_name = node.var_name_tok.value
value = context.symbol_table.get(var_name)
if not value:
return res.failure(RTError(node.pos_start,
node.pos_end,f"'{var_name} is not defined'",context))
value = value.copy().set_pos(node.pos_start,node.pos_end).set_context(context)
return res.success(value)
def visit_VarAssignNode(self, node, context):
res = RTResult()
var_name = node.var_name_tok.value
value = res.register(self.visit(node.value_node,context))
if res.error: return res
context.symbol_table.set(var_name,value)
return res.success(value)
def visit_NumberNode(self,node,context):
return RTResult().success(
Number(node.tok.value).set_context(context).set_pos(node.pos_start,node.pos_end)
)
def visit_StringNode(self,node,context):
return RTResult().success(
String(node.tok.value).set_context(context).set_pos(node.pos_start,node.pos_end)
)
def visit_ListNode(self,node,context):
res = RTResult()
elements = []
for element_node in node.element_nodes:
elements.append(res.register(self.visit(element_node,context)))
if res.error:return res
return res.success(
List(elements).set_context(context).set_pos(node.pos_start,node.pos_end)
)
def visit_BinOpNode(self,node,context):
res = RTResult()
left = res.register(self.visit(node.left_node,context))
if res.error: return res
right = res.register(self.visit(node.right_node,context))
if res.error: return res
if node.op_tok.type == TT_PLUS or node.op_tok.type:
result,error = left.added_to(right)
if node.op_tok.type == TT_MINUS:
result,error = left.subtracted_by(right)
if node.op_tok.type == TT_MUL:
result,error = left.multiplied_by(right)
if node.op_tok.type == TT_DIV:
result,error = left.divided_by(right)
if node.op_tok.type == TT_POWER:
result,error = left.powered_by(right)
elif node.op_tok.type == TT_EE:
result, error = left.get_comparison_eq(right)
elif node.op_tok.type == TT_NE:
result, error = left.get_comparison_ne(right)
elif node.op_tok.type == TT_LT:
result, error = left.get_comparison_lt(right)
elif node.op_tok.type == TT_GT:
result, error = left.get_comparison_gt(right)
elif node.op_tok.type == TT_LTE:
result, error = left.get_comparison_lte(right)
elif node.op_tok.type == TT_GTE:
result, error = left.get_comparison_gte(right)
elif node.op_tok.matches(TT_KEYWORD, 'AND'):
result, error = left.anded_by(right)
elif node.op_tok.matches(TT_KEYWORD, 'OR'):
result, error = left.ored_by(right)
if error: return res.failure(error)
return res.success(result.set_pos(node.pos_start,node.pos_end))
def visit_UnaryOpNode(self,node,context):
res = RTResult()
number = res.register(self.visit(node.node,context))
if res.error: return res
error = None
if node.op_tok.type == TT_MINUS:
number,error = number.multiplied_by(Number(-1))
elif node.op_tok.matches(TT_KEYWORD, 'NOT'):
number, error = number.notted()
if error: return res.failure(error)
return res.success(number.set_pos(node.pos_start,node.pos_end))
def visit_IfNode(self,node,context):
res = RTResult()
for condition,expr in node.cases:
condition_value = res.register(self.visit(condition,context))
if res.error: return res
if condition_value.is_true():
expr_value = res.register(self.visit(expr,context))
if res.error: return res
return res.success(Number(0)) #returns null eq
if node.else_case:
else_value = res.register(self.visit(node.else_case,context))
if res.error:return res
return res.success(Number(0))
return res.success(Number(0))
def visit_ForNode(self,node,context):
res = RTResult()
elements = []
start_value = res.register(self.visit(node.start_value_node,context))
if res.error:return res
end_value = res.register(self.visit(node.end_value_node,context))
if res.error: return res
if node.step_value_node:
step_value = res.register(self.visit(node.step_value_node,context))
if res.error: return res
else:
step_value = Number(1)
i = start_value.value
if step_value.value >= 0:
condition = lambda: i <= end_value.value
else:
condition = lambda: i >= end_value.value
while condition():
context.symbol_table.set(node.var_name_tok.value,Number(i))
i += step_value.value
elements.append(res.register(self.visit(node.body_node,context)))
if res.error: return res
return res.success(
Number(0)
)
def visit_WhileNode(self,node,context):
res = RTResult()
elements = []
while True:
condition = res.register(self.visit(node.condition_node,context))
if res.error: return res
if not condition.is_true(): break
elements.append(res.register(self.visit(node.body_node,context)))
if res.error: return res
return res.success(
Number(0)
)
def visit_RepeatNode(self,node,context):
res = RTResult()
elements = []
while True:
elements.append(res.register(self.visit(node.body_node,context)))
if res.error: return res
condition = res.register(self.visit(node.condition_node,context))
if res.error: return res
if condition.is_true():break
return res.success(
Number(0)
)
def visit_FuncDefNode(self,node,context):
res = RTResult()
func_name = node.var_name_tok.value if node.var_name_tok else None
body_node = node.body_node
arg_names = [arg_name.value for arg_name in node.arg_name_toks]
func_value = Function(func_name, body_node, arg_names,node.ret_node).set_context(context).set_pos(node.pos_start,
node.pos_end)
if node.var_name_tok:
context.symbol_table.set(func_name, func_value)
return res.success(func_value)
def visit_CallNode(self, node, context):
res = RTResult()
args = []
value_to_call = res.register(self.visit(node.node_to_call, context))
if res.error: return res
value_to_call = value_to_call.copy().set_pos(node.pos_start, node.pos_end)
for arg_node in node.arg_nodes:
args.append(res.register(self.visit(arg_node, context)))
if res.error: return res
return_value = res.register(value_to_call.execute(args))
if res.error: return res
return_value = return_value.copy().set_pos(node.pos_start, node.pos_end).set_context(context)
return res.success(return_value)
#run
#--------------------------------------------------
global_symbol_table = SymbolTable()
global_symbol_table.set('TRUE',Number(1))
global_symbol_table.set('FALSE',Number(0))
global_symbol_table.set('OUTPUT',BuiltInFunction.output)
global_symbol_table.set('MID',BuiltInFunction.mid)
def run(fn,text):
lexer = Lexer(fn,text)
tokens,error = lexer.make_tokens()
if error: return None,error
#generate ast
parser = Parser(tokens)
ast = parser.parse()
if ast.error: return None,ast.error
#runs
interpreter = Interpreter()
context = Context('<program>')
context.symbol_table = global_symbol_table
result = interpreter.visit(ast.node,context)
return result.value,result.error
kindly add the functionality for procedures and arrays, as this is CAIE level psuedocode.
|
8375f4086bd6ad56eb8e500ddcacae46
|
{
"intermediate": 0.30178189277648926,
"beginner": 0.5421352386474609,
"expert": 0.1560828536748886
}
|
38,215
|
global error_det
error_det = ''
import string
from strings_with_arrows import *
from errors import *
from nodes import *
DIGITS = '0123456789'
LETTERS = string.ascii_letters
LETTERS_DIGITS = LETTERS + DIGITS
class Position:
def __init__(self,idx,ln,col,fn,ftxt):
self.fn = fn
self.ftxt = ftxt
self.idx = idx
self.ln = ln
self.col = col
def advance(self,current_char = None):
self.idx += 1
self.col += 1
if current_char == '\n':
self.ln += 1
self.col = 0
return self
def regress(self,current_char = None):
self.idx -= 1
self.col -= 1
def copy(self):
return Position(self.idx,self.ln,self.col,self.fn,self.ftxt)
TT_INT = 'Int'
TT_REAL = 'Real'
TT_STRING = 'String'
TT_IDENTIFIER = 'Identifier'
TT_KEYWORD = 'Keyword'
TT_EQ = 'Eq'
TT_PLUS = 'Plus'
TT_MINUS = 'Minus'
TT_MUL = 'Mul'
TT_DIV = 'Div'
TT_POWER = 'Power'
TT_LPAREN = 'LParen'
TT_RPAREN = "RParen"
TT_LSQUAREBRACKET = 'LSquareBracket'
TT_RSQUAREBRACKET = 'RSquareBracket'
TT_LT = 'NE'
TT_EE = 'EE'
TT_LT = 'LT'
TT_GT = 'GT'
TT_LTE = 'LTE'
TT_GTE = 'GTE'
TT_NE = 'NE'
TT_Comma = 'COMMA'
TT_Arrow = "ARROW"
TT_Newline = 'Newline'
TT_EOF = "Eof"
KEYWORDS = [
'AND',"OR","NOT","IF","ELSE","THEN","FOR","WHILE","DO","STEP","TO","REPEAT","UNTIL","FUNCTION",'RETURNS','ENDIF','ENDFUNCTION','RETURNS','ENDWHILE',"NEXT",'RETURN', 'PROCEDURE', 'ARRAY'
]
class Token:
def __init__(self,type_,value = None, pos_start = None, pos_end = None):
self.type = type_
self.value = value
if pos_start:
self.pos_start = pos_start
self.pos_end = self.pos_start.copy()
self.pos_end.advance()
if pos_end:
self.pos_end = pos_end
def __repr__(self):
if self.value: return f'{self.type}:{self.value}'
return f'{self.type}'
def matches(self,type_,value):
return self.type == type_ and self.value == value
class Lexer:
def __init__(self,fn, text):
self.fn = fn
self.text = text
self.pos = Position(-1,0,-1,fn,text)
self.current_char = None
self.advance()
def advance(self):
self.pos.advance(self.current_char)
self.current_char = self.text[self.pos.idx] if self.pos.idx < len(self.text) else None
def regress(self):
self.pos.regress(self.current_char)
self.current_char = self.text[self.pos.idx] if self.pos.idx < len(self.text) else None
def make_tokens(self):
tokens = []
while self.current_char != None:
if self.current_char in ' \t':
self.advance()
elif self.current_char in ['\n',';']:
tokens.append(Token(TT_Newline,pos_start=self.pos))
self.advance()
elif self.current_char in LETTERS:
tokens.append(self.make_identifier())
elif self.current_char in DIGITS:
tokens.append(self.make_number())
elif self.current_char in ['"',"'"]:
tokens.append(self.make_string(self.current_char))
elif self.current_char == '[':
tokens.append(Token(TT_LSQUAREBRACKET,pos_start = self.pos))
self.advance()
elif self.current_char == ']':
tokens.append(Token(TT_RSQUAREBRACKET,pos_start = self.pos))
self.advance()
elif self.current_char == '+' or self.current_char == '&':
tokens.append(Token(TT_PLUS, pos_start=self.pos))
self.advance()
elif self.current_char == '-':
tokens.append(Token(TT_MINUS, pos_start=self.pos))
self.advance()
elif self.current_char == ':':
tokens.append(Token(TT_Arrow,pos_start=self.pos))
self.advance()
elif self.current_char == '*':
tokens.append(Token(TT_MUL, pos_start=self.pos))
self.advance()
elif self.current_char == '/':
tokens.append(Token(TT_DIV, pos_start=self.pos))
self.advance()
elif self.current_char == '(':
tokens.append(Token(TT_LPAREN, pos_start=self.pos))
self.advance()
elif self.current_char == ')':
tokens.append(Token(TT_RPAREN, pos_start=self.pos))
self.advance()
elif self.current_char == '^':
tokens.append(Token(TT_POWER,pos_start = self.pos))
self.advance()
elif self.current_char == '<':
tok = self.make_not_lessThan_assign()
tokens.append(tok)
elif self.current_char == '=':
tokens.append(Token(TT_EE,pos_start=self.pos))
self.advance()
elif self.current_char == '>':
tokens.append(self.make_greater_than())
elif self.current_char == ',':
tokens.append(Token(TT_Comma, pos_start=self.pos))
self.advance()
else:
pos_start = self.pos.copy()
char = self.current_char
self.advance()
return [],IllegalCharError(pos_start,self.pos,"'" + char + "'")
tokens.append(Token(TT_EOF, pos_start=self.pos))
return tokens, None
def make_string(self,end):
string = ''
pos_start = self.pos.copy()
self.advance()
while self.current_char != None and self.current_char != end:
string += self.current_char
self.advance()
self.advance()
return Token(TT_STRING,string,pos_start,self.pos)
def make_number(self):
num_str = ''
dotCount = 0
pos_start = self.pos.copy()
while self.current_char != None and self.current_char in DIGITS + '.':
if self.current_char == '.':
if dotCount == 1: break
num_str += '.'
dotCount += 1
else:
num_str += self.current_char
self.advance()
if dotCount == 0:
return Token(TT_INT,int(num_str),pos_start,self.pos)
else:
return Token(TT_REAL,float(num_str),pos_start,self.pos)
def make_identifier(self):
id_str = ''
pos_start = self.pos.copy()
while self.current_char != None and self.current_char in LETTERS_DIGITS + '_':
id_str += self.current_char
self.advance()
tok_type = TT_KEYWORD if id_str in KEYWORDS else TT_IDENTIFIER
return Token(tok_type,id_str,pos_start,self.pos)
def make_greater_than(self):
pos_start = self.pos.copy()
self.advance()
if self.current_char == '=':
self.advance()
return Token(TT_GTE,pos_start=pos_start,pos_end=self.pos)
return Token(TT_GT,pos_start=pos_start,pos_end=self.pos)
def make_not_lessThan_assign(self):
pos_start = self.pos.copy()
self.advance()
if self.current_char == '-':
self.advance()
return Token(TT_EQ,pos_start=pos_start,pos_end=self.pos)
elif self.current_char == '>':
self.advance()
return Token(TT_NE,pos_start=pos_start,pos_end=self.pos)
elif self.current_char == '=':
self.advance()
return Token(TT_LTE, pos_start=pos_start, pos_end=self.pos)
else:
return Token(TT_LT, pos_start=pos_start, pos_end=self.pos)
#Parser
#---------------------------------------
class Parser:
def __init__(self,tokens):
self.tokens = tokens
self.hasEq = 0
for q in tokens:
if q.type == TT_EQ:
self.hasEq += 1
self.tok_idx = -1
self.advance()
def advance(self):
self.tok_idx += 1
if self.tok_idx < len(self.tokens):
self.current_tok = self.tokens[self.tok_idx]
return self.current_tok
def regress(self):
self.tok_idx -= 1
self.current_tok = self.tokens[self.tok_idx]
return self.current_tok
def reverse(self,amount = 1):
self.tok_idx -= amount
self.update_current_tok()
return self.current_tok
def update_current_tok(self):
if self.tok_idx >= 0 and self.tok_idx < len(self.tokens):
self.current_tok = self.tokens[self.tok_idx]
def parse(self):
res = self.statements()
if not res.error and self.current_tok.type != TT_EOF:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected '+', '-', '*' or '/'"
))
return res
def statements(self):
res = ParseResult()
statements = []
pos_start = self.current_tok.pos_start.copy()
n = 0
while self.current_tok.type == TT_Newline:
res.register(self.advance())
statement = res.register(self.expr())
if res.error: return res
statements.append(statement)
more_statements = True
while True:
newline_count = 0
while self.current_tok.type == TT_Newline:
res.register(self.advance())
newline_count +=1
if newline_count == 0: more_statements = False
if not more_statements: break
statement = res.try_register(self.expr())
if statement == None:
self.reverse(1)
more_statements = False
continue
statements.append(statement)
return res.success(ListNode(
statements,pos_start,self.current_tok.pos_end.copy()
))
def for_expr(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD,'FOR'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end,f"Expected 'FOR'"))
res.register(self.advance())
if self.current_tok.type != TT_IDENTIFIER:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected identifier"))
var_name = self.current_tok
res.register(self.advance())
if self.current_tok.type != TT_EQ:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, "Expected '<-'"))
res.register(self.advance())
start_value = res.register(self.expr())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'TO'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'TO'"))
res.register(self.advance())
end_value = res.register(self.expr())
if res.error: return res
if self.current_tok.matches(TT_KEYWORD,'STEP'):
res.register(self.advance())
step_value = res.register(self.expr())
if res.error:return res
else:
step_value = None
if not self.current_tok.type == TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline"))
res.register(self.advance())
body = res.register(self.statements())
if res.error:
return res
if not self.current_tok.matches(TT_KEYWORD,'NEXT'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'NEXT'"))
res.register(self.advance())
if not self.current_tok.type == TT_IDENTIFIER:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Identifier"))
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected EOF or Newline"))
return res.success(ForNode(var_name,start_value,end_value,step_value,body))
def while_expr(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD,"WHILE"):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'WHILE'"))
res.register(self.advance())
condition = res.register(self.expr())
if res.error: return res
if self.current_tok.type != TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline"))
res.register(self.advance())
if not self.current_tok.matches(TT_KEYWORD,'DO'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'DO'"))
res.register(self.advance())
if self.current_tok.type != TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline"))
res.register(self.advance())
body = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'ENDWHILE'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'ENDWHILE'"))
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline or EOF"))
return res.success(WhileNode(condition,body))
def repeat_expr(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD,"REPEAT"):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'REPEAT'"))
res.register(self.advance())
if not self.current_tok.type == TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline"))
body = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'UNTIL'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'UNTIL'"))
res.register(self.advance())
condition = res.register(self.expr())
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected newline or EOF"))
return res.success(RepeatNode(body,condition))
def if_expr(self):
res = ParseResult()
cases = []
else_case = None
if not self.current_tok.matches(TT_KEYWORD,'IF'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'IF'"))
res.register(self.advance())
cond = res.register(self.expr())
if res.error: return res
if self.current_tok.type != TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'Newline'"))
res.register(self.advance())
if not self.current_tok.matches(TT_KEYWORD,'THEN'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'THEN'"))
res.register(self.advance())
if self.current_tok.type != TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'Newline'"))
res.register(self.advance())
statements = res.register(self.statements())
if res.error: return res
cases.append((cond,statements))
if self.current_tok.matches(TT_KEYWORD,'ELSE'): #instead of making a separate else-expr I added it here
res.register(self.advance())
if not self.current_tok.type == TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'Newline'"))
else_case = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'ENDIF'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'ENDIF'"))
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected EOF or Newline"))
return res.success(IfNode(cases,else_case))
def call(self):
res = ParseResult()
atom = res.register(self.atom())
if res.error:
return res
if self.current_tok.type == TT_LPAREN:
res.register(self.advance())
arg_nodes = []
if self.current_tok.type == TT_RPAREN:
res.register(self.advance())
else:
tok = self.current_tok
arg_nodes.append(res.register(self.expr()))
if res.error: res.failure(InvalidSyntaxError(tok.pos_start,tok.pos_end,""))
while self.current_tok.type == TT_Comma:
res.register(self.advance())
arg_nodes.append(res.register(self.expr()))
if res.error: return res
if self.current_tok.type != TT_RPAREN:
res.failure(
InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ')' or ','"))
res.register(self.advance())
return res.success(CallNode(atom,arg_nodes))
return res.success(atom)
def atom(self):
res = ParseResult()
tok = self.current_tok
if tok.type in [TT_INT,TT_REAL]:
res.register(self.advance())
return res.success(NumberNode(tok))
if tok.type == TT_STRING:
res.register(self.advance())
return res.success(StringNode(tok))
elif tok.type == TT_IDENTIFIER:
res.register(self.advance())
return res.success(VarAccessNode(tok))
elif tok.type == TT_LPAREN:
res.register(self.advance())
expr = res.register(self.expr())
if res.error: return res
if self.current_tok.type == TT_RPAREN:
res.register(self.advance())
return res.success(expr)
else:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected ')'"
))
elif tok.type == TT_LSQUAREBRACKET:
list_expr = res.register(self.list_expr())
if res.error:
return res
return res.success(list_expr)
elif tok.matches(TT_KEYWORD,'IF'):
if_expr = res.register(self.if_expr())
if res.error: return res
return res.success(if_expr)
elif tok.matches(TT_KEYWORD,'FOR'):
for_expr = res.register(self.for_expr())
if res.error:
return res
return res.success(for_expr)
elif tok.matches(TT_KEYWORD,'WHILE'):
while_expr = res.register(self.while_expr())
if res.error:return res
return res.success(while_expr)
elif tok.matches(TT_KEYWORD,"REPEAT"):
repeat_expr = res.register(self.repeat_expr())
if res.error:
return res
return res.success(repeat_expr)
elif tok.matches(TT_KEYWORD,"FUNCTION"):
function_def = res.register(self.func_def())
if res.error:
return res
return res.success(function_def)
else:
return res.failure(InvalidSyntaxError(tok.pos_start,tok.pos_end,"Expected int,real, '+', '-','(','IF','FOR','WHILE','REPEAT', or 'FUNCTION'"))
def power(self):
return self.bin_op(self.call,(TT_POWER,),self.factor)
def factor(self):
res = ParseResult()
tok = self.current_tok
if tok.type in (TT_PLUS,TT_MINUS):
res.register(self.advance())
factor = res.register(self.factor())
if res.error:
return res
return res.success(UnaryOpNode(tok,factor))
return self.power()
def term(self):
return self.bin_op(self.factor,(TT_DIV,TT_MUL))
def arith_expr(self):
return self.bin_op(self.term,(TT_PLUS,TT_MINUS))
def comp_expr(self):
res = ParseResult()
if self.current_tok.matches(TT_KEYWORD,'NOT'):
op_tok = self.current_tok
res.register(self.advance())
if res.error: return res
node = res.register(self.comp_expr())
if res.error:return res
return res.success(UnaryOpNode(op_tok,node))
node = res.register(self.bin_op(self.arith_expr,(TT_EE,TT_NE,TT_LT,TT_LTE,TT_GT,TT_GTE)))
tok = self.current_tok
if res.error:
return res
return res.success(node)
def expr(self):
res = ParseResult()
if self.current_tok.type == TT_IDENTIFIER:
var_name = self.current_tok
res.register(self.current_tok)
res.register(self.advance())
if self.current_tok.type == TT_EQ:
res.register(self.advance())
expr = res.register(self.expr())
if res.error: return res
return res.success(VarAssignNode(var_name,expr))
self.regress()
return self.bin_op(self.comp_expr,((TT_KEYWORD,'AND'),(TT_KEYWORD,'OR')))
def bin_op(self,func_a,ops,func_b = None):
if func_b == None:
func_b = func_a
res = ParseResult()
left = res.register(func_a())
while self.current_tok.type in ops or (self.current_tok.type, self.current_tok.value) in ops:
op_tok = self.current_tok
res.register(self.advance())
right = res.register(func_b())
if res.error:
return res
left = BinOpNode(left, op_tok, right)
return res.success(left)
def list_expr(self):
res = ParseResult()
element_nodes = []
pos_start = self.current_tok.pos_start.copy()
res.register(self.advance())
if self.current_tok.type == TT_RSQUAREBRACKET:
res.register(self.advance())
else:
tok = self.current_tok
element_nodes.append(res.register(self.expr()))
if res.error: res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ']', 'IF','FOR','WHILE','FUNCTION',variable,datatypoe"))
while self.current_tok.type == TT_Comma:
res.register(self.advance())
element_nodes.append(res.register(self.expr()))
if res.error: return res
if self.current_tok.type != TT_RSQUAREBRACKET:
res.failure(
InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ']' or ','"))
res.register(self.advance())
return ListNode(element_nodes,pos_start,self.current_tok.pos_end.copy())
def func_def(self):
res = ParseResult()
tok = self.current_tok
if not self.current_tok.matches(TT_KEYWORD,'FUNCTION'):
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'FUNCTION'"))
res.register(self.advance())
if self.current_tok.type != TT_IDENTIFIER:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected indentifier"))
var_name_tok = self.current_tok
res.register(self.advance())
if self.current_tok.type != TT_LPAREN:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected '('"))
res.register(self.advance())
arg_name_toks = []
if self.current_tok.type == TT_IDENTIFIER:
arg_name_toks.append(self.current_tok)
res.register(self.advance())
if not self.current_tok.type == TT_Arrow:
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ':'"))
res.register(self.advance())
if not self.current_tok.type == TT_IDENTIFIER or self.current_tok.value not in ['REAL', 'INTEGER', 'CHAR','BOOLEAN', 'STRING']:
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected datatype"))
res.register(self.advance())
while self.current_tok.type == TT_Comma:
res.register(self.advance())
if self.current_tok.type != TT_IDENTIFIER:
tok = self.current_tok
return res.failure(
InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected identifier"))
name = self.current_tok
res.register(self.advance())
if not self.current_tok.type == TT_Arrow:
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ':'"))
res.register(self.advance())
if not self.current_tok.type == TT_IDENTIFIER or self.current_tok.value not in ['REAL', 'INTEGER', 'CHAR', 'BOOLEAN', 'STRING']:
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected datatype"))
arg_name_toks.append(name)
res.register(self.advance())
if self.current_tok.type != TT_RPAREN:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ',' or ')'"))
else:
if self.current_tok.type != TT_RPAREN:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected identifier or ')'"))
res.register(self.advance())
if not self.current_tok.matches(TT_KEYWORD,'RETURNS'):
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'RETURNS'"))
res.register(self.advance())
if self.current_tok.value not in ['INTEGER','REAL','BOOLEAN','STRING','CHAR']:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'INTEGER','REAL','BOOLEAN','STRING' or 'CHAR'"))
res.register(self.advance())
if not self.current_tok.type == TT_Newline:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected Newline'"))
node_to_return = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'RETURN'):
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'RETURN'"))
res.register(self.advance())
expr = res.register(self.expr())
if res.error: return res
res.register(self.advance())
if not self.current_tok.matches(TT_KEYWORD,'ENDFUNCTION'):
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'ENDFUNCTION'"))
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected Newline or EOF'"))
return res.success(FuncDefNode(
var_name_tok,arg_name_toks,node_to_return,expr
))
#runtime result
#-------------------------------------------------
class RTResult:
def __init__(self):
self.value = None
self.error = None
def register(self,res):
if res.error: self.error = res.error
return res.value
def success(self,value):
self.value = value
return self
def failure(self,error):
self.error = error
return self
#values
#-------------------------------------------------
class Value:
def __init__(self):
self.set_context()
self.set_pos()
def set_context(self,context = None):
self.context = context
return self
def set_pos(self,pos_start = None,pos_end = None):
self.pos_start = pos_start
self.pos_end = pos_end
return self
def added_to(self,other):
return None,self.illegal_operation(other)
def subtracted_by(self,other):
return None,self.illegal_operation(other)
def multiplied_by(self,other):
return None,self.illegal_operation(other)
def divided_by(self,other):
return None, self.illegal_operation(other)
def powered_by(self,other):
return None,self.illegal_operation(other)
def get_comparison_eq(self, other):
return None,self.illegal_operation(other)
def get_comparison_ne(self, other):
return None,self.illegal_operation(other)
def get_comparison_lt(self, other):
return None,self.illegal_operation(other)
def get_comparison_gt(self, other):
return None,self.illegal_operation(other)
def get_comparison_lte(self, other):
return None,self.illegal_operation(other)
def get_comparison_gte(self, other):
return None,self.illegal_operation(other)
def anded_by(self, other):
return None,self.illegal_operation(other)
def ored_by(self, other):
return None,self.illegal_operation(other)
def notted(self):
return None,self.illegal_operation(self)
def execute(self, args):
return RTResult().failure(self.illegal_operation())
def copy(self):
raise Exception('No copy method defined')
def is_true(self):
return False
def illegal_operation(self, other=None):
if not other: other = self
return RTError(
self.pos_start, other.pos_end,
'Illegal operation',
self.context
)
class Number(Value):
def __init__(self,value):
self.value = value
super().__init__()
def set_context(self,context = None):
self.context = context
return self
def set_pos(self,pos_start = None,pos_end = None):
self.pos_start = pos_start
self.pos_end = pos_end
return self
def added_to(self,other):
if isinstance(other,Number):
return Number(self.value + other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def subtracted_by(self,other):
if isinstance(other,Number):
return Number(self.value - other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def multiplied_by(self,other):
if isinstance(other,Number):
return Number(self.value * other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def divided_by(self,other):
if isinstance(other,Number):
if other.value == 0:
return None,RTError(
other.pos_start
,other.pos_end,
'Divison by Zero',
self.context
)
return Number(self.value / other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def powered_by(self,other):
if isinstance(other,Number):
return Number(self.value ** other.value).set_context(self.context),None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_eq(self, other):
if isinstance(other, Number):
return Number(int(self.value == other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_ne(self, other):
if isinstance(other, Number):
return Number(int(self.value != other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_lt(self, other):
if isinstance(other, Number):
return Number(int(self.value < other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_gt(self, other):
if isinstance(other, Number):
return Number(int(self.value > other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_lte(self, other):
if isinstance(other, Number):
return Number(int(self.value <= other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_gte(self, other):
if isinstance(other, Number):
return Number(int(self.value >= other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def anded_by(self, other):
if isinstance(other, Number):
return Number(int(self.value and other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def ored_by(self, other):
if isinstance(other, Number):
return Number(int(self.value or other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def notted(self):
return Number(1 if self.value == 0 else 0).set_context(self.context), None
def copy(self):
copy = Number(self.value)
copy.set_pos(self.pos_start,self.pos_end)
copy.set_context(self.context)
return copy
def is_true(self):
return self.value != 0
def __repr__(self):
return f'{self.value}'
class String(Value):
def __init__(self,value):
super().__init__()
self.value = value
def added_to(self,other):
if isinstance(other,String):
return String(self.value + other.value).set_context(self.context),None
else:
return None,Value.illegal_operation(self,other)
def copy(self):
copy = String(self.value)
copy.set_pos(self.pos_start,self.pos_end)
copy.set_context(self.context)
return copy
def __str__(self):
return self.value
def __repr__(self):
return f'"{self.value}"'
class List(Value):
def __init__(self,elements):
super().__init__()
self.elements = elements
def added_to(self,other):
new_list = self.copy()
new_list.elements.append(other)
return new_list,None
def subtracted_by(self,other):
if isinstance(other,Number):
new_list = self.copy()
try:
new_list.elements.pop(other)
return new_list,None
except:
return None,RTError(other.pos_start,other.pos_end,'Element at this indewx is out of bound',self.context)
else:
return None,Value.illegal_operation(self,other)
def multiplied_by(self,other):
if isinstance(other,List):
new_list = self.copy()
new_list.elements.extend(other.elements)
else:
return None,Value.illegal_operation(self,other)
def divided_by(self,other):
if isinstance(other, Number):
try:
return self.elements[other.value],None
except:
return None, RTError(other.pos_start, other.pos_end, 'Element at this indewx is out of bound',
self.context)
else:
return None, Value.illegal_operation(self, other)
def copy(self):
copy = List(self.elements)
copy.set_pos(self.pos_start,self.pos_end)
copy.set_pos(self.context)
return copy
def __repr__(self):
return f"[{','.join([str(x) for x in self.elements])}]"
class BaseFunction(Value):
def __init__(self,name):
super().__init__()
self.name = name
def generateNewContext(self):
new_context = Context(self.name, self.context, self.pos_start)
new_context.symbol_table = SymbolTable(new_context.parent.symbol_table)
return new_context
def check_args(self,arg_names,args):
res = RTResult()
if len(args) > len(arg_names):
return res.failure(RTError(
self.pos_start, self.pos_end,
f"{len(args) - len(arg_names)} too many args passed into '{self.name}'",
self.context
))
if len(args) < len(arg_names):
return res.failure(RTError(
self.pos_start, self.pos_end,
f"{len(arg_names) - len(args)} too few args passed into '{self.name}'",
self.context
))
return res.success(None)
def populate_args(self,arg_names,args,exec_ctx):
for i in range(len(args)):
new_context = exec_ctx
arg_name = arg_names[i]
arg_value = args[i]
arg_value.set_context(new_context)
new_context.symbol_table.set(arg_name, arg_value)
def check_and_populate_args(self,arg_names,args,exec_ctx):
res = RTResult()
res.register(self.check_args(arg_names,args))
if res.error: return res
self.populate_args(arg_names,args,exec_ctx)
return res.success(None)
class Function(BaseFunction):
def __init__(self,name,body_node,arg_names,ret_node):
super().__init__(name)
self.body_node = body_node
self.arg_names = arg_names
self.ret_node = ret_node
def execute(self, args):
res = RTResult()
interpreter = Interpreter()
new_context = self.generateNewContext()
res.register(self.check_and_populate_args(self.arg_names,args,new_context))
if res.error: return res
value = res.register(interpreter.visit(self.body_node, new_context))
if res.error: return res
q = res.register(interpreter.visit(self.ret_node,new_context))
return res.success(q)
def copy(self):
copy = Function(self.name, self.body_node, self.arg_names,self.ret_node)
copy.set_context(self.context)
copy.set_pos(self.pos_start, self.pos_end)
return copy
def __repr__(self):
return f"<function {self.name}>"
class BuiltInFunction(BaseFunction):
def __init__(self,name):
super().__init__(name)
def execute(self, args):
res = RTResult()
exec_ctx = self.generateNewContext()
method_name = f'execute_{self.name}'
method = getattr(self,method_name,self.no_visit_method)
res.register(self.check_and_populate_args(method.arg_names,args,exec_ctx))
if res.error: return res
return_value = res.register(method(exec_ctx))
if res.error: return res
return res.success(return_value)
def no_visit_method(self,node,context):
raise Exception(f'No execute_{self.name} method defined')
def copy(self):
copy = BuiltInFunction(self.name)
copy.set_context(self.context)
copy.set_pos(self.pos_start,self.pos_end)
return copy
def __repr__(self):
return f'<built-in function {self.name}>'
#BuiltIn functions
def execute_output(self,exec_ctx):
print(str(exec_ctx.symbol_table.get('value')))
return RTResult().success(Number(0)) #return null equivalent
execute_output.arg_names = ['value']
def execute_mid(self,exec_ctx):
s = exec_ctx.symbol_table.get('s')
a = exec_ctx.symbol_table.get('a')
b = exec_ctx.symbol_table.get('b')
f = str(s)[a.value - 1 :a.value - 1 + b.value ]
return RTResult().success(Number(String(f)))
execute_mid.arg_names = ['s','a','b']
BuiltInFunction.output = BuiltInFunction('output')
BuiltInFunction.mid = BuiltInFunction('mid')
#context
#--------------------------------------------------
class Context:
def __init__(self,display_name, parent = None, parent_entry_pos = None):
self.display_name = display_name
self.parent = parent
self.parent_entry_pos = parent_entry_pos
self.symbol_table = None
#symbol stable
#--------------------------------------------------
class SymbolTable:
def __init__(self,parent = None):
self.symbols = dict()
self.parent = parent
def get(self,name):
value = self.symbols.get(name, None)
if value == None and self.parent:
return self.parent.get(name)
return value
def set(self, name, value):
self.symbols[name] = value
def remove(self,name):
del self.symbols[name]
#interpreter
#--------------------------------------------------
class Interpreter:
def visit(self,node,context):
method_name = f'visit_{type(node).__name__}'
method = getattr(self,method_name,self.no_visit_method)
return method(node,context)
def no_visit_method(self,node,context):
raise Exception(f'No visit_{type(node).__name__} defined')
def visit_VarAccessNode(self, node, context):
res = RTResult()
var_name = node.var_name_tok.value
value = context.symbol_table.get(var_name)
if not value:
return res.failure(RTError(node.pos_start,
node.pos_end,f"'{var_name} is not defined'",context))
value = value.copy().set_pos(node.pos_start,node.pos_end).set_context(context)
return res.success(value)
def visit_VarAssignNode(self, node, context):
res = RTResult()
var_name = node.var_name_tok.value
value = res.register(self.visit(node.value_node,context))
if res.error: return res
context.symbol_table.set(var_name,value)
return res.success(value)
def visit_NumberNode(self,node,context):
return RTResult().success(
Number(node.tok.value).set_context(context).set_pos(node.pos_start,node.pos_end)
)
def visit_StringNode(self,node,context):
return RTResult().success(
String(node.tok.value).set_context(context).set_pos(node.pos_start,node.pos_end)
)
def visit_ListNode(self,node,context):
res = RTResult()
elements = []
for element_node in node.element_nodes:
elements.append(res.register(self.visit(element_node,context)))
if res.error:return res
return res.success(
List(elements).set_context(context).set_pos(node.pos_start,node.pos_end)
)
def visit_BinOpNode(self,node,context):
res = RTResult()
left = res.register(self.visit(node.left_node,context))
if res.error: return res
right = res.register(self.visit(node.right_node,context))
if res.error: return res
if node.op_tok.type == TT_PLUS or node.op_tok.type:
result,error = left.added_to(right)
if node.op_tok.type == TT_MINUS:
result,error = left.subtracted_by(right)
if node.op_tok.type == TT_MUL:
result,error = left.multiplied_by(right)
if node.op_tok.type == TT_DIV:
result,error = left.divided_by(right)
if node.op_tok.type == TT_POWER:
result,error = left.powered_by(right)
elif node.op_tok.type == TT_EE:
result, error = left.get_comparison_eq(right)
elif node.op_tok.type == TT_NE:
result, error = left.get_comparison_ne(right)
elif node.op_tok.type == TT_LT:
result, error = left.get_comparison_lt(right)
elif node.op_tok.type == TT_GT:
result, error = left.get_comparison_gt(right)
elif node.op_tok.type == TT_LTE:
result, error = left.get_comparison_lte(right)
elif node.op_tok.type == TT_GTE:
result, error = left.get_comparison_gte(right)
elif node.op_tok.matches(TT_KEYWORD, 'AND'):
result, error = left.anded_by(right)
elif node.op_tok.matches(TT_KEYWORD, 'OR'):
result, error = left.ored_by(right)
if error: return res.failure(error)
return res.success(result.set_pos(node.pos_start,node.pos_end))
def visit_UnaryOpNode(self,node,context):
res = RTResult()
number = res.register(self.visit(node.node,context))
if res.error: return res
error = None
if node.op_tok.type == TT_MINUS:
number,error = number.multiplied_by(Number(-1))
elif node.op_tok.matches(TT_KEYWORD, 'NOT'):
number, error = number.notted()
if error: return res.failure(error)
return res.success(number.set_pos(node.pos_start,node.pos_end))
def visit_IfNode(self,node,context):
res = RTResult()
for condition,expr in node.cases:
condition_value = res.register(self.visit(condition,context))
if res.error: return res
if condition_value.is_true():
expr_value = res.register(self.visit(expr,context))
if res.error: return res
return res.success(Number(0)) #returns null eq
if node.else_case:
else_value = res.register(self.visit(node.else_case,context))
if res.error:return res
return res.success(Number(0))
return res.success(Number(0))
def visit_ForNode(self,node,context):
res = RTResult()
elements = []
start_value = res.register(self.visit(node.start_value_node,context))
if res.error:return res
end_value = res.register(self.visit(node.end_value_node,context))
if res.error: return res
if node.step_value_node:
step_value = res.register(self.visit(node.step_value_node,context))
if res.error: return res
else:
step_value = Number(1)
i = start_value.value
if step_value.value >= 0:
condition = lambda: i <= end_value.value
else:
condition = lambda: i >= end_value.value
while condition():
context.symbol_table.set(node.var_name_tok.value,Number(i))
i += step_value.value
elements.append(res.register(self.visit(node.body_node,context)))
if res.error: return res
return res.success(
Number(0)
)
def visit_WhileNode(self,node,context):
res = RTResult()
elements = []
while True:
condition = res.register(self.visit(node.condition_node,context))
if res.error: return res
if not condition.is_true(): break
elements.append(res.register(self.visit(node.body_node,context)))
if res.error: return res
return res.success(
Number(0)
)
def visit_RepeatNode(self,node,context):
res = RTResult()
elements = []
while True:
elements.append(res.register(self.visit(node.body_node,context)))
if res.error: return res
condition = res.register(self.visit(node.condition_node,context))
if res.error: return res
if condition.is_true():break
return res.success(
Number(0)
)
def visit_FuncDefNode(self,node,context):
res = RTResult()
func_name = node.var_name_tok.value if node.var_name_tok else None
body_node = node.body_node
arg_names = [arg_name.value for arg_name in node.arg_name_toks]
func_value = Function(func_name, body_node, arg_names,node.ret_node).set_context(context).set_pos(node.pos_start,
node.pos_end)
if node.var_name_tok:
context.symbol_table.set(func_name, func_value)
return res.success(func_value)
def visit_CallNode(self, node, context):
res = RTResult()
args = []
value_to_call = res.register(self.visit(node.node_to_call, context))
if res.error: return res
value_to_call = value_to_call.copy().set_pos(node.pos_start, node.pos_end)
for arg_node in node.arg_nodes:
args.append(res.register(self.visit(arg_node, context)))
if res.error: return res
return_value = res.register(value_to_call.execute(args))
if res.error: return res
return_value = return_value.copy().set_pos(node.pos_start, node.pos_end).set_context(context)
return res.success(return_value)
#run
#--------------------------------------------------
global_symbol_table = SymbolTable()
global_symbol_table.set('TRUE',Number(1))
global_symbol_table.set('FALSE',Number(0))
global_symbol_table.set('OUTPUT',BuiltInFunction.output)
global_symbol_table.set('MID',BuiltInFunction.mid)
def run(fn,text):
lexer = Lexer(fn,text)
tokens,error = lexer.make_tokens()
if error: return None,error
#generate ast
parser = Parser(tokens)
ast = parser.parse()
if ast.error: return None,ast.error
#runs
interpreter = Interpreter()
context = Context('<program>')
context.symbol_table = global_symbol_table
result = interpreter.visit(ast.node,context)
return result.value,result.error
so this is the interpreter i made for CAIE level psuedocode, pls add the procedure and array functionality for it, including yk specifying the number of possible elements in the array and the data type, raising errors in case the appended value doesn't match the data type of the array etc. the node.py file and the error.py file are given.
class NumberNode:
def __init__(self,tok):
self.tok = tok
self.pos_start = self.tok.pos_start
self.pos_end = self.tok.pos_end
def __repr__(self):
return f'{self.tok}'
class StringNode:
def __init__(self,tok):
self.tok = tok
self.pos_start = self.tok.pos_start
self.pos_end = self.tok.pos_end
def __repr__(self):
return f'{self.tok}'
class ListNode:
def __init__(self,element_nodes,pos_start,pos_end):
self.element_nodes = element_nodes
self.pos_start = pos_start
self.pos_end = pos_end
class VarAccessNode:
def __init__(self,var_name_tok):
self.var_name_tok = var_name_tok
self.pos_start = var_name_tok.pos_start
self.pos_end = var_name_tok.pos_end
class VarAssignNode:
def __init__(self,var_name_tok, value_node):
self.var_name_tok = var_name_tok
self.value_node = value_node
self.pos_start = var_name_tok.pos_start
self.pos_end = var_name_tok.pos_end
class BinOpNode:
def __init__(self,left_node,op_tok,right_node):
self.left_node = left_node
self.op_tok = op_tok
self.right_node = right_node
self.pos_start = self.left_node.pos_start
self.pos_end = self.right_node.pos_end
def __repr__(self):
return f'({self.left_node},{self.op_tok},{self.right_node})'
class UnaryOpNode:
def __init__(self,op_tok,node):
self.op_tok = op_tok
self.node = node
self.pos_start = self.op_tok.pos_start
self.pos_end = self.op_tok.pos_end
def __repr__(self):
return f'({self.op_tok}, {self.node})'
class IfNode:
def __init__(self,cases,else_case):
self.cases = cases
self.else_case = else_case
self.pos_start = self.cases[0][0].pos_start
self.pos_end = (self.else_case or self.cases[-1][0]).pos_end
class ForNode:
def __init__(self,var_name_tok,start_value_node,end_value_node,step_value_node,body_ode):
self.var_name_tok = var_name_tok
self.start_value_node = start_value_node
self.end_value_node = end_value_node
self.step_value_node = step_value_node
self.body_node = body_ode
self.pos_start=self.var_name_tok.pos_start
self.pos_end = self.body_node.pos_end
class WhileNode:
def __init__(self,condition_node,body_node):
self.condition_node = condition_node
self.body_node = body_node
self.pos_start = self.condition_node.pos_start
self.pos_end = self.body_node.pos_end
class RepeatNode:
def __init__(self,body_node,condition_node):
self.condition_node = condition_node
self.body_node = body_node
self.pos_start = self.body_node.pos_start
self.pos_end = self.condition_node.pos_end
class FuncDefNode:
def __init__(self,var_name_tok,arg_name_toks,body_nodes,ret_node):
self.var_name_tok = var_name_tok
self.arg_name_toks = arg_name_toks
self.body_node = body_nodes
self.pos_start = self.var_name_tok.pos_start
self.ret_node = ret_node
self.pos_end = self.body_node.pos_end
class CallNode:
def __init__(self,node_to_call,arg_node):
self.node_to_call = node_to_call
self.arg_nodes = arg_node
self.pos_start = self.node_to_call.pos_start
if len(self.arg_nodes) > 0:
self.pos_end = self.arg_nodes[-1].pos_end
else:
self.pos_end = self.node_to_call.pos_end
#Parser result
#---------------------------------------
class ParseResult:
def __init__(self):
self.error = None
self.node = None
self.advance_count = 0
self.to_reverse_count = 0
def register(self,res):
if isinstance(res,ParseResult):
if res.error: self.error = res.error
self.advance_count += res.advance_count
return res.node
self.advance_count += 1
return res
def success(self,node):
self.node = node
return self
def failure(self, error):
self.error = error
return self
def try_register(self,res):
if res.error:
self.to_reverse_count = res.advance_count
res.error = None
return None
return res.register(res)
thats nodes.py
|
8ef7df9501daa51f5f64b969534bea48
|
{
"intermediate": 0.30178189277648926,
"beginner": 0.5421352386474609,
"expert": 0.1560828536748886
}
|
38,216
|
write a pytorch code for adaptation layer
|
fd9f45246df6f57c784caf61694124cb
|
{
"intermediate": 0.1905246376991272,
"beginner": 0.1651991903781891,
"expert": 0.6442761421203613
}
|
38,217
|
write a pytorch function for 1 × 1 convolutions adatation layer to match the two feature maps output size
|
5ae88326488119bbe7262feca88b0173
|
{
"intermediate": 0.19329316914081573,
"beginner": 0.120643250644207,
"expert": 0.6860635876655579
}
|
38,218
|
global error_det
error_det = ''
import string
from strings_with_arrows import *
from errors import *
from nodes import *
DIGITS = '0123456789'
LETTERS = string.ascii_letters
LETTERS_DIGITS = LETTERS + DIGITS
class Position:
def __init__(self,idx,ln,col,fn,ftxt):
self.fn = fn
self.ftxt = ftxt
self.idx = idx
self.ln = ln
self.col = col
def advance(self,current_char = None):
self.idx += 1
self.col += 1
if current_char == '\n':
self.ln += 1
self.col = 0
return self
def regress(self,current_char = None):
self.idx -= 1
self.col -= 1
def copy(self):
return Position(self.idx,self.ln,self.col,self.fn,self.ftxt)
TT_INT = 'Int'
TT_REAL = 'Real'
TT_STRING = 'String'
TT_BOOLEAN = 'Boolean'
TT_CHAR = 'Char'
TT_IDENTIFIER = 'Identifier'
TT_KEYWORD = 'Keyword'
TT_EQ = 'Eq'
TT_PLUS = 'Plus'
TT_MINUS = 'Minus'
TT_MUL = 'Mul'
TT_DIV = 'Div'
TT_POWER = 'Power'
TT_LPAREN = 'LParen'
TT_RPAREN = "RParen"
TT_LSQUAREBRACKET = 'LSquareBracket'
TT_RSQUAREBRACKET = 'RSquareBracket'
TT_LT = 'NE'
TT_EE = 'EE'
TT_LT = 'LT'
TT_GT = 'GT'
TT_LTE = 'LTE'
TT_GTE = 'GTE'
TT_NE = 'NE'
TT_Comma = 'COMMA'
TT_Arrow = "ARROW"
TT_Newline = 'Newline'
TT_EOF = "Eof"
TT_ARRAY = 'ARRAY'
TT_PROCEDURE = 'PROCEDURE'
TT_END_PROCEDURE = 'ENDPROCEDURE'
KEYWORDS = [
'AND',"OR","NOT","IF","ELSE","THEN","FOR","WHILE","DO","STEP","TO","REPEAT","UNTIL","FUNCTION",'RETURNS','ENDIF','ENDFUNCTION','RETURNS','ENDWHILE',"NEXT",'RETURN', 'PROCEDURE', 'ARRAY'
]
ALLOWED_ARRAY_TYPES = ['INTEGER', 'REAL', 'STRING', 'BOOLEAN', 'CHAR']
class Token:
def __init__(self,type_,value = None, pos_start = None, pos_end = None):
self.type = type_
self.value = value
if pos_start:
self.pos_start = pos_start
self.pos_end = self.pos_start.copy()
self.pos_end.advance()
if pos_end:
self.pos_end = pos_end
def __repr__(self):
if self.value: return f'{self.type}:{self.value}'
return f'{self.type}'
def matches(self,type_,value):
return self.type == type_ and self.value == value
class Lexer:
def __init__(self,fn, text):
self.fn = fn
self.text = text
self.pos = Position(-1,0,-1,fn,text)
self.current_char = None
self.advance()
def advance(self):
self.pos.advance(self.current_char)
self.current_char = self.text[self.pos.idx] if self.pos.idx < len(self.text) else None
def regress(self):
self.pos.regress(self.current_char)
self.current_char = self.text[self.pos.idx] if self.pos.idx < len(self.text) else None
def make_array(self):
pos_start = self.pos.copy()
self.advance() # Skip the '['
min_value = self.make_expr()
if not min_value:
return [], InvalidSyntaxError(pos_start, self.pos, "Expected a number or expression after '['")
if self.current_char != ':':
return [], InvalidSyntaxError(pos_start, self.pos, "Expected ':' in array declaration")
self.advance() # Skip the ':'
max_value = self.make_expr()
if not max_value:
return [], InvalidSyntaxError(pos_start, self.pos, "Expected a number or expression after ':' in array declaration")
if self.current_char != ']':
return [], InvalidSyntaxError(pos_start, self.pos, "Expected ']' in array declaration")
self.advance() # Skip the ']'
if self.current_char != 'OF':
return [], InvalidSyntaxError(pos_start, self.pos, "Expected 'OF' in array declaration")
self.advance() # Skip 'OF'
array_type = self.make_identifier()
if array_type not in ALLOWED_ARRAY_TYPES:
return [], InvalidSyntaxError(pos_start, self.pos, f"Expected one of {ALLOWED_ARRAY_TYPES} in array declaration")
return [Token(TT_ARRAY, (min_value, max_value, array_type), pos_start, self.pos)], None
def make_tokens(self):
tokens = []
while self.current_char is not None:
if self.current_char in ' \t':
self.advance()
elif self.current_char in ['\n', ';']:
tokens.append(Token(TT_Newline, pos_start=self.pos))
self.advance()
elif self.current_char in LETTERS:
tokens.append(self.make_identifier())
elif self.current_char in DIGITS:
tokens.append(self.make_number())
elif self.current_char in ['"', "'"]:
tokens.append(self.make_string(self.current_char))
elif self.current_char == '[':
array_tokens, error = self.make_array()
if error:
return [], error
tokens += array_tokens
elif self.current_char == ']':
tokens.append(Token(TT_RSQUAREBRACKET, pos_start=self.pos))
self.advance()
elif self.current_char == '+':
tokens.append(Token(TT_PLUS, pos_start=self.pos))
self.advance()
elif self.current_char == '-':
tokens.append(Token(TT_MINUS, pos_start=self.pos))
self.advance()
elif self.current_char == ':':
tokens.append(Token(TT_Arrow, pos_start=self.pos))
self.advance()
elif self.current_char == '*':
tokens.append(Token(TT_MUL, pos_start=self.pos))
self.advance()
elif self.current_char == '/':
tokens.append(Token(TT_DIV, pos_start=self.pos))
self.advance()
elif self.current_char == '(':
tokens.append(Token(TT_LPAREN, pos_start=self.pos))
self.advance()
elif self.current_char == ')':
tokens.append(Token(TT_RPAREN, pos_start=self.pos))
self.advance()
elif self.current_char == '^':
tokens.append(Token(TT_POWER, pos_start=self.pos))
self.advance()
elif self.current_char == '<':
tok = self.make_not_lessThan_assign()
tokens.append(tok)
elif self.current_char == '>':
tokens.append(self.make_greater_than())
elif self.current_char == ',':
tokens.append(Token(TT_Comma, pos_start=self.pos))
self.advance()
elif self.current_char == 'P':
tok = self.make_keyword()
if tok.value == 'PROCEDURE':
tokens.append(Token(TT_PROCEDURE, pos_start=tok.pos_start, pos_end=tok.pos_end))
elif tok.value == 'ENDPROCEDURE':
tokens.append(Token(TT_END_PROCEDURE, pos_start=tok.pos_start, pos_end=tok.pos_end))
else:
return [], IllegalCharError(tok.pos_start, tok.pos_end, f"Unexpected character '{self.current_char}'")
else:
pos_start = self.pos.copy()
char = self.current_char
self.advance()
return [], IllegalCharError(pos_start, self.pos, "'" + char + "'")
tokens.append(Token(TT_EOF, pos_start=self.pos))
return tokens, None
def make_string(self,end):
string = ''
pos_start = self.pos.copy()
self.advance()
while self.current_char != None and self.current_char != end:
string += self.current_char
self.advance()
self.advance()
return Token(TT_STRING,string,pos_start,self.pos)
def make_number(self):
num_str = ''
dotCount = 0
pos_start = self.pos.copy()
while self.current_char != None and self.current_char in DIGITS + '.':
if self.current_char == '.':
if dotCount == 1: break
num_str += '.'
dotCount += 1
else:
num_str += self.current_char
self.advance()
if dotCount == 0:
return Token(TT_INT,int(num_str),pos_start,self.pos)
else:
return Token(TT_REAL,float(num_str),pos_start,self.pos)
def make_identifier(self):
id_str = ''
pos_start = self.pos.copy()
while self.current_char != None and self.current_char in LETTERS_DIGITS + '_':
id_str += self.current_char
self.advance()
tok_type = TT_KEYWORD if id_str in KEYWORDS else TT_IDENTIFIER
return Token(tok_type,id_str,pos_start,self.pos)
def make_greater_than(self):
pos_start = self.pos.copy()
self.advance()
if self.current_char == '=':
self.advance()
return Token(TT_GTE,pos_start=pos_start,pos_end=self.pos)
return Token(TT_GT,pos_start=pos_start,pos_end=self.pos)
def make_not_lessThan_assign(self):
pos_start = self.pos.copy()
self.advance()
if self.current_char == '-':
self.advance()
return Token(TT_EQ,pos_start=pos_start,pos_end=self.pos)
elif self.current_char == '>':
self.advance()
return Token(TT_NE,pos_start=pos_start,pos_end=self.pos)
elif self.current_char == '=':
self.advance()
return Token(TT_LTE, pos_start=pos_start, pos_end=self.pos)
else:
return Token(TT_LT, pos_start=pos_start, pos_end=self.pos)
so far these are my tokens and lexer for a pseudocode engine that has arrays and procedures and the other stuff.
|
7f25f829b2955ff01410a5c32ade05f7
|
{
"intermediate": 0.31928038597106934,
"beginner": 0.4573437571525574,
"expert": 0.2233758419752121
}
|
38,219
|
global error_det
error_det = ''
import string
from strings_with_arrows import *
from errors import *
from nodes import *
DIGITS = '0123456789'
LETTERS = string.ascii_letters
LETTERS_DIGITS = LETTERS + DIGITS
class Position:
def __init__(self,idx,ln,col,fn,ftxt):
self.fn = fn
self.ftxt = ftxt
self.idx = idx
self.ln = ln
self.col = col
def advance(self,current_char = None):
self.idx += 1
self.col += 1
if current_char == '\n':
self.ln += 1
self.col = 0
return self
def regress(self,current_char = None):
self.idx -= 1
self.col -= 1
def copy(self):
return Position(self.idx,self.ln,self.col,self.fn,self.ftxt)
TT_INT = 'Int'
TT_REAL = 'Real'
TT_STRING = 'String'
TT_BOOLEAN = 'Boolean'
TT_CHAR = 'Char'
TT_IDENTIFIER = 'Identifier'
TT_KEYWORD = 'Keyword'
TT_EQ = 'Eq'
TT_PLUS = 'Plus'
TT_MINUS = 'Minus'
TT_MUL = 'Mul'
TT_DIV = 'Div'
TT_POWER = 'Power'
TT_LPAREN = 'LParen'
TT_RPAREN = "RParen"
TT_LSQUAREBRACKET = 'LSquareBracket'
TT_RSQUAREBRACKET = 'RSquareBracket'
TT_LT = 'NE'
TT_EE = 'EE'
TT_LT = 'LT'
TT_GT = 'GT'
TT_LTE = 'LTE'
TT_GTE = 'GTE'
TT_NE = 'NE'
TT_Comma = 'COMMA'
TT_Arrow = "ARROW"
TT_Newline = 'Newline'
TT_EOF = "Eof"
TT_ARRAY = 'ARRAY'
TT_PROCEDURE = 'PROCEDURE'
TT_END_PROCEDURE = 'ENDPROCEDURE'
KEYWORDS = [
'AND',"OR","NOT","IF","ELSE","THEN","FOR","WHILE","DO","STEP","TO","REPEAT","UNTIL","FUNCTION",'RETURNS','ENDIF','ENDFUNCTION','RETURNS','ENDWHILE',"NEXT",'RETURN', 'PROCEDURE', 'ARRAY'
]
ALLOWED_ARRAY_TYPES = ['INTEGER', 'REAL', 'STRING', 'BOOLEAN', 'CHAR']
class Token:
def __init__(self,type_,value = None, pos_start = None, pos_end = None):
self.type = type_
self.value = value
if pos_start:
self.pos_start = pos_start
self.pos_end = self.pos_start.copy()
self.pos_end.advance()
if pos_end:
self.pos_end = pos_end
def __repr__(self):
if self.value: return f'{self.type}:{self.value}'
return f'{self.type}'
def matches(self,type_,value):
return self.type == type_ and self.value == value
class Lexer:
def __init__(self,fn, text):
self.fn = fn
self.text = text
self.pos = Position(-1,0,-1,fn,text)
self.current_char = None
self.advance()
def advance(self):
self.pos.advance(self.current_char)
self.current_char = self.text[self.pos.idx] if self.pos.idx < len(self.text) else None
def regress(self):
self.pos.regress(self.current_char)
self.current_char = self.text[self.pos.idx] if self.pos.idx < len(self.text) else None
def make_array(self):
pos_start = self.pos.copy()
self.advance() # Skip the '['
min_value = self.make_expr()
if not min_value:
return [], InvalidSyntaxError(pos_start, self.pos, "Expected a number or expression after '['")
if self.current_char != ':':
return [], InvalidSyntaxError(pos_start, self.pos, "Expected ':' in array declaration")
self.advance() # Skip the ':'
max_value = self.make_expr()
if not max_value:
return [], InvalidSyntaxError(pos_start, self.pos, "Expected a number or expression after ':' in array declaration")
if self.current_char != ']':
return [], InvalidSyntaxError(pos_start, self.pos, "Expected ']' in array declaration")
self.advance() # Skip the ']'
if self.current_char != 'OF':
return [], InvalidSyntaxError(pos_start, self.pos, "Expected 'OF' in array declaration")
self.advance() # Skip 'OF'
array_type = self.make_identifier()
if array_type not in ALLOWED_ARRAY_TYPES:
return [], InvalidSyntaxError(pos_start, self.pos, f"Expected one of {ALLOWED_ARRAY_TYPES} in array declaration")
return [Token(TT_ARRAY, (min_value, max_value, array_type), pos_start, self.pos)], None
def make_tokens(self):
tokens = []
while self.current_char is not None:
if self.current_char in ' \t':
self.advance()
elif self.current_char in ['\n', ';']:
tokens.append(Token(TT_Newline, pos_start=self.pos))
self.advance()
elif self.current_char in LETTERS:
tokens.append(self.make_identifier())
elif self.current_char in DIGITS:
tokens.append(self.make_number())
elif self.current_char in ['"', "'"]:
tokens.append(self.make_string(self.current_char))
elif self.current_char == '[':
array_tokens, error = self.make_array()
if error:
return [], error
tokens += array_tokens
elif self.current_char == ']':
tokens.append(Token(TT_RSQUAREBRACKET, pos_start=self.pos))
self.advance()
elif self.current_char == '+':
tokens.append(Token(TT_PLUS, pos_start=self.pos))
self.advance()
elif self.current_char == '-':
tokens.append(Token(TT_MINUS, pos_start=self.pos))
self.advance()
elif self.current_char == ':':
tokens.append(Token(TT_Arrow, pos_start=self.pos))
self.advance()
elif self.current_char == '*':
tokens.append(Token(TT_MUL, pos_start=self.pos))
self.advance()
elif self.current_char == '/':
tokens.append(Token(TT_DIV, pos_start=self.pos))
self.advance()
elif self.current_char == '(':
tokens.append(Token(TT_LPAREN, pos_start=self.pos))
self.advance()
elif self.current_char == ')':
tokens.append(Token(TT_RPAREN, pos_start=self.pos))
self.advance()
elif self.current_char == '^':
tokens.append(Token(TT_POWER, pos_start=self.pos))
self.advance()
elif self.current_char == '<':
tok = self.make_not_lessThan_assign()
tokens.append(tok)
elif self.current_char == '>':
tokens.append(self.make_greater_than())
elif self.current_char == ',':
tokens.append(Token(TT_Comma, pos_start=self.pos))
self.advance()
elif self.current_char == 'P':
tok = self.make_keyword()
if tok.value == 'PROCEDURE':
tokens.append(Token(TT_PROCEDURE, pos_start=tok.pos_start, pos_end=tok.pos_end))
elif tok.value == 'ENDPROCEDURE':
tokens.append(Token(TT_END_PROCEDURE, pos_start=tok.pos_start, pos_end=tok.pos_end))
else:
return [], IllegalCharError(tok.pos_start, tok.pos_end, f"Unexpected character '{self.current_char}'")
else:
pos_start = self.pos.copy()
char = self.current_char
self.advance()
return [], IllegalCharError(pos_start, self.pos, "'" + char + "'")
tokens.append(Token(TT_EOF, pos_start=self.pos))
return tokens, None
def make_string(self,end):
string = ''
pos_start = self.pos.copy()
self.advance()
while self.current_char != None and self.current_char != end:
string += self.current_char
self.advance()
self.advance()
return Token(TT_STRING,string,pos_start,self.pos)
def make_number(self):
num_str = ''
dotCount = 0
pos_start = self.pos.copy()
while self.current_char != None and self.current_char in DIGITS + '.':
if self.current_char == '.':
if dotCount == 1: break
num_str += '.'
dotCount += 1
else:
num_str += self.current_char
self.advance()
if dotCount == 0:
return Token(TT_INT,int(num_str),pos_start,self.pos)
else:
return Token(TT_REAL,float(num_str),pos_start,self.pos)
def make_identifier(self):
id_str = ''
pos_start = self.pos.copy()
while self.current_char != None and self.current_char in LETTERS_DIGITS + '_':
id_str += self.current_char
self.advance()
tok_type = TT_KEYWORD if id_str in KEYWORDS else TT_IDENTIFIER
return Token(tok_type,id_str,pos_start,self.pos)
def make_greater_than(self):
pos_start = self.pos.copy()
self.advance()
if self.current_char == '=':
self.advance()
return Token(TT_GTE,pos_start=pos_start,pos_end=self.pos)
return Token(TT_GT,pos_start=pos_start,pos_end=self.pos)
def make_not_lessThan_assign(self):
pos_start = self.pos.copy()
self.advance()
if self.current_char == '-':
self.advance()
return Token(TT_EQ,pos_start=pos_start,pos_end=self.pos)
elif self.current_char == '>':
self.advance()
return Token(TT_NE,pos_start=pos_start,pos_end=self.pos)
elif self.current_char == '=':
self.advance()
return Token(TT_LTE, pos_start=pos_start, pos_end=self.pos)
else:
return Token(TT_LT, pos_start=pos_start, pos_end=self.pos)
#Parser
#---------------------------------------
class Parser:
def __init__(self,tokens):
self.tokens = tokens
self.hasEq = 0
for q in tokens:
if q.type == TT_EQ:
self.hasEq += 1
self.tok_idx = -1
self.advance()
def advance(self):
self.tok_idx += 1
if self.tok_idx < len(self.tokens):
self.current_tok = self.tokens[self.tok_idx]
return self.current_tok
def regress(self):
self.tok_idx -= 1
self.current_tok = self.tokens[self.tok_idx]
return self.current_tok
def reverse(self,amount = 1):
self.tok_idx -= amount
self.update_current_tok()
return self.current_tok
def update_current_tok(self):
if self.tok_idx >= 0 and self.tok_idx < len(self.tokens):
self.current_tok = self.tokens[self.tok_idx]
def parse(self):
res = self.statements()
if not res.error and self.current_tok.type != TT_EOF:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected '+', '-', '*' or '/'"
))
return res
def statements(self):
res = ParseResult()
statements = []
pos_start = self.current_tok.pos_start.copy()
n = 0
while self.current_tok.type == TT_Newline:
res.register(self.advance())
statement = res.register(self.expr())
if res.error: return res
statements.append(statement)
more_statements = True
while True:
newline_count = 0
while self.current_tok.type == TT_Newline:
res.register(self.advance())
newline_count +=1
if newline_count == 0: more_statements = False
if not more_statements: break
statement = res.try_register(self.expr())
if statement == None:
self.reverse(1)
more_statements = False
continue
statements.append(statement)
return res.success(ListNode(
statements,pos_start,self.current_tok.pos_end.copy()
))
def for_expr(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD,'FOR'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end,f"Expected 'FOR'"))
res.register(self.advance())
if self.current_tok.type != TT_IDENTIFIER:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected identifier"))
var_name = self.current_tok
res.register(self.advance())
if self.current_tok.type != TT_EQ:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, "Expected '<-'"))
res.register(self.advance())
start_value = res.register(self.expr())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'TO'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'TO'"))
res.register(self.advance())
end_value = res.register(self.expr())
if res.error: return res
if self.current_tok.matches(TT_KEYWORD,'STEP'):
res.register(self.advance())
step_value = res.register(self.expr())
if res.error:return res
else:
step_value = None
if not self.current_tok.type == TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline"))
res.register(self.advance())
body = res.register(self.statements())
if res.error:
return res
if not self.current_tok.matches(TT_KEYWORD,'NEXT'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'NEXT'"))
res.register(self.advance())
if not self.current_tok.type == TT_IDENTIFIER:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Identifier"))
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected EOF or Newline"))
return res.success(ForNode(var_name,start_value,end_value,step_value,body))
def array_expr(self):
res = ParseResult()
pos_start = self.current_tok.pos_start.copy()
res.register(self.advance()) # Skip '['
index = res.register(self.expr()) # Parse array index expression
if res.error:
return res
if self.current_tok.type != TT_RSQUAREBRACKET:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected ]"
))
res.register(self.advance()) # Skip ']'
return res.success(ArrayAccessNode(TT_ARRAY, index))
def while_expr(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD,"WHILE"):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'WHILE'"))
res.register(self.advance())
condition = res.register(self.expr())
if res.error: return res
if self.current_tok.type != TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline"))
res.register(self.advance())
if not self.current_tok.matches(TT_KEYWORD,'DO'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'DO'"))
res.register(self.advance())
if self.current_tok.type != TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline"))
res.register(self.advance())
body = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'ENDWHILE'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'ENDWHILE'"))
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline or EOF"))
return res.success(WhileNode(condition,body))
def repeat_expr(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD,"REPEAT"):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'REPEAT'"))
res.register(self.advance())
if not self.current_tok.type == TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected Newline"))
body = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'UNTIL'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'UNTIL'"))
res.register(self.advance())
condition = res.register(self.expr())
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected newline or EOF"))
return res.success(RepeatNode(body,condition))
def if_expr(self):
res = ParseResult()
cases = []
else_case = None
if not self.current_tok.matches(TT_KEYWORD,'IF'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'IF'"))
res.register(self.advance())
cond = res.register(self.expr())
if res.error: return res
if self.current_tok.type != TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'Newline'"))
res.register(self.advance())
if not self.current_tok.matches(TT_KEYWORD,'THEN'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'THEN'"))
res.register(self.advance())
if self.current_tok.type != TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'Newline'"))
res.register(self.advance())
statements = res.register(self.statements())
if res.error: return res
cases.append((cond,statements))
if self.current_tok.matches(TT_KEYWORD,'ELSE'): #instead of making a separate else-expr I added it here
res.register(self.advance())
if not self.current_tok.type == TT_Newline:
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'Newline'"))
else_case = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'ENDIF'):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected 'ENDIF'"))
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
return res.failure(InvalidSyntaxError(self.current_tok.pos_start,
self.current_tok.pos_end, f"Expected EOF or Newline"))
return res.success(IfNode(cases,else_case))
def call(self):
res = ParseResult()
atom = res.register(self.atom())
if res.error:
return res
if self.current_tok.type == TT_LPAREN:
res.register(self.advance())
arg_nodes = []
if self.current_tok.type == TT_RPAREN:
res.register(self.advance())
else:
tok = self.current_tok
arg_nodes.append(res.register(self.expr()))
if res.error: res.failure(InvalidSyntaxError(tok.pos_start,tok.pos_end,""))
while self.current_tok.type == TT_Comma:
res.register(self.advance())
arg_nodes.append(res.register(self.expr()))
if res.error: return res
if self.current_tok.type != TT_RPAREN:
res.failure(
InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ')' or ','"))
res.register(self.advance())
return res.success(CallNode(atom,arg_nodes))
return res.success(atom)
def atom(self):
res = ParseResult()
tok = self.current_tok
if tok.type in [TT_INT,TT_REAL]:
res.register(self.advance())
return res.success(NumberNode(tok))
if tok.type == TT_STRING:
res.register(self.advance())
return res.success(StringNode(tok))
elif tok.type == TT_IDENTIFIER:
res.register(self.advance())
return res.success(VarAccessNode(tok))
elif tok.type == TT_LPAREN:
res.register(self.advance())
expr = res.register(self.expr())
if res.error: return res
if self.current_tok.type == TT_RPAREN:
res.register(self.advance())
return res.success(expr)
else:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected ')'"
))
elif tok.type == TT_LSQUAREBRACKET:
list_expr = res.register(self.list_expr())
if res.error:
return res
return res.success(list_expr)
elif tok.matches(TT_KEYWORD,'IF'):
if_expr = res.register(self.if_expr())
if res.error: return res
return res.success(if_expr)
elif tok.matches(TT_KEYWORD,'FOR'):
for_expr = res.register(self.for_expr())
if res.error:
return res
return res.success(for_expr)
elif tok.matches(TT_KEYWORD,'WHILE'):
while_expr = res.register(self.while_expr())
if res.error:return res
return res.success(while_expr)
elif tok.matches(TT_KEYWORD,"REPEAT"):
repeat_expr = res.register(self.repeat_expr())
if res.error:
return res
return res.success(repeat_expr)
elif tok.matches(TT_KEYWORD,"FUNCTION"):
function_def = res.register(self.func_def())
if res.error:
return res
return res.success(function_def)
else:
return res.failure(InvalidSyntaxError(tok.pos_start,tok.pos_end,"Expected int,real, '+', '-','(','IF','FOR','WHILE','REPEAT', or 'FUNCTION'"))
def power(self):
return self.bin_op(self.call,(TT_POWER,),self.factor)
def factor(self):
res = ParseResult()
tok = self.current_tok
if tok.type in (TT_PLUS,TT_MINUS):
res.register(self.advance())
factor = res.register(self.factor())
if res.error:
return res
return res.success(UnaryOpNode(tok,factor))
return self.power()
def term(self):
return self.bin_op(self.factor,(TT_DIV,TT_MUL))
def arith_expr(self):
return self.bin_op(self.term,(TT_PLUS,TT_MINUS))
def comp_expr(self):
res = ParseResult()
if self.current_tok.matches(TT_KEYWORD,'NOT'):
op_tok = self.current_tok
res.register(self.advance())
if res.error: return res
node = res.register(self.comp_expr())
if res.error:return res
return res.success(UnaryOpNode(op_tok,node))
node = res.register(self.bin_op(self.arith_expr,(TT_EE,TT_NE,TT_LT,TT_LTE,TT_GT,TT_GTE)))
tok = self.current_tok
if res.error:
return res
return res.success(node)
def expr(self):
res = ParseResult()
if self.current_tok.type == TT_IDENTIFIER:
var_name = self.current_tok
res.register(self.current_tok)
res.register(self.advance())
if self.current_tok.type == TT_EQ:
res.register(self.advance())
expr = res.register(self.expr())
if res.error: return res
return res.success(VarAssignNode(var_name,expr))
if self.current_tok.type == TT_LSQUAREBRACKET:
index = res.register(self.array_expr())
if res.error:
return res
if self.current_tok.type != TT_EQ:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected <- for assignment"
))
res.register(self.advance())
value = res.register(self.expr())
if res.error: return res
return res.success(ArrayAssignmentNode(var_name, index, value))
self.regress()
return self.bin_op(self.comp_expr,((TT_KEYWORD,'AND'),(TT_KEYWORD,'OR')))
def proc_def(self):
res = ParseResult()
if not self.current_tok.matches(TT_KEYWORD, 'PROCEDURE'):
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected 'PROCEDURE'"
))
res.register(self.advance()) # Advance past 'PROCEDURE'
if self.current_tok.type != TT_IDENTIFIER:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected an identifier"
))
procedure_name_tok = self.current_tok
res.register(self.advance()) # Advance past the procedure name
arg_name_toks = []
if self.current_tok.type != TT_LPAREN:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected '(' after procedure name"
))
res.register(self.advance()) # Advance past '('
if self.current_tok.type == TT_IDENTIFIER:
arg_name_toks.append(self.current_tok)
res.register(self.advance()) # Advance past argument name
while self.current_tok.type == TT_Comma:
res.register(self.advance()) # Advance past ','
if self.current_tok.type != TT_IDENTIFIER:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected an identifier"
))
arg_name_toks.append(self.current_tok)
res.register(self.advance()) # Advance past argument name
if self.current_tok.type != TT_RPAREN:
return res.failure(InvalidSyntaxError(
self.current_tok.pos_start, self.current_tok.pos_end,
"Expected ')' after procedure arguments"
))
res.register(self.advance()) # Advance past ')'
body = res.register(self.statements())
if res.error: return res
# Assuming ENDPROCEDURE marks the end of a procedure
if not self.current_tok.matches(TT_KEYWORD, "ENDPROCEDURE"):
return res.failure(InvalidSyntaxError(...))
res.register(self.advance()) # Advance past 'ENDPROCEDURE'
return res.success(ProcedureNode(procedure_name_tok, arg_name_toks, body))
def bin_op(self,func_a,ops,func_b = None):
if func_b == None:
func_b = func_a
res = ParseResult()
left = res.register(func_a())
while self.current_tok.type in ops or (self.current_tok.type, self.current_tok.value) in ops:
op_tok = self.current_tok
res.register(self.advance())
right = res.register(func_b())
if res.error:
return res
left = BinOpNode(left, op_tok, right)
return res.success(left)
def list_expr(self):
res = ParseResult()
element_nodes = []
pos_start = self.current_tok.pos_start.copy()
res.register(self.advance())
if self.current_tok.type == TT_RSQUAREBRACKET:
res.register(self.advance())
else:
tok = self.current_tok
element_nodes.append(res.register(self.expr()))
if res.error: res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ']', 'IF','FOR','WHILE','FUNCTION',variable,datatypoe"))
while self.current_tok.type == TT_Comma:
res.register(self.advance())
element_nodes.append(res.register(self.expr()))
if res.error: return res
if self.current_tok.type != TT_RSQUAREBRACKET:
res.failure(
InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ']' or ','"))
res.register(self.advance())
return ListNode(element_nodes,pos_start,self.current_tok.pos_end.copy())
def func_def(self):
res = ParseResult()
tok = self.current_tok
if not self.current_tok.matches(TT_KEYWORD,'FUNCTION'):
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'FUNCTION'"))
res.register(self.advance())
if self.current_tok.type != TT_IDENTIFIER:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected indentifier"))
var_name_tok = self.current_tok
res.register(self.advance())
if self.current_tok.type != TT_LPAREN:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected '('"))
res.register(self.advance())
arg_name_toks = []
if self.current_tok.type == TT_IDENTIFIER:
arg_name_toks.append(self.current_tok)
res.register(self.advance())
if not self.current_tok.type == TT_Arrow:
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ':'"))
res.register(self.advance())
if not self.current_tok.type == TT_IDENTIFIER or self.current_tok.value not in ['REAL', 'INTEGER', 'CHAR','BOOLEAN', 'STRING']:
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected datatype"))
res.register(self.advance())
while self.current_tok.type == TT_Comma:
res.register(self.advance())
if self.current_tok.type != TT_IDENTIFIER:
tok = self.current_tok
return res.failure(
InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected identifier"))
name = self.current_tok
res.register(self.advance())
if not self.current_tok.type == TT_Arrow:
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ':'"))
res.register(self.advance())
if not self.current_tok.type == TT_IDENTIFIER or self.current_tok.value not in ['REAL', 'INTEGER', 'CHAR', 'BOOLEAN', 'STRING']:
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected datatype"))
arg_name_toks.append(name)
res.register(self.advance())
if self.current_tok.type != TT_RPAREN:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected ',' or ')'"))
else:
if self.current_tok.type != TT_RPAREN:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected identifier or ')'"))
res.register(self.advance())
if not self.current_tok.matches(TT_KEYWORD,'RETURNS'):
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'RETURNS'"))
res.register(self.advance())
if self.current_tok.value not in ['INTEGER','REAL','BOOLEAN','STRING','CHAR']:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'INTEGER','REAL','BOOLEAN','STRING' or 'CHAR'"))
res.register(self.advance())
if not self.current_tok.type == TT_Newline:
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected Newline'"))
node_to_return = res.register(self.statements())
if res.error: return res
if not self.current_tok.matches(TT_KEYWORD,'RETURN'):
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'RETURN'"))
res.register(self.advance())
expr = res.register(self.expr())
if res.error: return res
res.register(self.advance())
if not self.current_tok.matches(TT_KEYWORD,'ENDFUNCTION'):
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected 'ENDFUNCTION'"))
res.register(self.advance())
if not self.current_tok.type in (TT_Newline,TT_EOF):
tok = self.current_tok
return res.failure(InvalidSyntaxError(tok.pos_start, tok.pos_end, "Expected Newline or EOF'"))
return res.success(FuncDefNode(
var_name_tok,arg_name_toks,node_to_return,expr
))
#runtime result
#-------------------------------------------------
class RTResult:
def __init__(self):
self.value = None
self.error = None
def register(self,res):
if res.error: self.error = res.error
return res.value
def success(self,value):
self.value = value
return self
def failure(self,error):
self.error = error
return self
#values
#-------------------------------------------------
class Value:
def __init__(self):
self.set_context()
self.set_pos()
def set_context(self,context = None):
self.context = context
return self
def set_pos(self,pos_start = None,pos_end = None):
self.pos_start = pos_start
self.pos_end = pos_end
return self
def added_to(self,other):
return None,self.illegal_operation(other)
def subtracted_by(self,other):
return None,self.illegal_operation(other)
def multiplied_by(self,other):
return None,self.illegal_operation(other)
def divided_by(self,other):
return None, self.illegal_operation(other)
def powered_by(self,other):
return None,self.illegal_operation(other)
def get_comparison_eq(self, other):
return None,self.illegal_operation(other)
def get_comparison_ne(self, other):
return None,self.illegal_operation(other)
def get_comparison_lt(self, other):
return None,self.illegal_operation(other)
def get_comparison_gt(self, other):
return None,self.illegal_operation(other)
def get_comparison_lte(self, other):
return None,self.illegal_operation(other)
def get_comparison_gte(self, other):
return None,self.illegal_operation(other)
def anded_by(self, other):
return None,self.illegal_operation(other)
def ored_by(self, other):
return None,self.illegal_operation(other)
def notted(self):
return None,self.illegal_operation(self)
def execute(self, args):
return RTResult().failure(self.illegal_operation())
def copy(self):
raise Exception('No copy method defined')
def is_true(self):
return False
def illegal_operation(self, other=None):
if not other: other = self
return RTError(
self.pos_start, other.pos_end,
'Illegal operation',
self.context
)
class Number(Value):
def __init__(self,value):
self.value = value
super().__init__()
def set_context(self,context = None):
self.context = context
return self
def set_pos(self,pos_start = None,pos_end = None):
self.pos_start = pos_start
self.pos_end = pos_end
return self
def added_to(self,other):
if isinstance(other,Number):
return Number(self.value + other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def subtracted_by(self,other):
if isinstance(other,Number):
return Number(self.value - other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def multiplied_by(self,other):
if isinstance(other,Number):
return Number(self.value * other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def divided_by(self,other):
if isinstance(other,Number):
if other.value == 0:
return None,RTError(
other.pos_start
,other.pos_end,
'Divison by Zero',
self.context
)
return Number(self.value / other.value).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def powered_by(self,other):
if isinstance(other,Number):
return Number(self.value ** other.value).set_context(self.context),None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_eq(self, other):
if isinstance(other, Number):
return Number(int(self.value == other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_ne(self, other):
if isinstance(other, Number):
return Number(int(self.value != other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_lt(self, other):
if isinstance(other, Number):
return Number(int(self.value < other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_gt(self, other):
if isinstance(other, Number):
return Number(int(self.value > other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_lte(self, other):
if isinstance(other, Number):
return Number(int(self.value <= other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def get_comparison_gte(self, other):
if isinstance(other, Number):
return Number(int(self.value >= other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def anded_by(self, other):
if isinstance(other, Number):
return Number(int(self.value and other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def ored_by(self, other):
if isinstance(other, Number):
return Number(int(self.value or other.value)).set_context(self.context), None
else:
return None, Value.illegal_operation(self, other)
def notted(self):
return Number(1 if self.value == 0 else 0).set_context(self.context), None
def copy(self):
copy = Number(self.value)
copy.set_pos(self.pos_start,self.pos_end)
copy.set_context(self.context)
return copy
def is_true(self):
return self.value != 0
def __repr__(self):
return f'{self.value}'
class String(Value):
def __init__(self,value):
super().__init__()
self.value = value
def added_to(self,other):
if isinstance(other,String):
return String(self.value + other.value).set_context(self.context),None
else:
return None,Value.illegal_operation(self,other)
def copy(self):
copy = String(self.value)
copy.set_pos(self.pos_start,self.pos_end)
copy.set_context(self.context)
return copy
def __str__(self):
return self.value
def __repr__(self):
return f'"{self.value}"'
class List(Value):
def __init__(self,elements):
super().__init__()
self.elements = elements
def added_to(self,other):
new_list = self.copy()
new_list.elements.append(other)
return new_list,None
def subtracted_by(self,other):
if isinstance(other,Number):
new_list = self.copy()
try:
new_list.elements.pop(other)
return new_list,None
except:
return None,RTError(other.pos_start,other.pos_end,'Element at this indewx is out of bound',self.context)
else:
return None,Value.illegal_operation(self,other)
def multiplied_by(self,other):
if isinstance(other,List):
new_list = self.copy()
new_list.elements.extend(other.elements)
else:
return None,Value.illegal_operation(self,other)
def divided_by(self,other):
if isinstance(other, Number):
try:
return self.elements[other.value],None
except:
return None, RTError(other.pos_start, other.pos_end, 'Element at this indewx is out of bound',
self.context)
else:
return None, Value.illegal_operation(self, other)
def copy(self):
copy = List(self.elements)
copy.set_pos(self.pos_start,self.pos_end)
copy.set_pos(self.context)
return copy
def __repr__(self):
return f"[{','.join([str(x) for x in self.elements])}]"
class BaseFunction(Value):
def __init__(self,name):
super().__init__()
self.name = name
def generateNewContext(self):
new_context = Context(self.name, self.context, self.pos_start)
new_context.symbol_table = SymbolTable(new_context.parent.symbol_table)
return new_context
def check_args(self,arg_names,args):
res = RTResult()
if len(args) > len(arg_names):
return res.failure(RTError(
self.pos_start, self.pos_end,
f"{len(args) - len(arg_names)} too many args passed into '{self.name}'",
self.context
))
if len(args) < len(arg_names):
return res.failure(RTError(
self.pos_start, self.pos_end,
f"{len(arg_names) - len(args)} too few args passed into '{self.name}'",
self.context
))
return res.success(None)
def populate_args(self,arg_names,args,exec_ctx):
for i in range(len(args)):
new_context = exec_ctx
arg_name = arg_names[i]
arg_value = args[i]
arg_value.set_context(new_context)
new_context.symbol_table.set(arg_name, arg_value)
def check_and_populate_args(self,arg_names,args,exec_ctx):
res = RTResult()
res.register(self.check_args(arg_names,args))
if res.error: return res
self.populate_args(arg_names,args,exec_ctx)
return res.success(None)
class Procedure(BaseFunction):
def __init__(self, procedure_name, body_node, arg_names):
super().__init__(procedure_name)
self.body_node = body_node
self.arg_names = arg_names
def execute(self, args):
res = RTResult()
interpreter = Interpreter()
# Create a new execution context for the procedure with a new symbol table
exec_ctx = self.generateNewContext()
# Populate the new context with arguments
res.register(self.check_and_populate_args(self.arg_names, args, exec_ctx))
if res.error: return res
# Execute the body of the procedure
value = res.register(interpreter.visit(self.body_node, exec_ctx))
if res.error: return res
# Normally, procedures do not return a value unless specified, return a “null” equivalent
return res.success(Number(0))
def copy(self):
# When copying a procedure, we copy the procedure’s name, body, and argument names
copy = Procedure(self.name, self.body_node, self.arg_names)
copy.set_context(self.context)
copy.set_pos(self.pos_start, self.pos_end)
return copy
def repr(self):
return f"<procedure {self.name}>"
class Function(BaseFunction):
def __init__(self,name,body_node,arg_names,ret_node):
super().__init__(name)
self.body_node = body_node
self.arg_names = arg_names
self.ret_node = ret_node
def execute(self, args):
res = RTResult()
interpreter = Interpreter()
new_context = self.generateNewContext()
res.register(self.check_and_populate_args(self.arg_names,args,new_context))
if res.error: return res
value = res.register(interpreter.visit(self.body_node, new_context))
if res.error: return res
q = res.register(interpreter.visit(self.ret_node,new_context))
return res.success(q)
def copy(self):
copy = Function(self.name, self.body_node, self.arg_names,self.ret_node)
copy.set_context(self.context)
copy.set_pos(self.pos_start, self.pos_end)
return copy
def __repr__(self):
return f"<function {self.name}>"
class BuiltInFunction(BaseFunction):
def __init__(self,name):
super().__init__(name)
def execute(self, args):
res = RTResult()
exec_ctx = self.generateNewContext()
method_name = f'execute_{self.name}'
method = getattr(self,method_name,self.no_visit_method)
res.register(self.check_and_populate_args(method.arg_names,args,exec_ctx))
if res.error: return res
return_value = res.register(method(exec_ctx))
if res.error: return res
return res.success(return_value)
def no_visit_method(self,node,context):
raise Exception(f'No execute_{self.name} method defined')
def copy(self):
copy = BuiltInFunction(self.name)
copy.set_context(self.context)
copy.set_pos(self.pos_start,self.pos_end)
return copy
def __repr__(self):
return f'<built-in function {self.name}>'
#BuiltIn functions
def execute_output(self,exec_ctx):
print(str(exec_ctx.symbol_table.get('value')))
return RTResult().success(Number(0)) #return null equivalent
execute_output.arg_names = ['value']
def execute_mid(self,exec_ctx):
s = exec_ctx.symbol_table.get('s')
a = exec_ctx.symbol_table.get('a')
b = exec_ctx.symbol_table.get('b')
f = str(s)[a.value - 1 :a.value - 1 + b.value ]
return RTResult().success(Number(String(f)))
execute_mid.arg_names = ['s','a','b']
BuiltInFunction.output = BuiltInFunction('output')
BuiltInFunction.mid = BuiltInFunction('mid')
#context
#--------------------------------------------------
class Context:
def __init__(self,display_name, parent = None, parent_entry_pos = None):
self.display_name = display_name
self.parent = parent
self.parent_entry_pos = parent_entry_pos
self.symbol_table = None
#symbol stable
#--------------------------------------------------
class SymbolTable:
def __init__(self,parent = None):
self.symbols = dict()
self.parent = parent
def get(self,name):
value = self.symbols.get(name, None)
if value == None and self.parent:
return self.parent.get(name)
return value
def set(self, name, value):
self.symbols[name] = value
def remove(self,name):
del self.symbols[name]
#interpreter
#--------------------------------------------------
class Interpreter:
def visit(self,node,context):
method_name = f'visit_{type(node).__name__}'
method = getattr(self,method_name,self.no_visit_method)
return method(node,context)
def no_visit_method(self,node,context):
raise Exception(f'No visit_{type(node).__name__} defined')
def visit_VarAccessNode(self, node, context):
res = RTResult()
var_name = node.var_name_tok.value
value = context.symbol_table.get(var_name)
if not value:
return res.failure(RTError(node.pos_start,
node.pos_end,f"'{var_name} is not defined'",context))
value = value.copy().set_pos(node.pos_start,node.pos_end).set_context(context)
return res.success(value)
def visit_VarAssignNode(self, node, context):
res = RTResult()
var_name = node.var_name_tok.value
value = res.register(self.visit(node.value_node,context))
if res.error: return res
context.symbol_table.set(var_name,value)
return res.success(value)
def visit_NumberNode(self,node,context):
return RTResult().success(
Number(node.tok.value).set_context(context).set_pos(node.pos_start,node.pos_end)
)
def visit_StringNode(self,node,context):
return RTResult().success(
String(node.tok.value).set_context(context).set_pos(node.pos_start,node.pos_end)
)
def visit_ListNode(self,node,context):
res = RTResult()
elements = []
for element_node in node.element_nodes:
elements.append(res.register(self.visit(element_node,context)))
if res.error:return res
return res.success(
List(elements).set_context(context).set_pos(node.pos_start,node.pos_end)
)
def visit_BinOpNode(self,node,context):
res = RTResult()
left = res.register(self.visit(node.left_node,context))
if res.error: return res
right = res.register(self.visit(node.right_node,context))
if res.error: return res
if node.op_tok.type == TT_PLUS or node.op_tok.type:
result,error = left.added_to(right)
if node.op_tok.type == TT_MINUS:
result,error = left.subtracted_by(right)
if node.op_tok.type == TT_MUL:
result,error = left.multiplied_by(right)
if node.op_tok.type == TT_DIV:
result,error = left.divided_by(right)
if node.op_tok.type == TT_POWER:
result,error = left.powered_by(right)
elif node.op_tok.type == TT_EE:
result, error = left.get_comparison_eq(right)
elif node.op_tok.type == TT_NE:
result, error = left.get_comparison_ne(right)
elif node.op_tok.type == TT_LT:
result, error = left.get_comparison_lt(right)
elif node.op_tok.type == TT_GT:
result, error = left.get_comparison_gt(right)
elif node.op_tok.type == TT_LTE:
result, error = left.get_comparison_lte(right)
elif node.op_tok.type == TT_GTE:
result, error = left.get_comparison_gte(right)
elif node.op_tok.matches(TT_KEYWORD, 'AND'):
result, error = left.anded_by(right)
elif node.op_tok.matches(TT_KEYWORD, 'OR'):
result, error = left.ored_by(right)
if error: return res.failure(error)
return res.success(result.set_pos(node.pos_start,node.pos_end))
def visit_UnaryOpNode(self,node,context):
res = RTResult()
number = res.register(self.visit(node.node,context))
if res.error: return res
error = None
if node.op_tok.type == TT_MINUS:
number,error = number.multiplied_by(Number(-1))
elif node.op_tok.matches(TT_KEYWORD, 'NOT'):
number, error = number.notted()
if error: return res.failure(error)
return res.success(number.set_pos(node.pos_start,node.pos_end))
def visit_IfNode(self,node,context):
res = RTResult()
for condition,expr in node.cases:
condition_value = res.register(self.visit(condition,context))
if res.error: return res
if condition_value.is_true():
expr_value = res.register(self.visit(expr,context))
if res.error: return res
return res.success(Number(0)) #returns null eq
if node.else_case:
else_value = res.register(self.visit(node.else_case,context))
if res.error:return res
return res.success(Number(0))
return res.success(Number(0))
def visit_ForNode(self,node,context):
res = RTResult()
elements = []
start_value = res.register(self.visit(node.start_value_node,context))
if res.error:return res
end_value = res.register(self.visit(node.end_value_node,context))
if res.error: return res
if node.step_value_node:
step_value = res.register(self.visit(node.step_value_node,context))
if res.error: return res
else:
step_value = Number(1)
i = start_value.value
if step_value.value >= 0:
condition = lambda: i <= end_value.value
else:
condition = lambda: i >= end_value.value
while condition():
context.symbol_table.set(node.var_name_tok.value,Number(i))
i += step_value.value
elements.append(res.register(self.visit(node.body_node,context)))
if res.error: return res
return res.success(
Number(0)
)
def visit_WhileNode(self,node,context):
res = RTResult()
elements = []
while True:
condition = res.register(self.visit(node.condition_node,context))
if res.error: return res
if not condition.is_true(): break
elements.append(res.register(self.visit(node.body_node,context)))
if res.error: return res
return res.success(
Number(0)
)
def visit_RepeatNode(self,node,context):
res = RTResult()
elements = []
while True:
elements.append(res.register(self.visit(node.body_node,context)))
if res.error: return res
condition = res.register(self.visit(node.condition_node,context))
if res.error: return res
if condition.is_true():break
return res.success(
Number(0)
)
def visit_FuncDefNode(self,node,context):
res = RTResult()
func_name = node.var_name_tok.value if node.var_name_tok else None
body_node = node.body_node
arg_names = [arg_name.value for arg_name in node.arg_name_toks]
func_value = Function(func_name, body_node, arg_names,node.ret_node).set_context(context).set_pos(node.pos_start,
node.pos_end)
if node.var_name_tok:
context.symbol_table.set(func_name, func_value)
return res.success(func_value)
def visit_CallNode(self, node, context):
res = RTResult()
args = []
value_to_call = res.register(self.visit(node.node_to_call, context))
if res.error: return res
value_to_call = value_to_call.copy().set_pos(node.pos_start, node.pos_end)
for arg_node in node.arg_nodes:
args.append(res.register(self.visit(arg_node, context)))
if res.error: return res
return_value = res.register(value_to_call.execute(args))
if res.error: return res
return_value = return_value.copy().set_pos(node.pos_start, node.pos_end).set_context(context)
return res.success(return_value)
# In the Interpreter class
def visit_ArrayAssignmentNode(self, node, context):
res = RTResult()
array_name = node.array_name_tok.value
array_instance = context.symbol_table.get(array_name)
index = res.register(self.visit(node.index_node, context))
if res.error: return res
value = res.register(self.visit(node.value_node, context))
if res.error: return res
if isinstance(array_instance, List):
if index.value >= 0 and index.value < len(array_instance.elements):
array_instance.elements[index.value] = value
return res.success(value)
else:
return res.failure(RTError(index.pos_start, index.pos_end,
"Index out of bounds: Array '" + array_name + "'", context))
else:
return res.failure(RTError(array_instance.pos_start, array_instance.pos_end,
"'" + array_name + "'" + "is not an array", context))
def visit_ArrayAccessNode(self, node, context):
res = RTResult()
array_name = node.array_name_tok.value
array_instance = context.symbol_table.get(array_name)
index = res.register(self.visit(node.index_node, context))
if res.error: return res
if isinstance(array_instance, List):
try:
value = array_instance.elements[index.value]
return res.success(value)
except:
return res.failure(RTError(index.pos_start, index.pos_end,
"Index out of bounds: Array '" + array_name + "'", context))
else:
return res.failure(RTError(array_instance.pos_start, array_instance.pos_end,
"'" + array_name + "'" + "is not an array", context))
def visit_ProcedureNode(self, node, context):
res = RTResult()
proc_name = node.procedure_name_tok.value
arg_names = [arg_name.value for arg_name in node.arg_name_toks]
body_node = node.body_node
procedure = Procedure(proc_name, body_node, arg_names)
procedure.set_context(context)
procedure.set_pos(node.pos_start, node.pos_end)
context.symbol_table.set(proc_name, procedure)
return res.success(procedure)
#run
#--------------------------------------------------
global_symbol_table = SymbolTable()
global_symbol_table.set('TRUE',Number(1))
global_symbol_table.set('FALSE',Number(0))
global_symbol_table.set('OUTPUT',BuiltInFunction.output)
global_symbol_table.set('MID',BuiltInFunction.mid)
def run(fn,text):
lexer = Lexer(fn,text)
tokens,error = lexer.make_tokens()
if error: return None,error
#generate ast
parser = Parser(tokens)
ast = parser.parse()
if ast.error: return None,ast.error
#runs
interpreter = Interpreter()
context = Context('<program>')
context.symbol_table = global_symbol_table
result = interpreter.visit(ast.node,context)
return result.value,result.error
change the call node function to accomodate the arrays and the procedures.
|
4677ec187af6cb07fe2648f2d385e870
|
{
"intermediate": 0.31928038597106934,
"beginner": 0.4573437571525574,
"expert": 0.2233758419752121
}
|
38,220
|
Create for me an bot to play with me in Messcraft that emulates 1.5.2 version https://mess.eu.org/
|
a6f17205f1550d89fb6e5f1c841c7b11
|
{
"intermediate": 0.3509974479675293,
"beginner": 0.38709136843681335,
"expert": 0.26191118359565735
}
|
38,221
|
Есть код, он показывает прямоугольник с картинкой. При наведении курсора на этот прямоугольник выскакивает текст и кнопка для перехода. Как сделать так, что бы текст отображался сразу. Кокой параметр в коде за это отвечает?
Сам код:
<div class="filterDiv cars position-relative">
<a href="#" data-toggle="modal" data-target="#modalWPWAF">
<div class="portfolio-img position-relative">
<figure>
<img src="assets/image/portfolio-img1.png" alt="portfolio-img1" class="img-fluid">
</figure>
</div>
</a>
<div class="portfolio-img-content text-left">
<div class="portfolio-img-title d-inline-block">
<h4>Курс №1</h4>
<p>Первая помощь человеку</p>
</div>
<a href="#" class="float-lg-right" data-toggle="modal" data-target="#modalWPWAF-icon">
<i class="fas fa-arrow-right d-flex align-items-center justify-content-center"></i>
</a>
</div>
|
74a419a57c441857cb2ebe65be867d53
|
{
"intermediate": 0.20666936039924622,
"beginner": 0.6466773748397827,
"expert": 0.14665327966213226
}
|
38,222
|
In a hypothetical , what uses might the mythical British Rail Flying Suacer have been put to?
|
310a3bbd7bd0cd5abe2452487f146acc
|
{
"intermediate": 0.3213454782962799,
"beginner": 0.3511526882648468,
"expert": 0.3275018334388733
}
|
38,223
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Setter {
address public owner;
uint public value;
constructor() {
owner = msg.sender;
}
function setValuel (uint _newValue) external {
require (msg.sender == owner, "Only the owner can set the value");
value = _newValue;
}
function setValue2(uint _newValue) external {
value = _newValue;
require (msg.sender == owner, "Only the owner can set the value");
}
}
Which of the two functions presented in the contracts below is a better implementation, and why? 🤔
|
06627be4c5cc9ac7e46e8d1771620f33
|
{
"intermediate": 0.3615554869174957,
"beginner": 0.46421390771865845,
"expert": 0.17423056066036224
}
|
38,224
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract Setter {
address public owner;
uint public value;
constructor() {
owner = msg.sender;
}
function setValuel (uint _newValue) external {
require (msg.sender == owner, "Only the owner can set the value");
value = _newValue;
}
function setValue2(uint _newValue) external {
value = _newValue;
require (msg.sender == owner, "Only the owner can set the value");
}
}
Which of the two functions presented in the contracts below is a better implementation, and why? 🤔
|
d819d92a4a80ca375cacb519154715d5
|
{
"intermediate": 0.3615554869174957,
"beginner": 0.46421390771865845,
"expert": 0.17423056066036224
}
|
38,225
|
What is the below code doing?
queryresult= Common_Function.CommonFun.convertToJson(
Constant.constant.constant.getPatientDtl,
session.query(Model.models.Application.M_Patient.MPID.label('ID'),
Model.models.Application.M_Patient.MP_UHID.label('UHID'),
Model.models.Application.M_Patient.MP_Name.label('Name'),
Model.models.Application.M_Patient.MP_Email.label('Email'),
Model.models.Application.M_Patient.MP_Mobile.label('Mobile'),
Model.models.Application.M_Patient.MP_Address.label('Address'),
sqlalchemy.func.concat(Model.models.Application.M_ReferredByDoctor.MRD_FirstName,' ',Model.models.Application.M_ReferredByDoctor.MRD_LastName).label('Referred By')
).filter(Model.models.Application.M_Patient.MP_IsActive==1,Model.models.Application.M_Patient.MP_IsDeleted==0,
Model.models.Application.M_Patient.M_Branch_MBID == int(branchId)
).filter(*apply
).outerjoin(Model.models.Application.M_ReferredByDoctor,
Model.models.Application.M_ReferredByDoctor.MRDID==Model.models.Application.M_Patient.MP_RefferedBy
).order_by(Model.models.Application.M_Patient.MPID.desc()).all()
)
|
fde7c681b97ee9f00f4a86552221bb15
|
{
"intermediate": 0.4010854959487915,
"beginner": 0.443477064371109,
"expert": 0.15543745458126068
}
|
38,226
|
Create horoscope east indian style for abhishek baruah, born 05 mar 1989, time 5 :50am, place bamunimaidan, guwahati assam
|
cbe5fdd7b10d39d63043bbee4c59a62f
|
{
"intermediate": 0.3748749792575836,
"beginner": 0.3246805965900421,
"expert": 0.30044445395469666
}
|
38,227
|
{ Game : Palworld-Win64-Shipping.exe
Version:
Date : 2024-01-25
Author : Sora
This script does blah blah blah
}
define(address,"Palworld-Win64-Shipping.exe"+2B8F253)
define(bytes,48 89 01 48 8B C1)
[ENABLE]
assert(address,bytes)
alloc(newmem,$1000,"Palworld-Win64-Shipping.exe"+2B8F253)
label(code)
label(return)
newmem:
code:
mov [rcx],rax
mov rax,rcx
jmp return
address:
jmp newmem
nop
return:
[DISABLE]
address:
db bytes
// mov [rcx],rax
// mov rax,rcx
dealloc(newmem)
{
// ORIGINAL CODE - INJECTION POINT: Palworld-Win64-Shipping.exe+2B8F253
Palworld-Win64-Shipping.exe+2B8F22E: E8 CD 26 3C 00 - call Palworld-Win64-Shipping.exe+2F51900
Palworld-Win64-Shipping.exe+2B8F233: 48 8B CB - mov rcx,rbx
Palworld-Win64-Shipping.exe+2B8F236: 48 8B 5C 24 30 - mov rbx,[rsp+30]
Palworld-Win64-Shipping.exe+2B8F23B: 48 8B 6C 24 38 - mov rbp,[rsp+38]
Palworld-Win64-Shipping.exe+2B8F240: 48 8B 74 24 40 - mov rsi,[rsp+40]
Palworld-Win64-Shipping.exe+2B8F245: 48 83 C4 20 - add rsp,20
Palworld-Win64-Shipping.exe+2B8F249: 5F - pop rdi
Palworld-Win64-Shipping.exe+2B8F24A: E9 B1 7A 40 00 - jmp Palworld-Win64-Shipping.exe+2F96D00
Palworld-Win64-Shipping.exe+2B8F24F: CC - int 3
Palworld-Win64-Shipping.exe+2B8F250: 48 8B 02 - mov rax,[rdx]
// ---------- INJECTING HERE ----------
Palworld-Win64-Shipping.exe+2B8F253: 48 89 01 - mov [rcx],rax
// ---------- DONE INJECTING ----------
Palworld-Win64-Shipping.exe+2B8F256: 48 8B C1 - mov rax,rcx
Palworld-Win64-Shipping.exe+2B8F259: C3 - ret
Palworld-Win64-Shipping.exe+2B8F25A: CC - int 3
Palworld-Win64-Shipping.exe+2B8F25B: CC - int 3
Palworld-Win64-Shipping.exe+2B8F25C: CC - int 3
Palworld-Win64-Shipping.exe+2B8F25D: CC - int 3
Palworld-Win64-Shipping.exe+2B8F25E: CC - int 3
Palworld-Win64-Shipping.exe+2B8F25F: CC - int 3
Palworld-Win64-Shipping.exe+2B8F260: 8B 02 - mov eax,[rdx]
Palworld-Win64-Shipping.exe+2B8F262: 89 01 - mov [rcx],eax
}
Нужно установит значение на 500 и заморозить его
|
1f09199db4ab1e14d3287ce4e5b04f8e
|
{
"intermediate": 0.2826911211013794,
"beginner": 0.4955369830131531,
"expert": 0.22177186608314514
}
|
38,228
|
how can i create a simple python program that takes two text inputs (has two text input areas), outputs both texts in two output sections (outputting the same exact formatting as the original texts, including new lines between paragraphs), and highlights words that match from each text in yellow (highlights when three or more words match)?
|
37a500991b363f458d38e954618557b4
|
{
"intermediate": 0.44950979948043823,
"beginner": 0.141505628824234,
"expert": 0.40898457169532776
}
|
38,229
|
How do i solve fuzzbuzz
|
8f19779ca6f5a7c815b0fd75fbcaf3e2
|
{
"intermediate": 0.2178751528263092,
"beginner": 0.20214225351810455,
"expert": 0.5799826383590698
}
|
38,230
|
Hi, write a script for Unity3D to create a lot of enemies. He must be able to:
1: Memorize the player's actions and learn from them.
2: Chase the player.
3: Self-study.
4: Look for profitable routes.
Use NavMeshAgent. Do not use ml agents
|
bf934dac798966211294aa7fd71f5894
|
{
"intermediate": 0.409976601600647,
"beginner": 0.28923508524894714,
"expert": 0.3007883131504059
}
|
38,231
|
Hi, would the data should like from this paragraph:
"
The method used in this manuscript is
based on the fundamental ideas described
by Lapedes and Farber (4) and, in particular, takes advantage of their observation
that antigenic distance is linearly related to
the logarithm of the HI measurement. Exploiting this observation allowed us to create a new method that is parametric yet still
handles HI measurements that are beyond
the sensitivity of the HI assay (9). We use
a modification of metric MDS (25) to position the antigens and antisera in the map
(9). This new approach offers computational advantages over the ordinal approach
including reduced running time and fewer
local minima, making it tractable to run on
datasets the size of the one used in this
manuscript, and on larger datasets.
Antigenic map of human influenza A
(H3N2) virus. We applied this method to
mapping the antigenic evolution of human
influenza A (H3N2) viruses, which became
widespread in humans during the 1968 Hong
Kong influenza pandemic and have been a
major cause of influenza epidemics ever
since. Antigenic data from 35 years of influenza surveillance between 1968 and 2003
were combined into a single dataset. We sequenced the HA1 domain of a subset of these
virus isolates (26, 27) and restricted the antigenic analysis to these sequenced isolates to
facilitate a direct comparison of antigenic and
genetic evolution. The resulting antigenic
dataset consisted of a table of 79 postinfection ferret antisera by 273 viral isolates, with
4215 individual HI measurements as entries
in the table. Ninety-four of the isolates were
from epidemics in the Netherlands, and 179
were from elsewhere in the world
"
I am trying to find their data but is not even in their supp material. I understand part of their methodology but I think it would be easier if I look at how their raw data looked. Could help me trying to see how their data looked (an approximate of HI values)?
|
de70c293fb4e4b4f4a895c85ec07a175
|
{
"intermediate": 0.3057386577129364,
"beginner": 0.373890221118927,
"expert": 0.320371150970459
}
|
38,232
|
I have this code:
@Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
private void updateUI(FirebaseUser user) {
if (user==null) {
mAuth.signInAnonymously().addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
updateUI(null);
}
}
});
}
}
}
I think it logs the user in anonymously to Google Firebase. But I want to link some values (nickname and score) in a Firebase database to the anonymous UID-s. How should I do it?
|
e20d173924b713da714b10452a3cec3a
|
{
"intermediate": 0.5812262892723083,
"beginner": 0.20858627557754517,
"expert": 0.21018745005130768
}
|
38,233
|
I'm trying to create a wordle game here is my current code .What do i need to add or fix . import java.util.Scanner;
public class WordleTester
{
public static void main(String[] args)
{
Scanner input =new Scanner(System.in);
System.out.println("Welcome to Wordle!!!");
System.out.println("Guess a 5 letter word to try and solve the clue. 'Y' indicates the letter is in the word but position is wrong. 'G' indicates the letter is in the right place in the word.");
System.out.println("if the word 'spice' was guessed and the output is 'spYcG', Then 'I' is in the word, but the wrong place.");
System.out.println("e would be in the right position for the word");
System.out.println("");
for (){
System.out.println("Guess a word: ");
}
}
}import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class wordle{
private static String target;
private final int maxAttempts = 6;
public Wordle() {
RandomWordList randomwordlist = new RandomWordList();
this.target = randomWordList.getRandomWord();
}
public void playGame(){
Scanner scanner = new Scanner(System.in);
boolean won = false;
for (int attempt = 0; attempts < maxAttempts; attempt++){
System.out.println("Enter your guess: ");
String guess = scanner.nextLine().trim().toLowerCase();
// validate guess
String feedback = provideFeedback(guess, target);
System.out.println("Feedback: " + feedback);
if(guess.equals(target)){
won = true;
break;
}
public static String yellow_finder(user, orginal){
String x = "";
for (int i = 0; i > user.length(); i++){
for (int j = 0; j > orginal.length(); j++){
if (user.substring(i, i+1).equals(orginal.substring(j, j+1))){
x = user.substring(0, i) + "Y" + user.substring(i+1);
}
}
}
return x;
}
public static String green_finder(user, original){
String r = wordle.yellow_finder(user, original);
String x = "";
for (int i = 0; i < user.length(); i++){
if (user.substring(i, i+1).equals(original.substring(i, i+1))){
x = user.substring(0, i) + "G" + user.substring(i+1);
}
}
for (int j = 0; j < user.length(); j++){
if (r.substring(j, j+1).equals("Y")) && !(x.substring(j, j+1).equals("G")){
x = x.substring(0, j) + "Y" + x.substring(j+1);
}
}
return x;
}
}import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class RandomWordList{
List <String> wordlist = new ArrayList<>(Arrays.asList(
"aback",
"abase",
"abate",
|
ce4f398185eb5e7a3995beb77262788b
|
{
"intermediate": 0.4070175886154175,
"beginner": 0.32790663838386536,
"expert": 0.2650757431983948
}
|
38,234
|
I want to create a wordle game in java. Can you help me? here is my word list import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class RandomWordList{
List <String> wordlist = new ArrayList<>(Arrays.asList(
"aback",
"abase",
"abate",
"abbey",
"abbot",
"abhor",
"abide",
"abled",
"abode",
"abort",
"about",
"above",
"abuse",
"abyss",
"acorn",
"acrid",
"actor",
"acute",
"adage",
"adapt",
"adept",
"admin",
"admit",
"adobe",
"adopt",
"adore",
"adorn",
"adult",
"affix",
"afire",
"afoot",
"afoul",
"after",
"again",
"agape",
"agate",
"agent",
"agile",
"aging",
"aglow",
"agony",
"agree",
"ahead",
"aider",
"aisle",
"alarm",
"album",
"alert",
"algae",
"alibi",
"alien",
"align",
"alike",
"alive",
"allay",
"alley",
"allot",
"allow",
"alloy",
"aloft",
"alone",
"along",
"aloof",
"aloud",
"alpha",
"altar",
"alter",
"amass",
"amaze",
"amber",
"amble",
"amend",
"amiss",
"amity",
"among",
"ample",
"amply",
"amuse",
"angel",
"anger",
"angle",
"angry",
"angst",
"anime",
"ankle",
"annex",
"annoy",
"annul",
"anode",
"antic",
"anvil",
"aorta",
"apart",
"aphid",
"aping",
"apnea",
"apple",
"apply",
"apron",
"aptly",
"arbor",
"ardor",
"arena",
"argue",
"arise",
"armor",
"aroma",
"arose",
"array",
"arrow",
"arson",
"artsy",
"ascot",
"ashen",
"aside",
"askew",
"assay",
"asset",
"atoll",
"atone",
"attic",
"audio",
"audit",
"augur",
"aunty",
"avail",
"avert",
"avian",
"avoid",
"await",
"awake",
"award",
"aware",
"awash",
"awful",
"awoke",
"axial",
"axiom",
"axion",
"azure",
"bacon",
"badge",
"badly",
"bagel",
"baggy",
"baker",
"baler",
"balmy",
"banal",
"banjo",
"barge",
"baron",
"basal",
"basic",
"basil",
"basin",
"basis",
"baste",
"batch",
"bathe",
"baton",
"batty",
"bawdy",
"bayou",
"beach",
"beady",
"beard",
"beast",
"beech",
"beefy",
"befit",
"began",
"begat",
"beget",
"begin",
"begun",
"being",
"belch",
"belie",
"belle",
"belly",
"below",
"bench",
"beret",
"berry",
"berth",
"beset",
"betel",
"bevel",
"bezel",
"bible",
"bicep",
"biddy",
"bigot",
"bilge",
"billy",
"binge",
"bingo",
"biome",
"birch",
"birth",
"bison",
"bitty",
"black",
"blade",
"blame",
"bland",
"blank",
"blare",
"blast",
"blaze",
"bleak",
"bleat",
"bleed",
"bleep",
"blend",
"bless",
"blimp",
"blind",
"blink",
"bliss",
"blitz",
"bloat",
"block",
"bloke",
"blond",
"blood",
"bloom",
"blown",
"bluer",
"bluff",
"blunt",
"blurb",
"blurt",
"blush",
"board",
"boast",
"bobby",
"boney",
"bongo",
"bonus",
"booby",
"boost",
"booth",
"booty",
"booze",
"boozy",
"borax",
"borne",
"bosom",
"bossy",
"botch",
"bough",
"boule",
"bound",
"bowel",
"boxer",
"brace",
"braid",
"brain",
"brake",
"brand",
"brash",
"brass",
"brave",
"bravo",
"brawl",
"brawn",
"bread",
"break",
"breed",
"briar",
"bribe",
"brick",
"bride",
"brief",
"brine",
"bring",
"brink",
"briny",
"brisk",
"broad",
"broil",
"broke",
"brood",
"brook",
"broom",
"broth",
"brown",
"brunt",
"brush",
"brute",
"buddy",
"budge",
"buggy",
"bugle",
"build",
"built",
"bulge",
"bulky",
"bully",
"bunch",
"bunny",
"burly",
"burnt",
"burst",
"bused",
"bushy",
"butch",
"butte",
"buxom",
"buyer",
"bylaw",
"cabal",
"cabby",
"cabin",
"cable",
"cacao",
"cache",
"cacti",
"caddy",
"cadet",
"cagey",
"cairn",
"camel",
"cameo",
"canal",
"candy",
"canny",
"canoe",
"canon",
"caper",
"caput",
"carat",
"cargo",
"carol",
"carry",
"carve",
"caste",
"catch",
"cater",
"catty",
"caulk",
"cause",
"cavil",
"cease",
"cedar",
"cello",
"chafe",
"chaff",
"chain",
"chair",
"chalk",
"champ",
"chant",
"chaos",
"chard",
"charm",
"chart",
"chase",
"chasm",
"cheap",
"cheat",
"check",
"cheek",
"cheer",
"chess",
"chest",
"chick",
"chide",
"chief",
"child",
"chili",
"chill",
"chime",
"china",
"chirp",
"chock",
"choir",
"choke",
"chord",
"chore",
"chose",
"chuck",
"chump",
"chunk",
"churn",
"chute",
"cider",
"cigar",
"cinch",
"circa",
"civic",
"civil",
"clack",
"claim",
"clamp",
"clang",
"clank",
"clash",
"clasp",
"class",
"clean",
"clear",
"cleat",
"cleft",
"clerk",
"click",
"cliff",
"climb",
"cling",
"clink",
"cloak",
"clock",
"clone",
"close",
"cloth",
"cloud",
"clout",
"clove",
"clown",
"cluck",
"clued",
"clump",
"clung",
"coach",
"coast",
"cobra",
"cocoa",
"colon",
"color",
"comet",
"comfy",
"comic",
"comma",
"conch",
"condo",
"conic",
"copse",
"coral",
"corer",
"corny",
"couch",
"cough",
"could",
"count",
"coupe",
"court",
"coven",
"cover",
"covet",
"covey",
"cower",
"coyly",
"crack",
"craft",
"cramp",
"crane",
"crank",
"crash",
"crass",
"crate",
"crave",
"crawl",
"craze",
"crazy",
"creak",
"cream",
"credo",
"creed",
"creek",
"creep",
"creme",
"crepe",
"crept",
"cress",
"crest",
"crick",
"cried",
"crier",
"crime",
"crimp",
"crisp",
"croak",
"crock",
"crone",
"crony",
"crook",
"cross",
"croup",
"crowd",
"crown",
"crude",
"cruel",
"crumb",
"crump",
"crush",
"crust",
"crypt",
"cubic",
"cumin",
"curio",
"curly",
"curry",
"curse",
"curve",
"curvy",
"cutie",
"cyber",
"cycle",
"cynic",
"daddy",
"daily",
"dairy",
"daisy",
"dally",
"dance",
"dandy",
"datum",
"daunt",
"dealt",
"death",
"debar",
"debit",
"debug",
"debut",
"decal",
"decay",
"decor",
"decoy",
"decry",
"defer",
"deign",
"deity",
"delay",
"delta",
"delve",
"demon",
"demur",
"denim",
"dense",
"depot",
"depth",
"derby",
"deter",
"detox",
"deuce",
"devil",
"diary",
"dicey",
"digit",
"dilly",
"dimly",
"diner",
"dingo",
"dingy",
"diode",
"dirge",
"dirty",
"disco",
"ditch",
"ditto",
"ditty",
"diver",
"dizzy",
"dodge",
"dodgy",
"dogma",
"doing",
"dolly",
"donor",
"donut",
"dopey",
"doubt",
"dough",
"dowdy",
"dowel",
"downy",
"dowry",
"dozen",
"draft",
"drain",
"drake",
"drama",
"drank",
"drape",
"drawl",
"drawn",
"dread",
"dream",
"dress",
"dried",
"drier",
"drift",
"drill",
"drink",
"drive",
"droit",
"droll",
"drone",
"drool",
"droop",
"dross",
"drove",
"drown",
"druid",
"drunk",
"dryer",
"dryly",
"duchy",
"dully",
"dummy",
"dumpy",
"dunce",
"dusky",
"dusty",
"dutch",
"duvet",
"dwarf",
"dwell",
"dwelt",
"dying",
"eager",
"eagle",
"early",
"earth",
"easel",
"eaten",
"eater",
"ebony",
"eclat",
"edict",
"edify",
"eerie",
"egret",
"eight",
"eject",
"eking",
"elate",
"elbow",
"elder",
"elect",
"elegy",
"elfin",
"elide",
"elite",
"elope",
"elude",
"email",
"embed",
"ember",
"emcee",
"empty",
"enact",
"endow",
"enema",
"enemy",
"enjoy",
"ennui",
"ensue",
"enter",
"entry",
"envoy",
"epoch",
"epoxy",
"equal",
"equip",
"erase",
"erect",
"erode",
"error",
"erupt",
"essay",
"ester",
"ether",
"ethic",
"ethos",
"etude",
"evade",
"event",
"every",
"evict",
"evoke",
"exact",
"exalt",
"excel",
"exert",
"exile",
"exist",
"expel",
"extol",
"extra",
"exult",
"eying",
"fable",
"facet",
"faint",
"fairy",
"faith",
"false",
"fancy",
"fanny",
"farce",
"fatal",
"fatty",
"fault",
"fauna",
"favor",
"feast",
"fecal",
"feign",
"fella",
"felon",
"femme",
"femur",
"fence",
"feral",
"ferry",
"fetal",
"fetch",
"fetid",
"fetus",
"fever",
"fewer",
"fiber",
"ficus",
"field",
"fiend",
"fiery",
"fifth",
"fifty",
"fight",
"filer",
"filet",
"filly",
"filmy",
"filth",
"final",
"finch",
"finer",
"first",
"fishy",
"fixer",
"fizzy",
"fjord",
"flack",
"flail",
"flair",
"flake",
"flaky",
"flame",
"flank",
"flare",
"flash",
"flask",
"fleck",
"fleet",
"flesh",
"flick",
"flier",
"fling",
"flint",
"flirt",
"float",
"flock",
"flood",
"floor",
"flora",
"floss",
"flour",
"flout",
"flown",
"fluff",
"fluid",
"fluke",
"flume",
"flung",
"flunk",
"flush",
"flute",
"flyer",
"foamy",
"focal",
"focus",
"foggy",
"foist",
"folio",
"folly",
"foray",
"force",
"forge",
"forgo",
"forte",
"forth",
"forty",
"forum",
"found",
"foyer",
"frail",
"frame",
"frank",
"fraud",
"freak",
"freed",
"freer",
"fresh",
"friar",
"fried",
"frill",
"frisk",
"fritz",
"frock",
"frond",
"front",
"frost",
"froth",
"frown",
"froze",
"fruit",
"fudge",
"fugue",
"fully",
"fungi",
"funky",
"funny",
"furor",
"furry",
"fussy",
"fuzzy",
"gaffe",
"gaily",
"gamer",
"gamma",
"gamut",
"gassy",
"gaudy",
"gauge",
"gaunt",
"gauze",
"gavel",
"gawky",
"gayer",
"gayly",
"gazer",
"gecko",
"geeky",
"geese",
"genie",
"genre",
"ghost",
"ghoul",
"giant",
"giddy",
"gipsy",
"girly",
"girth",
"given",
"giver",
"glade",
"gland",
"glare",
"glass",
"glaze",
"gleam",
"glean",
"glide",
"glint",
"gloat",
"globe",
"gloom",
"glory",
"gloss",
"glove",
"glyph",
"gnash",
"gnome",
"godly",
"going",
"golem",
"golly",
"gonad",
"goner",
"goody",
"gooey",
"goofy",
"goose",
"gorge",
"gouge",
"gourd",
"grace",
"grade",
"graft",
"grail",
"grain",
"grand",
"grant",
"grape",
"graph",
"grasp",
"grass",
"grate",
"grave",
"gravy",
"graze",
"great",
"greed",
"green",
"greet",
"grief",
"grill",
"grime",
"grimy",
"grind",
"gripe",
"groan",
"groin",
"groom",
"grope",
"gross",
"group",
"grout",
"grove",
"growl",
"grown",
"gruel",
"gruff",
"grunt",
"guard",
"guava",
"guess",
"guest",
"guide",
"guild",
"guile",
"guilt",
"guise",
"gulch",
"gully",
"gumbo",
"gummy",
"guppy",
"gusto",
"gusty",
"gypsy",
"habit",
"hairy",
"halve",
"handy",
"happy",
"hardy",
"harem",
"harpy",
"harry",
"harsh",
"haste",
"hasty",
"hatch",
"hater",
"haunt",
"haute",
"haven",
"havoc",
"hazel",
"heady",
"heard",
"heart",
"heath",
"heave",
"heavy",
"hedge",
"hefty",
"heist",
"helix",
"hello",
"hence",
"heron",
"hilly",
"hinge",
"hippo",
"hippy",
"hitch",
"hoard",
"hobby",
"hoist",
"holly",
"homer",
"honey",
"honor",
"horde",
"horny",
"horse",
"hotel",
"hotly",
"hound",
"house",
"hovel",
"hover",
"howdy",
"human",
"humid",
"humor",
"humph",
"humus",
"hunch",
"hunky",
"hurry",
"husky",
"hussy",
"hutch",
"hydro",
"hyena",
"hymen",
"hyper",
"icily",
"icing",
"ideal",
"idiom",
"idiot",
"idler",
"idyll",
"igloo",
"iliac",
"image",
"imbue",
"impel",
"imply",
"inane",
"inbox",
"incur",
"index",
"inept",
"inert",
"infer",
"ingot",
"inlay",
"inlet",
"inner",
"input",
"inter",
"intro",
"ionic",
"irate",
"irony",
"islet",
"issue",
"itchy",
"ivory",
"jaunt",
"jazzy",
"jelly",
"jerky",
"jetty",
"jewel",
"jiffy",
"joint",
"joist",
"joker",
"jolly",
"joust",
"judge",
"juice",
"juicy",
"jumbo",
"jumpy",
"junta",
"junto",
"juror",
"kappa",
"karma",
"kayak",
"kebab",
"khaki",
"kinky",
"kiosk",
"kitty",
"knack",
"knave",
"knead",
"kneed",
"kneel",
"knelt",
"knife",
"knock",
"knoll",
"known",
"koala",
"krill",
"label",
"labor",
"laden",
"ladle",
"lager",
"lance",
"lanky",
"lapel",
"lapse",
"large",
"larva",
"lasso",
"latch",
"later",
"lathe",
"latte",
"laugh",
"layer",
"leach",
"leafy",
"leaky",
"leant",
"leapt",
"learn",
"lease",
"leash",
"least",
"leave",
"ledge",
"leech",
"leery",
"lefty",
"legal",
"leggy",
"lemon",
"lemur",
"leper",
"level",
"lever",
"libel",
"liege",
"light",
"liken",
"lilac",
"limbo",
"limit",
"linen",
"liner",
"lingo",
"lipid",
"lithe",
"liver",
"livid",
"llama",
"loamy",
"loath",
"lobby",
"local",
"locus",
"lodge",
"lofty",
"logic",
"login",
"loopy",
"loose",
"lorry",
"loser",
"louse",
"lousy",
"lover",
"lower",
"lowly",
"loyal",
"lucid",
"lucky",
"lumen",
"lumpy",
"lunar",
"lunch",
"lunge",
"lupus",
"lurch",
"lurid",
"lusty",
"lying",
"lymph",
"lyric",
"macaw",
"macho",
"macro",
"madam",
"madly",
"mafia",
"magic",
"magma",
"maize",
"major",
"maker",
"mambo",
"mamma",
"mammy",
"manga",
"mange",
"mango",
"mangy",
"mania",
"manic",
"manly",
"manor",
"maple",
"march",
"marry",
"marsh",
"mason",
"masse",
"match",
"matey",
"mauve",
"maxim",
"maybe",
"mayor",
"mealy",
"meant",
"meaty",
"mecca",
"medal",
"media",
"medic",
"melee",
"melon",
"mercy",
"merge",
"merit",
"merry",
"metal",
"meter",
"metro",
"micro",
"midge",
"midst",
"might",
"milky",
"mimic",
"mince",
"miner",
"minim",
"minor",
"minty",
"minus",
"mirth",
"miser",
"missy",
"mocha",
"modal",
"model",
"modem",
"mogul",
"moist",
"molar",
"moldy",
"money",
"month",
"moody",
"moose",
"moral",
"moron",
"morph",
"mossy",
"motel",
"motif",
"motor",
"motto",
"moult",
"mound",
"mount",
"mourn",
"mouse",
"mouth",
"mover",
"movie",
"mower",
"mucky",
"mucus",
"muddy",
"mulch",
"mummy",
"munch",
"mural",
"murky",
"mushy",
"music",
"musky",
"musty",
"myrrh",
"nadir",
"naive",
"nanny",
"nasal",
"nasty",
"natal",
"naval",
"navel",
"needy",
"neigh",
"nerdy",
"nerve",
"never",
"newer",
"newly",
"nicer",
"niche",
"niece",
"night",
"ninja",
"ninny",
"ninth",
"noble",
"nobly",
"noise",
"noisy",
"nomad",
"noose",
"north",
"nosey",
"notch",
"novel",
"nudge",
"nurse",
"nutty",
"nylon",
"nymph",
"oaken",
"obese",
"occur",
"ocean",
"octal",
"octet",
"odder",
"oddly",
"offal",
"offer",
"often",
"olden",
"older",
"olive",
"ombre",
"omega",
"onion",
"onset",
"opera",
"opine",
"opium",
"optic",
"orbit",
"order",
"organ",
"other",
"otter",
"ought",
"ounce",
"outdo",
"outer",
"outgo",
"ovary",
"ovate",
"overt",
"ovine",
"ovoid",
"owing",
"owner",
"oxide",
"ozone",
"paddy",
"pagan",
"paint",
"paler",
"palsy",
"panel",
"panic",
"pansy",
"papal",
"paper",
"parer",
"parka",
"parry",
"parse",
"party",
"pasta",
"paste",
"pasty",
"patch",
"patio",
"patsy",
"patty",
"pause",
"payee",
"payer",
"peace",
"peach",
"pearl",
"pecan",
"pedal",
"penal",
"pence",
"penne",
"penny",
"perch",
"peril",
"perky",
"pesky",
"pesto",
"petal",
"petty",
"phase",
"phone",
"phony",
"photo",
"piano",
"picky",
"piece",
"piety",
"piggy",
"pilot",
"pinch",
"piney",
"pinky",
"pinto",
"piper",
"pique",
"pitch",
"pithy",
"pivot",
"pixel",
"pixie",
"pizza",
"place",
"plaid",
"plain",
"plait",
"plane",
"plank",
"plant",
"plate",
"plaza",
"plead",
"pleat",
"plied",
"plier",
"pluck",
"plumb",
"plume",
"plump",
"plunk",
"plush",
"poesy",
"point",
"poise",
"poker",
"polar",
"polka",
"polyp",
"pooch",
"poppy",
"porch",
"poser",
"posit",
"posse",
"pouch",
"pound",
"pouty",
"power",
"prank",
"prawn",
"preen",
"press",
"price",
"prick",
"pride",
"pried",
"prime",
"primo",
"print",
"prior",
"prism",
"privy",
"prize",
"probe",
"prone",
"prong",
"proof",
"prose",
"proud",
"prove",
"prowl",
"proxy",
"prude",
"prune",
"psalm",
"pubic",
"pudgy",
"puffy",
"pulpy",
"pulse",
"punch",
"pupil",
"puppy",
"puree",
"purer",
"purge",
"purse",
"pushy",
"putty",
"pygmy",
"quack",
"quail",
"quake",
"qualm",
"quark",
"quart",
"quash",
"quasi",
"queen",
"queer",
"quell",
"query",
"quest",
"queue",
"quick",
"quiet",
"quill",
"quilt",
"quirk",
"quite",
"quota",
"quote",
"quoth",
"rabbi",
"rabid",
"racer",
"radar",
"radii",
"radio",
"rainy",
"raise",
"rajah",
"rally",
"ralph",
"ramen",
"ranch",
"randy",
"range",
"rapid",
"rarer",
"raspy",
"ratio",
"ratty",
"raven",
"rayon",
"razor",
"reach",
"react",
"ready",
"realm",
"rearm",
"rebar",
"rebel",
"rebus",
"rebut",
"recap",
"recur",
"recut",
"reedy",
"refer",
"refit",
"regal",
"rehab",
"reign",
"relax",
"relay",
"relic",
"remit",
"renal",
"renew",
"repay",
"repel",
"reply",
"rerun",
"reset",
"resin",
"retch",
"retro",
"retry",
"reuse",
"revel",
"revue",
"rhino",
"rhyme",
"rider",
"ridge",
"rifle",
"right",
"rigid",
"rigor",
"rinse",
"ripen",
"riper",
"risen",
"riser",
"risky",
"rival",
"river",
"rivet",
"roach",
"roast",
"robin",
"robot",
"rocky",
"rodeo",
"roger",
"rogue",
"roomy",
"roost",
"rotor",
"rouge",
"rough",
"round",
"rouse",
"route",
"rover",
"rowdy",
"rower",
"royal",
"ruddy",
"ruder",
"rugby",
"ruler",
"rumba",
"rumor",
"rupee",
"rural",
"rusty",
"sadly",
"safer",
"saint",
"salad",
"sally",
"salon",
"salsa",
"salty",
"salve",
"salvo",
"sandy",
"saner",
"sappy",
"sassy",
"satin",
"satyr",
"sauce",
"saucy",
"sauna",
"saute",
"savor",
"savoy",
"savvy",
"scald",
"scale",
"scalp",
"scaly",
"scamp",
"scant",
"scare",
"scarf",
"scary",
"scene",
"scent",
"scion",
"scoff",
"scold",
"scone",
"scoop",
"scope",
"score",
"scorn",
"scour",
"scout",
"scowl",
"scram",
"scrap",
"scree",
"screw",
"scrub",
"scrum",
"scuba",
"sedan",
"seedy",
"segue",
"seize",
"semen",
"sense",
"sepia",
"serif",
"serum",
"serve",
"setup",
"seven",
"sever",
"sewer",
"shack",
"shade",
"shady",
"shaft",
"shake",
"shaky",
"shale",
"shall",
"shalt",
"shame",
"shank",
"shape",
"shard",
"share",
"shark",
"sharp",
"shave",
"shawl",
"shear",
"sheen",
"sheep",
"sheer",
"sheet",
"sheik",
"shelf",
"shell",
"shied",
"shift",
"shine",
"shiny",
"shire",
"shirk",
"shirt",
"shoal",
"shock",
"shone",
"shook",
"shoot",
"shore",
"shorn",
"short",
"shout",
"shove",
"shown",
"showy",
"shrew",
"shrub",
"shrug",
"shuck",
"shunt",
"shush",
"shyly",
"siege",
"sieve",
"sight",
"sigma",
"silky",
"silly",
"since",
"sinew",
"singe",
"siren",
"sissy",
"sixth",
"sixty",
"skate",
"skier",
"skiff",
"skill",
"skimp",
"skirt",
"skulk",
"skull",
"skunk",
"slack",
"slain",
"slang",
"slant",
"slash",
"slate",
"sleek",
"sleep",
"sleet",
"slept",
"slice",
"slick",
"slide",
"slime",
"slimy",
"sling",
"slink",
"sloop",
"slope",
"slosh",
"sloth",
"slump",
"slung",
"slunk",
"slurp",
"slush",
"slyly",
"smack",
"small",
"smart",
"smash",
"smear",
"smell",
"smelt",
"smile",
"smirk",
"smite",
"smith",
"smock",
"smoke",
"smoky",
"smote",
"snack",
"snail",
"snake",
"snaky",
"snare",
"snarl",
"sneak",
"sneer",
"snide",
"sniff",
"snipe",
"snoop",
"snore",
"snort",
"snout",
"snowy",
"snuck",
"snuff",
"soapy",
"sober",
"soggy",
"solar",
"solid",
"solve",
"sonar",
"sonic",
"sooth",
"sooty",
"sorry",
"sound",
"south",
"sower",
"space",
"spade",
"spank",
"spare",
"spark",
"spasm",
"spawn",
"speak",
"spear",
"speck",
"speed",
"spell",
"spelt",
"spend",
"spent",
"sperm",
"spice",
"spicy",
"spied",
"spiel",
"spike",
"spiky",
"spill",
"spilt",
"spine",
"spiny",
"spire",
"spite",
"splat",
"split",
"spoil",
"spoke",
"spoof",
"spook",
"spool",
"spoon",
"spore",
"sport",
"spout",
"spray",
"spree",
"sprig",
"spunk",
"spurn",
"spurt",
"squad",
"squat",
"squib",
"stack",
"staff",
"stage",
"staid",
"stain",
"stair",
"stake",
"stale",
"stalk",
"stall",
"stamp",
"stand",
"stank",
"stare",
"stark",
"start",
"stash",
"state",
"stave",
"stead",
"steak",
"steal",
"steam",
"steed",
"steel",
"steep",
"steer",
"stein",
"stern",
"stick",
"stiff",
"still",
"stilt",
"sting",
"stink",
"stint",
"stock",
"stoic",
"stoke",
"stole",
"stomp",
"stone",
"stony",
"stood",
"stool",
"stoop",
"store",
"stork",
"storm",
"story",
"stout",
"stove",
"strap",
"straw",
"stray",
"strip",
"strut",
"stuck",
"study",
"stuff",
"stump",
"stung",
"stunk",
"stunt",
"style",
"suave",
"sugar",
"suing",
"suite",
"sulky",
"sully",
"sumac",
"sunny",
"super",
"surer",
"surge",
"surly",
"sushi",
"swami",
"swamp",
"swarm",
"swash",
"swath",
"swear",
"sweat",
"sweep",
"sweet",
"swell",
"swept",
"swift",
"swill",
"swine",
"swing",
"swirl",
"swish",
"swoon",
"swoop",
"sword",
"swore",
"sworn",
"swung",
"synod",
"syrup",
"tabby",
"table",
"taboo",
"tacit",
"tacky",
"taffy",
"taint",
"taken",
"taker",
"tally",
"talon",
"tamer",
"tango",
"tangy",
"taper",
"tapir",
"tardy",
"tarot",
"taste",
"tasty",
"tatty",
"taunt",
"tawny",
"teach",
"teary",
"tease",
"teddy",
"teeth",
"tempo",
"tenet",
"tenor",
"tense",
"tenth",
"tepee",
"tepid",
"terra",
"terse",
"testy",
"thank",
"theft",
"their",
"theme",
"there",
"these",
"theta",
"thick",
"thief",
"thigh",
"thing",
"think",
"third",
"thong",
"thorn",
"those",
"three",
"threw",
"throb",
"throw",
"thrum",
"thumb",
"thump",
"thyme",
"tiara",
"tibia",
"tidal",
"tiger",
"tight",
"tilde",
"timer",
"timid",
"tipsy",
"titan",
"tithe",
"title",
"toast",
"today",
"toddy",
"token",
"tonal",
"tonga",
"tonic",
"tooth",
"topaz",
"topic",
"torch",
"torso",
"torus",
"total",
"totem",
"touch",
"tough",
"towel",
"tower",
"toxic",
"toxin",
"trace",
"track",
"tract",
"trade",
"trail",
"train",
"trait",
"tramp",
"trash",
"trawl",
"tread",
"treat",
"trend",
"triad",
"trial",
"tribe",
"trice",
"trick",
"tried",
"tripe",
"trite",
"troll",
"troop",
"trope",
"trout",
"trove",
"truce",
"truck",
"truer",
"truly",
"trump",
"trunk",
"truss",
"trust",
"truth",
"tryst",
"tubal",
"tuber",
"tulip",
"tulle",
"tumor",
"tunic",
"turbo",
"tutor",
"twang",
"tweak",
"tweed",
"tweet",
"twice",
"twine",
"twirl",
"twist",
"twixt",
"tying",
"udder",
"ulcer",
"ultra",
"umbra",
"uncle",
"uncut",
"under",
"undid",
"undue",
"unfed",
"unfit",
"unify",
"union",
"unite",
"unity",
"unlit",
"unmet",
"unset",
"untie",
"until",
"unwed",
"unzip",
"upper",
"upset",
"urban",
"urine",
"usage",
"usher",
"using",
"usual",
"usurp",
"utile",
"utter",
"vague",
"valet",
"valid",
"valor",
"value",
"valve",
"vapid",
"vapor",
"vault",
"vaunt",
"vegan",
"venom",
"venue",
"verge",
"verse",
"verso",
"verve",
"vicar",
"video",
"vigil",
"vigor",
"villa",
"vinyl",
"viola",
"viper",
"viral",
"virus",
"visit",
"visor",
"vista",
"vital",
"vivid",
"vixen",
"vocal",
"vodka",
"vogue",
"voice",
"voila",
"vomit",
"voter",
"vouch",
"vowel",
"vying",
"wacky",
"wafer",
"wager",
"wagon",
"waist",
"waive",
"waltz",
"warty",
"waste",
"watch",
"water",
"waver",
"waxen",
"weary",
"weave",
"wedge",
"weedy",
"weigh",
"weird",
"welch",
"welsh",
"whack",
"whale",
"wharf",
"wheat",
"wheel",
"whelp",
"where",
"which",
"whiff",
"while",
"whine",
"whiny",
"whirl",
"whisk",
"white",
"whole",
"whoop",
"whose",
"widen",
"wider",
"widow",
"width",
"wield",
"wight",
"willy",
"wimpy",
"wince",
"winch",
"windy",
"wiser",
"wispy",
"witch",
"witty",
"woken",
"woman",
"women",
"woody",
"wooer",
"wooly",
"woozy",
"wordy",
"world",
"worry",
"worse",
"worst",
"worth",
"would",
"wound",
"woven",
"wrack",
"wrath",
"wreak",
"wreck",
"wrest",
"wring",
"wrist",
"write",
"wrong",
"wrote",
"wrung",
"wryly",
"yacht",
"yearn",
"yeast",
"yield",
"young",
"youth",
"zebra",
"zesty",
"zonal",
));
}
public String getRandomWord()
{
Random random = new Random();
return word.List.get(random.nextInt(worldlist.size());
}
|
bd184ef124acd7acc5419e60c69f87a8
|
{
"intermediate": 0.3159773349761963,
"beginner": 0.49839505553245544,
"expert": 0.1856275498867035
}
|
38,235
|
I have this code:
@Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
updateUI(currentUser);
}
private void updateUI(FirebaseUser user) {
if (user==null) {
mAuth.signInAnonymously().addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
FirebaseUser user = mAuth.getCurrentUser();
updateUI(user);
} else {
updateUI(null);
}
}
});
}
}
}
I think it logs the user in anonymously to Google Firebase. But I want to link some values (nickname and score) in a Firebase database to the anonymous UID-s. How should I do it?
|
91b07d7d628b9fe9521f9bf93d606a36
|
{
"intermediate": 0.5339068174362183,
"beginner": 0.30844247341156006,
"expert": 0.15765076875686646
}
|
38,236
|
tell me whats wrong with my code import java.util.Scanner;
public class wordle {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
RandomWordList randomWordList = new RandomWordList();
String targetWord = randomWordList.getRandomWord();
int attempts = 6;
System.out.println("Welcome to Wordle!");
System.out.println("You have "+ attempts +" attempts to guess a 5-letter word.\n");
for (int i = 1; i <= attempts; i++) {
System.out.print("Attempt " + i + ": ");
String guess = scanner.next().toLowerCase();
if (guess.length() != targetWord.length()) {
System.out.println("Please enter a 5-letter word.");
i--;
continue;
}
if (guess.equals(targetWord)) {
System.out.println("Congratulations! You've guessed the word!");
break;
} else {
giveFeedback(guess, targetWord);
}
if (i == attempts) {
System.out.println("Game Over. The word was: " + targetWord);
}
}
scanner.close();
}
private static void giveFeedback(String guess, String targetWord) {
char[] feedback = new char[targetWord.length()];
for (int i = 0; i < targetWord.length(); i++) {
String targetLetter = targetWord.substring(i, i+1);
String guessLetter = guess.substring(i, i+1);
if (guessLetter.equals(targetLetter)) {
feedback[i] = targetLetter.charAt(0);
} else if (targetWord.contains(guessLetter)) {
feedback[i] = '+';
} else {
feedback[i] = '_'; //
}
}
System.out.println(new String(feedback));
}
}
|
266bdf455b05ef7efd3dcb5937bdbdc5
|
{
"intermediate": 0.24085618555545807,
"beginner": 0.6225444078445435,
"expert": 0.13659942150115967
}
|
38,237
|
Ray from mouse to game unity
|
7ccff66a513767d17511c596bc9ffa36
|
{
"intermediate": 0.3398199677467346,
"beginner": 0.2971312701702118,
"expert": 0.3630487620830536
}
|
38,238
|
fix my code pls import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
public class RandomWordList{
List <String> wordList = new ArrayList<>(Arrays.asList(
"aback",
"abase",
"abate",
"abbey",
"abbot",
"abhor",
"abide",
"abled",
"abode",
"abort",
"about",
"above",
"abuse",
"abyss",
"acorn",
"acrid",
"actor",
"acute",
"adage",
"adapt",
"adept",
"admin",
"admit",
"adobe",
"adopt",
"adore",
"adorn",
"adult",
"affix",
"afire",
"afoot",
"afoul",
"after",
"again",
"agape",
"agate",
"agent",
"agile",
"aging",
"aglow",
"agony",
"agree",
"ahead",
"aider",
"aisle",
"alarm",
"album",
"alert",
"algae",
"alibi",
"alien",
"align",
"alike",
"alive",
"allay",
"alley",
"allot",
"allow",
"alloy",
"aloft",
"alone",
"along",
"aloof",
"aloud",
"alpha",
"altar",
"alter",
"amass",
"amaze",
"amber",
"amble",
"amend",
"amiss",
"amity",
"among",
"ample",
"amply",
"amuse",
"angel",
"anger",
"angle",
"angry",
"angst",
"anime",
"ankle",
"annex",
"annoy",
"annul",
"anode",
"antic",
"anvil",
"aorta",
"apart",
"aphid",
"aping",
"apnea",
"apple",
"apply",
"apron",
"aptly",
"arbor",
"ardor",
"arena",
"argue",
"arise",
"armor",
"aroma",
"arose",
"array",
"arrow",
"arson",
"artsy",
"ascot",
"ashen",
"aside",
"askew",
"assay",
"asset",
"atoll",
"atone",
"attic",
"audio",
"audit",
"augur",
"aunty",
"avail",
"avert",
"avian",
"avoid",
"await",
"awake",
"award",
"aware",
"awash",
"awful",
"awoke",
"axial",
"axiom",
"axion",
"azure",
"bacon",
"badge",
"badly",
"bagel",
"baggy",
"baker",
"baler",
"balmy",
"banal",
"banjo",
"barge",
"baron",
"basal",
"basic",
"basil",
"basin",
"basis",
"baste",
"batch",
"bathe",
"baton",
"batty",
"bawdy",
"bayou",
"beach",
"beady",
"beard",
"beast",
"beech",
"beefy",
"befit",
"began",
"begat",
"beget",
"begin",
"begun",
"being",
"belch",
"belie",
"belle",
"belly",
"below",
"bench",
"beret",
"berry",
"berth",
"beset",
"betel",
"bevel",
"bezel",
"bible",
"bicep",
"biddy",
"bigot",
"bilge",
"billy",
"binge",
"bingo",
"biome",
"birch",
"birth",
"bison",
"bitty",
"black",
"blade",
"blame",
"bland",
"blank",
"blare",
"blast",
"blaze",
"bleak",
"bleat",
"bleed",
"bleep",
"blend",
"bless",
"blimp",
"blind",
"blink",
"bliss",
"blitz",
"bloat",
"block",
"bloke",
"blond",
"blood",
"bloom",
"blown",
"bluer",
"bluff",
"blunt",
"blurb",
"blurt",
"blush",
"board",
"boast",
"bobby",
"boney",
"bongo",
"bonus",
"booby",
"boost",
"booth",
"booty",
"booze",
"boozy",
"borax",
"borne",
"bosom",
"bossy",
"botch",
"bough",
"boule",
"bound",
"bowel",
"boxer",
"brace",
"braid",
"brain",
"brake",
"brand",
"brash",
"brass",
"brave",
"bravo",
"brawl",
"brawn",
"bread",
"break",
"breed",
"briar",
"bribe",
"brick",
"bride",
"brief",
"brine",
"bring",
"brink",
"briny",
"brisk",
"broad",
"broil",
"broke",
"brood",
"brook",
"broom",
"broth",
"brown",
"brunt",
"brush",
"brute",
"buddy",
"budge",
"buggy",
"bugle",
"build",
"built",
"bulge",
"bulky",
"bully",
"bunch",
"bunny",
"burly",
"burnt",
"burst",
"bused",
"bushy",
"butch",
"butte",
"buxom",
"buyer",
"bylaw",
"cabal",
"cabby",
"cabin",
"cable",
"cacao",
"cache",
"cacti",
"caddy",
"cadet",
"cagey",
"cairn",
"camel",
"cameo",
"canal",
"candy",
"canny",
"canoe",
"canon",
"caper",
"caput",
"carat",
"cargo",
"carol",
"carry",
"carve",
"caste",
"catch",
"cater",
"catty",
"caulk",
"cause",
"cavil",
"cease",
"cedar",
"cello",
"chafe",
"chaff",
"chain",
"chair",
"chalk",
"champ",
"chant",
"chaos",
"chard",
"charm",
"chart",
"chase",
"chasm",
"cheap",
"cheat",
"check",
"cheek",
"cheer",
"chess",
"chest",
"chick",
"chide",
"chief",
"child",
"chili",
"chill",
"chime",
"china",
"chirp",
"chock",
"choir",
"choke",
"chord",
"chore",
"chose",
"chuck",
"chump",
"chunk",
"churn",
"chute",
"cider",
"cigar",
"cinch",
"circa",
"civic",
"civil",
"clack",
"claim",
"clamp",
"clang",
"clank",
"clash",
"clasp",
"class",
"clean",
"clear",
"cleat",
"cleft",
"clerk",
"click",
"cliff",
"climb",
"cling",
"clink",
"cloak",
"clock",
"clone",
"close",
"cloth",
"cloud",
"clout",
"clove",
"clown",
"cluck",
"clued",
"clump",
"clung",
"coach",
"coast",
"cobra",
"cocoa",
"colon",
"color",
"comet",
"comfy",
"comic",
"comma",
"conch",
"condo",
"conic",
"copse",
"coral",
"corer",
"corny",
"couch",
"cough",
"could",
"count",
"coupe",
"court",
"coven",
"cover",
"covet",
"covey",
"cower",
"coyly",
"crack",
"craft",
"cramp",
"crane",
"crank",
"crash",
"crass",
"crate",
"crave",
"crawl",
"craze",
"crazy",
"creak",
"cream",
"credo",
"creed",
"creek",
"creep",
"creme",
"crepe",
"crept",
"cress",
"crest",
"crick",
"cried",
"crier",
"crime",
"crimp",
"crisp",
"croak",
"crock",
"crone",
"crony",
"crook",
"cross",
"croup",
"crowd",
"crown",
"crude",
"cruel",
"crumb",
"crump",
"crush",
"crust",
"crypt",
"cubic",
"cumin",
"curio",
"curly",
"curry",
"curse",
"curve",
"curvy",
"cutie",
"cyber",
"cycle",
"cynic",
"daddy",
"daily",
"dairy",
"daisy",
"dally",
"dance",
"dandy",
"datum",
"daunt",
"dealt",
"death",
"debar",
"debit",
"debug",
"debut",
"decal",
"decay",
"decor",
"decoy",
"decry",
"defer",
"deign",
"deity",
"delay",
"delta",
"delve",
"demon",
"demur",
"denim",
"dense",
"depot",
"depth",
"derby",
"deter",
"detox",
"deuce",
"devil",
"diary",
"dicey",
"digit",
"dilly",
"dimly",
"diner",
"dingo",
"dingy",
"diode",
"dirge",
"dirty",
"disco",
"ditch",
"ditto",
"ditty",
"diver",
"dizzy",
"dodge",
"dodgy",
"dogma",
"doing",
"dolly",
"donor",
"donut",
"dopey",
"doubt",
"dough",
"dowdy",
"dowel",
"downy",
"dowry",
"dozen",
"draft",
"drain",
"drake",
"drama",
"drank",
"drape",
"drawl",
"drawn",
"dread",
"dream",
"dress",
"dried",
"drier",
"drift",
"drill",
"drink",
"drive",
"droit",
"droll",
"drone",
"drool",
"droop",
"dross",
"drove",
"drown",
"druid",
"drunk",
"dryer",
"dryly",
"duchy",
"dully",
"dummy",
"dumpy",
"dunce",
"dusky",
"dusty",
"dutch",
"duvet",
"dwarf",
"dwell",
"dwelt",
"dying",
"eager",
"eagle",
"early",
"earth",
"easel",
"eaten",
"eater",
"ebony",
"eclat",
"edict",
"edify",
"eerie",
"egret",
"eight",
"eject",
"eking",
"elate",
"elbow",
"elder",
"elect",
"elegy",
"elfin",
"elide",
"elite",
"elope",
"elude",
"email",
"embed",
"ember",
"emcee",
"empty",
"enact",
"endow",
"enema",
"enemy",
"enjoy",
"ennui",
"ensue",
"enter",
"entry",
"envoy",
"epoch",
"epoxy",
"equal",
"equip",
"erase",
"erect",
"erode",
"error",
"erupt",
"essay",
"ester",
"ether",
"ethic",
"ethos",
"etude",
"evade",
"event",
"every",
"evict",
"evoke",
"exact",
"exalt",
"excel",
"exert",
"exile",
"exist",
"expel",
"extol",
"extra",
"exult",
"eying",
"fable",
"facet",
"faint",
"fairy",
"faith",
"false",
"fancy",
"fanny",
"farce",
"fatal",
"fatty",
"fault",
"fauna",
"favor",
"feast",
"fecal",
"feign",
"fella",
"felon",
"femme",
"femur",
"fence",
"feral",
"ferry",
"fetal",
"fetch",
"fetid",
"fetus",
"fever",
"fewer",
"fiber",
"ficus",
"field",
"fiend",
"fiery",
"fifth",
"fifty",
"fight",
"filer",
"filet",
"filly",
"filmy",
"filth",
"final",
"finch",
"finer",
"first",
"fishy",
"fixer",
"fizzy",
"fjord",
"flack",
"flail",
"flair",
"flake",
"flaky",
"flame",
"flank",
"flare",
"flash",
"flask",
"fleck",
"fleet",
"flesh",
"flick",
"flier",
"fling",
"flint",
"flirt",
"float",
"flock",
"flood",
"floor",
"flora",
"floss",
"flour",
"flout",
"flown",
"fluff",
"fluid",
"fluke",
"flume",
"flung",
"flunk",
"flush",
"flute",
"flyer",
"foamy",
"focal",
"focus",
"foggy",
"foist",
"folio",
"folly",
"foray",
"force",
"forge",
"forgo",
"forte",
"forth",
"forty",
"forum",
"found",
"foyer",
"frail",
"frame",
"frank",
"fraud",
"freak",
"freed",
"freer",
"fresh",
"friar",
"fried",
"frill",
"frisk",
"fritz",
"frock",
"frond",
"front",
"frost",
"froth",
"frown",
"froze",
"fruit",
"fudge",
"fugue",
"fully",
"fungi",
"funky",
"funny",
"furor",
"furry",
"fussy",
"fuzzy",
"gaffe",
"gaily",
"gamer",
"gamma",
"gamut",
"gassy",
"gaudy",
"gauge",
"gaunt",
"gauze",
"gavel",
"gawky",
"gayer",
"gayly",
"gazer",
"gecko",
"geeky",
"geese",
"genie",
"genre",
"ghost",
"ghoul",
"giant",
"giddy",
"gipsy",
"girly",
"girth",
"given",
"giver",
"glade",
"gland",
"glare",
"glass",
"glaze",
"gleam",
"glean",
"glide",
"glint",
"gloat",
"globe",
"gloom",
"glory",
"gloss",
"glove",
"glyph",
"gnash",
"gnome",
"godly",
"going",
"golem",
"golly",
"gonad",
"goner",
"goody",
"gooey",
"goofy",
"goose",
"gorge",
"gouge",
"gourd",
"grace",
"grade",
"graft",
"grail",
"grain",
"grand",
"grant",
"grape",
"graph",
"grasp",
"grass",
"grate",
"grave",
"gravy",
"graze",
"great",
"greed",
"green",
"greet",
"grief",
"grill",
"grime",
"grimy",
"grind",
"gripe",
"groan",
"groin",
"groom",
"grope",
"gross",
"group",
"grout",
"grove",
"growl",
"grown",
"gruel",
"gruff",
"grunt",
"guard",
"guava",
"guess",
"guest",
"guide",
"guild",
"guile",
"guilt",
"guise",
"gulch",
"gully",
"gumbo",
"gummy",
"guppy",
"gusto",
"gusty",
"gypsy",
"habit",
"hairy",
"halve",
"handy",
"happy",
"hardy",
"harem",
"harpy",
"harry",
"harsh",
"haste",
"hasty",
"hatch",
"hater",
"haunt",
"haute",
"haven",
"havoc",
"hazel",
"heady",
"heard",
"heart",
"heath",
"heave",
"heavy",
"hedge",
"hefty",
"heist",
"helix",
"hello",
"hence",
"heron",
"hilly",
"hinge",
"hippo",
"hippy",
"hitch",
"hoard",
"hobby",
"hoist",
"holly",
"homer",
"honey",
"honor",
"horde",
"horny",
"horse",
"hotel",
"hotly",
"hound",
"house",
"hovel",
"hover",
"howdy",
"human",
"humid",
"humor",
"humph",
"humus",
"hunch",
"hunky",
"hurry",
"husky",
"hussy",
"hutch",
"hydro",
"hyena",
"hymen",
"hyper",
"icily",
"icing",
"ideal",
"idiom",
"idiot",
"idler",
"idyll",
"igloo",
"iliac",
"image",
"imbue",
"impel",
"imply",
"inane",
"inbox",
"incur",
"index",
"inept",
"inert",
"infer",
"ingot",
"inlay",
"inlet",
"inner",
"input",
"inter",
"intro",
"ionic",
"irate",
"irony",
"islet",
"issue",
"itchy",
"ivory",
"jaunt",
"jazzy",
"jelly",
"jerky",
"jetty",
"jewel",
"jiffy",
"joint",
"joist",
"joker",
"jolly",
"joust",
"judge",
"juice",
"juicy",
"jumbo",
"jumpy",
"junta",
"junto",
"juror",
"kappa",
"karma",
"kayak",
"kebab",
"khaki",
"kinky",
"kiosk",
"kitty",
"knack",
"knave",
"knead",
"kneed",
"kneel",
"knelt",
"knife",
"knock",
"knoll",
"known",
"koala",
"krill",
"label",
"labor",
"laden",
"ladle",
"lager",
"lance",
"lanky",
"lapel",
"lapse",
"large",
"larva",
"lasso",
"latch",
"later",
"lathe",
"latte",
"laugh",
"layer",
"leach",
"leafy",
"leaky",
"leant",
"leapt",
"learn",
"lease",
"leash",
"least",
"leave",
"ledge",
"leech",
"leery",
"lefty",
"legal",
"leggy",
"lemon",
"lemur",
"leper",
"level",
"lever",
"libel",
"liege",
"light",
"liken",
"lilac",
"limbo",
"limit",
"linen",
"liner",
"lingo",
"lipid",
"lithe",
"liver",
"livid",
"llama",
"loamy",
"loath",
"lobby",
"local",
"locus",
"lodge",
"lofty",
"logic",
"login",
"loopy",
"loose",
"lorry",
"loser",
"louse",
"lousy",
"lover",
"lower",
"lowly",
"loyal",
"lucid",
"lucky",
"lumen",
"lumpy",
"lunar",
"lunch",
"lunge",
"lupus",
"lurch",
"lurid",
"lusty",
"lying",
"lymph",
"lyric",
"macaw",
"macho",
"macro",
"madam",
"madly",
"mafia",
"magic",
"magma",
"maize",
"major",
"maker",
"mambo",
"mamma",
"mammy",
"manga",
"mange",
"mango",
"mangy",
"mania",
"manic",
"manly",
"manor",
"maple",
"march",
"marry",
"marsh",
"mason",
"masse",
"match",
"matey",
"mauve",
"maxim",
"maybe",
"mayor",
"mealy",
"meant",
"meaty",
"mecca",
"medal",
"media",
"medic",
"melee",
"melon",
"mercy",
"merge",
"merit",
"merry",
"metal",
"meter",
"metro",
"micro",
"midge",
"midst",
"might",
"milky",
"mimic",
"mince",
"miner",
"minim",
"minor",
"minty",
"minus",
"mirth",
"miser",
"missy",
"mocha",
"modal",
"model",
"modem",
"mogul",
"moist",
"molar",
"moldy",
"money",
"month",
"moody",
"moose",
"moral",
"moron",
"morph",
"mossy",
"motel",
"motif",
"motor",
"motto",
"moult",
"mound",
"mount",
"mourn",
"mouse",
"mouth",
"mover",
"movie",
"mower",
"mucky",
"mucus",
"muddy",
"mulch",
"mummy",
"munch",
"mural",
"murky",
"mushy",
"music",
"musky",
"musty",
"myrrh",
"nadir",
"naive",
"nanny",
"nasal",
"nasty",
"natal",
"naval",
"navel",
"needy",
"neigh",
"nerdy",
"nerve",
"never",
"newer",
"newly",
"nicer",
"niche",
"niece",
"night",
"ninja",
"ninny",
"ninth",
"noble",
"nobly",
"noise",
"noisy",
"nomad",
"noose",
"north",
"nosey",
"notch",
"novel",
"nudge",
"nurse",
"nutty",
"nylon",
"nymph",
"oaken",
"obese",
"occur",
"ocean",
"octal",
"octet",
"odder",
"oddly",
"offal",
"offer",
"often",
"olden",
"older",
"olive",
"ombre",
"omega",
"onion",
"onset",
"opera",
"opine",
"opium",
"optic",
"orbit",
"order",
"organ",
"other",
"otter",
"ought",
"ounce",
"outdo",
"outer",
"outgo",
"ovary",
"ovate",
"overt",
"ovine",
"ovoid",
"owing",
"owner",
"oxide",
"ozone",
"paddy",
"pagan",
"paint",
"paler",
"palsy",
"panel",
"panic",
"pansy",
"papal",
"paper",
"parer",
"parka",
"parry",
"parse",
"party",
"pasta",
"paste",
"pasty",
"patch",
"patio",
"patsy",
"patty",
"pause",
"payee",
"payer",
"peace",
"peach",
"pearl",
"pecan",
"pedal",
"penal",
"pence",
"penne",
"penny",
"perch",
"peril",
"perky",
"pesky",
"pesto",
"petal",
"petty",
"phase",
"phone",
"phony",
"photo",
"piano",
"picky",
"piece",
"piety",
"piggy",
"pilot",
"pinch",
"piney",
"pinky",
"pinto",
"piper",
"pique",
"pitch",
"pithy",
"pivot",
"pixel",
"pixie",
"pizza",
"place",
"plaid",
"plain",
"plait",
"plane",
"plank",
"plant",
"plate",
"plaza",
"plead",
"pleat",
"plied",
"plier",
"pluck",
"plumb",
"plume",
"plump",
"plunk",
"plush",
"poesy",
"point",
"poise",
"poker",
"polar",
"polka",
"polyp",
"pooch",
"poppy",
"porch",
"poser",
"posit",
"posse",
"pouch",
"pound",
"pouty",
"power",
"prank",
"prawn",
"preen",
"press",
"price",
"prick",
"pride",
"pried",
"prime",
"primo",
"print",
"prior",
"prism",
"privy",
"prize",
"probe",
"prone",
"prong",
"proof",
"prose",
"proud",
"prove",
"prowl",
"proxy",
"prude",
"prune",
"psalm",
"pubic",
"pudgy",
"puffy",
"pulpy",
"pulse",
"punch",
"pupil",
"puppy",
"puree",
"purer",
"purge",
"purse",
"pushy",
"putty",
"pygmy",
"quack",
"quail",
"quake",
"qualm",
"quark",
"quart",
"quash",
"quasi",
"queen",
"queer",
"quell",
"query",
"quest",
"queue",
"quick",
"quiet",
"quill",
"quilt",
"quirk",
"quite",
"quota",
"quote",
"quoth",
"rabbi",
"rabid",
"racer",
"radar",
"radii",
"radio",
"rainy",
"raise",
"rajah",
"rally",
"ralph",
"ramen",
"ranch",
"randy",
"range",
"rapid",
"rarer",
"raspy",
"ratio",
"ratty",
"raven",
"rayon",
"razor",
"reach",
"react",
"ready",
"realm",
"rearm",
"rebar",
"rebel",
"rebus",
"rebut",
"recap",
"recur",
"recut",
"reedy",
"refer",
"refit",
"regal",
"rehab",
"reign",
"relax",
"relay",
"relic",
"remit",
"renal",
"renew",
"repay",
"repel",
"reply",
"rerun",
"reset",
"resin",
"retch",
"retro",
"retry",
"reuse",
"revel",
"revue",
"rhino",
"rhyme",
"rider",
"ridge",
"rifle",
"right",
"rigid",
"rigor",
"rinse",
"ripen",
"riper",
"risen",
"riser",
"risky",
"rival",
"river",
"rivet",
"roach",
"roast",
"robin",
"robot",
"rocky",
"rodeo",
"roger",
"rogue",
"roomy",
"roost",
"rotor",
"rouge",
"rough",
"round",
"rouse",
"route",
"rover",
"rowdy",
"rower",
"royal",
"ruddy",
"ruder",
"rugby",
"ruler",
"rumba",
"rumor",
"rupee",
"rural",
"rusty",
"sadly",
"safer",
"saint",
"salad",
"sally",
"salon",
"salsa",
"salty",
"salve",
"salvo",
"sandy",
"saner",
"sappy",
"sassy",
"satin",
"satyr",
"sauce",
"saucy",
"sauna",
"saute",
"savor",
"savoy",
"savvy",
"scald",
"scale",
"scalp",
"scaly",
"scamp",
"scant",
"scare",
"scarf",
"scary",
"scene",
"scent",
"scion",
"scoff",
"scold",
"scone",
"scoop",
"scope",
"score",
"scorn",
"scour",
"scout",
"scowl",
"scram",
"scrap",
"scree",
"screw",
"scrub",
"scrum",
"scuba",
"sedan",
"seedy",
"segue",
"seize",
"semen",
"sense",
"sepia",
"serif",
"serum",
"serve",
"setup",
"seven",
"sever",
"sewer",
"shack",
"shade",
"shady",
"shaft",
"shake",
"shaky",
"shale",
"shall",
"shalt",
"shame",
"shank",
"shape",
"shard",
"share",
"shark",
"sharp",
"shave",
"shawl",
"shear",
"sheen",
"sheep",
"sheer",
"sheet",
"sheik",
"shelf",
"shell",
"shied",
"shift",
"shine",
"shiny",
"shire",
"shirk",
"shirt",
"shoal",
"shock",
"shone",
"shook",
"shoot",
"shore",
"shorn",
"short",
"shout",
"shove",
"shown",
"showy",
"shrew",
"shrub",
"shrug",
"shuck",
"shunt",
"shush",
"shyly",
"siege",
"sieve",
"sight",
"sigma",
"silky",
"silly",
"since",
"sinew",
"singe",
"siren",
"sissy",
"sixth",
"sixty",
"skate",
"skier",
"skiff",
"skill",
"skimp",
"skirt",
"skulk",
"skull",
"skunk",
"slack",
"slain",
"slang",
"slant",
"slash",
"slate",
"sleek",
"sleep",
"sleet",
"slept",
"slice",
"slick",
"slide",
"slime",
"slimy",
"sling",
"slink",
"sloop",
"slope",
"slosh",
"sloth",
"slump",
"slung",
"slunk",
"slurp",
"slush",
"slyly",
"smack",
"small",
"smart",
"smash",
"smear",
"smell",
"smelt",
"smile",
"smirk",
"smite",
"smith",
"smock",
"smoke",
"smoky",
"smote",
"snack",
"snail",
"snake",
"snaky",
"snare",
"snarl",
"sneak",
"sneer",
"snide",
"sniff",
"snipe",
"snoop",
"snore",
"snort",
"snout",
"snowy",
"snuck",
"snuff",
"soapy",
"sober",
"soggy",
"solar",
"solid",
"solve",
"sonar",
"sonic",
"sooth",
"sooty",
"sorry",
"sound",
"south",
"sower",
"space",
"spade",
"spank",
"spare",
"spark",
"spasm",
"spawn",
"speak",
"spear",
"speck",
"speed",
"spell",
"spelt",
"spend",
"spent",
"sperm",
"spice",
"spicy",
"spied",
"spiel",
"spike",
"spiky",
"spill",
"spilt",
"spine",
"spiny",
"spire",
"spite",
"splat",
"split",
"spoil",
"spoke",
"spoof",
"spook",
"spool",
"spoon",
"spore",
"sport",
"spout",
"spray",
"spree",
"sprig",
"spunk",
"spurn",
"spurt",
"squad",
"squat",
"squib",
"stack",
"staff",
"stage",
"staid",
"stain",
"stair",
"stake",
"stale",
"stalk",
"stall",
"stamp",
"stand",
"stank",
"stare",
"stark",
"start",
"stash",
"state",
"stave",
"stead",
"steak",
"steal",
"steam",
"steed",
"steel",
"steep",
"steer",
"stein",
"stern",
"stick",
"stiff",
"still",
"stilt",
"sting",
"stink",
"stint",
"stock",
"stoic",
"stoke",
"stole",
"stomp",
"stone",
"stony",
"stood",
"stool",
"stoop",
"store",
"stork",
"storm",
"story",
"stout",
"stove",
"strap",
"straw",
"stray",
"strip",
"strut",
"stuck",
"study",
"stuff",
"stump",
"stung",
"stunk",
"stunt",
"style",
"suave",
"sugar",
"suing",
"suite",
"sulky",
"sully",
"sumac",
"sunny",
"super",
"surer",
"surge",
"surly",
"sushi",
"swami",
"swamp",
"swarm",
"swash",
"swath",
"swear",
"sweat",
"sweep",
"sweet",
"swell",
"swept",
"swift",
"swill",
"swine",
"swing",
"swirl",
"swish",
"swoon",
"swoop",
"sword",
"swore",
"sworn",
"swung",
"synod",
"syrup",
"tabby",
"table",
"taboo",
"tacit",
"tacky",
"taffy",
"taint",
"taken",
"taker",
"tally",
"talon",
"tamer",
"tango",
"tangy",
"taper",
"tapir",
"tardy",
"tarot",
"taste",
"tasty",
"tatty",
"taunt",
"tawny",
"teach",
"teary",
"tease",
"teddy",
"teeth",
"tempo",
"tenet",
"tenor",
"tense",
"tenth",
"tepee",
"tepid",
"terra",
"terse",
"testy",
"thank",
"theft",
"their",
"theme",
"there",
"these",
"theta",
"thick",
"thief",
"thigh",
"thing",
"think",
"third",
"thong",
"thorn",
"those",
"three",
"threw",
"throb",
"throw",
"thrum",
"thumb",
"thump",
"thyme",
"tiara",
"tibia",
"tidal",
"tiger",
"tight",
"tilde",
"timer",
"timid",
"tipsy",
"titan",
"tithe",
"title",
"toast",
"today",
"toddy",
"token",
"tonal",
"tonga",
"tonic",
"tooth",
"topaz",
"topic",
"torch",
"torso",
"torus",
"total",
"totem",
"touch",
"tough",
"towel",
"tower",
"toxic",
"toxin",
"trace",
"track",
"tract",
"trade",
"trail",
"train",
"trait",
"tramp",
"trash",
"trawl",
"tread",
"treat",
"trend",
"triad",
"trial",
"tribe",
"trice",
"trick",
"tried",
"tripe",
"trite",
"troll",
"troop",
"trope",
"trout",
"trove",
"truce",
"truck",
"truer",
"truly",
"trump",
"trunk",
"truss",
"trust",
"truth",
"tryst",
"tubal",
"tuber",
"tulip",
"tulle",
"tumor",
"tunic",
"turbo",
"tutor",
"twang",
"tweak",
"tweed",
"tweet",
"twice",
"twine",
"twirl",
"twist",
"twixt",
"tying",
"udder",
"ulcer",
"ultra",
"umbra",
"uncle",
"uncut",
"under",
"undid",
"undue",
"unfed",
"unfit",
"unify",
"union",
"unite",
"unity",
"unlit",
"unmet",
"unset",
"untie",
"until",
"unwed",
"unzip",
"upper",
"upset",
"urban",
"urine",
"usage",
"usher",
"using",
"usual",
"usurp",
"utile",
"utter",
"vague",
"valet",
"valid",
"valor",
"value",
"valve",
"vapid",
"vapor",
"vault",
"vaunt",
"vegan",
"venom",
"venue",
"verge",
"verse",
"verso",
"verve",
"vicar",
"video",
"vigil",
"vigor",
"villa",
"vinyl",
"viola",
"viper",
"viral",
"virus",
"visit",
"visor",
"vista",
"vital",
"vivid",
"vixen",
"vocal",
"vodka",
"vogue",
"voice",
"voila",
"vomit",
"voter",
"vouch",
"vowel",
"vying",
"wacky",
"wafer",
"wager",
"wagon",
"waist",
"waive",
"waltz",
"warty",
"waste",
"watch",
"water",
"waver",
"waxen",
"weary",
"weave",
"wedge",
"weedy",
"weigh",
"weird",
"welch",
"welsh",
"whack",
"whale",
"wharf",
"wheat",
"wheel",
"whelp",
"where",
"which",
"whiff",
"while",
"whine",
"whiny",
"whirl",
"whisk",
"white",
"whole",
"whoop",
"whose",
"widen",
"wider",
"widow",
"width",
"wield",
"wight",
"willy",
"wimpy",
"wince",
"winch",
"windy",
"wiser",
"wispy",
"witch",
"witty",
"woken",
"woman",
"women",
"woody",
"wooer",
"wooly",
"woozy",
"wordy",
"world",
"worry",
"worse",
"worst",
"worth",
"would",
"wound",
"woven",
"wrack",
"wrath",
"wreak",
"wreck",
"wrest",
"wring",
"wrist",
"write",
"wrong",
"wrote",
"wrung",
"wryly",
"yacht",
"yearn",
"yeast",
"yield",
"young",
"youth",
"zebra",
"zesty",
"zonal",
));
}
public String getRandomWord() {
Random random = new Random();
return wordList.get(random.nextInt(wordList.size()));
}
|
3c088d9026fbb98525a3edb359e47a0f
|
{
"intermediate": 0.2759929895401001,
"beginner": 0.5726575255393982,
"expert": 0.15134955942630768
}
|
38,239
|
Detect collision in a cube area in Unity not using rigidbodies
|
5da7b010d2ca52589a116def5668c4a2
|
{
"intermediate": 0.4317896068096161,
"beginner": 0.20221389830112457,
"expert": 0.36599650979042053
}
|
38,240
|
Requirements:
Write a program with a main method
Create at least one new method which is called from main that takes at least one parameter
Call at least two distinct methods from the String class
Utilize conditional statements or compound Boolean expressions
Utilize iteration
|
57f9ea5cac52f764abff4e2671dad720
|
{
"intermediate": 0.23174770176410675,
"beginner": 0.591404914855957,
"expert": 0.176847442984581
}
|
38,241
|
How can you translate this for android java app development?
it("should order and limit", () => {
var citiesRef = db.collection("cities");
// [START order_and_limit]
citiesRef.orderBy("name").limit(3);
// [END order_and_limit]
});
it("should order descending", () => {
var citiesRef = db.collection("cities");
// [START order_and_limit_desc]
citiesRef.orderBy("name", "desc").limit(3);
// [END order_and_limit_desc]
});
In google firebase, I have a users collection, inside a document with the userID, then inside that a score value. I want to create a leaderboard, so how can I code to sort the values, to return the top 10 userID?
Or should I use a different structure, and have a have a users collection, inside a document called scores, then inside that key-value pairs where the key is the userid, and the value is the score?
|
43550121ddf3dcfbad417ceb6f9650a8
|
{
"intermediate": 0.6341250538825989,
"beginner": 0.18794871866703033,
"expert": 0.17792615294456482
}
|
38,242
|
Requirements(java) that acheives somethings useful for programmers:
Write a program with a main method
Create at least one new method which is called from main that takes at least one parameter
Call at least two distinct methods from the String class
Utilize conditional statements or compound Boolean expressions
Utilize iteration
|
fe52295512df34cfd05b77b6b04bc0e8
|
{
"intermediate": 0.47790852189064026,
"beginner": 0.44798743724823,
"expert": 0.07410407066345215
}
|
38,243
|
Hi , write a todo app . you MUST use the FLET framework ( python)
|
add19127bc8d2d8d4fa3b87200003cbb
|
{
"intermediate": 0.8366464376449585,
"beginner": 0.08299627900123596,
"expert": 0.08035727590322495
}
|
38,244
|
Could you remove unecessary code. Make it more secure/effecient. Fix the hwid issue of not outputing the hwid and then the hashed hwid on the console. Fix probably the hwid is not retrieving it correctly
private string HashHwid(string input)
{
using (SHA256 sha256 = SHA256.Create())
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = sha256.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
{
sb.Append(hashBytes[i].ToString("x2"));
}
Console.WriteLine("Hashed HWID: " + sb.ToString());
return sb.ToString();
}
}
public static string SetValueForText1 = "";
public static string SetValueForText2 = "";
string connectionString = "Data Source=DESKTOP-E8D96UU\\SQLEXPRESS;Initial Catalog=sfd_loader;Integrated Security=True;Encrypt=False";
private void load_Click(object sender, EventArgs e)
{
string hwid = GetHardwareID();
string hashedHwid = HashHwid(hwid);
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string query = "SELECT * FROM Accounts WHERE Username=@Username";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@Username", login.Text);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
string password = reader["Password"].ToString();
string hashedHwidFromDb = reader["hwid"].ToString();
if (string.IsNullOrEmpty(hashedHwidFromDb))
{
MessageBox.Show("HWID not found in database. Please update HWID.");
UpdateHwidInDatabase(login.Text, hashedHwid);
}
else if (hashedHwid == hashedHwidFromDb)
{
SetValueForText1 = login.Text + " // Admin";
this.Hide();
var form1 = new Form2();
form1.Closed += (s, args) => this.Close();
form1.Show();
}
else
{
MessageBox.Show("HWID is incorrect!");
}
}
else
{
MessageBox.Show("Username is incorrect!");
}
}
}
}
if (checkBox1.Checked)
{
HowqueCheats.Properties.Settings.Default.Username = login.Text;
HowqueCheats.Properties.Settings.Default.Password = this.password.Text;
HowqueCheats.Properties.Settings.Default.Save();
}
else
{
HowqueCheats.Properties.Settings.Default.Username = "";
HowqueCheats.Properties.Settings.Default.Password = "";
HowqueCheats.Properties.Settings.Default.Save();
}
}
private void UpdateHwidInDatabase(string username, string hwid)
{
string updateQuery = "UPDATE Accounts SET hwid=@Hwid WHERE Username=@Username";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlCommand updateCommand = new SqlCommand(updateQuery, connection))
{
// Trim the hwid value to the maximum allowed length
updateCommand.Parameters.AddWithValue("@hwid", hwid.Length > 100 ? hwid.Substring(0, 100) : hwid);
updateCommand.Parameters.AddWithValue("@Username", username);
updateCommand.ExecuteNonQuery();
}
}
}
private string ExecuteCommand(string command)
{
try
{
using (System.Diagnostics.Process process = new System.Diagnostics.Process())
{
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo
{
FileName = "cmd.exe",
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
process.StartInfo = startInfo;
process.Start();
// Send the command to cmd.exe
process.StandardInput.WriteLine(command);
process.StandardInput.WriteLine("exit");
// Read the command output
string output = process.StandardOutput.ReadToEnd();
string errors = process.StandardError.ReadToEnd();
process.WaitForExit();
if (string.IsNullOrEmpty(errors))
{
return output;
}
else
{
MessageBox.Show("Error executing command: " + errors);
return string.Empty;
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error executing command: " + ex.Message);
return string.Empty;
}
}
private string GetHardwareID()
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UUID FROM Win32_ComputerSystemProduct");
ManagementObjectCollection collection = searcher.Get();
foreach (ManagementObject obj in collection)
{
return obj["UUID"].ToString();
}
return null;
}
private string ExtractUUID(string commandOutput)
{
// Use regular expressions to extract the UUID in the correct format
Regex uuidRegex = new Regex(@"^UUID\s+:\s+(.+)$", RegexOptions.IgnoreCase | RegexOptions.Multiline);
Match uuidMatch = uuidRegex.Match(commandOutput);
if (uuidMatch.Success)
{
// Take the first group as the UUID and trim any leading or trailing spaces
return uuidMatch.Groups[1].Value.Trim();
}
return string.Empty;
}
|
20356cb00dcfddf0cf9f672644d1d568
|
{
"intermediate": 0.3064148724079132,
"beginner": 0.446655809879303,
"expert": 0.24692930281162262
}
|
38,245
|
i am trying to make a chess game where an LLM is the opponent. i make a move, then the move and board info is sent to LLM context. the llm replies and generally the first word in the reply is the move, so i grab that word and try to enter it as a move for the LLM. separate from the game itself, i added a chat area. the chat area should not interfere with the game. really, the only benefit of the chat area during the game is it allows me to see the move the LLM is making. while not making moves in the game, i'd like to be able to chat with the LLM if i want. currently the only problem i see is that when I make a move, the LLM responds twice and i don't know why, but it's something with the way the code is setup.
import tkinter as tk
from PIL import Image, ImageTk
import chess
import requests
import re
# Functions
def draw_board(board, selected_square=None):
global board_images
board_images = {}
canvas.delete("all")
canvas_width = 900
canvas_height = 500
canvas.config(width=canvas_width, height=canvas_height)
start_x = 2
start_y = 2
for square in chess.SQUARES:
rank = chess.square_rank(square)
file = chess.square_file(square)
x0 = start_x + file * square_size
y0 = start_y + (7 - rank) * square_size
if (rank + file) % 2 == 0:
square_color = "white"
else:
square_color = "light gray"
canvas.create_rectangle(x0, y0, x0 + square_size, y0 + square_size, fill=square_color)
# Check if the square is selected and draw a highlight
if square == selected_square:
canvas.create_rectangle(x0, y0, x0 + square_size, y0 + square_size, fill="yellow")
piece = board.piece_at(square)
if piece:
image = Image.open(PIECE_IMAGES[str(piece)]).resize((square_size, square_size), Image.Resampling.LANCZOS)
photo = ImageTk.PhotoImage(image)
board_images[square] = photo
canvas.create_image(x0 + square_size // 2, y0 + square_size // 2, image=photo)
def process_move(move, game_board):
global san_moves, sa_number, total_moves, history, user_turn, chat_window, valid_moves, llm_turn
try:
if llm_turn:
result_label.config(text="It's not your turn to move.")
return
if move in game_board.legal_moves:
game_board.push(move)
fen_notation = game_board.fen()
shredder_fen = chess.Board(fen_notation)
result_label.config(text=f"FEN Notation: {fen_notation}")
draw_board(game_board)
if total_moves % 2 == 1:
sa_number += 1
san_moves += f"{sa_number}. {move} "
total_moves += 1
history = []
move_list = re.findall(r'\((.*?)\)', str(valid_moves))
chat_window.delete(1.0, tk.END)
role = "user"
else:
san_moves += f"{move} "
total_moves += 1
print("SAN Moves:", san_moves)
if move_list == ['']:
message = "Checkmate."
chat_window.insert(tk.END, f"\nCheckmate")
else:
message = f"Pick a move from THIS list {move_list}.\nThe board is currently at:\n{shredder_fen}."
history.append({"role": role, "content": message})
interact_with_llm(message)
llm_turn = True # Set the LLM turn to True after user move
else:
result_label.config(text="Illegal move")
return # Return here to avoid sending message to LLM for an illegal move
except ValueError:
result_label.config(text="Invalid move")
def interact_with_llm(message):
global history, llm_turn
try:
data = {
"mode": "chat",
"character": "ChessAI",
"seed": -1,
"messages": history
}
response = requests.post(api_url, headers=headers, json=data).json()
if 'choices' in response and response['choices']:
assistant_message = response['choices'][0]['message']['content']
history.append({"role": "assistant", "content": assistant_message})
chat_window.insert(tk.END, f"\nAssistant: {assistant_message}\n")
print_history()
llm_turn = False # Reset llm_turn to False after LLM responds
except Exception as e:
print(f"Error in LLM request: {e}")
chat_window.insert(tk.END, "\nAssistant: Error in LLM request")
llm_turn = False # Reset llm_turn even in case of an error
def on_square_click(event):
global selected_square, is_second_click
file = (event.x + 20) // square_size
rank = 7 - (event.y + 10) // square_size
square = chess.square(file, rank)
if not is_second_click:
# First click: Select the piece
move_entry.delete(0, tk.END)
move_entry.insert(tk.END, chess.square_name(square))
selected_square = square
is_second_click = True
draw_board(game_board, selected_square)
else:
# Second click: Generate and process the move
move = chess.Move(selected_square, square)
try:
if move in game_board.legal_moves:
process_move(move, game_board)
is_second_click = False
# Pass move information to LLM
message = f"User made move: {move}.\nCurrent board state:\n{game_board.fen()}"
interact_with_llm(message)
else:
result_label.config(text="Illegal move")
draw_board(game_board, selected_square)
is_second_click = False
except ValueError:
result_label.config(text="Invalid move")
is_second_click = False
def update_game_board(move_str):
global san_moves, sa_number, total_moves, history, user_turn, chat_window, valid_moves
try:
game_move = game_board.parse_san(move_str)
if game_move in game_board.legal_moves:
game_board.push(game_move)
fen_notation = game_board.fen()
shredder_fen = chess.Board(fen_notation)
result_label.config(text=f"FEN Notation: {fen_notation}")
# Add the valid move to the SAN moves string with move number
if total_moves % 2 == 1:
san_moves += f"{sa_number}. {move_str} "
total_moves += 1
history = []
move_list = re.findall(r'\((.*?)\)', str(valid_moves))
chat_window.delete(1.0, tk.END) # Clear the chat window
role = "user"
if move_list == ['']:
message = "Checkmate."
chat_window.insert(tk.END, f"\nCheckmate")
else:
message = f"Pick a move from THIS list {move_list}.\nThe board is currently at:\n{shredder_fen}."
history.append({"role": role, "content": message})
interact_with_llm(message)
else:
san_moves += f"{move_str} "
total_moves += 1
sa_number += 1
# Print or use san_moves as needed
print("SAN Moves:", san_moves)
draw_board(game_board)
else:
result_label.config(text="Illegal move")
except ValueError:
result_label.config(text="Invalid move")
def submit_move():
global valid_moves, move
move_str = move_entry.get().strip()
if move_str:
try:
update_game_board(move_str)
# Extract moves using regular expression
moves_list = re.findall(r'\((.*?)\)', str(valid_moves))
if moves_list:
print(moves_list[0])
except ValueError:
try:
game_board.set_fen(move_str)
draw_board(game_board)
result_label.config(text=f"FEN Notation: {move_str}")
except ValueError:
result_label.config(text="Invalid move")
move_entry.delete(0, tk.END)
def submit_message():
global chat_window, user_color, history
message = input_area.get("1.0", tk.END).strip()
role = "user"
chat_window.insert(tk.END, f"\n{role.capitalize()}: {message}\n")
history.append({"role": role, "content": message})
interact_with_llm(message)
def on_enter(event):
# Check if the cursor is in the input area
if event.widget == input_area:
submit_message()
elif event.widget == move_entry:
submit_move() # Assuming you want to submit the move in this case
def print_history():
print("\n=== Updated History ===")
for entry in history:
print(f"{entry['role']}: {entry['content']}")
print("=======================")
def clear_history():
global history, chat_window, game_board, san_moves
history = []
chat_window.delete(1.0, tk.END) # Clear the chat window
game_board = chess.Board(initial_fen)
draw_board(game_board)
san_moves = ""
def choose_white():
global user_color, white_button, black_button
user_color = "white"
history.append({"role": "user", "content": "White"})
print_history()
white_button.destroy() # Remove the "Choose White" button
black_button.destroy() # Remove the "Choose Black" button
def choose_black():
global user_color, white_button, black_button
user_color = "black"
history.append({"role": "user", "content": "Black"})
print_history()
white_button.destroy() # Remove the "Choose White" button
black_button.destroy() # Remove the "Choose Black" button
# Global Variables
user_color = None
history = []
san_moves = "" # Initialize an empty string to store SAN moves
sa_number = 1 # Initialize real number of moves
total_moves = 1
llm_move = ""
llm_turn = False
api_url = 'http://127.0.0.1:5000/v1/chat/completions'
headers = {"Content-Type": "application/json"}
initial_fen = chess.STARTING_FEN
game_board = chess.Board(initial_fen)
valid_moves = game_board.legal_moves
board_images = {}
square_size = 60 # Size of a square in the board
selected_square = None
move = None
is_second_click = False
# Create a dictionary to map piece symbols to image filenames
PIECE_IMAGES = {
"P": "images/Wp.png",
"p": "images/bp.png",
"R": "images/WR.png",
"r": "images/bR.png",
"N": "images/WN.png",
"n": "images/bN.png",
"B": "images/WB.png",
"b": "images/bB.png",
"Q": "images/WQ.png",
"q": "images/bQ.png",
"K": "images/WK.png",
"k": "images/bK.png"
}
# Tkinter Window
window = tk.Tk()
window.title("Chess")
# Tkinter Components
canvas = tk.Canvas(window)
canvas.pack()
draw_board(game_board)
canvas.bind("<Button-1>", lambda event: on_square_click(event))
move_entry = tk.Entry(window)
move_entry.place(x=7, y=520)
move_entry.bind("<Return>", on_enter)
submit_btn = tk.Button(window, text="Make Move", command=submit_move)
submit_btn.place(x=185, y=518)
result_label = tk.Label(window, text="FEN Notation: " + game_board.fen())
result_label.place(x=7, y=495)
chat_window = tk.Text(window, height=20, width=45, wrap=tk.WORD)
chat_window.place(x=515, y=20)
input_area = tk.Text(window, height=5, width=45, wrap=tk.WORD)
input_area.place(x=515, y=400)
input_area.bind("<Return>", on_enter)
submit_btn = tk.Button(window, text="Send", command=submit_message)
submit_btn.pack(side=tk.RIGHT, padx=10, pady=10)
clear_history_btn = tk.Button(window, text="Clear History", command=clear_history)
clear_history_btn.place(x=300, y=518)
white_button = tk.Button(window, text="Choose White", command=choose_white)
white_button.place(x=185, y=200)
black_button = tk.Button(window, text="Choose Black", command=choose_black)
black_button.place(x=185, y=240)
window.mainloop()
|
311a2bfa98f93776ec432741ac70104b
|
{
"intermediate": 0.521480143070221,
"beginner": 0.32007333636283875,
"expert": 0.15844647586345673
}
|
38,246
|
Stored Hashed Password: howque123.
Input Password: howque123.
Invalid Base64 String
Could you fix this issue and add improvements?
private string HashHwid(string input)
{
using (SHA256 sha256 = SHA256.Create())
{
byte[] inputBytes = Encoding.UTF8.GetBytes(input);
byte[] hashBytes = sha256.ComputeHash(inputBytes);
StringBuilder sb = new StringBuilder();
foreach (byte b in hashBytes)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
private string HashPassword(string password)
{
// Generate a random salt
byte[] salt;
new RNGCryptoServiceProvider().GetBytes(salt = new byte[16]);
// Create a password hash using PBKDF2
using (var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000, HashAlgorithmName.SHA256))
{
byte[] hash = pbkdf2.GetBytes(20); // 20 is the size of the hash
// Use Convert.ToBase64String directly on the hashBytes
string base64Hash = Convert.ToBase64String(hash);
// Combine salt and hash for storage if needed
byte[] hashBytes = new byte[36]; // 16 for salt + 20 for hash
Array.Copy(salt, 0, hashBytes, 0, 16);
Array.Copy(hash, 0, hashBytes, 16, 20);
return base64Hash;
}
}
private bool VerifyPassword(string inputPassword, string hashedPassword)
{
try
{
// Debugging: Print hashed password and input password
Console.WriteLine($"Stored Hashed Password: {hashedPassword}");
Console.WriteLine($"Input Password: {inputPassword}");
// Check if the hashed password is a valid Base64 string
if (!IsValidBase64String(hashedPassword))
{
Console.WriteLine("Invalid Base64 String");
return false;
}
// Convert the base64-encoded string back to bytes
byte[] hashBytes = Convert.FromBase64String(hashedPassword);
// Debugging: Print hash bytes
Console.WriteLine($"Decoded Hash Bytes: {BitConverter.ToString(hashBytes)}");
// Extract the salt and hash from the combined bytes
byte[] salt = new byte[16];
Array.Copy(hashBytes, 0, salt, 0, 16);
byte[] inputHash;
using (var pbkdf2 = new Rfc2898DeriveBytes(inputPassword, salt, 10000, HashAlgorithmName.SHA256))
{
inputHash = pbkdf2.GetBytes(20); // 20 is the size of the hash
}
// Debugging: Print input hash bytes
Console.WriteLine($"Input Hash Bytes: {BitConverter.ToString(inputHash)}");
// Compare the computed hash with the stored hash
for (int i = 0; i < 20; i++)
{
if (inputHash[i] != hashBytes[i + 16])
{
return false;
}
}
return true;
}
catch (Exception ex)
{
// Handle the exception and print a message
Console.WriteLine($"Error in VerifyPassword: {ex.Message}");
return false;
}
}
private bool IsValidBase64String(string s)
{
try
{
Convert.FromBase64String(s);
return true;
}
catch
{
return false;
}
}
// Use a secure method to store and retrieve connection strings
private string GetConnectionString()
{
// Replace this with a secure method to retrieve your connection string
return "Data Source=DESKTOP-E8D96UU\\SQLEXPRESS;Initial Catalog=sfd_loader;Integrated Security=True;Encrypt=False";
}
public static string SetValueForText1 = "";
public static string SetValueForText2 = "";
private void load_Click(object sender, EventArgs e)
{
string hwid = GetHardwareID();
string hashedHwid = HashHwid(hwid);
// Hash the entered password before checking it
string hashedPassword = HashPassword(password.Text);
using (SqlConnection connection = new SqlConnection(GetConnectionString()))
{
connection.Open();
string query = "SELECT * FROM Accounts WHERE Username=@Username";
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.AddWithValue("@Username", login.Text);
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
string storedPassword = reader["Password"].ToString();
string hashedHwidFromDb = reader["hwid"].ToString();
if (string.IsNullOrEmpty(hashedHwidFromDb))
{
MessageBox.Show("HWID not found in database. Please update HWID.");
UpdateHwidInDatabase(login.Text, hashedHwid); // Use the hashed value
}
else if (hashedHwid == hashedHwidFromDb && VerifyPassword(password.Text, storedPassword))
{
SetValueForText1 = login.Text + " // Admin";
this.Hide();
var form1 = new Form2();
form1.Closed += (s, args) => this.Close();
form1.Show();
}
else
{
MessageBox.Show("Credentials are incorrect!");
}
}
else
{
MessageBox.Show("Username is incorrect!");
}
}
}
}
if (checkBox1.Checked)
{
HowqueCheats.Properties.Settings.Default.Username = login.Text;
HowqueCheats.Properties.Settings.Default.Password = password.Text; // Save the plaintext password for simplicity
HowqueCheats.Properties.Settings.Default.Save();
}
else
{
HowqueCheats.Properties.Settings.Default.Username = "";
HowqueCheats.Properties.Settings.Default.Password = "";
HowqueCheats.Properties.Settings.Default.Save();
}
}
|
b877c15610c3aada16b4b1aea41aaed6
|
{
"intermediate": 0.3515145778656006,
"beginner": 0.4359528124332428,
"expert": 0.2125326246023178
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.