text:
Q: orthogonal functions with orthogonal first derivatives Is there any set of functions  $\phi_1(x) , \phi_2(x) , \ldots , \phi_n(x) , \ldots $ defined on $[a,b]$ such that
\begin{eqnarray}
&&\langle\phi_i, \phi_j\rangle = \int_a^b \phi_i(x)\phi_j(x) \, dx = 0   , & \quad i \neq j\\
\text{and} &&\langle\phi'_i, \phi'_j\rangle = \int_a^b \phi_i'(x)\phi_j'(x) \, dx = 0   , & \quad i \neq j\\
\end{eqnarray}
In other words is it possible to construct  a set of orthogonal functions with orthogonal first derivatives.
thanks for any help in advance.
If $\mathbf x_{(n)} = (1,x,...,x^n)^\top$  and $n= 2k$, we can build $k+1$ orthogonal functions as $\{f_1(x) , f_2(x) , \ldots, f_{k+1}(x)\} $  with orthogonal derivatives.
Where $$f_i(x) = \beta_{(i)}^\top \mathbf x_{(n)} $$
for example if $n=4$ we choose $\beta_{(1)} = (1,1,1,1,1) ^\top$, to calculate $\beta_{(2)}$  we obtain a system of $2$ equations with $n+1=5$ unknowns, thus we can choose three of the unknowns arbitrary, in this case we obtained $\beta_{(2)} = (1,1,1, -13863953/737217, 3891559/245739)^\top$
to calculate $\beta_{(3)}$ we obtain a system of $4$ equations with $n+1=5$ unknowns, thus we can choose one of the unknowns arbitrary, i chose $1$ for arbitrary elements and obtained  $\beta_{(3)} = (1,-107258998722634059/7523609370275492, 196455394286418897/3761804685137746, -262795627408036863/3761804685137746, 58289000568303981/1880902342568873)^\top$
(to calculate $\beta_{(i)} $ we have $n+3-2i$ choices)
Now I  have a question that is important to me:
can we choose the elements of $\beta_{(i)}$ (those element which are arbitrary)  such  that  the orthogonal  functions $\{f_1(x) , f_2(x) , \ldots, f_{k+1}(x)\} $ generate
the space $Span\langle 1,x,x^2,\ldots,x^k\rangle$ ?

A: You can build a collection of orthogonal polynomials with orthogonal derivatives. Define $\mathbf x_{(n)} = (1,x,...,x^n)^\top$ a polynomial of degre $n$ is just the inner product of $\mathbf x_{(n)}$ with some vector of coefficients $\beta = (\beta_0,...,\beta_n)^\top$. So you want to find a collection of vectors $\beta_{(1)},...,\beta_{(k)}$ in $\mathbb R^n$ such that
$$ \forall i \neq j, \ \int \langle \beta_{(j)}, \mathbf x_{(n)} \rangle \langle \beta_{(i)}, \mathbf x_{(n)} \rangle dx =  0 \Longleftrightarrow \beta_{(i)}^\top \left[ \int \mathbf x_{(n)} \mathbf x_{(n)}^\top dx \right] \beta_{(j)} = 0 $$
and
$$ \forall i \neq j, \ \int \langle \beta_{(j)}, \mathbf x_{(n)} \rangle' \langle \beta_{(i)}, \mathbf x_{(n)} \rangle' dx =  0 \Longleftrightarrow \beta_{(i)}^\top \left[ \int \mathbf y_{(n)} \mathbf y_{(n)}^\top dx \right] \beta_{(j)} = 0 $$
where $\mathbf y_{(n)} = (0,1,...nx^{n-1})^\top$. So basically, you want to find a collection of vectors that are orthgonal for the two Gram matrices $\int \mathbf x_{(n)} \mathbf x_{(n)}^\top dx$ and $\int \mathbf y_{(n)} \mathbf y_{(n)}^\top dx$. With a sufficiently large $n$, you can find $k$ such vectors (start with any $\beta_{(1)}$, then compute an orthogonal vector $\beta_{(2)}$ for the two Gram matrices and so on...)


text:
Q: Get the current transaction handle in interface method I'm trying to gain access to the current JDBI transaction handle in my interface method, the purpose of this is to avoid passing the handle as an argument to the interface's methods, thus keeping the interface free of any implementation details. The following example demonstrates what the intended use case is.
I have a UserApplicationService managing the transaction being used
class UserApplicationService(val jdbi: Jdbi, val userRepository: UserRepository) {

    fun changeUserName() {
        jdbi.useTransaction<Exception> {
            userRepository.updateName("peter pan")
        }
    }
}

I have a UserRepository interface
interface UserRepository {
    fun updateName(name: String)
}

I have a PostgresUserRepository implementation of the interface
class PostgresUserRepository: UserRepository {
    override fun updateName(name: String) {
        val handle: Handle = getHandle() // some method to get the handle of the transaction, this is what I need help solving
        handle.execute("...") // set new name of user using the handle
    }
}

Any suggestions on how to solve this would be greatly appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Algebraic Extension about 7th primitive roots I find an interesting question about 7th primitive roots.
Suppose that $\psi$ is a 7th primitive root of $1$.
Try to find the number of elements in $$\{a=a_1\psi+a_2\psi^2+a_3\psi^3+a_4\psi^4+a_5\psi^5+a_6\psi^6: a_i \in (0,1)\}$$ satisfy that $\mathbb{Q}(a)=\mathbb{Q}(\psi)$.
Anyone got some ideals?

A: Denote an automorphism on $\sigma:\mathbb{Q}(\psi) \to \mathbb{Q}(\psi)$ by $\sigma(\psi) = \psi^3$. It is a generator for the Galois group $G$. Let $X=\{a_1\psi+a_2\psi^2+a_3\psi^3+a_4\psi^4+a_5\psi^5+a_6\psi^6| a_i \in \{0,1\}\}$. Then $G$ acts on $X$. We wish to know the number of elements in $X$ with trivial stabilizer.
Let $x=a_1\psi+a_2\psi^2+a_3\psi^3+a_4\psi^4+a_5\psi^5+a_6\psi^6$.
There are only two elements of $X$ with stabilizer $G$: if $x$ is to be fixed by $\sigma$, then all $a_i$ are equal.
If $x$ is to be fixed by $\sigma^2$, then $a_1=a_2=a_4$, $a_3=a_5=a_6$, so there are $2^2=4$ such $x$ which will be fixed $\sigma^2$, but among them, 2 are also fixed by $\sigma$. Therefore there are 2 elements of $X$ which have stabilizer $\{1,\sigma^2,\sigma^4\}$.
If $x$ is to be fixed by $\sigma^3$, then $a_1=a_6$, $a_3=a_4$ and $a_2=a_5$, so there are $2^3=8$ such $x$ which will be fixed $\sigma^3$, but among them, 2 are also fixed by $\sigma$. Therefore there are 6 elements of $X$ which have stabilizer $\{1,\sigma^3\}$.
Hence there are $10$ elements with nontrivial stabilizer, your desired number is $2^6-10=54$.


text:
Q: Ajax response from a servlet is printing twice I am facing problem while appending the content of a div using ajax.The response from the servlet is printing twice.
Here is the code for both the pages.
demo.jsp

    <input type="submit" value="Add Content" onclick="run();"/>

This is Static Text.

DemoServlet
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/demo"})
public class Demo extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            /* TODO output your page here. You may use following sample code. */
            out.println("This is Dynamic Text
");
        } finally {
            out.close();
        }
    }
}

The final content of the output div is:
This is Static Text.
This is Dynamic Text.
This is Dynamic Text.
I am unable to understand why the Dynamic Text is printing twice.
Thanks in advance.

A: I suspect onreadystatechange is being called multiple times, more than one of which is carrying the response.  See What do the different readystates in XMLHttpRequest mean, and how can I use them?  Put a breakpoint in your handler to check.
You probably want to add a check that the response is complete:
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        content.innerHTML += xhr.responseText;
    }
}


text:
Q: List Item as a page object I'm working with page objects in Appium.
I've some view which contains a recyclerview with an items in it.
Each item contain several ui controls (button , image , text , etc ...
I was thinking to create a page object which represent an item in the list.
Something like that :
class MainView{
....
AndroidFindBy(...)
private AndroidElement list;
}

class Item{
  @AndroidFindBy(....)
  private AndroidElement button;

  @AndroidFindBy(....)
  private AndroidElement text;

  @AndroidFindBy(....)
  private AndroidElement image;

  ...
}

But I had a trouble to connect between the "Item" PO to the list which is in MainView.
Any ideas or what is the best practice to work in such case ?
thanks

A: Eventually the issue was solved with " Widget " appium's API.
https://github.com/appium/java-client/blob/master/docs/Page-objects.md#the-additional-feature


text:
Q: How to aggregate data by certain conditions on SAS EG? I have a question on aggregating the data, and the data structure looks like an example below: (Table A)
For example, the first row means 1/3 of the demand starting from 17JAN2016 will use for 1 day; and 1/3 will use for  2 days; the rest 1/3 will be used for 3 days.
ID   | Start_Date  | Length_of_Use | Percentage
-------------------------------------------------
1    | 17JAN2017   |      1        |  0.333
2    | 17JAN2017   |      2        |  0.334
3    | 17JAN2017   |      3        |  0.333
4    | 18JAN2017   |      1        |  0.5
5    | 18JAN2017   |      4        |  0.5
6    | 19JAN2017   |      2        |  0.5
7    | 19JAN2017   |      3        |  0.5
8    | 20JAN2017   |      2        |  1
9    | 21JAN2017   |      1        |  1

And I do have Demand by Use date level as below: (Table B)
ID  | Use_Date      | Use_Demand
-----------------------------------
1   | 17JAN2017     |      3
2   | 18JAN2017     |      4
3   | 19JAN2017     |      4
4   | 20JAN2017     |      4
5   | 21JAN2017     |      5

If we have the above 2 tables as known information,
how could I merge table A and table B into a table that could have demand by Start Date & Length of Use level as below? (Table C)
ID is just a sequence number, no key information.
First row is calculated by:
3*0.333 = 1

(Arrival Date 17JAN2016, Length of Use 1)
I would like to figure out demand by 'Start_Date' & 'Length_of_Use' level
based on demand by 'Use_Date' level (table B) and Probability for each 'Starting_Date' and 'Length_of_Use' (table A).
As the example in Table B, 17JAN2017 has use_demand of 3, and according to the probability, 1 of them has length of use 1, whcih means the 'use_date' is 17JAN2017; 1 of them has length of use 2, whcih means the 'use_date' is 17JAN2017 and 18JAN2017; the rest 1 has  length of use 3, whcih means the 'use_date' is 17JAN2017, 18JAN2017 and 19JAN2017.
As in table B, 18JAN2017 has use_demand of 4, 2 of them come from 17JAN2017, hence, the rest 2 of them should come from 18JAN2017. Based on the probability table (table A), Starting_Date 18JAN2017 has 2 types of length of stay, both have probability 0.5; hence Start_Date '18JAN2017' with length of use 1 has demand 1, and '18JAN2017' with length of use 4 has demand 1; whcih makes 4th and 5th row of table C.
Thank you!
ID   | Start_Date     | Length_of_Use | Demand
------------------------------------------------
1    | 17JAN2017      |      1        |  1
2    | 17JAN2017      |      2        |  1
3    | 17JAN2017      |      3        |  1
4    | 18JAN2017      |      1        |  1
5    | 18JAN2017      |      4        |  1
6    | 19JAN2017      |      2        |  1
7    | 19JAN2017      |      3        |  1
8    | 20JAN2017      |      2        |  1
9    | 21JAN2017      |      1        |  2


text:
Q: Why the export the Graphics or Image to local file I note the Put cannot export the Graphics or Image,I mean this code will be failure.
Image[Plot[x, {x, 0, 2}]] >> "plot.png"

But the documentation of Put don't mention this.Have I missed something or I have made any syntax error?

A: Here we "put", and then "get" the file:
Image[Plot[x, {x, 0, 2}]] >> "plot.png";
<< "plot.png"

Note that it returns the plot, exactly as it should! It also works if you leave off the Image command. In both cases, Put >> writes an expression to the file, that can be read back in by Get <<.


text:
Q: Linux Directory Access Problem: Permission Denied I'm attempting to run the command
username> ls -al var/

But I get the exception
ls: cannot open directory var/: Permission denied

When I check the permission of the directory I see
drwxr-x--x  6 sysuser abbagroup   4096 2010-07-28 11:55 var

I've confirmed that my user account is part of the group
> groups username
username: abbagroup

So why can't I run the command?

A: Did you by any chance just add username to abbagroup? This kind of change takes effect when you log in, and applies to the login process and its descendants.
When you run groups username, it tells you which groups username would belong to if (s)he logged in. Run groups with no argument instead, so that it tells you which groups the current process belongs to. If that doesn't show abbagroup, you need to log out and back in.

A: Try
sudo ls -al var/


text:
Q: How to use rest_url_prefix filter in wordpress How can I modify the WordPress REST API endpoint for my custom API endpoints only?
I'm using the WC API 2.6 also and I do not want to modify the endpoint for them. I just want to change the request endpoints for my custom API.
My API is built on WC_REST_Controller which further extends the WP_REST_Controller class.


text:
Q: Thread safe client lib on app engine (python) I found a little sample code about bigquery insert in one of Google's git repositories.
https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/appengine/standard/bigquery/main.py
If you see the app.yaml it says this code should be thread safe, but if I'm lokking at the client lib's documentation (https://developers.google.com/api-client-library/python/guide/thread_safety) it should not be thread safe. I'm a little bit confused now, that my following code is thread safe or not?
It's running on app engine standard env.
import pprint

from googleapiclient.discovery import build
from oauth2client.client import GoogleCredentials

credentials = GoogleCredentials.get_application_default()

# Create the bigquery api client
service = build('bigquery', 'v2', credentials=credentials)

response = service.datasets().list(projectId='PROJECTID').execute()

pprint.pprint(response)

---- UPDATE ----
After Tim's answer I changed my code to the following. This should be good now:
import pprint

from googleapiclient.discovery import build
from oauth2client.contrib.appengine import AppAssertionCredentials
import httplib2

credentials = AppAssertionCredentials(scope='https://www.googleapis.com/auth/bigquery')

# Create the bigquery api client
service = build('bigquery', 'v2')

def get():
    # authorize http object with client credentials
    http = credentials.authorize(httplib2.Http())
    response = service.datasets().list(projectId='PROJECTID').execute(http=http)

    pprint.pprint(response)

A: If you read the docs you reference it says

The google-api-python-client library is built on top of the httplib2
  library, which is not thread-safe. Therefore, if you are running as a
  multi-threaded application, each thread that you are making requests
  from must have its own instance of httplib2.Http().

They then go on to show you how to do this.  If you follow the instructions then yes it will be.
You sample code is too simple and isn't attempting what was outlined in the docs
# Create a new Http() object for every request
  def build_request(http, *args, **kwargs):
    new_http = httplib2.Http()
    return apiclient.http.HttpRequest(new_http, *args, **kwargs)
  service = build('api_name', 'api_version', requestBuilder=build_request)

  # Pass in a new Http() manually for every request
  service = build('api_name', 'api_version')
  http = httplib2.Http()
  service.stamps().list().execute(http=http)

So if you tried your code in a threaded situation it would not be thread safe.
If you are just trying that code from REPL then I doubt you are in a threaded situation.


text:
Q: installer prerequisite in VS2010 Setup Project VS2010 Setup project, Excel AddIn, C#,  ExcelDNA, NetOffice

*

*I use VS2010 setup project to create installer.
Click Prerequisite properties of the setup project, I see Windows Installer 3.1 and Windows Installer 4.5 are listed in prerequisite list.
In VS2008, I checked Windows Installer 3.1 in prerequisite (though I do not know why?).
In VS2010, I wonder maybe I should check windows installer 4.5 in prerequisite list.
I wonder if I need check it and why?

*Another thing is  Shared Add-in support Update for Microsoft .NET framework 2.0 (KB908002) is listed in prerequisites list, too.  Wonder if I need it? My AddIn is target .NET 35 Sp1

*My addIn target .NET framework 3.5 sp1 in VS2008, now I move to VS2010, in setup project, I can check either .NET 3.5 SP1 or .NET 4.0 as prerequisite.  Does my target .NET framework have to be the same version as that in prerequisite list?

A:
In VS2010, I wonder maybe I should check windows installer 4.5 in
  prerequisite list. I wonder if I need check it and why?

You should check it only if you need to use Windows Installer 4.5 features.

Another thing is Shared Add-in support Update for Microsoft .NET
  framework 2.0 (KB908002) is listed in prerequisites list, too. Wonder
  if I need it? My AddIn is target .NET 35 Sp1

You should answer this question. Does your add-in need it in order to work correctly? Did you add a .NET Framework prerequisite which includes this update?

Does my target .NET framework have to be the same version as that in
  prerequisite list?

It's the other way around. First you determine the .NET Framework version your add-in needs and then add it as a prerequisite.


text:
Q: two different values of x in javascript Why does the first alert show 3 and the second alert show 1?  I realize that this changes the scope but isn't go() and foo.baz.bar() calling the same thing?
var x = 3;

var foo = {
    x: 2,
    baz: {
        x: 1,
        bar: function() {
            return this.x;
        }
    }
}

var go = foo.baz.bar;

alert(go());
alert(foo.baz.bar());

A: The execution context of the first alert is the Window object. The execution context of the second alert is the function called bar.  That's it. The Execution Context is the bit to understand.
Here are the details: https://tc39.github.io/ecma262/#sec-execution-contexts

A: JavaScript assigns the definition of this at run time. This means that it doesn't analyze the code around it unless you're explicit, like how you are when you use foo.baz.bar. Using go immediately invokes
function() {
   return this.x;
}

Note that this particular statement is interpreted to be outside of the foo object. Its context is actually window or global (depending on your dev environment).


text:
Q: Unable to load pages in web browsers Using Ubuntu 11.10, I am having a problem browsing web pages. I tested my connection by pinging different sites. All of them reply to me, but my browsers do not work. The problem is not specific to one browser, as I have tested both Firefox and Chromium.
This is the wget output when run in Terminal:
wget ubuntu.com
Resolving ubuntu.com... 91.189.94.156 Connecting to ubuntu.com|91.189.94.156|:80

No error is raised.  What do I have to do?
Thanks for every bodies answers.
My problem was from IPV6 activat.
Open the firefox browser and type:
about:config

Press accept button with the text I'll be careful, I promiss!
then enter IPV6 in filter field. just one entry remain in list with text network.dns.disableIPv6. Right click on this and press Toggle. the value field must be true.
After, take logout and logon again.
Now test again!
I did the above stream.It got solve for some minutes but the problem started again.
So now I have not the page loading in my ubuntu.

A: The problem was related to IPv6.

*

*In Firefox's URL bar type: about:config

*Click the button with the text I'll be careful, I promise!

*Enter IPv6 in the filter field. Just one entry named network.dns.disableIPv6 should remain in the list.

*Right click on this and press Toggle. The value must be true.
After that, logout and login again, and it should work.

A: *

*Are you sure that is a browser problem?
Do you have a proxy? Check your browser
Firefox -> Modify -> Precerences -> Advanced -> Connection

*Do you have a trasparent proxy?
Check with this:
http://www.lagado.com/proxy-test

*Does your ISP block http traffic?
You say that ICMP works, check ftp, ssh and other protocols

A: Your browser is set to work offline.
For example in Firefox under File > Work offline.
Untick "Work offline" to resolve this.


text:
Q: Android 4.1 Webview.loadUrl(String url, Map additionalHttpHeaders) not working with 2 or multiple headers This is my code:
String urlBase = "http://" + host + "/rashome/";

String paramsClear = "login" + ":" + "true" + ":" + email + ":" + password + ":" + lang + ":" + isFastConn;

String paramsBase64Encode = Base64.encodeToString(paramsClear.getBytes(), Base64.DEFAULT);

paramsMap.put("credentials", paramsBase64Encode);
paramsMap.put("imei", imei);
if(!token.equals("")) {
    paramsMap.put("token", token);
}
webview.loadUrl(urlBase, paramsMap);

That is working fine on Webview Android 4.4+ (server receive all parameters), but on Webview Android 4.1 or under 4.4, it can't send imei and token value to server. I am too confused about this.


text:
Q: how to update my notification when new row is inserted to notifications table I have a page with a notification area where notification comes.(like facebook)
Now what i want is when a new row is inserted into database i want to alert user with a message (or increment numbers under notification icon).
I don't want to run ajax on set interval and check if new notification exists or not
is there any way to check notification only when new record is inserted into notifications table?


text:
Q: How to insert multiple check boxes values in single column one value in single row in database using jsp I want to store multiple check boxes values in database using JSP in single column of database but single value in single row.
 My JSP code QuickFunction.jsp:

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

 Quick Function

<form action="QuickServlet">

1
            Book A voucher
            Sales Voucher
                <input type="checkbox" name="voucher"
                    value="Sales Voucher" />

            Purchase Voucher
                <input type="checkbox" name="voucher"
                    value="Purchase Voucher" />

            Receipt
                <input type="checkbox" name="voucher"
                    value="Receipt" />

            Payment
                <input type="checkbox" name="voucher"
                    value="Payment" />

            		 Contra
                <input type="checkbox" name="voucher"
                    value="Contra" />

             Journal
                <input type="checkbox" name="voucher"
                    value="Journal">

        <input type="submit" value="Submit"/>
     </form>

My servlet code QuickServlet (doGet method):
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        PrintWriter out = response.getWriter();
        String voucher = "";
        String a[]=request.getParameterValues("voucher");
        for(int i=0;i<a.length;i++){
            voucher+=a[i]+"";
        }

        DBConnection dbc=new DBConnection();
         Connection con=dbc.getNewConnection();

         Statement st = null;
         ResultSet rs = null;
         try
            {
                st = con.createStatement();
            }
            catch (SQLException e)
            {
                e.printStackTrace();
            }

            String updatecust = "insert into vouchers(voucher) values('"+voucher+"');";
                    try
            {

                int i=st.executeUpdate(updatecust);

                if(i>0){
                out.print(" saved successfully....!!");
                }
                else
                   out.print("Sorry..!! Got an exception.");
            }
            catch (SQLException e)
            {
                e.printStackTrace();
            }

    }

This stores check boxes values in single column in single row as below :
mysql> select * from vouchers;
+--------------------------------------+
| voucher                              |
+--------------------------------------+
| Sales VoucherPurchase VoucherReceipt |
+--------------------------------------+

But i want to store one value in one row and so on. As below(Expected output):
mysql> select * from vouchers;
+------------------+
| voucher          |
+------------------+
| Sales Voucher    |
| Purchase Voucher |
| Receipt          |
+------------------+

Please help me. Thanks in advance!!

A: In your code, First your concatenating all voucher the using for loop and then inserting.
If you want each voucher is to be inserted in row wise then instead of concatenation voucher in for loop, You call insert query with in for loop and insert voucher.
Like this:
   for(int i=0;i<a.length;i++){
       String updatecust = "insert into vouchers(voucher) values('"+voucher+"');";
    }

A: It will work just check with creating  a small table(multicheck) of two field (id,voucher).
<?php include('config.php'); ?>

<?php
    $voucher= $_POST['voucher'];

    if($_POST['Submit']=='Submit'){
        for($i=0;$i<sizeof($voucher);$i++){
            $statement = $db->prepare("INSERT INTO multicheck (voucher) VALUES (?)");
            $statement->execute(array($voucher[$i]));
        }
}
?>

Here is form :

<form action="actionform.php" method="POST">
  <input type="checkbox" value="Sales Voucher" name="voucher[]">Sales Voucher

  <input type="checkbox" value="Receipt" name="voucher[]">Receipt

  <input type="checkbox" value="Contra" name="voucher[]">Contra

  <input type="checkbox" value="Journal" name="voucher[]">Journal

  <input type="submit" name="Submit" value="Submit">
</form>


text:
Q: Unable to delete Sharepoint Online term store items programmatically I'm trying to delete terms or term sets from the default taxonomy store in a C# application which authenticates with an Azure App. I've tried using certificate and app secret authentication as well as a user account context. Using the certificate/app secret, the authentication is successful and I can read terms but receive an error when I try to delete a term:
Microsoft.SharePoint.Client.ServerUnauthorizedAccessException: 'Access denied. You do not have permission to perform this action or access this resource.'
Tried this using both using CSOM and PnP Framework. The App has full read and write permissions for the SharePoint API and Graph API relating to SharePoint/Term Store.
Using user account, I get an error that the login/password could not be found. MFA is disabled for this account in 365 Admin, but it seems the web portal still asks for this to be set up when logging in via browser.
Using the MS Graph API and the same Azure App, I can also create terms, but Graph does not support deleting terms at the moment so this method cannot be used.


text:
Q: how to implement beacon on raspberry pi? If I want to implement the beacon and send message to Bluetooth devices,
should I need

*

*a raspberry pi + beacon devices

*a raspberry pi

which one is right?
I have found some people use raspberry pi and small beacon devices, others only use raspberry pi itself to send messages, both of them can send URL or data, and I want to know raspberry pi's character in this implementation.
thanks!!

A: A Bluetooth BLE device can advertise its services and as part of the advertisement can contain up to 28 bytes of advertising data. There is no format for that data defined in the Bluetooth specification and so it is up to the manufacturer to define so that both ends of Bluetooth signal understand it. This is advertising data is how beacons have been created and companies have defined the structure used by them. Examples of this are the iBeacon and Eddystone formats.
This tweet gives a good summary of the structure of the data used by the popular/common formats:
https://twitter.com/josryke/status/763006284052463617

On a Raspberry Pi the Bluetooth stack is BlueZ and it has API's that allow you to create the required advertisement from your favourite programming language:
https://git.kernel.org/pub/scm/bluetooth/bluez.git/tree/doc/advertising-api.txt
There are also couple of command line tools that will allow you to create the beacons by hand.
Transcript of using bluetoothctl to create an Eddystone URL beacon:
(venv) pi@raspberrypi:~ $ bluetoothctl
Agent registered
[bluetooth]# menu advertise
[bluetooth]# uuids feaa
[bluetooth]# service 0xfeaa 0x10 0x00 0x00 0x62 0x6c 0x75 0x65 0x74 0x6f 0x6f 0x74 0x68 0x00
[bluetooth]# back
[bluetooth]# advertise on
[CHG] Controller B8:27:EB:22:57:E0 SupportedInstances: 0x04
[CHG] Controller B8:27:EB:22:57:E0 ActiveInstances: 0x01
Advertising object registered
UUID: (feaa)
UUID: Google(0xfeaa)
  10 00 00 62 6c 75 65 74 6f 6f 74 68 00           ...bluetooth.
Tx Power: off
Name: off
Appearance: off
Discoverable: off
[bluetooth]#

Or the same advertisement using the btmgmt tool:
pi@raspberrypi:~ $ sudo btmgmt add-adv -u feaa -d 1016aafe100001626c7565746f6f746800 -g 1

An example of iBeacon using the btmgmt tool:
sudo btmgmt add-adv -d 1AFF4C000215000102030405060708090A0B0C0D0E0F1234567800 -g 1


text:
Q: Excel form on a web page I'm working on a project a little special and I have to insert an excel form on a web page so that users can fill it online and then on submit it have to be sent by email (as attachment or form) to the recipient of the form.
The company has no skydrive and the form must be an excel and not an HTML form.
Does anyone have an idea?
Thanks all !

A: I'm the creator of Appizy (http://appizy.com) that aims at converting Excel files into dynamic webapp. If I get it well you could generate your HTML form based on Excel Spreadsheet with Appizy.
Then you "just" need to plug a submit button to the generated webapp to send the data by email.

A: PHPExcel seems to offer a fully fledged engine for PHP (including calculating ability).
There doesn't seem to be any clear cut examples of how to interact with it via a webpage however.


text:
Q: Will I be able to play my Destiny Characters if I buy Legendary Edition (PS3) So I have Destiny on PS3. If I were to buy the Legendary Edition (Containing House of Wolves and Dark Below Expansion) will I be able to play with my characters from my original Destiny disc? May sound silly, but I need confirmation.

A: Yes. You're not actually buying a new game, you're buying the same game with added content.


text:
Q: Объявление функций в JavaScript Есть ли разница между:
var square = function(x) {
  return x * x;
};

и
function square(x) {
  return x * x;
};

Читаю https://eloquent-javascript.karmazzin.ru/chapter3 и пытаюсь понять как правильно объявлять функции.

A: Основное функциональное различие:

*

*В первом варианте (Function Expression) функцию можно будет использовать только после её объявления, она создается когда выполнение доходит до неё.

*Во втором (Function Declaration), функция будет доступна в любом месте кода (или в блоке кода, если функция объявлена в нём).


text:
Q: Cannot read property 'selectionEnd' of null in aoutoComplete material UI I have a problem with autoComplete
the react-text-mask is like this :
<MaskedInput
  {...other}
  ref={ref => {
    inputRef(ref ? ref.inputElement : null);
    return ref;
  }}
  mask={[
    /\d/,
    /\d/,
    /\d/,
    /\d/,
    ' ',
    /\d/,
    /\d/,
    /\d/,
    ' ',
    /\d/,
    /\d/,
    /\d/,
    /\d/,
  ]}
  placeholderChar={'\u2000'}
/>;

and the autoComplete component is like this:
<AmountAutoComplete
  options={this.state.autoCompleteOptions.map(option => option.title)}
  renderInput={params => {
    return (
      <TextField
        value={this.props.value}
        onChange={e => {
          onValueChange(e.currentTarget.value, '');
        }}
        InputProps={{
          inputComponent: this.TextMaskCustom,
        }}
      />
    );
  }}
/>;

and the error is
Cannot read property 'selectionEnd' of null
    at handleClick (useAutocomplete.js:763)
and in useAutocomplete.js:763 have the error about inputRef:
var handleClick = function handleClick() {
    if (firstFocus.current && inputRef.current.selectionEnd - inputRef.current.selectionStart === 0) {
      inputRef.current.focus();
      inputRef.current.select();
    }

A: I should send params into textField like this:
<TextField
    {...params}
     InputProps={{
     ...params.InputProps,
    }}
 />


text:
Q: ws02 5.0.0 missing sessionIndex in SAML 2.0 Response I just installed and configured wso2 IS. I have a small Java application acting as the SP. I am using the resident IDp. I am able to send a request and get a response back. For some reason, sessionIndex attribute of the AuthnStatement is missing. I understand this is an optional attribute but how do I configure my wso2Is and/or my SP and IDp to ensure it gets sent as part of the response. Here is the response I get.
<saml2p:Response Destination="http://localhost:8080" ID="igagmdgmjlflgcljianclnnpfkfilpbnfomonkmn" InResponseTo="ajbhplbldnpgoigiegdmmhlhlblmfjcbhpbcfpnn" IssueInstant="2015-02-09T15:20:52.141Z" Version="2.0" xmlns:saml2p="urn:oasis:names:tc:SAML:2.0:protocol"><saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity" xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion">localhost</saml2:Issuer><ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><ds:Reference URI="#igagmdgmjlflgcljianclnnpfkfilpbnfomonkmn"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><ds:DigestValue>gVmD3/tfB4suknjA89b0UilGxD4=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>c8Z4xjKjo05XfawLfSHCsA2L6DBEruI4nI0hvxm2yY//tAXgFdsh1ezkeJEMxB8enRR9Lh1Vhb4IQQ6BFhysEtdrP6MqQeu26ehwY5VbkhU3YTzut3m8/eVyL9XL6go8HiIUamRXTIELTwdjagoACVJ6KYPMApIB0+lqB1WERTU=</ds:SignatureValue><ds:KeyInfo><ds:X509Data><ds:X509Certificate>MIICNTCCAZ6gAwIBAgIES343gjANBgkqhkiG9w0BAQUFADBVMQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxDTALBgNVBAoMBFdTTzIxEjAQBgNVBAMMCWxvY2FsaG9zdDAeFw0xMDAyMTkwNzAyMjZaFw0zNTAyMTMwNzAyMjZaMFUxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzENMAsGA1UECgwEV1NPMjESMBAGA1UEAwwJbG9jYWxob3N0MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCUp/oV1vWc8/TkQSiAvTousMzOM4asB2iltr2QKozni5aVFu818MpOLZIr8LMnTzWllJvvaA5RAAdpbECb+48FjbBe0hseUdN5HpwvnH/DW8ZccGvk53I6Orq7hLCv1ZHtuOCokghz/ATrhyPq+QktMfXnRS4HrKGJTzxaCcU7OQIDAQABoxIwEDAOBgNVHQ8BAf8EBAMCBPAwDQYJKoZIhvcNAQEFBQADgYEAW5wPR7cr1LAdq+IrR44iQlRG5ITCZXY9hI0PygLP2rHANh+PYfTmxbuOnykNGyhM6FjFLbW2uZHQTY1jMrPprjOrmyK5sjJRO4d1DeGHT/YnIjs9JogRKv4XHECwLtIVdAbIdWHEtVZJyMSktcyysFcvuhPQK8Qc/E/Wq8uHSCo=</ds:X509Certificate></ds:X509Data></ds:KeyInfo></ds:Signature><saml2p:Status><saml2p:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></saml2p:Status><saml2:Assertion ID="hlfiehajebijcoclljpaenpkaodpjedjndoimpdd" IssueInstant="2015-02-09T15:20:52.141Z" Version="2.0" xmlns:saml2="urn:oasis:names:tc:SAML:2.0:assertion"><saml2:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">localhost</saml2:Issuer><ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#"><ds:SignedInfo><ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/><ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/><ds:Reference URI="#hlfiehajebijcoclljpaenpkaodpjedjndoimpdd"><ds:Transforms><ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/><ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/></ds:Transforms><ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/><ds:DigestValue>pTqbRLq9GTnyKNu4WYuX+XaCDVo=</ds:DigestValue></ds:Reference></ds:SignedInfo><ds:SignatureValue>Fsc0bdW7QYdX1VNpeMrjH+ETZA64WvodZhS+cPcCkWg+Azt1fZG8SaCHq6heqwx2tNjk5BUpHHNeOYUbcn7ztR6JQXfNynO0WG2D9096St5FcngoFqCL5X2Xa5XKdIKDMH/5UniIniKvm7XY62thx9+f8O0oD9/WhWbeW+jYv2A=</ds:SignatureValue><ds:KeyInfo><ds:X509Data><ds:X509Certificate>MIICNTCCAZ6gAwIBAgIES343gjANBgkqhkiG9w0BAQUFADBVMQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxDTALBgNVBAoMBFdTTzIxEjAQBgNVBAMMCWxvY2FsaG9zdDAeFw0xMDAyMTkwNzAyMjZaFw0zNTAyMTMwNzAyMjZaMFUxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzENMAsGA1UECgwEV1NPMjESMBAGA1UEAwwJbG9jYWxob3N0MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCUp/oV1vWc8/TkQSiAvTousMzOM4asB2iltr2QKozni5aVFu818MpOLZIr8LMnTzWllJvvaA5RAAdpbECb+48FjbBe0hseUdN5HpwvnH/DW8ZccGvk53I6Orq7hLCv1ZHtuOCokghz/ATrhyPq+QktMfXnRS4HrKGJTzxaCcU7OQIDAQABoxIwEDAOBgNVHQ8BAf8EBAMCBPAwDQYJKoZIhvcNAQEFBQADgYEAW5wPR7cr1LAdq+IrR44iQlRG5ITCZXY9hI0PygLP2rHANh+PYfTmxbuOnykNGyhM6FjFLbW2uZHQTY1jMrPprjOrmyK5sjJRO4d1DeGHT/YnIjs9JogRKv4XHECwLtIVdAbIdWHEtVZJyMSktcyysFcvuhPQK8Qc/E/Wq8uHSCo=</ds:X509Certificate></ds:X509Data></ds:KeyInfo></ds:Signature><saml2:Subject><saml2:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">joebloggs</saml2:NameID><saml2:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer"><saml2:SubjectConfirmationData InResponseTo="ajbhplbldnpgoigiegdmmhlhlblmfjcbhpbcfpnn" NotOnOrAfter="2015-02-09T15:25:52.141Z" Recipient="http://localhost:8080"/></saml2:SubjectConfirmation></saml2:Subject><saml2:Conditions NotBefore="2015-02-09T15:20:52.141Z" NotOnOrAfter="2015-02-09T15:25:52.141Z"><saml2:AudienceRestriction><saml2:Audience>localhost</saml2:Audience></saml2:AudienceRestriction></saml2:Conditions><saml2:AuthnStatement AuthnInstant="2015-02-09T15:20:52.142Z"><saml2:AuthnContext><saml2:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml2:AuthnContextClassRef></saml2:AuthnContext></saml2:AuthnStatement><saml2:AttributeStatement/></saml2:Assertion></saml2p:Response>

A: I enabled the "Enable Single Logout :" in SAML2 SSO issuer configuration. It looks like if it is enabled, it returns the "sessionIndex" attribute.


text:
Q: Configure Postgresql sslrootcert with Spring Cloud Connectors & HikariCP I'm currently trying to setup a datasource (Postgresql) on my SpringBoot 2.1.1 application with Spring Cloud Connectors (my application is hosted on PCF).
I need to configure the path to my sslrootcert (which is not specified in the jdbc url provided by the service broker we are using on PCF).
I've tried to configure it that way :
@Bean
public DataSource dataSource() {
    DataSourceConfig dataSourceConfig = new DataSourceConfig(null, new DataSourceConfig.ConnectionConfig("sslrootcert=/home/vcap/app/.postgresql/root.crt"), Collections.singletonMap("sslrootcert", "/home/vcap/app/.postgresql/root.crt"));
    return connectionFactory().dataSource(dataSourceConfig);
}

but my sslrootcert property is always ignored and fall back to the default ~/.postgresql/root.crt
I can't find anything in the documentation regarding a way of setting this kind of driver specific property.
Any kind of help would be appreciated.


text:
Q: Mahjongg doesn't display scores Since updating to 12.10 in mahjongg it always tells me I didn't make the top 10, but it doesn't show what the scores are. I used to following to reset the scores:
https://answers.launchpad.net/ubuntu/+source/gnome-games/+question/43471
However it still gives the same message and shows no scores. Any suggestions?

A: Sorry about the confusion.  You just have to rename them by appending gnome- in front of their names, example - /var/games/gnome-mahjongg.dragon.scores
Doesn't need the permissions change.

A: I just fixed mine after running strace on gnome-mahjongg
/var/games/gnome-mahjongg.easy.scores was not found
they are naming them mahjongg.easy.scores so following suit I changed the permissions on the /var/games/ directory and its files inside and for added measure I created a blank file in the directory with the proper name.  Scores started saving.


text:
Q: SSIS Derived Column Expression - removing leading zeros I have a package that is failing due to a negative sign with a numerical string such as:

000000000-25.00

The Derived column expression is:
ISNULL(wstr_Payment_Amount) || TRIM(wstr_Payment_Amount) == "" ? (DT_CY)0 : (DT_CY)wstr_Payment_Amount

The data type to column is money. I did a redirect row on the derived column to confirm it was the negative sign that was causing the failure.
Here is what I have..
FINDSTRING(wstr_Payment_Amount, "-", 1) >0  ? TRIM(SUBSTRING(wstr_Payment_Amount, FINDSTRING(wstr_Payment_Amount, "0-", 1), 8)) : wstr_Payment_Amount

I am using SSIS 2008.

A: If you are using two derived columns then leave it as a string in the first one...
ISNULL(wstr_Payment_Amount) || TRIM(wstr_Payment_Amount) == "" ? (DT_WSTR,100)"0" : (DT_WSTR,100)wstr_Payment_Amount

I think you were really close but consider the following once you identify the negative sign...
FINDSTRING(wstr_Payment_Amount, "-", 1) >0  ? (DT_CY) ("-" + replace(wstr_Payment_Amount,"-","")) : (DT_CY)wstr_Payment_Amount

This will just move the "-" to the front and all the zeroes will just go away.


text:
Q: String variable assignment doesn't work in grads Trying to assign string variable like,
mon = "jan"
but it returns Syntax error : Invalid Operand
I'm on window opengrads.
ga-> mon = "jan"
Syntax Error:  Invalid Operand
  'jan' not a variable or function name
  Error ocurred at column 1
DEFINE error:  Invalid expression.


text:
Q: How to safely consume from an exclusive queue in RabbitMQ? In a Remote Client Procedure (RPC) configuration, client queues are declared exclusive as it is shown in the official tutorial. If a client consumes a message from its exclusive queue and it crashes before acknowledging it, I would expect the message to be automatically requeued if the queue was still alive, but in this case, as the queue is exclusive, the queue doesn't exist any longer and the message is not being requeued.
Is there any way to make this scenario more reliable? Is there any way to requeue those messages into another queue which is still alive? I thought I might use Dead Letter Exchanges, but it seems this kind of messages (for which the server is unable to requeue after a consumer crash) are not managed by DLX.
I have undefined number of client processes, so I'm afraid queues must be exclusive, because each process has its own queue.
Any help would be appreciated.

A: If exclusive consumption and consumption continuity are required, single active consumer may be more appropriate.

Single active consumer allows to have only one consumer at a time consuming from a queue and to fail over to another registered consumer in case the active one is cancelled or dies. Consuming with only one consumer is useful when messages must be consumed and processed in the same order they arrive in the queue.

You can visit documentation to learn more.


text:
Q: Is there still any solution to load the existing Googlenews W2v into gensim and finetune it with additional corpus? In order to fine-tune word2vec embeddings in gensim, the following piece of code worked with previous versions:
model = Word2Vec.load_word2vec_format('GoogleNews-vectors-
negative300.bin.gz', binary=True)

However, I get the error message that Word2Vec.load_word2vec is depracated :
DeprecationWarning: Deprecated. Use gensim.models.KeyedVectors.load_word2vec_format instead.
When I use
model = gensim.models.KeyedVectors.load_word2vec_format('GoogleNews-
vectors-negative300.bin.gz', binary=True)

and then try to fine tune the model with train method as below:
model.train((corpus, total_examples=len(corpus2),epochs=10) )

I get the following error:
"AttributeError: 'Word2VecKeyedVectors' object has no attribute 'train'"
Is there still any solution to load the existing Googlenews W2V into gensim and fine-tune it with additional corpus?
In response to user:10473854: ignoring warning does not work as the module is already depracated. Also, running Word2Vec with the path for downloaded embedding will make Word2Vec fails. Check this:
model = Word2Vec('GoogleNews-vectorsnegative300.bin.gz')
model.wv.vocab

{'/': <gensim.models.keyedvectors.Vocab at 0x7ff6101c3940>,
'a': <gensim.models.keyedvectors.Vocab at 0x7ff6101c39e8>,
'e': <gensim.models.keyedvectors.Vocab at 0x7ff6101c3278>}

A: I wrote a similar thing for GloVe vectors in this answer
Basically starting from GloVe vectors and fine-tuning it on additional corpus using gensim.
In a similar fashion, it can be done for google news vectors as well.
In a gist, you need to set the hidden layers with the old vectors for words in your corpus which are already there in the google new corpus.


text:
Q: add an image to GridLayout in a .kv file from python How can I add an image object to a GridLayout defined in a .kv file?
Is this possible?
I have tried
ui.py
class Field(Widget):
    grid = ObjectProperty()

    grid.add_widget(Image(source="res/Water.png"))

class UI(App):
    def build(self):
        return Field()

ui.kv
<Field>
    GridLayout:
        cols: 9
        id: grid

I get when I run ui.py
 Traceback (most recent call last):
   File "ui.py", line 7, in
   File "E:\Scripts\Python\kivy\ui.py", line 8, in <module>
     class Field(Widget):
   File "E:\Scripts\Python\kivy\ui.py", line 17, in Field
     grid.add_Widget(Image(source="res/Water.png"))
 AttributeError: 'kivy.properties.ObjectProperty' object has no attribute 'add_Widget'


text:
Q: Check all files sizes in a path (C++) I'm trying to loop so that my program can get the weight of all files in a folder, and if the weight of any of these is equal to X, it will do an action, I need to know how I can loop like this, and i have a func to know whats the file size
std::ifstream::pos_type filesize(const char* filename)
{
    std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
    return in.tellg();
}

A: Here's a short example program that demonstrates how to use C++17's <filesystem> library to iterate over a directory. If your compiler is fairly up-to-date, it should support C++17 without issue.
#include <filesystem>
#include <iostream>

int main() {
  namespace fs = std::filesystem;

  fs::path pwd("");  // Current directory program was executed from
  pwd = fs::absolute(pwd);

  for (auto& i : fs::directory_iterator(pwd)) {
    try {
      if (fs::file_size(i.path()) / 1024 > 2048) {
        std::cout << i.path() << " is larger than 2MB\n";
      }
    } catch (fs::filesystem_error& e) {
      std::cerr << e.what() << '\n';
    }
  }
}

This was the contents of the directory:
.
├── a.out
├── fiveKB
├── fourMB
├── main.cpp
└── oneMB

0 directories, 5 files

And information about the files:
drwxr-xr-x   7 user  staff   224B Jul 29 22:11 ./
drwxr-xr-x  13 user  staff   416B Jul 29 21:59 ../
-rwxr-xr-x   1 user  staff    47K Jul 29 22:10 a.out*
-rw-r--r--   1 user  staff   5.0K Jul 29 21:58 fiveKB
-rw-r--r--   1 user  staff   4.0M Jul 29 21:59 fourMB
-rw-r--r--   1 user  staff   450B Jul 29 22:11 main.cpp
-rw-r--r--   1 user  staff   1.0M Jul 29 21:59 oneMB

And finally, the output:
"/Users/user/Documents/tmp/test/fourMB" is larger than 2MB


text:
Q: Why is the Parse push notification error occurring? I am trying to enable push notifications, but for some reason I am getting this error. The notification gets sent to parse, but not to the user.

A: Recently Apple changed how APNS Certificates work - you'll notice that newly created push certificates have the name "Apple Push Services:" and not "Apple Production IOS Push Services:". Apparently production certificates can be used for Sandbox and Production now: "Establish connectivity between your notification server, the Apple Push Notification service sandbox, and production environments to deliver remote notifications to your app."
I'm not sure how much they need to change on the backend side on Parse's end, but I noticed adding to AWS SNS didn't work for me last time I tried.


text:
Q: Are there any major differences or restrictions when using assets or res/raw folders? Background
Some files of the app can only be stored in res/raw or assets folders.
Each of those folders work in a very similar way to the other. res/raw folder allows to access files easier, with all the other benefits of resource files, while assets folder allows to access them no matter the file name and structure (including folders and sub folders).
The main idea of loading files is about the same for both of them. You just have a choice of ease-of-use, depends on your needs.
The problem
I remember that a very long time ago, I've found some special behavior of both of those folders:

*

*Each folder within the assets folder had a max number of files. I think it was about 500, but not sure. I've noticed this behavior a very long time ago,

*Some said that files in the assets folder have a max size for files (example here). I never saw such a restriction. Not even on Android 2.3 at the time.

*Some said (example here), and it's still believed even today (example here), that if you load a file from res/raw, it could take much more memory than if you took it from assets folder.
What I've tried
For #1, I never had to use more files anyway after the project I worked on, and at the time I worked on it, we simply split the files into more folders.
For #2 , as I wrote, I never noticed it anyway. I used much larger files sizes.
For #3, I tried to make a sample project that compares the memory usage between the 2 methods. I didn't notice any difference (memory usage or time to load) between the 2 methods. Especially not a major one. Sadly I have only one device (Nexus 5x), and it has quite a new Android version (8.1). It might be that starting from specific Android version there is no difference between the 2 methods. Another reason for this is that it's harder to measure memory usage on Java, because of the GC, and I've already noticed that on Android 8.x, memory works a bit differently than before (written about it here).
I tried to read about the differences and restrictions of the above, but all I've found are very old articles, so I think things might have changed ever since.
The questions
Actually it's just one question, but I'd like to split it in case the answer is complex:

*

*Are there any major or unique limitations or differences between using res/raw and assets folders?

*Does reading a file from the assets folder (by creating an input stream from it) really take less memory than using the res/raw? So much that even one of the most appreciated developers (here) decides to choose it, even nowadays?

*Have the above restrictions existed up to specific Android versions, and then they became identical in terms of no restrictions whatsoever (except of course files naming for res/raw, but that's just how it works) ?

*If so, from which Android version do they work about the same?

A: Are there any major or unique limitations or differences between using res/raw and assets folders?
Now, In android we don't have any restriction on max limit size for any file in assets or in raw.
Android Documentation:

Arbitrary files to save in their raw form. To open these resources
with a raw InputStream, call Resources.openRawResource() with the
resource ID, which is R.raw.filename.
However, if you need access to original file names and file hierarchy,
you might consider saving some resources in the assets/ directory
(instead of res/raw/). Files in assets/ aren't given a resource ID, so
you can read them only using AssetManager.

Does reading a file from the assets folder (by creating an input stream from it) really take less memory than using the res/raw? So much that even one of the most appreciated developers (here) decides to choose it, even nowadays?
No, I have not found any differences between memory usage. It is one of biggest mess that android is having right now, Also we don't have any official documentation about their memory limitation.
Have the above restrictions existed up to specific Android versions, and then they became identical in terms of no restrictions whatsoever (except of course files naming for res/raw, but that's just how it works) ?
Before android 2.3 we had memory restriction for asset folder, which is 1 MB.  Please refer link.
If so, from which Android version do they work about the same?
From android 2.3, We don't have any memory related restriction, which they launched in December, 2010


text:
Q: How to chain multiple JS promises to combined boolean result I am trying validate a variety of elements and their data on my page. I have 3 different methods to complete the validation, some of which make ajax calls. Each one returns a promise of a boolean. I want to combine the results into one variable. I thought the following code was working correctly, but my isValid variable seems to only be capturing the value of the last validation function called, saveCurrentSource(). How do I get isValid to be equal to the results of saveSourceResponse() && validateSource() && saveCurrentSource()?
async validate() {
  return new Promise(resolve => {
    let isValid = this.saveSourceResponse()
      .then(saveSourceResponse => {
      console.log("saveSourceResponse",saveSourceResponse);
        return this.validateSource();
      }).then(validateSourceResponse => {
          console.log("validateSourceResponse",validateSourceResponse);
        return this.saveCurrentSource(validateSourceResponse);
      }).then(saveCurrentSourceResponse => {
          console.log("saveCurrentSourceResponse",saveCurrentSourceResponse);
        return saveCurrentSourceResponse;
      });
    resolve(isValid);
  });
}

A: First, if you're using an async method, there's no need for directly accessing the promises at all, just use await:
async validate() {
    return (
        await this.saveSourceResponse() &&
        await this.validateSource() &&
        await this.saveCurrentSource()
    );
}

(I've also added a parallel version below.)
(I'm assuming saveCurrentSource doesn't actually need the argument you're passing to it.)
If you did want to access the promises (e.g., not use async on validate), you'd use && in each then handler — and wouldn't use new Promise, as there's no reason to:
validate() {
    return this.saveSourceResponse()
        .then(isValid => isValid && this.validateSource())
        .then(isValid => isValid && this.saveCurrentSource());
}

If my assumption about saveCurrentSource is incorrect, we'd adjust those accordingly:
async validate() {
    return (
        await this.saveSourceResponse() &&
        await this.validateSource() &&
        await this.saveCurrentSource(true) // `true` because this won't get executed
                                           // if `this.validateSource()` resolves
                                           // to `false`
    );
}

Or:
validate() {
    return this.saveSourceResponse()
        .then(isValid => isValid && this.validateSource())
        .then(isValid => isValid && this.saveCurrentSource(true)); // `true` again,
                                                                   // see above
}

As Sescudero points out, if those can run in parallel, we should run them in parallel:
async validate() {
    const results = await Promise.all([
        this.saveSourceResponse(),
        this.validateSource(),
        this.saveCurrentSource()
    ]);
    return results.every(valid => valid);
}

...which is very much the same if not using async:
validate() {
    return Promise.all([
        this.saveSourceResponse(),
        this.validateSource(),
        this.saveCurrentSource()
    ]).then(results => results.every(valid => valid));
}

A: Your last then is returning saveCurrentSourceResponse. You need it to return all the other returned responses, too, perhaps by storing them in a local variable like so:
async validate() {
  return new Promise(resolve => {
    let responses = [];
    let isValid = this.saveSourceResponse()
      .then(saveSourceResponse => {
        responses.push({saveSourceResponse});
      console.log("saveSourceResponse",saveSourceResponse);
        return this.validateSource();
      }).then(validateSourceResponse => {
        responses.push({validateSourceResponse});
          console.log("validateSourceResponse",validateSourceResponse);
        return this.saveCurrentSource(validateSourceResponse);
      }).then(saveCurrentSourceResponse => {
        responses.push({saveCurrentSourceResponse});
          console.log("saveCurrentSourceResponse",saveCurrentSourceResponse);
        return responses;
      });
    resolve(isValid);
  });
}


text:
Q: Access a given cell of a DataTable in C# It may seem easy but I cannot find the way: dt.Rows[r].Cells[c] does not work for DataTable.
This is what I have tried. I do not have other ideas.

A: dt.Rows[r] should return a DataRow assuming r is an int value between 0 and dt.Rows.Count-1 inclusive.
To get a specific cell value from a DataRow you use one of it's indexers, so you don't need the .Cells - you can just do dt.Rows[r][c] where c is either an int, a string or a DataColumn


text:
Q: Combine MultiIndex columns to a single index in a pandas dataframe With my code I integrate 2 databases in 1. The problem is when I add one more column to my databases, the result is not as expected. Use Python 2.7
code:
import pandas as pd
import pandas.io.formats.excel
import numpy as np

# Leemos ambos archivos y los cargamos en DataFrames
df1 = pd.read_excel("archivo1.xlsx")
df2 = pd.read_excel("archivo2.xlsx")

df = (pd.concat([df1,df2])
        .set_index(["Cliente",'Fecha'])
        .stack()
        .unstack(1)
        .sort_index(ascending=(True, False)))

m = df.index.get_level_values(1) == 'Impresiones'
df.index = np.where(m, 'Impresiones', df.index.get_level_values(0))

# Creamos el xlsx de salida
pandas.io.formats.excel.header_style = None

with pd.ExcelWriter("Data.xlsx",
                    engine='xlsxwriter',
                    date_format='dd/mm/yyyy',
                    datetime_format='dd/mm/yyyy') as writer:

    df.to_excel(writer, sheet_name='Sheet1')

archivo1:
Fecha       Cliente     Impresiones Impresiones 2   Revenue
20/12/17    Jose        1312        35              $12
20/12/17    Martin      12          56              $146
20/12/17    Pedro       5443        124             $1,256
20/12/17    Esteban     667         1235            $1

archivo2:
Fecha       Cliente     Impresiones Impresiones 2   Revenue
21/12/17    Jose        25          5               $2
21/12/17    Martin      6347        523             $123
21/12/17    Pedro       2368        898             $22
21/12/17    Esteban     235         99              $7,890

Hope Results:

I tried with m1 = df.index.get_level_values(1) == 'Impresiones 2' df.index = np.where(m1, 'Impresiones 2', df.index.get_level_values(0)) but I have this error: IndexError: Too many levels: Index has only 1 level, not 2

A: The first bit of the solution is similar to jezrael's answer to your previous question, using concat + set_index + stack + unstack + sort_index.
df = pd.concat([df1, df2])\
       .set_index(['Cliente', 'Fecha'])\
       .stack()\
       .unstack(-2)\
       .sort_index(ascending=[True, False])

Now comes the challenging part, we have to incorporate the Names in the 0th level, into the 1st level, and then reset the index.
I use np.insert to insert names above the revenue entry in the index.
i, j = df.index.get_level_values(0), df.index.get_level_values(1)
k = np.insert(j.values, np.flatnonzero(j == 'Revenue'), i.unique())

Now, I create a new MultiIndex which I then use to reindex df -
idx = pd.MultiIndex.from_arrays([i.unique().repeat(len(df.index.levels[1]) + 1), k])
df = df.reindex(idx).fillna('')

Now, drop the extra level -
df.index = df.index.droplevel()

df

Fecha        20/12/17 21/12/17
Esteban
Revenue            $1   $7,890
Impresiones2     1235       99
Impresiones       667      235
Jose
Revenue           $12       $2
Impresiones2       35        5
Impresiones      1312       25
Martin
Revenue          $146     $123
Impresiones2       56      523
Impresiones        12     6347
Pedro
Revenue        $1,256      $22
Impresiones2      124      898
Impresiones      5443     2368


text:
Q: JsonParseException while importing JSON to elasticsearch I am trying to import some json data into my elasticsearch instance and getting the following error:
{
  "error" : "JsonParseException[Unexpected end-of-input: expected close marker for ARRAY (from [Source: [B@7110db07; line: 1, column: 0])\n at [Source: [B@7110db07; line: 1, column: 3]]",
  "status" : 500
}

I am using an Ubuntu (14.04) running on VirtualBox and this is the command I used to import the data:
url -XPOST 'localhost:9200/mydata/fields/_bulk?pretty' --data-binary @mydata.json

And here is my JSON sample:
[
  {
    "field1":"sometext",
    "field2":"O",
    "field3":"TEXT",
    "field4":"CR",
    "field5":"09:38.0",
    "field6":"09:38.0",
    "field7":"14:13.0",
    "field8":"NULL",
    "field9":"NULL",
    "field10":"0",
    "field11":"5",
    "field12":"NULL",
    "field13":"NULL",
    "field14":"4",
    "field15":"0"
  },
  {
    "field1":"othertext",
    "field2":"O",
    "field3":"TEXT",
    "field4":"CR",
    "field5":"09:38.0",
    "field6":"09:38.0",
    "field7":"14:13.0",
    "field8":"NULL",
    "field9":"NULL",
    "field10":"0",
    "field11":"5",
    "field12":"NULL",
    "field13":"NULL",
    "field14":"4",
    "field15":"0"
  },
]

Is is possible to import a JSON array using the bulk API?

A: Your json doesnt have to contain line breaks in the bulk API, since the API uses the line break as a delimiter. From elasticsearch documentation here http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/docs-bulk.html

Because this format uses literal \n's as delimiters, please be sure
  that the JSON actions and sources are not pretty printed.


text:
Q: MCD43A3 MODIS products I have MCD43A3 product and I am using that to get the albedo values(Black sky and White Sky). I have some in-situ snow depth data, corresponding to which I want to get these albedo values.
For most of the in-situ data I'm getting a value of 32767, which is a fill value for the product. For some data I'm getting, a value like 908,889,976 which is multiplied by scale factor of 0.0010 to get the albedo values like .908,.889,.976.
My question is what should I do about the 32767 values which I am getting for most part of my data? Does getting this type of value mean that the image has noise or error? I have little experience with MCD products, any kind of help would be appreciated.
Thanks,
GBh

A: You may want to check this page:
https://lpdaac.usgs.gov/products/modis_products_table/mcd43a3
32767 is actually the fill value, so that's NO DATA (to be removed prior to rescaling). Then rescale the pixel values with 0.0010.


text:
Q: MEEP install in Google Colab I am trying to use Google Colab to install MEEP.
!wget -c https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh
!chmod +x Miniconda3-latest-Linux-x86_64.sh
!bash ./Miniconda3-latest-Linux-x86_64.sh -b -p ./anaconda
import os
os.environ['PATH'] += ":/content/anaconda/bin"
!conda create -n mp -c conda-forge pymeep
import sys
sys.path.append('/content/anaconda/envs/mp/lib/python3.8/site-packages/')

I copied the code from here: https://gist.github.com/venky18/e24df1e55502e2d6523881b3f71c0bff.
However, it turns out an error message:

ImportError: /content/anaconda/envs/mp/lib/python3.9/site-packages/meep/_meep.so: undefined symbol: PyCMethod_New

How do I modify my code to install it correctly?

A: From here. This works currently:
!wget -c https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh
!chmod +x Miniconda3-latest-Linux-x86_64.sh
!bash ./Miniconda3-latest-Linux-x86_64.sh -b -u -p /usr/local
import os
if os.path.isdir('/content/anaconda'): root_path = '/content/anaconda'
else: root_path = '/usr/local/'
os.environ['PATH'] += f":{root_path}/bin"
!conda create -n mp -c conda-forge pymeep python=3.7 -y
print(">> ", root_path)
import sys
sys.path.append(f'{root_path}envs/mp/lib/python3.7/site-packages/')

I believe the problem with the code snippet you linked was that currently the colab python default version is 3.7.12. Conda now defaults to 3.8. Trying to use packages from a 3.8 install in a 3.7 install is asking for trouble. Adding python=3.7 to the conda create line forces conda to use python 3.7, so the right packages are installed.


text:
Q: Powershell - Extract first line from CSV files and export the results Thanks in advance for the help.
I have a folder with multiple CSV files.  I'd like to be able to extract the first line of each of the files and store the results in a separate CSV file.   The newly created CSV file will have the first column as the file name and the second column to be the first line of the file.
The output should look something like this (as an exported CSV File):
FileName,FirstLine
FileName1,Col1,Col2,Col3
FileName2,Col1,Col2,Col3

Notes:
There are other files that should be ignored.  I'd like the code to loop through all CSV files which match the name pattern.  I'm able to locate the files using the below code:
$targetDir ="C:\CSV_Testing\"
Get-ChildItem -Path $targetDir -Recurse -Filter "em*"

I'm also able to read the first line of one file with the below code:
Get-Content C: \CSV_Testing\testing.csv | Select -First 1

I guess I just need someone to help with looping through the files and exporting the results.  Is anyone able to assist?
Thanks

A: You basically need a loop, to enumerate each file, for this you can use ForEach-Object, then to construct the output you need to instantiate new objects, for that [pscustomobject] is the easiest choice, then Export-Csv will convert those objects into CSV.
$targetDir = "C:\CSV_Testing"
Get-ChildItem -Path $targetDir -Recurse -Filter "em*.csv" | ForEach-Object {
    [pscustomobject]@{
        FileName  = $_.Name
        FirstLine = $_ | Get-Content -TotalCount 1
    }
} | Export-Csv path\to\theResult.csv -NoTypeInformation

I have assumed the files actually have the .Csv extension hence changed your filter to -Filter "em*.csv", if that's not the case you could use the filter as you currently have it.


text:
Q: Are there any signs that the circumstances of Voldemort's conception influenced his magical abilities? Voldemort could feel no love due to the fact that his (witch) mother conceived him when his (muggle) father was under the influence of a powerful love potion. The love potion cannot create actual love, only infatuation, something that was addressed by J.K. Rowling when she said something along the lines of;

"this would be the result of such a loveless/evil union".

Is there any evidence to suggest that the love potion (or anything else about the manner of his conception) made him preternaturally powerful at magic or augmented his intelligence, handsomeness or otherwise any other skill or capability?
Full quote here:

Ravleen: How much does the fact that voldemort was conceived under a
  love potion have to do with his nonability to understand love is it
  more symbolic
J.K. Rowling: It was a symbolic way of showing that he came from a
  loveless union – but of course, everything would have changed if
  Merope had survived and raised him herself and loved him.
J.K. Rowling: The enchantment under which Tom Riddle fathered
  Voldemort is important because it shows coercion, and there can't be
  many more prejudicial ways to enter the world than as the result of
  such a union.

A: No
The quote you provided:

J.K. Rowling: It was a symbolic way of showing that he came from a loveless union – but of course, everything would have changed if Merope had survived and raised him herself and loved him.
J.K. Rowling: The enchantment under which Tom Riddle fathered Voldemort is important because it shows coercion, and there can't be many more prejudicial ways to enter the world than as the result of such a union.

The implication, based on my emphasized parts, is that Voldemort's inability to love was due to the fact that his father had no love for him, and his mother wasn't there to provide him love. Had he been raised by a loving parent, everything would have been different for him, Tom Riddle.
There's no implication that the circumstances of the union of his parents had any effect on his magical abilities. However, it should be readily obvious that Voldemort's sociopathic ways enabled him to pursue darker and deadlier arts than any other dark wizards, because he had no regard for the lives of others.

Darchey: Did voldemort ever love a girl
J.K. Rowling: No, he loved only power, and himself. He valued people whom he could use to advance his own objectives.


text:
Q: How to use "multi-threading" in python with ROS services and serial comunication? I want to run multiple process in python with ROS services and serial communication (between Raspberry Pi and ESP32 Microcontroller) in my robot. The software schematic in the robot is shown in this image
I start doing in C++ as can see from this link How to use ROS services and serial communication with posix and semaphores in C++? but I realized that my modules for serial communication and the ODOM(Pressure, IMU) read are in python.
So,  the structure of the program should be the following one. First I Open Serial port (Serial communication of the Raspberry PI 4). While the Serial is Open Two processes are running
First one, the main one run automatically and do the following: The thread ask for ODOM Updates(Pressure and IMU from the microcontroller) and Publish them. Also every 0.3 seconds check the modem inbox and if something new it publish.
The other one only on DEMAND from ROS Services detect that there is new message in the modem inbox do HALT( on the first main Process) and execute (publish) on the serial Port. Then the first process resume with normal work
So I trying to do first some pseudo python code that looks like these But I need help as Im new to python and multithreading. Here it is
#!/usr/bin/env python3

from sys import ps1
import rospy
import numpy as np
from os import system
import time
import threading
import Microcontroller_Manager_Serial as Serial
import IMU_Functions as IMU
import Pressure_Functions as Pressure
from std_msgs.msg import Float32

mutex = threading.Lock()

from std_msgs.msg import String
Communication_Mode_ = 0 # Serial Communication

pub_pressure = rospy.Publisher('depth',Float32,queue_size=1)

P0 = 1.01325 #Default Pressure

def callback(data):
    global P0
    mutex.acquire()
    while (Serial.Serial_Port_Standard()): # While serial Port is open

        try:
            data_received_pressure = Pressure.Pressure_Get_Final_Values(1,1)
            data_received_imu = IMU.IMU_Get_Values(1, 1)
            P1 = (np.int16((data_received_pressure[6]<<24) | (data_received_pressure[7]<<16) | (data_received_pressure[8]<<8) | (data_received_pressure[9])))/10000
            P0 = (np.int16((data_received_pressure[6]<<24) | (data_received_pressure[7]<<16) | (data_received_pressure[8]<<8) | (data_received_pressure[9])))/10000

            P = P1 - P0 # Relative Measured Pressure
            pressure = P
            pub_pressure.publish(pressure)
         except:
             print ("pressure not obtained")

        Modem.Send_Data(Communication_Mode, receiver_ID, data_size, data_to_send)

def listener():

# Not sure how to check every 0.3 seconds the modem inbox and if something new it publish. And also the  DEMAND from ROS Services detect that there is new message in the modem inbox do HALT( on the first main Process) and execute (publish) on the serial Port. Then the first process resume with normal work

For the modem check up I though need something like this , but im not sure.
def callback_modem(data_in):

        data_in = Serial.Serial_Port_Receive_Data(20,0.2)
        if (data_in[0] == 91) # Received data from acoustic modem
        rt = RepeatedTimer(1, data_in, "Recieved Data") # it auto-starts, no need of rt.start()
        modem_data= data_in
        pub_modem.publish(modem_data)

        try:
            sleep(0.3) # your long-running job goes here...
        finally:
            rt.stop() # better in a try/finally block to make sure the program ends!

The third thread with ROS Services callback should be like this?
def handle_ros_service(req):
    data_received_temperature = TEMPERATURE.TEMPERATURE_Get_Values(1, 1)
    Tempetrature = (np.int16((data_received_imu[6]<<24) | (data_received_imu[7]<<16) | (data_received_imu[8]<<8) | (data_received_imu[9])))/10000
    mutex.acquire(blocking=True)
    return handle_ros_service(req.Tempetrature)

def publish_on_serial():
    # send temperature over serial port
    mutex.release()

A: You could build a default, simple node with two callbacks, one of which is your message callback for the subscribed ROS topic, and one of which is a callback to a TimerEvent which can be called repeatedly every 0.3 seconds. You need to start the TimerEvent before rospy.spin() in the main.
The code could look like this:
#!/usr/bin/env python

import threading
import rospy
from std_msgs.msg import String

mutex = threading.Lock()

def msg_callback(msg):
    # reentrang processing
    mutex.acquire(blocking=True)
    # work serial port here, e.g. send msg to serial port
    mutex.release()
    # reentrant processing

def timer_callback(event):
    # reentrant processing
    mutex.acquire(blocking=True)
    # work serial port here, e.g. check for incoming data
    mutex.release()
    # reentrant processing, e.g. publish the data from serial port

def service_callback(req):
    # read out temperature
    mutex.acquire(blocking=True)
    # send temperature over serial port
    mutex.release()

if __name__ == '__main__':
    # initialize serial port here
    rospy.init_node('name')
    rospy.Subscriber('/test_in', String, msg_callback)
    rospy.Service('on_req', Empty, service_callback)
    rospy.Timer(rospy.Duration(0.3), timer_callback)
    rospy.spin()

In fact, rospy starts two different threads for the callbacks. However, these threads are not running in parallel on different cores due to the GIL but they get scheduled and switch execution at certain system calls, e. g., when calling IO operations. Hence, you still need to sync your threads with a Lock as you did in your question.


text:
Q: CMAKE COMPILER_CXX_ID behaviour Does
$<COMPILER_CXX_ID:Clang>

will return 1 for Clang and AppleClang
According to the doc I would say yes but I'm not sure...

1 if the CMake-id of the CXX compiler matches comp, otherwise 0

src: https://cmake.org/cmake/help/latest/manual/cmake-generator-expressions.7.html
src: https://cmake.org/cmake/help/latest/variable/CMAKE_LANG_COMPILER_ID.html

A: TLDR: When using $<CXX_COMPILER_ID:Clang> and having CMP0025 to NEW then AppleClang won't match it.
Matching both
First I suppose the policy CMP0025 is set to NEW to get AppleClang on MacOS with clang provided by Xcode
if (POLICY CMP0025)
  cmake_policy(SET CMP0025 NEW)
endif()

To match both compilers with CMP0025 set to NEW you have two options
Option 1
first create a variable:
if("${CMAKE_CXX_COMPILER_ID}" MATCHES "Clang")
  set(USING_CLANG ON)
else()
  set(USING_CLANG OFF)
endif()

note: notice the use of MATCHES instead of EQUALS
Then you can use it in your generator expression:
target_compile_definition(target PUBLIC
  $<$<BOOL:${USING_CLANG}>:-DUSE_CLANG>)

Option 2
You may also use:
target_compile_definition(target PUBLIC
$<$<OR:$<CXX_COMPILER_ID:Clang>,$<CXX_COMPILER_ID:AppleClang>>:-DUSE_CLANG>

Annexe
You can find a working example at https://github.com/Mizux/cmp0025
note: Don't hesitate to look at the Travis-CI log (by clicking on the build badge)


text:
Q: Complex numbers proof using modulus and conjugates The question:
If $\alpha ,  \beta$ are complex numbers where $\alpha \ne \beta$ and $|\alpha|=1$.
Prove that $|\frac{\alpha \overline{\beta}-1}{\alpha-\beta}| =1$

A: $$|\alpha\bar\beta-1|=|\bar\beta-\alpha^{-1}|=|\bar\beta-\bar\alpha|=|\beta-\alpha|$$

A: This is a visual demonstration. If you are looking for a mathematically rigorous answer, @Kenta S has beautifully solved it in a single line.
You may know that when we multiply complex numbers, their modulus get multiplied and their arguments get added up.
WLOG, lets represent the complex numbers on the argand plane as:

Now, conjugate of a complex number is obtained by reflecting the number about the real number line

As $\alpha$ is unimodular, so multiplying it with any complex number would mean a rotation by an angle $arg(\alpha)$

$|α\barβ−1|$ is the distance between the point $1$ and the point $α\barβ$
Similarly, $|α-β|$ is the distance between the points corresponding to $α$ and $β$. i.e. the length of the segments represented by f and g in purple in the following diagram:

Which can be shown equal by showing the following orange triangles congruent. Proof left
for the reader

Hence, $|α-β|=|α\barβ−1|$

A: Hint:
It comes down to proving
$$\biggl|\frac{\alpha \bar{\beta}-1}{\alpha-\beta} =1\biggr|^2 =1,$$
i.e., since  $\;|z|^2=z\bar z$,
$$ \frac{\alpha \bar\beta -1}{\alpha-\beta}\,\frac{\bar\alpha \beta -1}{\bar\alpha-\bar\beta}=1\iff (\alpha \bar\beta -1)(\bar\alpha \beta -1)=(\alpha-\beta)(\bar\alpha-\bar\beta).$$


text:
Q: Ehcache statistics thread not getting timeout We are using ehcache 2.7 version in our application. As part of performance test, we observed that there are more than 8000 threads in waiting state. These all threads were statistics threads created by ehcache. Is there any configuration which can be used to keep this thread count limited. We can't upgrade to newer version at this point of time. Please suggest.

A: This was happening due to the way ehcache CacheManager works. In the ehcache 2.7 version, the number statistics threads created are equal to the number of processors per CacheManager. As we had 32 processor machine and more than 200 cache managers this number grew to 8000. The following two issues which we are planning to fix -
1. Upgrade the ehcache to newer version where it creates only 1 statistics thread per cache manager.
2. Use single cache manager for multiple identical caches.
3. Destroy the cache manager if cache is flushed.
Thanks!


text:
Q: AWS return callback within a callback I'm wanting to return a value in the main of my AWS function. I'm having trouble getting the data to pass from the first callback so I can send it to the final one.
  /** module used for outbound http requests */
    var request = require('request');

    /** module used for parsing XML easily. https://www.npmjs.com/package/xml2js*/
    var parseString = require('xml2js').parseString;
exports.handler = (event, context, callback) => {

    // testing array of coordinates
    var arrayOfPoints = [39.7683800, -86.1580400, 41.881832, -87.623177];
    var results = getXMLFromNOAA(arrayOfPoints);
    callback(null, results); // <- returns 'undefined' in the AWS console. I'm assuming race condition.
};

/**
* getXMLFromNOAA
*
* This is a function used for figuring out the functionality of NOAA XML parsing
*
* @param arrayOfPoints {Array[Double]} - An evenly numbered index array of latitudes and longitudes
*
* @return result {XML/JSON} - weather information abled to be parsed
*/
function getXMLFromNOAA(arrayOfPoints, callback) {

    var baseURL = "http://graphical.weather.gov/xml/sample_products/browser_interface/ndfdXMLclient.php?whichClient=NDFDgenLatLonList&lat=&lon=&listLatLon=";

    // for-loop getting all points and dynamically adding them to the query url string
    // iterate 2 at a time since they are coupled coordinates (e.g. [lat1, lng1, lat2, lng2, ... latN, lngN])
    for(var i = 0; i < arrayOfPoints.length; i = i + 2)
    {
        // if we're at the end of the arrayOfPoints, finish up the chain of query coordinates
        if( (i+2) == arrayOfPoints.length)
        {
            baseURL = baseURL.concat(arrayOfPoints[i]);
            baseURL = baseURL.concat("%2C");
            baseURL = baseURL.concat(arrayOfPoints[i+1]);
        }
        else
        {
            baseURL = baseURL.concat(arrayOfPoints[i]);
            baseURL = baseURL.concat("%2C");
            baseURL = baseURL.concat(arrayOfPoints[i+1]);
            baseURL = baseURL.concat("+");
        }
    }

    // TIME
    baseURL = baseURL.concat("&lat1=&lon1=&lat2=&lon2=&resolutionSub=&listLat1=&listLon1=&listLat2=&listLon2=&resolutionList=&endPoint1Lat=&endPoint1Lon=&endPoint2Lat=&endPoint2Lon=&listEndPoint1Lat=&listEndPoint1Lon=&listEndPoint2Lat=&listEndPoint2Lon=&zipCodeList=&listZipCodeList=&centerPointLat=&centerPointLon=&distanceLat=&distanceLon=&resolutionSquare=&listCenterPointLat=&listCenterPointLon=&listDistanceLat=&listDistanceLon=&listResolutionSquare=&citiesLevel=&listCitiesLevel=&sector=&gmlListLatLon=&featureType=&requestedTime=&startTime=&endTime=&compType=&propertyName=&product=time-series&begin=2016-09-04T00:00:00&end=2016-09-11T00:00:00");

    // CHARACTERISTICS REQUESTED
    // http://graphical.weather.gov/xml/docs/elementInputNames.php
    baseURL = baseURL.concat("&Unit=e&maxt=maxt&mint=mint&temp=temp&appt=appt&rh=rh&sky=sky&wwa=wwa&iceaccum=iceaccum&ptornado=ptornado&phail=phail&ptstmwinds=ptstmwinds&pxtornado=pxtornado&pxhail=pxhail&ptotsvrtstm=ptotsvrtstm&wgust=wgust");

    // Used for testing and seeing the final result
    console.log(baseURL);

    request(baseURL, function (error, response, body)
    {
        if (!error && response.statusCode == 200)
        {
            parseString(body, function (err, result) {
                console.log('inside parseString: ' + result); // <- this prints but it won't show up in the main
                // callback(null, result); <- doesnt work
                return result; // doesnt work either
            });
        }
    })
}

I want to be able to make my code more modular for scalability. I know theres a way to take the async process of the getXMlFromNOAA and perform them iteratively. I'm just not as familiar with JavaScript as I should be. Any help would really be appreciated.

A: You can use async module to make it more readable and flexible and also free from the asynchronous issue.
Write your stuff something like this
/** module used for outbound http requests */
var request = require('request');
var async = require('async');

/** module used for parsing XML easily. https://www.npmjs.com/package/xml2js*/
var parseString = require('xml2js').parseString;
exports.handler = (event, context, callback) => {

    async.waterfall([

        function(next) {
            // testing array of coordinates
            var arrayOfPoints = [39.7683800, -86.1580400, 41.881832, -87.623177];
            var results = getXMLFromNOAA(arrayOfPoints, next);

        },
        function(baseURL, next) {

            request(baseURL, function(error, response, body) {
                if (!error && response.statusCode == 200) {
                    parseString(body, function(err, result) {
                        console.log('inside parseString: ' + result); // <- this prints but it won't show up in the main
                        if (!err)
                            next(null, result);
                    });
                }
            })

        }
    ], function(err, result) {
        if (!err) {
            callback(null, results); // <- returns 'undefined' in the AWS console. I'm assuming race condition.
        }

    })

};

/**
 * getXMLFromNOAA
 *
 * This is a function used for figuring out the functionality of NOAA XML parsing
 *
 * @param arrayOfPoints {Array[Double]} - An evenly numbered index array of latitudes and longitudes
 *
 * @return result {XML/JSON} - weather information abled to be parsed
 */
function getXMLFromNOAA(arrayOfPoints, next) {

    var baseURL = "http://graphical.weather.gov/xml/sample_products/browser_interface/ndfdXMLclient.php?whichClient=NDFDgenLatLonList&lat=&lon=&listLatLon=";

    // for-loop getting all points and dynamically adding them to the query url string
    // iterate 2 at a time since they are coupled coordinates (e.g. [lat1, lng1, lat2, lng2, ... latN, lngN])
    for (var i = 0; i < arrayOfPoints.length; i = i + 2) {
        // if we're at the end of the arrayOfPoints, finish up the chain of query coordinates
        if ((i + 2) == arrayOfPoints.length) {
            baseURL = baseURL.concat(arrayOfPoints[i]);
            baseURL = baseURL.concat("%2C");
            baseURL = baseURL.concat(arrayOfPoints[i + 1]);
        } else {
            baseURL = baseURL.concat(arrayOfPoints[i]);
            baseURL = baseURL.concat("%2C");
            baseURL = baseURL.concat(arrayOfPoints[i + 1]);
            baseURL = baseURL.concat("+");
        }
    }

    // TIME
    baseURL = baseURL.concat("&lat1=&lon1=&lat2=&lon2=&resolutionSub=&listLat1=&listLon1=&listLat2=&listLon2=&resolutionList=&endPoint1Lat=&endPoint1Lon=&endPoint2Lat=&endPoint2Lon=&listEndPoint1Lat=&listEndPoint1Lon=&listEndPoint2Lat=&listEndPoint2Lon=&zipCodeList=&listZipCodeList=&centerPointLat=&centerPointLon=&distanceLat=&distanceLon=&resolutionSquare=&listCenterPointLat=&listCenterPointLon=&listDistanceLat=&listDistanceLon=&listResolutionSquare=&citiesLevel=&listCitiesLevel=&sector=&gmlListLatLon=&featureType=&requestedTime=&startTime=&endTime=&compType=&propertyName=&product=time-series&begin=2016-09-04T00:00:00&end=2016-09-11T00:00:00");

    // CHARACTERISTICS REQUESTED
    // http://graphical.weather.gov/xml/docs/elementInputNames.php
    baseURL = baseURL.concat("&Unit=e&maxt=maxt&mint=mint&temp=temp&appt=appt&rh=rh&sky=sky&wwa=wwa&iceaccum=iceaccum&ptornado=ptornado&phail=phail&ptstmwinds=ptstmwinds&pxtornado=pxtornado&pxhail=pxhail&ptotsvrtstm=ptotsvrtstm&wgust=wgust");

    // Used for testing and seeing the final result
    console.log(baseURL);
    //retun to callback after getting URL
    next(null, baseURL)
}

A: Thats not how callbacks work.  Change the handler to something like this:
exports.handler = (event, context, callback) => {
  var arrayOfPoints = [39.7683800, -86.1580400, 41.881832, -87.623177];
  getXMLFromNOAA(arrayOfPoints, function(result) {
    console.log('returned');
    console.log(result);
    callback(null, result);
  });
};

Also uncomment (go back) to the callback(result) in getXMLFromNOAA;
Also for NOAA there is a module.  Always search node-modules/npmjs.com/npms.io first before reinventing the wheel.  The example here https://github.com/thataustin/noaa-forecasts is very similar to what you are doing so I would start with that.
If you want to simplify async stuff in the future you can use babel with async and await keywords.  But you will need to make sure you really learn callbacks and promises first.


text:
Q: Exact Match without special characters in Solr My current field type in schema is currently defined to do exact match only;
<fieldType name="text_exact" class="solr.TextField" positionIncrementGap="100">
      <analyzer type="index">
         <tokenizer class="solr.KeywordTokenizerFactory"/>
         <filter class="solr.LowerCaseFilterFactory"/>
         <filter class="solr.TrimFilterFactory"/>
      </analyzer>
      <analyzer type="query">
         <tokenizer class="solr.KeywordTokenizerFactory"/>
         <filter class="solr.LowerCaseFilterFactory"/>
         <filter class="solr.TrimFilterFactory"/>
      </analyzer>
   </fieldType>

Now, I want to implement an exact match but special characters are removed during indexing.
I read that using StandardTokenizerFactory would remove the special characters. However, I don't want the side effect of it splitting the phrase on white spaces.
Is it possible to do StandardTokenizerFactory during indexing and then using in query KeywordTokenizerFactory?
Any other ideas?

A: You could use CharFilterFactories from Solr, there possible suitable factories for you:
solr.HTMLStripCharFilterFactory: it will remove all html special characters, like <, >, &, etc.
solr.PatternReplaceCharFilterFactory: it will replace all characters, you could use it like regexp:
<charFilter class="solr.PatternReplaceCharFilterFactory" pattern="([^a-z])" replacement=""/>

it will remove all non alphabetic chars, similar to this you could remove all your special characters.
For more info - https://wiki.apache.org/solr/AnalyzersTokenizersTokenFilters#CharFilterFactories


text:
Q: SQL Server INSERT INTO with WHERE clause I'm trying to insert some mock payment info into a dev database with this query:
INSERT
    INTO
        Payments(Amount)
    VALUES(12.33)
WHERE
    Payments.CustomerID = '145300';

How can adjust this to execute? I also tried something like this:
IF NOT EXISTS(
    SELECT
        1
    FROM
        Payments
    WHERE
        Payments.CustomerID = '145300'
) INSERT
    INTO
        Payments(Amount)
    VALUES(12.33);

A: I think you are trying to do an update statement (set amount = 12.33 for customer with ID = 145300)
UPDATE Payments
SET Amount = 12.33
WHERE CustomerID = '145300'

Else if you are trying to insert a new row then you have to use
IF NOT EXISTS(SELECT 1 FROM Payments WHERE CustomerID = '145300')
    INSERT INTO Payments(CustomerID,Amount)
    VALUES('145300',12.33)

Or if you want to combine both command (if customer exists do update else insert new row)
IF NOT EXISTS(SELECT 1 FROM Payments WHERE CustomerID = '145300')
    INSERT INTO Payments(CustomerID,Amount)
    VALUES('145300',12.33)
ELSE
    UPDATE Payments
    SET Amount = 12.33
    WHERE CustomerID = '145300'

A: If you want to insert new rows with the given CustomerID
INSERT
    INTO
        Payments(Amount,CustomerID )
VALUES(12.33,'145300');

else if you already have payment for the customer you can do:
UPDATE
        Payments
SET Amount = 12.33
WHERE
    CustomerID = '145300';

A: It sounds like having the customerID already set. In that case you should use an update statement to update a row. Insert statements  will add a completely new row which can not contain a value.

A: Do you want to perform update;
update Payments set Amount  = 12.33 where Payments.CustomerID = '145300'

A: i do inserts into a table if the record doesn't exist this way. may not be entirely what is after but it may be helpful
insert into x (a,b)
select 1,2
where 0=(select count(*) from x where a = 1 and b = 2)

A: Ok, looks like I actually need to just do an insert into the Payments table that has the correct CustomerID, as there are currently no Payments with that CustomerID, so I cannot update it.
I ran INSERT INTO Payments (CustomerID, Amount, PaymentTypeID) Values ('145300', 24.99, 8); and then SELECT * FROM Payments WHERE Payments.CustomerID = '145300'; to confirm and we're in business. Thanks everyone!

A: Better solution and without risk of deadlocks:
UPDATE Payments
    SET Amount = 12.33
WHERE CustomerID = '145300'

INSERT INTO Payments(CustomerID,Amount)
    SELECT '145300',12.33
WHERE @@ROWCOUNT=0

A: Try to update as below if you want to modify existing row,
UPDATE Payments SET Amount = 12.33 WHERE CustomerID = '145300';


text:
Q: Ubuntu(Xubuntu) will not boot after power failure I have Xubuntu installed with sda configured in LVM setup.  Previously, I have used older, standard partitioning with a root, /boot, and swap all on separate sda1,2,3.  I have always seemed to have problems with failing to boot after power loss, and I have learned to boot into a recovery mode and fsck, and this has fixed things reliably (side topic: Why in the hell isn't filesystem recovery more self-guided, perhaps prompted for when the system sees problems on boot?).
However, two days ago was my first power loss since switching to LVM (old drive was reporting imminent failure via SMART, so purchased a new HD).
If it tries a normal boot, the screen goes black, and it stays that way.
I boot into recovery, and can get to a Busybox/initramfs limited prompt. It reports "Waiting for root filesystem", then "Gave up waiting for root filesystem".  It offers a few hints that boot arguments may be incorrect (these worked for many months on this install), but also states "ALERT!  /dev/mapper/xubuntu--vg-root does not exist. Dropping to a shell!"
I have followed suggestions I have found elsewhere here on askubuntu, including to ls dev at the initramfs shell, and if I don't see the filesystem to wait 10 seconds and try again.  There were suggestions that RAID setup could be a problem, or setups installed dual-boot with wubi.  None of these applied.
Booting off a LiveCD, I can mount and read the contents of my hard drive. I have read suggestions to use lvm tools to get information and will post the following.  I suspect that I need to fix an error in the LVM-configured filesystems.
ubuntu@ubuntu:~$ sudo lvm pvscan
  PV /dev/sda1   VG xubuntu-vg      lvm2 [<465.76 GiB / 4.00 MiB free]
  Total: 1 [<465.76 GiB] / in use: 1 [<465.76 GiB] / in no VG: 0 [0   ]

ubuntu@ubuntu:~$ sudo lvm vgscan
  Reading volume groups from cache.
  Found volume group "xubuntu-vg" using metadata type lvm2

ubuntu@ubuntu:~$ sudo lvm lvscan
  ACTIVE            '/dev/xubuntu-vg/root' [464.80 GiB] inherit
  ACTIVE            '/dev/xubuntu-vg/swap_1' [976.00 MiB] inherit

I'm not entirely sure what to do from here, so it seems reasonable to try to fsck the xubuntu-vg root.
ubuntu@ubuntu:~$ sudo fsck /dev/xubuntu-vg/root
fsck from util-linux 2.32
e2fsck 1.44.4 (18-Aug-2018)
/dev/mapper/xubuntu--vg-root: clean, 538363/30466048 files, 48101510/121844736 blocks

it doesn't seem that either there is a problem there. Or that I am not doing things correctly.
Any suggestions as to what I am missing?  Thanks!
[Updated Info]
Back in town from work travel, and a little sad to see no suggestions. But I spent some time digging back into this after my morning coffee.
I looked over the steps I took earlier, and see that when I did my fsck /dev/xubuntu-vg/root, I was looking at the live session's mount. NOT my hard drive. So that explains a lot. Figure I would spell out what I am doing here, should anyone else find this thread and it might be useful to them...
When I mount the hard drive (clicked on it in the GUI file browser), it appears when I do the mount command: /dev/mapper/xubuntu--vg-root on /media/ubuntu/1d3ca2dc-c59a-4582-a538-8c529926b276 type ext4 (rw,nosuid,nodev,relatime,uhelper=udisks2) So, when I try to fdisk that, I get:
sudo fdisk /dev/mapper/xubuntu--vg-root
Welcome to fdisk (util-linux 2.32).
Changes will remain in memory only, until you decide to write them.
Be careful before using the write command.

The old ext4 signature will be removed by a write command.

Device does not contain a recognized partition table. Created a new DOS disklabel with disk identifier 0x5490643a.

Command (m for help):

I am VERY apprehensive about the warning that I will remove the old ext4 signature!
[Another Update]
Went ahead and did a
sudo fsck -f /dev/mapper/xubuntu--vg-root
fsck from util-linux 2.32
e2fsck 1.44.4 (18-Aug-2018)
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
/dev/mapper/xubuntu--vg-root: 538364/30466048 files (0.3% non-contiguous), 48101511/121844736 blocks

It did not report any errors with this lvm filesystem.  Yet, it still won't boot.
I also suspect I am talking to myself. This has to be repairable, as I can read the hard drive filesystem when booting from my LiveCD. Have also tried a few lvm tools, sudo vgchange --ignorelockingfailure -ay, then sudo lvscan --ignorelockingfailure, then re-tried the sudo fsck -f /dev/mapper/xubuntu--vg-root that the webpage recommended.
No success.


text:
Q: Setting focus to maximize button In SWT can I set focus to the maximize button of a view?
More concretely I want to set a tablist for a composite with setTabList() method, but I can't refer to the maximize button.

A: All the controls in a setTabList() call must be direct children of the Composite. Since the maximize button belongs to a ToolBar outside of the view you can't use it in the tab list.


text:
Q: HTML tag  appearing on live website only I am creating a website using php with javascript and jquery. Everything seems to be normal when I see the output locally, but when I upload it live, some parts of the website gets affected by the  tag. I did not even try to add this tag before.
My bootstrap grid does not stay on one row anymore and some of my paragraph tags and headers turn italic all of a sudden. What or where is the origin of this  tag?
Example:

This is my php for each to output the contents of my database. It echos a picture, a header tag, a paragraph tag and a "Read More" link.
Locally they are all the same, but in the live website as you can see, the second output has its "Read More" in italic only but the third one has it on every text.
<?php
  foreach($lstBlog as $rowBlog) {
    $datetime = new DateTime($rowBlog['createddate']);
  echo'
';
  echo'
';
  echo'';
  echo'
';
  echo'
'.$datetime->format('F j, Y').'
';
  echo'
'.$rowBlog['blog_name'].'
';
  echo'
';
  echo substr($rowBlog['blog_description'], 0, 100);
  echo strlen($rowBlog['blog_description']) > 100 ? ".....
" : "
";
  echo'';
  echo'
Read More

';
} ?>

A: I think that your issue might be coming from discrepancies between what you have in your local environment and what you have in the production environment. At a glance, just looking at the screenshot, I'm guessing that something in the second column opens the  tag and then doesn't close it.

This makes me think that this might be an issue with how you generate that excerpt in that section, are you stripping all the HTML? Just from the screenshot, I can see a situation where it's getting 'trimmed' and closing, not including the enclosing  tag.
If my theory is correct, what you'd have to do is ensure that the output that is generated for the excerpt doesn't include any HTML (stripped).
As mentioned in one of the comments by shadowdev to your original question, the relevant function that you're looking for is strip_tags()
A more in-depth explanation to accomplish what you're trying to do can be found in another question:
Truncate text containing HTML, ignoring tags