text:
Q: arcpy.setValue for Condition from Dictionary I am trying to create a function to update multiple fields based on different criteria. I want to pass the field name and condition through a dictionary (please see the function description in the enclosed code).
def CalculateFieldsBasedOnCondition(sourceTable, fieldNames_Condition):
  '''
  fieldNames_Condition = {'TestID': '"LOC-"+(row.getValue("OBJECTID"))',
                          'UPADATED':'Yes'}

  usage: CalculateFieldsBasedOnCondition(sourceTable, fieldNames_Condition)
  '''
  try:
    rows=arcpy.UpdateCursor(sourceTable)
    for row in rows:
      for fieldName, condition in fieldNames_Condition.iteritems():
        row.setValue(fieldName,condition)
        rows.updateRow(row)
    del row, rows

  except Exception, e:
    import traceback, sys
    tb = sys.exc_info()[2]
    print "Line %i" % tb.tb_lineno
    print e.message

I am working with Python 2.6.5, Arcpy 10 and Win 7 64 and the sourceTable is a FileGDB Featureclass.
I would like to get the result of TestID field as "LOC-101" where 101 is the value of the ObjectID field. If I run this now-it'll write the condition as such as it's treated as a string. How can I parse the condition as a non string item?

A: If you have a string that contains Python code you want to run, you can use the Python Built-In Function exec.
In your case what you could do is:
def CalculateFieldsBasedOnCondition(sourceTable, fieldNames_Condition):
'''
fieldNames_Condition = {'TestID': 'id = "LOC-" + str(row.getValue("OBJECTID"))',
                        'UPADATED':'Yes'}

usage: CalculateFieldsBasedOnCondition(sourceTable, fieldNames_Condition)
'''
try:
  rows=arcpy.UpdateCursor(sourceTable)
  for row in rows:
    for fieldName, condition in fieldNames_Condition.iteritems():
      exec(condition)
      row.setValue(fieldName,id)
      rows.updateRow(row)
  del row, rows

except Exception, e:
  import traceback, sys
  tb = sys.exc_info()[2]
  print "Line %i" % tb.tb_lineno
  print e.message

This should execute the row.getValue code in your condition and return a new variable id.  Then, you can use id in your row.setValue.
Here is a simpler example of exec:
x = 'y = "LOC" + str(2*5)'
exec(x)
print y # should return "LOC10"


text:
Q: IIF Function in Access query that adds three fields together and compares answer to another field I'm using Windows Access 2010.  I'm trying to run an IIF Function, using Expression Builder, in a query on one table that asks the query to add three fields together and compare the answer to a fourth field.  If the sum of the three fields are equal to the fourth field return "Ok" if not equal return"Err".
This is the the expression I'm using:
SalmonRelSum: IIf([SalmonRelUM]+[SalmonRelAd]+
                  [SalmonRelUK]=SalmonReleasedCount],"Ok","Err")

When I run the query I get Err on all lines whether it is correct or not.
What am I doing wrong?

A: Assuming that you really mean this:
IIf([SalmonRelUM]+[SalmonRelAd]+[SalmonRelUK]=[SalmonReleasedCount],"Ok","Err")
--------------------------------^

The problem is probably NULL values.  You can use the NZ() function to treat them as zeroes:
IIf(NZ([SalmonRelUM], 0) + NZ([SalmonRelAd], 0) + NZ([SalmonRelUK], 0) =[SalmonReleasedCount],
    "Ok", "Err"
   )

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cucumber: Does a Background run before each execution of a Scenario Outline? Given a Feature file like the following:
Feature: Coffee improves mood in the background

  Background:
    Given the user drank coffee

  Scenario Outline: Coffee changes peoples moods
    Then user <USER> should be <MOOD>

    Examples:
      | USER     | MOOD         |
      |  Michael |  happy       |
      |  Elvis   |  electrified |
      |  John    |  sad         |

Should the background test step "the user drank coffee" run 1 time, or 3 times?

A: Take a look at the contrived answer below.  In the output, you'll see that the background step is executed 3 times.
feature.rb:
Feature: Does a background run before each scenario outline?

  Background:
    When I'm a background step

  Scenario Outline: foo
    Then I should print '<count>'

    Examples:
      |count|
      | 10  |
      | 20  |
      | 30  |

step_def.rb:
When(/^I'm a background step$/) do
  print "BACKGROUND EXECUTED"
end

Then(/^I should print '(\d+)'$/) do |num|
  # empty step
end

output:
Feature: Does a background run before each scenario outline

BACKGROUND EXECUTED  Background:                  # features/login.feature:3
    When I'm a background step # features/step_definitions/login.rb:1

  Scenario Outline: foo           # features/login.feature:6
    Then I should print '<count>' # features/login.feature:7

    Examples:
      | count |
      | 10    |
BACKGROUND EXECUTED      | 20    |
BACKGROUND EXECUTED      | 30    |

3 scenarios (3 passed)
6 steps (6 passed)


text:
Q: fix sidenav - full length I want to make a sidenav that is either full length of the screen or that is actually fixed, with only the right side of the screen scrolling.  Somehow this is not working and the bar is ending abruptly when the right side's height is larger than the bar's.  See sidenav not full screen the photo and code.  Any ideas?
    <!DOCTYPE html>
{% load staticfiles %}
{% load sass_tags %}

    <meta charset="utf-8">
    <title>B  L A C K S H E E P</title>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

    <link rel="stylesheet" href="{% static 'css/master.css' %}">
    <link href="{% sass_src 'scss/master.scss' %}" rel="stylesheet" type="text/css" />

        Menu

           Usuarios

              Crear Usuario

              Login

              Logout

           Compras

              Crear OC

              Administrar OCs

              Crear Proveedor

              Administrar Proveedores

           Almacén

              Crear Item

              Administrar Items

              Crear Ingreso de Mercadería

              Administrar Ingresos

              Crear Egreso de Mercadería

             Administrar Egresos de Mercadería

            Ver Inventario

           Ventas

              Crear Cliente

              Administrar Clientes

              Crear Venta

              Administrar Ventas

    {% block content %}

SISTEMA DE GESTIÓN DE STOCKS V. 1.0

Blacksheep Peru©

    {% if user.is_authenticated %}

Bienvenid@ @{{user.username}}

    {% endif %}

    {% endblock %}


text:
Q: Action - Reaction? I got to know that when a book is kept on a table.

*

*Earth attracts it due to Gravitational force. The book responds by
attracting the earth with same force. (An action-reaction pair)

*The book is kept on table therefore it pushes it with a force which
is nothing but the same force with which it was attracted by the
earth. Thus, the book exerts a force on the table. (Am I correct up
to here ?)

*Now the table responds by pushing the book back which is the normal
force. This force is due the Electromagnetic Force between the table
and the book molecules.

So, the force with which the book pushes the table is at core due to Gravitational Force. And the force due to which the table pushes the book (i.e. normal force) is at core due to Electromagnet Force.
And the both are in turn action-reaction pairs ?
Is it true that the reaction of a gravitational force can be electromagnetic force ??

A: To your last question: no. An action-reaction pair must consist of the same type of force, exerted in exactly opposite directions and always equal in magnitude. That is the content of Newton's 3rd Law, given in mathematical form by
$$\vec{F}_{\textrm{1 on 2}} = -\vec{F}_{\textrm{2 on 1}}.$$
In your example, if the book was on a table in an elevator accelerating upward, the force exerted by the book on the table (and vice versa) would be larger than the force exerted on the book by gravity. We infer this by noting that there is a net force upwards on the book (because it is accelerating), and so the force upwards must be larger than the force downwards (which is the gravitational force). The scalar equation looks like
$$0\neq m a = F_{\textrm{net}} = F_{\textrm{N, table on book}} - mg.$$
Thus, the force (whatever its nature) exerted by the book on the table and the gravitational force exerted by the Earth on the book do not have to be equal, and therefore cannot compose an action/reaction pair.
You are confusing the causal chain of events with "action/reaction" (which is understandable since the phrase "action/reaction" implies some sort of causal chain, although that is not really the conceptual content of the 3rd Law). In this case, the book is pulled down by the gravitational force exerted by the Earth. The table is in the way, and as a consequence, the book pushes into the table. The table gets compressed (think of the table as a very stiff spring), and so it then exerts a force upwards on the book.

So, to be clear, the statement

So, the force with which the book pushes the table is at core due to Gravitational Force.

is correct, but it is irrelevant. That force might come about as a consequence of the fact that the gravitational force is acting, but that force is not a gravitational force itself.


text:
Q: "error: stray \255 in program" on Raspberry Pi I'm having a problem in my program that I do not quite understand. The code itself looks perfectly fine. Also, I find it strange that this code works in Code::Blocks for Raspberry Pi, but not on Code::Blocks for the CHIP computer. Here is the stack trace:
home/chip/Desktop/SuperLuigiBros/startScreen.cpp:41:4: error: stray \255 in program

Here is the code:
File startScreen.cpp
createBrickArea(-15,600, 40, 20, "brBrick");

File brick.cpp:
void createBrickArea(int x, int y, int numBricks, int numRows, string brickType) {
    int brShadowWidth = 32;
    int brShadowHeight = 32;

    for (int i = 0; i <= numRows; i++) {
        if (brickType == "brick") {
            if (i == 0) {
                createBrickRow(x, y + 1, numBricks, "topBrick");
            }

            if (i % 2 == 0 && i != 0) {
                createBrickRow(x, y + 8 * i, numBricks, brickType);
            }

            if (i % 2 != 0 && i != 0) {
                createBrickRow(x + 8, y + 8 * i, numBricks, brickType);
            }
        }

        if (brickType == "brBrick") {
            createBrickRow(x, y + brShadowHeight * i, numBricks, brickType);
        }
    }
}

A: You have a character in your source file that isn't in the basic source character set. The error message tells you the location and value of that character: it's in column 4 of line 41 of startScreen.cpp. I don't think you've pasted the correct line of startScreen.cpp so I can't point it out, but you should delete that character.


text:
Q: Debug Docker Container with Visual Studio Code I have a Django project in Visual Studio Code. I start it through a virtual machine (linux) using Docker. I want to be able to debug the project by adding breakpoints.
I tried following this tutorial, but can't get it:
https://code.visualstudio.com/docs/containers/debug-python
The application starts in "localhost: 8000", the private IP of the physical machine is 192.168.0.102 and that of the virtual machine: 192.168.56.1.
My file launch.json:
{
"name": "Python: Remote Attach",
"type": "python",
"request": "attach",
"port": 5678,
"host": "192.168.56.1",
"pathMappings": [
    {
    "localRoot": "${workspaceFolder}",
    "remoteRoot": "/code"
    }
  ]
}

My views.py:
    # -*- coding: utf-8 -*-
    import tempfile, time
    import json
    import ptvsd
    ptvsd.enable_attach(address=('192.168.56.1', 5678))  #This is ok?
    ptvsd.wait_for_attach()
    ...

The error:
csuperior-web | Performing system checks...
csuperior-web |
csuperior-web | Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f4742165b70>
csuperior-web | Traceback (most recent call last):
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 228, in wrapper
csuperior-web |     fn(*args, **kwargs)
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run
csuperior-web |     self.check(display_num_errors=True)
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 359, in check
csuperior-web |     include_deployment_checks=include_deployment_checks,
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 346, in _run_checks
csuperior-web |     return checks.run_checks(**kwargs)
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/django/core/checks/registry.py", line 81, in run_checks
csuperior-web |     new_errors = check(app_configs=app_configs)
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py", line 16, in check_url_config
csuperior-web |     return check_resolver(resolver)
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/django/core/checks/urls.py", line 26, in check_resolver
csuperior-web |     return check_method()
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py", line 254, in check
csuperior-web |     for pattern in self.url_patterns:
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__
csuperior-web |     res = instance.__dict__[self.name] = self.func(instance)
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py", line 405, in url_patterns
csuperior-web |     patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/django/utils/functional.py", line 35, in __get__
csuperior-web |     res = instance.__dict__[self.name] = self.func(instance)
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/django/urls/resolvers.py", line 398, in urlconf_module
csuperior-web |     return import_module(self.urlconf_name)
csuperior-web |   File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module
csuperior-web |     return _bootstrap._gcd_import(name[level:], package, level)
csuperior-web |   File "<frozen importlib._bootstrap>", line 994, in _gcd_import
csuperior-web |   File "<frozen importlib._bootstrap>", line 971, in _find_and_load
csuperior-web |   File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
csuperior-web |   File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
csuperior-web |   File "<frozen importlib._bootstrap_external>", line 678, in exec_module
csuperior-web |   File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
csuperior-web |   File "/code/ConsejoSuperior/urls.py", line 28, in <module>
csuperior-web |     url(r'^reunion/', include('reunion.urls', namespace='reunion')),
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/django/conf/urls/__init__.py", line 50, in include
csuperior-web |     urlconf_module = import_module(urlconf_module)
csuperior-web |   File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module
csuperior-web |     return _bootstrap._gcd_import(name[level:], package, level)
csuperior-web |   File "<frozen importlib._bootstrap>", line 994, in _gcd_import
csuperior-web |   File "<frozen importlib._bootstrap>", line 971, in _find_and_load
csuperior-web |   File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
csuperior-web |   File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
csuperior-web |   File "<frozen importlib._bootstrap_external>", line 678, in exec_module
csuperior-web |   File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
csuperior-web |   File "/code/reunion/urls.py", line 4, in <module>
csuperior-web |     from reunion.views import generar_temario_pdf, generar_convocatoria_pdf, \
csuperior-web |   File "/code/reunion/views.py", line 5, in <module>
csuperior-web |     ptvsd.enable_attach(address=('192.168.56.1', 5678))
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/ptvsd/attach_server.py", line 101, in enable_attach
csuperior-web |     ptvsd_enable_attach(address)
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/ptvsd/_remote.py", line 64, in enable_attach
csuperior-web |     **kwargs)
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/ptvsd/pydevd_hooks.py", line 128, in install
csuperior-web |     daemon = Daemon(**kwargs)
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/ptvsd/daemon.py", line 503, in __init__
csuperior-web |     super(Daemon, self).__init__(wait_for_user, **kwargs)
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/ptvsd/daemon.py", line 100, in __init__
csuperior-web |     self._install_exit_handlers()
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/ptvsd/daemon.py", line 425, in _install_exit_handlers
csuperior-web |     self._exithandlers.install()
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/ptvsd/exit_handlers.py", line 62, in install
csuperior-web |     self._install_signal_handler()
csuperior-web |   File "/usr/local/lib/python3.6/site-packages/ptvsd/exit_handlers.py", line 103, in _install_signal_handler
csuperior-web |     orig[sig] = signal.signal(sig, self._signal_handler)
csuperior-web |   File "/usr/local/lib/python3.6/signal.py", line 47, in signal
csuperior-web |     handler = _signal.signal(_enum_to_int(signalnum), _enum_to_int(handler))
csuperior-web | ValueError: signal only works in main thread

Thanks!


text:
Q: postgresql group by datetime in join query I have 2 tables in my postgresql timescaledb database (version 12.06) that I try to query through inner join.
Tables' structure:
CREATE TABLE currency(
    id serial PRIMARY KEY,
    symbol TEXT NOT NULL,
    name TEXT NOT NULL,
    quote_asset TEXT
);

CREATE TABLE currency_price (
    currency_id integer NOT NULL,
    dt timestamp WITHOUT time ZONE NOT NULL,
    open NUMERIC NOT NULL,
    high NUMERIC NOT NULL,
    low NUMERIC NOT NULL,
    close NUMERIC,
    volume NUMERIC NOT NULL,
    PRIMARY KEY (
        currency_id,
        dt
    ),
    CONSTRAINT fk_currency FOREIGN KEY (currency_id) REFERENCES currency(id)
);

The query I'm trying to make is:
SELECT currency_id AS id, symbol, MAX(close) AS close, DATE(dt) AS date
FROM currency_price
JOIN currency ON
currency.id = currency_price.currency_id
GROUP BY currency_id, symbol, date
LIMIT 100;

Basically, it returns all the rows that exist in currency_price table. I know that postgres doesn't allow select columns without an aggregate function or including them in "group by" clause. So, if I don't include dt column in my select query, i receive expected results, but if I include it, the output shows rows of every single day of each currency while I only want to have the max value of every currency and filter them out based on various dates afterwards.
I'm very inexperienced with SQL in general.
Any suggestions to solve this would be very appreciated.

A: There are several ways to do it, easiest one comes to mind is using window functions.
select *
  from (
     SELECT currency_id,symbol,close,dt
           ,row_number() over(partition by currency_id,symbol
                                  order by close desc,dt desc) as rr
       FROM currency_price
       JOIN currency ON currency.id = currency_price.currency_id
      where dt::date = '2021-06-07'
       )q1
 where rr=1

General window functions:
https://www.postgresql.org/docs/9.5/functions-window.html
works also with standard aggregate functions like SUM,AVG,MAX,MIN and others.
Some examples: https://www.postgresqltutorial.com/postgresql-window-function/


text:
Q: Getting own location
Possible Duplicate:
How do I get the current GPS location programmatically in Android?

Got a code below.. Will this get me my own location..?
public class MyLocationListener implements LocationListener {

public static double latitude;
public static double longitude;

public void onLocationChanged(Location loc)
{
    loc.getLatitude();
    loc.getLongitude();
    latitude=loc.getLatitude();
    longitude=loc.getLongitude();
}

public void onProviderDisabled(String provider)
{
    //print "Currently GPS is Disabled";
}
public void onProviderEnabled(String provider)
{
    //print "GPS got Enabled";
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}

I know this has been asked several times.. Please help me with the code...

A: You may use this code to start listing for GPS updates and do something with the data you receive. It also prints messages in the log file for easy debugging. Please, note, this function does not return any results, it only starts listening to GPS. Results will be provided some time later in // do something here with the new location data part, when you may save them somewhere.
private void getGpsData() {
    locationManager = (LocationManager) owner.getSystemService(Context.LOCATION_SERVICE);

    locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
            Log.i(TAG, "location change:" + location.toString());

            String longitude = "Londitude: " + location.getLongitude();
            String latitude = "Latitude: " + location.getLatitude();

            if( location.hasAccuracy() ) {  // good enough?
                // do something here with the new location data
                ....
                //
                Log.i(TAG, "GPS listener done");
                locationManager.removeUpdates(this);    // don't forget this to save battery
            }
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
            Log.i(TAG, provider + " status:" + status);
        }

        public void onProviderEnabled(String provider) {
            Log.i(TAG, provider + " enabled");
        }

        public void onProviderDisabled(String provider) {
            Log.i(TAG, provider + " disabled");
        }
    };
    Log.i(TAG,"GPS listener started");
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener );
}


text:
Q: Trash Bin in Unity launcher shows full even when empty I'm having a weird problem where my Trash Bin in Unity launcher is showing full when its not. Usually it wouldn't bother me but its been happening so often lately its getting annoying. Any assistance would be greatly appreciated.

A: I had the same issue. Files that were deleted from a USB drive were causing the Trash to appear full even though it was empty. As soon as I emptied the trash with the USB drive mounted, the trash was cleared.

A: I would just delete the files, and if the bin is still full I would open a Terminal (Ctrl-Alt-T), type "xkill" and press enter. This will change the mouse pointer into an X. Hover the mouse over the Unity Dashboard and press the left mouse button. This will kill the dashboard, and one second later it will come back.
EDIT: The xkill approach will kill the session and the apps running in it and you'll have to login again. It does result in an empty trashcan icon though. (Tested under 14.04): It appears this is a long standing bug with many duplicates see: https://bugs.launchpad.net/ubuntu/+source/gnome-applets/+bug/269441

A: The trash on the desktop tries to sum up all the trashes current user can access.
Each disk, each drive, has got its own trash, sort of speaking.
So (desktop) trash staying full after the usb stick is unplugged means :

*

*trash has not been emptied while usb stick was plugged in,

*deleted files on that usb stick are still present, they've just been moved to the "onboard" .trash folder but not actually deleted.

If that happens just plug in back that usb stick, or external drive, and deleted files will appear again inside the (desktop) trash. Now empty that trash and files from all "connected" trashes will be actually deleted.
It's not a bug. It's just how trashes work under linux-ubuntu.

A: Found that deleting files from ext-HDD causes the trash bin to be full even though its not. The solution is to move the files you want to delete from external to trash-bin than empty. Or log out and log back in


text:
Q: Down-converting voltage I'm trying to reduce the voltage of a power supply for a certain load without affecting the current the load draws. Since the op-amps I could find were not able to provide sufficient current, I added a NPN transistor to the output of the op amp as can be seen in the figure below. I simulated the circuit and it worked perfectly. Would such a circuit function as desired in practice?

A: It should work within the limitations of the opamp and the transistor.
The opamp limitations include its power supply range, input and output voltage range, and output current capability.
The transistor limitations include its current handling capability, and power dissipation at the worst case operating point.
You also have to make sure that the output current divided by the gain of the transistor at that operating point is something the opamp can source.
Added
Note that your circuit will make the output voltage some fraction of the input voltage.  That doesn't matter much if the input voltage is well regulated.  If it varies, however, then the output voltage will vary proportionally with it.  It's not clear if that's what you want.
If what you really want is a lower and fixed output voltage from a higher but possibly varying input voltage, then a off the shelf linear regulator would be simpler than doing it yourself.
If you want a standard output voltage, like 5 V, 9 V, 12 V, for example, then you can even get linear regulators pre-set to that fixed voltage.  The old standard 7805 is one 5 V example of this.
If you want some unusual output voltage, then use a adjustable regulator, like the LM317.  It does all the regulating, and you set the output voltage with a resistor divider.


text:
Q: Mocking methods that call other methods Still hit database.Can I avoid it? It has been decided to write some unit tests using moq etc..It's lots of legacy code c#
(this is beyond my control so cannot answer the whys of this)
Now how do you cope with a scenario when you dont want to hit the database but you indirectly still hit the database?
This is something I put together it's not the real code but gives you an idea.
How would you deal with this sort of scenario?
Basically calling a method on a mocked interface still makes a dal call as inside that method there are other methods not part of that interface?Hope it's clear
         [TestFixture]
            public class Can_Test_this_legacy_code
            {
                [Test]
                public void Should_be_able_to_mock_login()
                {
                    var mock = new Mock<ILoginDal>();
                    User user;
                    var userName = "Jo";
                    var password = "password";
                    mock.Setup(x => x.login(It.IsAny<string>(), It.IsAny<string>(),out user));

                    var bizLogin = new BizLogin(mock.Object);
                    bizLogin.Login(userName, password, out user);
                }
            }

            public class BizLogin
            {
                private readonly ILoginDal _login;

                public BizLogin(ILoginDal login)
                {
                    _login = login;
                }

                public void Login(string userName, string password, out User user)
                {
                    //Even if I dont want to this will call the DAL!!!!!
                    var bizPermission = new BizPermission();
                    var permissionList = bizPermission.GetPermissions(userName);

                    //Method I am actually testing
                    _login.login(userName,password,out user);
                }
            }
            public class BizPermission
            {
                public List<Permission>GetPermissions(string userName)
                {
                    var dal=new PermissionDal();
                    var permissionlist= dal.GetPermissions(userName);
                    return permissionlist;
                }
            }

            public class PermissionDal
            {
                public List<Permission> GetPermissions(string userName)
                {
                    //I SHOULD NOT BE GETTING HERE!!!!!!
                    return new List<Permission>();
                }
            }

            public interface ILoginDal
            {
                void login(string userName, string password,out User user);
            }

            public interface IOtherStuffDal
            {
                List<Permission> GetPermissions();
            }

            public class Permission
            {
                public int Id { get; set; }
                public string Name { get; set; }
            }

Any suggestions?
Am I missing the obvious?
Is this Untestable code?
Very very grateful for any suggestions.

A: As it is now, BizLogin is not testable, as it directly instantiates BizPermission, which in turn instantiates PermissionDal, which then hits the DB.
The best solution would be to refactor BizLogin to replace the direct instantiation of BizPermission with a call to a factory (method), or Dependency Injection. It is not clear to me from your post whether you can refactor the code - if so, this is the preferred solution.
However, if refactoring is not an option, you could still try a nasty trick. This is possible in Java, I don't know C# that well, but since the two languages are fairly similar, I guess it can be possible in C# too (although I can not fill in the exact technical details).
You could replace the compiled class files of BizPermission with different mock implementations for your unit tests. This is of course risky, as you must make sure that the alternative implementations don't get mixed into your production assemblies. Also it requires a bit of messing with classpaths and stuff. So only try this if refactoring is really, absolutely out of question.
How to replace class files with test implementations
(using Java terminology - I hope it is clear enough for C# too...) The basic idea is that the runtime is looking for classes on the classpath, and it loads the first suitable class definition it finds on the classpath. So you can create a mock implementation of BizPermission in your unit test source folder, in the exact same package and with the same interface as the original. Then have it compiled into e.g. a test-classes folder (whereas your production code is compiled into e.g. classes). Now if you set up your test classpath so that test-classes is before classes, the runtime will load the fake BizPermission class when running your tests, instead of the original, when BizLogin attempts to instantiate this class.
Example of refactoring to use a factory method
public class BizLogin
{
    private readonly ILoginDal _login;

    public BizLogin(ILoginDal login)
    {
        _login = login;
    }

    protected BizPermission getBizPermission()
    {
        return new BizPermission();
    }

    public void Login(string userName, string password, out User user)
    {
        var bizPermission = getBizPermission();
        var permissionList = bizPermission.GetPermissions(userName);

        //Method I am actually testing
        _login.login(userName,password,out user);
    }
}

In test code:
public class FakeBizPermission implements BizPermission
{
    public List<Permission>GetPermissions(string userName)
    {
        // produce and return fake permission list
    }
}

public class BizLoginForTest
{
    public BizLoginForTest(ILoginDal login)
    {
        super(login);
    }

    protected BizPermission getBizPermission()
    {
        return new FakeBizPermission();
    }
}

This way you can test the critical functionality via BizLoginForTest, with minimal changes to the original BizLogin class.
An alternative would be to inject a full factory object, as mentioned in Jeff's comment. This would require a bit more code changes (possibly including in the clients of BizLogin), so it's a bit more intrusive.
Note that the prime goal of such refactorings is always to allow unit testing, not to win a prize for the beauty of your new design :-) So it is best to start with the least changes to existing code which allow you to cover the functionality with tests. Once you have the tests in place, you can refactor with more confidence towards a cleaner, better design.


text:
Q: Make grid fill remaining space if there are less columns than specified I am creating a card where it uses grid to displa data. I need to be able to allow a maximum of 8 columns but also allow the grid fill the space available if there is less than 8 columns.
Currently, I'm using grid-template-columns: repeat(8, auto); which fills the space nicely with 8 columns but if I have 6, for example, it leaves a space to the right.

*,
body,
html {
  margin: 0;
  box-sizing: border-box;
}

.card {
  width: 100%;
  height: 150px;
  min-height: 100px;
  background-color: #333333;
  border-radius: 15px;
  padding: 10px 10px;
  overflow: hidden;
  position: relative;
}

.gridWrapper {
  display: grid;
  grid-template-columns: repeat(8, auto);
  grid-gap: 5px;
  margin-bottom: 10px;
}

.gridItem {
  display: flex;
  flex-direction: column;
  justify-content: center;
  padding: 6px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

label {
  font-family: Helvetica;
  font-size: 0.8em;
  color: #76a8b0;
  font-weight: 100;
}

p {
  color: #ffffff;
  font-family: Helvetica;
  font-weight: 100;
}

.cardFooter {
  display: flex;
  flex-direction: row;
  justify-content: center;
  padding: 10px 0 5px 0;
  position: absolute;
  background: #333333;
  bottom: 0;
  width: 100%;
}

      Label

ContentContentContent

      Label

Content

      Label

Content

      Label

Content

      Label

Content

      Label

Content

I've created a jsfiddle at https://jsfiddle.net/eh7g8Lx1/1/

A: Replace grid-template-columns: repeat(8, auto);
line with
grid-template-columns: repeat(auto-fit, minmax(1rem,1fr));

auto-fit value wil solve your problem

A: I managed to fix this with;

grid-template-columns: repeat(auto-fit, 12%);


text:
Q: How would you pick the best image from a webpage in a crawler? If you were given any random webpage on the internet and had the html source only. What method would use to give you the most accurate image that would best describe that webpage? Assume that there are no meta tags or hints.
Facebook does something similar when you post a link but they give you choices of n images to chose from, they don't actually pick one unless it has the meta tags on it.

A: This is best-guess stuff, but:

*

*ignoring anything hosted in another domain will eliminate most ads

*once you've grabbed the images, you can get their size; the biggest is probably the one to use.

*images that are inside  and point to the root of the domain are probably logos. Example: the SO logo on this page is inside .

Edited to add:
It's true that large sites use auxiliary servers for their images. But you could probably make up a couple of simple parsing rules that will get 80% of cases, picking out g-ecx.images-amazon.com and static.ak.fbcdn.net as non-ad servers.

A: If you find og:image meta property, you can use that quite safely, as part of Open Graph specification used to provide images for Facebook links.
Example of format:

        <title>The Rock (1996)</title>
        <meta property="og:image" content="http://ia.media-imdb.com/rock.jpg"/>
        ...

    ...

A: Try to analyze the structure of the page. The majority of web pages roughly has a header, content and footer area. The content area is most likely to contain images related to the subject of the page, so that's what you're looking for.
Find the content area
Most content areas are div elements with with an ID or class named content, so that's always a good first guess. There may be alternative descriptors of the content element, so you'll need to do some research to find common patterns.
The content area will also contain multiple h1 or h2 headings in most cases, so that's another indicator to look for.
Find the header and footer
Another approach is to identify the header and footer. Headers usually contain a hint to the logo of the site, such as an image, CSS class name or link to the root of the site. Footers are most likely to contain things like copyright statements.
You can also find the header and footer by analyzing the links on the page. Most internal links will be in the header and footer, while the content has relatively more outgoing links, if any.
Once you have the header and footer, the content is usually in between :)
Find an image
Once you've identified the content area, the first image is usually your best pick. You should, however, ignore images with a small width and/or height, as these will likely be decorative images.
You could also double-check the images against any included CSS files, to make sure you're not picking an image that's related to the design of the page.
Fall back to an educated guess
If you cannot reliably guess the content area of the page, just use the biggest image on the page, as egrunin suggested. Again, you can check this image against the CSS files, to rule out any design-related images.
In the fall-back case, you could log the URL and review those pages to improve your image detection algorithms.

A: Well I would try to look for divs/spans/h1 with something like class or id = "logo" or "top". Almost every page has its logo on the top of page. Just look on stackoverflow :) logo.
I do it this way in my crawler and it works fine :)


text:
Q: How to view the read and write from the application I won't sudo the application I am using, as I do not trust it. But it is still able to read and write to the files in the /home/{username} when I run it.
How can I see what files the application is reading and writing?

A: You can view the read() and write() calls made by an application by using strace:
strace -f -e read,write <executable>   # Launch new process, or
strace -f -e read,write -p <pid>       # Attach to existing process

You can also see what file descriptors it currently has by looking at /proc/<pid>/fd:
$ ls -l /proc/$$/fd
total 0
lrwx------ 1 chris chris 64 Dec 23 12:46 0 -> /dev/pts/3
lrwx------ 1 chris chris 64 Dec 23 12:47 1 -> /dev/pts/3
lrwx------ 1 chris chris 64 Dec 23 12:47 10 -> /dev/pts/3
lrwx------ 1 chris chris 64 Dec 23 12:47 2 -> /dev/pts/3


text:
Q: Помощь с процентами, питон queries = [
'смотреть сериалы онлайн',
'новости спорта',
'афиша кино',
'курс доллара',
'сериалы этим летом',
'курс по питону',
'сериалы про спорт',
'один',
'два',
'три',
'sdf'

]

res = [(x,len(x.split())) for x in queries]
res1 = dict(res)

count3 = 0
count2 = 0
count1 = 0
for i in res1.values():
  if i == 3:

    count3 += 1
  elif i == 2:
    count2 += 1
  elif i == 1:
    count1 += 1

print(f'Запросы с 3-мя словами составляют: { count3 * 10} %')
print(f'Запросы с 2-мя словами составляют: {count2 * 10} %')
print(f'Запросы с 1-им словом составляют: {count1 * 10} %')

Мне нужно ответы перевести в проценты, т,е. я получаю данные о количестве слов в каждом элементе и вывожу, а теперь мне надо перевести это в процент , но я не доконца понимаю как это сделать(то есть проценты я как бы считать умею) но я не понимаю мне queries принять за сто процентов и отнимать необходимое и как тогда это реализовывать ? Памагити

A: queries = [
    'смотреть сериалы онлайн',
    'новости спорта',
    'афиша кино',
    'курс доллара',
    'сериалы этим летом',
    'курс по питону',
    'сериалы про спорт',
    'один',
    'два',
    'три',
    'sdf'
]

lq = len(queries)

words = dict()

for query in queries:
    l = len(query.split())
    words[l] = words.setdefault(l, 0) + 1

print(f'Запросы с 3-мя словами составляют: {lq / 100 * words[3]} %')
print(f'Запросы с 2-мя словами составляют: {lq / 100 * words[2]} %')
print(f'Запросы с 1-им словом составляют: {lq / 100 * words[1]} %')


text:
Q: vmware vcenter appliance 5.0.0 update slow First, while it would be amazing to get a solution, at this point I'm willing to accept new ideas to try.
Here is the background:
What I'm trying to accomplish is to upgrade an old vCenter Appliance 5.0.0 to at least 5.5.  I've tried all kinds of things, but every time the upgrade fails with red X beside "upgrading vcenter appliance"
This is what I've tried

*

*Tried upgrading from 5.0 -> 5.1 (fails same way)

*Tried upgrading from 5.0 -> 5.5 (fails same way)

My latest goal is to update from from 5.0.0.3324 build 472350 -> 5.0.0.latest.   It looks like the version I'm running is DB2 and I wonder if the transition from DB2->postgres->new version is just too much.  That's why I thought I'd give it this easier task.  This task never fails.  Instead it runs for a week crunching away at /storage/db/export/*.lob files.  I looked into some of them randomly and all 5 that I looked at contain the word "en".  I'm wondering if it went into some kind of a loop.  There was 7 million+ of them there in total.  I didn't have the patience for it to finish, because right now I'm doing the upgrade in the lab, and even if it did finish, it would not be viable solution for the live environment.  I can't be without vcenter for a week.  I tried pruning the database size by turning off logging and reducing retention.  That didn't seem to make a difference.  Is there a way to prune this so that the update doesn't take more than 1 day?
Now thinking outside of the box:

*

*Let's say I give up on automatic update and upgrade, what's the best way to get my configuration manually imported from the old environment?  I saw an option where I could import config.  But how do I export?

*Let's say that I even give up on export/import and I    just rebuild from scratch.  Are there any guides that walk me through the process of doing that?

*Are there other things I should try with the upgrade before giving up on it or am I at a dead end?

Thank you


text:
Q: Cassandra cluster many small nodes vs fewer large nodes I'm wondering what will be the differences between a Cassandra cluster with a few large, powerful nodes, and a cluster with many small nodes. For example, if I choose to run Cassandra on AWS EC2, what will be the difference if I choose one m4.4xlarge node, or two m4.2xlarge nodes, or 4 m4.xlarge, or 8 m4.large? They should have the same compute power, according to https://aws.amazon.com/ec2/pricing/. But will they have different performance in reality for Cassandra? Assume we always set replication factor as 1 so the comparison is fair.

A: I am going to answer this question out of experience. When you are launching Cassandra it requires at least 8 GB for the heap. Therefore I recommend you run on at least 8 GB of RAM, if not more.
Having more nodes obviously means that you have more redundancy, but sometimes the additional resources will be wasted if the nodes do not have similar machine types. For example, if you have 10 nodes with 100 GB of disk, then any node with more than 200 GB of disk will like go to waste. It also means that these nodes will have to communicate more with each therefore increasing the bandwidth required. For AWS, the better VM you get the better the networking.
DataStax recommends use of minimum 16 GB of RAM for Cassandra only in production and between 32-64 GB for recommended specs.
After trying both models I can tell you that the sweet spot is at 8 threads/cores, 32 GB of RAM and 1 TB of SSD.
If you can have a minimum of three such nodes then I think you're fine. If it's a question on whether you should get one powerful node or three less powerful for the same money, always go for the more nodes.


text:
Q: Apache showing "Index of /" directory instead of my functional django application I am using windows 10 in conjunction with XAMMP (Apache) to host my website.
What it looks like: https://imgur.com/a/yCtIH4M
Here is the relevant segment of my htconfigs doc.
LoadModule wsgi_module "C:/Users/taber/AppData/Local/Programs/Python/Python310/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd"
WSGIPythonHome "C:/Users/taber/AppData/Local/Programs/Python/Python310"
WSGIPythonPath "C:\xampp\htdocs\neostorm"
##################################################################################################
#                                       NEOSTORM.US.TO VIRTUAL HOST                              #
##################################################################################################
<VirtualHost *:443>
ServerName neostorm.us.to
Alias /static "C:/xampp/htdocs/neostorm/static"
<Directory "C:/xampp/htdocs/neostorm/static">
        Require all granted
</Directory>
WSGIScriptAlias / "C:/xampp/htdocs/neostorm/neostorm/wsgi.py"
<Directory "C:/xampp/htdocs/neostorm/neostorm">
    <Files wsgi.py>
        Require all granted
    </Files>
</Directory>
</VirtualHost>
##################################################################################################
#                                   MAIL.NEOSTORM.US.TO VIRTUAL HOST                             #
##################################################################################################
<VirtualHost *:443>
    ServerName mail.neostorm.us.to
    DocumentRoot "C:/xampp/htdocs/webmail"
    <Directory "C:/xampp/htdocs/webmail">
        Require all granted
    </Directory>
</VirtualHost>```

  [1]: https://i.stack.imgur.com/klF8N.png
  [2]: https://i.stack.imgur.com/DS0a5.png


text:
Q: Why is a class member not modified by a method inside another class, when passed as a parameter In the following code, I pass a reference to a class variable, using its class name, to a method in another class, expecting it to modify it, but it doesn't. As I understand it, Python always passes parameters by reference, never by value, so I would expect the class variable value to have changed. Why not?
Python 3.6.7 (v3.6.7:6ec5cf24b7, Oct 20 2018, 12:45:02) [MSC v.1900 32 bit (Intel)] on win32
>>> class Other:
...     def modify(self, another_class_member):
...         another_class_member += 1
...
>>> class Mine:
...     cls_incrementer = 0
...     def __init__(self):
...         self.my_other = Other()
...
>>> mine = Mine()
>>> mine.cls_incrementer
0
>>> mine.my_other.modify(Mine.cls_incrementer)
>>> Mine.cls_incrementer
0
>>> mine.cls_incrementer
0

A: This statement creates a local variable and just increments that
another_class_member += 1

If we unpack that we get
another_class_member = another_class_member + 1

Now it should be clear that you are creating a new local variable that shadows your parameter.

A: You can't do the way you want, but you can try following:
Python 3.5.2 (default, Nov 12 2018, 13:43:14)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> class Other:
...     def modify(self, another_class):
...             another_class.increment()
...
>>> class Mine:
...     cls_incrementer = 0
...     def __init__(self):
...             self.my_other = Other()
...     def increment(self):
...             self.cls_incrementer += 1
...
>>> mine = Mine()
>>> mine.cls_incrementer
0
>>> mine.my_other.modify(mine)
>>> mine.cls_incrementer
1


text:
Q: Singleton -- оптимальная реализация В PEP0318 приведен такой паттерн одиночки:
def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:

Сразу же бросается в глаза некоторая неоптимальность данной каноничной реализации (простите что святотатствую). Так, если это паттерн "одиночка", то зачем нам словарь инстансов (причем сам термин во множественном числе)?
Недолго думая я набросал свой собственный велосипед:
def Singleton(f):
    instance = f()
    return lambda : instance

@Singleton
class Some:
   def __init__(self):
        print(str(self.__class__) + " init here.")

который точно также прекрасно справляется со своей задачей. Это может быть и неочевидно на первый взгляд, но проверьте и убедитесь:
first = Some()
second = Some()
third = Some()

print("first == second ?", first == second)
print("first == third  ?", first == third)

Вывод:
<class '__main__.Some'> init here.
first == second ? True
first == third  ? True

А вопрос будет такой: какие вы видите недостатки в подобной реализации? Может быть я чтото не учел? Заранее благодарю за конструктивные ответы.

Upd. Здесь доработанный вариант синглтона с учетом всех замечаний.

A: В реализации из PEP0318 для каждого класса с декоратором @singleton экземпляр будет создан только в тот момент, когда он будет в первый раз запрошен.
В вашей реализации экземпляр создаётся в тот момент, когда в коде встречается определение класса, даже если по факту дальше в коде экземпляр класса никогда явно не создаётся.
Более того, если в одном модуле определено много классов с вашим декоратором, а другой модуль импортирует из первого только один класс, то экземпляры будут созданы сразу для всех.
Это может быть нежелательным поведением по следующим причинам:

*

*Инстанцирование экземпляра может занимать много времени, памяти или требовать такие ресурсы, как соединение с базой, открытые файлы, сетевые сокеты и т.п. Лишние экземпляры буду зря тратить эти ресурсы. Кроме того, для программиста, который использует вашу реализацию декоратора может быть вообще сюрпризом, что эти ресурсы оказались заняты. Если он не планировал создавать экземпляры нескольких классов с этим декоратором, то существует вероятность, что он написал свой код так, что эти неожиданные экземпляры вообще будут конфликтовать друг с другом. Отладка всего этого может оказаться для него очень нетривиальной задачей ))

*Инстанцирование экземпляра может требовать определённых условий. Например, класс может ожидать, что в момент создания экземпляра уже будет существовать подключение к базе данных. Но если инстанцирование происходит не в момент, когда экземпляр явно в первый раз запрошен в коде, а гораздо раньше, то это может стать проблемой.


text:
Q: Programmatically add constraints to labels that have been programmatically added to a table cell Here's what I've tried.
I've set my rows to automatically resize based on their content which works perfectly if I manually add labels and manually add constraints to said labels.
override func viewDidLoad() {
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 100
}

Then I'm adding labels and their constraints like so:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "TypeCell", for: indexPath) as UITableViewCell

    // Programmatically add a label
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = dataLabels[indexPath.row] // dataLabels is an array of my labels
    label.tag = indexPath.row
    cell.contentView.addSubview(label)

    // Programmatically add constraints
    label.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 15).isActive = true
    label.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: 15).isActive = true

    return cell
}

When I run the project, I don't get any errors. The rows seem to be sizing to the height of the label and the label is responding to the programmatically set constraint but the row doesn't seem to know that the constraint exists. Here's a screenshot:

In my past experience, this should have been all that I needed to add constraints to objects programmatically.
I've also tried using:
tableView.beginUpdates()
tableView.endUpdates()

But that doesn't help. When the table reloads, it reloads right back to the same position.

A: Looks like a common "whoops" mistake...
// Programmatically add constraints
label.topAnchor.constraint(equalTo: cell.contentView.topAnchor, constant: 15).isActive = true
label.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: 15).isActive = true

What those two lines say, is:

*

*Make the Top of the Label equal to the Top of the ContentView PLUS 15pts.

then

*

*Make the Bottom of the Label equal to the Bottom of the ContentView PLUS 15pts.

What you really want is for the Bottom of the ContentView to be equal to the Bottom of the Label PLUS 15pts.
So, you can change the line to either:
// set Bottom of Label to Bottom of View MINUS 15pts
label.bottomAnchor.constraint(equalTo: cell.contentView.bottomAnchor, constant: -15).isActive = true

or
// set Bottom of View to Bottom of Label PLUS 15pts
cell.contentView.bottomAnchor.constraint(equalTo: label.bottomAnchor, constant: 15).isActive = true

That should do it.


text:
Q: How can i get the password show and hide option for an existing char field in xml for odoo 8 framework is it possible by using some widgets I have added the java script in the xml file  and added widget in the smtp_pass field.
<group string="Security and Authentication" colspan="4">
<field name="smtp_encryption" on_change="on_change_encryption(smtp_encryption)"/>
<script>
    openerp.MODULE_NAME = function (instance) {
        instance.MODULE_NAME.Password = instance.web.form.FieldChar.extend({
            events: {
                "click .password": "toggle_password",
            },

            initialize_content: function() {
              this.setupFocus(this.$('input'));
              this.$('input').parent().append('<i class="fa fa-fw fa-eye password" style="position: relative;margin-bottom: 0px;bottom: 20px;left: 90%;"/>');
            },

            toggle_password: function() {
                var node = this.$('input');
                if (node.attr('type') === 'password') {
                    node.prop('type', 'text');
                    $('i').toggleClass("fa-eye-slash");
                } else {
                    node.prop('type', 'password');
                    $('i').removeClass('fa-eye-slash')
                }
            },
        });

        instance.web.form.widgets.add('password', 'instance.MODULE_NAME.Password');
    };
</script>
<field name="smtp_user"/>
<field name="smtp_pass" password="True" widget='password'/>

And in python file i added the related field for smtp_pass
'smtp_pass': fields.char('Password',size=64, help="Optional password for SMTP authentication"),
'related_smtp_pass':fields.char(related='smtp_pass'),

A: Using a field several times on the form view is not supported in Odoo 8.
You can add a related field to smtp_password and use it to show the password.
related_smtp_password = fields.Char(related='smtp_password')

It is not possible to set the password attribute with conditions.
The char field is handled by the client widget, you can customize the behavior of the char field using the javascript.
You can extend the char widget and create a new one with an eye to the right corner to show or hide the password, you can try the following example:
openerp.MODULE_NAME = function (instance) {
    instance.MODULE_NAME.Password = instance.web.form.FieldChar.extend({
        events: {
            "click .password": "toggle_password",
        },

        initialize_content: function() {
            this.setupFocus(this.$('input'));
            this.$('input').parent().append('<i class="fa fa-fw fa-eye password" style="position: relative;margin-bottom: 0px;bottom: 20px;left: 90%;"/>');
        },

        toggle_password: function() {
            var node = this.$('input');
            if (node.attr('type') === 'password') {
                node.prop('type', 'text');
                $('i').toggleClass("fa-eye-slash");
            } else {
                node.prop('type', 'password');
                $('i').removeClass('fa-eye-slash')
            }
        },

    });

    instance.web.form.widgets.add('password', 'instance.MODULE_NAME.Password');
};

You have just to use the following declaratio in the form view:
<field name="smtp_password" password="True" widget='password'/>

Edit:
Create an XML file (templates.xml) and add the following code:
<openerp>
    <data>
        <template id="assets_backend" name="Assets" inherit_id="web.assets_backend">
            <xpath expr="." position="inside">
                <script type="text/javascript" src="/MODULE_NAME/static/src/js/script.js"></script>
            </xpath>
        </template>
    </data>
</openerp>

And add it to the data in the manifest file (__openerp__.py):
'data': [
        'templates.xml',
    ],

Then create the js file under /static/src/js/ and add the above javascript code.


text:
Q: Скрипт javascript "оставьте заявку до **" как сделать? Всем привет. Сейчас начал изучать PHP, но здесь вроде JavaScript.
Как сделать скрипт, чтобы каждый день было текущее число.

Оставьте заявку до 20.08 (включительно) и получите скидку 25%

21 числа будет написано 21.08 и т.д

A: Для получения даты можно использовать конструкцию в JS:
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //Январь не может быть нулем
if(dd<10) {
    dd = '0'+dd
 }

if(mm<10) {
    mm = '0'+mm
}
var today = dd+'.'+mm;

Дальше привести ее к формату, который вы желаете, и в html оставить элемент "span" с каким-нибудь Id, после чего найти этот элемент и вставить в него текст:
document.getElementById("myspan").innerHTML=today;


text:
Q: How to prevent a microcontroller to reboot due to Vcc fluctuations? Case #1: I have a pump station with an autonomous 240V pump motor switched by a 240V pressure switch, feeding a pressure tank to a max. pressure. After said tank are four 24V solenoid valves (250mA inrush, 180mA holding), controlled by a 5V-fed relay board (Sainsmart). This relay board is connected to microcontroller (Arduino UNO) outputs via optocoppler.
The relays come ON|OFF in series. Once the last one switches OFF, the pump motor still runs due to the switch-OFF-pressure not reached yet. A few seconds later the pressure is up, the pump switches OFF -- and here comes the problem -- the microcontroller reboots (when the motor switches OFF).
There is a single phase 240V supply for all of it.
The solenoid valves get their power from a ring-core transformer 50VA.
The microcontroller has a 240V/5V switched plug-in power supply with 2A (<200mA required).

Case #2: Another scenario: the 240V/5V connected microcontroller controls a small relay (5A), which switches 240V (with snubber) for a bigger 25A DIN-mounted relay (contactor), which switches a 3kW resistive heating element for a hot water system. On occasion, the microcontroller reboots when it switches on the load.
I see the same problem in both cases. But what could be the problem/solution?
100uF with 0.1uF in parallel to 5V Vcc/GND?

Case #1: the trials...
1. use a 4k7 and parallel 100nF from +5V Vcc to RESET. No change.
2. use a 1,000uF capacitor parallel to +5V Vcc and GND. No change.
Case #1: the solution...
3. add a snubber (104 in series with 100R) parallel to the relay contacts.
No more rebooting problems! :)
Thanks for all the input; it triggered a lot of research and validation, resulting in some learning... more so to create more robust circuits, when it comes to inputs into uC devices.

A: I agree with Lucky Bot that PSU "holdover" is not a problem here, and I agree with Spehro Pefhany and Lucky Bot that this looks like an EMC problem.
What happens when the pressure switch switches off is that an inductive load gets abruptly turned off. The "magnetic inertia" of the inductance tries to keep the current flowing, but you've barred the path by a very high resistance... which results in an immediate mighty voltage spike across the inductor's terminals, typically pulling an arc across the mechanical switch contacts, excited by the motor's winding. The arc itself is noisy, and the switch can be bouncey. Apart from the voltage spike, the brief but mighty dI/dT also produces an EM pulse spreading through the "ether" from the inductor(s), possibly inducing some glitches/noise in the various PCB traces around your Arduino.
There's a similar problem with relay coils, e.g. driven by a transistor. As the transistor goes open circuit, its collector suffers a spike from the relay coil - which is why the transie should always be protected by an anti-parallel "flyback diode".
Properly blocking the power rail to your Arduino MCU is one partial countermeasure. Unfortunately, attention to PCB layout is another one. At the motor, you can try inserting an EMC filter in the power wiring, and/or pull a ferrite bead/ring/sleeve over the wires, or some such.
Do you have a 'scope to maybe look at some interesting points around the MCU? Such as, the PSU input and the reset input?
That said, digital circuitry can be tough to debug upon this symptom, even with a 'scope at hand. Your advantage is that the Arduino is a simple board, and well documented. I haven't studied the PCB myself. Generally, in computers, the reset line is not a single trace going from some switch or header to the MCU, it can be a more complex network in itself, with several "sources" of the reset signal. A good place (starting point) to look for reset glitches is at the CPU's RESET input pin. And, you may face an interesting uncertainty: the glitches that you see on a 'scope, do they come from the trace or "node" that you're watching, or are they possibly induced into the "loop" between your probe tip and the probe's ground leash? For comparison, try shorting your probe tip to the probe's ground clamp, and generate the EM spike, to be half sure what you're looking at.
You may find that the amplitude of the EM pulse / spike is somewhat random, or very random. Apart from other misc random influences (such as the precise unique one-time pattern of the "bounce" of a mechanical relay contact) the sinusoidal shape of the current through the motor can also be a factor in AC-driven inductive loads. What's random here is the instant in time vs. the instantaneous phase of the sinewave, where the relay contacts open. Some solid-state switches (transistor-based, i.e. PhotoMOS or IGBT) can cause EMI too, by the same mechanism. They don't exhibit mechanical "bouncing", but the abrupt turn-off (dI/dt) is still there. Solid-state switches based on a triac or thyristor should be more polite: they switch off during a zero transition. That's why they only work for AC.
As for some references... speaking of blocking power to IC's by capacitors, try reading through this topic and follow the links to the Kemet KSIM and to the Murata C39E appnote. Those two sources dissect the "choice of blocking capacitors" in meticulous detail :-) And, maybe take a look at this video on spiking caused by inductive loads on turn-off (and the purpose of flyback diodes, though a flyback diode will only protect the switching transistor, and will not prevent the EM pulse spreading though the ether). You seem to be into DIY... ferrite sleeves for power filtering can be found in scrap PC power supplies or various cords and even data interconnect cables. A proper power line filter for your motor (LC PI or whatever) can easily cost more than the Arduino, but may be worth the investment.
If you try some ferrite sleeves or rings, you can put several in series, or wind a couple turns around one, you can make a common mode choke by inserting or winding the live and return alongside each other through a shared ring... And whether you try ferrite sleeves/rings or an LC filter (or both), it may make a difference if you put the filter close to the motor vs. close to the switch. I'd say close to the motor would be better, as it would make the "parasitic antenna" shorter for the radiated RF energy... then again my view may be naive.

A: Using Q = C * V, and taking the derivative, we get
dQ/dt = dC/dT * V  + C * dV/dT
Now we keep the capacitor constant, leaving dQ/dT = C * dV/dT
Replace dQ/dT with I, and we have the useful I = C * dV/dT
Now assume I = 0.2 amps, dV = 0.5 volt, dT = 5 seconds, and re-arrange to find C.
C = I /(dV/dT) =  I * dT / dV = 0.2 * 5 / 0.5 = 2 Farads capacity.
Have you considered a super-capacitor, isolated by a schottky diode from the MCU VDD pin? with 100 ohms across the diode to keep the super-cap charged?
=========================================
Lets take a swag (scientific wild asses guess) at the math for magnetic field problems on PCBs. Use the formula
Vinduce = MUo * MUr * Area/Distance * dI/dT.
Our first assumption is the dI/dT: assume its 10 amps in 100 nanoseconds, with the 100nanoseconds defined by parasitic capacitance in the pump motor windings.
Again this is a SWAG.
Assume the PCB, at the MCU Reset pin, has 1cm by 1cm area. Or if the Reset trace runs all over the place, assume 1cm by 10cm. And assume the pump/relay wiring is 1cm away from this Reset loop.
What induced voltage can we predict, using our assumptions? First task is inset values for MUo (4*pi*1e-7) and for MUr (1, for air, vacuum, copper, FR-4, etc) and the equation becomes
Vinduce = 2e-7 * Area/Distance * dT/dT
Vinduce = 2e-7 * 0.01meter * 0.01meter/0.01meter * 10 amps/100nanoSec
Vinduce = [here we put a number indicating a big problem exists: 1volt; and we
    agree if our math predicts 1v is likely then we probably do have a problem]
Vinduce = 2e-7 * 0.01 * 10amp * 1e+7
Vinduce = 2e^(-7 -2 +1 +7) = 2e^(-1) = 0.2 volts.
OK we may or may not have an EMI problem. Examine the area of the loop on the Reset pin. Perhaps bring the StackExchange people into the thinking, by posting that portion of the PCB layout (the layers, and the component layer).
There have been at least 3 good answers on EMI. Once you find the loop area on the Reset pin, make a loop of that size, on insulated wire, and tape it to the PCB to be monitored by a scope probe; getting a zero-area GND connection to the probe may be a challenge. Then turn the pump on and off and on and off. And please report what you find.

A: Sounds like the problem is EMI from the switching, and this is one reason why hobbist boards like Arduino are not often used industrially, and relativey expensive PLCs are common.
The solution is better EMC design and layout, or buying a product with those features engineered into it from the beginning. Avoiding mechanical relays helps, but is often less appropriate.

A: Whatever measly input capacitance is inside the Switch mode converter is probably enough to run the MCU through this event considering these caps are charged to full AC line voltage. Likely Spehro is correct and the RESET pin on the MCU is getting toggled from EMI. Try connecting this pin directly to the MCU supply or put the largest SMD cap that will easily fit across whatever tiny cap is normally present on this pin.


text:
Q: Re-run JavasScript
A: JQuery load can take a second parameter that is a function to be called when the load is complete. So you can call the function that initializes your div when the load is completed. View the JQuery API Docs for load() for more info.
<script>
        $(function() {
            $('.cart-container-toggle').on('click', function() {
           $('.cart-container').load("https://www.website.com/ .inner-container", initCartDiv);
            });
        });
</script>

<script>
    function initCartDiv() {
          jQuery(function($) {
            ajaxCart.init({
              formSelector: '#AddToCartForm',
              cartContainer: '#CartContainer',
              addToCartSelector: '#AddToCart',
              cartCountSelector: '#CartCount',
              cartCostSelector: '#CartCost',
              moneyFormat: {{ shop.money_format | json }}
            });
          });

          jQuery(document.body).on('afterCartLoad.ajaxCart', function(evt, cart) {
            // Bind to 'afterCartLoad.ajaxCart' to run any javascript after the cart has loaded in the DOM
            timber.RightDrawer.open();
          });
    }

    initCartDiv();
</script>


text:
Q: How can we get the sum of the current page rows/data and how do we know new page is being added in multipage widget? How to find sum of all the rows in a particular page. I am using Multipage widget and my data (rows) span across multiple pages. So i want to achieve the below.

*

*End of the every page i want to show, sum of number of rows printed in this particular page.

*I show the data by grouping the category. for ex, if i take the classic example of invoice page that was given in dart-pdf package in the below screen shot, it shows 10 detail record rows in this page. so in the footer record for this page, i want to show total number of row = 10 and total $ amt = 955.82. This is one problem i am facing. Footer callback function is being called after all detail records are painted and hence i assume i can't use this callback. but i can try store the detail records count in some global variable and can use this in footer call back but the problem is how do i know this is last row is being written in this page. I am unable to find out any call back to say new page is added or end of page etc. if i know this is end of the page then i can count how many rows written so far. similarly if we have any callback explaining new page is being added when data span across multiple pages that would be nice to achieve.

*

*Another use case is, assume that your invoice page (above screen shot) is given for one category (in other words group by category) and if this category span across to next page then in next page first row, i should say this "same category invoice records are continued in this page". In order to show this, i need to know whether new page is being painted or not. is there a way to achieve this?

my widget tree is pdf.addpage -> multipage -> Table -> tablerow -> other widgets.
Appreciate the response. Thanks!


text:
Q: C# addition operator overloading I am trying to port some C# code to another language (C# is not my usual language).
I have a vector class (cpVect) that overrides the '+' operator twice:
    public static cpVect operator +(cpVect p1, cpVect p2)
    {
        return new cpVect(
            p1.x + p2.x,
            p1.y + p2.y
            );
    }

    public static cpVect operator +(cpVect p1)
    {
        return new cpVect(
            +p1.x,
            +p1.y
            );
    }

I can see that a new instance of cpVect is returned from both methods but I'm trying to figure out how one would call these methods in a code example (so I can make sure I'm porting them correctly). For instance, does the second method add p1 to the receiving cpVect?
v3 = v1 + v2   <-- does this call method one above?
v1 = v1 + v2   <-- does this call method two above?

Thanks

A: Both call the binary operator. The unary operator would be called if you only had one operand:
v3 = +v1;

The unary + operator is rarely useful, to be honest - but it's mostly there for symmetry with the unary - operator.


text:
Q: Share doesnt ask credentials I got a problem with one share-folder. Its just basic network-share from one VM and idea is that only admins can access to that share.
When im logged with admin-user account I can get to share, but if I go with non-admin-account it just throws me with a pop-up "you have no permissions" or something similar.
And what I want, is that I have change to write admin-credentials on that point so I could access share. No i cant access it with normal user-account at all.
Few points:

*

*Its domain-environment.

*All other users have a mapped drive to same server where is the one im trying to access.

*I have tried to access admin-share after i have deleted (net use) all connections to that other share i writed on point 2.

Thanks in advance.

A: Credentials are not per-share, they're per-server. So if you can successfully authenticate to the server at all, the client assumes that's OK.
You can use net use \\host\share /user:DOMAIN\Admin from the command line to temporarily connect with different credentials (specifying a drive letter is optional).
Some programs can also be run via runas /user:DOMAIN\Admin /netonly, however, Explorer itself won't work with it.


text:
Q: I get [Errno 22] Invalid argument when I compile a Python file containing only certain comments. Sometimes the file even gets deleted #import pynput.keyboard
# str (key

When I try to run the Python file above (with only comments!) I get this error:
PS C:\Users\[my name]\Documents> python3 test.py
C:\Users\[my name]\AppData\Local\Microsoft\WindowsApps\python3.exe: can't open file 'test.py': [Errno 22] Invalid argument

It happens both when I run it with VS Code and in Windows PowerShell and I get the same thing with some similar codes. For example:
#import pynput.keyboard
key = 2
print(str(key))

and
import pynput.keyboard
key = 2
print(str(key))

and
#import pynput.keyboard
#aastr  (keyaa

When I started getting these errors (in a larger file) the file also got deleted every time, but now I can't replicate that anymore. Can anyone explain what is happening?


text:
Q: Why this code finishes if getter is marked as synchronized? Why this code successfully finishes when method get() is marked as synchronized despite the fact that field value is not volatile? Without synchronized it runs indefinitely on my machine (as expected).
public class MtApp {

    private int value;

    /*synchronized*/ int get() {
        return value;
    }

    void set(int value) {
        this.value = value;
    }

    public static void main(String[] args) throws Exception {
        new MtApp().run();
    }

    private void run() throws Exception {
        Runnable r = () -> {
            while (get() == 0) ;
        };
        Thread thread = new Thread(r);
        thread.start();
        Thread.sleep(10);
        set(5);
        thread.join();
    }
}

A: Synchronization forces this.value = value to happen before get().
It ensures the visibility of the updated value.
Without synchronization, there is no such guarantee. It might work, it might not.

A: @Andy Turner is partly correct.
The addition of the synchronized on the get() method is affecting the memory visibility requirements, and causing the (JIT) compiler to generate different code.
However, strictly speaking there needs to be a happens before relationship connecting the set(...) call and the get() call.  That means that the set method should be synchronized as well as get (if you are going to do it this way!).
In short, the version of your code that you observed to be working is NOT guaranteed to work on all platforms, and in all circumstances.  In fact, you got lucky!

Reading between the lines, it seems that you are trying to work out how Java's memory model works by experimentation.  This is not a good idea.  The problem is that you are trying to reverse engineer an immensely complicated black box without enough "input parameters"1 for you to vary to cover all potential aspects of the black boxes behavior.
As a result the "learning by experiment" approach is liable to leave you with an incomplete or mistaken understanding.
If you want a complete and accurate understanding, you should start by reading about the Java Memory Model in a good text book ... or the JLS itself.  By all means, use experimentation to try to confirm your understanding, but you do need to be aware that the JMM specifies (guarantees) only what happens if you do the right thing.  If you do the wrong thing, your code may work anyway ... depending on all sorts of factors.  Hence, it is often difficult to get experimental confirmation that a particular way of doing things is either correct or incorrect2.
1 - Some the parameters you would need don't actually exist.  For example, the one that allows you to run Java N for N > 12, or the one that allows you to run on hardware that you don't have access ... or that doesn't yet exist.
2 - As is illustrated by your example.  You are getting the "right" answer, even though the code is wrong.

A: For starters, either value needs to be volatile or both get and set need to be synchronized for this to be correct.
JLS 17.4.5:

An unlock on a monitor happens-before every subsequent lock on that monitor.

It is possible for value to be set to 5 prior to the lock being released, which puts it before the happens-before edge and makes it available the next time the lock is acquired.
It should be noted that such guarantees are fragile and depending on the thread scheduler, may not exist at all. On platforms with weaker synchronization models, you may not see the same effects you see here.

See also:
Loop doesn't see changed value without a print statement
Strange behavior of a Java thread associated with System.out


text:
Q: Expected value of sum of independent variables squared Hi can someone tell me if I can decompose the following:
x any y are statistically independent and have zero mean.
$E((x + y)^2) = E(x^2) + E(y^2)$
I tried with setting into the definition of the expected value:
$\sum_{x}\sum_{y}(x^2 + 2xy + y^2) P(X = x, Y = y)$
$\sum_{x}\sum_{y}x^2 P(X = x, Y = y) + \sum_{x}\sum_{y} 2xy P(X = x, Y = y) + \sum_{y}\sum_{x} y^2 P(X = x, Y = y)$
$\sum_{x}x^2 P(X = x) + 2\sum_{y}\sum_{x}xy P(X = x, Y = y) + \sum_{y} y^2 P(Y = y) $
$E(x^2) + 2 E(xy) + E(y^2)$
I come to the statement above, but I think it is wrong I need the first statement for a proof and I can't image how I can do if the first statement is wrong.

A: Note that if $X$ and $Y$ are independent, then $E(XY) = E(X)E(Y)$. So,
\begin{align*}
E((X+Y)^2) & = E(X^2 +2XY + Y^2)\\
& = E(X^2) +2 E(XY) +E(Y^2)\\
& = E(X^2) +2 E(X)E(Y) +E(Y^2)\\
& = E(X^2) +2 (0) +E(Y^2)\\
& = E(X^2)+E(Y^2)\,.
\end{align*}
Regarding your comment

Ok but then all above would be zero? Because $E(X^2) = E(X)E(X) = 0$ and
  $E(X^2) = E(X)E(X) = 0$

This isn't true because that decomposition is possible if two random variables are independent. Since $X$ isn't independent of $X$, $E(X^2) \ne E(X)E(X)$.


text:
Q: can't execute a command even i'm in the group and command is -rwx--x--- I'm in $ORACLE_HOME/OPatch directory and when I type opatch then I get the response as,
-bash: opatch: command not found

If I do ./opatch, then I get the response as,
/bin/sh: ./opatch: Permission denied

ls -l on OPatch shows -rwx--x---.
So for the group oinstall, it should have execute right and id -g confirms that the user belongs to the oinstall group.
So why I can't execute opatch in this case?

A: It sounds like opatch is a script. That is, it is a text file that starts with #! and lists its interpreter (maybe /bin/sh). Only compiled binaries (directly executable code) can be executed without read permission. For all scripts, no matter the interpreter (sh, python, etc...), the interpreter needs to be able to open the file, which mandates read permission plus execute permission.


text:
Q: What does the keyword this refer to when used as a function parameter/agrument? Hello I'm somewhat past the newbie stage of javascript and am looking at how a certain widget library works. (All printed out code, can't copy and paste) I condensed it so I hope it's enough for you guys to understand.
Page.prototype.createForm= function (){
    ....
    this.form1 = new Form();
    ....
    this.form1.clickEvent(this,"clickedDelete");
};

Page.prototype.clickedDelete= function (){
     ....
};

So my question is what the this inside ClickEvent mean?
this.Form.clickEvent(this,"clickedDelete")
I hope this is enough information, but anyways, what is this inside
 (this,"clickedDelete")

referring to?
is it the page object or page.form1 (thus called this.form1?)
If this is too little information, can you provide any links or examples of your own that's somewhat close to this example. Thank you.

A: this refers to whatever object the currently executing function is called on -- in your example, it is the Page object, assuming it is called along the lines of page.createForm().


text:
Q: Javascript function for trilinear interpolation All,
I THINK that I'm looking for a function for Trilinear interpolation.
Here's the details:
I have a three dimensional dataset:

*

*Dimension 1 varies from 0 to 100 in increments of 5

*Dimension 2 varies from 0 to 100 in increments of 5

*Dimension 3 varies from 0 to 1 in increments of 0.1

So, I have 4851 total values (21 x 21 x 11).
If I need to find the value for (10, 25, 0.3) - that's easy - I can just look it up in the 3-dimensional array.
But, I need to be able to come up with the best approximation, given dimensional values of (17,48,0.73), for example.
So, I think that what I'm looking for is a trilinear interpolation (although I'd definitely appreciate any suggestions for a better method, or a hint that I'm on the wrong topic altogether...)
A quick google search turns up this formula:
Vxyz =
V000(1-x)(1-y)(1-z) +
V100x(1-y)(1-z) +
V010(1-x)y(1-z) +
V001(1-x)(1-y)z +
V101x(1-y)z +
V011(1-x)yz +
V110xy(1-z) +
V111xyz

Which looks like what I'm looking for, but I'm not sure what x, y, and z represent. If I had to guess, x is a ratio - the distance of my "target" first dimension value from the nearest two values I have, y is the ratio for the second dimension, and z is the ratio for the third dimension.
Of course, since I don't really know what I'm talking about, I wouldn't know if this is right or wrong.
So, ideally, I'd like a bit of Javascript or pseudo-code that shows exactly how to accomplish this.
Many thanks in advance!

A: The code you are looking at is trying to do a weighted average of the 8 points of the cube with vertices that are in your dataset, and which encloses the point you are trying to find a value for.
For a point p
// Find the x, y and z values of the
// 8 vertices of the cube that surrounds the point
x0 = Math.floor(p.x / 5);
x1 = Math.floor(p.x / 5) + 1;

y0 = Math.floor(p.y / 5);
y1 = Math.floor(p.y / 5) + 1;

z0 = Math.floor(p.z / .1);
z1 = Math.floor(p.z / .1) + 1;

// Look up the values of the 8 points surrounding the cube
p000 = dataset[x0][y0][z0];
p001 = dataset[x0][y0][z1];
// ...

// Find the weights for each dimension
x = (x - x0) / 5;
y = (y - y0) / 5;
z = (z - z0) / .1;

// Compute the guess using the method you found
// ...


text:
Q: Least Common Subsequence with optimized space (two columns, since it's Markovian) I'm trying to write LCS of two String objects using bottom-up dynamic programming. I'm able to get it to work properly with O(mn) space. However, as I could see, I don't need all the previous columns. So, I tried to modify it to get it fit in 2 columns so space become O(m). However, it's not working for all inputs (for example, to this: abcabc and abcbcca). What am I missing here? NOT HW, NOT CONTEST nothing. Practicing DP.
public int longestCommonSubsequence(String input) {
    char[] firstStr = this.string.toCharArray();
    char[] secondStr = input.toCharArray();
    int[][] maxLength = new int[firstStr.length+1][2];

    for(int i=0; i <= firstStr.length; i++) {
      maxLength[i][0] = 0;
    }
    for(int j=0; j < 2; j++) {
      maxLength[0][j] = 0;
    }

    for(int i=0; i < firstStr.length; i++) {
      for(int j=0; j < secondStr.length; j++) {
        if(firstStr[i] == secondStr[j]) {
          maxLength[i+1][1] = 1 + maxLength[i][0];
        }
        else {
          maxLength[i+1][1] = maxLength[i][1]>maxLength[i+1][0]?maxLength[i][1]:maxLength[i+1][0];
        }
      }
      //Copy second row to first row
      for(int l =0; l < firstStr.length; l++) {
        maxLength[l][0] = maxLength[l][1];
      }
    }

    return maxLength[firstStr.length -1][0];
  }

A: This has two problems:
    if(firstStr[i] == secondStr[j]) {
        maxLength[i+1][1] = 1 + maxLength[i][0];
        // check here if maxLength[i+1][1] is greather than the last max length
    }
    else {
        maxLength[i+1][1] = maxLength[i][1]>maxLength[i+1][0]?maxLength[i][1]:maxLength[i+1][0];
         // absolutely wrong: maxLength[i+1][1] = 0;
    }

Here can see the algorithm with micro optimization.
public static int lcs(String s0, String s1) {
    int maxLength = 0;
    int [][]lengths = new int[2][s1.length()+1];

    for (int i = 0; i < s0.length(); i++) {
        for (int j = 0; j < s1.length(); j++) {
            if (s0.charAt(i) == s1.charAt(j)) {
                lengths[0][j+1] = lengths[1][j] + 1;
                if (lengths[0][j+1] > maxLength) {
                    maxLength = lengths[0][j+1];
                }
            } else {
                lengths[0][j+1] = 0;
            }
        }
        int []temp = lengths[0];
        lengths[0] = lengths[1];
        lengths[1] = temp;
    }
    return maxLength;
}


text:
Q: jasmine mock second method I am trying to do the following thing in Jasmine but not sure if it is possible :
I Got a service object with 2 methods, A and B.
Method A calls method B (B is in fact a $http call which I do not want to do during my test : I want to mock it).
In my BeforeEach section I do this :
spyOn(Serviceinstance, 'B').and.callFake(function(){
     return true;
      });
in my Test :
var result = Serviceinstance.A();
expect(result).toBeTrue();

Of course, the real code of B returns false.
My problem is that my test always fails. the function provided in the spy is never called by method A.
On the other hand, If I call B like this :
var result = Serviceinstance.B();

Then the function of the spy is called, and my test passes.
So should I modify my instance like this :
Serviceinstance.B = function(){return true;}

because Jasmine cannot mock a "second" level of the call stack ? (seems totally unlikely to me)
I am definitively missing something....

A: This is a code that works:
describe('Service test suite', function() {
    it('should return true', function() {
        var Serviceinstance = new Service();
        spyOn(Serviceinstance, 'B').and.callFake(function() {
            return true;
        });
        expect(Serviceinstance.A()).toBe(true);
    })
});

https://jsfiddle.net/ronapelbaum/9moLhhbr/


text:
Q: KVM Installation on Ubuntu 17.10 I have gone through this article.
But I am getting following error when adding user to group.
adduser: The group `libvirtd' does not exist.

This worked perfectly in 16.04.
Is there anything missing in Ubuntu 17.10?

A: I had the same problem following the guide you've mentioned above.
The problem is - that group is called libvirt and NOT libvirtd.
You should already be part of it (run groups to check), so just logout and login back.
To check if it's ok run virsh -c qemu:///system list WITHOUT sudo.
More info
The answer was found here:

According to this ubuntu help, the correct group name is libvirt.

A: In recent releases (>= Ubuntu Yakkety) the user group libvirtd was renamed to libvirt. An upgraded system gets a new libvirt group with the same gid as the libvirtd group to match that.
Do this Bash script to resolve it.
cat /etc/group | grep "libvirt"
sudo adduser root libvirt
sudo adduser ubuntu libvirt
sudo adduser root libvirtd       # legacy
sudo adduser ubuntu libvirtd     # legacy
cat /etc/group | grep "libvirt"
sudo systemctl restart libvirtd
sudo systemctl status libvirtd


text:
Q: Issues Upgrading Maria DB Galera 10.5.10 -> 10.5.15 I am running Debian Buster 10.12.  I have galera configured with 3 nodes.  I'm currently trying to process the following upgrade:
   libmariadb-dev (1:10.5.10+maria~buster => 1:10.5.15+maria~buster)
   libmariadb-dev-compat (1:10.5.10+maria~buster => 1:10.5.15+maria~buster)
   libmariadb3 (1:10.5.10+maria~buster => 1:10.5.15+maria~buster)
   mariadb-client (1:10.5.10+maria~buster => 1:10.5.15+maria~buster)
   mariadb-client-10.5 (1:10.5.10+maria~buster => 1:10.5.15+maria~buster)
   mariadb-client-core-10.5 (1:10.5.10+maria~buster => 1:10.5.15+maria~buster)
   mariadb-common (1:10.5.10+maria~buster => 1:10.5.15+maria~buster)
   mariadb-server (1:10.5.10+maria~buster => 1:10.5.15+maria~buster)
   mariadb-server-10.5 (1:10.5.10+maria~buster => 1:10.5.15+maria~buster)
   mariadb-server-core-10.5 (1:10.5.10+maria~buster => 1:10.5.15+maria~buster)
   mysql-common (1:10.5.10+maria~buster => 1:10.5.15+maria~buster)

After the update runs, I'm unable to get the node to start.  The error being: 2022-05-01 20:24:22 0 [ERROR] WSREP: /home/buildbot/buildbot/build/gcs/src/gcs_group.cpp:gcs_group_handle_join_msg():1170: Will never receive state. Need to abort.
Here is a snippet of the logs:
2022-05-01 20:24:22 0 [Note] WSREP: Shifting CLOSED -> OPEN (TO: 0)
2022-05-01 20:24:22 0 [Note] WSREP: Opened channel 'db-cluster-mariacluster'
2022-05-01 20:24:22 0 [Note] WSREP: New COMPONENT: primary = yes, bootstrap = no, my_idx = 1, memb_num = 3
2022-05-01 20:24:22 0 [Note] WSREP: STATE EXCHANGE: Waiting for state UUID.
2022-05-01 20:24:22 1 [Note] WSREP: Starting applier thread 1
2022-05-01 20:24:22 0 [Note] WSREP: STATE EXCHANGE: sent state msg: af98cb7e-c98c-11ec-8036-4bdaa86e34fe
2022-05-01 20:24:22 0 [Note] WSREP: STATE EXCHANGE: got state msg: af98cb7e-c98c-11ec-8036-4bdaa86e34fe from 0 (mariacluster-db2)
2022-05-01 20:24:22 0 [Note] WSREP: STATE EXCHANGE: got state msg: af98cb7e-c98c-11ec-8036-4bdaa86e34fe from 2 (mariacluster-db3)
2022-05-01 20:24:22 2 [Note] WSREP: Starting rollbacker thread 2
2022-05-01 20:24:22 0 [Note] WSREP: STATE EXCHANGE: got state msg: af98cb7e-c98c-11ec-8036-4bdaa86e34fe from 1 (mariacluster-db1)
2022-05-01 20:24:22 0 [Note] WSREP: Quorum results:
        version    = 6,
        component  = PRIMARY,
        conf_id    = 689,
        members    = 2/3 (joined/total),
        act_id     = 17942450,
        last_appl. = 17942346,
        protocols  = 2/10/4 (gcs/repl/appl),
        vote policy= 0,
        group UUID = b61a8e41-7939-11eb-a472-c255843a33c7
2022-05-01 20:24:22 0 [Note] WSREP: Flow-control interval: [28, 28]
2022-05-01 20:24:22 0 [Note] WSREP: Shifting OPEN -> PRIMARY (TO: 17942451)
2022-05-01 20:24:22 1 [Note] WSREP: ####### processing CC 17942451, local, ordered
2022-05-01 20:24:22 1 [Note] WSREP: Process first view: b61a8e41-7939-11eb-a472-c255843a33c7 my uuid: af4b3fad-c98c-11ec-a283-bf212d4e4d7b
2022-05-01 20:24:22 1 [Note] WSREP: Server mariacluster-db1 connected to cluster at position b61a8e41-7939-11eb-a472-c255843a33c7:17942451 with ID af4b3fad-c98c-11ec-a283-bf212d4e4d7b
2022-05-01 20:24:22 1 [Note] WSREP: Server status change disconnected -> connected
2022-05-01 20:24:22 1 [Note] WSREP: wsrep_notify_cmd is not defined, skipping notification.
2022-05-01 20:24:22 1 [Note] WSREP: ####### My UUID: af4b3fad-c98c-11ec-a283-bf212d4e4d7b
2022-05-01 20:24:22 1 [Note] WSREP: Cert index reset to 00000000-0000-0000-0000-000000000000:-1 (proto: 10), state transfer needed: yes
2022-05-01 20:24:22 0 [Note] WSREP: Service thread queue flushed.
2022-05-01 20:24:22 1 [Note] WSREP: ####### Assign initial position for certification: 00000000-0000-0000-0000-000000000000:-1, protocol version: -1
2022-05-01 20:24:22 1 [Note] WSREP: State transfer required:
        Group state: b61a8e41-7939-11eb-a472-c255843a33c7:17942451
        Local state: 00000000-0000-0000-0000-000000000000:-1
2022-05-01 20:24:22 1 [Note] WSREP: Server status change connected -> joiner
2022-05-01 20:24:22 1 [Note] WSREP: wsrep_notify_cmd is not defined, skipping notification.
2022-05-01 20:24:22 0 [Note] WSREP: Joiner monitor thread started to monitor
2022-05-01 20:24:22 0 [Note] WSREP: Running: 'wsrep_sst_rsync --role 'joiner' --address '192.168.216.139' --datadir '/var/lib/mysql/' --parent '17935' --mysqld-args --wsrep_start_position=b61a8e41-7939-11eb-a472-c255843a33c7:17942404'
WSREP_SST: [INFO] Using stunnel for SSL encryption: CA: '/etc/mysql/ssl/ca.crt', CAPATH='', ssl-mode='VERIFY_CA' (20220501 20:24:22.659)
2022.05.01 20:24:22 LOG4[ui]: Insecure file permissions on /etc/mysql/ssl/mariacluster.key
2022-05-01 20:24:22 1 [Note] WSREP: ####### IST uuid:00000000-0000-0000-0000-000000000000 f: 0, l: 17942451, STRv: 3
2022-05-01 20:24:22 1 [Note] WSREP: IST receiver addr using ssl://192.168.216.139:4568
2022-05-01 20:24:22 1 [Note] WSREP: IST receiver using ssl
2022-05-01 20:24:22 1 [Note] WSREP: Prepared IST receiver for 0-17942451, listening at: ssl://192.168.216.139:4568
2022-05-01 20:24:22 0 [Note] WSREP: Member 1.0 (mariacluster-db1) requested state transfer from '*any*'. Selected 0.0 (mariacluster-db2)(SYNCED) as donor.
2022-05-01 20:24:22 0 [Note] WSREP: Shifting PRIMARY -> JOINER (TO: 17942451)
2022-05-01 20:24:22 1 [Note] WSREP: Requesting state transfer: success, donor: 0
2022-05-01 20:24:22 1 [Note] WSREP: Resetting GCache seqno map due to different histories.
2022-05-01 20:24:22 1 [Note] WSREP: GCache history reset: b61a8e41-7939-11eb-a472-c255843a33c7:0 -> b61a8e41-7939-11eb-a472-c255843a33c7:17942451
2022-05-01 20:24:22 0 [Warning] WSREP: 0.0 (mariacluster-db2): State transfer to 1.0 (mariacluster-db1) failed: -125 (Operation canceled)
2022-05-01 20:24:22 0 [ERROR] WSREP: /home/buildbot/buildbot/build/gcs/src/gcs_group.cpp:gcs_group_handle_join_msg():1170: Will never receive state. Need to abort.
2022-05-01 20:24:22 0 [Note] WSREP: gcomm: terminating thread
2022-05-01 20:24:22 0 [Note] WSREP: gcomm: joining thread
2022-05-01 20:24:22 0 [Note] WSREP: gcomm: closing backend
2022-05-01 20:24:22 0 [Note] WSREP: view(view_id(NON_PRIM,aaca8b78-b91d,711) memb {
        af4b3fad-a283,0
} joined {
} left {
} partitioned {
        aaca8b78-b91d,0
        c4cb7478-ac36,0
})
2022-05-01 20:24:22 0 [Note] WSREP: PC protocol downgrade 1 -> 0
2022-05-01 20:24:22 0 [Note] WSREP: view((empty))
2022-05-01 20:24:22 0 [Note] WSREP: gcomm: closed
2022-05-01 20:24:22 0 [Note] WSREP: /usr/sbin/mariadbd: Terminated.
Terminated

Any ideas what I'm missing?  This is a fully functional cluster on the current version.  I ended up restoring a backup while I do some research before trying again.


text:
Q: RestEasy file upload with progress When posting a file to a resteasy service, something similar to this blog post http://www.mkyong.com/webservices/jax-rs/file-upload-example-in-resteasy/
What is the best way to track the progress of the bytes received by the server, as in a progress bar for the file upload?


text:
Q: Access php value from Jquery It's strange that I didn't find anything at Google but I hope you can help me. I have a Table with different accounts. When I click on one of those rows, another table for this specific account will slide in. This "specific table" for this account needs to show some account specified data and therefore I need to tell my ajax request for what account he needs those data. The problem: I don't know how I can tell this. I never used Ajax requests without a form.
My HTML Table (I need the var $orderid for my ajax request)
foreach($data as $row)
{
    $orderid =$row['id'];
    $username = $row['name'];
    $done = $row['refsDone'];
    $quantity = $row['quantity'];
    $running =$row['refsRunning'];
    $untouched = $quantity - ($done+$running);
    echo "

        $username
        0 %
        22 Aug 2014
        $done / $quantity
        $running
        $untouched

                Content of the additional info is here

";
}

My Jquery part which handles only the slide effect of the div and its trigger function:
$('.mySlideToggler').click(function( event ){
    event.preventDefault();
    event.stopPropagation();
    $(this).closest('tr').next().find('.slideMe').slideToggle();
});

So basically my question is: How can I access the php value $orderid from my Jquery function?

A: Put the order id in the html:
<tr class='header mySlideToggler' data-id="<?php echo $orderid; ?>">

And then:
$('.mySlideToggler').click(function( event ){
  event.preventDefault();
  event.stopPropagation();
  var id = $(this).data('id');
  $(this).next().find('.slideMe').slideToggle();
});

A: Store your id within some data-attribute that can be accessed by JS.

A: Create some hidden variable and assign value of $orderid to it.
then read same variable inside jQuery. And you are done :)

A: You can set the ordered attribute wherever you want in your HTML element, like this:
<?php
foreach($data as $row)
{
    $orderid =$row['id'];
    $username = $row['name'];
    $done = $row['refsDone'];
    $quantity = $row['quantity'];
    $running =$row['refsRunning'];
    $untouched = $quantity - ($done+$running);
 ?>
    <tr class='header mySlideToggler' orderedid='<?php echo $orderedid ?>'>
    <?php echo $username ?>
    0 %
    22 Aug 2014
    <?php echo $done / $quantity ?>
    <?php echo $running ?>
    <?php echo $untouched ?>

            Content of the additional info is here

<?php
}
?>

PHP will render the right id for you like a simple HTML attribute. After it, you can access the attribute of your element using jQuery selector inside your .click() function:
$(this).attr('orderedid');

As a good practice, do not "echo" your HTML. Instead of it, enclose plain HTML inside PHP tags. This will make your code more legible.