Q: How can I write output with javascript? I have created a jsfiddle with a code that is intended to replace a string inside a paragraph with a string stored in a button. As far as I can tell, it's right. But I can't get it to work. Can someone point out my mistake?

Product information

<button onclick="document.getElementByID('arbitraryIdentification').innerHTML = 'this text just replaced the original text'">text swaperizer</button>

http://jsfiddle.net/q8x9oupn/1/

A: You need to wrap id in quotes and getElementById (not ID)
http://jsfiddle.net/q8x9oupn/3/

A: Take a look at the function document.getElementById.

Returns a reference to the element by its ID; the ID is a string which
  can be used to identify the element

So, your correct code would be:
document.getElementById('unique-key-here')

Source

A: *

*'getElementByID' is supposed to be 'getElementById' ('Id' instead of 'ID')
<button onClick="document.getElementById('arbitraryIdentification').innerHTML = 'this text just replaced the original text'">
</button>


Q: Find all instances of "Replace" but not ".Replace" Due to the unfortunate choice of method naming, this is proving nearly impossible to find an answer to this using SO/Google searches...
TL;DR How can I find all instances of the function Replace( in my application, but not the extension method .Replace(?
Long version: I am converting a large VB.Net app to C#.  Within the 250,000 lines of code I know there are usages of the Visual Basic Replace function, in addition to the String.Replace method.
Is it possible to search for Replace, without including occurrences of .Replace?  I tagged RegEx as I was hoping that is the way, and had a play about at RegExr, but can't figure it out fully.
Thanks.

A:
How can I find all instances of the function Replace( in my application, but not the extension method .Replace(?

You need to use a regex with a negative lookbehind:
(?<!\.)Replace\(
^^^^^^^

The (?<!\.) lookbehind will invalidate all matches of Replace( that are immediately preceded with a ..
If you want to match Replace( that are only preceded with whitespace, use (?<!\S)Replace\(, the (?<!\S) will require either a whitespace or start of string before Replace(.
Since the ( and . are special regex metacharacters, they must be escaped with \.
See the regex demo.


Q: I got a error,when i start my computer i am getting this type of problem,when i open my computer(continue to wait or press s to skip mounting or m for manual recovery)
please help me regarding this

A: From observing your short question, I'm led to believe one of your UUID's are incorrect in /etc/fstab
What you could do as Step 1, is to type:
    sudo blkid

then for Step 2 type:
    sudo nano /etc/fstab

and compare the UUID's of all listed devices between the blkid output and your fstab file.
If any information does not match, edit fstab as root and correct the discrepancies.


Q: How to Insert an Image in a MongoDB database and display it on a webpage using PHP? I am writing some code to display Images on Web page. The next code show data in the web but not the Images. what can I change to show the Images in the web.
<?php

$m = new MongoClient();
$db = $m->selectDB("local");

// Get the users collection
//$c_faq = $db->faq;

// GridFS
$grid = $db->getGridFS();

// The file's location in the File System
$path = "C:\Wamp\Apache\htdocs\knowledge\scripts";

$filename = "\imagen1.png";

// Note metadata field & filename field
$storedfile = $grid->storeFile($path . $filename,
         array("metadata" => array("filename" => $filename),
         "filename" => $filename));

// Return newly stored file's Document ID
echo $storedfile;

// GridFS
$gridFS = $db->getGridFS();

// Find image to stream
$image = $gridFS->findOne("\imagen1.png");

// Stream image to browser
header('Content-type: imagen.png');
echo $image->getBytes();

?>


Q: How can I simplify 2 methods with only Parameter different? I have 2 methods with exactly same body. Only the second parameter (Class or TypeReference) is different. How can I make one method out of this or at least extract the body so it is not duplicated ?
Thanks.
public static <T> T mapResponseBody(ApiException e, Class<T> type) {
    T result = null;
    ObjectMapper objectMapper = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    try {
        result = objectMapper.readValue(e.getResponseBody(), type);
    } catch (IOException ioException) {
        log.error("Json Mapper Error",ioException);
    }
    return result;
}

 public static <T> T mapResponseBodyArray(ApiException e, TypeReference<T> type) {
    T result = null;
    ObjectMapper objectMapper = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    try {
        result = objectMapper.readValue(e.getResponseBody(), type);
    } catch (IOException ioException) {
        log.error("Json Mapper Error",ioException);
    }
    return result;
}

A: This might help you take a look at it. One method will have the functionality while the other methods will act as a helper to use. We cannot ignore the variable 'Class and TypeReference' because it is used in the objectMapper.
public static <T> T mapResponseBody(ApiException e, Class<T> typeClass , TypeReference<T> typeReference) {
    T result = null;
    ObjectMapper objectMapper = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    try {
        if(typeClass != null){
            result = objectMapper.readValue(e.getResponseBody(), typeClass);
        }else{
            result = objectMapper.readValue(e.getResponseBody(), typeReference);
        }
    } catch (IOException ioException) {
        System.out.println("Json Mapper Error : " + ioException);
    }
    return result;
}
public static <T> T mapResponseBody(ApiException e, Class<T> typeClass) {
    return mapResponseBody(e, typeClass, null);
}

public static <T> T mapResponseBody(ApiException e, TypeReference<T> typeReference) {
    return mapResponseBody(e, null, typeReference);
}

A: You can change your method with TypeReference where you will transform it in Class and call the other method.
public static <T> T mapResponseBody(ApiException e, Class<T> type) {
    T result = null;
    ObjectMapper objectMapper = new ObjectMapper()
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    try {
        result = objectMapper.readValue(e.getResponseBody(), type);
    } catch (IOException ioException) {
        log.error("Json Mapper Error",ioException);
    }
    return result;
}

public static <T> T mapResponseBodyArray(ApiException e, TypeReference<T> type) {

    Class<T> typeClass = (Class<T>) TypeFactory.defaultInstance().constructType(type).getRawClass();

    return mapResponseBody(e, typeClass);

}


Q: Post Variable to PHP script I am unable to post a string to a PHP script by sending it as xmlhttp data.
What I am really trying to do is reading that data which I am sending now as a hard-coded string, from another variable.
What I have now is the following code:
xmlhttp.open("POST", "test.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name=testname");

This post requests executes well and the PHP script receives the content of the name parameter ($stringData = $_POST["name"]);
I am trying to replace the 'testname' string with dynamic content from a variable. So
VARIABLE= "someContentNotHardCoded";
xmlhttp.send("name="+ VARIABLE);

but this doesn't seem to work. Is it possible what I am trying to do here, to append/replace the 'testname' string with dynamic content loaded from a variable?

A: This is possible, but with these alterations:
Variables should start with a $ sign and concatenation is done with the . sign:
$variable = "someContentNotHardCoded";
xmlhttp.send("name=".$variable);


Q: Displaying data from a SQLiteDatabase with adapter Code for the DBHelper class:
class DBHelper extends SQLiteOpenHelper {

    private static final String DATABASE_PATH = Environment.getDataDirectory()
            + "/data/test.data/databases/";
    private static final String DATABASE_NAME = "test.sqlite3";
    private static final int SCHEMA_VERSION = 1;
    public static final String TABLE_NAME = "terran_builds";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_OVERVIEW = "overview";

    public SQLiteDatabase dbSqlite;

    private final Context myContext;

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, SCHEMA_VERSION);
        this.myContext = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void createDatabase() {
        createDB();
    }

    private void createDB() {

        boolean dbExist = DBExists();
        if (!dbExist) {

            this.getReadableDatabase();

            copyDBFromResource();

        }

    }

    private boolean DBExists() {
        SQLiteDatabase db = null;

        try {
            String databasePath = DATABASE_PATH + DATABASE_NAME;
            db = SQLiteDatabase.openDatabase(databasePath, null,
                    SQLiteDatabase.OPEN_READWRITE);
            db.setLocale(Locale.getDefault());
            db.setLockingEnabled(true);
            db.setVersion(1);
        } catch (SQLiteException e) {
            Log.e("SqlHelper", "database not found");
        }

        if (db != null) {

            db.close();
        }

        return db != null ? true : false;
    }

    private void copyDBFromResource() {

        InputStream inputStream = null;
        OutputStream outStream = null;
        String dbFilePath = DATABASE_PATH + DATABASE_NAME;

        try {

            inputStream = myContext.getAssets().open(DATABASE_NAME);

            outStream = new FileOutputStream(dbFilePath);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = inputStream.read(buffer)) > 0) {
                outStream.write(buffer, 0, length);
            }
            outStream.flush();
            outStream.close();
            inputStream.close();
        } catch (IOException e) {

            throw new Error("Problem copying database from resource file.");
        }

    }

    public void openDataBase() throws SQLException {

        String myPath = DATABASE_PATH + DATABASE_NAME;
        dbSqlite = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READWRITE);
    }

    @Override
    public synchronized void close() {
        // TODO Auto-generated method stub

        if (dbSqlite != null) {
            dbSqlite.close();
        }
        super.close();
    }

    public Cursor getTerran() {

        SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

        queryBuilder.setTables(TABLE_NAME);

        String[] asColumnsToReturn = new String[] { COLUMN_ID, COLUMN_NAME,
                COLUMN_OVERVIEW };

        Cursor mCursor = queryBuilder.query(dbSqlite, asColumnsToReturn, null,
                null, null, null, "name");

        return mCursor;
    }

    public String getName(Cursor c) {
        return (c.getString(1));
    }
}

Code for the Terran activity:
public class Terran extends Activity {

    private DBHelper dbHelp = null;
    private Cursor ourCursor = null;
    private DBAdapter adapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        try {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.terran_layout);

            // this is our listview element, obtained by id from our xml layout
            ListView myListView = (ListView) findViewById(R.id.tvterran);

            // create our database helper
            dbHelp = new DBHelper(this);
            // we call the create right afther initializing helper
            dbHelp.createDatabase();
            // open the database
            dbHelp.openDataBase();
            // get our cursor
            ourCursor = dbHelp.getTerran();

            // tell android to start managing cursor
            startManagingCursor(ourCursor);
            // create our adapter
            adapter = new DBAdapter(ourCursor);
            // set the adapter
            myListView.setAdapter(adapter);

        } catch (Exception e) {

            // send real error message
            Log.e("ERROR", "ERROR IN CODE: " + e.toString());

            e.printStackTrace();
        }
    }

    class DBAdapter extends CursorAdapter {
        DBAdapter(Cursor c) {
            super(Terran.this, c);
        }

        @Override
        public void bindView(View row, Context ctxt, Cursor c) {
            // TODO Auto-generated method stub
            terranHolder holder = (terranHolder) row.getTag();
            holder.populateFrom(c, dbHelp);

        }

        @Override
        public View newView(Context ctxt, Cursor c, ViewGroup parent) {
            // TODO Auto-generated method stub
            LayoutInflater inflater = getLayoutInflater();
            View row = inflater.inflate(R.layout.terran_layout, parent, false);
            terranHolder holder = new terranHolder(row);
            row.setTag(holder);
            return (row);
        }
    }

    static class terranHolder {
        private TextView name = null;

        terranHolder(View row) {
            name = (TextView) row.findViewById(R.id.tvterran);
        }

        void populateFrom(Cursor c, DBHelper r) {
            name.setText(r.getName(c));
        }
    }

}

Logcat exception:
01-30 20:07:13.765: E/ERROR(7153): ERROR IN CODE: java.lang.NullPointerException
01-30 20:07:13.775: W/System.err(7153): java.lang.NullPointerException
01-30 20:07:13.775: W/System.err(7153):     at com.subdeveloper.starcraftbuilds.Terran.onCreate(Terran.java:46)
01-30 20:07:13.775: W/System.err(7153):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-30 20:07:13.775: W/System.err(7153):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
01-30 20:07:13.775: W/System.err(7153):     at android.app.ActivityThread.startActivityNow(ActivityThread.java:1499)
01-30 20:07:13.775: W/System.err(7153):     at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
01-30 20:07:13.775: W/System.err(7153):     at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
01-30 20:07:13.775: W/System.err(7153):     at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:731)
01-30 20:07:13.775: W/System.err(7153):     at android.widget.TabHost.setCurrentTab(TabHost.java:403)
01-30 20:07:13.775: W/System.err(7153):     at android.widget.TabHost.addTab(TabHost.java:242)

I can't get the ListView to generate from the query results. From my debugging I understand that the error is in the Terran class on line 46. I can't figure out what is wrong. Tested with other database, database connection works.

A: com.subdeveloper.starcraftbuilds.Terran.onCreate(Terran.java:46)
put a break point in and run the debugger. Something is null, and I'm guessing it's the list. It's on like 46.
Btw, I'm gold random player. Used to be high diamond Toss. Good luck with the project.

A: Your ListView is null that means that either don't have a ListView with that id in your layout or android didn't generate the proper id for the list and you have an old one that is incorrect.
Try to refresh the project, delete the R class from the folder gen so that the ID are generated again, restart the IDE.


Q: Prolog different variable, same value If you query e.g.
?- X = 10, Y = 10, Z = 10.

The output is
X = Y, Y = Z, Z = 10.

But my X is totally different from Y, they just happen to accidentally both be 10, so it doesn't seem clear/logical to display it that way.
Can i make it look like this instead?:
X = 10, Y = 10, Z = 10.

A: I share your preference. Note that different Prolog systems have different top levels...
SWI-Prolog gives me this:

$ swipl
?- X = 10, Y = 10, Z = 10.
X = Y, Y = Z, Z = 10.

Traella Prolog says something quite similar:

$ tpl
?- X = 10, Y = 10, Z = 10.
   X = 10, Y = X, Z = X.

GNU-Prolog and Scryer Prolog, however, give me answers that I like better:

$ gprolog
| ?- X = 10, Y = 10, Z = 10.

X = 10
Y = 10
Z = 10

yes

$ scryer-prolog
?- X = 10, Y = 10, Z = 10.
   X = 10, Y = 10, Z = 10.

A: change([H,Q,D,N,P]) :-member(H,[0,1,2]), /* Half-dollars /member(Q,[0,1,2,3,4]), / quarters /member(D,[0,1,2,3,4,5,6,7,8,9,10]) , / dimes /member(N,[0,1,2,3,4,5,6,7,8,9,10, / nickels /11,12,13,14,15,16,17,18,19,20]),S is 50H + 25Q +10D + 5*N,S =< 100,P is 100-S.


Q: Compiling ocaml can't find module in opam library, Js.ml in js_from_ocaml Trying to compile ocaml into javascript.
Some OCaml code I have put in https://gist.github.com/larsr/6b3cd6f62d54d56e3f9a uses the menhir parser, and the js_of_ocaml library together.   I've installed them with opam.
The code comes from http://toss.sourceforge.net/ocaml.html.
It is a lexer and a parser and a main program that calls them.
The goal is to generate a javascript program from the ocaml code and run it from within a web page.
I am able to compile the first Main program using only menhir with make from the Makefile in the repo, which does
ocamlbuild -use-menhir -menhir "menhir --external-tokens Lexer" Main.native

and I can compile a program that only uses js_of_ocaml, with make Formula.js, which does
ocamlfind ocamlc -package js_of_ocaml -package js_of_ocaml.syntax \
      -syntax camlp4o -linkpkg -o Formula.byte Formula.ml
js_of_ocaml Formula.byte

My problem is that now I'm unable to get ocamlfind to build JsClient.js, with
make JsClient.js

so I can't produce javascript code for 'JsClient.ml'.  The error I get is that the compiler can't find the module Js which is used by JsClient.  The code seems to be in the opam library in my home-dir, but I can't get the right arguments to ocamlfind to use it.
How do I compile the JsClient.ml into JsClient.js?

A: The rule that you use to compile the JsClient.ml file is not good.
JsClient.byte:
    ocamlbuild -use-menhir -menhir "menhir --external-tokens Lexer"

As you said, this file use the module Js so you need to compile with the same way than the file Formula.ml :
ocamlfind ocamlc -package js_of_ocaml -package js_of_ocaml.syntax \
      -syntax camlp4o -linkpkg -o JsClient.byte JsClient.ml
js_of_ocaml JSClient.byte


Q: Why are my classes not found even though my imports are correct? The Classes ADSTool and the Class PPM are not found by my compiler. I'm using Eclipse Helios. The docs say that I have to import java.lang.Object for both, and I imported java.lang*; I can't see why this isn't working.

A:
The docs say that I have to import java.lang.Object for both, and I imported java.lang*

Any documentation that tells you that you have to import classes in java.lang is blatantly wrong.  The classes in java.lang are implicitly imported.

In fact, I suspect that your problem is that you need to add the JAR files containing those two classes (ADSTool and PPM) to the build path of your Eclipse project.  If the classes are not available on the build path, the Eclipse compiler won't find them.

A: check Project->Properties->Java Build Path
did you include JRE System Library in Libraries Tab?

A: Import java.lang.*, not java.lang*. The second dot matters; without it, the compiler can get confused about what you're actually trying to import.


Q: How to access azure web app console or kudu console locally using putty or mac terminal? I have hosted a web app in azure and I am able to use console through kudu console or azure dashboard but for better development workflow, accessing it through mac terminal is essential.
I don't know how to access azure's web console (not azure server management console) through mac terminal.
Its not linux vm. Its default web app using windows.

A: No, it is not possible.
On Mac, if you want to access Kudu Console, you could use a browser open http://<yoursite>.scm.azurewebsites.net. But you could not do it on mac terminal.
On Mac terminal, you could call Kudu API to manage your web app, see this link.
On Mac terminal, you also could use Azure CLI 2.0 to manage your web app.

A: You're trying to do something web apps are not designed to do. You cannot rdp/ssh into a web app. That's what the kudu web console / powershell is for, if you need a command-line for something.
If you need to move specific app or data content to a web app, it's done through the version control provider you wire up to it (e.g. git), or ftp.


Q: Why doesn't OpenSSH work but paramiko does when using ansible playbook? I am running ansible-playbook with
ansible-playbook -u vagrant -i .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory playbook.yml -c ssh

This throws error fatal: [default]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: ", "unreachable": true}
However, it works fine after adding connection flag -c paramiko.
ansible-playbook -u vagrant -i .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory playbook.yml -c paramiko

Question: what could be the reasons the default connection (OpenSSH) does not work but paramiko does? How can I debug it and make OpenSSH works too?
I would like to understand the reasons. Please let me know if you need more information other than

*

*local: ubuntu 20.04

*remote: CentOS 7

*ansible [core 2.13.6]

When running with verbose mode
ansible-playbook -u vagrant -i .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory playbook.yml -c ssh -vvv

The output is
/usr/lib/python3/dist-packages/paramiko/transport.py:236: CryptographyDeprecationWarning: Blowfish has been deprecated
  "class": algorithms.Blowfish,
ansible-playbook [core 2.13.6]
  config file = /etc/ansible/ansible.cfg
  configured module search path = ['/home/john/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/john/.local/lib/python3.10/site-packages/ansible
  ansible collection location = /home/john/.ansible/collections:/usr/share/ansible/collections
  executable location = /usr/bin/ansible-playbook
  python version = 3.10.6 (main, Nov  2 2022, 18:53:38) [GCC 11.3.0]
  jinja version = 3.1.2
  libyaml = True
Using /etc/ansible/ansible.cfg as config file
host_list declined parsing /home/john/test/.vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory as it did not pass its verify_file() method
script declined parsing /home/john/test/.vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory as it did not pass its verify_file() method
auto declined parsing /home/john/test/.vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory as it did not pass its verify_file() method
Parsed /home/john/test/.vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory inventory source with ini plugin
Skipping callback 'default', as we already have a stdout callback.
Skipping callback 'minimal', as we already have a stdout callback.
Skipping callback 'oneline', as we already have a stdout callback.

PLAYBOOK: playbook.yml *************************************************************************************************
1 plays in playbook.yml

PLAY [all] *************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************
task path: /home/john/test/playbook.yml:2
<127.0.0.1> ESTABLISH SSH CONNECTION FOR USER: vagrant
<127.0.0.1> SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o Port=2222 -o 'IdentityFile="/home/john/test/.vagrant/machines/default/virtualbox/private_key"' -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o 'User="vagrant"' -o ConnectTimeout=10 -o 'ControlPath="/home/john/.ansible/cp/055b8f4af0"' 127.0.0.1 '/bin/sh -c '"'"'echo ~vagrant && sleep 0'"'"''
<127.0.0.1> (255, b'/home/vagrant\n', b'')
fatal: [default]: UNREACHABLE! => {
    "changed": false,
    "msg": "Failed to connect to the host via ssh: ",
    "unreachable": true
}

PLAY RECAP *************************************************************************************************************
default                    : ok=0    changed=0    unreachable=1    failed=0    skipped=0    rescued=0    ignored=0

A: The command that Ansible is running is returning 255 as the return code, for some reason:
<127.0.0.1> (255, b'/home/vagrant\n', b'')

OpenSSH uses this return code for connection errors but does not prevent remote processes from returning it, and Ansible can't tell the difference between a 255 that is a genuine connection error and whatever happened here.
Paramiko is a Python library and raises errors using native Python error handling, so it doesn't have the same issue.
The only way to get Ansible's OpenSSH plugin working is to figure out why '/bin/sh -c '"'"'echo ~vagrant && sleep 0'"'"' is returning 255 on your target host, and fix that issue.


Q: Return content of read-only  Here is the HTML:

<input type="text" maxlength="30" size="30"
class="ax-terminal-inputField ax_x20i" readonly="readonly" style="width: 240px;">

Here is some of my casper code:
var x = require('casper').selectXPath;
....//truncated for shortness//....
    casper.echo(x('//*[@id="ifldf14"]/input').value);

The result in undefined. I tried .value, .text, .innerHTML, but they all come up undefined when run. How do I get the content of the input field?

A: DOM context
CasperJS a sandboxed DOM context (page context). It is only there where you can access DOM elements directly. The page context is inside of the casper.evaluate() callback. Everything else about a DOM element is only a representation of it, because DOM nodes cannot be passed to the outside context.
Accessing input value
There are a lot of ways to get information out of the DOM, but DOM nodes cannot be printed to the console as-is. Here are two ways to get the input value.

*

*You can use casper.evaluate(). Since you want to use an XPath expression, you can use __utils__.getElementByXPath() helper function that is injected by CasperJS into the page:
var value = casper.evaluate(function(xpathexpr){
    return __utils__.getElementByXPath(xpathexpr).value;
}, '//*[@id="ifldf14"]/input');
casper.echo("value: " + value);

*If the input field is inside of a form and if the element has a name attribute, then you can use casper.getFormValues() and get the value using the name of the field.
casper.echo(casper.getFormValues('form').nameHere);

XPath helper utility
var x = require('casper').selectXPath;

Is only a little helper that transforms a string to an object with the properties type and path. It's only used in CasperJS internally to represent XPaths. The distinction is necessary, because CasperJS supports both CSS selectors and XPath expressions. Both of them are simple strings initially, but are executed differently.

A: The problem was I was not using jQuery to get my value out. Thanks for everyone's input!


Q: Tomcat: not appending trailing "/" when finding a directory I deployed a .war archive in Tomcat 7.0.22 (Java 1.6, MacOS Lion). The war is called "myapp.war" and so Tomcat is serving http://localhost/myapp (having expanded the war in /webapps/myapp). This is the usual behavious
When accessing a url that corresponds to a directory, it should append "/" . For having static files (.css, .js..) working correctly, this is needed, but while with the sample sites that ship with Tomcat this works (for example visiting http://127.0.0.1:8080/examples suddenly remaps to http://127.0.0.1:8080/examples/), on my site tomcat doesn't add any "/" making the search for static files broken. When manually calling localhost:8080/myapp/ (<-- I add the slash) everything works fine.
What should be going on? Mind that I haven't touched any Tomcat setting, I'm just experimenting with what comes out directly from Apache's zip file!
Thanks

A: Firstly you should explain more about your situation. As @mico has told here is a solution:
<filter>
    <filter-name>Jersey Filter</filter-name>
     <filter-class>com.sun.jersey.spi.container.servlet.ServletContainer</filter-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>your package name(s)</param-value>
        </init-param>
    <init-param>
            <param-name>com.sun.jersey.config.property.WebPageContentRegex</param-name>
            <param-value>.*\.jsp|.*\.css|.*\.png|.*\.js|.*\.gif|.*\.jpg</param-value>
        </init-param>
</filter>

<filter-mapping>
    <filter-name>Jersey Filter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
    <dispatcher>INCLUDE</dispatcher>
</filter-mapping>

 <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
</welcome-file-list>

The idea on solution based on:

defining Jersey ServletContainer as a filter instead of a servlet

Here you can read more: http://jersey.576304.n2.nabble.com/Tomcat-trailing-slashes-and-welcome-files-td4684494.html
Here says that: If you have a '/*' mapping, then Tomcat won't redirect
One more: you should see how tomcat logs your request and decide the main problem.


Q: Can a SQL Server have a CPU bottleneck when Processor Time is under 30% Is it in principle possible for the CPU to be the bottleneck on a SQL Server if the Performance Counter Processor:Processor Time is constantly under 30% on all cores? Or does low Processor Time automatically allow me to rule out the CPU as a potential trouble source?
I am asking this because SQL Nexus lists CPU as the top bottleneck on a server with low Processor Time values.

A: In cases where there are a lot of synchronous operations in a query the cpu can become the bottle neck even when the cpu is reporting to have cycles to spare.  There's only so much multi-threading that can happen.  As cpu core count continues to increase the more you'll likely see this scenario.  About the only thing you can do is get faster CPU cores or look into what sort of optimization can be done to the query/database.

A: If you have a high Processor Queue Length then you could theoretically have some CPU bottleneck.

A: The thing to look for are SQL wait times.  There are DMV's that can sow you what the system is waiting for.  Look at Brent Ozar's site for more details.
Things to look out for:  SQL server will (by default) use multi-threaded parallel processing for queries that it expects to take longer than 10 seconds or so.  Sometimes this is just not appropriate for the type of query being performed and you get very high CX_WAIT times - where the different threads need to talk and syncronise with each other.  You can get better throughput (more transactions per second, even though each transaction takes longer) by setting this value higher (on the server) or via a hint on the query. (See Google for more details!)
Does your queries have lots of complicated string manipulation?  Or CLR functions?
SQL is most likely to be DISK bound, then RAM speed bound before being pure CPU bound.


Q: How to use npm installed package in laravel application? I want to use select2 package in my laravel 5 application.
I installed it using npm install select2 and also ran npm run dev. It appears in my node_modules folder.
But how do I actually refer to the files - js and scss of select2 package in my app.blade.php ?

A: I suggest an answer to this thread because it isn't marked as resolved and despite the answer given it didn't allow me to resolve the issue as of the time of reading this.

Resources

*

*select2.org

*npm

I have since found a functional solution of which here are the details in relation to the question of the OP. Verified and working with Laravel 8

*

*Install package via npm
npm install select2

*Edit /resources/js/app.js to import javascript from package
require('./bootstrap');

/* ... */
require('select2');  // Add this
/* ... */

Alpine.start();

*Edit /resources/css/app.css to import styles from package
/* ... */
@import 'select2'; // Add this

*Edit /resources/js/bootstrap.js to enable the use of .select2();
window._ = require('lodash');
/* ... */
window.select2 = require('select2'); // Add this

*Run NPM
npm run dev
npm run watch

*NPM result in my case

Laravel Mix v6.0.39
✔ Compiled Successfully in 2982ms
√ Mix: Compiled successfully in 3.05s
webpack compiled successfully

Testing
According to configuration documentation
HTML
<input type="text" class="form-control js-example-basic-single">

JS
<script type="text/javascript">
  $(document).ready(function () {

    $('.js-example-basic-single').select2({
      placeholder: 'Select2 testing purpose'
    });

  });
</script>

Render

A: Run npm run watch , because keeps track of all changes in .js.
In app.js add
require('select2/dist/js/select2');

In app.blade.php example:
<div>
   <select class="js-select2 css-select2-50">
                    <option>1</option>
   </select>
</div>


Q: How to fix error with resource routes definition Here https://laravel.com/docs/5.7/controllers#resource-controllers I read that defining a resource
I had post/put methods :
POST    /photos store   photos.store
...
PUT/PATCH   /photos/{photo} update  photos.update

but defining in routes/web.php next resource routes:
Route::resource('site-subscriptions', 'Admin\SiteSubscriptionsController', [ 'except' => [] ] )->middleware('WorkTextString');

with form definition :
   <form method="POST" action="http://local-votes.com/admin/site-subscriptions/store" accept-charset="UTF-8" id="form_site_subscription_edit" enctype="multipart/form-data">
            <input type="hidden" name="_token" value="X7rzFjRq4o4TeA67FmkQTMI9ApjygM3ovE1C14i2">

I got error for POST :
  "message": "",
    "exception": "Symfony\\Component\\HttpKernel\\Exception\\MethodNotAllowedHttpException",
    "file": "/mnt/_work_sdb8/wwwroot/lar/votes/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php",
    "line": 255,

Have I error in my web.php definition error ?
Thanks!

A: if you are working with blade, getting a working link this way is bad, you should use laravel helpers like the following:
<form method="POST" action="{{route('site-subscriptions.store')}}" accept-charset="UTF-8" id="form_site_subscription_edit" enctype="multipart/form-data">

this way you are making sure that the links are correct even if you change your APP_URL in the deployment.
what actually done, is calling route helper function to get the URL for you by the route's name.
from the docs:

route():
The route function generates a URL for the given named route:
$url = route('routeName');
If the route accepts parameters, you may pass them as the second argument to the method:
$url = route('routeName', ['id' => 1]);
By default, the route function generates an absolute URL. If you wish to generate a relative URL, you may pass false as the third argument:
$url = route('routeName', ['id' => 1], false);


Q: How To Obtain Monthly Data from Quarterly Data Problem:
I have quarterly level data. I need to perform a month over month analysis. Is there a function, or a ggplot feature that will interpolate the quarterly data and fill in monthly data?
Reference Data:
dput(HPF[1:25, ])
structure(list(region = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), path = c(1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
), date = structure(c(16116, 16205, 16297, 16389, 16481, 16570,
16662, 16754, 16846, 16936, 17028, 17120, 17212, 17301, 17393,
17485, 17577, 17666, 17758, 17850, 17942, 18031, 18123, 18215,
18307), class = "Date"), index_value = c(1, 1.033852765, 1.041697122,
1.038876363, 1.041043093, 1.060900982, 1.073728928, 1.075879441,
1.080898915, 1.10368893, 1.119240863, 1.122827602, 1.128639801,
1.15275796, 1.169021733, 1.172707492, 1.178666441, 1.203634882,
1.220348482, 1.223890323, 1.229770019, 1.255791539, 1.273560554,
1.278236959, 1.285508086), index = c(0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
24), counter = 1:25, BaseQoQ = c(0, 0.033852765, 0.00758749917354051,
-0.00270784947028013, 0.00208564760655761, 0.0190749923163842,
0.0120915582298895, 0.00200284535874973, 0.00466546139717505,
0.0210843166587877, 0.0140908661646175, 0.00320461762840418,
0.00517639483536669, 0.0213692260175751, 0.0141085757499344,
0.00315285755256367, 0.00508136004984272, 0.0211836361259394,
0.0138859385432799, 0.00290231933930496, 0.00480410367620832,
0.021159663675294, 0.0141496533844698, 0.00367191413499146, 0.00568840303732765
), fdate = structure(c(16116, 16205, 16297, 16389, 16481, 16570,
16662, 16754, 16846, 16936, 17028, 17120, 17212, 17301, 17393,
17485, 17577, 17666, 17758, 17850, 17942, 18031, 18123, 18215,
18307), class = "Date"), StressC = c(0.99749, 1.031342765, 1.039187122,
1.036366363, 1.038533093, 1.058390982, 1.071218928, 1.073369441,
1.078388915, 1.10117893, 1.116730863, 1.120317602, 1.126129801,
1.15024796, 1.166511733, 1.170197492, 1.176156441, 1.201124882,
1.217838482, 1.221380323, 1.229770019, 1.255791539, 1.273560554,
1.278236959, 1.285508086), StressQoQ = c(0, 0.0339379492526242,
0.00760596502560418, -0.0027143898728953, 0.00209069888540969,
0.0191210941026796, 0.0121202336548254, 0.00200753827606026,
0.00467637125510434, 0.0211333913794913, 0.0141229845362187,
0.00321182042946733, 0.00518799221722843, 0.021416855302633,
0.0141393626118667, 0.00315964160130755, 0.00509225924746737,
0.021228843485116, 0.0139149560969629, 0.00290830110260876, 0.0068690282969297,
0.021159663675294, 0.0141496533844698, 0.00367191413499146, 0.00568840303732765
)), .Names = c("region", "path", "date", "index_value", "index",
"counter", "BaseQoQ", "fdate", "StressC", "StressQoQ"), row.names = c(NA,
-25L), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), vars = "region", drop = TRUE, indices = list(
    0:24), group_sizes = 25L, biggest_group_size = 25L, labels = structure(list(
    region = 1), row.names = c(NA, -1L), class = "data.frame", vars = "region", drop = TRUE, .Names = "region"))

Any insight would be much appreciated! I hope the data I have provided is enough to offer suggestions.
Goal:
I only need to plot/graph the monthly information, I do not need it reference in a data.frame.

A: So this is what you can do:
1) create a vector of dates to interpolate
months <- lapply(X = data$date, FUN = seq.Date, by = "month", length.out = 3)
months <- data.frame(date = do.call(what = c, months))

2) left join you date.frame to the months data.frame to create NAs for extrapolation
library(dplyr)
monthly_data <- left_join(x = months, y = data, by = "date")

3) use one of na.locf() na.appox() na.spline() to interpolate f.ex StressC
library(zoo)
monthly_data$StressC <- na.spline(object = monthly_data$StressC)

Note: the extrapolations above are

*

*na.locf() - most recent point

*na.appox() - linear

*na.spline() - spline (often used in graphics)

Run the following (before interpolation) to see the difference:
plot(x = monthly_data$StressC, ylab = "StressC", xlab="", xaxt = "n")
lines(x = na.locf(monthly_data$StressC), col = "red")
lines(x = na.approx(monthly_data$StressC), col = "green")
lines(x = na.spline(monthly_data$StressC), col = "blue")

Can also do something like this to get gglot:
ggplot(monthly_data, aes(x=date)) +
  geom_point(aes(y = StressC), colour="black") +
  geom_line(aes(y = na.locf(StressC)), col="red") +
  geom_line(aes(y = na.spline(StressC)), col="red")


Q: Json file to Room Db I am a newbie on Android Development.I have a json file formatted like this:
"users": [{
    "id": "1",
    "name": "Vanessa",
    "profilepic": "https://.."
  },...
]

I am creating room database but how can I record this user json file into it. I heard about gson but I could not find any solution for my problem

A: For this you need to first create a model that can parse this kind of json for you. you can use a pretty neat plugin that I have been sing called json to kotlin class.
Steps to install:

*

*Go to file->settings->plugins

*search for json to kotlin and install

*now just like you make a new file there will be a new option paste your json and give it a name and now it automatically generates a model for you.

*Also I will recommend you to watch some tutorials on youtube, my favorite content creator is Philip Lackener he has a very good tutorial on roomdb

I am also new to android development so i get it.
I recommend you to go through a beginner playlist it will really help you get the basics. you also need to see basics of roomdb because what you are asking is really basics of roomdb.


Q: Do gluons care about flavor? I think the answer to my question is no, but I can't find an explicit statement about this on my books or online.
I know that gluons are the vector bosons for QCD, the $SU(3)$ gauge theory of color, and they come in $3^2-1=8$ different types, and they have interactions with themselves and with quarks, which are the only particles that aren't in the singlet representation of the $SU(3)$ color group. My question is: if there was only one quark, say the up quark, would gluons care?  I wonder this because it's often said that the strong force "keeps quarks together inside nucleons" but from what I understand it doesn't necessarily mix the flavors and could easily create, say, a three-up-proton with charge $+2e$.
I read this question but it doesn't answer my doubt: I know that, since there are many flavors of quarks, the gluon can interact with all of them, my doubt is whether the gluons need so many different flavors to work, if I need to consider all of them to make a $SU(3)$ theory work.

A: Flavor is entirely orthogonal to color - the gluon(s) neither "know" nor "care" about flavor, but the existence of different quarks still leads to phenomena descending from the strong force that you wouldn't get without them:
What remains of the strong force on the scale between nucleons is often called the residual strong force and can be thought of as being mediated by pions. The pions, being bound states of up- and down-quarks, evidently would not exist in a world with only a single quark.
Another phenomenon related to the strong force is that confinement depends on the number of flavors, too, see e.g. this answer.
So while on the level of the QCD Lagrangian there is nothing that would indicate at first sight that the different quark species and gluons interact in interesting ways (and indeed a theory with only a single quark species and gluons would be consistent!), there are emergent phenomena that depend on both gluons and different flavors.


Q: NiFi ListenHTTP processor: Uses an unsupported protocol I have configured a ListenHTTP 1.7.0 processor in NiFi 1.7.0-RC1. It is listening on a custom port behind a reverse proxy. I have configured a StandardRestrictedSSLContextService with a JKS keystore and have added the keystore password. We have not configured the truststore as we don't expect to need mutual TLS. The certificate is signed by an internal enterprise CA and is (or should be!) trusted by the client.
When I test this with Chrome I receive the following:

This site can’t provide a secure connection
my.server uses an unsupported protocol.
ERR_SSL_VERSION_OR_CIPHER_MISMATCH
Unsupported protocol
The client and server don't support a common SSL protocol version or cipher suite.

Troubleshooting:

*

*We have tried both TLS and TLSv1.2 in the ListenHTTP processor.

*We have treid using curl (Linux) and Invoke-WebRequest (Windows) but have received variations on the bad cipher/SSL version message above.

*I don't see anything in the release notes suggesting that the ListenHTTP processor changed much since 1.7.0, so I'm assuming that I don't need to upgrade NiFi.

Can anyone suggest what to try next or explain why we see this error?

I have read the following:

*

*https://www.simonellistonball.com/technology/nifi-ssl-listenhttp/

*https://cwiki.apache.org/confluence/display/NIFI/Release+Notes

*Nifi: how to make ListenHTTP work with SSL

A: What version of Java are you running on? Java 11 provides TLSv1.3, which is the default offering if you have generic TLS selected, but NiFi 1.7.0 doesn't support TLSv1.3 (and doesn't run on Java 11). So assuming you are running on Java 8, recent updates have introduced TLSv1.3 but should still provide for TLSv1.2. This can also indicate that the certificate you have provided is invalid or incompatible with the cipher suite list provided by the client. You can use $ openssl s_client -connect <host:port> -debug -state -CAfile <path_to_your_CA_cert.pem> to try diagnosing the available cipher suites & protocol versions. Adding -tls1_2 or -tls1_3, etc. will restrict the connection attempt to the specified protocol version as well.
You should definitely upgrade from NiFi 1.7.0 -- it was released over 2 years ago, has known issues, and there have been close to 2000 bug fixes and features added since, including numerous security issues. NiFi 1.12.1 is the latest released version.


Q: how to clear facebook stream cache I am using facebook publish_stream method to post feed on facebook user timeline. The post is containing the image URL and title with some description. However the posted image could be change later but that change couldn't reflect on facebook side as they had cached the image.
So I wanted to be know how could clear the facebook cache on publish stream so they can show the latest image on user timeline.

A: Once a image has been published on Facebook, FB will always show the cached version. if, however, you want to update the image for a new post, try running the URL to the Debug Tool to update Facebook's cache. Any existing posts that use this image won't be updated.
It's to prevent people from changing content once it's already shared - otherwise it won't represent what the user originally shared. This would be something spammers could easily abuse.


Q: Find a formula for $0 · 1 · 2 + 1 · 2 · 3 + 2 · 3 · 4 + \dots +n(n + 1)(n + 2)$, for $n \in \mathbb N$ $$\sum\limits_{i=1}^n i(i + 1)(i + 2)$$
$$\sum\limits_{i=1}^n i^3 + 3i^2 + 2i$$
$$\sum\limits_{i=1}^n i^3 + 3\sum\limits_{i=1}^ni^2 + 2\sum\limits_{i=1}^ni$$
$$= (\frac14)n^4 + (\frac12)n^3 + (\frac14)n^2 + n^3 + 3(\frac{n^2}2) + (\frac{n}2) + n^2 + n$$
$$ =n^4 + 3n^3 + 8n^2 + 3n$$
Why does what I did above not work?

A: It is very much easier to note that $$n(n+1)(n+2)(n+3)-(n-1)n(n+1)(n+2)=4n(n+1)(n+2)$$ from which you get a telescoping series.
This is related to the binomial identity $\binom nr+\binom n{r+1}=\binom {n+1}{r+1}$ with $r=3$, and the pattern clearly generalises.

A: Required formulas:
$$\sum_{i=1}^n i^3=\left(\frac{n(n+1)}2\right)^2$$
$$\sum_{i=1}^n i^2=\frac{n(n+1)(2n+1)}{6}$$
$$\sum_{i=1}^n i=\frac{n(n+1)}2$$

I will start off at the third step.
$$\sum_{i=1}^n i^3+3\sum_{i=1}^n i^2+2\sum_{i=1}^n i$$
$$=\left(\frac{n(n+1)}{2}\right)^2+3\cdot \frac{n(n+1)(2n+1)}{6}+2\cdot \frac{n(n+1)}{2}$$
$$=\frac{n^2(n+1)^2}{4}+\frac{n(n+1)(2n+1)}{2}+n(n+1)$$
$$=\frac{n^2(n^2+2n+1)}{4}+\frac{2n(2n^2+3n+1)}{4}+\frac{4n^2+4n}{4}$$
$$=\frac{n^4+2n^3+n^2+4n^3+6n^2+2n+4n^2+4n}{4}$$
$$=\frac{n^4+6n^3+11n^2+6n}{4}$$
$$\color{green}{\sum_{i=1}^n i(i+1)(i+2)=\frac{n^4+6n^3+11n^2+6n}{4}}$$

A: In addition to these excellent answers, there is a general approach that words for all partial sums of the form:
$$S(n) = \sum_{k=1}^n f(k),$$
where $f$ is a degree $d$ polynomial.
We must have that $S(n) = g(n)$, where $g$ is a degree $d+1$ polynomial, with $d+2$ coefficients to determine.  Then we evaluate $S(n)$, for $n=1,\dots,d+2$, to get a linear system with $d+2$ equations and unknowns that can be solved for.
More strikingly, if you have a proposed solution to such a problem, a proof of its correctness requires merely that you check its correctness for $d+2$ different values of $n$!

A: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle\, #1 \,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\, #1 \,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\, #1 \,\right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil\, #1 \,\right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\, #1 \,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}
 \newcommand{\wt}[1]{\widetilde{#1}}$
$\ds{\sum_{k = 1}^{n}k\pars{k + 1}\pars{k + 2}:\ {\large ?}}$

\begin{align}&\color{#c00000}{%
\sum_{k = 1}^{n}k\pars{k + 1}\pars{k + 2}}
=\sum_{k = 1}^{n}{\pars{k + 2}! \over \pars{k - 1}!}
=3!\sum_{k = 1}^{n}{k + 2 \choose 3}
=6\sum_{k = 1}^{n}\oint_{\verts{z}=1}{\pars{1 + z}^{k + 2} \over z^{4}}
\,{\dd z \over 2\pi\ic}
\\[3mm]&=6\oint_{\verts{z}=1}{1 \over z^{4}}\sum_{k = 1}^{n}\pars{1 + z}^{k + 2}
\,{\dd z \over 2\pi\ic}
=6\oint_{\verts{z}=1}{1 \over z^{4}}\,
{\pars{1 + z}^{3}\bracks{\pars{1 + z}^{n} - 1} \over \pars{1 + z} - 1}
\,{\dd z \over 2\pi\ic}
\\[3mm]&=6\ \underbrace{\oint_{\verts{z}=1}{\pars{1 + z}^{n + 3} \over z^{5}}
\,{\dd z \over 2\pi\ic}}_{\ds{=\ {n + 3 \choose 4}}}\ -6\
\underbrace{\oint_{\verts{z}=1}{\pars{1 + z}^{3} \over z^{5}}
\,{\dd z \over 2\pi\ic}}_{\ds{=\ 0}}\ =\ 6{n + 3 \choose 4}
\\[3mm]&=6\,{\pars{n + 3}\pars{n + 2}\pars{n + 1}n \over 4\cdot 3\cdot 2\cdot 1}
\end{align}

$$\color{#00f}{\large%
\sum_{k = 1}^{n}k\pars{k + 1}\pars{k + 2}
={1 \over 4}\,\pars{n + 3}\pars{n + 2}\pars{n + 1}n}
$$

A: $$
0 \cdot 1 \cdot 2 + 1 \cdot 2 \cdot 3 + 2 \cdot 3 \cdot 4 + \cdots +n(n + 1)(n + 2)
=
3!\ \sum_{k=1}^{n+2} \binom{k}{3}
=
6 \binom{n+3}{4}
$$
The key sum is the sum of a column of Pascal's triangle, which is found by induction using Pascal's rule.


Q: custom dialog border is always white <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/yellow"
    android:orientation="vertical" >
     <LinearLayout
        android:id="@+id/progresscontent"
        android:layout_width="266dp"
        android:layout_height="52dp"
        android:layout_margin="8dp"
        android:background="@color/red"
        android:orientation="horizontal" >

        <ProgressBar
            android:id="@+id/progress"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="12dip"
            android:visibility="visible"
            android:padding="5dp"
            style="@android:style/Widget.ProgressBar.Inverse"/>

        <TextView
            android:id="@+id/progressmessage"
            style="@style/DialogText.Title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingBottom="10dip"
            android:paddingLeft="40dip"
            android:paddingTop="10dip"
            android:textColor="@color/codeFont"
            android:textSize="15dip" />

    </LinearLayout>

</LinearLayout>

I am trying create my own custom dialog but there is one problem here. Custom dialog border is always showing white color, what's the problem here. Any help please.

A: If you want the Dialog Border to appear in any colour you wish you have to use layout style and a theme. There is an excellent article about it here: http://blog.androgames.net/10/custom-android-dialog/


Q: C++ : Reading file and store data in multi-vector I am trying to read data file with the this format
T1: I1,I2,I5
T2: I2,I4
T3: I2,I3
T4: I1,I2,I4
T5: I1,I3
T6: I2,I3
T7: I1,I3
T8: I1,I2,I3,I5
T9: I1,I2,I3

I don't want to read the first column T1,T2,T3 ...... , but each line will be a dataset I want to start read after (space '  ' ) and end with each line and how can I separate the data according to (comma ',')
I wrote this code but it didn't work correctly and it reads the first column anyway
string CItem;

// set of elements
set< CItem > CItemSet;

//Transactions
 CItemSet CTransaction;

// set of transactions
vector< CTransaction > CTransactionSet;

ifstream inFile(inFileName);
    if (!inFile)
    {
        cout << "Failed to open input file filename:." << inFileName;
    }

CTransactionSet transSet;
    CTransaction tran;
    string txtLine;
    // read every line from the stream
    while (getline(inFile, txtLine))
    {

        istringstream txtStream(txtLine);
        string txtElement;
        // read every element from the line that is seperated by commas
        // and put it into the vector or strings

        while (getline(txtStream, txtElement, ','))
        {
            if (txtElement == ": ") break;
            else tran.insert(txtElement);
        }
        transSet.push_back(tran);
    }

A: Since you have
CTransaction tran;

outside the first while loop, items keep getting added to it. Move it inside the while loop.
CTransactionSet transSet;
string txtLine;
// read every line from the stream
while (getline(inFile, txtLine))
{
    CTransaction tran;

A: I solve the problem by doing what you said R Sahu but the most important solution is by using .ignore so we don't read the part before the ' '
CTransactionSet transSet;
    string txtLine;
    // read every line from the stream
    while (getline(inFile, txtLine))
    {
        istringstream txtStream(txtLine);
        txtStream.ignore(txtLine.length(), ' ');
        // read every element from the line that is seperated by commas
        // and put it into the vector or strings
        string txtElement;
        CTransaction tran;
        while (getline(txtStream, txtElement, ','))
        {
            tran.insert(txtElement);
        }
        transSet.push_back(tran);
    }


Q: Prove that $G$ is abelian if there exists $m\in \mathbb{N}$, so that $f(x)=x^m$, $f \in Aut(G)$ Let $G$ be a finite group with the following property: for any automorphism $f \in G$, there exists $m\in \mathbb{N}$ such that $f(x)=x^{m},\forall x\in G$.
Prove that $G$ is abelian.
Let $s,t \in G$, with $ord(s)|ord(t)$.
We know that $f:G\rightarrow G, f(x)=txt^{-1} \in Aut(G)$. Therefore $f(x)=x^m, m \in \mathbb{N}, m \geq 1.$
Then $t=t\cdot t\cdot t^{-1}=f(t)=t^m$, hence $t^{m-1}=1$, following that $ord(t)|m-1.$
Obviously, $ord(s)|m-1$, so $s^{m-1}=1$, which means $s=s^m=f(s)=tst^{-1}.$
Multiplying with $t$ on the right side, we obtain $st=ts$.
So I proved that $ts=st$, for any $s,t \in G$, with $ord(s)|ord(t)$.
But I got stuck here, because I don't know how to prove that any two elements of $G$ commute, regardless of their order.

A: Let $p$ be a prime dividing $|G|$.  Let $H_p$ be the set of all elements in $G$ whose order is a power of $p$.  This is a normal subgroup; clearly it is fixed by all automorphisms, so we need to check it's a subgroup.  If $x,y\in H_p$, then we can assume $|x|$ divides $|y|$ (remember, they each have order a power of $p$). By what you've proved, they commute, and so $|xy|$  divides $|y|$; this means $xy\in H_p$, so it's a subgroup.  Note we've also proved $H_p$ is abelian.
Do this for all primes dividing $|G|$.  Clearly, $H_p\cap H_q$ is trivial when $p\neq q$. Thus they all commute, and so $\prod H_p$ is a normal abelian subgroup of $G$. We'll be done if we can show this is all of $G$.
Let $g\in G$ such that $|g|=\prod_i p_i^{\alpha_i}$. We can induct on $i$ to show that $g$ is in $\prod H_p$. The case $i=1$ is obvious.
For the inductive case, write $|g|=p^\alpha r$, where $r$ is "the rest" of the factors. Since $p^\alpha$ and $r$ are coprime, we can write $mp^\alpha+nr=1$.  Then $g^{mp^\alpha}g^{nr}=g$, and $g^{nr}$ has order a power of $p$.  Thus $g^{nr}\in H_p$, and by the induction hypothesis, $g^{mp^\alpha}\in\prod H_p$. Thus
$$ g=g^{mp^\alpha}g^{nr}\in \prod H_p$$
EDIT:
I should mention that once you know $G$ is abelian, it is pretty easy to prove it must be cyclic.

A: I have made corrections in view ofthe mistake pointed out by Max and the observation of Derek Holt. Thanks Max and Derek!
Here is my modified argrument. Let $\vert G\vert=p_1^{n_1}p_2^{n_2}\ldots p_k^{n_k}$.  For each $g\in G$, there is a smallest $x\in\mathbb{N}$ such that $tgt^{-1}=g^x$ for all $g\in G$.  Let us denote this $x$ by $\psi(t)$.  Then, \begin{equation}g^{\psi(s)\psi(t)}=g^{\psi(st)}\forall g\in G.\ \ \ (*)
\end{equation}
From (*) we have $o(g)\mid (\psi(s)\psi(t)-\psi(st))$ for all $g\in G$ for any $s$, $t\in G$. Let
$m=lcm\{o(g)\vert g\in G\}$, i.e. the exponent of $G$. Then, it follows that $\psi(ts)\equiv \psi(t)\psi(s)\pmod{m}$. If $o(t)=k$, $1=\psi(t^k)\equiv \left(\psi(t)\right)^k\pmod{m}$, so $\psi(t)$ is coprime to $m$. Consider the map $\lambda\colon g\to\left(\frac{\mathbb{Z}}{m\mathbb{Z}}\right)^*$ given by $t\mapsto \{\psi(t)\}$, where $\{\psi(t)\}$ is the residue class of $\psi(t)\bmod{m}$.  So, $\lambda(G)\subset \left(\frac{\mathbb{Z}}{m\mathbb{Z}}\right)^*$.  From ( * ) we actually have group homomorphism $\lambda \colon G\to \left(\frac{\mathbb{Z}}{m\mathbb{Z}}\right)^*$.The kernel of $\lambda$  is $Z(G)$.
Again,  $G$ is the direct product of its $p$-Sylow subgroups since the $p$-Sylow subgroups are normal as pointed out by Derek Holt.  Let $H_p$ be the $p$-Sylow subgroup of $G$. For any $t\in H_p$, there is an inner automorphism $t\mapsto tgt^{-1}$, so, we still have the map $\lambda$ for this case. The image of $\lambda$ restricted to $H_p$ is in $\left(\frac{\mathbb{Z}}{p^r\mathbb{Z}}\right)^*$ for some $r$. The kernel of the map is $Z\left (H_p\right)$ and $H_p/Z\left(H_p\right)$ is isomorphic to a subgroup of $\left(\frac{\mathbb{Z}}{p^r\mathbb{Z}}\right)^*$. So, if $p$ is odd, $H_p/Z \left (H_p\right)$ is cyclic. It follows that $H_p$ is abelian.  The argument doesn't work for $2$.


Q: Existence of sections of sphere bundles. I am reading this article, could you please tell me where I can find the proof of Theorem 2.1.1?

Theorem 2.1.1. Let $\pi: S \rightarrow M$ be a $(d-1)$-sphere bundle over a closed manifold $M$ of dimension $d$. Suppose that the structure group of $S$ can
be reduced to the orthogonal group $\mathrm{O}(d, \mathbb{R})$, then there exists a smooth map $s: M \rightarrow S$ such that $s \in \Gamma(M \backslash I, S)$, where $I$ is discrete.

Thanks!

A: Here is the correct statement:
Theorem. Suppose that $M$ is a smooth closed $n$-manifold, $\xi=(\pi:S\to M)$ is a smooth fiber bundle with fibers $S^{n-1}$, whose structure group is reduced to the orthogonal group $O(n)$. Then there is a finite subset $I\subset M$ and a smooth section $s$ of this bundle over $M\setminus I$.
Proof. By the assumption, the bundle $\xi$ is associated with a principal $O(n)$-bundle over $M$, hence, there is a rank $n$ real vector bundle $\eta=(E\to M)$ equipped with a (fiberwise) metric, such that $\xi$ is the unit sphere bundle of $\eta$.
Now, we can start the actual proof. First, take the zero section $\sigma_0$ of $\eta$. Then perturb it to a smooth section $\sigma$ of the same bundle $\eta$ which is transversal to the zero section. (Such perturbation arguments you can find in any good differential topology textbook, say, in Guillemin and Pollack. Incidentally, it is a good exercise to see that if $\sigma$ is a smooth map $M\to E$ sufficiently close to a section in $C^{1}$ topology, then $\sigma$ itself is the precomposition of a section with a diffeomorphism $M\to M$ close to $id_M$.) By transversality and since $E$ has dimension $2n$, it follows that the set of zeroes of $\sigma$ is a 0-dimensional submanifold $I$ in $M$. By compactness of $M$, $I$ has to be finite. Now, on $M\setminus I$, replace $\sigma$ with
$$
s=\sigma/|\sigma|,
$$
where the norm is the fiberwise norm on $\eta$. Thus, $s$ is the required section of $\xi$. qed.
The argument I gave is very standard, it is used for instance to define index of a vector field, in the case when $\eta$ is the tangent bundle of $M$.


Q: System has not been booted with systemd ERROR when updating Postgresql in Ubuntu I've been following this link to update Postgresql on my Ubuntu-18.04 (VM running on Windows 10)
https://computingforgeeks.com/install-postgresql-12-on-ubuntu/
However, Im getting the below error, so I cannot proceed.
.../desktop/my_app$ systemctl status postgresql.service
System has not been booted with systemd as init system (PID 1). Can't operate.

What can I do?

A: service postgresql status
or
systemctl status postgresql
Must work.


Q: Круговой импорт Python: как справиться с ним? Существует приложение, использующее PyQt5, которое состоит из главного скрипта AsQamm.py и собственной библиотеки _asQamm, в которой находятся все функции, необходимые для его работы.
Функции находятся в классах, унаследованных от класса MainWindow, внутри соответствующих модулей. Соответственно, каждый модуль для своей работы нуждается в импорте класса MainWindow, который находится в AsQamm.py.
В то же время, в конструкторе класса MainWindow есть методы, для вызова которых необходимы модули из _asQamm. В итоге - получается порочный круг кругового импорта, при попытке с ним справиться вылетают самые разные ошибки.

Дисклеймер
Я знаю, что по-хорошему, нужно делать МВП, однако я не понимаю, как мне изложить суть проблемы, не рассказав всю суть.

Структура приложения
Текущая структура приложения и комментарий представлена ниже. Вы также можете спустится ниже к списку ссылок на файлы и смотреть их код через pastebin:

_asQamm     #Библиотека со всеми модулями, которые необходимы для осуществления функций приложения.
    |________
    |__init__.py        #На данный момент здесь отсутствуют какие-либо команды. Я пробовал перенести сюда
    |  (пустой)         #команды импорта из AsQamm.py, но это породило другую проблему — классы из
    |                   #модулей, находящихся в библиотеке (см. далее), не могли
    |                   #инициализироваться, так как имя MainWindow при
    |                   #'определении классов не определяется (ImportError:
    |                   # name ‘MainWindow’ is not defined').
    |________
    |asQammUI.py        #Второй по важности модуль приложения. Его код является результатом работы
    |  (ссылка ниже)    #pyuic5, здесь находится интерфейс. От класса Ui_MainWindow здесь наследуется
    |                   #главный класс приложения MainWindow.
    |________
    |asQammFunctions.py #Внутри находится класс UIFunctions, предназначенный для осуществления действий с
    |  (ссылка ниже)    #интерфейсом приложения без создания экземпляра, по этой причине класс не имеет
    |                   #конструктора. Все методы этого класса работают напрямую с родительским классом
    |                   #MainWindow. Фактически, в модуле functions я планировал размещать классы с
    |                   #методами, для осуществления которых создавать экземпляр класса не нужно.
    |________
    |asQammResources.py #RCC, и так понятно, зачем он нужен. Не содержит никакого дополнительно
    |  (ссылка ниже)    #написанного мной кода, подгружается в начале AsQamm.py. Прикрепил в неконверт.
    |                   #виде, конвертируйте командой
    |                   # `pyrcc5 resources.qrc -o _asQamm\asQammResources.py`.
    |________
    |asQammUsers.py     #Модуль, после тщетной попытки создания класса в котором возникла проблема.
    |  (ссылка ниже)    #Планировался как код модуля пользователей программы, в котором должен был быть
    |                   #центральный класс AQUserSystem (род. MainWindow) (с экземпляром в основном коде)
    |                   #и другие классы, наследуемые от него.
    |                   #Однако я обнаружил, что я не могу создать экземпляр этого класса (ошибка
    |                   #ImportError: name 'MainWindow is not defined' при инициализации модуля
    |                   #asQammUsers). Если я изменю в коде последнего `import AsQamm` на `from AsQamm
    |                   #import MainWindow`, интерпретатор скажет, что круговой импорт.
    |                   # ~~Да, я в ООП у Python что-то всегда не понимал. Надо ещё подучить это~~
    |
AsQamm.py     # Ядро приложения. Конструктор класса MainWindow создаёт экземпляр класса Ui_MainWindow,
(ссылка ниже) # затем должен был создавать экземпляр AQUserSystem, затем - выполнять несколько методов
              # по первоначальной настройке интерфейса (привязка кнопок и инициализатор анимации меню
              # (UIFunctions.toggleSimpleWidgetInteraction и UIFunctions.createLabels)).

Ссылки на файлы
_asQamm\asQammUI.py - тык. Осторожно! 1249 строк!
_asQamm\asQammFunctions.py - тык
_asQamm\asQammUsers.py     - тык
AsQamm.py                  - тык
resources.qrc - тык
Также для запуска приложения потребуeтся папка images: скачать архив. разархивируйте в корень программы.

Стактрейсы
В текущем состоянии
  File "G:\Work\Code\Hyrex AsQamm\AsQamm.py", line 9, in <module>
    import _asQamm.asQammUsers as aqUsers
  File "G:\Work\Code\Hyrex AsQamm\_asQamm\asQammUsers.py", line 1, in <module>
    import AsQamm
  File "G:\Work\Code\Hyrex AsQamm\AsQamm.py", line 10, in <module>
    import _asQamm.asQammFunctions as aqFunctions
  File "G:\Work\Code\Hyrex AsQamm\_asQamm\asQammFunctions.py", line 5, in <module>
    class UIFunctions(MainWindow):
NameError: name 'MainWindow' is not defined.

Если строку 1 в модуле asQammUsers заменить на from AsQamm import MainWindow
  File "G:\Work\Code\Hyrex AsQamm\AsQamm.py", line 9, in <module>
    from _asQamm.asQammUsers import *
  File "G:\Work\Code\Hyrex AsQamm\_asQamm\asQammUsers.py", line 1, in <module>
    import AsQamm
  File "G:\Work\Code\Hyrex AsQamm\AsQamm.py", line 10, in <module>
    from _asQamm.asQammFunctions import *
  File "G:\Work\Code\Hyrex AsQamm\_asQamm\asQammFunctions.py", line 1, in <module>
    from AsQamm import MainWindow
ImportError: cannot import name 'MainWindow' from partially initialized module 'AsQamm' (most likely due to a circular import) (G:\Work\Code\Hyrex AsQamm\AsQamm.py)

A: Я отметил строки которые поменял
AsQamm.py
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.Qt import *

from _asQamm.asQammUI import *

#from _asQamm.asQammResources import *
# добавил в asQammUI.py  -> import resources_rc                           # !!!

import _asQamm.asQammUsers as aqUsers

#import _asQamm.asQammFunctions as aqFunctions
from _asQamm.asQammFunctions import  UIFunctions                          # !!!

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
###
        self.uiFunctions = UIFunctions(self)                               # +++

#        aqFunctions.UIFunctions.createLabelsAtMainMenu(self)
        self.uiFunctions.createLabelsAtMainMenu()            # ? - self

        # Добавляем привязки клавиш к анимациям    vvvvvvvvvvvvvvvv
        self.ui.btn_Toggle.clicked.connect(lambda: self.uiFunctions.toggleSimpleWidgetInteraction(190, 1))            # - self,
        #                                                     vvvvvvvvvvvvvvvv
        self.ui.btn_DefnToggleCamList.toggled.connect(lambda: self.uiFunctions.toggleSimpleWidgetInteraction(320, 2)) # - self,

# Cкин Дом  selectSkin () отсутствует 1 обязательный позиционный аргумент: 'self
#        self.ui.btn_page1.clicked.connect( lambda: aqFunctions.UIFunctions.selectSkin(1) )
        self.ui.btn_page1.clicked.connect( lambda: self.uiFunctions.selectSkin(1) )

        # Скин Защита
#        self.ui.btn_page2.clicked.connect( lambda: aqFunctions.UIFunctions.selectSkin(2) )
        self.ui.btn_page2.clicked.connect( lambda: self.uiFunctions.selectSkin(2) )

        # Скин Растения
#        self.ui.btn_page3.clicked.connect( lambda: aqFunctions.UIFunctions.selectSkin(3) )
        self.ui.btn_page3.clicked.connect( lambda: self.uiFunctions.selectSkin(3) )

        # Скин Управление                          vvvvvvvvvvvvvvvv
        self.ui.btn_page4.clicked.connect( lambda: self.uiFunctions.selectSkin(4) )       #  !

        # Скин Конфигурации                        vvvvvvvvvvvvvvvv
        self.ui.btn_page5.clicked.connect( lambda: self.uiFunctions.selectSkin(5) )       #  !

if __name__ == "__main__":
    app = QApplication(sys.argv)
    root = MainWindow()
    root.show()
    sys.exit(app.exec_())

asQammFunctions.py
from PyQt5 import QtCore, QtGui, QtWidgets                  # +++
from PyQt5.Qt import *                                      # +++  QPropertyAnimation

#from AsQamm import MainWindow                              # ---
import AsQamm                                               # +++

import json

#class UIFunctions(MainWindow):
class UIFunctions(QtWidgets.QMainWindow):
    def __init__(self, parent=None):                                                   # +++
        super(UIFunctions, self).__init__(parent)                                      # +++
        self.parent = parent                                                           # +++

    def createLabelsAtMainMenu(self):
#       self.parent.ui. !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        self.parent.ui.hintsSizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
        self.parent.ui.styleSheet = str('''QLabel { font: 12pt "Segoe UI Semibold"; color: white; }
        QLabel:hover { color: rgb(47, 105, 23); }''')

#       self.parent.ui.
        self.parent.ui.lbl_MenuHint1 = QtWidgets.QLabel(parent = self.parent.ui.frame_top_menus)
        self.parent.ui.lbl_MenuHint1.setText('Наш дом')
        self.parent.ui.lbl_MenuHint1.setStyleSheet(self.parent.ui.styleSheet)
        self.parent.ui.lbl_MenuHint1.setSizePolicy(self.parent.ui.hintsSizePolicy)

        self.parent.ui.cel_TopMenuBtn1.addWidget(self.parent.ui.lbl_MenuHint1)
        self.parent.ui.lbl_MenuHint1.hide()

        self.parent.ui.lbl_MenuHint2 = QtWidgets.QLabel(parent = self.parent.ui.frame_top_menus)
        self.parent.ui.lbl_MenuHint2.setText('Защита')
        self.parent.ui.lbl_MenuHint2.setStyleSheet(self.parent.ui.styleSheet)
        self.parent.ui.lbl_MenuHint2.setSizePolicy(self.parent.ui.hintsSizePolicy)

        self.parent.ui.cel_TopMenuBtn2.addWidget(self.parent.ui.lbl_MenuHint2)
        self.parent.ui.lbl_MenuHint2.hide()

        self.parent.ui.lbl_MenuHint3 = QtWidgets.QLabel(parent = self.parent.ui.frame_top_menus)
        self.parent.ui.lbl_MenuHint3.setText('Растения')
        self.parent.ui.lbl_MenuHint3.setStyleSheet(self.parent.ui.styleSheet)
        self.parent.ui.lbl_MenuHint3.setSizePolicy(self.parent.ui.hintsSizePolicy)

        self.parent.ui.cel_TopMenuBtn3.addWidget(self.parent.ui.lbl_MenuHint3)
        self.parent.ui.lbl_MenuHint3.hide()

        self.parent.ui.lbl_MenuHint4 = QtWidgets.QLabel(parent = self.parent.ui.frame_top_menus)
        self.parent.ui.lbl_MenuHint4.setText('Оборудование')
        self.parent.ui.lbl_MenuHint4.setStyleSheet(self.parent.ui.styleSheet)
        self.parent.ui.lbl_MenuHint4.setSizePolicy(self.parent.ui.hintsSizePolicy)

        self.parent.ui.cel_TopMenuBtn4.addWidget(self.parent.ui.lbl_MenuHint4)
        self.parent.ui.lbl_MenuHint4.hide()

        self.parent.ui.lbl_MenuHint5 = QtWidgets.QLabel(parent = self.parent.ui.frame_top_menus)
        self.parent.ui.lbl_MenuHint5.setText('Конфигурация')
        self.parent.ui.lbl_MenuHint5.setStyleSheet(self.parent.ui.styleSheet)
        self.parent.ui.lbl_MenuHint5.setSizePolicy(self.parent.ui.hintsSizePolicy)

        self.parent.ui.cel_TopMenuBtn5.addWidget(self.parent.ui.lbl_MenuHint5)
        self.parent.ui.lbl_MenuHint5.hide()

    # Функция toggleSimpleWidgetInteraction может быть использована для анимирования виджетов простой
    # линейной анимацией. Ей необходимо иметь следующие аргументы: желаемый максимальный размер
    # виджета (ширина/высота в зависимости от типа анимации) и ID виджета, с которым она будет
    # работать.

    def toggleSimpleWidgetInteraction(self, maxLength, widgetId):

        maxExtend = int()

        if widgetId == 1: # проверяем аргумент на 1 вариант

            # получаем ширину фрейма
            width = self.parent.ui.frame_left_menu.width()
            maxExtend = maxLength
            standard = 60

            # установим максимальное значение ширины фрейма
            if width == 60:
                lengthExtended = maxExtend
                self.parent.ui.lbl_MenuHint1.show()
                self.parent.ui.lbl_MenuHint2.show()
                self.parent.ui.lbl_MenuHint3.show()
                self.parent.ui.lbl_MenuHint4.show()
                self.parent.ui.lbl_MenuHint5.show()

            else:
                lengthExtended = standard
                self.parent.ui.lbl_MenuHint1.hide()
                self.parent.ui.lbl_MenuHint2.hide()
                self.parent.ui.lbl_MenuHint3.hide()
                self.parent.ui.lbl_MenuHint4.hide()
                self.parent.ui.lbl_MenuHint5.hide()

            # выполним горизонтальную анимацию

            self.animation = QPropertyAnimation(self.parent.ui.frame_left_menu, b"minimumWidth")
            self.animation.setDuration(200)
            self.animation.setStartValue(width)
            self.animation.setEndValue(lengthExtended)
            self.animation.setEasingCurve(QtCore.QEasingCurve.InOutQuart)
            self.animation.start()

            self.animation2 = QPropertyAnimation(self.parent.ui.frame_top_menus, b"minimumWidth")
            self.animation2.setDuration(200)
            self.animation2.setStartValue(width)
            self.animation2.setEndValue(lengthExtended)
            self.animation2.setEasingCurve(QtCore.QEasingCurve.InOutQuart)
            self.animation2.start()

        elif widgetId == 2: # проверяем второй вариант

            height = self.parent.ui.tbw_DefnCamList.height()
            maxExtend == maxLength
            standard = 43

            # установим максимальное значение высоты фрейма и скроем/отобразим мешающие
            # элементы
            if height == 43:

                self.parent.ui.lbl_DefnCurrSetCamId.hide()
                self.parent.ui.lbl_ReadOnly10.hide()
                self.parent.ui.gvf_DefnCamView.hide()

            else:

                self.parent.ui.lbl_DefnCurrSetCamId.show()
                self.parent.ui.lbl_ReadOnly10.show()
                self.parent.ui.gvf_DefnCamView.show()

#    def selectSkin(id, self):
    def selectSkin(self, id):                    ###################################
        print(f'def selectSkin(self, id): {id}')
        if id == 1:

            self.parent.ui.stack.setCurrentWidget(self.parent.ui.page_1)
            self.parent.ui.lbl_SkinName.setText('Наш дом')

        elif id == 2:

            self.parent.ui.stack.setCurrentWidget(self.parent.ui.page_2)
            self.parent.ui.lbl_SkinName.setText('Защита')

        elif id == 3:

            self.parent.ui.stack.setCurrentWidget(self.parent.ui.page_3)
            self.parent.ui.lbl_SkinName.setText('Растения')

        elif id == 4:

            self.parent.ui.stack.setCurrentWidget(self.parent.ui.page_4)
            self.parent.ui.lbl_SkinName.setText('Управление')

        elif id == 5:

            self.parent.ui.stack.setCurrentWidget(self.parent.ui.page_5)
            self.parent.ui.lbl_SkinName.setText('Конфигурация')

asQammUI.py
from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):

    ...

# +++
import resources_rc    # +++

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

A: *

*Перестройте компонент AsQamm.py. Сейчас все методы, которые осуществляются с MainWindow, вызываются в конструкторе этого класса. Для выполнения этих методов необходимы модули, отсылающие при инициализации обратно к классу MainWindow. таким, образом, образовалась парадоксальная ситуация: для того, чтобы инициализировать класс MainWindow, необходима функциональность из внешних модулей, однако для инициализации этих модулей необходимо инициализировать родительский класс.

*Наследование класса UIFunctions действительно не имеет смысла. Переопределите атрибуты методов с self на root.
Решение:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

from _asQamm.asQammUI import *
from _asQamm.asQammResources import *

class MainWindow(QMainWindow):

    def __init__(self):

        QMainWindow.__init__(self)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

from _asQamm.asQammUsers import *
from _asQamm.asQammFunctions import *

if __name__ == "__main__":
    app = QApplication(sys.argv)
    root = MainWindow()

    UIFunctions.createLabelsAtMainMenu(root)

    # Добавляем привязки клавиш к анимациям
    root.ui.btn_Toggle.clicked.connect(lambda: UIFunctions.toggleSimpleWidgetInteraction(root, 190, 1))
    root.ui.btn_DefnToggleCamList.toggled.connect(lambda: UIFunctions.toggleSimpleWidgetInteraction(root, 320, 2))

    # Cкин Дом
    root.ui.btn_page1.clicked.connect( lambda: UIFunctions.selectSkin(1) )

    # Скин Защита
    root.ui.btn_page2.clicked.connect( lambda: UIFunctions.selectSkin(2) )

    # Скин Растения
    root.ui.btn_page3.clicked.connect( lambda: UIFunctions.selectSkin(3) )

    # Скин Управление
    root.ui.btn_page4.clicked.connect( lambda: UIFunctions.selectSkin(4) )

    # Скин Конфигурации
    root.ui.btn_page5.clicked.connect( lambda: UIFunctions.selectSkin(5) )

    root.show()
    sys.exit(app.exec_())


Q: broken pipe when installing NodeJS 16 on Ubuntu 22.04 Trying to install NodeJS 16 on ubuntu 22.04.
Ran the official installation instructions:
sudo apt-get install -y nodejs
Got the following error:
The following NEW packages will be installed:
  nodejs
0 upgraded, 1 newly installed, 0 to remove and 4 not upgraded.
Need to get 0 B/27.1 MB of archives.
After this operation, 128 MB of additional disk space will be used.
Selecting previously unselected package nodejs.
(Reading database ... 218989 files and directories currently installed.)
Preparing to unpack .../nodejs_16.17.0-deb-1nodesource1_amd64.deb ...
Unpacking nodejs (16.17.0-deb-1nodesource1) ...
dpkg: error processing archive /var/cache/apt/archives/nodejs_16.17.0-deb-1nodesource1_amd64.deb (--unpack):
 trying to overwrite '/usr/include/node/common.gypi', which is also in package libnode-dev 12.22.9~dfsg-1ubuntu3
dpkg-deb: error: paste subprocess was killed by signal (Broken pipe)
Errors were encountered while processing:
 /var/cache/apt/archives/nodejs_16.17.0-deb-1nodesource1_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

A: Various versions of Node.js are using a same file (one from apt install, one from manually download), which caused the conflict, resulting the error.
Remove your Node.js 12.22.9 first.


Q: Java modulus operator and PreIncrement - SCJA Im revising for my SCJA exam at the minute and im confused by this question and answer. The question is what is the result of running and compiling the code.
    public class Test{
       public static void main(String args[]){
         int counter = 0;
         for(int i=0; i< 4; ++i){
            for(int k=0; k< 4; ++k){
               system.out.println("Hello - "+ ++counter);
               if((k % 4) == 0)
               break;
            }
         }
       }
    }

So the answer they give is "Hello-1" because 0 % 4 = 0
But my question is should k not be 1 because its been pre-incremented?
Thanks in advance!

A: A for loop has the following structure:
for (initialization; condition; update)

The update is executed after every execution of the loop.
Therefore the following two loops are identical:
for (int i = 0; i < 10; i++) {

and
for (int i = 0; i < 10; ++i) {

A:
my question is should k not be 1 because its been pre-incremented?

The ++k happens at the end of the loop iteration, i.e. after the if statement.
It makes no difference whether it's ++k or k++; in either case the first value of k is zero.

So the answer they give is "Hello-1"

This is clearly incorrect, since counter is never incremented and stays at zero throughout the program.

A: k cannot be 1.
This is because when a for loop runs, it only updates after it has executed all the code within    the loop. Since the loop breaks even before the first iteration is completed, k remains 0.


Q: Java scanner hasNextLine returns null after an object is constructed only once(?) first post.
I have a list file with user information I'm trying to create objects out of, to then put into an array list. When it has read the first 4 lines it constructs the object once, and when it loops to continue reading the file it stops because hasNextResult = null. (proof)
List file:
Lilly
Lilly Anderson
193.164.85.111
avatar.img
Johnny
Jonathan Anderson
224.12.8.94
avatar.img

Constructor:
public Friend(String nickname, String fullname, String lastip, String image){
    this.nickname = nickname;
    this.fullname =fullname;
    this.lastip =lastip;
    this.image =image;
}

@Override
public String toString(){
    return nickname + ", " + fullname + ", " + lastip + ", " + image;
}

Scanner:
public static Friend build(InputStream in){
    Friend friend;

    Scanner reader = new Scanner(in, StandardCharsets.UTF_8);

    if(reader.hasNextLine()){
        friend = new Friend(reader.nextLine(), null, null, null);
    }else{
        return null;
    }
    if(reader.hasNextLine()){
        friend.setFullname(reader.nextLine());
    }
    if(reader.hasNextLine()){
        friend.setIp(reader.nextLine());
    }
    if(reader.hasNextLine()){
        friend.setImg(reader.nextLine());
    }
    return friend;
}

Main:
public static void main(String[] args) throws FileNotFoundException {
    List<Friend> al = new ArrayList<>();

    FileInputStream reader = new FileInputStream("Friends.list");
    Friend f;

    while((f = Friend.build(reader))!= null){
        al.add(f);
    }
    Collections.sort(al);
    printCollection(al.iterator());
}

Output:
run:
Lilly, Lilly Anderson, 193.164.85.111, avatar.img
BUILD SUCCESSFUL (total time: 0 seconds)

Thanks for reading.

A: It tries to read the next line after the last line, Try this: Change the code for the scanner to this:
Scanner:
public static Friend build(InputStream in, int counter){
    Friend friend;

    Scanner reader = new Scanner(in, StandardCharsets.UTF_8);

    if(reader.hasNextLine()){
        friend = new Friend(reader.nextLine(), null, null, null);
    }else if(counter < 0){
    if(true){
        friend.setFullname(reader.readLine());
    }
    if(reader.hasNextLine()){
        friend.setIp(reader.nextLine());
    }
    if(reader.hasNextLine()){
        friend.setImg(reader.nextLine());
    }
        return friend;
    } else {
    return null;
    }
    if(reader.hasNextLine()){
        friend.setFullname(reader.nextLine());
    }
    if(reader.hasNextLine()){
        friend.setIp(reader.nextLine());
    }
    if(reader.hasNextLine()){
        friend.setImg(reader.nextLine());
    }
    return friend;
  }

Main:
 public static void main(String[] args) throws FileNotFoundException {
    List<Friend> al = new ArrayList<>();

    FileInputStream reader = new FileInputStream("Friends.list");
    Friend f;
    int counter = 0;
    while((f = Friend.build(reader, counter))!= null){
        al.add(f);
        counter++;
    }
    Collections.sort(al);
    printCollection(al.iterator());
 }

A: Do not create a new Scanner for each friend, try this:
    public static Friend build(Scanner reader){
        Friend friend;

        if(reader.hasNextLine()){
            friend = new Friend(reader.nextLine(), null, null, null);
        }else{
            return null;
        }
        if(reader.hasNextLine()){
            friend.setFullname(reader.nextLine());
        }
        if(reader.hasNextLine()){
            friend.setIp(reader.nextLine());
        }
        if(reader.hasNextLine()){
            friend.setImg(reader.nextLine());
        }
        return friend;
    }

and call it like in:
...
FileInputStream in = new FileInputStream("Friends.list");
Scanner reader = new Scanner(in, StandardCharsets.UTF_8.name());
Friend f;

while((f = Friend.build(reader))!= null){
     al.add(f);
}
...

Reason: Scanner kind of does read ahead the next token(s), so it is/they are already consumed when the next Scanner is created. From its source code:

 // Internal buffer used to hold input
 private CharBuffer buf;

 // Size of internal character buffer
 private static final int BUFFER_SIZE = 1024; // change to 1024;

I would use a BufferedReader instead of Scanner (for reading just lines)


Q: Problem when installing pip for python 2.7.16 in Ubuntu 18.04 I used the following in Home
$ sudo apt install python-pip

the output was the following
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 python-pip : Depends: python:any (< 2.8)
              Depends: python:any (>= 2.7.5-5~)
              Recommends: python-all-dev (>= 2.6) but it is not going to be installed
              Recommends: python-setuptools but it is not going to be installed
              Recommends: python-wheel but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I already tried the following without sucess
sudo apt-get clean

no special output but didn't fix the problem
sudo apt-get autoclean

no special output but didn't fix the problem
sudo apt-get -f install after sudo dpkg --configure -a and then
sudo apt-get -f install
output was : 0 upgraded, 0 newly installed, 0 to remove and 5 not upgraded.
sudo apt-get -u dist-upgrade and then sudo apt-get -o Debug::pkgProblemResolver=yes dist-upgrade
which gave the output :  0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

The aforementioned were some of the solutions proposed here How do I resolve unmet dependencies after adding a PPA?
Thanx!! :)

A: I just did
$ sudo apt install python-setuptools

and after
$ sudo apt install python-pip

and it solved the problem..


Q: Excel VBA - CountIfs - Moving from one spreadsheet to another I'm working on a CountIfs formula for a project and am having a little trouble. I'm pulling data from worksheet HR Data Detail and pasting it onto worksheet HR Data Summary. At the end of my CountIfs formula I have the range Z2:Z, which contains the years 2017, 2018, 2019, from worksheet HR Data Summary. I want Cell C2 on HR Data Summary to be a box that I can auto-fill in any year. For example, if I put 2018 into C2 then I want the CountIfs formula to pull the data for that specific year.
Sub Linking ()

'Defining finRow
Sheets("HR Data Detail". Activate)
Dim finRow As String
finRow = Sheets("HR Data Detail").Range("A50000").End(xlUp).Row

With Sheets ("HR Data Detail")

'Division 21 Employees
    Sheets("HR Data Summary").Range("L4") = _
        Application.WorksheetFunction.CountIfs(.Range("V2:V" & finRow), ">0", _
            .Range("S2:S" & finRow), "=21", .Range("L2:L" & finRow), "=January", _
            .Range("H2:H" & finRow), "=Employee", _
            Sheets("HR Data Detail").Range("Z2:Z" & finRow), "'HR Data Summary'!C2")

A: Assuming I'm understanding the purpose of this complex COUNTIFS formula -
It seems the problem is with the last range/criteria combo. Try changing
Sheets("HR Data Detail").Range("Z2:Z" & finRow), "'HR Data Summary'!C2")

to the following:
.Range("Z2:Z" & finRow), "=" & Sheets("HR Data Summary").Range("$C$2").Value


Q: How to implement monkey patch in C++? Is it possible to implement monkey patching in C++?
Or any other similar approach to that?
Thanks.

A: To add to other answers, consider that any function exposed through a shared object or DLL (depending on platform) can be overridden at run-time.  Linux provides the LD_PRELOAD environment variable, which can specify a shared object to load after all others, which can be used to override arbitrary function definitions.  It's actually about the best way to provide a "mock object" for unit-testing purposes, since it is not really invasive.  However, unlike other forms of monkey-patching, be aware that a change like this is global.  You can't specify one particular call to be different, without impacting other calls.

A: Considering the "guerilla third-party library use" aspect of monkey-patching, C++ offers a number of facilities:

*

*const_cast lets you work around zealous const declarations.

*#define private public prior to header inclusion lets you access private members.

*subclassing and use Parent::protected_field lets you access protected members.

*you can redefine a number of things at link time.

If the third party content you're working around is provided already compiled, though, most of the things feasible in dynamic languages isn't as easy, and often isn't possible at all.

A: I suppose it depends what you want to do. If you've already linked your program, you're gonna have a hard time replacing anything (short of actually changing the instructions in memory, which might be a stretch as well). However, before this happens, there are options. If you have a dynamically linked program, you can alter the way the linker operates (e.g. LD_LIBRARY_PATH environment variable) and have it link something else than the intended library.
Have a look at valgrind for example, which replaces (among alot of other magic stuff it's dealing with) the standard memory allocation mechanisms.

A: Not portably so, and due to the dangers for larger projects you better have good reason.
The Preprocessor is probably the best candidate, due to it's ignorance of the language itself. It can be used to rename attributes, methods and other symbol names - but the replacement is global at least for a single #include or sequence of code.
I've used that before to beat "library diamonds" into submission - Library A and B both importing an OS library S, but in different ways so that some symbols of S would be identically named but different. (namespaces were out of the question, for they'd have much more far-reaching consequences).
Similary, you can replace symbol names with compatible-but-superior classes.
e.g. in VC, #import generates an import library that uses _bstr_t as type adapter. In one project I've successfully replaced these _bstr_t uses with a compatible-enough class that interoperated better with other code, just be #define'ing _bstr_t as my replacement class for the #import.
Patching the Virtual Method Table - either replacing the entire VMT or individual methods - is somethign else I've come across. It requires good understanding of how your compiler implements VMTs. I wouldn't do that in a real life project, because it depends on  compiler internals, and you don't get any warning when thigns have changed. It's a fun exercise to learn about the implementation details of C++, though.  One application would be switching at runtime from an initializer/loader stub to a full - or even data-dependent - implementation.
Generating code on the fly is common in certain scenarios, such as forwarding/filtering COM Interface calls or mapping OS Window Handles to library objects. I'm not sure if this is still "monkey-patching", as it isn't really toying with the language itself.

A: As monkey patching refers to dynamically changing code, I can't imagine how this could be implemented in C++...


Q: How to calculate the rank of a list without pandas and numpy? i've written the following code:
  s = [2,1,-99,100,45,-2]
    li=[]

    for i in range(len(s)):
       li.append([s[i],i])
       li.sort()
       sort_index = []

    for x in li:
       sort_index.append(x[1])

    print(sort_index)

   this gives the output as :[2, 5, 1, 0, 4, 3]

required output : [4,3,1,6,5,2]
I need the rank such that the output is the rank of the first element of s
what are the suggested changes in my code to find the rank. And we shouldn't use numpy and pandas

A: Ranking in this context appears to be in terms of sorted order.  For that purpose one can compare the position of the elements in the original list against a sorted list to get the correct answer.
Example:
s = [2,1,-99,100,45,-2]
sorted_s = sorted(s)
ranked_s = [
    sorted_s.index(value) + 1
    for value in s
]
print(rank)

Output:
[4, 3, 1, 6, 5, 2]


Q: something wrong with this jquery? There is a debugging syntax error, but I can’t see it! im a bit of a newbie, so excuse my code!!
$(document).ready(function(){
     /* fetch elements and stop form event */
     $("form.follow-form").submit(function (e) {
        /* stop event */
        e.preventDefault();
        /* "on request" */
        $(this).find('i').addClass('active');
        /* send ajax request */
            $.ajax({
                type: "POST",
                url: "ajax_more.php",
                data: $(this).serialize(),
                cache: false,
                success: function(html){
                    $("ul.statuses").append(html);
                    $("form.follow-form").remove();
                }
            });
            else {
                $(".morebox").html('The End');
            }
            return false;
     });
});

A: Try this
$(document).ready(function() {
    /* fetch elements and stop form event */
    $("form.follow-form").submit(function(e) { /* stop event */
        e.preventDefault(); /* "on request" */
        $(this).find('i').addClass('active'); /* send ajax request */
        $.ajax({
            type: "POST",
            url: "ajax_more.php",
            data: $(this).serialize(),
            cache: false,
            success: function(html) {
                $("ul.statuses").append(html);
                $("form.follow-form").remove();
            }
        });
        $(".morebox").html('The End');
        return false;
    });
});

A: You’ve got an else, but no if.
Here’s the code with some proper indentation — indentation makes the code much easier to understand, so you spot errors more quickly.
$(document).ready(function(){

    /* fetch elements and stop form event */
    $("form.follow-form").submit(function (e) {

        /* stop event */
        e.preventDefault();

        /* "on request" */
        $(this).find('i').addClass('active');

        /* send ajax request */
        $.ajax({
            type: "POST",
            url: "ajax_more.php",
            data: $(this).serialize(),
            cache: false,
            success: function(html){
                $("ul.statuses").append(html);
                $("form.follow-form").remove();
            }
        });

======> /* HERE’S THE ELSE WITHOUT AN IF */

        else {
            $(".morebox").html('The End');
        }

        return false;
    });

});


Q: Perl - How to change every $variable occurrence of ";" in a string Very new here so be gentle. :)
Here is the jist of what I want to do:
I want to take a string that is made up of numbers separated by semi-colons (ex. 6;7;8;9;1;17;4;5;90) and replace every "X" number of semicolons with a "\n" instead. The "X" number will be defined by the user.
So if:
$string = "6;7;8;9;1;17;4;5;90";
$Nth_number_of_semicolons_to_replace = 3;

The output should be:
6;7;8\n9;1;17\n4;5;90

I've found lots on changing the Nth occurrence of something but I haven't been able to find anything on changing every Nth occurrence of something like I am trying to describe above.
Thanks for all your help!

A: use List::MoreUtils qw(natatime);
my $input_string = "6;7;8;9;1;17;4;5;90";
my $it = natatime 3, split(";", $input_string);
my $output_string;

while (my @vals = $it->()) {
    $output_string .= join(";", @vals)."\n";
}

A: Here is a quick and dirty answer.
my $input_string = "6;7;8;9;1;17;4;5;90";
my $count = 0;
$input_string =~ s/;/++$count % 3 ? ";" : "\n"/eg;

A: Don't have time for a full answer now, but this should get you started.
$string = "6;7;8;9;1;17;4;5;90";
$Nth_number_of_semicolons_to_replace = 3;
my $regexp = '(' . ('\d+;' x ($Nth_number_of_semicolons_to_replace - 1)) . '\d+);';
$string =~ s{ $regexp ) ; }{$1\n}xsmg

A: sub split_x{
  my($str,$num,$sep) = @_;
  return unless defined $str;

  $num ||= 1;
  $sep = ';' unless defined $sep;

  my @return;
  my @tmp = split $sep, $str;
  while( @tmp >= $num ){
    push @return, join $sep, splice @tmp, 0, $num;
  }
  push @return, join $sep, @tmp if @tmp;

  return @return;
}

print "$_\n" for split_x '6;7;8;9;1;17;4;5;90', 3

print join( ',', split_x( '6;7;8;9;1;17;4;5;90', 3 ) ), "\n";

A: my $string = "6;7;8;9;1;17;4;5;90";
my $Nth_number_of_semicolons_to_replace = 3;

my $num = $Nth_number_of_semicolons_to_replace - 1;
$string =~ s{ ( (?:[^;]+;){$num} [^;]+ ) ; }{$1\n}gx;

print $string;

prints:

6;7;8
9;1;17
4;5;90

The regex explained:
s{
  (                   # start of capture group 1
     (?:[^;]+;){$num} # any number of non ';' characters followed by a ';'
                      # repeated $num times
     [^;]+            # any non ';' characters
  )                   # end of capture group
  ;                   # the ';' to replace
}{$1\n}gx;            # replace with capture group 1 followed by a new line

A: If you've got 5.10 or higher, this could do the trick:
#!/usr/bin/perl

use strict;
use warnings;

my $string = '1;2;3;4;5;6;7;8;9;0';
my $n = 3;

my $search = ';.*?' x ($n -1);

print "string before: [$string]\n";

$string =~ s/$search\K;/\n/g;

print "print string after: [$string]\n";

HTH,
Paul