Ошибка empty result

начнем с того, что у вас вот тут очень жуткая ошибка

for i in range(0,l-1):
    if (s[i]==s[i+1] and s[i+1]!=s[i+2]):

потому что в случае, если друг за другом будут идти одинаковые элементы и условие s[i]==s[i+1] будет выполнено, то дальше будет проверено s[i+1]!=s[i+2]

и если одинаковые элементы находятся в конце списка, то будет обращение к s[i+2], а учитывая, что i доходит до len(s) - 2 включительно, то обращение будет к s[len(s)] — а это выход за диапазон и будет ошибка

IndexError: list index out of range

что легко можно проверить введя 1 1

на счет вывода ответа — ну так вроде когда находит одинаковые элементы — выводит, когда не находит — не выводит ничего, как вы и заложили в коде :)

А вообще можно обойтись и без сортировки :)

s = list(map(int, input().split()))
res = set(v for v in s if s.count(v) > 1)

и без множества

res = [s[i] for i in range(len(s)) if s[:i + 1].count(s[i]) == 2]

ну или покороче

res = [v for i, v in enumerate(s) if s[:i + 1].count(v) == 2]

или без count():

from collections import Counter
res = [v for v, c in Counter(s).items() if c > 1]

или без преобразования в целые числа, зато с регулярками :)

import re
res = set(re.findall(r"(\d+)(?= .*\1)", input()))

P.S.

а вот как должен выглядеть ваш алгоритм:

for i in range(1, l):
    if s[i] == s[i - 1] and (i == l - 1 or s[i] != s[i + 1]):
        print(s[i], end=" ")
print()

начнем с того, что у вас вот тут очень жуткая ошибка

for i in range(0,l-1):
    if (s[i]==s[i+1] and s[i+1]!=s[i+2]):

потому что в случае, если друг за другом будут идти одинаковые элементы и условие s[i]==s[i+1] будет выполнено, то дальше будет проверено s[i+1]!=s[i+2]

и если одинаковые элементы находятся в конце списка, то будет обращение к s[i+2], а учитывая, что i доходит до len(s) - 2 включительно, то обращение будет к s[len(s)] — а это выход за диапазон и будет ошибка

IndexError: list index out of range

что легко можно проверить введя 1 1

на счет вывода ответа — ну так вроде когда находит одинаковые элементы — выводит, когда не находит — не выводит ничего, как вы и заложили в коде :)

А вообще можно обойтись и без сортировки :)

s = list(map(int, input().split()))
res = set(v for v in s if s.count(v) > 1)

и без множества

res = [s[i] for i in range(len(s)) if s[:i + 1].count(s[i]) == 2]

ну или покороче

res = [v for i, v in enumerate(s) if s[:i + 1].count(v) == 2]

или без count():

from collections import Counter
res = [v for v, c in Counter(s).items() if c > 1]

или без преобразования в целые числа, зато с регулярками :)

import re
res = set(re.findall(r"(d+)(?= .*1)", input()))

P.S.

а вот как должен выглядеть ваш алгоритм:

for i in range(1, l):
    if s[i] == s[i - 1] and (i == l - 1 or s[i] != s[i + 1]):
        print(s[i], end=" ")
print()

Вместо сумы чисел, который код должен выводить, он выводит «empty result». Это странно, вроде все переменные и их данные введены.

p = 0
while p == 1:
    a = int(input())
    b = int(input())
    c = int(input())
    d = int(input())
    x = int(input())
    p = 0
    
    if a == 0:
        print(a)
        p = 1
    if b == 0:
        print(a + b)
        p = 1
    if c == 0:
        print(a + b + c)
        p = 1
    if d == 0:
        print(a + b + c + d)
        p = 1
    if x == 0:
        print( a + b + c + d)
        p = 1
Issue type
  • Bug Report
OverPy version
OS
  • OSX 10.12.3

Python version

  • Python 3.5
Summary

When setting a short timeout (1-30s), such that the timeout is reached, an empty result is returned instead of a timeout error. Looking into the query() function code determines that there is a <remark> describing the timeout in the xml result, and that the error code ‘200’ is raised, but the parse_xml() function is being used to resolve it to an empty result. A similar issue is discussed in the Overpass API #94.

Steps to reproduce

Run a short timeout query like

[out:xml][timeout:10];
area["name"="France"]->.searchArea;
(
node["amenity"="embassy"](area.searchArea);
way["amenity"="embassy"](area.searchArea);
relation["amenity"="embassy"](area.searchArea);
);
out center;

via
result = overpy.Overpass().query(query))

Expected results

raise overpy.exception.OverpassGatewayTimeout or some relevant error

Actual results

returns a result for which

print(result.get_nodes())
print(result.get_ways())
print(result.get_relations())

returns an empty list [] for each.

XML result looked like:

b'<?xml version="1.0" encoding="UTF-8"?>n<osm version="0.6" generator="Overpass API">n<note>The data included in this document is from www.openstreetmap.org. The data is made available under ODbL.</note>n<meta osm_base="2017-03-17T15:40:02Z" areas="2017-03-17T06:44:02Z"/>nn<remark> runtime error: Query timed out in "query" at line 1 after 2 seconds. </remark>nn</osm>n'

f.code: 200

Topic: Python reverse — empty result  (Read 4073 times)

Hi,

I received a python source code from a client to run the reverse eng. in EA.
EA processes all .py files without producing any result/class.

The Python code has :
— import declarations
— def (e.g. def functionA(arg1, arg2) : …)

Is there any precondition to check so it works?

Thanks


Logged


There should be some classes at least.

q.


Logged


Are there classes in your code?

If you’re writing classless Python I don’t think you’ll get anything out of an EA reverse-engineer.

/Uffe


Logged

My theories are always correct, just apply them to the right reality.


Hi,

The code I have does not include any class. I confirm that I got some results once I added «class : <classname>» in the files.

Thanks


Logged


Hi,

I ran a new test with a Python file with content illustrated as follows:

import libA
import libB
class myClass (arg1):
  def functA(arg1, arg2):
     localvar = arg1 ...

  def functB(arg1, arg2, arg3):
# code removed

  def functC():
# code removed

if a = "test":
  print('test')


Running EA reverse, I get a «myClass» class with functA operation only (and arg1 parameter).
Any idea why the other def are not picked up?

Thanks
Guillaume


Logged


You should learn a bit Python first. Class operations have self as first parameter.

q.


Logged


I changed the incomplete method bodies from your example to ‘pass’ and EA imported all three methods.

They weren’t static like I would have expected given they were missing the self parameter as suggested by qwerty.


Logged

Eve

support@sparxsystems.com


Thanks for your replies.
With support of the Python dev team, I simply figured out that the code samples I got needed to have a proper indent level applied so the def can be reversed as class operations.

I got a query on running the EA Execution analyzer’s recording feature with Python. I saw that it’s not supported according to the help; could it be supported in the future?


Logged


You may be able to use the gdb debugger to do that, but I suspect the gdb support for python is in the UI side, not the API side.


Logged

Eve

support@sparxsystems.com


Список частых ошибок в Python и их исправление.

TypeError: object is not subscriptable

Ошибка, которая сообщает, что обращение идет к элементам не правильно. Возможно, это другой тип объекта, а не тот, который вам кажется. Проверить можно командой type().

Например, такое может быть, если это список (list), а в обращаетесь за элементом к словарю (dictionary).

TypeError: unsupported type for timedelta days component: str

Ожидается число, а передается в timedelta строка. Исправить просто, если уверены, что передается цифра, то достаточно явно преобразовать в число: int(days)

Failed execute: tuple index out of range

Означает что передаётся меньше данных, чем запрашивается.

ModuleNotFoundError: No module named ‘bot.bot_handler’; ‘bot’ is not a package

venv/bin/python bot/bot.py
Traceback (most recent call last):
File «bot/bot.py», line 4, in
from bot.bot_handler import BotHandler
File «bot/bot.py», line 4, in
from bot.bot_handler import BotHandler
ModuleNotFoundError: No module named ‘bot.bot_handler’; ‘bot’ is not a package

Конфилкт имени файла и директории — они не должны быть здесь одинаковыми. Поменяйте название директории или имени файла.

ValueError: a coroutine was expected, got

Traceback (most recent call last):
File «test.py», line 41, in
asyncio.run(update.update_operations)
File «/usr/local/Cellar/python/3.7.4_1/Frameworks/Python.framework/Versions/3.7/lib/python3.7/asyncio/runners.py», line 37, in run
raise ValueError(«a coroutine was expected, got {!r}».format(main))
ValueError: a coroutine was expected, got

Забыта скобки () у функции в команде asyncio.run(update.update_operations).

Moderators: Developers, Moderators

stormonts

Cacti User
Posts: 349
Joined: Tue Mar 31, 2009 10:05 am

ERROR: Empty result when running python script

I have a Python script that runs perfectly fine from the command line while logged in as «cactiuser», however when run as part of the poller process, it returns a «ERROR: Empty result». Command and expected result are shown below:

Code: Select all

cactiuser@marlin:/usr/local/cacti/rra> python /usr/local/cacti/scripts/get_db_size.py -H shark.xyz.com -p 5443 -U plone_stats -d zodb_db1
1556.49570847
cactiuser@marlin:/usr/local/cacti/rra>

Results in Cacti log

Code: Select all

08/29/2011 02:32:01 PM - SPINE: Poller[0] Host[89] TH[1] DS[9631] SCRIPT: python /usr/local/cacti/scripts/get_db_size.py -H shark.xyz.com -p 5443 -U plone_stats -d zodb_db1, output: 0
08/29/2011 02:32:01 PM - SPINE: Poller[0] Host[89] ERROR: Empty result [shark]: 'python /usr/local/cacti/scripts/get_db_size.py -H shark.xyz.com -p 5443 -U plone_stats -d zodb_db1'

Permissions, on the file as created are listed below. Other RRAs in the folder have ownership of cactiuser:root and changing perms on this file to match didn’t help.

Code: Select all

-rw-r--r-- 1 cactiuser wwwrun  92664 2011-08-29 14:34 shark_mb_9631.rrd

noname

Cacti Guru User
Posts: 1566
Joined: Thu Aug 05, 2010 2:04 am
Location: Japan

stormonts

Cacti User
Posts: 349
Joined: Tue Mar 31, 2009 10:05 am

Re: ERROR: Empty result when running python script

Post

by stormonts »

Put following line in crontab for cactiuser:

Code: Select all

/usr/local/cacti-0.8.7g/scripts/get_db_size.py -H shark.xyz.com -p 5443 -U plone_stats -d zodb_db1 >>/tmp/db.log

and nothing is written to the db.log file. Run the same command show above at a command line while logged in as cactiuser and the db.log is updated withe the desired results.

Permissions on the python file are set to 755, have deleted the RRAs and rebuilt the poller cache but still no luck.

Also wanted to add that the Python script is getting sizes about a postgres database. There is a .pgpass file located in the home directory of cactiuser which has permissions set as

Code: Select all

-rw-------  1 cactiuser wwwrun    148 2011-08-17 09:30 .pgpass

Since the poller runs as cactiuser, should the permissions above be acceptable?

noname

Cacti Guru User
Posts: 1566
Joined: Thu Aug 05, 2010 2:04 am
Location: Japan

Re: ERROR: Empty result when running python script

Post

by noname »

stormonts wrote:Put following line in crontab for cactiuser:

Code: Select all

/usr/local/cacti-0.8.7g/scripts/get_db_size.py -H shark.xyz.com -p 5443 -U plone_stats -d zodb_db1 >>/tmp/db.log

and nothing is written to the db.log file. Run the same command show above at a command line while logged in as cactiuser and the db.log is updated withe the desired results.

Try again with this in crontab:

/usr/local/cacti-0.8.7g/scripts/get_db_size.py -H shark.xyz.com -p 5443 -U plone_stats -d zodb_db1 >>/tmp/db.log 2>&1

«2>&1» means redirecting stderr to stdout.

stormonts

Cacti User
Posts: 349
Joined: Tue Mar 31, 2009 10:05 am

Re: ERROR: Empty result when running python script

Post

by stormonts »

Results with that command are below. Guess I need to dig into the script more? Odd that it works perfectly from the command line but not from cron?

Code: Select all

which: no psql in (/usr/bin:/bin)
Traceback (most recent call last):
  File "/usr/local/cacti-0.8.7g/scripts/get_db_size.py", line 74, in ?
    main(sys.argv[1:])
  File "/usr/local/cacti-0.8.7g/scripts/get_db_size.py", line 60, in main
    command_output = Popen(cmd_args, stdout=PIPE).communicate()[0]
  File "/usr/lib64/python2.4/subprocess.py", line 542, in __init__
    errread, errwrite)
  File "/usr/lib64/python2.4/subprocess.py", line 975, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

noname

Cacti Guru User
Posts: 1566
Joined: Thu Aug 05, 2010 2:04 am
Location: Japan

Re: ERROR: Empty result when running python script

Post

by noname »

>> Odd that it works perfectly from the command line but not from cron?

User cron environment is somewhat different from user login environment.
(I’ve forgotten references about that..)

But first of all, try to specify all commands in your script with absolute pathname.

stormonts

Cacti User
Posts: 349
Joined: Tue Mar 31, 2009 10:05 am

Re: ERROR: Empty result when running python script

Post

by stormonts »

Now I’m even more confused…

Realized I was missing a space in the cron I posted earlier. If I put this in the crontab for cactiuser, it correctly rights the expected value into db.log

/usr/local/cacti-0.8.7g/scripts/get_db_size.py -H shark.xyz.com -p 5443 -U plone_stats -d zodb_db1 >> /tmp/db.log

However the command you noted generates the errors described earlier:

/usr/local/cacti-0.8.7g/scripts/get_db_size.py -H shark.xyz.com -p 5443 -U plone_stats -d zodb_db1 >> /tmp/db.log 2>&1

So the script does run fine as part of the cron for cactiuser (as long as the 2>&1 isn’t stuck on the end) but it still returns the «Empty result» in the cacti poller. Does the poller shell out to run scripts and the script in question is shelling out and the user permissions are getting mixed up?

noname

Cacti Guru User
Posts: 1566
Joined: Thu Aug 05, 2010 2:04 am
Location: Japan

Re: ERROR: Empty result when running python script

Post

by noname »

stormonts wrote:If I put this in the crontab for cactiuser, it correctly rights the expected value into db.log

/usr/local/cacti-0.8.7g/scripts/get_db_size.py -H shark.xyz.com -p 5443 -U plone_stats -d zodb_db1 >> /tmp/db.log

However the command you noted generates the errors described earlier:

/usr/local/cacti-0.8.7g/scripts/get_db_size.py -H shark.xyz.com -p 5443 -U plone_stats -d zodb_db1 >> /tmp/db.log 2>&1

So the script does run fine as part of the cron for cactiuser (as long as the 2>&1 isn’t stuck on the end) but it still returns the «Empty result» in the cacti poller.

Just guessing,
if error occurred during polling (even if correct result is outputted), poller determines it as «invalid»…?
I think you’d better to solve the issue which you mentioned at the above.

Who is online

Users browsing this forum: No registered users and 4 guests

Flutter is a popular open-source mobile app development framework that allows developers to create high-performance and visually appealing mobile apps for Android and iOS platforms. When developing a Flutter app, one may encounter the runJavascriptReturningResult error, which occurs when the result returned by the JavaScript code is empty. This article will guide you through how to troubleshoot this issue.

Understand the runJavascriptReturningResult method

Before diving into troubleshooting, it’s essential to understand what the runJavascriptReturningResult method does. This method executes a JavaScript string in a Flutter web view and returns the result as a string. For example, in the following code snippet, we execute a simple JavaScript program and return the result.

final result = await controller.runJavascriptReturningResult("""
  function add(a, b) {
    return a + b;
  }
  add(2, 3)
""");
print(result); // 5

Possible causes of the empty result error

The runJavascriptReturningResult error occurs when the JavaScript code executed by the method fails to produce any result. This may happen due to several reasons, some of which are:

  • Syntax errors in the JavaScript code.
  • Invalid code or undefined variables used in the JavaScript code.
  • Incorrectly formatted or invalid input values passed to the JavaScript code.

Troubleshooting the empty result error

To troubleshoot the empty result error, follow these steps:

  1. Check for syntax errors: Review the JavaScript code to ensure that it is free of syntax errors or other issues that could cause the code to fail. If your JavaScript code generates an error, it may fail silently, resulting in an empty result.

  2. Use console logs to debug: You can use print() statements or console.log() statements inside the JavaScript code to debug any issues that may be causing the empty result error. These statements can help identify the root cause of the error.

final result = await controller.runJavascriptReturningResult("""
  function add(a, b) {
    console.log('Adding', a, b);
    return a + b;
  }
  add(2, 3)
""");
print(result); // 5
  1. Test with different input values: Test the JavaScript code with different input values to determine if the issue is related to the input itself.
final result = await controller.runJavascriptReturningResult("""
  function square(num) {
    if (typeof num === "number") {
      return num * num;
    } else {
      console.log("Expected a number, but received", typeof num);
      return undefined;
    }
  }
  square(5)
""");
print(result); // 25
  1. Debug using a debugger: Use a debugger to step through the JavaScript code and identify any issues that could be causing the empty result error.

Conclusion

The runJavascriptReturningResult error occurs when the JavaScript code executed by the method fails to return a result. There are several possible reasons for this, including syntax errors in the JavaScript code, invalid code or undefined variables used in the JavaScript code, or incorrectly formatted or invalid input values passed to the JavaScript code. By following the troubleshooting steps outlined in this article, you can easily identify and fix the issue, allowing you to continue developing your Flutter app with ease.

Terraform Version — 1.0.11
AWS Provider — 3.66.0

We are getting intermittent errors like following when working with terraform for AWS Infrastructure Provisioning:

==============

│ Error: error updating Security Group (sg-0a73d418ae947fe09): couldn’t find resource

│ with module.security_groups.aws_security_group.default[«CIOPS-MS-Redis-SG»],
│ on ../../modules/Stack/SecurityGroups/main.tf line 1, in resource «aws_security_group» «default»:
│ 1: resource «aws_security_group» «default» {



│ Error: error updating Security Group (sg-0348f9cfa61f16235): couldn’t find resource

│ with module.security_groups.aws_security_group.default[«CIOPS-MySQL-SG»],
│ on ../../modules/Stack/SecurityGroups/main.tf line 1, in resource «aws_security_group» «default»:
│ 1: resource «aws_security_group» «default» {



│ Error: error reading Route Table (rtb-0fc9e07acc59ca7eb): couldn’t find resource

│ with module.data_vpc.aws_route_table.public_route_table[«us-east-1a»],
│ on ../../modules/Stack/VPC/main.tf line 92, in resource «aws_route_table» «public_route_table»:
│ 92: resource «aws_route_table» «public_route_table» {


│ Error: error reading Route in Route Table (rtb-0061e7bf9ed9458d7) with destination (10.110.64.0/20): couldn’t find resource

│ with module.routing_extapp_data.aws_route.source[«CIOPS-ExtApp-Private-Routing-1b»],
│ on ../../modules/Stack/Routing/main.tf line 13, in resource «aws_route» «source»:
│ 13: resource «aws_route» «source» {


│ Error: error reading Route Table (rtb-03178c1f7809c539c): couldn’t find resource

│ with module.extapp_vpc.aws_route_table.public_route_table[«us-east-1a»],
│ on ../../modules/Stack/VPC/main.tf line 92, in resource «aws_route_table» «public_route_table»:
│ 92: resource «aws_route_table» «public_route_table» {



│ Error: error reading Route Table Association (rtbassoc-09e721baf95da7d6f): empty result

│ with module.extapp_vpc.aws_route_table_association.default_private[«CIOPS-ExtApp-ELB-Private-Subnet-1a»],
│ on ../../modules/Stack/VPC/main.tf line 266, in resource «aws_route_table_association» «default_private»:
│ 266: resource «aws_route_table_association» «default_private» {

NOTE — The Errors are not static but intermittent. We got the error 3-4 times in about 100 executions done over a period of 48 hours.

==========================

Procedure to reproduce issue
Pre-requisites:

  1. Use Region us-east-1 only
  2. IAM role attached to EC2 instance on which terraform will be executed with account administrator access.
  3. One VPC , it’s CIDR . The VPC should have 2 private route table and one public route table . Keep their route table entires , VPC ID and CIDR handy.
  4. Second VPC , it’s CIDR . The VPC should have 2 private route table and one public route table . Keep their route table entires , VPC ID and CIDR handy.
  5. One S3 bucket with folder names State-Files and FlowLogs in us-east-1

Steps to follow

  1. Go to Folder Path Scripts/Terraform/Reinvent/StackLdapPeering

  2. Edit File for following fields
    => Replace AWS Account ID

    ldap_vpc_access_role => Set to IAM role ARN from pre-requisutes 2.

    ldap_ops_vpc_id = Set to VPC ID from pre-requisutes 3.
    ldap_ops_vpc_cidr = Set to VPC CIDR from pre-requisutes 3.
    <Private route table ID 1 for VPC Alpha> => Replace with one private Route Table ID from pre-requisutes 3.
    <Private route table ID 2 for VPC Alpha> => Replace with second private Route Table ID from pre-requisutes 3.
    => Replace with public Route Table ID from pre-requisutes 3.

    ops_vpc_id = Set to VPC ID from pre-requisutes 4.
    ops_vpc_cidr = Set to VPC CIDR from pre-requisutes 4.
    <Private route table ID 1 for VPC Beta> => Replace with one private Route Table ID from pre-requisutes 4.
    <Private route table ID 2 for VPC Beta> => Replace with second private Route Table ID from pre-requisutes 4.

    => Replace the string with S3 bucket from pre-requisutes 5.

  3. Execute Commands as follows:
    => export AWS_DEFAULT_REGION=»us-east-1″

    => terraform init -reconfigure -input=false -backend-config=»encrypt=true» -backend-config=»max_retries=100″ -backend-config=»bucket=<Valid S3 Bucket Name from pre req 5>/State-Files/» -backend-config=»region=us-east-1″ -backend-config=»key=CIOPS-test.tfstate»

    =>terraform get

=>terraform plan -input=false -var-file=CIOPS.tfvars
This will show 761 resources to be created

=> terraform apply -auto-approve -input=false -var-file=CIOPS.tfvars

Terraform Configuration :
Scripts.zip

Понравилась статья? Поделить с друзьями:
  • Ошибка empty reply from server
  • Ошибка empty character constant
  • Ошибка emps toyota
  • Ошибка emp dll как исправить rdr 2
  • Ошибка eml на бмв е46