text:
Q: Read, Update XML column client side using Breeze JS Breeze render xml column (SQL xml data column) as it is (not converted to object as Breeze used to).
For example, bellow is data received client-side from Breeze :
<employee><firstname>Martin</firstname><lastname>MALONGA</lastname><age>74</age></employee>

*

*How to access this xml element at client-side using Breeze? are they functions like xquery inside breeze platform?

*How to update xml element client side and hope Breeze will transfer it to server?

For the 1st question I'd tried parser.parseFromString and get something but with a painful gymnastic labor; hope someone will pull out a better approch.

A: You can query the XML using jquery selectors.
Access element
var employee = $(returnedBreezeObservable());
var firstname = employee.children('firstname').text();

Change element
NOTE: the xmlToString function was taken from this question.
function xmlToString(xmlData) {
    var xmlString;
    //IE
    if (window.ActiveXObject){
        xmlString = xmlData.xml;
    }
    // code for Mozilla, Firefox, Opera, etc.
    else{
        xmlString = (new XMLSerializer()).serializeToString(xmlData);
    }
    return xmlString;
}

var employee = $(returnedBreezeObservable());
employee.children('firstname').text('John');
employee.children('lastname').text('Doe');
returnedBreezeObservable(xmlToString(employee));


text:
Q: Client Side Validation applied to fields which are dynamically available Ok I have been trying to find an answer on this for a couple of days unsuccessfully (with a few poorly worded questions along the way). So if you know of where an answer to this has already been discussed please point it out to me.
Here is my issue;
 I am working with a form that is built with kendo (i did not create it, and this is my first time working with kendo). part of the design calls for 2 or more optional fields that only appear when a criteria is met. For example if someone selects "2 part combo" or "3 part combo" in a drop down menu then the appropriate number of additional drop down items appear for the user to define the different parts of their combo. now those extra drop downs exist all the time on the page and simply get switched between being visible or hidden.
however when they are hidden their value is also null.
I need to have these fields validate as required ONLY when they are visible and not validate when they are not.
here is a sample of the code where it determines if the field is visible or hidden
    @model PhoenixOnlineMVC.Areas.EventManagement.Models.CompetitionPlannedElementItem

@Model.Index
@(Html.Kendo().DropDownListFor(m => m.SelectedTypeId)
          .HtmlAttributes(new { style = "width:120px" })
          .DataTextField("Text")
          .DataValueField("Value")
          .BindTo(Model.Types)
          )
@(Html.Kendo().DropDownListFor(m => m.SelectedElementId)
           .HtmlAttributes(new { style = "width:160px" })
           .DataTextField("Text")
           .DataValueField("Value")
           .Events(events => events.Select(@Model.SelectedFunctionName))
           .DataSource(source => source.Read(read => read.Action("GetCascadeElements", "Event")
                                                           .Data(@Model.DataFunctionName))
                                        .ServerFiltering(true))
           .Enable(false)
           .AutoBind(false)
           .CascadeFrom(@Model.TypeComboBoxName)
           )

    @{
              const string htmlHiddenAttributes = "width:120px; margin: 2px 4px 4px 0; display:none; ";
              const string htmlVisibleAttributes = "width:120px; margin: 2px 4px 4px 0;";

              if (Model.SelectedSuppElementId1 != null)
                  {
                      @Html.DropDownListFor(m => m.SelectedSuppElementId1, Model.SuppElements1, new { style = htmlVisibleAttributes })
                  }
              else
                  {
                      @Html.DropDownListFor(m => m.SelectedSuppElementId1, Model.SuppElements1, new { style = htmlHiddenAttributes })
                  }

this code comes from a .cshtml file that is used by the main view for the page to create the components. and all of it is contained within an Html.BeginForm on the main page.
the above code is used to create an instance of the SelectedSuppElementId fields multiple times in the main view page
If you don't have a suggestion for a solution perhaps point me to additional helpful information

A: Would this FIDDLE help you any?
It just looks at the css attribute display and tells you if the element is displayed or hidden.
JS
$('.hide').on('click', function(){
    $('.hideme').hide();
});
$('.show').on('click', function(){
    $('.hideme').show();
});
$('.validate').on('click', function(){
    $('.putmehere').html('');
    $('.dropdown').each(function(){
        if( $(this).css('display') == 'none' )
       {
         $('.putmehere').append('hidden ');
        }
         else
         {
         $('.putmehere').append('shown ');
         }
    });
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Test always times out, does not show promise output         browser.sleep(4000);
        var discount_type = element(by.id("discount_type"));
        var discount_value= element(by.id("discount_value"));
        var grandTotal    = element(by.id("grand-total"));
        var subtotal      = element(by.id("subtotal"));
        var delivery_fee  = element(by.id("delivery_fee"));

        var last = protractor.promise.defer();

        console.log("hallo");
        subtotal.getText().then(function(sub) {
          console.log("#############");
          console.log(sub);
          delivery_fee.getText().then(function(fee) {
            console.log(fee);
            var calc = parseFloat(sub) - parseFloat(fee) - parseFloat(config.promocodes.referral.discount);
            console.log(calc);
            last.fulfill(calc);
          });
        });
        last.then(function(calc) {
            console.log("final wait");
            expect(grandTotal.getText()).toBe("$" + calc);
        });

I need to calculate a value before I can be sure that my test ran ok.
In my tests, I always get to see "hallo" in the console.
Then I get a
> hallo
 A Jasmine spec timed out. Resetting the WebDriver Control Flow.
> F
>
> Failures: 1) Refer a user and apply referral code should assign
> referral discount to user   Message:
>     Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.   Stack:
>     Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
>         at Timer.listOnTimeout (timers.js:92:15)

It seems the code never enters the subtotal.getText() promise! Why is that???

A: You never return from the promise resolution function. And, you don't have to have a deferred:
var last = subtotal.getText().then(function(sub) {
  return delivery_fee.getText().then(function(fee) {
    return parseFloat(sub) - parseFloat(fee) - parseFloat(config.promocodes.referral.discount);
  });
});
last.then(function(calc) {
    expect(grandTotal.getText()).toBe("$" + calc);
});


text:
Q: (Precise) behavior of $f(x)=\frac{1}{x-x\log(x)}$ for $0Question
What is the behavior of $f(x)=\frac{1}{x-x\log(x)}$ for $0<x<1$?
Attempt
I know that the Taylor series does not exist for $f(x)$ at $x=0$. However, when I look at the graph of this function between $0$ and $1$ I feel that it decays exponentially (or like $1/x^n$) to $1$ as $x \rightarrow 1^-$. Is there any way of saying how fast it decays in this interval? I know that the Taylor expansion for $f(x)$ at $x=1$ is $1+1/2(x-1)^2+\mathcal{O}(x-1)^3$ but I actually want to say something like "$f(x)$ decreases exponentially in the interval $(0,1]$". Is this possible to say?
Sorry if my question is a bit informal. I do not know the mathematical terms necessary to express this idea.

A: $x-x\ln(x)=x(1-\ln(x))$ and since $\lim\limits_{x\to0^+}\ln(x)=-\infty$ then the $1$ is negligeable.
So $f(x)\sim\frac1{x\ln(x)}$ near $0^+$ also $x^{\alpha}\ln(x)\to 0$ for any $\alpha>0$ so the behaviour is very similar to $\frac1x$.
Near $1$ you already found the behaviour.
But beside these two critical points, we cannot say much except that it goes from something in $\frac 1x$ near $0$ to something in $\frac 1{x^2}$ near $1$ (not considering the translations).

A: One of fundamental inequalities on logarithm is:
$$ 1 - \frac1x \leq \log (x) \leq x-1 \quad\text{for all}\quad x > 0$$ Using if for your problem, you then have $$1 \leq \frac{1}{x-x\log(x)}\leq \frac 1{x(2-x)}$$


text:
Q: In a group of order $pq^2$, if p divides $|Z(G)|$, then G is abelian I want to prove that in a group of order $pq^2$, if $p$ divides $|Z(G)|$, then $G$ is abelian.
I know that in this case, the order of $G/Z(G)$ must be $q^2$.
If $G/Z(G)\simeq \mathbb{Z}/{q^2}\mathbb{Z}$, then we are done, because $\mathbb{Z}/{q^2}\mathbb{Z}$ is cyclic.
But what happens if $G/Z(G)\simeq \mathbb{Z}/{q}\mathbb{Z}\times \mathbb{Z}/{q}\mathbb{Z}$? I think I'm missing something trivial..

A: You do not know that $G/Z(G)$ must have order $q^2$. In fact you are try to prove $G$ is abelian, which implies $Z(G) = G$ so you are actually trying to show $G/Z(G)$ has order $1$.
Note that since $p$ divides $|Z(G)|$, a sylow $p$, $S_p$ is central. Thus $1 \to S_p \to G \to G/S_p \to1$ is a short exact sequence with $S_p$ central and $G/S_p$ nilpotent (order $q^2$ is abelian). It follows that $G$ is nilpotent, and hence is the product of its Sylow subgroups $G = S_p \times S_q$ and $S_q$ has order $q^2$ and is hence abelian.

A: Let suppose $|Z(G)|=p$ (else $G/Z(G)$ is cyclic).
Let $S$ be the subgroup generated by an element $s$ of order $q$ and consider $C(S)$, the centralizer of $S$ (the biggest subgroup of $G$ such that every element of $C(S)$ commutes with every element of $S$).
What about the cardinality of this subgroup?

*

*On the one hand, by Sylow theorems, $s$ is contained in a $q$-Sylow $Q$, that have to be abelian, so $Q < C(S)$.

*On the other hand, the (unique) $p$-Sylow $P$ is contained in the center of $G$ and then $P < C(S)$.

Hence $C(S)=G$ (looking at their the cadinality) and then we have an absurd because this means that $|Z(G)| > p$.

A: Clearly $|Z(G)|=p$ and index$[G:Z(G)]=q^2$, so $Z(G)$ is normal Hall-subgroup. By the theorem of Schur-Zassenhaus it has a complement $H$, so $G=HZ(G)$, $H \cap Z(G) =1$. Hence $|H|=q^2$ and $H$ is abelian. But then $G=HZ(G)$ must be abelian.
Note without Schur-Zassenhaus: in general if $G/Z(G)$ is abelian, then $G$ is nilpotent. And hence $G$ is the direct product of its Sylow subgroups. In this case it follows that $G$ is abelian. By the way note that you must assume that $p \neq q$, otherwise the statement of the OP is not true.


text:
Q: Difference between {`${props.title} `} and {props.title} I see in some places, to get the value of title from props, we use
{`${props.title} `}

while in some other places, we use it
{props.title}

What is the difference?

A: The first option is using template literals, read further here from the documentation:

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.

The second option is just passing a string value to the attribute.
Consider the following:

const data = {
  title: 'random title'
};

console.log(data.title);
console.log(`${data.title}`);

I hope that helps!

A: The first one is used when you have to use some string literals. For eg, when you want to append something to your title in this case.
If you want to use only title, generally, the second one is used.

A: Both answers already here are good. I don't know the context of your question but in your exemple the difference between

{`${props.title} `}

and

{props.title}

is maybe because on the first one using the template literals there is an extra spacing before the last backtick.
It's usefull with jsx when you want to do something like

 {`${props.withExtraSpacing}: some text`}

instead of

 {props.withoutExtraSpacing} + " " + ": some text"


text:
Q: Excel VBA Extract Text from a Cell I have tried looking through Stack Overflow for previous suggestions but haven't found any that have worked.
Here is my situation: I am trying to look at a simple Excel sheet which shows someone's name, position, and then their "Role" which is a custom field I am creating. Right now, I am looking to just do "Engineers" but will also expand to things like "Admin Assistant" and "Manager". (The real spreadsheet is about 8100 lines long).
Here is an example of some test data:

All I need is to scan through the "Title" column, see if it matches a String (in this case, my test string is engineer), and then to copy the String and the remaining I or II or III or in some cases, IV after it.
I have heard about using a regular expression and have used them in SQL before, but am struggling coming up with what I need. Here is my current code where I tried using the MID function:
Sub GetRole()
' Custom function written to take role out of official title

strRole = "Engineer" ' String to check for
Dim lrow As Integer ' Number of Rows
Dim Role As String ' Role to write into adjacent cell

lrow = Cells(Rows.Count, "B").End(xlUp).Row

For i = lrow To 2 Step -1
    If InStr(1, Cells(i, 2), "Engineer") > 0 Then
        Role = Mid(Cells(i,3)), 1, 5)
    Cells.(i, 3).Value = Role
    End If
Next i

End Sub

But that didn't quite work. Any help or advice would be greatly appreciated. I am willing to provide any extra information necessary.

A: You can solve this using Regular Expressions. First you need to enable the reference which you do so by going to Tools > References... and enable Microsoft VBScript Regular Expressions 5.5

Then use the following code to generate your answers
Sub GetRole()
    ' Custom function written to take role out of official title

    ' Uncomment the below if using Early Binding i.e. you enable the reference
    ' Dim ReGex As New RegExp
    ' Comment below line if decide to use Late Binding (i.e. you enable the reference)
    Dim ReGex As Object
    Dim i As Long, lrow As Long ' Number of Rows

    ' Comment the below line if decide to use Late Binding (i.e. you enable the reference)
    Set ReGex = CreateObject("VBScript.RegExp")

    With ReGex
        .Global = True
        .IgnoreCase = True
        .Pattern = "(Engineer\sI*\b)"
    End With

    With ActiveSheet
        lrow = .Cells(.Rows.Count, "B").End(xlUp).Row
        For i = lrow To 2 Step -1
            If ReGex.test(.Cells(i, 2).Value2) Then .Cells(i, 3).Value2 = Trim(ReGex.Execute(Cells(i, 2).Value2)(0))
        Next i
    End With
End Sub

Generates output:

A: I think Excel formula will be easier to extend compared to debugging VBA and Regex:
=IF(ISNUMBER(  FIND("Engineer III", E4)), "Engineer III",
 IF(ISNUMBER(  FIND("Engineer II" , E4)), "Engineer II",
 IF(ISNUMBER(SEARCH("Engineer *I" , E4)), "Engineer I", "")))


text:
Q: Eclipse Indigo didn't find log4j.xml and hibernate.cfg.xml I'm using Eclipse indigo (3.7)
I added a hibernate config file and a logger config file, under "src" folder.
The application run but when I try to open the server connection I get:
log4j: Trying to find [log4j.xml] using context classloader     org.eclipse.core.runtime.internal.adaptor.ContextFinder@1787005.
log4j: Trying to find [log4j.xml] using     org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader@183e895 class loader.
log4j: Trying to find [log4j.xml] using ClassLoader.getSystemResource().
log4j: Trying to find [log4j.properties] using context classloader org.eclipse.core.runtime.internal.adaptor.ContextFinder@1787005.
log4j: Trying to find [log4j.properties] using org.eclipse.osgi.internal.baseadaptor.DefaultClassLoader@183e895 class loader.
log4j: Trying to find [log4j.properties] using ClassLoader.getSystemResource().
log4j: Could not find resource: [null].
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.annotations.Version).
log4j:WARN Please initialize the log4j system properly.
Hibernate Exception: hibernate.cfg.xml not found

I have no problems in other prject with the same structure.
The applications are RCP ( Rich Client Platform ).
What I need to know is how to make sure that Eclipse added correctly the "bin" and "source" folder to the classpath !!
If I look the project with the directory perspective I see the files below "bin" folder !!
I think that because of the first problem , hibernate could'nt  find theri config file !
Any idea ?
Best Reagards


text:
Q: Implementation of a Python encription code in PHP or NodeJS I am trying to implement a python encription code based on gzip and crypto library but i dont know the equivalent modules or functions in either php or node js
from Crypto.Cipher import DES, AES
def enclen(p):
   return ((16 - p % 16) & 0xF) + p + 4

def rsb(a, b):
return (0 - a + b) & 0xffffffff

def ands(a, b):
   return (a & b) & 0xffffffff

def _ror(val, bits, bit_size):
    return ((val & (2 ** bit_size - 1)) >> bits % bit_size) | \
           (val << (bit_size - (bits % bit_size)) & (2 ** bit_size - 1))

def __ROR4__(a, b):
    return _ror(a, b, 32)

def eor(a, b):
   return (a ^ b) & 0xffffffff

class Crypto(object):
    def __init__(self):
        self.key = b'!*ss!_defaul%t54'
       self.kl = 0x10
        self.sbox0 = bytes.fromhex(
        '637C777BF26B6FC53001672BFED7AB76CA82C97DFA5947F0ADD4A2AF9CA472'
        'C0B7FD9326363FF7CC34A5E5F171D8311504C723C31896059A071280E2EB27'
        'B27509832C1A1B6E5AA0523BD6B329E32F8453D100ED20FCB15B6ACBBE394A'
        '4C58CFD0EFAAFB434D338545F9027F503C9FA851A3408F929D38F5BCB6DA21'
        '10FFF3D2CD0C13EC5F974417C4A77E3D645D197360814FDC222A908846EEB8'
        '14DE5E0BDBE0323A0A4906245CC2D3AC629195E479E7C8376D8DD54EA96C56'
        'F4EA657AAE08BA78252E1CA6B4C6E8DD741F4BBD8B8A703EB5664803F60E61'
        '3557B986C11D9EE1F8981169D98E949B1E87E9CE5528DF8CA1890DBFE64268'
        '41992D0FB054BB16')
    self.plen = 0

def crypt(self, payload):
    if not isinstance(payload, bytes):
        payload = payload.encode('utf8')
    self.plen = len(payload)
    i = 0
    r = [00] * 16
    while i < self.kl:
        a = self.key[i]
        r[i] = self.sbox0[a]
        i += 1

    t = int.from_bytes(r[:4], 'big')
    r[:4] = int.to_bytes(t, 4, 'little')
    t = int.from_bytes(r[4:8], 'big')
    r[4:8] = int.to_bytes(t, 4, 'little')
    t = int.from_bytes(r[8:12], 'big')
    r[8:12] = int.to_bytes(t, 4, 'little')
    t = int.from_bytes(r[12:16], 'big')
    r[12:16] = int.to_bytes(t, 4, 'little')
    b = rsb(self.plen, 0)
    b = ands(b, 0xf)
    c = b + self.plen + 4

    result = [00] * enclen(self.plen)
    result[0] = 0x74
    result[1] = 0x63
    result[2] = 0x02
    result[3] = b
    result[4:len(payload) + 4] = payload

    i = 4
    while i != c:
        a = result[i]
        result[i] = self.sbox0[a]
        i += 1

    a = c - 4
    b = 0
    a = a >> 4
    d = 4
    while b < a:
        c = int.from_bytes(result[d:d + 4], 'big')
        e = int.from_bytes(r[:4], 'little')
        c ^= e
        result[d:d + 4] = int.to_bytes(c, 4, 'big')
        c = int.from_bytes(result[d + 4:d + 8], 'big')
        e = int.from_bytes(r[4:8], 'little')
        c = eor(e, __ROR4__(c, 24))
        result[d + 4:d + 8] = int.to_bytes(c, 4, 'big')
        c = int.from_bytes(result[d + 8:d + 12], 'big')
        e = int.from_bytes(r[8:12], 'little')
        c = eor(e, __ROR4__(c, 16))
        result[d + 8:d + 12] = int.to_bytes(c, 4, 'big')
        c = int.from_bytes(result[d + 12:d + 16], 'big')
        e = int.from_bytes(r[12:16], 'little')
        c = eor(e, __ROR4__(c, 8))
        result[d + 12:d + 16] = int.to_bytes(c, 4, 'big')
        b += 1
        d += 0x10
    return bytes(result)

I dont have much idea what really goes behind this code some byte size operations but i dont know what exactly happens
Either nodejs or php equivalent of this code or any idea to how to implement it in those lang or if those languages are supported this kind of operations I dont know

A: Node.js has really good modules that can handle compression and encryption.

*

*Crypto for cryptography related operations. It supports many algorithms to encrypt/hash stuff

*Zlib for compression. Supports algorithms like gzip, deflate, zip, etc...

The docs also include examples on how to use these modules, so make sure to check them


text:
Q: Does data saved to internal storage persist over sequential runs in Android Studio? I have an application that saves data onStop() to a file in the internal storage. And then when the application is started again it will attempt to retrieve that data that was stored there onStart().
I am currently testing my application through running the application through Android Studio onto my Google Pixel 2 (Android 8.1.0 API 27).
My question has three parts. Don't feel obligated to answer all parts.

*

*Since I am emulating the app on my device, are the internal storage files deleted when I close the app on my device? Or do they persist?

*Is this the same with SQLite and Shared Preferences? Or do they persist through emulation runs?

*If they are deleted what are the steps I should take in-order to test that my data management process is working? Should I place the apk on my device and then run/close it?

P.S.
I am a university student learning Android development, I have been scouring stack-overflow and Android documentation for information on data storing and the like. Its entirely likely that I missed something so if you know of some resource that might help me out here, I would greatly appreciate you sending it my way.

A: Have you tried?
Short answer is SQLite data and Shared Preferences will stick around unless you programmatically remove it, uninstall the app OR clear data from settings.


text:
Q: Quarter end from today's date I'm trying to get a quarter end date based on today's date, but I wanted to strip the time first. If I do that, the below code throws me an error on the last line AttributeError: 'datetime.datetime' object has no attribute 'to_period'
import pandas as pd
import datetime

today_datetime = datetime.date.today().strftime('%Y-%m-%d')
today_date = datetime.datetime.strptime(today_datetime, '%Y-%m-%d')
df['Qend'] = today_date.to_period("Q").end_time

Could you advise me, how to improve it to get the Quarter end of today's date without time, please?

A: Considering @Ezer-k comment, below is code, which insert quarter end date based on current date with stripped time.
today_datetime = pd.Timestamp.now()
# get month end stripped time
df['Qend'] = today_datetime.to_period('M').end_time
df['Qend'] = df['Qend'].dt.strftime('%Y-%m-%d')

I'm sure there might be better way also, but just to return with correct answer.


text:
Q: UIImagePickerController corrupts image I'm working on an app and I need to get bytes from an UIImage.
For the moment, I use UIImagePickerController, and get the UIImage like this,
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];

and then get data from UIImage using this code,
NSData *data = UIImageJPEGRepresentation(image, 1.0);

However, data appears to get corrupted in this case.
On other hand, I have add the jpeg to app's bundle, and tried to convert the image then to data,
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"mapa" ofType:@"jpeg"];
NSData *myData = [NSData dataWithContentsOfFile:filePath];

Surprisingly this works perfectly.
Here are my questions:

*

*How can I get the bytes of image selected from UIImagePickerController correctly?

*Is there a way to add photos to the bundle programmatically?

Thanks!
EDIT:
I have some metadata bytes on the original JPEG ("GEO-Information").
If i store the jpeg on the ipad, that metadata disappear, and I need them :S

A: Use the below code to store image in document directory;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,     NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *getImagePath = [documentsDirectory stringByAppendingPathComponent:@"savedImage.png"];
[data writeToFile:savedImagePath atomically:NO];

Here 'data' will be the NSData you have obtained from your image captured.


text:
Q: R while loop help needed So I've created a while loop to give a coordinate point, Xm and Ym, which follows a uniform distribution, where the point must be within a circle of radius 25. Below is the code for that:
outcome<-function()
{
done=0
while(done==0){
  Xm<-runif(1,-25,25)
  Ym<-runif(1,-25,25)
if (Xm^2+Ym^2<=25^2){
    z<-c(Xm,Ym)
    done=1
  }
 }
z
}
outcome()

I now need to do the same thing, 250 times. I've changed the code to this:
plotoutcome<-function()
{
  done=0
  while(done==0){
    Xm2<-runif(250,-25,25)
    Ym2<-runif(250,-25,25)
    if (Xm2^2+Ym2^2<=25^2){
      z<-c(Xm2,Ym2)
      done=1
    }
  }
  z
}
plotoutcome()

However when I run the second code, I get this error message: In if (Xm2^2 + Ym2^2 <= 25^2) { :
  the condition has length > 1 and only the first element will be used.
Any ideas on how to fix this?

A: The simplest way is to take advantage of outcome:
replicate(250, outcome())

But if a new function is needed, here is a plotoutcome function:
plotoutcome<-function()
{
  total <- 0
  done <- FALSE
  Xtmp <- numeric(250)
  Ytmp <- numeric(250)
  while(!done){
    Xm2 <- runif(1, -25, 25)
    Ym2 <- runif(1, -25, 25)
    i <- Xm2^2 + Ym2^2 <= 25^2
    if(i){
      total <- total + 1
      Xtmp[total] <- Xm2
      Ytmp[total] <- Ym2
    }
    done <- total == 250
  }
  list(X = Xtmp, Y = Ytmp)
}
do.call(cbind, plotoutcome())


text:
Q: Find the index of max value in a 3D array and store as 2D array I have a 3D array of shape 7x10000x10000 . The first dimension of the array is a vector of length 7. I want to create a 2D array, of shape 10000x10000, that has the the index of max element in the vector. I tried doing it using loops but it s very slow because of the size of the array. Is there any better way of doing it , like flatten, find max in each vector and reshape?
    for i in range(0,7):
    for j in range(0,10000):
        for k in range(0,10000):
            vector = myarray[:,j,k]
            m = np.argmax(vector)
            img[j,k] = m


text:
Q: Не работает крос доменный запрос на клиенте Когда я делаю запрос на другой домен , то не проходит запрос. Использую XMLHttpRequest.
Вот такая ошибка вылетает в консоли chrome:

Failed to load https://www.amazon.com/gp/offer-listing/B00XU2I36S: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource. Origin 'http://localhost:17777' is therefore not allowed
  access.


text: Q: Download stopping at 800KB I have a problem with downloading in chrome browser, whenever I try to download anything (jpg mp3 mp4 exe) the download hangs around 800 KB for at least 30 minutes or so and continues to download. so i downloaded free download manager Uget, but same problem in that too. What would be the cause..?


text:
Q: Scanning text file to ArrayList> I am trying to read a text file into an ArrayList<ArrayList<String>>
The File Looks like:
A D E F
B A F
C A B D
D B C
E B C D F
F A B D
G
H A D F

Following is my piece of code:
private static void registerPages() throws IOException {
        Scanner input = new Scanner(new File(webPath));
        //input.useDelimiter(" ");

        ArrayList<ArrayList<String>> arrayList = new ArrayList<>();
        ArrayList<String> row = new ArrayList<>();
        String tempStr;
        String[] tempArr;

        while (input.hasNextLine())
        {
            row.clear();
            tempStr = input.nextLine(); //get row in string
            tempArr = tempStr.split(" "); //split string into strings[]
            Collections.addAll(row, tempArr); //add each strings[] to arrayList
            arrayList.add(row); //add arrayList to arrayList
        }

        System.out.println("arrayList:\n" + arrayList);

    }

The output is:
arrayList:
[[H, A, D, F], [H, A, D, F], [H, A, D, F], [H, A, D, F], [H, A, D, F], [H, A, D, F], [H, A, D, F], [H, A, D, F]]

The wanted output is:
arrayList:
[[A, D, E, F], [B, A, F], [C, A, B, D], [D, B, C], [E, B, C, D, F], [F, A, B, D], [G], [H, A, D, F]]

Just FYI,
this text file is supposed to be a webgraph. First word is a web-page. Next words in the same line are other webpages linking to this web-page (in-links). Eventually, i am supposed to code the 'Page Rank' algorithm.
Thank You in advance.

A: Instead of using row.clear() try instantiate row in each iterations.
row = new ArrayList<>()
Hint:
You are creating row only once. So all item holders in arrayList points to the same memory block. You have to create new instances (Real object in memory) so they can hold different values.

A: public static void main(String[] args) {
    File file = new File("webpath.txt"); // Your text file
    ArrayList<List<String>> arrayList = new ArrayList<>();

    try(Scanner sc = new Scanner(file)) {
        List<String> arrayRow = new ArrayList<>();

        while (sc.hasNextLine()) {
            String line = sc.nextLine(); // Retrieve 1 line from the text file
            String[] data = line.split(" "); // Splitting the characters and storing them
            arrayRow = Arrays.asList(data); // Converting array to List
            arrayList.add(arrayRow); // Adding row of characters to the final arraylist
        }
    }
    catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    // Looping through the result arraylist
    for (List<String> array : arrayList) {
        for(String item : array) {
            System.out.print(item + " ");
        }
        System.out.println();
    }
}

A: Problem is that you are reusing and adding to arrayList same instance of list representing row (so it prints N times current/last state). You should create new list for each row and then add it to your main list.
So simply move ArrayList<String> row = new ArrayList<>(); inside your loop and.

A: You add the same row many times in the arrayList. Every time you modify the same row and finally you have only the last row inserted many time. You have to create new row every time: put line
ArrayList row = new ArrayList<>();
in place of
row.clear();

A: public static void main(String[] args) throws IOException {
    registerPages(new FileReader("test.txt"));
}

private static void registerPages(Reader reader) throws IOException {
    Scanner input = new Scanner(reader);
    List<List<String>> arrayList = new ArrayList<>();

    while (input.hasNextLine()) {
        List<String> row = new ArrayList<>();
        Collections.addAll(row, input.nextLine().split(" "));
        arrayList.add(row);
    }

    System.out.println("arrayList:\n" + arrayList);
}

Outputs:
arrayList:
[[A, D, E, F], [B, A, F], [C, A, B, D], [D, B, C], [E, B, C, D, F], [F, A, B, D], [G], [H, A, D, F]]

The problem with your code was that you were constantly operating on the same row instance. The main arrayList instance had the same instance of a List in it multiple times, and you were constantly re-adding the same instance, clearing and setting new data for it every time. That's why you are seeing the same result on all entries for arrayList - it basically contains the same list multiple times. This is because the list is a mutable object - It's state can be modified and by passing it to another data structure does not prevent it from reflecting the changes made to it in the other data structure. By passing an object (e.g. to another method) does not mean you are copying its contents, you are sharing that object with the other method. Both are seeing the same object - and changes to the shared object are visible to both.


text:
Q: Use of enough, example from Murphy grammar course What is the correct sentence:
I know English enough to read a newspaper   OR
I know enough English to read a newspaper.

A: Either could be correct, depending on what you want to emphasize.

*

*I know English enough to read a newspaper.

You are sufficiently familiar with the words, verb conjugations, and grammar & syntactic rules of English.
This could also be expressed as

*

*I know English well enough to read a newspaper.

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

*

*I know enough English  to read a newspaper.

You have learned (perhaps by rote) a large number of set phrases and patterns, and are good at guessing from context the ones you don't know.

A: Well, what you should have done is check the frequencies of the core/critical expressions utilized at Google Books (not vanilla/normal Google):
"know English well enough to"
About 6,480 results
"know English enough to"
About 1,170 results
This clearly shows that a majority supports the version with "well" (and that might be recommended in some books, and justifiably so). However, the other version seems to be well tolerated and used by native speakers.


text:
Q: Selenium Python Edge disable `open office files in browser` setting Python: 3.9.9
Selenium: 4.1.5
Edge: 101.0.1210.39 (X64) driver link
I am trying to automate downloading excel file from a website, but due to Edge's default setting of open office files in browser set to True, on pressing download button with selenium it redirects to Edge file viewer instead of downloading it.
Since I want to automate the process I don't want to manually go to settings and disable it every time.
Any work arounds will be appreciated too...
Thank you!

A: This is what worked for me:
from pathlib import Path
from selenium import webdriver

if Path('..\msedgedriver.exe').exists():
    driver = webdriver.Edge('..\msedgedriver.exe')

    # Settings
    driver.get('edge://settings/downloads')
    toggle = driver.execute_script('''
            return document.querySelector(' input[aria-label="Open Office files in
    the browser"]');
    ''')
    toggle.click()

# continue...

similarly you can change any setting as per required.


text:
Q: Don't I have to call super() in constructor when class extends Sprite in actionscript3? I always don't call super() when I extends Sprite.
But doesn't not calling super() cause any problem?

Till now, I don't have any problem and I have never seen code which call super() in constructor which class extends Sprite.

How about TextField?
I don't have any problem about TextField, too.

How to know whether I should call super() or not?

A: If you don't call super() explicitly, Flash will do it automatically before all other code in your constructor.
If you call super() explicitly, it will be called at the line on which you wrote it.
However, note that you can not set or get any this or super properties or call any methods before the super class is instantiated

A: If flash doesn't detect a call to super() in your child constructor then flash will implicitly call super() before your child's constructor. So:
public class Parent {
    public function Parent() {
        trace("Parent");
    }
}

public class Child extends Parent {
    public function Child() {
        trace("Child");
    }
}

new Child();
// Parent
// Child

So your child constructor essentially looks like this
    public function Child() {
        super(); // <-- Added by flash!
        trace("Child");
    }

So, no, omitting an explicit call to super() will not usually adversely affect your child's class.
So why would you want to explicitly call super()?
The first reason is flash will only ever automatically generate a parameterless call to super, meaning that if your parent classes constructor requires arguments, then you will need to explicitly call it with those arguments. If you omit the super(args...) call in this case, you will get a compiler error.
Second, if even your parent has a parameter-less constructor, you can use super() to control the order that the constructors execute. Flash will always insert the call before the childs constructor. So if you wanted to change that order. Then
public class Child extends Parent {
    public function Child() {
        trace("Child");
        super()
    }
}

would do it in the opposite order. Or you could do:
public class Child extends Parent {
    public function Child() {
        // work before initilizing parent
        super()
        // work after initilizing parent
    }
}

Lastly, there is a very obscure way to not call your parents constructor by saying:
public class Child extends Parent {
    public function Child() {
        if(false) super()
    }
}

Because flash sees there is a call, it doesn't insert one. However because its behind a if (false) it never gets called, so the parent class never gets initialized.

A: You can safetly exclude the call to the base constructor. If you do not call super() in the constructor, the compiler will add a call to the base constructor with no arguments.


text:
Q: Gfortran complex actual to real dummy argument I am trying to use fftpack with gfortran, but I am getting errors that i think relate to that some routines are passed complex arrays when the dummy argument is declared as real.
I read a comment on an intel fortran page that one could disable "check routine interface". Does anyone know if there is a similar option for gfortran?
I would like to not have to edit the fftpack... ( i guess this is because complex in memory is represented by two reals and the array arguments are passed as references but please correct me if I am wrong :) )
[to elaborate and meet the comments...]
So after downloading the dfftpack from netlib and compiling as a standalone file (f77 I pressume) with all subroutines in the same file I get a warning for example in
   SUBROUTINE DFFTF (N,R,WSAVE)
   IMPLICIT DOUBLE PRECISION (A-H,O-Z)
   DIMENSION       R(1)       ,WSAVE(1)
   IF (N .EQ. 1) RETURN
   CALL RFFTF1 (N,R,WSAVE,WSAVE(N+1),WSAVE(2*N+1))
   RETURN
   END

the waring appears when calling CALL RFFTF1 (N,R,WSAVE,WSAVE(N+1),WSAVE(2*N+1)). The beginning of RFFTF1 looks like this...
SUBROUTINE RFFTF1 (N,C,CH,WA,IFAC)
IMPLICIT DOUBLE PRECISION (A-H,O-Z)
DIMENSION       CH(*)      ,C(*)       ,WA(*)      ,IFAC(*)

and the warning from compiling hits the actual argument WSAVE(2*N+1) - to the dummy argument IFAC: (output from code::blocks build log window)
 mingw32-gfortran.exe -Jobj\Debug\  -Wall -g     -c
 C:\... \dfftpack.f -o obj\Debug\dfftpack.o
 C:\... \dfftpack.f:345.40:
 CALL RFFTB1 (N,R,WSAVE,WSAVE(N+1),WSAVE(2*N+1))
                                   1 Warning: Type mismatch in argument
'ifac' at (1); passed REAL(8) to INTEGER(4)

I assume this will cause an incorrect result.. (the passing of a real to integer seems not to convert/round to the nearest integer but to something else. Does anyone know if it should be rounded in the call, like: NINT(WSAVE(2*N+1))?

A: I encountered this problem when I refactored FFTPACK 5.1 from FORTRAN 77 to Fortran 2008. I performed a C-language style cast without copying as follows:
use ISO_C_binding, only: c_f_pointer, c_loc

integer, parameter :: N = 42
complex, target    :: c(N) ! Also works for the allocatable attribute
real, pointer      :: r(:) => null()

! Pass memory address from complex array to real array
call c_f_pointer(c_loc(c), r, shape=[2*size(c)])

call procedure_expecting_real_arg(r, ....)

! Terminate association
nullify( r )


text:
Q: Drag across formula and but reference ONE column I am collecting 25 samples of a certain rock and in that, analyzing data on 8 different elements. I want to drag across a formula that, simply, would be =(C15/C3)
I have these selected rows:

and want to put them here:

But, of course, when I drag it across, it changes the column. Is there a way that I can change the row when I drag across? (both the denominator and the numerator need to change)

A: Use INDEX()
=INDEX($C:$C,COLUMN(A:A) -1 + 15)/INDEX($C:$C,COLUMN(A:A)-1 + 3)

The COLUMN(A:A) -1 is the counter, the part that moves to the next row as it is dragged across.
The 15 and 3 are the starting rows.


text:
Q: Reading a CSV and transposing the contents into an ArrayList I have a CSV file with values I want to load into an arraylist but there's a trick to it. Here are the CSV contents. Consider these values as all strings for simplicity.
 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 0.10
 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.9, 10.10

When I get the arrayList packed I want it to look like this:
 1, 0.1, 1.1
 2, 0.2, 2.2
 3, 0.3, 3.3
 4, 0.4, 4.4
 5, 0.5, 5.5
 6, 0.6, 6.6
 7, 0.7, 7.7
 8, 0.8, 8.8
 9, 0.9, 9.9
 10, 0.10, 10.10

The reason for this is this array list will be loaded into a database, each row is a new row in the database. What this data is is measurements taken over time. For example the first row value 1 is a measurement taken at minute 1, 2 the measurement taken at minute 2, same goes for each row. So each array in the list should be all the values taken at minute 1, the next array/db row is all the measurements taken at minute 2, etc.
Currently I'm just loading it into an arrayList line by line but I don't want to put it into the database that way. Here's my current code;
 int count = 0;
 String file = "C:\\Temp\\loadtest.csv";
 List<String[]> content = new ArrayList<>();
 try (BufferedReader br = new BufferedReader(new FileReader(file))) {
     String line = "";
     while (((line = br.readLine()) != null) && (count <17)) {
          content.add(line.split(";"));
     }
     count++;
  } catch (FileNotFoundException e) {
        //Some error logging
  }

I can't seem to figure out how to handle this so any Java code examples are welcome.

A: List<List<String>> arrays = Files.lines(Paths.get(path)).map(s -> Arrays.asList(s.split(","))).collect(Collectors.toList());

List<List<String>> collect = IntStream.range(0, arrays.get(0).size()).boxed()
        .map(i -> IntStream.range(0, arrays.size()).boxed()
            .map(j -> arrays.get(j).get(i)).collect(Collectors.toList()))
        .collect(Collectors.toList());

First read it as List of List - using split for it.
After that you can transpose it for example like in next line.

A: So, assuming "1, 0.1, 1.1" would be the first desired string in the array list, this is the code:
public void handleCSV() {
    Path path = Paths.get("C:\\Temp\\", "loadtest.csv");

    Charset charset = Charset.forName("ISO-8859-1"); // <- the actual
                                                        // charset of you
                                                        // csv

    List<String> finalLine = new ArrayList<>();

    try {
        List<String> lines = Files.readAllLines(path, charset);

        boolean isFirstLine = true;
        int index = 0;
        for (String line : lines) {
            String[] lineContent = line.split(",");
            for (String column : lineContent) {
                if (isFirstLine) {
                    finalLine.add(column);
                } else {
                    String myEntry = finalLine.get(index);
                    myEntry.concat("," + column);
                    finalLine.set(index, myEntry);
                }
                index++; // adding an index for each element in the row
            }
            index = 0;
            isFirstLine = false;
        }
    } catch (IOException e) {
        System.out.println(e);
    }
}

This code should produce the results you want if every line has the same number of entries

A: After you have loaded the content of the file into your arrayList you can do something similar to matrix transposing to swap rows and columns. Assuming you want the result to be in a list with string arrays again, and also assuming that your rows have always the same length:
public static void main(String[] args) {
   List<String[]> content = new ArrayList<>();
   content.add(new String[]{"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"});
   content.add(new String[]{"0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "0.10"});
   content.add(new String[]{"1.1", "2.2", "3.3", "4.4", "5.5", "6.6", "7.7", "8.8", "9.9", "10.10"});
   transpose(content).stream().forEach(row ->{System.out.println(Arrays.toString(row));});
}
public static List<String[]> transpose(List<String[]> list){
    String[][] temp = new String[list.get(0).length][list.size()];
    for (int i = 0; i < list.size(); i++)
        for (int j = 0; j < list.get(0).length; j++)
            temp[j][i] = list.get(i)[j];
    return Arrays.stream(temp).collect(Collectors.toList());
}

A:  def transposeArrayList(ArrayList<String> targetArray) {

     List resultArray = new ArrayList<>()
     for(int i=0; i<targetArray.size(); i++) {   // this is up to the number of arrays in the list
         // iterate over all the arrays
         for(j=0; j<targetArray.get(i).size(); j++) {
             // if we are ele 0 then we need to create an array list
             if (i == 0) {
                 resultArray.add(new ArrayList())
                 System.out.println("dest = " + resultArray)
                 System.out.println("i is " + i + ", j is " + j)
             }
             ArrayList arrToAddTo = resultArray.get(j)
             ArrayList arrToAddFrom = targetArray.get(i)
             Object objToAdd = arrToAddFrom.get(j)
             arrToAddTo.add(objToAdd)
         }
     }
     System.out.println("original = " + targetArray)
     System.out.println("dest = " + resultArray)
     return resultArray
 }


text:
Q: How to use a picker to get some value after a selection is made? I have a picker that that reads in from a list of tuples and have a couple questions on how to make it work. What I want to do is that the picker displays some strings and when the user makes a selection a value corresponding to the string is saved into a variable. Then I want to use this variable in a function to calculate something a print the calculation to the user. I currently have:
@State private var rating: Int = 0

func scale(rating: Float, someValue1: Float, someValue2: Float) -> Float{
    return (rating + someValue1 * 2.5 + someValue2 * 1.5) / 10
}

var arrayOfTuples: [(score: String, value: Int)] = [
        (score: "A+", value: 60),
        (score: "A", value: 55),
        (score: "A-", value: 50),
        (score: "B+", value: 45),
        (score: "B", value: 40),
        (score: "B-", value: 35),
        (score: "C+", value: 30),
        (score: "C", value: 25),
        (score: "C-", value: 20),
        (score: "D+", value: 15),
        (score: "D", value: 10),
        (score: "D-", value: 5),
        (score: "F", value: 0)
    ]

Picker(selection: $rating, label: Text("Choose")) {
                        ForEach(0 ..< arrayOfTuples.count) {
                            Text(self.arrayOfTuples[$0].score)
                        }
                    }

This code only is displaying the score part of the arrayOfTuples (A+, A, A-, etc.) which is what I want but when the user selects something from the picker I don't think it's saving the value of the corresponding score into the variable "rating". I then want to use rating to calculate the function when a button is pressed:
Button(action: {
            print(self.scale(rating: Float(self.rating), someValue1: Float(self.someValue1) ?? 0, someValue2: Float(self.someValue2)))
        }) {
            Text("Calculate")
        }

Also, all of this is done inside the ContentView struct created when an app is created in Xcode so I don't know if I am declaring and defining the functions where they're supposed to be so if there is a better way please let me know.
Additionally, the picker is the default picker. I would prefer to use the wheel picker however when I use it it shows it in the main screen where I would prefer it comes up as a pop-up only when the user presses the selection button.
Finally, as you can see in the button the action is printing the value. However, I don't want to print the value rather display it to the user through a popup box or somewhere else that the user can see.
Any ideas how to do this? Thank you so much in advance.

A: There's quite a bit you need to do to accomplish everything you're asking, but let's start with the picker view basics.  You need to conform to the Picker View Data Source and Delegate protocols, then implement the required methods the picker view expects.  Here's an example:
class PickerViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate {

//...rating and tuple variables

overide func viewDidLoad() {
   let pickerView = UIPickerView()
   pickerView.dataSource = self
   pickerView.delegate = self
   self.view.addSubview(pickerView)
}

func numberOfComponents(in pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return arrayOfTuples.count
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
    return arrayOfTuples[row].score
}

func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
    rating = arrayOfTuples[row].value
}

}

They key to storing the picker's value in the rating variable is the didSelectRow method.  The code example I wrote just takes a plain picker view and adds it onto the view controller's view, without thought to placement or constraints or anything, so it's not going to be pretty, but it illustrates how to use a picker view for selecting data.  If you want to have the picker view pop-up and hide, there's several ways to do it, including adding the subview over the top of other views, and the removing it from its super view, or presenting a new view controller.  How familiar are you with doing that in Swift?


text:
Q: Doctrine ODM saving big number This might be a stupid question, but I'm struggling to save a big number in mongoDB document.
Basically, I want to save a number that can be bigger than the max int value. Thus, I declared my document field as a @Field(type="float").
Now the problem is that saving the number result in an error. I also tried simply using @Integer but the number was reduced to 2147483647 (which is the max int value for 32 bits system).
So I tried a last solution, saving my number in a string. This works fine (at least it appears to be correct in the database), but returning the document and doing a echo $number gives me back 2147483647.
Anybody has a fix to this ? What am I doing wrong ?

A: Last things first: The value is being displayed as the max-int value because PHP is seeing it as numeric. You can see more about this process here.
The mongodb extension itself does support 64-bit integers on 32-bit systems using MongoInt64, but the Doctrine ODM doesn't handle 32- or 64-bit integers differently when hydrating back from MongoDB, so you'll never see that 64-bit value come back as a MongoInt64 class, even if PHP could support it -- which it can't :)
SO, I'd say your options are either force the value to a string (echo (String) $number;), or try and troubleshoot why you are getting an error attempting to save the value as a float. There are precision issues with floats in php that may make it untenable to store the number that way regardless.
Hope this helps!


text:
Q: How to place the subject line under the greeting line in t-letter module in ConTeXt? I'm writing a letter using the t-letter module available with ConTeXt.  I want the subject line to be underneath the greeting line, but I can't work out how to do it.
I think it is something like:
\setupletterstyle[subject][after=opening]

The relevant documentation is, I think, at page 55 here, but I still can't work it out: http://dl.contextgarden.net/modules/t-letter/doc/context/third/letter/correspondence.pdf

A: This is an ugly workaround to swap the opening and subject:
\setupletterstyle [opening]
    [
        before={\blank[-4*line, force]},
         after={\blank[4*line]},
    ]

\setupletterstyle [subject]
    [
        before={\blank[2*line, force]},
    ]


text:
Q: How to add multiple languages on Samsung Store? I have an app published on the Samsung Store with the language default as English. But I want to add multiple languages (like Portuguese/Korean...) in the store, how I do it?
PS: My app already has the multiple strings.xml in the project.

A: I find the answer on the FAQ, to add a new language I needed to go in App Informations, set the mode to Advanced and then click on add button.


text:
Q: PHP - In which cases can an email not be accepted for delivery? With the following statement we will get a boolean whether the mail we try to send gets accepted for delivery or not:
if(mail($to $subject $message $headers))

Since I always get true even if I am not connected to the internet, I assume that this response has nothing to do with the fact if it gets sent for real or not. So in which cases can I get false? And where does this 'getting accepted for delivery' happens (on my computer, on the server, in the aether...)?

A: The mail() function uses the system mailer - which can be sendmail, or a mail transfer agent directly. The return value only indicates that the message was delivered successfully to whatever intermediary your system is configured with (usually sendmail on linux systems).
If you need actual data on deliverability, you could use a third party mail service such as SendGrid or MailGun, etc, which use APIs to send and also can report back delivery status, and other data.

A: As explained in the php.net documentation,

mail() Returns TRUE if the mail was successfully accepted for
  delivery, FALSE otherwise. It is important to note that just because
  the mail was accepted for delivery, it does NOT mean the mail will
  actually reach the intended destination.

In other words, the mail() function returns true if he gets all the values he needs to send the mail. But cannot know if the mail was received or not because PHP is not the one sending the mail. The mail server (most likely exim) is.
There's a nice PHP library that can help you validate if an email is valid/exists and belongs to a user. It's called kickbox
So before using the mail() function, you could run the email in kickbox and in combination with the returned true of mail() you can assume the mail was sent out as long as exim does his job.
You can also use an API like MailJet to send out your email in your name instead of using the servers mail server and receive a status report directly from the API to know if the mail server was successful or not in sending the mail.

A: As most of the replies here already answered your question, may I suggest an alternative which is PHPMailer (https://github.com/PHPMailer/PHPMailer)?
It's a library for sending emails in PHP and you can define the SMTP, account info and even attach files when sending out emails. It even allows for SMTP debugging of sorts as well using "$mail->SMTPDebug = SMTP::DEBUG_SERVER;" for example.
Quite easy to use too. You can refer to the official tutorial here: https://github.com/PHPMailer/PHPMailer/wiki/Tutorial


text:
Q: How to replace column names in data set using a csv lookup file I am using RStudio and I have the following R codes running (which retrieves Stock prices):
if (!require(BatchGetSymbols)) install.packages('BatchGetSymbols')

library(BatchGetSymbols)

# set dates
first.date <- Sys.Date() - 60
last.date <- Sys.Date()
freq.data <- 'daily'
# set tickers
tickers <- c('AAPL','BIDU')

l.out <- BatchGetSymbols(tickers = tickers,
                         first.date = first.date,
                         last.date = last.date,
                         freq.data = freq.data,
                         cache.folder = file.path(tempdir(),
                                                  'BGS_Cache') ) # cache in tempdir()
library(ggplot2)

p <- ggplot(l.out$df.tickers, aes(x = ref.date, y = price.close))
p <- p + geom_line()
p <- p + facet_wrap(~ticker, scales = 'free_y')
print(p)

Output of p is shown below:

I would like the ggplot2 graph to display the company name instead of the ticker symbol. (That is, APPLE instead of "AAPL", BAIDU instead of "BIDU").
I have a csv file which contains the list of code names (tickers) and their relevant company names. How can I replace the tickers with the Company Names so that they are displayed in my ggplot2 graph?
I have tried the following (still giving the same graph as before):
if (!require(BatchGetSymbols)) install.packages('BatchGetSymbols')

library(BatchGetSymbols)

# set dates
first.date <- Sys.Date() - 60
last.date <- Sys.Date()
freq.data <- 'daily'
# set tickers
tickers <- c('AAPL','BIDU')

l.out <- BatchGetSymbols(tickers = tickers,
                         first.date = first.date,
                         last.date = last.date,
                         freq.data = freq.data,
                         cache.folder = file.path(tempdir(),
                                                  'BGS_Cache') ) # cache in tempdir()

codes_list <- read.csv("codes_list.csv", stringsAsFactors=FALSE)

codes_list$code <- as.character(codes_list$code)
codes_list$desc <- as.character(codes_list$desc)
rownames(codes_list) <- codes_list$code
replaced <- names(l.out$df.tickers) %in% codes_list$code
names(l.out$df.tickers)[replaced] <- codes_list[names(l.out$df.tickers)[replaced], "desc"]

library(ggplot2)

p <- ggplot(l.out$df.tickers, aes(x = ref.date, y = price.close))
p <- p + geom_line()
p <- p + facet_wrap(~ticker, scales = 'free_y')
print(p)

An extract of the "codes_list.csv" file is shown below:
code       desc
AAPL       APPLE
BIDU       BAIDU

I tried the above based on the solution provided here: Replace column name by referring to a table file in R

A: I would do a join on the two datasets to get the corresponding desc.
require(dplyr)
require(ggplot2)

codes_list <- read.csv("codes_list.csv", stringsAsFactors=FALSE)

inner_join(l.out$df.tickers, codes_list, by = c('ticker' = 'code')) %>%
  ggplot(aes(x = ref.date, y = price.close)) +
  geom_line() +
  facet_wrap(~desc, scales = 'free_y')

Let me know if this helps!
EDIT: l.out is a list and the relevant object is l.out$df.tickers


text:
Q: Hibernate-spatial jpa with myql and Spring boot 1.5.7 not working I want to use hibernate spatial with mysql and spring boot. I tried but failing.
application.properties file given below
spring.datasource.url=jdbc:mysql://localhost:3306/tour_management
spring.datasource.username=root
spring.datasource.password=admin
endpoints.actuator.enabled=true
endpoints.info.enabled=true

spring.jpa.properties.hibernate.dialect =
org.hibernate.spatial.dialect.mysql.MySQLSpatial5InnoDBDialect
spring.jpa.database-platform =
org.hibernate.spatial.dialect.mysql.MySQLSpatial5InnoDBDialect

@Data
@Entity(name = "Place")
public class PlaceEntity extends BaseEntity {
@Id
@GeneratedValue
@Column(name = "ID")
private long id;
@Column(name = "NAME")
private String name;
@Column(name = "CODE")
private String code;
@Column(name = "LONGITUDE")
private Double longitude;
@Column(name = "LATITUDE")
private Double latitude;

@Column(name = "LOCATION",columnDefinition = "geometry(Point,4326)")
private Point location;
}

But I am getting Exception when deploy
buildscript {
ext {
    springBootVersion = '1.5.7.RELEASE'
}
repositories {
    mavenCentral()
    maven {
        url "http://www.hibernatespatial.org/repository"
    }
}
dependencies {
    classpath("org.springframework.boot:spring-boot-gradle-
plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.fm'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
maven {
    url "http://www.hibernatespatial.org/repository"
}
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-actuator')
compile('org.springframework.boot:spring-boot-starter-data-jpa')
compile('mysql:mysql-connector-java')
compile('org.projectlombok:lombok:1.14.8')
compile('org.springframework.boot:spring-boot-starter-web')
compile('com.vividsolutions:jts:1.13')
testCompile('org.springframework.boot:spring-boot-starter-test')
}

Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.spatial.dialect.mysql.MySQLSpatial5InnoDBDialect] as strategy [org.hibernate.dialect.Dialect]
        at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:113) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
Is there any version related problem????

A: If we match your exception at runtime :

Caused by:
  org.hibernate.boot.registry.selector.spi.StrategySelectionException:
  Unable to resolve name
  [org.hibernate.spatial.dialect.mysql.MySQLSpatial5InnoDBDialect] as
  strategy [org.hibernate.dialect.Dialect] at
  org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:113)
  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]

with the source code of StrategySelectorImpl :
@Override
    @SuppressWarnings("unchecked")
    public <T> Class<? extends T> selectStrategyImplementor(Class<T> strategy, String name) {
        final Map<String,Class> namedStrategyImplementorMap = namedStrategyImplementorByStrategyMap.get( strategy );
        if ( namedStrategyImplementorMap != null ) {
            final Class registered = namedStrategyImplementorMap.get( name );
            if ( registered != null ) {
                return (Class<T>) registered;
            }
        }

        try {
            return classLoaderService.classForName( name );
        }
        catch (ClassLoadingException e) {
            throw new StrategySelectionException(
                    "Unable to resolve name [" + name + "] as strategy [" + strategy.getName() + "]"
            );
        }
    }

We understand that org.hibernate.spatial.dialect.mysql.MySQLSpatial5InnoDBDialect class is not loadable by the classloader. It is probably not in the classpath.
I suppose you should add the hibernate spatial dependency that matches with your Hibernate version.


text:
Q: Replacing one string with another for a set of text files using python file.readlines() and .replace() not saving replacement I have tried to iterate line by line through the text file to find the sections I'm looking to replace and update them with the desired values. The problem I have is that I seem to be updating the value but the value is not written in to the the string. I have printed the output from the file as an explanation of sorts.
for files in glob.iglob(directory+'*'+suffix, recursive=True):
    if "-pst" not in files and "Static" not in files:
        print(files)
        file1 = open(files,"r")
        data=file1.readlines()
        for line in data:
            if "6168" in line:
                print(line)
                line=line.replace("6168", GuideNodes[0])
                print(line)
            line=line.replace("6158", GuideNodes[1])

        for line in data:
            if "6168" in line:
                print(line+"$")

The output for this code is:
 6168, 1

 6170, 1

 6168, 4

 6170, 4

 6168, 2

 6170, 2

 6168, 3

 6170, 3

 6168, 5

 6170, 5

 6168, 6

 6170, 6

 6168, 1
$
 6168, 4
$
 6168, 2
$
 6168, 3
$
 6168, 5
$
 6168, 6
$

So you can see that the code initially updates the line but this is not carried over into "data".
I'm working line by line as I also need to move some lines in the code as the text file is a script for another application otherwise I would just edit the text as one long string using file.read().
I'd greatly appreciate if anyone can explain why this is not working as I'd expect!

A: Strings in Python are immutable, so when you write line=line.replace("6168", GuideNodes[0]), you create a new string and assign it to line, but it does not change the original value on your data list.
To update the contents of the list, you should change your inner loop to:
for idx, line in enumerate(data):
    if "6168" in line:
        print(line)
        line=line.replace("6168", GuideNodes[0])
        print(line)
    line=line.replace("6158", GuideNodes[1])
    data[idx] = line   # Replaces the original line in data


text:
Q: How to correctly add bootstrap to Angular app I created angular app and install bootstrap using "npm install bootsrap" and add the path to angular.json file. but when i create a button and add bootstrap classes the output doesn't show applying bootstrap classes.

Can someone help me to solve this...
thanks

A: First things first you want to add bootstrap latest (5) as an npm package like so:
npm install bootstrap@next

In your angular.json add bootstrap stylesheet and javascript:
"styles": [
  "src/scss/styles.scss",
  "./node_modules/bootstrap/dist/css/bootstrap.min.css",
],

"scripts": [
  "./node_modules/bootstrap/dist/js/bootstrap.min.js"
]

Now add popperjs and add it to your scripts:
npm install @popperjs/core
"scripts": [
  "./node_modules/@popperjs/core/dist/umd/popper.min.js",
  "./node_modules/bootstrap/dist/js/bootstrap.min.js"
]

Now lets test and see if everything works accordingly
Add a dropdown component to your app.component.html

  <button
    class="btn btn-secondary dropdown-toggle"
    type="button"
    id="dropdownMenuButton1"
    data-bs-toggle="dropdown"
    aria-expanded="false"
  >
    Dropdown button
  </button>

Action

Another action

Something else here

You should be able to click and view the dropdown menu items

A: You can do this
npm i bootstrap --save

and add the bootstrap in angular.json
 "styles": [
       "node_modules/bootstrap/dist/css/bootstrap.css",
       "src/styles.scss"
 ],
 "scripts": [
      "node_modules/bootstrap/dist/js/bootstrap.js"
 ]

A: If you have angular version above 9+ you can use this
ng add @ng-bootstrap/ng-bootstrap

To get an idea you can refer this document:
https://www.npmjs.com/package/@ng-bootstrap/ng-bootstrap

A: If you are using Sass, you need to do the following two steps:

*

*Install bootstrap using npm i bootstrap

*In angular.json file, add the following line to the styles array before any other entry: "./node_modules/bootstrap/scss/bootstrap.scss"
Your styles array should look like this ("build" -> "options" -> "styles"):
"styles": [
    "./node_modules/bootstrap/scss/bootstrap.scss",
    "src/styles.scss"
],


text:
Q: How can I find and print all of the numbers between two numbers in PHP? Right now I'm asking the user for two numbers. I'm trying to print the numbers in between $one and $two assuming $one is smaller than $two.

A: <?php
foreach (range($one, $two) as $number) {
    echo $number." \n";
}
?>

range($one, $two) makes an array of numbers from $one to $two.
<?php
$numbers = range($one, $two);
foreach ($numbers as $number) {
    echo $number." \n";
}
?>

In this example, the array of numbers are first stored in $numbers before they are printed.
If $one is 5 and $two is 10 these examples will output:
5
6
7
8
9
10

A: Just a simple for loop should do the trick:
for($i=$a; $i<=$b; $i++) {
  echo $i;
}

A: range gives an array containing all the numbers.
You can iterate over that:
foreach (range($one, $two) as $number)
    echo "$number
\n";

Or simply use a loop:
for ($number = $one; $number <= $two; $number++)
    echo "$number
\n";

A: This sounds like homework...
for ($i=$one+1; $i<$two; $i++)
{
  echo $i . "\n";
}

This really gets you only the numbers between, not the endpoints.

A: for($i=$one + 1; $i<$two; $i++) {
    echo $i;
}


text:
Q: difference between aggregate ($match) and find, in MongoDB? What is the difference between the $match operator used inside the aggregate function and the regular find in Mongodb?
Why doesn't the find function allow renaming the field names like the aggregate function?
e.g. In aggregate we can pass the following string:
{ "$project" : { "OrderNumber" : "$PurchaseOrder.OrderNumber" , "ShipDate" : "$PurchaseOrder.ShipDate"}}

Whereas, find does not allow this.
Why does not the aggregate output return as a DBCursor or a List? and also why can't we get a count of the documents that are returned?
Thank you.

A:
Why does not the aggregate output return as a DBCursor or a List?

The aggregation framework was created to solve easy problems that otherwise would require map-reduce.
This framework is commonly used to compute data that requires the full db as input and few document as output.

What is the difference between the $match operator used inside the aggregate function and the regular find in Mongodb?

One of differences, like you stated, is the return type. Find operations output return as a DBCursor.
Other differences:

*

*Aggregation result must be under 16MB. If you are using shards, the full data must be collected in a single point after the first $group or $sort.

*$match only purpose is to improve aggregation's power, but it has some other uses, like improve the aggregation performance.

and also why can't we get a count of the documents that are returned?

You can. Just count the number of elements in the resulting array or add the following command to the end of the pipe:
{$group: {_id: null, count: {$sum: 1}}}

Why doesn't the find function allow renaming the field names like the aggregate function?

MongoDB is young and features are still coming. Maybe in a future version we'll be able to do that. Renaming fields is more critical in aggregation than in find.
EDIT (2014/02/26):
MongoDB 2.6 aggregation operations will return a cursor.
EDIT (2014/04/09):
MongoDB 2.6 was released with the predicted aggregation changes.

A: I investigated a few things about the aggregation and find call:
I did this with a descending sort in a table of 160k documents and limited my output to a few documents.

*

*The Aggregation command is slower than the find command.

*If you access to the data like ToList() the aggregation command is faster than the find.

*if you watch at the total times (point 1 + 2) the commands seem to be equal

Maybe the aggregation automatically calls the ToList() and does not have to call it again. If you dont call ToList() afterwards the find() call will be much faster.
7 [ms] vs 50 [ms] (5 documents)


text:
Q: ¿Por qué tengo este error en la lectura de una QSqlQuery? En mi programa de Qt tengo un Stringpara insertar ciertos datos en una base de datos SQLite. La parte de código donde se ejecuta defino mi QStringy se ejecuta la QSqlquery es la siguiente:
    qDebug()<<"Mi id del clone"<<myClonedSetupID;
    qDebug()<<"Mi id del original"<<cloneFromId;
    QString queryStr;
    QSqlQuery query;
    queryStr=QString("INSERT INTO SetupEvaluationMagnitudes (Setup_ID, AssessmentGroup, Assessment, AssessmentQuantity, Selection) "
                     "SELECT '%1',AssessmentGroup,Assessment,AssessmentQuantity, Selection "
                     "FROM SetupEvaluationMagnitudes WHERE Setup_ID = '%2' ").arg(myClonedSetupID,cloneFromId);
    qDebug()<<queryStr;
    if(!query.exec(queryStr)){
        qDebug()<<"Error clonning"<<query.lastError();
    }

Pues bien, lo que ocurre al ejecutarlo, que lo veo gracias a los qDebug(), es lo siguiente:
Mi id del clone 19
Mi id del original 11
"INSERT INTO SetupEvaluationMagnitudes (Setup_ID, AssessmentGroup, Assessment, AssessmentQuantity, Selection)
SELECT '         19',AssessmentGroup,Assessment,AssessmentQuantity, Selection
FROM SetupEvaluationMagnitudes
WHERE Setup_ID = '%2' "

Como se puede ver el error es que el myClonedSetupIDsi que lo coge bien y pone el id del clone que corresponde (poniendo 19 en el lugar del %1), pero en el cloneFromIdno me coge el id original (11 en este caso) y sigue poniendo %2.
Nota: tanto myClonedSetupIDcomo cloneFromIdson tipo int.
¿Alguna idea de porque puede ser? ¿  Por qué me coge uno bien y otro no?

A: No es posible hacer lo que pretendes. QString.arg( ) tiene muchas sobrecargas ... pero ninguna reemplaza a la vez 2 int.
Lo mas simple, creo que es llamar a arg( ) 2 veces:
queryStr = QString("INSERT INTO SetupEvaluationMagnitudes (Setup_ID, AssessmentGroup, Assessment, AssessmentQuantity, Selection) "
                     "SELECT '%1',AssessmentGroup,Assessment,AssessmentQuantity, Selection "
                     "FROM SetupEvaluationMagnitudes WHERE Setup_ID = '%2' ").arg( myClonedSetupID ).arg( cloneFromId );


text:
Q: attach image while sending emails I have this application where it looks for any jpg images on folder and if any jpeg found it sends an email to the client i can  send the data from the jpeg but how to attach image to the mail.
I tried this but received this error  system.io.__error.winioerror(int32 errorcode string maybefullpath).
Dim DirSearch As IO.FileInfo() = FileDirInfo.GetFiles("*.jpg")
            Dim FileInfo As IO.FileInfo

            Dim FileDir, FileName As String
            FileDir = FileDirInfo.ToString

 For Each FileInfo In DirSearch
            'for any files found, Split the filename into strings
            FileName = FileInfo.ToString

            Dim attachment As System.Net.Mail.Attachment
            attachment = New System.Net.Mail.Attachment(FileName)

                Dim attachment As System.Net.Mail.Attachment
                attachment = New System.Net.Mail.Attachment(FileName)

                Dim SmtpServer As New SmtpClient
                Dim mail As New MailMessage
                SmtpServer.Credentials = New Net.NetworkCredential("pramm", "roar")(//fake)
                'SmtpServer1.EnableSsl = True
                SmtpServer.Port = 587
                SmtpServer.Host = "email.loror.ac.uk"
                mail = New MailMessage
                mail.From = New MailAddress("alerts@loro.ac.uk")
                mail.To.Add("alerts@loro.ac.uk")
                mail.Subject = "Alert"
                mail.Body = "Vehicle " & VRM & " captured on " & Camera & " at " & TimeStr & " on the date " & DateStr
         attachment = New System.Net.Mail.Attachment(FileName)
            'mail.Attachments.Add(attachment)
                SmtpServer.Send(mail)

A: This is the code I use for HTML-type emails and file attachments.
You can also put the HTML code to include the attachment as an  in the HTML code of your email.
''' <summary>
''' Sends the HTML-type email and possible attached files to the given email addresses.
''' </summary>
Public Sub SendEmail(ByVal fromAddress As String, _
             ByVal fromName As String, _
             ByVal toAddresses As String(), _
             ByVal subject As String, _
             ByVal body As String, _
             Optional ByVal attachedFilePaths As List(Of String) = Nothing)

    Dim oMsg As System.Net.Mail.MailMessage = New System.Net.Mail.MailMessage()

    Dim addrFrom As New System.Net.Mail.MailAddress(fromAddress, fromName)
    oMsg.From = addrFrom

    For i As Integer = 0 To toAddresses.Length - 1
        Dim address As New System.Net.Mail.MailAddress(toAddresses(i))
        oMsg.To.Add(address)
    Next

    oMsg.Subject = subject

    oMsg.Body = body

    oMsg.IsBodyHtml = True

    If attachedFilePaths IsNot Nothing Then
        For Each path As String In attachedFilePaths
            Dim oAttch As System.Net.Mail.Attachment = New System.Net.Mail.Attachment(path)
            oMsg.Attachments.Add(oAttch)
        Next
    End If

    '---
    'GENERIC:
    Dim client As New System.Net.Mail.SmtpClient(emailSenderHost, emailSenderPort)
    Dim myLogin As New Net.NetworkCredential(emailSenderUsername, emailSenderPassword)
    client.EnableSsl = False

    client.EnableSsl = False
    client.UseDefaultCredentials = True
    client.Credentials = myLogin
    client.EnableSsl = emailSenderEnableSsl
    client.Send(oMsg)

End Sub

A: Please check if the below helps.

*

*If the images are created by some process, then make sure the process disposes them properly. Or try by manually placing an image.

*Ensure that the application pool has permissions to the folder.

As a basic test you can create a sample directory under the root of your application, place a jpg manually. And then run the application, after making necessary changes to use this directory.


text:
Q: Liquibase maven - SQL Server out put to console during execution My maven project uses liquibase plugin to generate a text file with all DDLs and DMLs. It is executing these database queries and scripts against SQL Server.
mvn run is showing only liquibase output(shown below) on the console but not the output of SQL statements. I'm able to capture output of the SQL statements in a log file using sqlcmd -e command in maven goals. How can I get the same output on my console during maven execution?
INFO  3:50 PM: liquibase: Successfully acquired change log lock
DEBUG  3:50 PM: LiquibaseSchemaResolver: Found namespace details class liquibase.parser.core.xml.StandardNamespaceDetails for http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd
DEBUG  3:50 PM: LiquibaseSchemaResolver: Local path for http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd is liquibase/parser/core/xml/dbchangelog-3.5.xsd
DEBUG 3:50 PM: LiquibaseSchemaResolver: Successfully loaded XSD from liquibase/parser/core/xml/dbchangelog-3.5.xsd
INFO 3:50 PM: liquibase: Reading from [dbo].[DATABASECHANGELOG]
INFO  3:50 PM: liquibase: Successfully released change log lock
INFO  3:50 PM: liquibase: Successfully acquired change log lock
DEBUG 3:50 PM: LiquibaseSchemaResolver: Found namespace details class liquibase.parser.core.xml.StandardNamespaceDetails for http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd
DEBUG  3:50 PM: LiquibaseSchemaResolver: Local path for http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-3.5.xsd is liquibase/parser/core/xml/dbchangelog-3.5.xsd
DEBUG  3:50 PM: LiquibaseSchemaResolver: Successfully loaded XSD from liquibase/parser/core/xml/dbchangelog-3.5.xsd
INFO  3:50 PM: liquibase: Reading from [dbo].[DATABASECHANGELOG]
INFO  3:50 PM: liquibase: Successfully released change log lock

A: Specify configuration file in MVN like so (note the "configuration" section):
  <project>
    <build>
      <plugins>
        <plugin>
          <groupId>org.liquibase</groupId>
          <artifactId>liquibase-maven-plugin</artifactId>
          <version>x.x.x.x</version>
          <configuration>
            <propertyFileWillOverride>true</propertyFileWillOverride>
            <propertyFile>target/classes/liquibase.properties</propertyFile>
          </configuration>
        </plugin>
      </plugins>
    </build>
  </project>

In configuration file specify
verbose: true

Source: http://www.liquibase.org/documentation/maven/

A: My bad. I was executing it in quite mode. Running the same without -q produced full output. Thanks


text:
Q: Should I use extra arraylist for efficient data operations while using Sqlite db with recyclerviews? I hope straightforward questions.
1) I managed to get the data from Sqlite db and showing them on recyclerview. The question is for example when i click on the recyclerview items and do some operations (for example copying the content or updating) is it better to use an arraylist and get the data first when application loads then do the operations on this arraylist elements (then notifying db eventually)?
2) If there is no need for extra arraylist on onContextItemSelected() operations while clicking recyclerview item again, i ve some trouble in choosing the element and its values.
public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.idshare :
            //implicit intent
            shareImplicitIntent();
            return true;

......
for the  shareImplicitIntent() method
private void shareImplicitIntent() {
    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    Cursor cursor=WordListOpenHelper.mReadableDB.rawQuery("SELECT * FROM
    diary", null);
    cursor.moveToPosition(XYZ);
    Entry_Model entry_model= new Entry_Model();
    entry_model.setmEntry(cursor.getString(cursor.getColumnIndex(WordListOpenHelper.KEY_ENTRY)));
    String title = entry_model.getmEntry(); ......

basically using cursor and getting the title of the cursor at XYZ position.
But how can I choose that XYZ position ?
Working hours on it but couldnt find a clue. Please help me.Thanks a lot

A: To answer my question myself, shortly no,  for example for getting input from the user and putting them in the arraylist then doing the database operations on the arraylist  not very useful nor necessary. (Yet if your database is planned to hold only small amount of entries though you can use arraylist/linkedlists for fast CRUD manipulations on the recyclerview adapter).
For the second part of the question it s easy to copy the content of the  clicked recyclerview element by creating setonclicklistener  in the viewholder constructor of the viewholder innerclass, for example;
(note unlike in the example you dont have to use contentresolver if you dont plan to share the datas in the database with other applications)
itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                int pos =getAdapterPosition();
                String entry = "";
                String[] mProjection =
                        { Contract.WordList.KEY_ENTRY,    // Contract class constant for the _ID column name  };

                Cursor cursor = mContext.getContentResolver().query(Uri.parse(
                        queryUri), mProjection, null, null, sortOrder);

                if (cursor != null) {
                    if (cursor.moveToPosition(pos)) {
                        int indexEntry = cursor.getColumnIndex(Contract.WordList.KEY_ENTRY);
                        entry = cursor.getString(indexEntry);

                    }
                }

                Toast.makeText(v.getContext(), "copied entry is " + entry, Toast.LENGTH_LONG).show();

                return false;
            }
        });


text:
Q: Count node depth in neo4j I have this query in Neo4j:
MATCH (sentence:Sentence)-[r*]->(n:Word )
WITH n, COUNT(r) AS c
RETURN n, c

My graph is a linguistic database containing words and dependency relations between them.
This query should return depth of nodes, however the COUNT(r) always returns 1.
When I ommit the COUNT function and write just
WITH n, r AS c

instead (trying in web browser neo4j interface), neo4j returns multiple relations for each word node "n" as expected.
Can you please help me what am I doing wrong, how to count the length of path between sentence node and word node? thanks.

A: I think it query return n and c and there are multiple record of n so count(r) return 1.
Try this -
MATCH (sentence:Sentence)-[r*]->(n:Word )
WITH n, LENGTH(r) AS depth
RETURN n, depth

You will get depth like this.
Or Try this
   MATCH p= (sentence:Sentence)-->(n:Word)
   RETURN n, length(p) as depth

http://docs.neo4j.org/chunked/stable/query-functions-scalar.html#functions-length

A: In version 4.x, U should use SIZE function
MATCH (sentence:Sentence)-[r*]->(n:Word )
WITH n, SIZE(r) AS depth
RETURN n, depth

https://neo4j.com/docs/cypher-manual/current/functions/scalar/#functions-size

A: Finally found the solution myself - it is cypher's LENGTH function:
MATCH (sentence:Sentence)-[r*]->(n:Word )
WITH n, LENGTH(r) AS c
RETURN n, c

found in this useful cheat sheet: http://assets.neo4j.org/download/Neo4j_CheatSheet_v3.pdf


text:
Q: Automatically adding/expanding new row in MS Access forms I am trying to build an invoice form in which the user has to select an item and when ever the item is selected from the combo box, a new blank row should be added at bottom as shown in the screen shot below.

I have seen that the Northwind sales database has done same thing but I don't know how to implement it.
        As per my search, they have build form (below screen shot) and put it in Order Detail (Subform),
but what is the logic behind automatically adding of new row at last?

A: http://www.accessforums.net/forms/automatically-adding-expanding-new-row-ms-access-50531.html
above link give you complete solution


text:
Q: Set-SFTPFile upload full directory I need to upload full directory (with recourcive folders) to the server by sftp
#SSH
$secpasswd = ConvertTo-SecureString $Password -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential($User, $secpasswd)

$sftpSession = New-SFTPSession -ComputerName $HostIP -Credential $Credentials

#Folders Paths
$FilePath = Get-ChildItem -Path uploading-folder | Select-Object -ExpandProperty FullName
$SftpPath = "/home/new-folder"

# Upload the file to the SFTP path
Set-SFTPFile -SessionId ($sftpSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath -Overwrite

#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }

But i cant upload folders inside folders (and filse in them). How can I upload full folder with files and folders inside it?

A: Posh does not seem to support recursive operations. You have to code it on your own.
Quoting Reddit post SFTP - How to upload an entire folder/directory instead of one file at a time?:
# Get a recursive list of files in the target folder ($path).
# Change the include to your needs,
# and remove the -Force if you don't want hidden files included
$path = "./Recursion test/"
$uploadFiles = Get-ChildItem $path -Recurse -Include "*" -Force

$session = New-SFTPSession (your args here)
$remoteFolder = Get-SFTPCurrentDirectory $sessoin.Index

Set-SFTPDirectoryPath $session.Index -Path $destinationPath
foreach ($item in $uploadFiles) {
    if ($item.GetType -eq [System.IO.DirectoryInfo]) {
        New-SFTPDirectory $sessionIndex $item
    }
    else {
        $localFolder = $item.PSPath | Split-Path | Split-Path -Leaf
        if ($localFolder -ne $remoteFolder) {
            Set-SFTPCurrentDirectory $session.Index $localFolder
            $remoteFolder = $localFolder
        }
        Set-SFTPFile $session.Index $item.Name
    }
}

Or use another SFTP library that supports recursive operations.

A: Code :
$folders =  @('D:\Shares\folderone\*.pdf','D:\Shares\foldertwo\*.pdf')
foreach ($folder in $folders) {
    $files = Get-ChildItem $folder
    foreach ($file in $files) {
        Set-SFTPItem -SessionId $SFTPSession.SessionId -Path $file -Destination /upload -Verbose
        }
    }


text:
Q: How to write a simple Axis client (service generated from netbeans) This is really basic, but here goes:
I have created a simple "hello world" client using net beans, and I can successfully "test" it by right-clicking and saying "test in browser".
However, the tutorial doesn't go any further - specifically, it doesn't give the actual client code for invoking the service.
Can anyone point out to some example code for this?
Thanks,
Jack

A: Here it is - on the netbeans ide: new file, web services, web service client


text:
Q: How can I get my code to wait for me to scan my second RFID? Is there a way for me to pause my code in the middle of the two if statements so I can scan the second RFID so the code can continue on to the second if statement with the information from the second RFID?
void loop()
{
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {

    return;
  }
  //Show UID on serial monitor

  Serial.print("UID tag :");
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++) {

     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));

  }
  Serial.println();
  //Serial.print("Message : ");
  content.toUpperCase();
  int count = 0;

  if (content.substring(1) == "89 E7 75 47")
  {
    Serial.println("Authorized access");
    Serial.println();
    digitalWrite(yellowLED, HIGH);
    delay(1000);
    digitalWrite(yellowLED, LOW);

  count = count + 1;
  }
 else   {
    Serial.println(" Access denied");
    Serial.println();
    digitalWrite(redLED, HIGH);
    delay(2000);
    digitalWrite(redLED, LOW);

if (content.substring(2) == "F9 9A 76 47")
  {
    Serial.println("Authorized access");
    Serial.println();
    digitalWrite(yellowLED, HIGH);
    delay(1000);
    digitalWrite(yellowLED, LOW);
    count = count + 1;
  }
 else   {
    Serial.println(" Access denied");
    Serial.println();
    digitalWrite(redLED, HIGH);
    delay(1000);
    digitalWrite(redLED, LOW);
  }

if (count == 2 ) {
    digitalWrite(greenLED, HIGH);
    delay(3000);
    digitalWrite(greenLED, LOW);

}

}
}

I want to scan two RFIDs within the duration of the code but the whole code runs through after I've scanned one.

A: If you want to wait until data is available, you can use Serial.available(). It is a handy function that returns a bool:
if ( ! mfrc522.PICC_IsNewCardPresent())
{
  return;
}

while(! Serial.available()){}

// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {

  return;
}

Keep in mind that the serial buffer should be either read completely before the next loop, or Serial.flush() should be called.


text:
Q: Why do I need to add curly braces to the action creator? Action creators:
export const addTodoCustom = function (text) {
    return {
        type: "ADD_TODO",
        id: nextTodoId++,
        text
    };
};

Right statement:
import * as actions from "../actions"
import AddTodo from "../components/AddTodo";
import {bindActionCreators} from "redux";
import {addTodoCustom} from "../actions";

export default connect(mapStateToProps, {addTodoCustom})(AddTodo);

Wrong statement:
export default connect(mapStateToProps, addTodoCustom)(AddTodo);

Why do I need to add curly braces to the action creator in React with Redux? What is the syntax of Javascript?
Update:
Sample Project:
https://github.com/gongzelong0718/redux-quickstart-tutorial/tree/question
Note: please check out the branch question

Update 2
Here is what I thought:
I check the JavaScript ES6 syntax: Enhanced Object Literal Value Shorthand
The right statement is equals to:
export default connect(mapStateToProps, {a: addTodoCustom})(AddTodo);

So why do I need to use {a: addTodoCustom} instead of addTodoCustom?

A: First, you need to import your connect function before you can use it like so:
import { connect } from 'react-redux';
With the connect helper you can pass up to two arguments to it, the first one being either null or mapStateToProps, but you have to create that function first. Its purpose is to take your global state object (application state), the thing that sits inside your Redux store and map it or take some properties off the state object and provide them as props to your component of AddTodo.
I think you are also missing your payload property, so instead you want your action creator to look like so:
export const addTodoCustom = text => {
   return {
     type: "ADD_TODO",
     id: nextTodoId++,
     payload: text
   };
};

It would have been helpful I think for you to also post your reducer, since this is all part of the Redux system.
Now back to your connect() function, the second argument would be the action creator that you want to bind to that component which would be addTodoCustom. Please ensure that your relative path to it in your import statement is correct.
Once having done all the above then this export default connect(mapStateToProps, {addTodoCustom})(AddTodo); should work as long as you have your mapStateToProps function. If not then you need to write it like this: export default connect(null, {addTodoCustom})(AddTodo);
You never showed the contents of your AddTodo component, and one can only assume by the use of mapStateToProps that it is a class-based component, it would be helpful if you shared that code as well.

A: Checking the source code of (bindActionCreators)[https://github.com/reduxjs/redux/blob/9d3273846aa8906d38890c410b62fb09a4992018/src/bindActionCreators.ts]. We know
export default function bindActionCreators(
  actionCreators: ActionCreator<any> | ActionCreatorsMapObject,
  dispatch: Dispatch
) {
  if (typeof actionCreators === 'function') {
    return bindActionCreator(actionCreators, dispatch)
  }

  if (typeof actionCreators !== 'object' || actionCreators === null) {
    throw new Error(
      `bindActionCreators expected an object or a function, instead received ${
        actionCreators === null ? 'null' : typeof actionCreators
      }. ` +
        `Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`
    )
  }

  const boundActionCreators: ActionCreatorsMapObject = {}
  for (const key in actionCreators) {
    const actionCreator = actionCreators[key]
    if (typeof actionCreator === 'function') {
      boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
    }
  }
  return boundActionCreators
}

So the final reason is that we need to pass a map as the 1st parameter of bindActionCreators. So we need to pass a object with key and value. {a: addTodoCustom}, ActionCreatorsMapObject like what is defined in source code, not a addTodoCustom which is a object and also a function
But there is another question:
Why does it execute the following codes when I pass addTodoCustom
export default function bindActionCreators(
  actionCreators: ActionCreator<any> | ActionCreatorsMapObject,
  dispatch: Dispatch
) {
  if (**typeof actionCreators === 'function'**) {
    return bindActionCreator(actionCreators, dispatch)
  }

and then call bindActionCreator(actionCreators, dispatch)
function bindActionCreator<A extends AnyAction = AnyAction>(
  actionCreator: ActionCreator<A>,
  dispatch: Dispatch
) {
  return function(this: any, ...args: any[]) {
    return dispatch(actionCreator.apply(this, args))
  }
}

I read the doc https://react-redux.js.org/using-react-redux/connect-mapdispatch#defining-the-mapdispatchtoprops-function-with-bindactioncreators

bindActionCreators accepts two parameters:
A function (an action creator) or an object (each field an action
  creator)

It says I can pass a function.
IMHO, addTodoCustom is a funtion
{a, addTodoCustom} is an Object.
Correct me if I am wrong.


text:
Q: Logging of inno setup without command-line log I have to log the different steps of the installation of an inno setup (in \verysilent mode). But I don't want to log the command line because it contains some critical information (like password).
How can I easily keep the logging without the command-line log ?


text:
Q: How to have these 2 matrices side by side In fact I want to have these two matrices side by side, here is the code:
\immediate\write18{makeindex \jobname.nlo -s nomencl.ist -o \jobname.nls}
\documentclass[10pt]{elsarticle}
\DeclareGraphicsExtensions{.pdf,.gif,.jpg}

\usepackage{lineno}
\modulolinenumbers[5]
\usepackage{graphicx}
\usepackage{amssymb,amsmath,nccmath}
\usepackage{cclicenses}
\usepackage{makecell}
\usepackage{lscape,array}
\newcolumntype{C}[1]{>{\centering\arraybackslash}p{#1}}
\usepackage[thin, , thinc]{esdiff}
\usepackage{subcaption}
\usepackage{caption}
\usepackage{framed}
\usepackage{nomencl}
\usepackage[hmargin=2.6 cm,vmargin=3.25cm]{geometry}
\usepackage{setspace}\doublespacing
\usepackage[font=small,skip=0pt]{caption}
\makenomenclature
\setlength{\nomitemsep}{-\parskip}\usepackage{booktabs,multirow}
\renewcommand{\cellset}{\renewcommand{\arraystretch}{0.5}}

\journal{Journal of \LaTeX\ Templates}

\bibliographystyle{elsarticle-num}
\begin{document}
\begin{align*}
\begin{bmatrix}
1
\end{bmatrix}
=
\begin{bmatrix}
\mfrac{A}{B} &  E & \mfrac{C}{D} & 0 \\
-K &  \mfrac{-Z}{Y} & T & \mfrac{W}{V} \\
\mfrac{XY}{MOP}& -\mfrac{US}{TV} & \mfrac{1}{B}(\mfrac{MN}{AB}-\mfrac{LA}
{BC}) & RR \\
\mfrac{A}{B} & \mfrac{C}{D} & -E & \mfrac{1}{C}(\mfrac{DE}{GH}-\mfrac{IJ}
{KL})  \\
\end{bmatrix}
\end{align*}

\begin{align*}
\begin{bmatrix}
 2
\end{bmatrix}
 =
\begin{bmatrix}
A & 0 & 0 & 0\\
0 & A & 0 & 0\\
\mfrac{AA}{BB} & 0 & \mfrac{1}{CCr} & 0 \\
0 & \mfrac{-DE}{BCD} & 0 & \mfrac{1}{FG}
\end{bmatrix}
\end{align*}\par
\end{document}

A: very similar to what suggested marmotin his comments above:
\documentclass[10pt]{elsarticle}
\usepackage[hmargin=2.6 cm,
            vmargin=3.25cm]{geometry}
\usepackage{amssymb, nccmath}

\begin{document}
\[\renewcommand\arraystretch{2}
[1] = \begin{bmatrix}
        \mfrac{A}{B}    &  E                & \mfrac{C}{D}  & 0 \\
                -K      &  \mfrac{-Z}{Y}    & T             & \mfrac{W}{V} \\
        \mfrac{XY}{MOP} & -\mfrac{US}{TV}   & \mfrac{1}{B}\left(\mfrac{MN}{AB}-\mfrac{LA}{BC}\right)
                                                            & RR \\
        \mfrac{A}{B}    & \mfrac{C}{D}      & -E            & \mfrac{1}{C}\left(\mfrac{DE}{GH}-\mfrac{IJ}{KL}\right)  \\
\end{bmatrix},
    \qquad
[2] = \begin{bmatrix}
        A               & 0                 & 0                 & 0 \\
        0               & A                 & 0                 & 0 \\
        \mfrac{AA}{BB}  & 0                 & \mfrac{1}{CCr}    & 0 \\
        0               & \mfrac{-DE}{BCD}  & 0                 & \mfrac{1}{FG}
\end{bmatrix}
\]


text:
Q: where login users are stored in mysql? Where can the "login users" created be found in MySQL?  In SQL Server it is found under Security-->Logins.
I am creating new user as:
create user 'customer' @'localhost' identified by 'hassaan09';
grant all privileges on customer.* to 'customer' @'localhost' identified by 'hassaan09';

using MySQL Workbench 5.6

A: As documented under The MySQL Access Privilege System:

Internally, the server stores privilege information in the grant tables of the mysql database (that is, in the database named mysql). The MySQL server reads the contents of these tables into memory when it starts and bases access-control decisions on the in-memory copies of the grant tables.

As documented under Privilege System Grant Tables:

These mysql database tables contain grant information (emphasis added):

*

*user: Contains user accounts, global privileges, and other non-privilege columns.

Therefore, they are stored in the mysql.user table:
SELECT * FROM mysql.user