text:
Q: Passing Data from XWalkView to Native Android I have a question which may be simple for you guys.
I'm running a WebApp using Crosswalk(XWalkView), everything looks smooth. I found out how to launch a native function from inside the website into my Android App.
public class WebAppInterface {
    @org.xwalk.core.JavascriptInterface
    public void callFunction() {
        onBuyGasButtonClicked(getCurrentFocus());

    }

I need to know how to pass data along with it. I'm using in-app-billing. I got their code samples and I think everything is going fine, but I need to update my PHP MySQL server with the amount purchased.
How can I pass the variable to my Android App? (egs. email)

A: Let's assuming passing a string from JavaScript to native code. Firstly, create a JavaScript interface as you did:
public class WebAppInterface {
    @org.xwalk.core.JavascriptInterface
    public void callFunction(String text) {
    }
}

Then, add the interface to your XWalkView object:
mXWalkView.addJavascriptInterface(new WebAppInterface(), "testObject");

In your JavaScript:
function test(text) { testObject.callFunction(text); }


text:
Q: multiprocessing > Manager() > RLock Error: I've got a collection of multiprocessing.Process objects in a list, and they all use the same instance of what I will call a "process safe queue" to communicate in a process-safe (thread-safe but with processes) way to the parent process whose responsibility it is to manage the threads.
When the child process goes to put something into the queue, it calls the ProcessSafeQueue().enqueue() which first acquires a multiprocessing.Manager > RLock, then writes to the queue, and finally releases the lock.
In this case it was the pid of the child process.  Here's a traceback of the error.
Traceback (most recent call last):
File /usr/lib/python2.5/site-packages/my_project/some_module.py, line 87, in send_data
    q.enqueue(os.getpid())
File /usr/lib/python2.5/site-packages/my_project/some_module.py, line 33, in enqueue
    self.lock.acquire()
File /usr/lib/python2.5/site-packages/processing/managers.py, line 979, in acquire
    return self._callMethod(\'acquire\', (blocking,))
File /usr/lib/python2.5/site-packages/processing/managers.py, line 740, in _callMethod
    self._connect()
File /usr/lib/python2.5/site-packages/processing/managers.py, line 727, in _connect
    connection = Client(self._token.address, authkey=self._authkey)
File /usr/lib/python2.5/site-packages/processing/connection.py, line 187, in Client
    answerChallenge(c, authkey)
File /usr/lib/python2.5/site-packages/processing/connection.py, line 425, in answerChallenge
    message = connection.recvBytes()

And here's the actual error:
IOError: [Errno 11] Resource temporarily unavailable
I'm wondering if someone could help me understand why I might get this error after the application had been running successfully for ~7 hours or so.

A: I had a similar issue and I resolved it by removing socket.setdefaulttimeout.

A: The answer here is that the error is totally misleading.  Resource temporarily unavailable really means that some error occurred while reading the socket.  This could be an auth error, or that there was simply no data available to read (though I'm not sure why that would generate an error... it does, in practice).  The solution here is to suppress the error and retry.

[Update after a few years of further experience with concurrency in Python]
I found that designing my concurrency model to reduce/remove-altogether the need for synchronization mechanisms (locks, queues, or semaphores) both simplified my design and made it work with less fragility and without the error I described above.

redpajama_set_name: RedPajamaStackExchange


text:
Q: $\left( \sum_{i=1}^N a_i^2\right)^{1/2} \leq \left(\mathbb{E} \left| \sum_{i=1}^N a_iX_i\right|^p \right)^{1/p}$ for all $p \geq2$? Let  $X_1,X_2, \dots, X_N $ be i.i.d sub-guaussian random variable ,with $E[X_i] = 0$ and $\operatorname{Var}[X_i] =1$  $a_1,a_2,\dots ,a_N \in R$
$$\left(\sum_{i=1}^N a_i^2\right)^{1/2} \leq \left( E \left| \sum_{i=1}^N a_iX_i\right|^p\right)^{1/p}$$
for all  $p \geq2$ ?
is that possible to do that?

A: Yes, it is possible. Actually, an upper bound holds as well -- namely, this is the Khintchine inequality for subgaussian random variables. See e.g. these lecture notes.
The lower bound you seek is the simple part, and id actually a simple consequence of Jensen's inequality:
$$\begin{align*}
\mathbb{E}\left[\left\lvert\sum_i a_i X_i\right\rvert^p\right]^{1/p}
&= \mathbb{E}\left[\left(\left|\sum_i a_i X_i\right|^2\right)^{p/2}\right]^{1/p}
\geq \left(\mathbb{E}\left[\left(\sum_i a_i X_i\right)^2\right]\right)^{1/2}
= \left(\operatorname{Var}\left[\sum_i a_i X_i\right]\right)^{1/2}\\
&= \left(\sum_i a_i^2 \operatorname{Var}\left[X_i\right]\right)^{1/2}
= \left(\sum_i a_i^2 \right)^{1/2}
\end{align*}$$
using the fact that $p\geq 2$ (i.e., $p/2\geq 1$) for Jensen's inequality, then the fact that $\mathbb{E}\sum_i a_i X_i = 0$ to rewrite the expectation of the square as the variance, and finally independence of the $X_i$'s.

A: Consider a Random Variable $$Z=\sum_{i=1}^{N} a_iX_i$$
Then $Z$ is Gaussian with  mean $E[Z]=0$ and variance $Var[Z] = \sigma^2=\sum_{i=1}^{N} a_i^2 $
$E[|Z|^p] = \sigma^p[(p-1)!!]\sqrt{\dfrac{2}{\pi}}$ if p is odd, and
$E[|Z|^p] = \sigma^p[(p-1)!!]$ if n is even. https://en.wikipedia.org/wiki/Normal_distribution#Moments
$\implies E[|Z|^p] = \sigma^p k$, let $k$ be a constant depending on whether n is even or odd. But note that $|k|\geq1$ for $p \geq 2$.
$\therefore$ $(E[|Z|^p])^{1/p} = (\sigma^p k)^{1/p} \geq \sigma$. But $\sigma = (\sum_{i=1}^{N}a_i^2)^{1/2}$
$\implies$ $(\sum_{i=1}^{N}a_i^2)^{1/2} \leq (E[|Z|^p])^{1/p}$
$$(\sum_{i=1}^{N}a_i^2)^{1/2} \leq (E[|\sum_{i=1}^{N} a_iX_i|^p])^{1/p} $$


text:
Q: How to extract the value id from the json (Grail) json
categories": [
    {
        "id" : "A", "name" : "bed_room","description" : "Bedroom"........

controller
     def categories = Catalogue.categories
[categories: categories]

Gsp
<g:each in="${categories}" var="category">

                ${category.value.id}

            </g:each>

on html page
It prints: [A, B, C, D...]
The external json file resides inside directory and the categories are obtained into array. I am trying to display the elements in html
Like this:

A

B

But it currently prints one array of all items: [A, B, C, D...] which is not correct.
How do I display these elements in html?
Help appreciated.


text:
Q: Disable https when Nginx reverse proxy to IP address I configured Nginx as a reverse proxy on my server for a site, say example.com
I want the client to access my site using an IP address, something like http://192.0.2.67
The problem is that there is a redirection on the example.com site setting HTTP to redirect to HTTPS. (This example.com using Cloudflare)
When the client accesses my site from http://192.0.2.67 they are redirected to https://example.com
How do I disable HTTP redirect to HTTPS on my Nginx reverse proxy?
My code is like below :
server {
   listen 80;

   location / {
       proxy_pass http://example.com;
   }
}

A: I don't see the redirection in the code you have post in the question. It mean that the redirection is done on side example.com.
Depends how is the redirection done. In case the redirection is done simply "http TCP/80 => https TCP/433" and no following checks you can try to proxy directly to https:
server {
   listen 80;

   location / {
       proxy_pass https://example.com;
   }
}

In case this will not help I am afraid you have not much chances to success as you are not the node realizing the force for https redirect.
In case there is HTTP Strict Transport Security (HSTS) header in the page the redirection is done on browser level and there you have also minimal chances to skip ip (in theory you can try to filter out this header).

A: It seems to me that the page is making a redirect, not the webserver. Through PHP, that can be achieved with something like this:
<?php header('Location: http://google.com') ?>

In that case, it's hard to prohibit that kind of behavior through the webserver itself.

A: Nginx doesn't redirect here. It's the origin server that is sending this HTTP redirect. With Nginx you can replace sent redirects with your own redirect target:
server {
    listen 80;

    location / {
        proxy_pass http://example.com;
        # replace redirects
        proxy_redirect http://example.com http://192.0.2.67;
    }
}

For more details see documentation of ngx_http_proxy_module


text:
Q: How to combine two list of object in one list with Rxjs I have 2 differents list of objects and i want to combine them together for exemple:
listObj1 = [{name:'bob 1'}, {name:'bob 2'}]
listObj2 = [{pseudo:'Bob Razowski'}, {pseudo:'sponge bob'}]

result = [
   {name:'bob 1', pseudo:'Bob Razowski}
   {name:'bob 2', pseudo:'sponge bob'}
]

Can i do that with rxjs and how or if you have a better solution let me know
const characters = [];
const name$ = Observable.from(this.nameList)
                    .map(item => {
                        return {'name': item};
                    })

const pseudo$ = Observable.from(this.pseudoList)
                    .map(item => {
                        return {'pseudo': item};
                    })
Observable.zip(name$, pseudo$).subscribe(result => {
                        let char= {};
                        if(result.length > 1) {
                            char['name'] = result[0];
                            char['pseudo'] = result[1];
                            characters.push(char)
                        }
                    });

I started something like that but when i see the result, i can do it without rxjs. My question is more if it exists an other operator to do that.
thank

A: Well, you can do it with RxJS, but there is no obvious reason to do so, looking at your code snippet. One reason to do it reactively would be that you had really long lists and wanted to let the combination happen on (hypothetical) multiple threads. But in JavaScript that's not really practical, so for...of or Array.map are the right choices for this kind of task.
Anyhow, the RxJS solution would look like this:
zip(
    from(listOb1),
    from(listObj2)
).pipe(
    map(([one, two]) => Object.assign({}, one, two)),
    toArray()
)

Convert both lists into Observable streams with from, then zip them together and map each pair onto a new object using Object.assign. Collect the objects with toArray and done.


text:
Q: Saving Workbook Referencing Several Cell Values I have been struggling with this for the past several hours.
I am wanting to save a Workbook by referencing 4 different cell values. The following is the code that is not working.
Sub SU_CreateSaveWorkbook_Macro() 'Save to folder and ask which folder
Application.DisplayAlerts = False
Dim filename1 As String
Dim filename2 As String
Dim filename3 As String
Dim filename4 As String

filename1 = Sheet15.Range("C12")
filename2 = Sheet15.Range("C6")
filename3 = Sheet15.Range("C7")
filename4 = Sheet15.Range("C8")

Dim SvName As String
SvName = filename1 & "_" & filename2 & "_" & filename3 & filename4 & Format(Now, " mm-dd-yyyy ")

On Error Resume Next
    userResponce = Application.Dialogs(xlDialogSaveAs).Show(SvName)
On Error GoTo 0
If userResponce = False Then
    Exit Sub
Else
Sheet15.Range("K19").Value = "1"
End If
Application.DisplayAlerts = True
End Sub

A: After Format you need to have two parentheses like: Now() to get the date value of today returned and it also needs to include filetype extension .xlsm. (unless you want it saved as a .pdf)
SvName = filename1 & "_" & filename2 & "_" & filename3 & filename4 & Format(Now(), "mm-dd-yyyy")&".xlsm"
' This will save it on Path if filename1 includes the Path (Like C:/Temp)
    Dim wb As Workbook
    Set wb = ActiveWorkbook
    With wb
    .SaveAs FileName:= _
        SvName
    End With


text:
Q: Does Hosted Payment Page accept hosted_login_token? Currently, I want to use Hosted Payment Page of Recurly for charging user. I wanna know if we can let user select their account billing information (credit card) in that page. Does Hosted Payment Page accept hosted_login_token? or is there any way to do that?

A: The hosted pages are really just designed for interactions that require billing information. Since you already have that, you can use the regular Recurly API (subscription create  call) to add a new subscription to their account. Just reference the existing account_code, and Recurly will use that stored billing information.


text:
Q: Pandas conditional formatting on multiple columns with different criteria I would like conditionally format a df with multiple criterias according to its columns, which looks like below:

business_entity
2021-H1
2022-H1
2022-H2
Movement

2
ABC
0
0
100
100

4
DEF
99
99
100
1

8
GHI
97
97
98
1

20
JKl
98
98
98
0

3
MNO
98
97
98
1

23
PQR
0
0
98
98

19
STU
98
97
98
1

22
VWX
96
98
98
0

17
DFD
97
99
98
-1

What I'm trying to do is to format the df with the following criteria:
for columns from 2021-H1 to 2022-H2:
if values >= 89 (green), if values >=79.5 and <89 (orange), and if value <79.5 (red)
for "Movement" column:
if  value >=.05 (green), value >-.05 and <.05 (orange), and value <=-.05 (red)
I've done some research here and come up with the below code:
division_summary_table.style.apply(lambda x: ['background:green'
                                          if (colname=='2021-H1' and value >=89)
                                          else 'background:orange'
                                          if (colname=='2021-H1' and value >=79.5)
                                          else 'background:red'
                                          if (colname=='2021-H1' and value <79.5)
                                          else 'background:green'
                                          if (colname=='2022-H1' and value >=89)
                                          else 'background:orange'
                                          if (colname=='2022-H1' and value >=79.5)
                                          else 'background:red'
                                          if (colname=='2022-H1' and value <79.5)
                                          else 'background:green'
                                          if (colname=='2022-H2' and value >=89)
                                          else 'background:orange'
                                          if (colname=='2022-H2' and value >=79.5)
                                          else 'background:red'
                                          if (colname=='2022-H2' and value <79.5)
                                          else 'background:green'
                                          if (colname=='Movement' and value >=.5)
                                          else 'background:orange'
                                          if (colname=='Movement' and value >=0)
                                          else 'background:red'
                                          if (colname=='Movement' and value <-.5)
                                          else ' '
                                          for colname, value in x.items()],axis=1).format(precision=0)

It works fine for now but really "verbose". Since I need to produce multiple table like this and to apply the same formatting, I tried to to write a simple function then reuse it later:
def styler(df):
    for colname, value in df.items():

        if (colname=='2021-H1' and value >=89):
            return 'background:green'
        elif (colname=='2021-H1' and value >=79.5):
            return 'background:orange'
        elif (colname=='2021-H1' and value <79.5):
            return 'background:red'
        else:
            return ''

division_summary_table.apply(styler)

When I apply it gives me the below error:
"Function <function styler at 0x000002566633C940> resulted in the apply method collapsing to a Series".Usually, this is the result of the function returning a single value, instead of list-like.
I'm a beginner and really have no idea how to fix it. Appreciate your advise on a better way to accomplish what I want to achieve. One more thing I need help is how to save the tables in as png file with the conditional formattings.

A: Let's define functions to colorize subset of columns:
def colorize_year(v):
    return np.select(
        [v >= 89, (v < 89) & (v >= 79.5), v < 79.5],
        ['background: green', 'background: orange', 'background: red']
    )

def colorize_movement(v):
    return np.select(
        [v >= .05, (v < .05) & (v >= -.05), v <= -.05],
        ['background: green', 'background: orange', 'background: red']
    )

(
    df.style
    .apply(colorize_movement, subset=['Movement'])
    .apply(colorize_year, subset=['2021-H1', '2022-H1', '2022-H2'])
)

Result


text:
Q: Dynamically generating form choices from db content Using rest frameworks serializers and renderers, I want to generate an HTML radio button input that takes its choices from a field in the database.
For example, given I have "A", "B", and "C" as the content of an organizations model, I want a from with these three choices as radio buttons. Can you use standard model serializers to do this?

A: To retrieve possible choices for specific request body fields you can use OPTIONS HTTP method request. Please follow https://www.django-rest-framework.org/api-guide/metadata/
. Basically metadata parser reads serializer definition and returns possible field names, their types and allowed choices in a specific (also customizable) format.


text:
Q: Video not playing in ASP.NET Core MVC I created a project with ASP.NET Core 6 MVC web app. In this project, videos are uploaded.
To prevent all users from accessing the videos, a folder named "File" was created outside the
wwwroot  and the videos were uploaded to the File folder.
Videos will not play when referenced from the File folder with the code below. What is the reason for this problem and what should I do to solve it?
<video src="../File/Videos/VideoName.mp4" controls width="640" height="300" loop/>

A: When you want to Serve files outside of web root, You need to configure the Static File Middleware as follows
//.....other middleware...

app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(
           Path.Combine(builder.Environment.ContentRootPath, "File")),
    RequestPath = "/File"
});

//.....other middleware...

Then Use this code to show video:
<video src="@Url.Content("File/video/VideoDemo.mp4")" controls width="640" height="300" loop/>

Demo:

More details you can refer to this Docs


text:
Q: How to compute conditional density function in this particular case?
Suppose we have two random variables $\xi,\eta$, which are defined on the same probability space and $\xi \sim \mathcal{U}[0,1]$. Moreover, $\forall \lambda\in[0,1]:(\eta|\xi=\lambda)\sim \mathcal{Be}(\lambda)$.

I need to find the distribution of $\eta$. In order to do so, I need to calculate $f_{\xi}(\lambda|\eta=t)$, but how does one compute it? In the question conditional probability combining discrete and continous random variables user Wio computes it using  joint probability density, but is it really possible, given that one of the variables is absolutely continuous and the other is discrete?

A: $$\begin{aligned}P(\eta \leq t)&=E[P(\eta\leq t|\xi)]=\\
&=\int_0^1P(\eta\leq t|\xi=y)dy=\\
&=\int_0^1(y \mathbf{1}_{\{0\leq t<1\}}(t)+\mathbf{1}_{\{t\geq 1\}}(t))dy=\\
&=\frac{1}{2}\mathbf{1}_{\{0\leq t<1\}}(t)+\mathbf{1}_{\{t\geq 1\}}(t)\end{aligned}$$
We may conclude $\eta \sim \textrm{Bernoulli}(1/2)$.


text:
Q: jaxb, unmarshal exception Пытаюсь unmarshal ить xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<CreateSmth>
............
</CreateSmth>

в следующий класс
@XmlRootElement(name = "CreateSmth")
public class CreateSmth
    extends BasicRQType
    implements Serializable
{

и получаю ошибку:
javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"CreateSmth"). Expected elements are (none)

at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:740)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:262)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:257)
at com.sun.xml.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:124)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1148)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:573)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:555)
at com.sun.xml.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:168)
at org.apache.xerces.parsers.AbstractSAXParser.startElement(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl.scanStartElement(Unknown Source)
at org.apache.xerces.impl.XMLNSDocumentScannerImpl$NSContentDispatcher.scanRootElementHook(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl$FragmentContentDispatcher.dispatch(Unknown Source)
at org.apache.xerces.impl.XMLDocumentFragmentScannerImpl.scanDocument(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:258)
at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:229)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:214)
at ___.XmlUtils.xml2object(XmlUtils.java:22)
at ___.parseXml(CreateSmth.java:44)
at ___.MyClass.method(MyClass.java:24)
at ?.* Когда запускаем парсинг xml _______.xml(________.feature:6)

в чем может быть проблема? Возможно, в том классе (BasicRQType), от которого наследуется CreateSmth?
(public class BasicRQType implements Serializable без @XmlRootElement)


text:
Q: concatenate hash values when key is same in perl I have a hash
something like :
abc=>1
hello=>32
abc=>4
hello=>23
hello=>12
xyz=>18

how can we concatenate the values, whose keys are same.
So the output will be:
abc=>"1,4"
hello=>"23,12,32"
xyz=>"18".

I tried by sorting the hash by keys then checking for each key, if they are same then concatenate the value, but i am not getting that how to compare two keys in same loop.
Thanks in advance.

A: The exact way this works depends on the real source of your data, but this program shows a way to read the information from the DATA filehandle to build and dump a hash.
The values of the hash are anonymous arrays that contain all the values corresponding to the same key.
use strict;
use warnings;

my %data;

while (<DATA>) {
  my ($k, $v) = /\w+/g;
  push @{ $data{$k} }, $v;
}

for my $k (sort keys %data) {
  printf "%s => %s\n", $k, join ',', @{ $data{$k} };
}

__DATA__
abc=>1
hello=>32
abc=>4
hello=>23
hello=>12
xyz=>18

output
abc => 1,4
hello => 32,23,12
xyz => 18

A: If it's a list with key value pairs you are talking about then you could do something like:
my @kv = (
    abc=>1,
    hello=>32,
    abc=>4,
    hello=>23,
    hello=>12,
    xyz=>18,
);

my %hash;

while(@kv){
    my $k = shift @kv;
    my $v = shift @kv;

    $hash{$k} = defined $hash{$k} ? "$hash{$k},$v" : $v;
}

A: my @pairs = (
    abc=>1,
    hello=>32,
    abc=>4,
    hello=>23,
    hello=>12,
    xyz=>18,
);

my %hash;

# collect
for(my $idx = 0; $idx < scalar @pairs; $idx += 2){
    my $key = $pairs[$idx];
    my $val = $pairs[$idx+1];
    push @{ $hash{$key} }, $val;
}

# print combined
while( my ($key, $val) = each %hash ){
    print "$key = ", join(',', @$val), "\n";
}

A: Since it is unclear what you are really trying to do, I am guessing that you have a file that you need to change. In which case, a one-liner might be in order.
perl -lwne '
    ($k,$v) = split /=>/;
    $data{$k} = join ",", $data{$k} // (), $v }{
    print "$_=>$data{$_}" for keys %data' input.txt > output.txt

Output:
hello=>32,23,12
abc=>1,4
xyz=>18

Note that the keys in the output will not be in the same order as the input. You can sort the keys if you like, but I opted not to.
Explanation:

*

*-l will remove line endings while reading, and put them back while printing

*-n will place a while(<>) loop around the program, reading the file (or STDIN) line by line.

*// is the defined-or operator. It will return the RHS if the LHS is undefined.

*}{ is the eskimo kiss operator which only works with the -n option. What it does is basically the same as an END block, it performs the following code at the end of the input.


text:
Q: How to get write permission on Android 7 SD-card using StorageVolume? Even after getting a permanent permission to write to the external storage I can't get write access to every folder of my sd-card. How to get those? For instance this app can do this, and I guess second permission dialog (under "Write permission on Android 7") is all about that. How to create that? Article Maybe, the solution is bound to the createAccessIntent method of StorageVolume class somehow...
Here is a code I'm currently using to get permanent permission:
RxPermissions.getInstance(getActivity())
                .request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granted -> {
                    if (!granted) return;
                    showAlternativeDirectoryChooser(); // success
                }, throwable -> {
                });

A:
Maybe, the solution is bound to the createAccessIntent method of StorageVolume class somehow

Correct.

Here is a code I'm currently using to get permanent permission:

That has nothing to do with removable storage. That code is for external storage.


text:
Q: c# regular expressions, allow numbers and letters only not working I'm using ASP.NET MVC.
I need a regular expression that allows only numbers and letters, not spaces or ",.;:~^" anything like that.  Plain numbers and letters.
Another thing: 2 characters can't repeat consecutively.
So I can have 123123 but not 1123456.
I got as far as to:
Regex ER1 = new Regex(@"(.)\\1", RegexOptions.None);

Regex ER2 = new Regex(@"[A-Z0-9]", RegexOptions.IgnoreCase);

I could not make it all in one expression and I still have some characters passing through.
Here is my entire code for testing:
class Program
{
    static void Main(string[] args)
    {
        string input = Console.ReadLine();

        Regex ER1 = new Regex(@"(.)\\1", RegexOptions.None);

        Regex ER2 = new Regex(@"[A-Z0-9]", RegexOptions.IgnoreCase);

        if (!ER1.IsMatch(input) && ER2.IsMatch(input))
            Console.WriteLine( "Casou");
        else
            Console.WriteLine( "Não casou");

            Console.ReadLine();
    }
}

I find these expressions quite complex and I'd be really happy to have some help with this.

A: Something like this should work
@"^(?:([A-Z0-9])(?!\1))*$"

A: Let's try this:
@"^(([0-9A-Z])(?!\2))*$"

Explained:
^               start of string
 (              group #1
   ([0-9A-Z])   a digit or a letter (group #2)
   (?!\2)      not followed by what is captured by second group ([0-9A-Z])
 )*             any number of these
$               end of string

The ?! group is called a negative lookahead assertion.

(LastCoder's expression is equivalent)


text:
Q: What default implementation of new/delete from the std-rtl should I use when overriding new/delete in global namespace? I'm using the RTL as a dynamic library. This allows for an overridden new/delete operator in global namespace, because the linker would find my implementation first. I could rely on malloc() and free() to do the allocation stuff, but there are things like 'new_handlers' and 'std::nothrow' objects. Standard library templates require a certain behaviour of the new/delete operators, but the standard library's implementation of new/delete in global namespace is out of scope! Is there an implementation in another namespace from the standard libary that I can use?
I might dynamically determine the address of the standard library's impementation (in the dll) and call it through a pointer, but that's not subject to a beauty reward. Still would this work? (I am using borland C++ builder 2006).
EDIT I want to ask this question:
Does this sample code behave similar to RTL's operator new(size_t)? Or did I missunderstand it?
void *new_replacement(size_t p_size)
{
    void *l_retval = NULL;

    while(l_retval == NULL && p_size != 0)
    {
        l_retval = malloc(p_size);
        if (l_retval == NULL)
        {
            void (*l_handler)() = std::set_new_handler(NULL);

                                 // could not find another way to obtain the current new_handler
            if (l_handler == NULL) throw std::bad_alloc();
            std::set_new_handler(l_handler);
            l_handler();
        }
    }
    return l_retval;
}

A: You've replaced, not overridden the default implementation and you no longer can call it. You will have to reimplement it - for example by using malloc() and taking care of its return value, it's not very hard.


text:
Q: How to keep text inside a div, always in the middle? I'm trying to make text stay in the middle of a resizable DIV.
Here's the example:
CSS
#rightmenu {
  position: absolute;
  z-index: 999999;
  right: 0;
  height: 60%;
  text-align: center;
}

HTML

This text should be center aligned and in the middle of the resizable rightmenu

I've tried to make a Class to contain the text with the "margin-top and margin-bottom" both on auto, but doesn't work.

A: Flexbox has really changed the game with aligning elements in a fluid manner. Define your container element to be display: flex and then to align your inner children you would use justify-content: center; align-items: center;
.container {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    display: flex;
    justify-content: center;
    align-items: center;
}
.parent {
    height: 500px;
    width: 500px;
    position: relative;
}

Hello

World

You'll notice that "Hello" and "World" will both be vertically and horizontally centered within the .container element.

A: If you don't care about IE7 support, you can do it like that:
HTML:

    Content, content, content.

CSS:
#wrap {
    /* Your styling. */
    position: absolute;
    z-index: 999999;
    right: 0;
    height: 60%;
    text-align: center;

    /* Solution part I. */
    display: table;
}

/* Solution part II. */
#inside {
    width: 100%;
    height: 100%;
    display: table-cell;
    vertical-align: middle;
}

The code: http://tinkerbin.com/ETMVplub
If you're OK with JavaScript you can try this jQuery plugin: http://centratissimo.musings.it/ but since it also doesn't seems to support IE7 the CSS solution is probably better.

A: Replace height: 60%; with padding: 30% 0;.

A: If you want the text to be horizontally centered in a div, 'text-align:center;' is your friend. If you want it vertically centered; wrap the content inside an inner div, and then use 'margin: auto' for that inner div. Of course, you'll have to give the inner div a width; otherwise, the horizontal center won't work.
'valign="middle"' also works in tables if tables are an option (otherwise discouraged)

A: Check if this is needed:

centered


text:
Q: Composite literal uses unkeyed fields I am working with new official mongodb driver for golang. I have created one complex query to insert the data into mongo db and then sort it according to an element value. I am using a filter in which I have created the bson type using :-
filter := bson.D{{"autorefid", "100"}}

But It is showing a warning saying:

primitive.E composite literal uses unkeyed fields

The warnings are creating a mess in my code.

A: The warnings can be stopped by setting the check flag to false.
$ go doc cmd/vet

By default all checks are performed. If any flags are explicitly set to true, only those tests are run. Conversely, if any flag is
  explicitly set to false, only those tests are disabled. Thus
  -printf=true runs the printf check, -printf=false runs all checks except the printf check.
Unkeyed composite literals

Flag: -composites

Composite struct literals that do not use the field-keyed syntax.

But the warning is due to not providing the keys name when setting the value in primitive.E struct.
Setting keys for primitive.E struct will remove the warning messages. For example
filter := bson.D{primitive.E{Key: "autorefid", Value: "100"}}

Package primitive contains types similar to Go primitives for BSON
  types can do not have direct Go primitive representations.

type E struct {
    Key   string
    Value interface{}
}

E represents a BSON element for a D. It is usually used inside a D.

For more information have a look at primitive.E

A: Since no one else has pointed this out — the warning is there to safeguard you from changes in the third-party API breaking your code silently.
Ignoring this vet warning has the potential to lead to really nasty and hard to track down runtime bugs, so you'd be better off if you were to always specify the keys of 3rd party structs explicitly.
Such would be the case if the maintainers of the library you are using decided to change the order of elements in their struct for whatever reason. For example, switching Key with Value, in the OP case. Your code would still appear to compile just fine, but what you intended to be the key would now be passed as the value and vice versa, and things would just start breaking in unexpected ways.

A: You can simply change:
filter := bson.D{{"autorefid", "100"}}

to:
filter := bson.D{{Key: "autorefid", Value: "100"}}

//Skip primitive.E as said by Chris W

A: You can change:
filter := bson.D{{"autorefid", "100"}}

to:
filter := bson.D{primitive.E{Key: "autorefid", Value: "100"}}

A: If you are using vscode try disable the following in settings:

A: Actually, if ordered representation of a BSON document doesn't necessary you can change your BSON document to unordered representation by simply change
filter := bson.D{{"autorefid", "100"}}

to
filter := bson.M{"autorefid": "100"}

See this stackoverflow answer for more details about bson.D vs bson.M. The MongoDB server is smart enough to find matching indices regardless of the used order.


text:
Q: How to delete folders that aren't empty? I am using these lines.  Is there any way to shorten it or is this the best?
Objective is to delete the Refresh folder and all of its contents. The script works, but I'd like it to be as minimal as possible.
# Set var $Path to equal Refresh folder
$Path = "C:\data\Refresh"
# Find sub-folders of Refresh
Get-ChildItem -Path $path -Recurse | Remove-Item -Force -Recurse
# Delete Refresh top level folder itself
Remove-Item $Path -Force

A: Since you want to delete the folder and all its content don't bother with Get-ChildItem. Simply call Remove-Item with the path you want to delete.
$Path = 'C:\data\Refresh'
Remove-Item $Path -Recurse -Force

or just
Remove-Item 'C:\data\Refresh' -Recurse -Force


text:
Q: Differences between Oracle Cloud for Industry vs Oracle Public Cloud? What are the major differences between Oracle Cloud for Industry and Oracle Public Cloud? I would like to know in what sense does Oracle mean the cloud is public.

A: Oracle cloud for industry has multiple cloud solutions( with their product bundles) targeted to specific industries like financial services, Consumer goods etc. Their public cloud is just like any other public cloud which means the platform or infrastructure provided by the cloud will run in oracle's data centers and not on say a company's datacenter which would then become private cloud. In case of a public cloud anyone is eligible to buy computing services and use it. You are only ensured logical separation and not physical hardware level separation.

A: OCI predates OPC.
OCI is a SaaS offering from Oracle lines of businesses such as Retail, Health Science, Finance, etc.
OPC on the other hand is general purpose cloud which could be just the VMs (IaaS) or Database/App Server/Fusion Middleware (PaaS) or an ERP product like HCM (SaaS).
OPC is self service - you just sign up for a service and you manage it entirely once you have access.
OCI is managed by Oracle.


text:
Q: Adding Values in Html I am creating an HTML Invoice. The system we use outputs the data to html in HTML. I put the relevant tag (such as {{order_purchasedate}}) and the values are displayed there instead.
I need the invoice to display the total order weight for all items in the order. The weights will be displayed as numbers in a list for example "60 80 120" with just a space separating them.
How can I add the numbers is html and only display the total?
I know I could use Java but I am not familiar with this. If someone could help that would be great.
Ben
*edit I have made an attempt at the code. I am struggling getting the output. I am sure you guys must think me an idiot!
<!DOCTYPE html>

Invoice

A: You can use JavaScript to take your values and calculate total value.
getTotal = function(values){

    var total = values.split(" ").reduce(function(a,b){

        a = parseInt(a)
        b = parseInt(b)

        return a+b

    });

    return total
}

and then just call that function
getTotal(x)

where x is your list
Here is the working example:
http://jsfiddle.net/o89f1mj5/1/

A:

Invoice

    <input id="total" name="total" type="text"></input>
    <input id="totalBtn" type="button" value="Get Total" onClick="getTotal();"></input>

Working JS Fiddle: http://jsfiddle.net/o89f1mj5/9/
In the JSFiddle put "5 15 30" into the text box (without the quote of course) and it will make the paragraph be 50
This is what @mgibala did above using a Textbox and a Button.  His answer should be accepted I am just giving you it in application with a variable input option.


text:
Q: Problem to instal INTL extension on php 7.3 in MAC 10.14 I am configuring local cakephp 3, but I am not able to install ext intl on mac, I have the following error when trying:
1 error generated.
make: *** [php_intl.lo] Error 1
ERROR: `make 'failed

this error occurs when executing the following command:
sudo pecl install intl
Can someone help me with this? thank you!

A: So many time later, i finally fix it:
First make sure you installed Xcode and started it at least once to finish installation and accept license agreement.
Download latest version of autoconf from
http://ftp.gnu.org/gnu/autoconf/autoconf-latest.tar.gz.
Its a prerequisite to build php modules which is not shipped with macOS.
Extract the file and open a terminal in macOS and open the extracted folder using cd command.
Afterwards use commands:
./configure
make
sudo make install (your password is required, make sure you are an admin user in macOS)

Download the version of php you use in xampp from php.net
Extract it and open the extracted folder in a terminal using cd.
Change to subfolder ext/intl.
Run these commands to build the extension:
/Applications/XAMPP/bin/phpize

./configure --enable-intl --with-php-config=/Applications/XAMPP/bin/php-config --with-icu-dir=/Applications/XAMPP/xamppfiles/

make

sudo make install (password required)

Delete all files you downloaded and also the extracted folders.
Add to php.ini file in xampp/etc folder line
extension="intl.so"
Since intl-extension has to be compiled anew each time you installed a new version of xampp I wrote a shell script to do this for me.


text:
Q: how to store s3 credentials in an untracked file using fog I'm trying to get refinerycms to upload files to s3, using the fog gem.
I'd like to pull my S3 credentials from a file that is not in my git repo (e.g. s3.yml)
I found some old references to doing this using the aws-s3 gem, but not fog.
Thanks in advance for any help!

A: I keep my config in a config file rather than a yml file.
In config/s3_config.rb:
ENV['S3_KEY']     = 'MYS3KEY'
ENV['S3_SECRET']  = 'MYSECRETKEY'
ENV['S3_BUCKET']  = 'this-is-my-bucket'

When you run your rails app (this would be in development), the config file is automatically loaded, so those credentials will be referenced to the constants (ENV['S3_KEY']).
This would be different when you deploy your application. For instance Heroku, you would create those config vars.


text:
Q: Three.js OrbitControls seems to break after returning to Chrome tab from another tab I'm not sure if the issue has something to do with how I've set things up in my application, some configuration issue with Chrome, the DOM, OrbitControls or another feature of Three.js.
When I load my application inside a tab in Chrome, everything works perfectly. When I change to another tab in Chrome, or minimize Chrome then return to it (I'm on a Windows machine), OrbitControls behavior changes. Notably, clicking on the left mouse button and moving the mouse around no longer orbits as before, but instead zooms out, up the Y-axis. It also appears like the camera-angle is suddenly a lot wider, and camera rotation center-point changes.
The only apparent fix is to reload the application in the tab, which works, but as I'm getting near alpha release on the product I'm starting to think about how users are not going to tolerate the issue as I have...
Here's what I believe to be my relevant code.
document.addEventListener( "DOMContentLoaded", init );

function init() {

    cameras();
    initRenderer();
    initEventListeners();
    entities();
    // Create the Stereoscopic viewing object (Not applied yet)
    var effect = new THREE.StereoEffect( renderer );

    render();
}

function render() {

    renderer.render(scene, entities.cameras.perspCamera );

    requestAnimationFrame( render );
}

// if the device we're using has 'alpha' attribute, then it's a mixedReality-compatible mobile browser...
function setOrientationControls(e) {
    if (e.alpha) {
        initVRControls ();
    }
    else {
        initbrowserControls ();
        var camera = entities.cameras.perspCamera;
        entities.cameras.init( camera );
    }
}

function initbrowserControls() {

    // Create the Mouse-Based Controls - Hold down left mouse button and move around the window...

    var camera = entities.cameras.perspCamera;

    entities.browserControls = new THREE.OrbitControls ( camera , container );

    entities.browserControls.target.set(
        camera.position.x + 0.15,
        camera.position.y,
        camera.position.z
    );

    entities.browserControls.noPan = true;
    entities.browserControls.noZoom = true;
}

function initEventListeners() {

    // Listen for Device Orientation events.
    window.addEventListener('deviceorientation', setOrientationControls, true);

}

function initRenderer() {

    renderer = new THREE.WebGLRenderer({ alpha: true });
    renderer.setClearColor( 0xffffff, 1 );
    renderer.setSize( window.innerWidth, window.innerHeight );
    renderer.domElement.setAttribute( 'id' , 'renderSpace' );
    renderer.domElement.setAttribute( 'class' , 'threeWebGLRenderer' );

    container.appendChild( renderer.domElement );

};

if the code provided isn't sufficient to answer the question, let me know. I can provide what's needed. Thanks for the help!

UPDATE:
I've edited my code as suggested by @PerrinPrograms in the comments to try to reset the controls when document.visibilityState is reset to "visible".
This seems a workaround... I'd rather get to the source of the problem, but thought following the tracks of it might provide more illumination.
The result is that the behavior is exactly the same, with the added bonus, as noted in the comments, that when I return to the application tab and have a console-break point at setOrientationControls(e) inside of my new if statement, I cannot restart the console action and have to reload the tab.
Here's what I did to my code:
function initEventListeners() {

    // Listen for Device Orientation events.
    window.addEventListener('deviceorientation', setOrientationControls, true);
    document.addEventListener('visibilitychange', onDocumentVisible, true); // ADDED LINE

}

// ADDED FUNCTION
function onDocumentVisible(e){

    if ( document.visibilityState === "visible" ){ // CONSOLE LOCKS UP IF I PLACE BREAK HERE
        setOrientationControls(e);  // HERE TOO
    }
}

The plot thickens... Thanks all for looking into this with me.


text:
Q: dispatchGesture How to add more gesture without cancel gesture before? Path pathpre = new Path();
              pathpre.moveTo(500,500);
              GestureDescription.Builder Builder = new GestureDescription.Builder();
              Builder.addStroke(new GestureDescription.StrokeDescription(pathpre,0,10,true));
              dispatchGesture(Builder.build(),null,null);
              //do something here after that add gesture
              Path path = new Path();
              path.moveTo(600,600);
              Builder = new GestureDescription.Builder();
              Builder.addStroke(new GestureDescription.StrokeDescription(path,0,5000));
              dispatchGesture(Builder.build(),null,null);

When the first gesture is pressing, I want add more gesture without cancel
the first gesture,


text:
Q: Requesting Token from ADFS with AD Group Membership Info I have a rest client application and I want to be able to get an access token from ADFS /token endpoint for that client. The client will be used by existing AD Users, and I want to get the Group Membership of the AD User in the access token.
How can I send my AD User Credentials to ADFS and get the AD Group Membership Info of that AD User in the access token as claims?
I know the solution for the case of "/authorize endpoint and entering the credentials in the login popup". What I am asking is how to do that with a client app where the credentials should be somehow encoded and sent to adfs /token endpoint.

A: You should review https://learn.microsoft.com/en-us/windows-server/identity/ad-fs/overview/ad-fs-openid-connect-oauth-flows-scenarios as that has details of the supported flows and samples for those scenarios.
What you are asking to do is the Resource owner password credential flow and is not recommended. https://learn.microsoft.com/en-us/windows-server/identity/ad-fs/overview/ad-fs-openid-connect-oauth-flows-scenarios#resource-owner-password-credentials-grant-flow-not-recommended


text:
Q: Oracle SQLPlus default configuration file location on GNU/Linux Does Oracle SQLPlus have configuration files for database host, pid, port and if so what are the default locations on a GNU/Linux host? In other words, when you invoke sqlplus from a Linux command line how does it know where to find the database to which to connect?
I have not been having any luck hunting through Oracle's online documentation.

A:
when you invoke sqlplus (from a linux command line) how does it know where to find the database to which to connect?

List of databases accessible to you is stored in TNSNAMES.ORA file. I don't know Linux, but - on MS Windows, it is stored in oracle home directory, \network\admin. I suppose you should be able to locate it.
In there, following the syntax, you create "aliases" to all your databases, by specifying host (or its IP address), port, SID or SERVICE_NAME. For example:
ORA10=
  (DESCRIPTION=
    (ADDRESS=
      (PROTOCOL=TCP)
      (HOST=my_db_server)
      (PORT=1523)
    )
    (CONNECT_DATA=
      (SERVICE_NAME=ORA10)
    )
  )

While connecting to the database, you have to supply the connection string which consists of username, password and the database. For example:
sqlplus scott/tiger@ora10

If there are several Oracle products installed, each of them has its own TNSNAMES.ORA file. In order NOT to maintain all of them (because, you'd want to connect to ORA10 from Forms Builder, SQL*Plus, Apex, ...), you can create TNS_ADMIN environment variable which points to a directory that holds one copy of the TNSNAMES.ORA file - in there, you keep all databases you're connecting to.

A: In Linux/Unix, sqlplus searches for the tnsnames.ora file, looking sequentially in the

*

*if it is defined $TNS_ADMIN

*more often $ORACLE_HOME/network/admin

*last chance /etc


text:
Q: unable to run .apk file in android studio I extracted a game from my android mobile using APK extractor. I wanted to get my hands dirty with the code by opening the file in Android Studio, but i am unable to run the apk file.
I did add "Gradle" to the project module and it failed with message "The project 'Candy Crush Saga_com.king.candycrushsaga' is not a Gradle-based project".
When I tried run the apk file without "Gradle" I am hitting the error "Error: Please select Android SDK". Can anyone guide me on how to make this apk run ?
excerpts from androidmanifest.xml file
xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1137101"
android:versionName="1.137.1.1"
android:installLocation="0"
package="com.king.candycrushsaga">

<uses-sdk
    android:minSdkVersion="16"
    android:targetSdkVersion="26" />

A: It is imposible to read code of apk in AndroidStudio without some changes , you can try this to see java code:

*

*Download dex2jar tool from dex2jar.

*Use the tool to convert the APK file to JAR:
$ d2j-dex2jar.bat demo.apk
dex2jar demo.apk -> ./demo-dex2jar.jar

*Once the JAR file is generated, use JD-GUI to open the JAR file. You will see the Java files.
The output will be similar to:


text:
Q: How to create a IdP with ITfoxtec i am interested to create a IdP (Identity Provider) with SAML.
It´s possible to create a full IdP funcionalities with ITfoxtec Nuget?
Have any example with ASP.Net, c#?

A: Yes, it is possible to implement an IdP using the ITfoxtec Identity Saml 2.0 library. You can see an ASP.NET MVC core IdP example at https://github.com/ITfoxtec/ITfoxtec.Identity.Saml2/tree/master/test/TestIdPCore.
I have implemented the SAML 2.0 IdP part of FoxIDs using the ITfoxtec Identity Saml 2.0 library.


text:
Q: How to convert a video file from mkv to a format supported by the TV set? I have a mkv video file which contains the following content:
> mkvmerge --identify original.mkv
File 'original.mkv': container: Matroska
Track ID 0: video (V_MPEGH/ISO/HEVC)
Track ID 1: audio (AAC)
Tags for track ID 0: 7 entries
Tags for track ID 1: 7 entries

But a 'standard' conversion using avconv does not work, neither a suggestion I found elsewhere (see below, and below that...). The original file can neither be played by mplayer nor when played from a hard drive connected to a TV.
How to solve these problem in order to convert the file into a more 'normal/standard' format, so it can be played by mplayer and on TV?
> avconv  -i original.mkv  -vcodec copy -acodec aac -strict -2 -b:a 384k  output.mp4
avconv version 9.18-6:9.18-0ubuntu0.14.04.1, Copyright (c) 2000-2014 the Libav developers
  built on Mar 16 2015 13:19:10 with gcc 4.8 (Ubuntu 4.8.2-19ubuntu1)
[matroska,webm @ 0x11d3200] Unknown/unsupported AVCodecID V_MPEGH/ISO/HEVC.
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 3 with DTS 209, packet 4 with DTS 167
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 4 with DTS 167, packet 5 with DTS 125
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 6 with DTS 292, packet 7 with DTS 250
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 8 with DTS 500, packet 9 with DTS 417
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 9 with DTS 417, packet 10 with DTS 334
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 13 with DTS 709, packet 14 with DTS 626
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 14 with DTS 626, packet 15 with DTS 542
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 18 with DTS 918, packet 19 with DTS 834
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 19 with DTS 834, packet 20 with DTS 751
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 23 with DTS 1126, packet 24 with DTS 1043
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 24 with DTS 1043, packet 25 with DTS 959
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 28 with DTS 1293, packet 29 with DTS 1210
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 29 with DTS 1210, packet 30 with DTS 1168
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 32 with DTS 1460, packet 33 with DTS 1376
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 33 with DTS 1376, packet 34 with DTS 1335
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 36 with DTS 1627, packet 37 with DTS 1543
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 37 with DTS 1543, packet 38 with DTS 1501
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 40 with DTS 1835, packet 41 with DTS 1752
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 41 with DTS 1752, packet 42 with DTS 1668
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 45 with DTS 2002, packet 46 with DTS 1919
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 46 with DTS 1919, packet 47 with DTS 1877
[matroska,webm @ 0x11d3200] Non-increasing DTS in stream 0: packet 49 with DTS 2211, packet 50 with DTS 2127
Input #0, matroska,webm, from 'original.mkv':
  Duration: 00:58:38.02, start: 0.000000, bitrate: N/A
    Stream #0.0: Video: [0][0][0][0] / 0x0000, 1920x1080, PAR 255:254 DAR 680:381, 23.98 fps, 23.98 tbr, 1k tbn (default)
    Metadata:
      BPS             : 1242590
      BPS-eng         : 1242590
      DURATION        : 00:58:38.015000000
      DURATION-eng    : 00:58:38.015000000
      NUMBER_OF_FRAMES: 84348
      NUMBER_OF_FRAMES-eng: 84348
      NUMBER_OF_BYTES : 546431695
      NUMBER_OF_BYTES-eng: 546431695
      _STATISTICS_WRITING_APP: mkvmerge v7.8.0 ('River Man') 32bit built on Mar 27 2015 16:18:02
      _STATISTICS_WRITING_APP-eng: mkvmerge v7.8.0 ('River Man') 32bit built on Mar 27 2015 16:18:02
      _STATISTICS_WRITING_DATE_UTC: 2016-05-16 06:10:27
      _STATISTICS_WRITING_DATE_UTC-eng: 2016-05-16 06:10:27
      _STATISTICS_TAGS: BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES
      _STATISTICS_TAGS-eng: BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES
    Stream #0.1: Audio: aac, 48000 Hz, 5.1, fltp (default)
    Metadata:
      BPS             : 187584
      BPS-eng         : 187584
      DURATION        : 00:58:37.995000000
      DURATION-eng    : 00:58:37.995000000
      NUMBER_OF_FRAMES: 82453
      NUMBER_OF_FRAMES-eng: 82453
      NUMBER_OF_BYTES : 82490002
      NUMBER_OF_BYTES-eng: 82490002
      _STATISTICS_WRITING_APP: mkvmerge v7.8.0 ('River Man') 32bit built on Mar 27 2015 16:18:02
      _STATISTICS_WRITING_APP-eng: mkvmerge v7.8.0 ('River Man') 32bit built on Mar 27 2015 16:18:02
      _STATISTICS_WRITING_DATE_UTC: 2016-05-16 06:10:27
      _STATISTICS_WRITING_DATE_UTC-eng: 2016-05-16 06:10:27
      _STATISTICS_TAGS: BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES
      _STATISTICS_TAGS-eng: BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES
[mp4 @ 0x11daf60] track 0: could not find tag, codec not currently supported in container
Output #0, mp4, to 'output.mp4':
  Metadata:
    encoder         : Lavf54.20.4
    Stream #0.0: Video: [0][0][0][0] / 0x0000, 1920x1080 [PAR 255:254 DAR 680:381], q=2-31, 90k tbn, 1k tbc (default)
    Metadata:
      BPS             : 1242590
      BPS-eng         : 1242590
      DURATION        : 00:58:38.015000000
      DURATION-eng    : 00:58:38.015000000
      NUMBER_OF_FRAMES: 84348
      NUMBER_OF_FRAMES-eng: 84348
      NUMBER_OF_BYTES : 546431695
      NUMBER_OF_BYTES-eng: 546431695
      _STATISTICS_WRITING_APP: mkvmerge v7.8.0 ('River Man') 32bit built on Mar 27 2015 16:18:02
      _STATISTICS_WRITING_APP-eng: mkvmerge v7.8.0 ('River Man') 32bit built on Mar 27 2015 16:18:02
      _STATISTICS_WRITING_DATE_UTC: 2016-05-16 06:10:27
      _STATISTICS_WRITING_DATE_UTC-eng: 2016-05-16 06:10:27
      _STATISTICS_TAGS: BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES
      _STATISTICS_TAGS-eng: BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES
    Stream #0.1: Audio: aac, 48000 Hz, 5.1, fltp, 384 kb/s (default)
    Metadata:
      BPS             : 187584
      BPS-eng         : 187584
      DURATION        : 00:58:37.995000000
      DURATION-eng    : 00:58:37.995000000
      NUMBER_OF_FRAMES: 82453
      NUMBER_OF_FRAMES-eng: 82453
      NUMBER_OF_BYTES : 82490002
      NUMBER_OF_BYTES-eng: 82490002
      _STATISTICS_WRITING_APP: mkvmerge v7.8.0 ('River Man') 32bit built on Mar 27 2015 16:18:02
      _STATISTICS_WRITING_APP-eng: mkvmerge v7.8.0 ('River Man') 32bit built on Mar 27 2015 16:18:02
      _STATISTICS_WRITING_DATE_UTC: 2016-05-16 06:10:27
      _STATISTICS_WRITING_DATE_UTC-eng: 2016-05-16 06:10:27
      _STATISTICS_TAGS: BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES
      _STATISTICS_TAGS-eng: BPS DURATION NUMBER_OF_FRAMES NUMBER_OF_BYTES
Stream mapping:
  Stream #0:0 -> #0:0 (copy)
  Stream #0:1 -> #0:1 (aac -> aac)
Could not write header for output file #0 (incorrect codec parameters ?): Operation not permitted

I also tried the following command:
avconv  -i original.mkv  -vcodec x264 -acodec aac -strict -2 -b:a 384k  output.mp4

which gives the following error:
Unknown encoder 'x264'

I also tried the following command:
avconv  -i original.mkv  -vcodec libx264 -acodec aac -strict -2 -b:a 384k  output.mp4

which resulted in this error:
[buffer @ 0x24adb00] Invalid pixel format string '-1'
Error opening filters!

A: Your file is HEVC-encoded, so it is H.265, which was still new or even changing when your avconv version was published, you would need more recent codecs to deal with it. Your avconv version  is quite outdated, I suggest you give it a go with the latest ffmpeg, which is now included in universe since 15.04.
On any Ubuntu newer than that, a simple apt update followed by apt install ffmpeg will install a newer version. If you are on 14.04, add this ppa
by add-apt-repository ppa:mc3man/trusty-media to get the latest ffmpeg.


text:
Q: Error diss.DWT devuelve siempre -1 Estoy probando el ejemplo de la función diss.DWT(), y siempre me devuelve -1 y este warning:
[1] -1
Warning message:
In diss.DWT(rbind(x, y, z)) : DWT Distance Temporarily not supported
El código es:
x <- cumsum(rnorm(100))
y <- cumsum(rnorm(100))
z <- sin(seq(0, pi, length.out=100))
#compute the distance
diss.DWT(rbind(x, y, z))

A: El error algo nos dice:

DWT Distance Temporarily not supported

Si además revisamos el código de la función, particularmente en el repositorio del proyecto (diss.R):
diss.DWT <- function(series) {
  warning("DWT Distance Temporarily not supported")
  return(-1)
    # if ( length(dim(series)) == 2 ) {
    #     if ( dim(series)[1] < 2 ) {
    #         stop( "diss.DWT needs a minimum of 2 series to compute the distance, incorrect amount provided" )
    #     }
    # } else {
    #     stop( "diss.DWT series matrix with incorrect dimensions" )
    # }
    # wt <- wavelet.feature.extraction( series )
    # dist(wt)
}

vemos, que hay una gran parte de código comentada y la parte funcional simplemente es el warning y el retorno de -1. Podemos deducir con esto elementos, que los autores del paquete, por algún motivo deshabilitaron la función, más precisamente en el último commit (historia) del proyecto. Resumiendo, el warning y el retorno -1 de está función se explican por la decisión de los autores de comentar esta funcionalidad, como decía un colega: "está bien que ande mal". No encontré información del motivo, pero entiendo se lo podrías preguntar en caso de ser necesario. En el paper del proyecto al final encontrarás los correos de los dos autores.


text:
Q: How to add MD5 hash toa PowerShell file dump Looking for a line to add that pulls the file information as below but includes an MD5 hash
It can be from certutil, but there is not a means to download that module so looking for a means that uses PowerShell without an additional update of PowerShell.
We are looking to compare two disks for missing files even when the file might be located in an alternate location.
cls
$filPath="G:/"
Set-Location -path $filPath

Get-ChildItem -Path $filPath -recurse |`
foreach-object{
$Item=$_
$Path =$_.FullName

$ParentS=($_.FullName).split("/")
$Parent=$ParentS[@($ParentS.Length-2)]

$Folder=$_.PSIsContainer
#$Age=$_.CreationTime
#$Age=$_.ModifiedDate
$Modified=$_.LastWriteTime
$Type=$_.Extension
$Path | Select-Object `
    @{n="Name";e={$Item}},`
    @{n="LastModified";e={$Modified}},`
    @{n="Extension";e={$Type}},`
    @{n="FolderName";e={if($Parent){$Parent}else{$Parent}}},`
    @{n="filePath";e={$Path}}`
} | Export-csv Q:/lpdi/fileDump.csv -NoTypeInformation

Possible answer here: (Thanks Guenther)
@{name="Hash";expression={(Get-FileHash -Algorithm MD5 -Path $Path).hash}}

In this script it meets the filehash condition along with the name of the file which allows a way to find the file on the folder and know it matches another one in another location based on the hash.
I'm not sure what happens on the file hash itself.  If it includes the name of the file, the hash will be different.  If it is only the file itself and the path doesn't matter, it should meet the requirement.  I'm not sure how to include it in the code above however

A: Your code could be simplified so you don't need all those 'in-between' variables.
Also, the path separator character in Windows is a backslash (\), not a forward slash (/) which makes this part of your code $ParentS=($_.FullName).split("/") not doing what you expect from it.
Try
$SourcePath = 'G:\'

Get-ChildItem -Path $SourcePath -File -Recurse | ForEach-Object {
    # remove the next line if you do not want console output
    Write-Host "Processing file '$($_.FullName)'.."
    $md5 = ($_ | Get-FileHash -Algorithm MD5).Hash
    $_ | Select-Object @{Name = 'Name';         Expression = { $_.Name }},
                       @{Name = 'LastModified'; Expression = { $_.LastWriteTime }},
                       @{Name = 'Extension';    Expression = { $_.Extension }},
                       @{Name = 'FolderName';   Expression = { $_.Directory.Name }},
                       @{Name = 'FilePath';     Expression = { $_.FullName }},
                       @{Name = 'FileHash';     Expression = { $md5 }}
} | Export-Csv -Path 'Q:/lpdi/fileDump.csv' -NoTypeInformation

Because getting hash values is a time consuming process I've added a Write-Host line, so you know the script did not 'hang'..

A: Edit: Okay so, here is my workaround as promised.
Before we start, requirements are:

*

*Have python 3.8 or above installed and registered in windows PATH

*edit the ps1 file variables accordingly

*edit the python file variables accordingly

*bypass powershell script execution policies

There are 4 files in the working directory (different from your target directory):

*

*addMD5.ps1 (static)

*addMD5.py (static)

*fileDump-original.csv (auto-generated)

*fileDump-modified.csv (auto-generated)

Here are the contents of those 4 files:
addMD5.ps1
$targetDir="C:\Users\USERname4\Desktop\myGdrive"
$workingDir="C:\Users\USERname4\Desktop\myWorkingDir"
$pythonName="addMD5.py"
$exportName = "fileDump-original.csv"

Set-Location -path $workingDir

if (Test-Path $exportName)
{
  Remove-Item $exportName
}

Get-ChildItem -Path $targetDir -recurse |`
foreach-object{
$Item=$_
$Path =$_.FullName

$ParentS=($_.FullName).split("/")
$Parent=$ParentS[@($ParentS.Length-2)]

$Folder=$_.PSIsContainer
#$Age=$_.CreationTime
#$Age=$_.ModifiedDate
$Modified=$_.LastWriteTime
$Type=$_.Extension
$Path | Select-Object `
    @{n="Name";e={$Item}},`
    @{n="LastModified";e={$Modified}},`
    @{n="Extension";e={$Type}},`
    @{n="FolderName";e={if($Parent){$Parent}else{$Parent}}},`
    @{n="filePath";e={$Path}}`
} | Export-csv $exportName -NoTypeInformation

python $pythonName

addMD5.py
import os, hashlib

def file_len(fname):
    with open(fname) as fp:
        for i, line in enumerate(fp):
            pass
    return i + 1

def read_nth(fname,intNth):
    with open(fname) as fp:
        for i, line in enumerate(fp):
            if i == (intNth-1):
                return line

def getMd5(fname):
    file_hash = hashlib.md5()
    with open(fname, "rb") as f:
        chunk = f.read(8192)
        while chunk:
            file_hash.update(chunk)
            chunk = f.read(8192)
    return file_hash.hexdigest()

file1name = "fileDump-original.csv"
file2name = "fileDump-modified.csv"

try:
    os.remove(file2name)
except:
    pass

file2 = open(file2name , "w")

for linenum in range(file_len(file1name)):
    if (linenum+1) == 1:
        file2.write(read_nth(file1name,linenum+1).strip()+',"md5"\n')
    else:
        innerfilename = read_nth(file1name,linenum+1).split(",")[4].strip()[1:-1]
        file2.write(read_nth(file1name,linenum+1).strip()+',"'+getMd5(innerfilename)+'"\n')

file2.close()

fileDump-original.csv
"Name","LastModified","Extension","FolderName","filePath"
"test1.txt","20-Jun-21 12:50:44 PM",".txt","C:\Users\USERname4\Desktop\myGdrive\test1.txt","C:\Users\USERname4\Desktop\myGdrive\test1.txt"
"test2.txt","20-Jun-21 12:50:37 PM",".txt","C:\Users\USERname4\Desktop\myGdrive\test2.txt","C:\Users\USERname4\Desktop\myGdrive\test2.txt"

fileDump-modified.csv
"Name","LastModified","Extension","FolderName","filePath","md5"
"test1.txt","20-Jun-21 12:50:44 PM",".txt","C:\Users\USERname4\Desktop\myGdrive\test1.txt","C:\Users\USERname4\Desktop\myGdrive\test1.txt","d659c1bc0a3010b0bdd45d9a8fee3196"
"test2.txt","20-Jun-21 12:50:37 PM",".txt","C:\Users\USERname4\Desktop\myGdrive\test2.txt","C:\Users\USERname4\Desktop\myGdrive\test2.txt","d55749658669d28f8549d94cd01b72ba"


text:
Q: How to call all list items in a list based on item count I'm trying to code a simple bruteforcer in Python, mainly to put my Python knowledge to the test. I have the number of items in a list, but I want to make "brutedata" have that same number of items. Here's a snippet of my code:
while count < contentscount - 1:
    count = count + 1
    brutedata = { postdata[0] : "admin", postdata[1] : contents[count] }
    brute = requests.post(target, data=brutedata)
    bruteresponse = brute.text

For example, if there are 3 POST parameters specified, brutedata will be:
brutedata = { postdata[0] : "value", postdata[1] : "value", postdata[2] : "value" }

A: You can generate a dictionary with a dict comprehension:
brutedata = {'postdata[{}]'.format(i): v for i, v in enumerate(itemlist)}

This produces a dictionary with N keys, keys named postdata[0], postdata[1], ..., postdata[N] with values in the same order as the input itemlist elements.
This syntax requires Python 2.7 or newer; for older versions, you can use the dict() constructor with a generator expression producing (key, value) pairs:
brutedata = dict(('postdata[{0}]'.format(i), v) for i, v in enumerate(itemlist))

Demo:
>>> itemlist = ['foo', 'bar', 'baz']
>>> {'postdata[{}]'.format(i): v for i, v in enumerate(itemlist)}
{'postdata[1]': 'bar', 'postdata[2]': 'baz', 'postdata[0]': 'foo'}
>>> dict(('postdata[{0}]'.format(i), v) for i, v in enumerate(itemlist))
{'postdata[1]': 'bar', 'postdata[2]': 'baz', 'postdata[0]': 'foo'}

Take into account dictionaries have no set order; the fact that postdata[0] is listed after the other two keys in the sample output is simply due to the implementation details of the underlying hash table used for dict.


text:
Q: Accessing values from Dictionaries that are part of an Array in Swift G'day,
I'm trying to use a for loop to access the values for the same key within an array of dictionaries in Swift.
For example,
let dictionaryOne = [
                    "name": "Peter",
                    "age": "42",
                    "location": "Milwaukee"]

let dictionaryTwo = [
                    "name": "Paul",
                    "age": "89",
                    "location": "Denver"]

let arrayOfDictionaries = [dictionaryOne, dictionaryTwo]

I'm attempting to create a function using a for loop that will output an array containing the values for location i.e. ["Milwaukee", "Denver"]
I have looked at other responses but I can only find how to access the value for "location" straight from the dictionary itself, which would be cumbersome if there were many different dictionaries rather than just two.
Many thanks for any help you can provide!

A: You can take advantage of the map method, whose purpose is to loop through the array and transform each element into another type:
arrayOfDictionaries.map { (dict: [String : String]) -> String? in
    return dict["location"]
}

The closure passed to the map receives an array element, and returns the transformed value - in your case, it retrieves and returns the value for the location key.
You can also use the compact form:
arrayOfDictionaries.map { $0["location"] }

Note that this method returns an array of optional strings, because the dictionary subscript operator always returns an optional. If you need an array of non optionals, then this is the unsafe version:
let x = arrayOfDictionaries.map { $0["location"]! }

Of course if the value for "location" key doesn't exist for an array element, a runtime exception will be raised.
More info about map at the Swift Standard Template Library

A: There are a few ways you could do this.  One is to use key-value coding (KVC):
let locations = (arrayOfDictionaries as NSArray).valueForKey("location") as [String]

A: The way I see it, you would populate a new array of Strings from the cities listed before.
var locations = [String]()

for dictionary in arrayOfDictionaries{
    locations.append(dictionary["location"]!)
}

println(locations)


text:
Q: Search through NSArray for string I would like to search through my NSArray for a certain string.
Example:
NSArray has the objects: "dog", "cat", "fat dog", "thing", "another thing", "heck here's another thing"
I want to search for the word "another" and put the results into one array, and have the other, non results, into another array that can be filtered further.

A: If the strings inside the array are known to be distinct, you can use sets. NSSet is faster then NSArray on large inputs:
NSArray * inputArray = [NSMutableArray arrayWithObjects:@"one", @"two", @"one again", nil];

NSMutableSet * matches = [NSMutableSet setWithArray:inputArray];
[matches filterUsingPredicate:[NSPredicate predicateWithFormat:@"SELF contains[c] 'one'"]];

NSMutableSet * notmatches = [NSMutableSet setWithArray:inputArray];
[notmatches  minusSet:matches];

A: Not tested so might have a syntax error, but you'll get the idea.
NSArray* inputArray = [NSArray arrayWithObjects:@"dog", @"cat", @"fat dog", @"thing", @"another thing", @"heck here's another thing", nil];

NSMutableArray* containsAnother = [NSMutableArray array];
NSMutableArray* doesntContainAnother = [NSMutableArray array];

for (NSString* item in inputArray)
{
  if ([item rangeOfString:@"another"].location != NSNotFound)
    [containsAnother addObject:item];
  else
    [doesntContainAnother addObject:item];
}

A: It would not work because as per document "indexOfObjectIdenticalTo:" returns the index of the first object that has the same memory address as the object you are passing in.
you need to traverse through your array and compare.


text:
Q: z-index issue with several absolute positioned elements Is it possible to bring an element into foreground that is inside an absolute positioned element and lying under another absolute positioned element?
For example:

Test 1

Test 2

CSS:
#el1, #el2, #test1, #test2 {
  position: absolute;
  top: 0;
  left: 0;
}

#el1 {
  z-index: 2;
}

#el2 {
  z-index: 1;
}

#test1, #test2 {
  z-index: 3;
}

All elements are absolute positioned and the first is lying over the second. Now I want to have both test-elements in the foreground. That's not possible because for the second the z-index does not apply because it's inside #el2. Is there any solution for this or do I have to put the test-elements outside the others?

A: The child elements will inherit the parents' z-index. You will have to change the structure of your markup to refelect the desired z-indexing.

Test 1

Test 2


text:
Q: Programing error: ('ODBC SQL type 102 is not yet supported. column-index=12 type=102', 'HY106') I have series of Python and Teradata files that I inherited. Each file is dependent on another. I'm trying to make this a little easier to run and I'm using pyodbc to run the Teradata queries. One of the queries is running fine, but when run another query, it get the following error:
File "...\pandas\io\sql.py", line 1753, in _fetchall_as_list
result = cur.fetchall()
ProgrammingError: ('ODBC SQL type 102 is not yet supported.  column-index=12  type=102', 'HY106')
The queries are near identical, the only thing changing is a level of grouping (the first query that is working is more granular).
I'm not sure why one works but the other doesn't, but I wonder if it has to do with file that is being imported? I also thought it might have to do with my version of Teradata or Spyder being incompatible, but that wouldn't explain why one query is working but the other isn't. I'm fairly new to Python and I don't see anything on type 102 error. Any feedback would he greatly appreciated.

A: So here's the thing, it's telling you the error, just not telling you well. To solve, change the SELECT statement to include one column at a time, when I get an error on a new column I'll convert in the query to a known good data type.
Example:
tableResult = pd.read_sql(
    "SELECT TOP 10 * FROM warehouse.equipment;",
    cnxn
)

results in an error message. I don't need select *, that's bad practice anyway. Start adding one at a time. Usually it's dates because dates are hard.
tableResult = pd.read_sql(
    "SELECT TOP 10 equipment_id FROM warehouse.equipment;",
    cnxn
)

Sometimes this is pretty trash too because who's the time?  Then I'll fire this query and I'll know to convert:
select
    column_name,
    data_type,
    character_maximum_length,
    collation_name
from information_schema.columns
where
    table_schema in ('warehouse')
    and table_name in ('equipment')
;

Now I can see that one column is returning datetimeoffset.  You'll replace this process with your tables for your tech stack, but the answers the same.


text:
Q: How to re-import an existing project from github into Android Studio? I don't want to keep local changes Trying; File -> New -> Project from Version Control -> Git
gives me following error:

The directory <project-name> already exists. Please choose another directory.

My understanding was that it will ask for confirmation whether to overwrite or not. Is deleting the project from file system and importing again the only way?

A: Git is simply saying that a directory with the name of the project you want to clone and import already exists. It's not asking for confirmation, it is simply refusing to clone it to the location of your choice. You have at least two options to deal with this:

*

*Delete (or alternatively rename) the existing directory so that Git can clone the repo anew

*Reset the repository so that it matches the remote, discarding your changes:
git fetch origin
git reset --hard origin/master

Link to a detailed answer by Dan Moulding.


text:
Q: Setting default values for inherited property without using accessor I always see people debating whether or not to use a property's setter in the -init method. My problem is how to create a default value in a subclass for an inherited property. Say we have a class called NSLawyer -- a framework class, that I can't change -- with an interface that looks like this:
@interface NSLawyer : NSObject {
    @private
    NSUInteger _numberOfClients;
}

@property (nonatomic, assign) NSUInteger numberOfClients;

@end

And an implementation that looks like this:
@implementation NSLawyer

- (instancetype)init
{
    self = [super init];
    if (self) {
        _numberOfClients = 0;
    }
    return self;
}

@end

Now let's say I want to extend NSLawyer. My subclass will be called SeniorPartner. And since a senior partner should have lots of clients, when SeniorPartner gets initialized, I don't want the instance to start with 0; I want it to have 10. Here's SeniorPartner.m:
@implementation SeniorPartner

- (instancetype)init
{
    self = [super init];
    if (self) {

        // Attempting to set the ivar directly will result in the compiler saying,
        // "Instance variable _numberOfClients is private."

        // _numberOfClients = 10; <- Can't do this.

        // Thus, the only way to set it is with the mutator:
        self.numberOfClients = 10;

        // Or: [self setNumberOfClients:10];
    }
    return self;
}

@end

So what's a Objective-C newcomer to do? Well, I mean, there's only one thing I can do, and that's set the property. Unless there's something I'm missing. Any ideas, suggestions, tips, or tricks?

A: You should do exactly has you have; call the accessor. The declaring class typically avoids calling its own accessors in init to avoid accidentally calling an overridden accessor in a subclass that might rely on the consistency of data you haven't initialized yet. Your superclass on the other hand should be completely consistent by the time the subclass's init is run, so there is no problem using superclass accessors at that time.
Consider the common and general case: you want to set your transform in a UIView subclass. How would you solve that other than call setTransform:? Subclassing non-Apple code is no different.

A: Make it @protected. It is very rare to make an ivar or property private these days. Private ivars and/or properties are better declared in the implementation. For that matter @protected ivars/properties are rarely seen in Objective-C but perfectly fine.
Using a setter either as a method or with dot notation is just wrong (yes it works but is really bad form), if you want use setters/getters declare a property.


text:
Q: spring.mvc.view.suffix does not work I'm new with spring boot, and I've wrote the WelcomeController which is below.
@Controller
public class WelcomeController {
    @RequestMapping("/home")
    public String home() {
        return "homePage";
    }
}

Then I add spring.mvc.view.suffix=.html to the application.properties.
I suppose only the localhost:8080/home.html url would render homePage.html. But when I visit localhost:8080/home, I still get the homePage.html, not a 404 error as I supposed.
How can I make url which only end with '.html' legal? Why the spring.mvc.view.suffix=.html config don't work?

A: I think you are getting confused with the purpose of the property. Basically all it's doing is stating what's the extension the view file will have in the server.
Read a bit about it here https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html around chater 74.8
I believe that you are just trying to validate the url endpoint and make sure it ends in ".html"
@Controller
public class WelcomeController {
    @RequestMapping("/home")
    public String home(HttpServletRequest request) throws Exception {

        String uri = request.getRequestURI();
        if (!isValidEndpoint(uri)) {
            throw new InvalidUrlException();
        }

        return "homePage";
    }

    private boolean isValidEndpoint(String url) {
        return url.endsWith(".html");
    }
}

@ResponseStatus(code=HttpStatus.NOT_FOUND, reason="The url needs to end with '.html'")
class InvalidUrlException extends Exception {
    private static final long serialVersionUID = 1L;

    public InvalidUrlException() {
        super();
    }
}


text:
Q: Connect a CSS file to a custom wordpress widget So i searched quite a while and just did not find out, how to do this, possibly because of the language barrier or not enough PHP knowledge:
public function widget( $args, $instance ) {

    ?>

    <?php

    if ( ! empty( $instance['title'] ) ) {
        echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ). $args['after_title'];
    }
    /*echo __( 'Hello, World!', 'text_domain' );*/

    ?>

                <?php

                if ( ! empty( $instance['mainTxt'] ) ) {
                    echo apply_filters( 'widget_title', $instance['mainTxt'] );
                }
                ?>

    <?php

    echo $args['after_widget'];
}

I succesfully made a custom widget for my selfmade wordpress theme and played around with the styling.
That worked quite okay, but i'd like to use a css file just for that widget type.
So how can i use a css file for that? Thanks in advance (and sorry for spelling, i'm not a native speaker).

A: So, you can't add a style sheet that only applies to your widget. You'll end up loading it for the whole site or just the admin dashboard.
For a much more elegant solution than inline styling, go for one of these two methods:
function extra_css () {
   echo '';
}

Then add the action:
add_action( 'wp_head', 'extra_css' );

Another way to do it is enqueue a whole stylesheet
function add_css_file() {
   wp_enqueue_style('css', 'path/to/your/style');
}

The add the action:
add_action('wp_enqueue_scripts', 'add_css_file');

A: Add a class to the wrapping div and use that in your stylesheet.

.custom-widget {
  padding: 0 0 14% 0
}
.mainbar {
  border: 2px solid #e0e0e0;
  border-radius: 2px;
  background: #f3f3f3;
}
.mainbar > div {
  background: #e0e0e0;
  padding: 2% 3%
}
public function widget( $args, $instance ) { ?>

    <?php

    if ( ! empty( $instance['title'] ) ) {
        echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ). $args['after_title'];
    }
    /*echo __( 'Hello, World!', 'text_domain' );*/

    ?>

        <?php if ( ! empty( $instance[ 'mainTxt'] ) ) { echo apply_filters( 'widget_title', $instance[ 'mainTxt'] ); } ?>

<?php echo $args[ 'after_widget']; }


text:
Q: Assign identifier values that include an original name in R I have a data frame for which one of the attributes is the original object identifier number. I have split some of the records into two objects. Now, I would like to assign a new object identifier that includes the original name and a letter from a to z (fortunately my dataset has a maximum of 12 duplicates per original identifier). I found a method with a for loop but given that my dataset has over 750 000 records, it is very long. Is there something more straightforward than my solution? I have not yet mastered creating apply/dlyr type commands in R.
#create data.frame
sample = data.frame(ID_obj=c(1:6, 4, 2), x=c(1,1,1,1,2,2,2,4), y=c("a3", "4a", "5b", "8b"))

#reorder sample by ID_obj
sample<-sample[order(sample$ID_obj),]

#create empty vector
test<-numeric(0)
for (i in 1:6)
{
add<-letters[1:dt[i,"Freq"]]
test<-c(test, add)
}

sample$ID_obj_new<-paste(sample$ID_obj, test, sep="_")
#  ID_obj x  y ID_obj_new
#1      1 1 a3        1_a
#2      2 1 4a        2_a
#8      2 4 8b        2_b
#3      3 1 5b        3_a
#4      4 1 8b        4_a
#7      4 2 5b        4_b
#5      5 2 a3        5_a
#6      6 2 4a        6_a

A: Here you go with a solution using the package dplyr
library(dplyr)
library(bindrcpp)

sample %>%
    group_by(ID_obj) %>%
    mutate(ID_obj_new = paste(ID_obj, letters[1:n()], sep="_")) %>%
    ungroup()

A: For the sake of completeness, here is also a concise solution which uses the rowid() function from the data.table package:
library(data.table)
setDT(sample)[, ID_obj_new := paste(ID_obj, letters[rowid(ID_obj)], sep = "_")][]

   ID_obj x  y ID_obj_new
1:      1 1 a3        1_a
2:      2 1 4a        2_a
3:      2 4 8b        2_b
4:      3 1 5b        3_a
5:      4 1 8b        4_a
6:      4 2 5b        4_b
7:      5 2 a3        5_a
8:      6 2 4a        6_a

This will work even if sample is not ordered.


text:
Q: How can I add third talent or fourth talent? I want to add more talent for character.
I add table character_talent data for character but it doesn't work.
Can you share me the steps?

A: Not dual specialization? 3 or 4 ?
And client supports this?

A: Depends on your question. If you mean more talents available for players to use, than you can do it in world configurations at the line:
Rate.Talent
    Description: Talent point rate.
    Default:     1
    Rate.Talent = 1

Rate.Talent = 1 is the normal (default) starting at level 10 by giving you 1 talent point for each level, 71 in total.
Rate.Talent = 2 is the double rate. So if you get level 71 you will receive 142 talents points.


text:
Q: Dynamic tables from a stored procedure using Linq to Entities I have a question about Entity Framework and Linq to Entities. My .NET version is 4.0. I'm refactoring the database access layer of an existing application, and I plan to use Linq to Entities (instead of today's DataReaders and SQL strings). The structure of the database cannot be altered.
My problem comes from a stored procedure, which, simplified, looks like the following:
CREATE PROCEDURE getElement @tableid as int, @elementid as int AS
BEGIN
DECLARE @tablename as varchar(50)
SELECT @tablename = tablename FROM tables WHERE tableid = @tableid
EXEC('SELECT * FROM ' + @tablename + ' WHERE elementid = ' + @elementid)
END

I know that the row(s) returned will have a column named elementid, and based on this value, I know what other columns to expect.
Today, this is solved with an SqlDataReader which does a dictionary-like lookup of the elemendid element.
public Element getElement(SqlDataReader dr)
{
    switch((int)dr["elementid"])
    {
        case 1:
            return getTextElement(dr);
        case 2:
            return getImageElement(dr);
        //...
    }
}

Element is an abstract base class. getTextElement returns a TextElement : Element, and getImageElement returns an ImageElement : Element.
How do I model this in Entity Framework? Complex types does not seem to cut it, since it does not seem to support dynamic properties. I have also looked at an EntityObject Generator, but I'm not really all that experienced with customizing T4 code (maybe I ought to learn for this problem?). The perfect solution for me would be to have the imported stored procedure return an object with the dynamic type, but Entity Framework 4 does not seem to support this.

A: I think the problem you are encountering is that the EF and Linq to Sql designers generate models based on the known structure of a table.  You sproc evaluates the result using EXEC, so the procedure cannot be analysed to figure out what the result model will look like.  I'm not sure this can be solved using an ORM tool, you may need to specialise two stored procedures, one for explicitly returning TextElement models, and one for ImageElement models.

A: I just thought that I would add how I solved this.
I created a couple of helper classes that emulates the behaviour of Linq to Entities, and use them on my special stored procedures. It's far from perfect, or even good, but it makes the resulting code look quite similar to Linq to Entities. This is important for me as the rest of my database layer will use Linq to Entities.
In the perfect world, I would be able to formulate a query to Linq to Entities, and then use the result somewhat similar to what I'm doing right now.
Here we go...
The code is used as follows:
var connectionString = new SqlConnectionStringBuilder
{
    DataSource = @"C:\Temp\Northwind.mdf"
};

var commandText = "select * from Customers";

using (var rows = new SqlCommandHelper(connectionString.ToString(), System.Data.CommandType.Text, commandText))
{
    foreach (dynamic row in rows)
    {
        try
        {
            Console.WriteLine(row.Fax ?? "Emtpy");
        }
        catch (IndexOutOfRangeException)
        {
            Console.WriteLine("Invalid column name");
        }
    }
}

As you can see, the enumeration of the rows looks similar to how it would be if I had used Linq to Entities instead of SqlCommandHelper.
The SqlCommandHelper class is the following code:
class SqlCommandHelper : IEnumerable<DynamicSqlRow>, IDisposable
{
    private SqlConnection connection;
    private SqlCommand command;

    public SqlCommandHelper(string connectionString, System.Data.CommandType commandType, string commandText, params SqlParameter[] parameters)
    {
        connection = new SqlConnection(connectionString);
        command = new SqlCommand
        {
            CommandText = commandText,
            CommandType = commandType,
            Connection = connection
        };

        command.Parameters.AddRange(parameters);
    }

    public IEnumerator<DynamicSqlRow> GetEnumerator()
    {
        if (connection.State != System.Data.ConnectionState.Open)
        {
            connection.Open();
        }

        using (var reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                yield return new DynamicSqlRow(reader);
            }
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public void Dispose()
    {
        command.Dispose();
        connection.Dispose();
    }
}

As you can see, the magic lies within DynamicSqlRow. I thing to note is that you'll need to import the System.Dynamic namespace for DynamicSqlRow to compile.
class DynamicSqlRow : DynamicObject
{
    System.Data.IDataReader reader;

    public DynamicSqlRow(System.Data.IDataReader reader)
    {
        this.reader = reader;
    }

    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
        var row = reader[binder.Name];

        result = row is DBNull ? null : row;

        return true;
    }
}

I hope that this code might be useful for anyone else, or that it makes someone think of a better solution.
A useful link for me was Walkthrough: Creating and Using Dynamic Objects from MSDN.
Take care


text:
Q: Logistic regression returns error but runs okay on reduced dataset I would appreciate your input on this a lot!
I am working on a logistic regression, but it is not working for some reason:
mod1<-glm(survive~reLDM2+yr+yr2+reLDM2:yr +reLDM2:yr2+NestAge0,
         family=binomial(link=logexp(NSSH1$exposure)),
                       data=NSSH1, control = list(maxit = 50))

When I run the same model with less data it works!
But with the complete dataset I get an error and warning messages:
Error: inner loop 1; cannot correct step size
In addition: Warning messages:
1: step size truncated due to divergence
2: step size truncated due to divergence

This is the data: https://www.dropbox.com/s/8ib8m1fh176556h/NSSH1.csv?dl=0
Log exposure link function from User-defined link function for glmer for known-fate survival modeling:
library(MASS)
logexp <- function(exposure = 1) {
    linkfun <- function(mu) qlogis(mu^(1/exposure))
    ## FIXME: is there some trick we can play here to allow
    ##   evaluation in the context of the 'data' argument?
    linkinv <- function(eta)  plogis(eta)^exposure
    mu.eta <- function(eta) exposure * plogis(eta)^(exposure-1) *
      .Call(stats:::C_logit_mu_eta, eta, PACKAGE = "stats")
    valideta <- function(eta) TRUE
    link <- paste("logexp(", deparse(substitute(exposure)), ")",
               sep="")
    structure(list(linkfun = linkfun, linkinv = linkinv,
               mu.eta = mu.eta, valideta = valideta,
               name = link),
          class = "link-glm")
}

A: tl;dr you're getting in trouble because your yr and yr2 predictors (presumably year and year-squared) are combining with an unusual link function to cause numerical trouble; you can get past this using the glm2 package, but I would give at least a bit of thought to whether it makes sense to try to fit the squared year term in this case.
Update: brute-force approach with mle2 started below; haven't yet written it to do the full model with interactions.
Andrew Gelman's folk theorem probably applies here:

When you have computational problems, often there's a problem with your model.

I started by trying a simplified version of your model, without the interactions ...
NSSH1 <- read.csv("NSSH1.csv")
source("logexpfun.R")  ## for logexp link
mod1 <- glm(survive~reLDM2+yr+yr2+NestAge0,
          family=binomial(link=logexp(NSSH1$exposure)),
          data=NSSH1, control = list(maxit = 50))

... which works fine. Now let's try to see where the trouble is:
mod2 <- update(mod1,.~.+reLDM2:yr)  ## OK
mod3 <- update(mod1,.~.+reLDM2:yr2) ## OK
mod4 <- update(mod1,.~.+reLDM2:yr2+reLDM2:yr)  ## bad

OK, so we're having trouble including both interactions at once.  How are these predictors actually related to each other? Let's see ...
pairs(NSSH1[,c("reLDM2","yr","yr2")],gap=0)

 yr and yr2 aren't perfectly correlated, but they're perfectly rank-correlated and it's certainly not surprising that they're interfering with each other numerically Update: of course "year" and "year-squared" look like this! even using poly(yr,2), which constructs an orthogonal polynomial, doesn't help in this case ... still, it's worth looking at the parameters in case it provides a clue ...
As mentioned above, we can try glm2 (a drop-in replacement for glm with a more robust algorithm) and see what happens ...
library(glm2)
mod5 <- glm2(survive~reLDM2+yr+yr2+reLDM2:yr +reLDM2:yr2+NestAge0,
          family=binomial(link=logexp(NSSH1$exposure)),
          data=NSSH1, control = list(maxit = 50))

Now we do get an answer. If we check cov2cor(vcov(mod5)), we see that the yr and yr2 parameters (and the parameters for their interaction with reLDM2 are strongly negatively correlated (about -0.97). Let's visualize that ...
library(corrplot)
corrplot(cov2cor(vcov(mod5)),method="ellipse")

What if we try to do this by brute force?
library(bbmle)
link <- logexp(NSSH1$exposure)
fit <- mle2(survive~dbinom(prob=link$linkinv(eta),size=1),
     parameters=list(eta~reLDM2+yr+yr2+NestAge0),
     start=list(eta=0),
     data=NSSH1,
     method="Nelder-Mead")  ## more robust than default BFGS
summary(fit)
##                   Estimate Std. Error  z value   Pr(z)
## eta.(Intercept)  4.3627816  0.0402640 108.3545 < 2e-16 ***
## eta.reLDM2      -0.0019682  0.0011738  -1.6767 0.09359 .
## eta.yr          -6.0852108  0.2068159 -29.4233 < 2e-16 ***
## eta.yr2          5.7332780  0.1950289  29.3971 < 2e-16 ***
## eta.NestAge0     0.0612248  0.0051272  11.9411 < 2e-16 ***

This seems reasonable (you should check predicted values and see that they make sense ...), but ...
cc <- confint(fit)  ## "profiling has found a better solution"

This returns an mle2 object, but one with a mangled call slot, so it's ugly to print the results.
coef(cc)
## eta.(Intercept)                      eta.reLDM2
##     4.329824508                    -0.011996582
##       eta.yr                         eta.yr2
##     0.101221970                     0.093377127
##     eta.NestAge0
##      0.003460453
##
vcov(cc) ## all NA values! problem?

Try restarting from those returned values ...
fit2 <- update(fit,start=list(eta=unname(coef(cc))))
coef(summary(fit2))
##                     Estimate  Std. Error    z value        Pr(z)
## eta.(Intercept)  4.452345889 0.033864818 131.474082 0.000000e+00
## eta.reLDM2      -0.013246977 0.001076194 -12.309102 8.091828e-35
## eta.yr           0.103013607 0.094643420   1.088439 2.764013e-01
## eta.yr2          0.109709373 0.098109924   1.118229 2.634692e-01
## eta.NestAge0    -0.006428657 0.004519983  -1.422274 1.549466e-01

Now we can get confidence intervals ...
ci2 <- confint(fit2)
##                       2.5 %       97.5 %
## eta.(Intercept)  4.38644052  4.519116156
## eta.reLDM2      -0.01531437 -0.011092655
## eta.yr          -0.08477933  0.286279919
## eta.yr2         -0.08041548  0.304251382
## eta.NestAge0    -0.01522353  0.002496006

This seems to work, but I would be very suspicious of these fits.  You should probably try other optimizers to make sure you can get back to the same results.  Some better optimization tool such as AD Model Builder or Template Model Builder might be a good idea.
I don't hold with mindlessly dropping predictors  with strongly correlated parameter estimates, but this might be a reasonable time to consider it.


text:
Q: VMWare ESXi 4.0 all VM's randomly lock up: help required Rig:

*

*Dell PowerEdge T610

*2 x Intel Xeon quad-core

*16gb RAM

Buckle in and prepare for a long ride, this is not so much a specific question as a shameless attempt to get a free ninja sysadmin instead of trying to hire one  I hear a few of them hang around these parts :)
So I'm running VMWare ESXi 4.0 on a Dell PowerEdge. I have:

*

*6 instances of Windows Server 2008,

*1 Instance of Windows Server 2003,  1

*1 instance of Ubuntu 10,  and 1

*1 instance of Windows XP.

Randomly, typically a few weeks apart, all vm's will just suddenly cease to respond. I can connect using the VSphere Client but the console tab for each vm just remains a blank black screen. No response to ping on the network.
VMWare has nothing to say about any of it, the syslog appears normal no obvious errors of any kind. If I try and reboot or power cycle any VM using VSphere Client it gets to 95% in the notification area and then... nothing.
If I attach keyboard and mouse to the physical server there's an option F12 to restart but this does... yep you guessed it nothing at all. I have waited up to 20-30 minutes and nothing happens.
I need someone from the school of knocks to take me by the hand and give me some pointers on how to troubleshoot and isolate this issue. I have a sneaking suspicion it might be something to do with the SCSI hard drive array, messages mentioning SCSI are often (but not always) the last thing in the syslog at the time this lock-up happens, although VMWare carries on logging all kinds of mundane fluff after these messages as if nothing's wrong.
I'm a busy dev and as much as I'd love to be a talented sysadmin, unfortunately I'm not so
any help or words of advise for getting a handle on my vm issue would be much appreciated.

A: It's either dicky hardware, some sort of code corruption or a very odd bug.
My advice would be to immediately upgrade to 4.1U1, this will ensure the code's up to date and isn't corrupt in any way - if your actual VMs are on a different set of disks I'd wipe the OS disk too before this update.
Other than that it's going to be the usual trick of replacing parts until you gain stability - at least you have a suspicion of what part/s might be at fault.
Of course you can always call VMWare and/or Dell if you have support contracts.