text:
Q: How to find empty repos (zero commit) in GitLab I'm using GitLab 11.9 (it's old, I know ....), and I need to list all the repositories that have been created but that are empty o with zero commits.
Is it possible to list them from admin interface o via API?

A: To achieve this with Gitlab API we will combine Projects API https://docs.gitlab.com/ee/api/projects.html#list-all-projects
And the Commits API
https://docs.gitlab.com/ee/api/projects.html#list-all-projects
To the following bash script (Make sure you have curl and jq installed)
#!/bin/bash

ACCESS_TOKEN=$1
GITLAB_URL=$2

curl -s --header "PRIVATE-TOKEN: $ACCESS_TOKEN" $GITLAB_URL/api/v4/projects/?per_page=50000 | jq '.[] | "\(.id) \(.web_url) \(.name)"' | sed 's/^"\(.*\)"$/\1/'| while read line
do
        PROJECT_ID=$(echo $line | cut -d " " -f1 )
        PROJECT_NAME=$(echo $line | cut -d " " -f3- )
        REPO_URL=$(echo $line | cut -d " " -f2 )

        COMMIT_IDS=$(curl -s --header "PRIVATE-TOKEN: $ACCESS_TOKEN" $GITLAB_URL/api/v4/projects/$PROJECT_ID/repository/commits | jq '.[].id')

        if [[ $COMMIT_IDS == "" ]]; then echo "$PROJECT_ID $PROJECT_NAME $REPO_URL";fi

done

Execution Example:
./my_script.sh "<your_access_token>" "https://gitlab.example.com"

The output of this script will be the Project ID Project Name and Project URL of the repos with 0 commits
E.G.
33294654 project-for-issues-286e58fd4f6a5603 https://gitlab.com/gitlab-qa-sandbox-group/qa-test-2022-01-31-18-09-07-311cfe607ff3ce9b/project-for-issues-286e58fd4f6a5603

33294612 project-with-ci-variables-c1b233588d3fbce7 https://gitlab.com/gitlab-qa-sandbox-group/qa-test-2022-01-31-18-09-05-68cad66167d10aa2/project-with-ci-variables-c1b233588d3fbce7

Note: This script assumes that you have less than 50.000 repositories in your Gitlab


text:
Q: Notes client crashes when using object tag and pdf in XPiNC I have a PDF file as file resource (test.pdf) in my database and the following xpage which displays it as an embedded object:
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">

<xp:panel tagName="object">
    <xp:this.attrs>
        <xp:attr name="data" value="test.pdf"></xp:attr>
        <xp:attr name="type" value="application/pdf"></xp:attr>
        <xp:attr name="width" value="600"></xp:attr>
        <xp:attr name="height" value="600"></xp:attr>
    </xp:this.attrs>

    It appears your Web browser is not configured to display PDF files. No worries, just click here to download the PDF file.
</xp:panel>
</xp:view>

It works all fine in the web browser (Firefox). When I open the xpage in the Notes client (XPiNC) for the first time the PDF is also displayed embedded. But when I open the xpage a few times the Client crashes.
I use Release 8.5.3FP1.
Do you have any suggestions? Is the use of the object tag forbidden in XPiNC?

As recommended in the answer from Simon O'Doherty I checked all files in 'IBM_TECHNICAL_SUPPORT' and 'workspace\logs' folder which were modified since/ after the client crashed.
There were no FATAL in the nsd file.
error-log-1.xml:
<CommonBaseEvent creationTime="2012-08-21T22:08:27.093+02:00" globalInstanceId="ELc0a808f50001394acb55ed00000009" msg="Project facet jst.web has not been defined. It is used in plugin org.eclipse.wst.jsdt.web.core." severity="50" version="1.0.1">
<extendedDataElements name="CommonBaseEventLogRecord:level" type="noValue">
    <children name="CommonBaseEventLogRecord:name" type="string">
        <values>SCHWERWIEGEND</values>
    </children>
</extendedDataElements>
<sourceComponentId component="Expeditor 6.2" componentIdType="ProductName" instanceId="1327306362466" location="MBS-86" locationType="Hostname" subComponent="org.eclipse.wst.common.project.facet.core" threadId="4" componentType="http://www.w3.org/2001/XMLSchema-instance"/>
<situation categoryName="ReportSituation">
    <situationType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="ReportSituation" reasoningScope="INTERNAL" reportCategory="LOG"/>
</situation>
</CommonBaseEvent>´

console_MBS-86_2012_08_21@22_06_40.log :
[0548:0002-1230] 21.08.2012 22:27:14,34 DeskClientOpenInt> Calling CreateProgramRCP     pszRCPCmdLine[/authenticate ] bDeskProvisioningRestart [0]
[0548:0002-1230] 21.08.2012 22:27:14,37 DeskClientOpenInt> Executed CreateProgramRCP
[0548:0002-1230] 21.08.2012 22:27:21,35 DeskClientOpenInt> Calling CreateProgramRCP pszRCPCmdLine[/authenticate ] bDeskProvisioningRestart [0]
[0548:0002-1230] 21.08.2012 22:27:21,38 DeskClientOpenInt> Executed CreateProgramRCP
[0548:0002-1230] 21.08.2012 22:27:27,27 DeskClientOpenInt> Calling CreateProgramRCP pszRCPCmdLine[/authenticate ] bDeskProvisioningRestart [0]
[0548:0002-1230] 21.08.2012 22:27:27,29 DeskClientOpenInt> Executed CreateProgramRCP
[0548:000E-0D34]  Thread=[0548:000E-0D34]
[0548:000E-0D34] Stack base=0x05F70084, Stack size = 2560 bytes
[0548:000E-0D34] PANIC: The notes2 process (pid=2052) exited unexpectedly.

Thx in advance.

A: Dealing with crashes.

*

*In the IBM_TECHNICAL_SUPPORT folder under your data folder there should be an NSD file. Open that file and search for FATAL and post the fatal thread.

*If there is no FATAL stack, then check the workspace\logs folder for any Javacores, or Error logs. For the error logs you need to look for SEVERE references, as these are most likely to cause a crash.

*Also check the XPages logs in the IBM_TECHNICAL_SUPPORT folder for any errors.
Without those details it is not possible to diagnose the root cause.

A: Upgrading from Adobe Reader 8.1.4 to Adobe Acrobat X/ Reader 10.1.4 fixed the problem, no crash occurred since the update.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where is the Set product new from date found in database? I am a newbie to magento and would like to know where the "set product new from date" values for each product are found in the databse table and the column name. I checked with the catalogrule_product. There is a column named from_time, I am not sure is this is the right table or if there are any other table related to this.

A: Magento follows EAV database structure. In database, you will find eav_attribute table.
In there search for attribute_code = 'news_from_date' and attribute_code = 'news_to_date' and note down ids of these attributes.
Now go to catalog_product_entity_datetime table and search for attribute_id =  and entity_id =
I think, your query is resolved now. If you have any confusion then please ask.

A: Attribute name is : news_from_date
$code = 'news_from_date'
now using $attributeId= getAttributeId($code );
$entity_id= $product->getId();
Now as stated above query :  select * from catalog_product_entity_datetime wher attribute_id = $attributeId and entity_id = $entity_id


text:
Q: A question about inclusions of ideals generated by algebraic sets Let $R$ be a ring and  $X_1,X_2 \subseteq \mathbb{A}^n$ two algebraic sets such that $X_1 \subseteq X_2$. Then is it true that $I(X_1) \supseteq I(X_2)$ where
$$I(X) = \{f \in R \, | \,  f(p)=0 \, \, , \, p \in X\} $$
If $f \in I(X_1)$ then $f(p)=0 \, \, \, \forall p \in X_1$ but if $p \in X_1 \Rightarrow p \in X_2$ and so I would rather think that $I(X_1) \subseteq I(X_2)$


text:
Q: To chunk or not to chunk: How to control DocBook chunking with elements at the same level? We are converting our documentation from a FrameMaker/ePublisher process to a DocBook XML process. The problem we have is that we cannot control the chunking in an easy fashion.
In our newly converted XML files, the h2topic paragraph designation turns into a role = "new-topic" attribute in the XML. The core problem is that we are using a build technique in ePublisher that is relatively easy to implement, but in the DocBook XSL build, this same technique is very difficult to implement.
In the DocBook build, you can easily chunk topics at any level in the XML tag hierarchy; we could start each new page at the h4 level if we wanted to, just by setting a build parameter. To start new pages for some sections, and not for others, at the same level in the tag hierarchy, we are thinking that it would require some particularly gnarly custom XSLT coding.
Is this assumption correct?
Many thanks.
P.


text:
Q: Add/remove class with jquery based on vertical scroll combined with fullPage.js? I'm trying to add/remove CSS classes (e.g. "clearHeader" and "darkHeader") with jQuery based on vertical scroll. That itself is very easy and works well, but when I try to combine that with fullPage.js (see http://alvarotrigo.com/fullPage) - it doesn't work.
Script used:
//<![CDATA[
    $(function() {
        var header = $("#fullpage");
        $(window).scroll(function() {
            var scroll = $(window).scrollTop();

            if (scroll >= 500) {
                header.removeClass('clearHeader').addClass("darkHeader");
            } else {
                header.removeClass("darkHeader").addClass('clearHeader');
            }
        });
    });
//]]>

See jsfiddles:

*

*only script: http://jsfiddle.net/ccn469og/11/

*only fullPage: http://jsfiddle.net/7s1yb1un/2/

*both: http://jsfiddle.net/84bywp2z/
Anyone had this issue before or knows of a workaround script that considers this type of irregular scrolling? (basically fullPage "toggles" between full-page sections accessible by pressing the down/up key or by a single mouse scroll).

A: If you read the fullPage.js FAQs you will see this:

jQuery scroll event doesn't work.
  Same answer as Parallax doesn't work with fullpage.js

Which is:

Short answer: use the scrollBar:true option for fullPage.js or autoScrolling:false if you don't want to use the auto-scrolling feature.

Explanation: Parallax, as well as many other plugins which depends on the scrolling of the site, listens the scrollTop property of javascript. fullPage.js doesn't actually scroll the site but it changes the top or translate3d property of the site. Only when using the fullPage.js option scrollBar:true or autoScrolling:false it will actually scroll the site in a way it is accessible for the scrollTop property.

There you have it. If there's no scroll bar, then you will jump from section to section so in your case, the most logical thing to do would be to use the callbacks provided by fullPage.js such as afterLoad, onLeave, afterSlideLoad or onSlideLeave.
Or, if you want to deal only with css, fullPage.js adds a class to the body depending on the section/slide the page currently is.
You could easily do something like:
body.fp-viewing-secondPage .demo{
   display:none;
}
body.fp-viewing-thirdPage .demo{
    display:block
}


text:
Q: Swift - React on "@" when pressing the keyboard I want to call a function every time, whenever the user clicks on the "@" character on the keyboard.
Currently, I am using following approach
func textViewDidChange(_ textView: UITextView) { //Handle the text changes here
   if (textView.text.contains("@") {
      doSomething()
   }
}

However, the code above doesn't work for me, because my text view will contain characters like @. This means, after having @ at least once in my text view, it will call the doSomething() function every time when I type something on the keyboard. Is there another way to check the input of the user?

A: instead of checking in textViewDidChange move to shouldChangeCharactersIn
func textField(_ textView: UITextView, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    if (textView.text.contains"@") { // Already have @ value
        doSomething()
    }
    if (string == "@") { // user input char
        doSomething()
    }
    return true
}

Refer => https://developer.apple.com/documentation/uikit/uitextviewdelegate/1618630-textview


text:
Q: Javascript - onClick return what was clicked on so, I have a div with stuff like
s and s in them, and I want it so that if a user doubleclicks on one of them (for example they double click on anything inside the

 tags it will turn it into a textbox with
title
 inside it...
I just can't figure out how to send to the javascript function what was double clicked on?

A: try if you are famous with jQuery:
$('#yourDiv *').dblclick(function(event)){
 alert(event.target.html());
}

A: Here is a very bare example for single click:

Hello

My

Friend

test live: http://jsfiddle.net/MsTzY/


text:
Q: Multiple exception logging for single problem - how to handle this? The pattern of catch wrap and re-throw and logging at every catch-point causes several entries in the log. What do you usually do ?

A: In a single catch block, EITHER handle (which could be as simple as just logging) OR throw (rethrowing the exception, or wrapping it and throwing the new exception), never both.
Wrapping is not a problem, because if you look at the stacktraces, frames are not repeated. The causes only contain the frames below the wrap.

A: Any individual exception should only be logged in 1 location to avoid clogging up your logs. As long as the exception contains the original cause, you should be able to trace back to it.
Personally I do the following:
Catch checked exception at lowest level point that I can, wrap in a RuntimeException (or subclass) with the best message to detail what was happening when the exception occurred and re-throw. No logging is done at the low level. Catch the unchecked (Runtime) exceptions at a very high level, just before it can impact a user. There it gets logged (with original cause) and converted into a useful message for the end user.
This only applies to exceptions that cannot be handled (which is most). There are other cases for things like connection retries, but I don't think that's the primary point of your question.

A: I wouldn't catch and wrap unless you think you are adding some value by doing so.  In which case you want each layer to appear in the logs.  Any layers you don't want, don't put them there.
If you have not control over the wrapping, you can un-wrap and discard them, or just put up with them being in the logs.

A: It may be best to do this using a multiple approaches:

*

*Try not to catch every exception, instead declare your methods/constructors to throw these exception and catch them from code higher up the call chain.  There is little point in catching and re-throwing unless you need to close resources (such as database handles.)

*Extend your own exception class and chain other exceptions into it.  While you are at it, include a state variable in your Exception class to see if it was already logged or not.

A: Checked exceptions usually aren't worth the troubles they cause.
My favorite way to get a checked exception up the tree to where it can be handled is to wrap it once as an unchecked exception and let it fly.
You could also just use the throws clause in each method.
Or you trap it at a low level and actually handle it and return it as an error code.
The very best way to handle exceptions is to never generate them. (For instance if you are trying to open a file that may or may not exist, rather than opening it then creating it if the open fails, test it, create it if necessary THEN open it and avoid the exception altogether.


text:
Q: Help with contour lines in circuitikz - unwanted circles appeared I am doing this scheme in LaTeX.
and I wrote this code. I think everything is good but these lines contours inside this scheme. This red and blue dashed lines. I get these circles with arrows or something like that, and I don't know why. Beside that, I want to ask you how to get these corners rounded, because adding did not help at all. Thanks.

A: I have no idea, why there are these symbols, but  if you exchange the to with -- everything is ok:
\draw[>=latex',red,dashed,rounded corners=10pt,->](0.5,1.5) -- (0.5,2.5) -- (4.5,2.5) -- (4.5,0.5) -- (0.5,0.5);
\draw[>=latex',blue,dashed,rounded corners=10pt,->](9.5, 1.5) -- (9.5,2.5) -- (14.5, 2.5) -- (14.5, 0.5) -- (9.5, 0.5);

EDIT: There was a bug in circuitikz, therefore, the surgearrester appears at to-paths without []-option. This is fixed at the current git-version.


text:
Q: Server response header states status code 301 despite correct hostname I've made a simple client socket in c that has been mostly successful.
The problem I'm having is my client socket receives a 301 status from, ironically, www.w3.org.

Observe, when I send the following GET with my client c socket
GET / HTTP/1.1
Host: time.com
Connection: keep-alive
Accept: */*
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

I receive
HTTP/1.1 200 OK
Server: nginx
Date: Thu, 12 Nov 2015 08:44:34 GMT
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Connection: keep-alive
Vary: Accept-Encoding
Last-Modified: Thu, 12 Nov 2015 08:40:48 GMT
Cache-Control: max-age=74, must-revalidate
X-nananana: Batcache
Vary: Cookie
X-hacker: If you're reading this, you should visit automattic.com/jobs and apply to join the fun, mention this header.
X-Pingback: http://time.com/xmlrpc.php
X-UA-Compatible: IE=edge,chrome=1
Link: <http://ti.me/nACNOw>; rel=shortlink
Content-Encoding: gzip
X-ac: 4.ord _dca

However, when I send a GET request to www.w3.org.
GET / HTTP/1.1
Host: www.w3.org
Connection: keep-alive
Accept: */*
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8

I receive
HTTP/1.1 301 Moved Permanently
Content-length: 0
Location: http://www.w3.org/
Connection: close

When google chrome sends a similar GET to www.w3.org
GET / HTTP/1.1
Host: www.w3.org
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36

The server responds with
HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: max-age=600
Content-Length: 39276
Content-Location: Home.html
Content-Type: text/html; charset=utf-8
Date: Sun, 15 Nov 2015 04:40:47 GMT
ETag: "996c-524790d293380;89-3f26bd17a2f00"
Expires: Sun, 15 Nov 2015 04:50:47 GMT
Last-Modified: Sat, 14 Nov 2015 05:00:14 GMT
P3P: policyref="http://www.w3.org/2014/08/p3p.xml"
Server: Apache/2
TCN: choice
Vary: negotiate,accept

Why does my client's GET receive a 301 despite its near equivalence with Chrome's GET?
Do some websites have a strict set of required HTTP header fields?
Is there a bigger picture that I'm missing?

A: w3.org enforces the canonical URL www.w3.org with a permanent redirect. Requesting just w3.org will result in a HTTP 301. The canonical URL is a matter of preference so it shouldn't be assumed that the non-prefixed URL will always redirect to the www prefixed one.


text:
Q: android-opencv converting mat to grayscale with using matToBitmap/bitmapToMat I am using newer opencv library of willowgarage in eclipse. And I want to convert a mat variable into grayscale, I've tried everything I found on the net but they didnt work for me.
Here is my code
package com.deneme.deneme;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import org.opencv.android.Utils;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class main extends Activity {
/** Called when the activity is first created. */

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    ImageView img=(ImageView) findViewById(R.id.pic);

    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.p26);

    Mat imgToProcess=Utils.bitmapToMat(bmp);

    //******
    //right here I need to convert this imgToProcess to grayscale for future opencv processes
    //******

    Bitmap bmpOut = Bitmap.createBitmap(imgToProcess.cols(), imgToProcess.rows(), Bitmap.Config.ARGB_8888);

    Utils.matToBitmap(imgToProcess, bmpOut);
    img.setImageBitmap(bmpOut);
}

}

A: Add the following code in your code block:
Imgproc.cvtColor(imgToProcess, imgToProcess, Imgproc.COLOR_BGR2GRAY);
Imgproc.cvtColor(imgToProcess, imgToProcess, Imgproc.COLOR_GRAY2RGBA, 4);

Or you can access pixels by yourself:
for(int i=0;i<imgToProcess.height();i++){
    for(int j=0;j<imgToProcess.width();j++){
        double y = 0.3 * imgToProcess.get(i, j)[0] + 0.59 * imgToProcess.get(i, j)[1] + 0.11 * imgToProcess.get(i, j)[2];
        imgToProcess.put(i, j, new double[]{y, y, y, 255});
    }
}


text:
Q: How does the Role hierarchy change enforcement works in ITIM 5.1? "The people affected by the role hierarchy change operation are evaluated against
all applicable policies in the system, including policies that are not related to any
of the parent roles. As a result, you might find accounts not related to the role
hierarchy change that are being enforced."
Can someone explain in layman's term what exactly the above lines are trying to convey, like :
when does a role hierarchy change operation occur ?
what are the applicable policies here and how will change be evaluated ?

A: You have just the above part from a longer chapter and it sounds a little bit out of context, but it is not that complicated.
Role hierarchies have to do with relationships between roles. In ITIM/ISIM you can define that roles are parents/children of other roles and thus create hierarchies. It also supports that notion of inheritance, so that for example Provisioning policies that apply to the Parent role, apply to the children roles as well.
A role hierarchy change happens when you add a parent or a child in a given role. If for example you had Role1 and you a provisioning policy that applies to this role, when you add Role2 as a child of the Role1 role, then the provisioning policy will now apply to Role2 too.
As for the other matter in discussion, lets start with two facts :

*

*You might have a number of provisioning policies in your system. Depending on how the policy membership is set up, each one of those can apply to specific roles, groups, or all the persons in your system.

*In the default ITIM configuration, each time you modify a person, the modifyPerson workflow is executed. This can contain a number of nodes, but by default it contains a modifyPerson node and an enforcePolicy node. The modifyPerson performs, as the name implies, the modifications on the person object in ITIM. The enforcePolicy node, again as the name implies, evaluates ALL applicable provisioning policies for the person and performs the necessary actions on the persons accounts according to the provisioning policies.

What the sentence you quoted says is that when you add a role (RoleA) as a child of another role (RoleB), the provisioning policy (lets call it Policy1 ) that applies to RoleA, now applies to RoleB also. And if you had a person that was member of the RoleB, now that you perform the role hierarchy change, the policies for this person will be evaluated because ITIM needs to enforce Policy1 for him. However this does not mean that at this time, the only policy that applies to this person, is Policy1. A number of different policies can apply to him and ALL of them will be evaluated at this time. This can lead to changes in other accounts or more changes in the same account of this person.
By the way, this has been modified a little bit with ISIM 6 , FixPack 3, Intermittent FixPack 11. Now the enforce policy node in the workflow can be configured to only take into consideration the provisioning policies that need to be reevaluated for the specific change that happens and not blindly go through and evaluate everything again.


text:
Q: Proving a Rational Expression is Surjective I need to prove that the function $f:(-1,1)\rightarrow\mathbb{R}$ defined by $f(x) = \frac{x}{x^2 - 1}$ is surjective.
My work.
$b = \frac{a}{a^2 - 1} \iff b(a^2 -1)=a \iff ba^2 - b - a=0$
From here I did a few cases:
Case 1) $b=0$. Then $a=0$.
Using the quadratic formula: $a = \frac{1\pm \sqrt{1+4b^2}}{2b}$.
Case 2) $b \gt0$. Then $a = \frac{1+ \sqrt{1+4b^2}}{2b}$ $\notin (-1,1)$ $\forall$ b $\in R$.
Case 3) $b \gt0$. Then $a = \frac{1- \sqrt{1+4b^2}}{2b}$ $\in (-1,1)$ $\forall$ b $\in R$.
Using Case 1 and Case 3, f is subjective. Is this correct? I cannot use Calculus.

A: It is correct. But you should justify the assertions that $\frac{1+\sqrt{1+4b^2}}{2b}\notin(-1,1)$ and that $\frac{1-\sqrt{1+4b^2}}{2b}\in(-1,1)$. This follows easily from the fact that$$\frac{1+\sqrt{1+4b^2}}{2b}\times\frac{1-\sqrt{1+4b^2}}{2b}=-1.$$

A: You can also just argue that $f$ is continuous on $(-1,1)$ and that
$$
\lim_{x \to -1^+} f(x)=+\infty, \quad \lim_{x\to 1^-} f(x) = -\infty.
$$
The intermediate value theorem (or a mild generalisation of it) takes care of the rest.


text:
Q: How to save multiple categories in magento 2 How to save multiple categories. For a single category using the method save.
Ejm.: Save category1, category2, category3, ... category100. How to save 100 in 100 categories.

A: I got it to work by deleting the spaces.
category1,category2,category3, ...


text:
Q: three horizontal buttons with a small margin between them with ConstraintLayout I want to draw a keyboard with big buttons for a calc app, three per row, and between these three buttons I need to put a small empty margin. I know how to do that with a LinearLayout but I completly ignore how this can be achieved with Constraint Layouts.
I tried to assign some distance between the buttons, centering the central one and then constraining to the central button the right and the left one.
the result is terrible because using different screens the distance between the button can become huge, while instead I want to achieve the same proportions in all the screens, in other words the distance between the buttons(the small margins) should be always really tiny, undependently by the screen, filling almost all the screen surface with the buttons and not with the empty spaces.

A: To achieve this in constraintLayout you can use barriers/guidelines/chains.
The easiest solution would be to use chains:
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/frameLayout2"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Fragments.MenusDesign.ExpandableCategoriesMenu.ExpandableCategoriesMenu">

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    app:layout_constraintBottom_toBottomOf="@+id/button2"
    app:layout_constraintEnd_toStartOf="@+id/button2"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="@+id/button2" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/button3"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toEndOf="@+id/button"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button"
    app:layout_constraintBottom_toBottomOf="@+id/button2"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toEndOf="@+id/button2"
    app:layout_constraintTop_toTopOf="@+id/button2" />


text:
Q: Keyboard gives bad ascii values I poured water over my notebook this morning.
  When i turn it on, it works, but integrated keyboard doesn't work. It gives totally wrong ascii values.
What can be done now?

A: Best thing is to disconnect power cables and battery until the laptops internals have fully dried up to prevent any short circuits.
If problem still exists after, you can call their service center if you still have warranty.
If not, you can try to find a replacement keyboard on ebay or directly from laptop manufacturer. This assuming it's only the keyboard circuit board that's toasted


text:
Q: How To Show Progress Bar On a WebView In MonoDroid I have been trying to display the progress bar implementation in a WebView used by an app using monodroid. I have reached quite far but couldn't seem to solve the last part of the puzzle. I am using the paid version of Monodroid Pro and am using Galaxy S2 as the test device.
Here is what I have done so far :-
In the OnCreate Section :-
        Window.RequestFeature(WindowFeatures.Progress);

        SetContentView(Resource.Layout.Main);

        Window.SetFeatureInt(WindowFeatures.Progress, Window.ProgressVisibilityOn);

        wv.SetWebViewClient(new monitor());

        wv.LoadUrl("https://www.google.com");

Now on the onprogress changed override method :-
  private class progress : WebChromeClient
  {
        public override void OnProgressChanged(WebView view, int newProgress)
        {
           base.OnProgressChanged(view, newProgress);
        }
  }

Now the solutions I have seen are for java implementation of Android which is quite easy, i.e :-
webview.setWebChromeClient(new WebChromeClient() {
    public void onProgressChanged(WebView view, int progress)
    {
        //Make the bar disappear after URL is loaded, and changes string to Loading...
        MyActivity.setTitle("Loading...");
        MyActivity.setProgress(progress * 100); //Make the bar disappear after URL is loaded

        //Return the app name after finish loading
        if(progress == 100)
            MyActivity.setTitle(R.string.app_name);
     }
 });

But using monodroid i can't use SetProgress method as in the Android implementation, the Activity instance can be made in OnCreate Method, whereas in Monodroid a whole new class is to be made and then webchromeclient is to be inherited first and then so on. What am i missing? Is there another way that I don't know about? Some help would be really appreciated.

A: C# doesn't support anonymous classes like Java, as you noticed, so you need to define a separate class. The Activity.SetProgress() method is public, which means that you can pass a reference to your activity into the class, and use that to call the method:
public class CustomWebChromeClient : WebChromeClient
{
    private Activity _context;

    public CustomWebChromeClient(Activity context)
    {
        _context = context;
    }

    public override void OnProgressChanged(WebView view, int newProgress)
    {
        base.OnProgressChanged(view, newProgress);

        _context.SetProgress(newProgress * 100);
    }
}

Then your activity could create an instance of this class, passing itself into the constructor:
webview.SetWebChromeClient(new CustomWebChromeClient(this));

I have a more complete browser demo available here that may also help you get going.


text:
Q: Spring Cloud Contract Stub Runner server how to connect it to Artifactory repository and get stubs artifact file via REST? I've create REST service which should connect to Artifactory.com repository, find stubs of contract tests artifact and get it. But when I start app and use GET method it doesn't returned any information (only {} in response). What parameters or else may be I didn't write or write wrong? Thanks for help.
Main class:
@SpringBootApplication
@EnableStubRunnerServer
@AutoConfigureStubRunner(
        repositoryRoot = "http://artifactory.example.com/artifactory/exampleapp",
        stubsMode = StubRunnerProperties.StubsMode.REMOTE,
        ids = "com.exampleproject:users:develop-20190806.111405-21:stubs:8555")
public class StubRunnerApplication {
    public static void main(String[] args) {
        SpringApplication.run(StubRunnerApplication.class, args);
    }
}

REST controller
@RestController
@RequestMapping(value = "/stubs", produces = MediaType.APPLICATION_JSON_VALUE)
public class StabsController {

    @StubRunnerPort("com.exampleproject:users")
    private int port;

    private final StubRunning stubRunning;

    @Autowired
    public StabsController(StubRunning stubRunning) {
        this.stubRunning = stubRunning;
    }

    @GetMapping("/")
    public Map<String, Integer> getStabs() {
        return stubRunning.runStubs().toIvyToPortMapping();
    }
}

application.yml
stubrunner:
  work-offline: true
  cloud.stubbed.discovery.enabled: false

pom.xml
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.1.RELEASE</version>
        <relativePath/>
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <spring-boot-starter-web.version>2.1.6.RELEASE</spring-boot-starter-web.version>
        <spring-boot.version>2.1.6.RELEASE</spring-boot.version>
        <spring-cloud-contract-verifier.version>2.1.1.RELEASE</spring-cloud-contract-verifier.version>
        <spring-cloud-contract-stub-runner.version>2.1.2.RELEASE</spring-cloud-contract-stub-runner.version>
        <spring-cloud-stream.version>1.2.1.RELEASE</spring-cloud-stream.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${spring-boot-starter-web.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>${spring-boot.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-contract-verifier</artifactId>
            <version>${spring-cloud-contract-verifier.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-contract-stub-runner</artifactId>
            <version>${spring-cloud-contract-stub-runner.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-stream</artifactId>
            <version>${spring-cloud-stream.version}</version>
        </dependency>
    </dependencies>

Expected result:
Applying GET method to link localhost:8080/stubs/ will returned stubs of contract tests.
Actual result:
Applying GET method to link localhost:8080/stubs/ returns {}

A: To begin with, why do you set the versions of all of your libraries manually? Please go to start.spring.io, generate a project that will contain the BOMs and those will set the versions automatically for you.
Coming back to the main question I think you should remove
stubrunner:
  work-offline: true

cause it makes no sense - there's no such property anymore.
Please also change
repositoryRoot = "http://artifactory.example.com/artifactory/exampleapp",
to
repositoryRoot = "http://artifactory.example.com/artifactory/libs-snapshot-local",
or sth like this. It has to point to the root of where your JARs can be found. For repo.spring.io that would be e.g. https://repo.spring.io/libs-snapshot-local/
BTW here you have an example of such a server - https://github.com/spring-cloud-samples/stub-runner-boot/
UPDATE: In the presented repository a SPEL expression was used from inside the ids property. It does not seem to be supported ATM.


text:
Q: calculating the gradient of a particular multivariate normal Suppose I have negative twice a log-likelihood of some multivariate normal data: $x_1, \ldots, x_n$. I assume the covariance matrix has a low-rank structure: $LL^\intercal + \Psi$, where $\Psi$ is diagonal, and $L$ is lower-triangular and low rank. The mean vector is $\mu$.
\begin{align}
f(\mu, L, \Psi) &= - 2 \log L(x_1, \ldots, x_n ; \mu, L, \Psi)\\
&= \text{const} + n\log \det(LL^\intercal + \Psi) + \sum_{i=1}^n (x_i - \mu)^\intercal  (LL^\intercal + \Psi)^{-1} (x_i - \mu) \\
&= \text{const} + n\log \det(LL^\intercal + \Psi) + \text{trace}\left[ (LL^\intercal + \Psi)^{-1}\sum_{i=1}^n    (x_i - \mu)(x_i - \mu)^\intercal\right]
\end{align}
I assume that because these matrices lie on a lower-dimensional space, the gradient can be written as
\begin{align*}
\nabla f(\mu, L, \Psi)
&= \begin{bmatrix}
\frac{\partial f}{\partial \mu} \\
\frac{\partial f}{\partial \text{vech} (L)} \\
\frac{\partial f}{\partial \text{diag} (\Psi)}
\end{bmatrix}
\end{align*}
Finding the first block of that vector is straightforward:
\begin{align*}
\frac{\partial f}{\partial \mu}
&=  - 2  (LL^\intercal + \Psi)^{-1}n \bar{x} + 2 n (LL^\intercal + \Psi)^{-1}\mu
\end{align*}
However, I'm stuck on the other two pieces.

A: $
\def\bs{\boldsymbol}
\def\o{{\tt1}}
\def\P{{\Psi}}
\def\M{P^{-1}}
\def\LR#1{\left(#1\right)}
\def\op#1{\operatorname{#1}}
\def\vecc#1{\op{vec}\LR{#1}}
\def\vech#1{\op{vech}\LR{#1}}
\def\diag#1{\op{diag}\LR{#1}}
\def\Diag#1{\op{Diag}\LR{#1}}
\def\trace#1{\op{Tr}\LR{#1}}
\def\qiq{\quad\implies\quad}
\def\qif{\quad\iff\quad}
\def\p{\partial}
\def\grad#1#2{\frac{\p #1}{\p #2}}
\def\c#1{\color{red}{#1}}
\def\CLR#1{\c{\LR{#1}}}
\def\Sk{\sum_{k=1}^n}
$For typing convenience, define the all-ones vector $\o$ and the variables
$$\eqalign{
P &= {\P+LL^T} \\
dP &= d\P+dL\,L^T+L\,dL^T \\
p &= \diag{\P} \qif \P = \Diag{p} \\
h &= \vech{L} = {Ev} \\
v &= \vecc{L} \:= \c{E^Th} \\
}$$
where $E$ is the Elimination Matrix and the last equality
in $\c{\rm red}$ is only true if $L$ is lower triangular.
Replace the vector summation by a matrix whose columns are the {$x_k$} vectors
$$\eqalign{
X &= {\bs[}\,x_1\;x_2\:\cdots\:x_n\,{\bs]} \\
M &= {\bs[}\;\mu\;\;\mu\;\;\cdots\;\;\mu\,{\bs]} \;= \mu\o^T \\
Y &= {M-X} \qiq dY = d\mu\,\o^T \\
Z &= \M Y \\
YY^T &= \Sk \LR{x_k-\mu}\LR{x_k-\mu}^T  \\
}$$
and introduce the Frobenius product, which is a concise
notation for the trace
$$\eqalign{
A:B &= \sum_{i=1}^m\sum_{j=1}^n A_{ij}B_{ij} \;=\; \trace{A^TB} \\
A:A &= \|A\|^2_F \\
}$$
The properties of the underlying trace function allow the terms in a
Frobenius product to be rearranged in many different ways, e.g.
$$\eqalign{
A:B &= B:A \;=\; \vecc{A}:\vecc{B} \\
A:B &= A^T:B^T \\
C:\LR{AB} &= \LR{CB^T}:A = \LR{A^TC}:B \\
\Diag{a}:B &= a:\diag{B} \\
\\
}$$

Write the function using the above notation, then calculate its differential
$$\eqalign{
f &= f_0 + n\log\det(P) + YY^T:\M \\
\\
df
 &= n\,d\LR{\log\det P} + YY^T:{d\M} + \M:d\LR{YY^T} \\
 &= n\LR{P^{-1}:dP}
   \;+\; YY^T:\LR{-\M\,dP\,\M}
   \;+\; \M:\LR{dY\,Y^T+Y\,dY^T} \\
 &= nP^{-1}:\c{dP} \;-\; ZZ^T:\c{dP} \;+\; 2\M Y:dY \\
 &= \LR{nP^{-1}-ZZ^T}:\CLR{d\P+dL\,L^T+L\,dL^T}
   \;+\; 2\M Y:\LR{d\mu\,\o^T} \\
 &= \LR{nP^{-1}-ZZ^T}:d\P
   \;+\; 2\LR{nP^{-1}-ZZ^T}L:dL
   \;+\; 2\M Y\o:d\mu \\
 &= \diag{nP^{-1}-ZZ^T}:dp
   \;+\; 2\vecc{nP^{-1}L-ZZ^TL}:dv
   \;+\; 2\M Y\o:d\mu \\
\\
 &= \diag{nP^{-1}-ZZ^T}:dp
   \;+\; 2\vecc{nP^{-1}L-ZZ^TL}:E^Tdh
   \;+\; 2\M Y\o:d\mu \\
 &= \diag{nP^{-1}-ZZ^T}:dp
   \;+\; 2E\,\vecc{nP^{-1}L-ZZ^TL}:dh
   \;+\; 2\M Y\o:d\mu \\
}$$
Now isolate the respective gradients as
$$\eqalign{
\grad{f}{p} &= \diag{nP^{-1}-ZZ^T} \\
\grad{f}{v} &= 2\vecc{nP^{-1}L-ZZ^TL} \\
\grad{f}{h} &= 2E\,\vecc{nP^{-1}L-ZZ^TL} \\
\grad{f}{\mu} &= 2\M Y\o \\
}$$
Note that
$$E\,\vecc{nP^{-1}L-ZZ^TL}\ne\vech{nP^{-1}L-ZZ^TL}$$
because the matrix argument is not symmetric.


text:
Q: Trying namespaced functions Jquery: Syntax Issue I'm trying to change my approach in writing javascript as I did with PHP. Here is the old code that I check it's working.
$(document).ready(function(){

    var calculatetotalwidth = $('#container').width()
    var calculatesegment = calculatetotalwidth / 5
    var calculaterating = calculatesegment * rating

    $('#ratings .ratingbar').animate({width:calculaterating},1200);
});

It's simply a animation that will mimic a progressbar that will display my rating, by segmenting the width of the content div and divide it by the scope I choose (which is 5/5 in this case).
Here is my OOP approach on the problem.
var RatingsBar = {

    fadeOptions: {
    slow: 5000,
    medium: 2500,
    fast: 1200
    },

    Calculate: function (contaierid, score, scope) {

    $(document).ready(function () {

        var calculatetotalwidth = $(contaierid).width()
        var calculatesegment = calculatetotalwidth / scope
        var calculaterating = calculatesegment * score

        $('#ratings .ratingbar').animate({
        width: calculaterating
        }, RatingsBar.fadeOptions.slow);

    });

    }
}

RatingsBar.Calculate('#container', ratings, 5)

I used the source code pattern in jqueryslideslidemenu plugin. I can't seem to make it work. Am I missing something here?
I got the thing to work. The problem now, is that I need ratings to be used. I took it from a PHP code here:
    class rating_system {

    var $score;

    function __construct($rate) {
        $this->score = $rate;
    }

    function run_rate() {
        $this->phptojava();
        echo $this->displayrate();
    }

    function phptojava() {
        echo '";
    }

    function displayrate() {
        $wrapper = '

';
        $wrapper = $wrapper . '
' . $this->score . '
';
        $wrapper = $wrapper . '
' . '
' . '
' . 'ratings' . '
';
        $wrapper = $wrapper . '

';

        return $wrapper;
    }

}

$view = new rating_system(4);

Thanks everyone. I manage to get it working.

<?php

    class rating_system {

        var $score;

        function __construct($rate) {
            $this->score = $rate;
        }

        function run_rate() {
            $this->phptojava();
            echo $this->displayrate();
        }

        function phptojava() {
            echo '";
        }

        function displayrate() {
            $wrapper = '

';
            $wrapper = $wrapper . '
' . $this->score . '
';
            $wrapper = $wrapper . '
' . '
' . '
' . 'ratings' . '
';
            $wrapper = $wrapper . '

';

            return $wrapper;
        }

    }

    $view = new rating_system(2);
?>

<?php echo $view->run_rate(); ?>

This one is the entire code I'm trying.

A: Try the jsHint codechecker
I have already checked the code for you, here is the report:
http://www.jshint.com/reports/65020
You have missed the round brackets behind the function statement:
Line 4: $(document).ready(function {
Expected '(' and instead saw '{'.

Please fix the syntax-errors and post the code again ;)

A: Maybe this would work, hard to tell without a working test case.
var RatingsBar = {

    fadeOptions: {
    slow: 5000,
    medium: 2500,
    fast: 1200
    },

    Calculate: function (contaierid, score, scope) {
        var calculatetotalwidth = $(contaierid).width();
        var calculatesegment = calculatetotalwidth / scope;
        var calculaterating = calculatesegment * score;

        $('#ratings .ratingbar').animate({
        width: calculaterating
        }, RatingsBar.fadeOptions.slow);
    }
};

$(document).ready(function () {
    RatingsBar.Calculate('#container', Ratings, 5);
});

Try reproducing your problem on jsfiddle.net and post the link.
Edit : What is Ratings supposed to be (second argument in your function call)? Replace Ratings by any value or define a Ratings variable and the code above works.

A: How about the Ratings param? Replace it for one number to see...
RatingsBar.Calculate('#container', 10, 5)

A:     var ratingsBar = {};

    ratingsBar.fadeOptions: {
        slow: 5000,
            medium: 2500,
            fast: 1200
        };

    ratingsBar.calculate: function (contaierid, score, scope) {

            //$(document).ready(function () {

                var calculate

totalwidth = $(contaierid).width(),
                calculatesegment = calculatetotalwidth / scope,
                calculaterating = calculatesegment * score;

            $('#ratings .ratingbar').animate(
                {
                    width:calculaterating
                },
                ratingsBar.fadeOptions.slow
            );

        //});

    };

ratingsBar.calculate('#container', Ratings, 5);

Try this one, it should work. The main problem wast that you bind function to document ready after this event :- )
Another thing is there is missing few semicolons.
I'm not entirely sure that ratingsBar.fadeOptions.slow was defined at this time, so I've changed a little your name spacing.

A: There are numerous typos preventing this to work:
Ratings is undefined in RatingsBar.Calculate('#container', Ratings, 5)
missing semicolons on the var in the Calculate function.
So, I just refactored it to be how I would do it.
var RatingsBar = {
    speeds: {
        slow: 5000,
        medium: 2500,
        fast: 1200
    },
    calculate: function (container, score, outOf) {
        var $container = $(container),
            ratio = score / outOf,
            rating = Math.floor($container.width() * ratio);

        $container.find('.ratingbar').animate({width: rating}, this.speeds.slow);
    }
};

$(document).ready(function () {
    var score = 2,
        outOf = 5;

    RatingsBar.calculate('#container', score, outOf);
});

HTML

#container {
    position: relative;
    height: 30px;
    width: 250px;
    border: 1px solid #cccccc;
    padding: 1px;
}

CSS
#container .ratingbar {
    height: 100%;
    width: 0px;
    background-color: blue;
}

Either way to calculate the width of the .ratingbar works. It just made more sense to me this way.


text:
Q: Consistently assigning electrode nodes in random resistor networks In the context of random resistor networks, the general question of interest is often "what is the effective resistance between two arbitrarily chosen nodes?"
But more specifically about the nodes we choose to assign as electrodes, along which we would measure/compute the resistance, are there generally accepted ways or definitions for how to assign the electrodes?
To be more precise, this can be easily relevant as soon as we have two networks (maybe one is a transformed version of the other), and we are interested in comparing the conductivity (or equivalently) the resistance of the two networks. Then depending on how we proceed to choose the electrode-nodes, we will obtain different results and not be able to meaningfully compare the two networks.
To resolve this, one might adopt some of the following, natural looking, definitions, given a network of \$n\$ nodes and \$m\$ edges (resistors, either uniformly valued or according to another known distribution):

*

*Using the graph diameter nodes: We assign the nodes $i,j$ that are furthest apart as electrodes, i.e., furthest in the sense of the graph distance between them.

*We choose the nodes \$i,j\$ randomly and average over \$x\$ such realizations.

*We choose the nodes \$i,j\$ that are exactly a distance \$d\$ apart, and obtain the resistance as a function of graph distance.
Either of these definitions have an arbitrary aspect to them. For example, if we choose the first definition, then the two networks may have very different diameters, and therefore, we'd be comparing resistances at different distances.
My questions are:

*

*How does one consistently compare the resistance of two networks either by factoring out effect of the choice of electrodes, or by adopting a generally accepted definition for how to assign the electrode nodes?

*Is the dependence of resistance on choice of electrode placement a well studied problem? I haven't been able to pinpoint works that directly tackle this aspect of random resistor networks.


text:
Q: Custom property(list) in propertygrid return ,,Constructor type collection was not found" in C# I have an application in WindowsForms and i use control propertyGrid.
I set a SelectedObject property to my custom object. But one property like this:
[CategoryAttribute("Options"), DescriptionAttribute("")]
[TypeConverter(typeof(Language))]
public List<Language> Languages { get; set; }

return me ,,Constructor type Language was not found"
Other string or enum property work fine.
There is a code of Language class:
public class Language
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Code { get; set; }
        public string ISOCode { get; set; }
        public string LocaleCode { get; set; }

        public Language(int id, string name, string code, string isoCode, string localeCode)
        {
            this.ID = id;
            this.Name = name;
            this.Code = code;
            this.ISOCode = isoCode;
            this.LocaleCode = localeCode;
        }
    }

Thank you for any answer

A: Add a default constructor like this:
public Language()
{
    // Set default values or leave empty
}

A: I try it add previously, but i have same problem.
There is an image.
Translation
Chyba (Error)
Konstruktor typu Nextis.Eshop9.Entities.Language nebyl nalezen.
(Constructor type Nextis.Eshop9.Entities.Language was not found.)
but other properties(string, enum etc.) i can edit.
Property languages


text:
Q: ReactJS - Moving vertical line when hovering over Line chart using chart.js v3.7.1 I am working on the latest version of Chart.js, i.e., v3.7.1. However, I notice that most of the configurations have been changed from those of version 2.x. My problem is that I would like to draw a vertical line everytime there is a mouseover the chart, but not necessary having the mouse on the data points, but can be above or below, as long as the mouse point is in line with a data point, a verical line is drawn. This is clearly illustrated by this code on JSFiddle. I tried this Solution on this platform but it fails to work since it is based on ChartJS v2.6.0. Anyone with an idea of doing this? Here are my codes:
LineChart.js
import React from "react";
import Chart from 'chart.js/auto';
import { Line } from "react-chartjs-2";
import 'chartjs-adapter-moment';

const newOptions = {
    responsive: true,
    plugins: {
        responsive: true,
        title: {
            display: true,
            text: 'Weekly Logs'
        },
    },
    scales: {
        x: {
            type: "time",
            time: {
                displayFormats: {
                    'day': 'dddd'
                }
            }
        }
    },
    interaction: {
        mode: "index",
        axis: 'y'
    }
};

const LineChart = ({ dataChart }) => {
  return <Line
            data={dataChart} options={newOptions}
        />;
};

export default LineChart;

A: You can use a custom plugin for this:

const plugin = {
  id: 'corsair',
  afterInit: (chart) => {
    chart.corsair = {
      x: 0,
      y: 0
    }
  },
  afterEvent: (chart, evt) => {
    const {
      chartArea: {
        top,
        bottom,
        left,
        right
      }
    } = chart;
    const {
      x,
      y
    } = evt.event;
    if (x < left || x > right || y < top || y > bottom) {
      chart.corsair = {
        x,
        y,
        draw: false
      }
      chart.draw();
      return;
    }

    chart.corsair = {
      x,
      y,
      draw: true
    }

    chart.draw();
  },
  afterDatasetsDraw: (chart, _, opts) => {
    const {
      ctx,
      chartArea: {
        top,
        bottom,
        left,
        right
      }
    } = chart;
    const {
      x,
      y,
      draw
    } = chart.corsair;

    if (!draw) {
      return;
    }

    ctx.lineWidth = opts.width || 0;
    ctx.setLineDash(opts.dash || []);
    ctx.strokeStyle = opts.color || 'black'

    ctx.save();
    ctx.beginPath();
    if (opts.vertical) {
      ctx.moveTo(x, bottom);
      ctx.lineTo(x, top);
    }
    if (opts.horizontal) {
      ctx.moveTo(left, y);
      ctx.lineTo(right, y);
    }
    ctx.stroke();
    ctx.restore();
  }
}

Chart.register(plugin)

const options = {
  type: 'line',
  data: {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderColor: 'pink'
      },
      {
        label: '# of Points',
        data: [7, 11, 5, 8, 3, 7],
        borderColor: 'orange'
      }
    ]
  },
  options: {
    plugins: {
      corsair: {
        horizontal: false,
        vertical: true,
        color: 'red',
        dash: [],
        width: 2
      }
    }
  },
}

const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
  <canvas id="chartJSContainer" width="600" height="400"></canvas>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
</body>

For you to use this in react, you only need the Chart.register line like so:
import React from "react";
import Chart from 'chart.js/auto';
import { Line } from "react-chartjs-2";
import 'chartjs-adapter-moment';

const plugin = {
  // Plugin code, see stack snipet above
}

Chart.register(plugin)


text:
Q: PHP file_get_contents doesn't retrieve cookies I've read some topics about this problem..and some people says to use cURL (althought I don't know how..)
I have two files, index.php and response.php.
index.php
/* After the body tag, in the middle of screen */
<?php echo file_get_contents('http://localhost/football/classes/response.php?type=clients'); ?>

This code was working perfectly until I realize that I need to retrieve the same info, but with cookies, when the page loads.
My old response.php file was this:
switch($_REQUEST['type']){
    case 'clients':
        $content = $load->clients();
        echo $content;
        break;
}

But now I need to do the same code but with a parameter, inside the function clients(). This parameter is a cookie.
switch($_REQUEST['type']){
    case 'clients':
        $display = 0;
        if(isset($_COOKIE['display'])){
            $display = 1;
        }
        $content = $load->clients($display);
        echo $content;
        break;
}

I do always receive $display = 0; because PHP doesn't detect the cookie. Although, this cookie is initialized in Chrome Cookies. Even if I do var_dump($_COOKIE); I still don't receive nothing.
I know that this problem is because of file_get_contents() How can I solve this problem?
Thanks.
Edit: Tried the @Martin solution, without success. file_get_contents receive cookies
<?php
    $ckfile = tempnam ("/tmp", "CURLCOOKIE");
    $ch = curl_init ("http://localhost/football/index.php");
    curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec ($ch);

    $ch = curl_init ("http://localhost/football/classes/response.php?type=clients");
    curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
    $output = curl_exec ($ch);

    echo $output;
?>

The page keeps on looping and doesn't stop. It shows nothing.

A: The super global $_COOKIE only contains the cookies that your visitor sent to your Web server when it requested your page, it will never contain the cookies that another server may send to your application when it loads another page.
But you can still retrieves all the response headers using $http_response_header.
More info in the PHP doc : $http_response_header


text:
Q: Turn on Gps with cordova periodically I want to create an app with cordova that must turn on and turn off the gps periodically, the user must not active gps manually. Is it possible and how can I do?

A: You can use this  cordova plugin to turn on GPS location manually
Call this methods of plugins periodically as whenever you want to
   access fine location or configure as per your needs.
function calldialog() {
      document.addEventListener("deviceready",function() {
      cordova.dialogGPS("Your GPS is Disabled, this app needs to be enable to      works.",//message
                    "Use GPS, with wifi or 3G.",//description
                    function(buttonIndex){//callback
                      switch(buttonIndex) {
                        case 0: break;//cancel
                        case 1: break;//neutro option
                        case 2: break;//user go to configuration
                      }},
                      "Please Turn on GPS",//title
                      ["Cancel","Later","Go"]);//buttons
     });
     }

A: You can't turn on the location service automatically because its related to user privacy. So whenever you want to turn on the location service you must required the user permission. Following plugin may use full to u to turn on the location service with user permission.
https://github.com/rodrigo-martinezd/cordova-dialog-gps


text:
Q: redirect browser window from expressjs after qr code authentication request made from android phone
*

*Android app was developed using ionic framework.

*I have an authenticated user on my android phone using jwt token stored in local storage.

*I have a web application which authenticates user when they scan the qr code from their android app.

*On successfull scan from the android phone.I make an ajax call to the server with jwt token (set on req.headers.authorization using $httpProvider) and qr scanned code.

Android(Ionic Framework) app ajax call code

$scope.scanqr = function () {
  cordova.plugins.barcodeScanner.scan(
    function (result) {
      $http({
        url:'http://localhost:3000/',
        method:'POST',
        data:{
          //qr code result.text
          unique: result.text
        }
      })
        .success(function () {
          alert("Authenticated in WebApp");
        });
    },
    function (error) {
      alert("Scanning failed.Try Again");
    }
  );
};

Server Code running on http://localhost:3000/ This is the route in which I receive the request and process it.

router.post('/', function(req, res) {
    if (req.headers.authorization && req.body.unique) {
        Code.findOne({
            unique:req.body.unique
        }, function (err,code) {
            if(code){
                var query = Code.remove({unique: req.body.unique});
                query.exec();
                var token = req.headers.authorization;
                req.session.token = token;
                res.cookie('auth',token);
                res.redirect('/dashboard');
            }else{
                res.redirect('/');
            }
        })
    }
});

I know that redirection doesn't happen because the request was made by the phone not by the browser.Is there any way to redirect the browser ?

I tried socket.io by emitting the token and saving it in browsers local storage.But the drawback is that I'm emitting the token to everyone.If multiple browsers were opened with the webapp all the windows are authenticated and I cannot emit to a particular browser also as I do not know any details of the requestor.
Are there any possible solutions for this problem ?


text:
Q: Variables in files included by bootstrap.php in cakephp seem not to be defined I am including a file in bootstrap.php like this
include('files/settings.php');

The settings.php file contains
    $var= "value";
    function myFunction(){
        echo "myFunction echo";
    }

Now, in one of my templates I try to use the function and the variable.
The problem is that while the function is working as expected, when I try to print the variable i get a "not defined" notice.
I use CakePHP 2.1.3
Thank you!

A: When defined like this, the variable is a global.
You have to import it in the function where you want to use it, like this:
function globalVariableUsingFunction() {
    global $var;
    echo $var;
}

More info in the php doc
EDIT: Based on the comments, this is CakePHP specific behavior: from this thread

File bootstrap is included in method Configure::__loadBootstrap() so
  You have to mark Your global variables by keyword 'global' as global -
  otherwise they are valid only in scope inside of above mentioned
  method.

So, modifying your bootstrap.php like this
global $var= "value";
function myFunction(){
    echo "myFunction echo";
}

should do the trick.


text:
Q: parsing the pdf file using PyPDF 2  by asynchronously what I mean to say is as you can see in the second screenshot, the address and phone details are getting mixedI have a task to parse a pdf file using python scripting with some specific attributes. I have to fetch first name, last name, address and email. I have done the below.
from PyPDF2 import PdfFileReader
f = open('CV_Smith.pdf', 'rb')
reader = PdfFileReader(f)
contents = reader.getPage(0).extractText()
f.close()
print(contents)

but getting a problem because the text is coming asynchronously and difficult to process.
screenshots of given pdf.

thank you in advance.

A: pypdf (and also PyPDF2) improved a lot since you asked the question. It might now work as you want.
However, what you want might not be possible without heuristics. You want a semantic extraction / "boxing" of text fragments. This information is not within the PDF. In the worst case, every single letter is absolutely positioned on the PDF. Without giving any hint which letters belong to the same word - yet to the same "block" of text.


text:
Q: DateFormat Parsing Error I have a date coming in. So for example 02/16/2012. What I need to do in order to work with my database format is convert it to 2012-02-16. I figured this would be pretty straightforward. But I can't work it. Here is my date parser.
String endDateString = "02/16/2012"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd");
endDate = dateFormat.parse(endDateString)

Any suggestions? Thanks.

A: What you want to do is parse the incoming format to a Date object
final SimpleDateFormat idf = new SimpleDateFormat("MM/dd/yyyy");
final Date indate = idf.parse("02/16/2012");

then reformat the Date object to the format you desire
final SimpleDateFormat odf = new SimpleDateFormat("yyyy-MM-dd");
final String s = odf.format(indate);

A: You should parse it FROM one correct format, then convert TO string with another correct format. What are you doing -- is trying to interpret date in MM/dd/yyyy format with yyyy-MM-dd format, i.e. incorrect.
SAMPLE
public static void main(String[] args) throws ParseException {

    SimpleDateFormat sourceFormat = new SimpleDateFormat("MM/dd/yyyy");
    SimpleDateFormat destinationFormat = new SimpleDateFormat("yyyy-MM-dd");

    String sourceDateString = "02/16/2012";
    String destinationDateString;

    Date dat; // this object stores "perfect" date object

    // interpreting string with input format and converting it to date
    dat = sourceFormat.parse(sourceDateString);

    // expressing date object as string in destination format
    destinationDateString = destinationFormat.format(dat);

    System.out.format("Done from %s to %s\n", sourceDateString, destinationDateString));

}

A: The date-format you specify has to match the date-format of your input like so:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");

A: This snippet can tell you how to get it done.
SimpleDateFormat inputDateFormat = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat outputDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String endDateString = "02/16/2012";
String endDate =     outputDateFormat.format(inputDateFormat.parse(endDateString));

Reference: SimpleDateFormat

A: You can also convert a date at the database level. For example MySQL has a function STR_TO_DATE. In your case it would be STR_TO_DATE('02/16/2012','%m/%d/%Y')

A: You are parsing with wrong format
new SimpleDateFormat("MM/dd/yyyy");


text:
Q: What is the maximum of the product of three numbers' factorials whose sum is a given number? Suppose $x,y,z$ are very large numbers. If $x+y+z=N$, is there a maximum value of $x!y!z!$?
What I have tried is using the Stirling approximation:
$$\ln x!y!z!=x\ln x + y\ln y + z \ln z - x - y - z.$$
The second part is $N$, but I got stuck calculating the maximum of the first term.

A: Write out the product to see that $(n-2)! 1! 1!$ is always the largest.
If you allow $a|b|c = 0$ then $n! 0! 0!$ is the largest.
Consider just with two components, $a$ and $b$:
Which is larger?
$$\underbrace{n \cdot (n-1) \cdots (n-a+1)}_{a~elements} \underbrace{(n-a) \cdot (n-a-1) \cdots 1}_{b~elements}$$
or
$$((n-a) \cdot (n-a-1) \cdots 1 )((n-b) \cdot (n-b-1) \cdots 1)?$$


text:
Q: fetching only Character of email from address book i have used following code for getting for getting information from address book
ABRecordRef ref = CFArrayGetValueAtIndex(allPeopleName, i );
        NSString* personName = (__bridge_transfer NSString*) ABRecordCopyValue(ref, kABPersonFirstNameProperty);
        NSDate* Date = (__bridge_transfer NSDate*) ABRecordCopyValue(ref, kABPersonBirthdayProperty);
         **NSString* personEmail = (__bridge_transfer NSString*) ABRecordCopyValue(ref, kABPersonEmailProperty);**
          NSString *birthdayDate = [dateFormat stringFromDate:Date];
        **NSLog(@"personEmail%@",personEmail);**

// this is what personaEmail prints
personEmailABMultiValueRef 0x8a64740 with 2 value(s)
    0: $!!$ (0x8a2bea0) - miou@yahoo.in (0x8a41df0)
    1: $!!$ (0x8a423c0) - minadi@yahoo.com (0x8a64720)
        ABMultiValueRef phones = (ABMultiValueRef)ABRecordCopyValue(ref, kABPersonPhoneProperty);
        NSString* mobile=@"";
        NSString* mobileLabel;
        for (int i=0; i < ABMultiValueGetCount(phones); i++) {
            //NSString *phone = (NSString *)ABMultiValueCopyValueAtIndex(phones, i);
            //NSLog(@"%@", phone);
            mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
            if([mobileLabel isEqualToString:(NSString *)kABPersonPhoneMobileLabel]) {
                NSLog(@"mobile:");
            } else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhoneIPhoneLabel]) {
                NSLog(@"iphone:");
            } else if ([mobileLabel isEqualToString:(NSString*)kABPersonPhonePagerLabel]) {
                NSLog(@"pager:");
            }
            [mobile release];
            mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
            NSLog(@"%@", mobile);
            NSCharacterSet* charactersToRemove = [[NSCharacterSet decimalDigitCharacterSet] invertedSet] ;
            mobile = [[mobile componentsSeparatedByCharactersInSet:charactersToRemove] componentsJoinedByString:@""] ;

    }

now my question are
  how can i get only email from that all other stuff
  i always want only one email id not two how can i get only home email id? doesnt matter how many email ids are there in address book

A: personEmail (or, more correctly, the return value of ABRecordCopyValue(ref, kABPersonEmailProperty)) isn't a NSString.  Look at the log message - it's a ABMultiValueRef.
You will want to use the methods described in this documentation to access individual components.

A:    This will print all the email id. You can take the necessary one.

  NSString *email;
  CFStringRef value, label;
   ABMutableMultiValueRef multi = ABRecordCopyValue(person, kABPersonEmailProperty);
    CFIndex count = ABMultiValueGetCount(multi);
  if (count == 1)
  {
    value = ABMultiValueCopyValueAtIndex(multi, 0);
    email = (__bridge NSString*) value;
    NSLog(@"EmailID   %@",email);
    CFRelease(value);
}
else
{
    for (CFIndex i = 0; i < count; i++)
    {
        label = ABMultiValueCopyLabelAtIndex(multi, i);
        value = ABMultiValueCopyValueAtIndex(multi, i);

        // check for Work e-mail label
        if (CFStringCompare(label, kABWorkLabel, 0) == 0)
        {
            email = (__bridge NSString*) value;
            NSLog(@"EmailID   %@",email);
        }

        // check for Home e-mail label
        else if(CFStringCompare(label, kABHomeLabel, 0) == 0)
        {
            email = (__bridge NSString*) value;
            NSLog(@"EmailID   %@",email);
        }

        CFRelease(label);
        CFRelease(value);
      }
  }
   CFRelease(multi);


text:
Q: Programmatically create SharePoint 2010 content type using XML definition file Is there any way to programmatically create a SharePoint 2010 content type using an XML definition file?
SPFields can be added in the following way:
SPContext.Current.Web.Fields.AddFieldAsXml("<xml />");

Is there any similar way to programmatically add content types to a site collection/site?

A: You can programmatically create/add content types, but not using XML definition (as far as I'm aware). You have to construct it, add it to a content type collection, and manually add your field references to the field links collection.
A rough example would be:
using (SPSite site = new SPSite("http://localhost"))
{
    using (SPWeb web = site.OpenWeb())
    {
        SPContentType contentType = new SPContentType(web.ContentTypes["Document"], web.ContentTypes, "Financial Document");
        web.ContentTypes.Add(contentType);
        contentType.Group = "Financial Content Types";
        contentType.Description = "Base financial content type";
        contentType.FieldLinks.Add(new SPFieldLink(web.Fields.GetField("OrderDate")));
        contentType.FieldLinks.Add(new SPFieldLink(web.Fields.GetField("Amount")));
        contentType.Update();
    }
}

You don't get to control the content type IDs this way though. I prefer using features as per Greg Enslow's response.

A: The most common way is to use a feature definition and then activate the feature for your site collection. The xml for the feature will look something like this:
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
   <!-- Parent ContentType: Document (0x0101) -->
  <ContentType ID="0x0101000728167cd9c94899925ba69c4af6743e"
               Name="Financial Document"
               Group="Financial Content Types"
               Description="Base financial content type"
               Version="0">
    <FieldRefs>
      <FieldRef ID="{1511BF28-A787-4061-B2E1-71F64CC93FD5}" Name="OrderDate" DisplayName="Date" Required="FALSE"/>
      <FieldRef ID="{060E50AC-E9C1-4D3C-B1F9-DE0BCAC300F6}" Name="Amount" DisplayName="Amount" Required="FALSE"/>
    </FieldRefs>
  </ContentType>
</Elements>

See the full sample at http://msdn.microsoft.com/en-us/library/ms463449.aspx.
Was there a specific reason you were trying to use the object model instead?


text:
Q: Как преобразавать обьект класса в list? Мне нужно автоматически фиксировать появление обьектов класса
class InstaPost:

        def __init__(self, who, image, who_image="gui/oPhone/contacts/default.png", where=None, comments=[], like=False, answer_variants={}):

            self.who = who
            self.image = image
            self.who_image = who_image

            self.where = where or ""
            self.comments = comments

            self.my_answer = None
            self.like = like

            self.answer_variants = []

            for answer_variant_name, answer_variant in answer_variants.items():

                answer_variant = answer_variant if isinstance(answer_variant, (list, tuple, set)) else [answer_variant]

                self.answer_variants.append( AnswerOnPost(self, answer_variant_name, *answer_variant) )

Я хочу сохранять все атрибуты обьектов во внешний список ввиде вложеного листа.
Но not_object = list(post)
Выдает ошибку TypeError: "InstaPost" object is not iterable
Были похожие вопросы с решением реализовать методы __iter__, __getitem__ и keys
Не совсем понятно как это сделать тут.


text:
Q: Failed to start recording, [TypeError: undefined is not an object (evaluating '_ExponentAV.default.requestPermissionsAsync')] when I used expo audio to record audio, always has error:
Failed to start recording, TypeError: undefined is not an object evaluating '_ExponentAV.default.requestPermissionsAsync'
at node_modules\expo\build\environment\react-native-logs.fx.js:27:23 in error
at src\components\Chat\ChatForm.tsx:189:19 in startRecording
import React, { useState } from "react";

import { Audio } from "expo-av";

type ChatFormProps = {
  onSend: () => void;
};

const ChatForm: React.FC<ChatFormProps> = ({ onSend }) => {

const [isRecording, setIsRecording] = useState(false);
const [recordTime, setRecordTime] = useState<string>("00:00");

const recording = new Audio.Recording();

  const startRecording = async () => {
    try {
      console.log("Requesting permissions..");
      // console.log(Audio);
      await Audio.requestPermissionsAsync();
      await Audio.setAudioModeAsync({
        allowsRecordingIOS: true,
        playsInSilentModeIOS: true,
      });

      console.log("Starting recording..");
      await recording.prepareToRecordAsync(
        Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY
      );
      await recording.startAsync();
      setIsRecording(!isRecording);
      console.log("Recording started");
    } catch (err) {
      console.error("Failed to start recording", err);
    }
  };

  const stopRecording = async () => {
    try {
      console.log("Stopping recording..");
      setIsRecording(!isRecording);
      await recording.stopAndUnloadAsync();
      const uri = recording.getURI();
      console.log("Recording stopped and stored at", uri);
    } catch (err) {
      console.error("Failed to stop recording", err);
    }
  };
}

A: try to initialize your recording inside the try bloc
const startRecording = async () => {
    try {
      console.log("Requesting permissions..");
      // console.log(Audio);
      await Audio.requestPermissionsAsync();
      await Audio.setAudioModeAsync({
        allowsRecordingIOS: true,
        playsInSilentModeIOS: true,
      });

const recording = new Audio.Recording();

      console.log("Starting recording..");
      await recording.prepareToRecordAsync(
        Audio.RECORDING_OPTIONS_PRESET_HIGH_QUALITY
      );
      await recording.startAsync();
      setIsRecording(!isRecording);
      console.log("Recording started");
    } catch (err) {
      console.error("Failed to start recording", err);
    }
  };

  const stopRecording = async () => {
    try {
      console.log("Stopping recording..");
      setIsRecording(!isRecording);
      await recording.stopAndUnloadAsync();
      const uri = recording.getURI();
      console.log("Recording stopped and stored at", uri);
    } catch (err) {
      console.error("Failed to stop recording", err);
    }
  };
}


text:
Q: How to keep JPA Fetch child data when using CompletableFuture? Hi i trying to multithreading my function that execute queries with different condition, but i think JPA lost it's persistent bag while i am doing it, since the data won't show up and i got an error. I will start with my synchronous code first since it work, and i will show my async code that not work.
here is my Entity class :
TransSalesOrder class
@OneToMany(mappedBy = "transSalesOrder")
private List<TransDeliveryOrder> transDeliveryOrder;

TransDeliveryOrder class
@OneToMany(mappedBy = "deliveryOrder", orphanRemoval = true, cascade = CascadeType.ALL)
private List<TransDeliveryOrderDetail> transDeliveryOrderDetail;

@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "transSalesOrderId")
private TransSalesOrder transSalesOrder;

and here is TransDeliveryOrderDetail class :
@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "delivery_order_id", referencedColumnName = "id")
private TransDeliveryOrder deliveryOrder;

Here is my synchronous way that work :
this is my function, that execute 3 others function :
public List<TransSalesOrderOnlyResponseDto> findUnAssignedSO() {
    List<TransSalesOrderOnlyResponseDto> transSalesOrdersResponseNew = findSOHaveItemLeftOverOnly();
    transSalesOrdersResponseNew.addAll(findPureUnAssignedSO());
    transSalesOrdersResponseNew.addAll(findSalesOrderWithBpsjInDeliveryOrder());

    return transSalesOrdersResponseNew;
}

and here is 3 function that executed :
private List<TransSalesOrderOnlyResponseDto> findSOHaveItemLeftOverOnly() {
    List<TransSalesOrder> transSalesOrders = iTransSalesOrderQdslRepository.findSOHaveLeftOverButDone();
    return buildTransSalesOrdersResponseNew(transSalesOrders);
}

private List<TransSalesOrderOnlyResponseDto> findPureUnAssignedSO() {
    return iSalesOrderMapper.entityToSOOnlyDto(iTransSalesOrderQdslRepository.findUnAssignedSalesOrder());
}

private List<TransSalesOrderOnlyResponseDto> findSalesOrderWithBpsjInDeliveryOrder() {
    List<TransSalesOrder> transSalesOrders = iTransSalesOrderQdslRepository.findSalesOrderWithBpsjInDeliveryOrder();

    return buildTransSalesOrdersBpsjOnlyResponseNew(transSalesOrders);
}

in this way is worked, but then i try to async my 3 method since 3 of my function can execute in async way, they don't have to wait each other to complete
here is my Asynchronous way using CompletableFuture :
public List<TransSalesOrderOnlyResponseDto> findUnAssignedSO() {
    List<TransSalesOrderOnlyResponseDto> transSalesOrdersResponseNew = new ArrayList<>();

    findSOHaveItemLeftOverOnly()
            .thenAccept( transSalesOrdersResponseNew::addAll )
            .thenCompose( v -> findPureUnAssignedSO() )
            .thenAccept( transSalesOrdersResponseNew::addAll )
            .thenCompose( v -> findSalesOrderWithBpsjInDeliveryOrder() )
            .thenAccept( transSalesOrdersResponseNew::addAll )
            .join();

    return transSalesOrdersResponseNew;
}

private CompletableFuture<List<TransSalesOrderOnlyResponseDto>> findSOHaveItemLeftOverOnly() {
    return CompletableFuture.supplyAsync(() -> {
        List<TransSalesOrder> transSalesOrders = iTransSalesOrderQdslRepository.findSOHaveLeftOverButDone();
        return buildTransSalesOrdersResponseNew(transSalesOrders);
    });
}

private CompletableFuture<List<TransSalesOrderOnlyResponseDto>> findPureUnAssignedSO() {
    return CompletableFuture.supplyAsync(() -> iSalesOrderMapper.entityToSOOnlyDto(iTransSalesOrderQdslRepository.findUnAssignedSalesOrder()));
}

private CompletableFuture<List<TransSalesOrderOnlyResponseDto>> findSalesOrderWithBpsjInDeliveryOrder() {
    return CompletableFuture.supplyAsync(() -> {
        List<TransSalesOrder> transSalesOrders = iTransSalesOrderQdslRepository.findSalesOrderWithBpsjInDeliveryOrder();

        return buildTransSalesOrdersBpsjOnlyResponseNew(transSalesOrders);
    });
}

when i run my findUnAssignedSO function, i got this error :

org.hibernate.LazyInitializationException: failed to lazily initialize
a collection of role:
com.bit.microservices.b2b.warehouse.entity.TransSalesOrder.transSalesOrderDetail,
could not initialize proxy - no Session

when i debug it, i found the child data is not loaded, here is the option i try :

*

*i trying to keep the JPA attach using @Transactional, it's not working.

*i don't want change my fetchType in @OneToMany relation to EAGER, i read all around internet that will have performance issue later

*Using Set insted of List, this will cause performance issue too

i didn't show my repository since i use JpaRepository and QueryDSL, which is mixed, but i am open for any solution doesn't need to attached to QueryDSL. How can i fetch the data properly?

A: Fetch performance is a difficult topic and I totally understand that you don't want to change the fetch type or mode on entity level. Usually, this can be solved by using entity graphs for defining a graph of associations to fetch which are per-query. In your particular case, the problem is that the threads do not fetch all the state that is later needed. When you access that state later in a different thread, the proxy has no reference to a persistence context anymore (because it's bound to a transaction/thread) and fails with the LazyInitializationException you are seeing. You can solve this by using an entity graph so that no lazy loading happens, or by enabling the hibernate.enable_lazy_load_no_trans property which will create a session on-demand for fetching the data, but I think this is a perfect use case for Blaze-Persistence Entity Views.
I created the library to allow easy mapping between JPA models and custom interface or abstract class defined models, something like Spring Data Projections on steroids. The idea is that you define your target structure(domain model) the way you like and map attributes(getters) via JPQL expressions to the entity model.
A DTO model for your use case could look like the following with Blaze-Persistence Entity-Views:
@EntityView(TransSalesOrder.class)
public interface TransSalesOrderOnlyResponseDto {
    @IdMapping
    Long getId();
    String getName();
    List<TransDeliveryOrderDto> transDeliveryOrder;

    @EntityView(TransDeliveryOrder.class)
    interface TransDeliveryOrderDto {
        @IdMapping
        Long getId();
        String getName();
    }
}

Querying is a matter of applying the entity view to a query, the simplest being just a query by id.
TransSalesOrderOnlyResponseDto a = entityViewManager.find(entityManager, TransSalesOrderOnlyResponseDto.class, id);
The Spring Data integration allows you to use it almost like Spring Data Projections: https://persistence.blazebit.com/documentation/entity-view/manual/en_US/index.html#spring-data-features
Page<TransSalesOrderOnlyResponseDto> findAll(Pageable pageable);

The best part is, it will only fetch the state that is actually necessary!


text:
Q: How can I simulate a ssh session on a client behind a NAT? Quick question:
How can I simulate a ssh session, that I can use to run commands on a client behind a NAT, that uses only program installed by default on most operating systems (telnet...).
Long version:
I got this problem from this story: a friend of mine got her linux broken. She wasn't able to install anything, and I wanted to run commands on her computer to solve the problem (it's really not practical to say "type this", "what is written ?", "ok, now type this"...). The thing is that she does not have open-ssh-server installed, and she is behind a NAT proxy. Hopefully, I have a server with a public ip.
So I came out with this first solution. On the server side, I run (nc is also named netcat sometimes):
nc -l -p 23456

and on the client side, I run these commands to create a double pipe between netcat and bash. NB : I could use telnet instead of netcat here if netcat is not installed:
mkfifo fifo0
nc <server ip> 23456 < fifo0 | sh > fifo0

Then, I just need to type the commands on the server, and I get the answer directly. However, it does not work well with complex applications such as vim/emacs/screen that needs to run inside a tty. I though that I could use socat to deal with that, but actually I don't really understand how the tty works (I cannot even link a bash session to a tty)... So here is my question: how could I improve (or change) what I did, in order to provide also a working session for application that needs to run in a tty ? I also would like to use the most basic applications as possible, I want to use only the application installed by default on most operating system (debian and ubuntu for example).
EDIT 1
I found a first solution. For now it has one problem: it does not handle the Ctrl-... keys (I need to find a way not to escape these chars I guess), and it needs socat installed (which is not installed by default):
on the server:
socat READLINE,history=/tmp/my_history TCP-LISTEN:23456

on the client:
socat PTY,link=/tmp/socat.pty TCP:185.107.80.185:23456 &
sleep 1 && ( setsid bash ) </tmp/socat.pty >/tmp/socat.pty 2>&1

EDIT 2
I found a way to avoid the problem of Ctrl-... keys, by logging using screen (works also with minicom...) on the server. It still has the problem of needing socat installed on the client machine. Here are all the commands:
On the server:
socat PTY,link=/tmp/socat.pty TCP-LISTEN:<server port> &
screen /tmp/socat.pty

on the client:
socat PTY,link=/tmp/socat.pty TCP:<server ip>:<server port>
sleep 1 && ( setsid bash ) </tmp/socat.pty >/tmp/socat.pty 2>&1

Now, I'm curious if it's possible to do the same thing with just telnet installed.


text:
Q: Splitting a AT command string using sscanf() I have a problem with splitting a string using sscanf() in C.
I have
char sms[]="AT+CMGR=7+CMGR: \"REC UNREAD\",\"+213552830677\",\"\",\"14/11/29,21:20:36+04\"123456Cn50555202555";

and I want to get
char number[15] = "+213552830677";
char code[6] = "123456 ";
char cmd[2] = "Cn";
char arg[20] = "50555202555";

I use this code to do the split and print the results:
sscanf(sms,"AT+CMGR=8+CMGR: \"REC UNREAD\",\"+%12s\",\"\",\"14/11/29,21:20:36+04\"%6s%2s%s",tmp ,number ,code ,cmd ,arg);
printf("Temp: %s\r\nNumber: %s\r\nCode: %s\r\nCommand: %s\r\nArgument: %s\r\n",tmp ,number ,code ,cmd ,arg);

A: *

*In the sscanf format you forgot a conversion specification for the argument tmp; thus the input is assigned to the wrong objects.

*char code[6] and char cmd[2] are one short of space for the terminating null character, thus possibly other objects are overwritten.

After correcting these errors, e. g.
    char code[6+1];
    char cmd[2+1];
    char tmp[1+1];
    sscanf(sms, "AT+CMGR=%1s+CMGR: \"REC UNREAD\",\"+%12s"
                "\",\"\",\"14/11/29,21:20:36+04\"%6s%2s%s",
                tmp, number, code, cmd, arg);

it works.


text:
Q: Laravel 6 with Digital Ocean Managed Redis I'm having trouble connecting to my managed DO Redis db, and cannot find any accounts of it being successfully used. Has anyone had experience with this and could shed some light on it?
I've changed the database credentials, cleared the config etc, but get
 [Symfony\Component\Debug\Exception\FatalThrowableError] Call to a member function connect() on null


text:
Q: How to set text output alignment in MySQL Data export? This is the SQL query
$query = "SELECT col1,col2,col3,col4,col5,col6,col7,col8 FROM table;
if (!$result = mysqli_query($con, $query))
{
    exit(mysqli_error($con));
}

This is the part that outputs the text file
$filename = "output.txt";
$file = fopen($filename, "w");
foreach ($result as $rows)
{
    fwrite($file, implode("\t",$rows).PHP_EOL);
}

header('Content-Description: File Transfer');
header('Content-type: text/tab-separated-values');
header('Content-Disposition: attachment; filename="'.basename($filename).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($filename));
readfile($filename);
exit;

This is the current output:
 This is the output that I need:

A: As commented out by @Slava Rozhnev and best way is to use csv like this:
<?php

$query = "SELECT col1,col2,col3,col4,col5,col6,col7,col8 FROM table";
$result = mysqli_query($con, $query);

$fp = fopen('file.csv', 'w');

while( $row = mysqli_fetch_array($result, MYSQLI_ASSOC) ) {
    fputcsv($fp, $row);
}

fclose($fp);


text:
Q: Display yAxis label on a diagonal line I get example from highcharts :
I'd like to make yAxis label ( 0k,50k..in example) not in vertical line

but on a diagonal line like this image

I've been search on highchart's docs but could not found some attribute to do that on yAxis label or maybe I'm wrong ,I've tried some attribute on highchart's docs but still no luck
yAxis: {
    gridLineInterpolation: 'polygon',
    lineWidth: 0,
    min: 0,
    labels: {
      ...
    }
},

Please suggest how to do that
Many thanks !

A: You can rotate whole graph using pane.startAngle, see: http://jsfiddle.net/xEAxK/381/
Or wrap method responsible for positioning that points and edit radius to use different than axis.startAngleRad: http://jsfiddle.net/xEAxK/385/
Code:
(function (H) {
    H.wrap(H.Tick.prototype, 'getLabelPosition', function (proceed, x, y, label, horiz, labelOptions, tickmarkOffset, index, step) {
        var rot = this.axis.isXAxis ? this.axis.startAngleRad : -2.5 * Math.PI / 4,
            origRot = this.axis.startAngleRad,
            axis = this.axis,
            optionsY = labelOptions.y,
            ret;

        axis.startAngleRad = rot;

            centerSlot = 20, // 20 degrees to each side at the top and bottom
            align = labelOptions.align,
            angle = ((axis.translate(this.pos) + rot + Math.PI / 2) / Math.PI * 180) % 360;

        if (axis.isRadial) {
            ret = axis.getPosition(this.pos, (axis.center[2] / 2) + H.pick(labelOptions.distance, -25));

            // Automatically rotated
            if (labelOptions.rotation === 'auto') {
                label.attr({
                    rotation: angle
                });

                // Vertically centered
            } else if (optionsY === null) {
                optionsY = axis.chart.renderer.fontMetrics(label.styles.fontSize).b - label.getBBox().height / 2;
            }

            // Automatic alignment
            if (align === null) {
                if (axis.isCircular) {
                    if (this.label.getBBox().width > axis.len * axis.tickInterval / (axis.max - axis.min)) { // #3506
                        centerSlot = 0;
                    }
                    if (angle > centerSlot && angle < 180 - centerSlot) {
                        align = 'left'; // right hemisphere
                    } else if (angle > 180 + centerSlot && angle < 360 - centerSlot) {
                        align = 'right'; // left hemisphere
                    } else {
                        align = 'center'; // top or bottom
                    }
                } else {
                    align = 'center';
                }
                label.attr({
                    align: align
                });
            }

            ret.x += labelOptions.x;
            ret.y += optionsY;

        } else {
            ret = proceed.call(this, x, y, label, horiz, labelOptions, tickmarkOffset, index, step);
        }
        axis.startAngleRad = origRot;
        return ret;
    });
})(Highcharts);


text:
Q: The use of the word "disjunction" in a sentence I am not a native English speaker. I have been given the task of reviewing a text written in English. I wonder if I by the following use of the word "disjunction", make myself guilty of the very same crime I accuse my reviewee of, namely that he is using a particular word in a wrong way, simply to portray himself as being eloquent. I claim that "quantitative is used in disjunction to qualitative".

A: You're simply looking for

contrast

or indeed

opposite

"quantitative is used in contrast to qualitative"
"quantitative is the opposite of qualitative"
As you say, "wanted to let the respondent know that quantitative is most often used as meaning the opposite of qualitative when collecting data".
There is no disjunction, whatsoever, between "quantitative" and "qualitative". They are just two words.  A disjunction is a "thing" - rather like these "things": "a debate", "tension in the air", "a war", "an ongoing argument".
Please note that your sentence

"quantitative is most often used as meaning the opposite of qualitative when collecting data"

is perfectly correct and accurately explains that quantitative is most often used as meaning the opposite of qualitative when collecting data.


text:
Q: Fetch method Formpara Javascript this is my jersey server, REST api using java
    @POST
        @Produces({MediaType.APPLICATION_JSON})
        @Path("registration")
        public User register(@FormParam("username") String userName, @FormParam("password") String password) {

            boolean isOk = true;
            User newUser =null;
            List<User> userList = em.createNamedQuery("User.findAll").getResultList();
            for(User user: userList){
                    if(user.getUsername().equals(userName)){
                    isOk = false;
                }
            }
            if(isOk == true){
                newUser = new User();
                newUser.setUsername(userName);
                newUser.setPassword(password);
                super.create(newUser);
            }

            return newUser;
        }

I use javascript to POST new user to the server via formdata
  buttonLogin.addEventListener('click', (evt) => {
  evt.preventDefault();
  console.log('login');

  const  imgData = new FormData();
  imgData.append('username', 'newuser');
  imgData.append('password', '123');

  for (var p of imgData) {
  console.log(p);
}
  //
  let url = endPointUrl + `webresources/users/registration`;
  const myHeader = new Headers({'Content-Type':"application/x-www-form-urlencoded"});

  fetch(url, {
    method: 'POST',
    headers: myHeader,
    data: imgData
  })
  .then(json)
  .then((data) => {
    console.log(data);
      });
});

My server did receive formparam but it is null object. I expect that the server will receive username: "newuser" and password "123" but server receive null object
I test server with postman and everything is ok. So I assume that the problem is javascript code.
Could you show me what is wrong with my code. Thank


text:
Q: Not receiving WM_NCHitTest on title bar I noticed that the message WM_NCHitTest isn't sent to a form when the cursor is inside the caption bar (not on the border).
I tried to intercept it using either
procedure WMNCHitTest(var Message: TWMNCHitTest); message WM_NCHITTEST;

or
procedure WndProc(var Message: TMessage); override;

According to MSDN I was expecting to receive it for any point, with no blind spots.
Did I miss something or this is the intended behaviour?
I'm using Delphi 2010 on Windows 7, with Aero on.

A: Yes -- that's expected. Unless you disable the DWM, you won't get WM_NCHITTEST messages when the cursor is in the title bar. Basically, when the DWM is on, the title bar "belongs" to the DWM, not your application.
If you really need those messages, you can disable the DWM -- but keep in mind that when/if you do this, it does not just disable it for your application. If you disable it, it's disabled for the whole system (until it's re-enabled again, of course).

A: There might be an alternative message you can listen to... see http://social.msdn.microsoft.com/Forums/en-US/windowsuidevelopment/thread/9a8a63c8-79b5-43a8-82eb-f659be947add

A: You can always use the WM_NCMOUSEMOVE message and test for its HitTest property:
procedure WMNCMouseMove(var Message: TWMNCMouseMove); message WM_NCMOUSEMOVE;

[...]
procedure TForm11.WMNCMouseMove(var Message: TWMNCMouseMove);
begin
  with Message do
    if HitTest = HTCAPTION then
      Caption := Format('%d:%d',[XCursor,YCursor]);
end;


text:
Q: PySide (Qt): How to set background color of button's tooltip? I've just got a fast question:
How to set a color  of button's tooltip?
code
    btnExample = QtGui.QPushButton('Example button', self)
    btnExample.setStyleSheet("color: rgb(0, 255, 0)")
    btnExample.clicked.connect(function_of_button)
    btnExample.setToolTip('Animated splines toolkit') # I'd like to change colors here

It's PySide, Python, I've got light gray text on button, so the text on tooltip is also light.
I've got to change it's background to black


text:
Q: Getting the error "AttributeError: 'NoneType' object has no attribute 'shape'" when implementing Atari Breakout I have made a code to solve Atari Breakout. I am facing a little problem, but I can't say what it is.
Here is the code
It is a problem with the replay memory.
try:
    next_states = torch.tensor(batch[3], dtype=torch.float32)
except:
    import ipdb; ipdb.set_trace()

The problem is located where are those lines.  set_trace() is use to pop-up an interactive shell. From there, if I run for i in range(batch_size): print(batch[3][i].shape), I obtained this output
ipdb> for i in range(32): print(batch[3][i].shape)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
(4, 84, 84)
*** AttributeError: 'NoneType' object has no attribute 'shape'

How can I improve that code to avoid such error?

A: The error is telling you the problem. You're trying to call shape on None, so, in your code, some variable a is None and you are calling shape on it, i.e. a.shape. This is one of the most common errors in programming!
In your for loop
for i in range(32):
    print(batch[3][i].shape)

at some point, batch[3][i] is None, so you will have to figure out what batch[3] contains and why it is None.
See the discussion here https://chat.stackexchange.com/transcript/message/54070403#54070403.


text:
Q: can't read XML via PHP I can't find the reason, only see the following error message.
Input is not proper UTF-8, indicate encoding ! Bytes: 0x00 0x5D 0x5D 0x3E
the followings are my php code
$reader2 = new XMLReader();
$reader2->XML($xmlstring);
$user_data="";

while ($reader2->read()) {

    if ($reader2->name == "user_id" && $reader2->nodeType == XMLReader::ELEMENT) {
        $reader2->read();
        $user_data .=$reader2->value;
    }

}
$reader2->close();

The followings are XML data
<?xml version="1.0" encoding="UTF-8" ?>
<SOAP:Envelope xmlns:SOAP="http://www.w3.org/2003/05/soap-envelope" >
    <SOAP:Body >
<user_id>1234567890</user_id>
<greeting_name><![CDATA[ABCDEF ..yl/�]]></greeting_name>
</SOAP:Body>
</SOAP:Envelope>

I try a lot of ways,but still can't find the solution. the greeting tag value may be chinese or English words.

A: Not all byte sequences encode a character in utf-8. There are sequences that have no meaning or - to put it blunt- are wrong. The xml parser found such a wrong sequence in the input document (which claims to be properly utf-8 encoded) and complained about it. The xml document needs to be fixed.