text:
Q: How to reference CloudFormationProvisionedProduct Outputs I need to provision AWS resources via AWS Service Catalog. I have a 'product' which i can provision and then i need to reference some property available in Outputs of provisioned product resource.
I wanted to reference the value within Outputs of AWS::ServiceCatalog::CloudFormationProvisionedProduct and hoped that it works same way as Outputs of a stack.
I tried !GetAtt http:// ProvisionedProductName, Outputs.InnerProperty - did not work, i get Requested attribute Outputs.InnerProperty must be a readonly property in schema for AWS::ServiceCatalog::CloudFormationProvisionedProduct
The Outputs attribute exists, however i am not sure how to explode this list and get an inner property.
I tried to use !Select to reference a list item, however it does not seem to work either:
!Select [1, !GetAtt https://forums.aws.amazon.com/
Template error:
Fn::Select requires a
list argument with two
elements: an integer
index and a list
Help appreciated

A: They recently launched this exact feature, so "!GetAtt YOURPROVISIONEDPRODUCTNAME.Outputs.YOUROUTPUTNAME" should work.
https://aws.amazon.com/about-aws/whats-new/2020/07/provisioned-product-outputs-now-available-aws-service-catalog/
This blog was updated too: https://aws.amazon.com/blogs/mt/how-to-launch-secure-and-governed-aws-resources-with-aws-cloudformation-and-aws-service-catalog/, search for ".Outputs."


text:
Q: Calender View highlight guys how can i do with CalenderView that the first day of every month will be in highlight or just in different color or even not the start of the month even highlight middle of the month

A: First you should understand how to select a date, then highlight those dates .
Here is a Sample:
String date = "22/3/2014";
    String parts[] = date.split("/");

    int day = Integer.parseInt(parts[0]);
    int month = Integer.parseInt(parts[1]);
    int year = Integer.parseInt(parts[2]);

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.YEAR, year);
    calendar.set(Calendar.MONTH, month);
    calendar.set(Calendar.DAY_OF_MONTH, day);

    long milliTime = calendar.getTimeInMillis();

And now set the selected date in the calendar view by doing and further activities as your requirement:
mCalendarView.setDate (milliTime, true, true);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Intermittent error thrown, "A required anti-forgery token was not supplied or was invalid." I'm occasionally getting this error during normal use, and I've not found a way to stop it without removing the attribute that requires the token, which I'd rather not do.
I've gotten this bug during my own testing (but seemingly randomly) and I know from my logging that actual logged-in users are getting it as well.
Does anyone know what would cause the antiforgerytoken system to break (other than a real attack), and how I could fix this without opening up a security hole in my forms?
Thanks!

A: Here's a portion of my answer to a similar question:
Machine Key and Cookies: this issue is ugly, easy to spot (causes exceptions), but not very intuitive. The validation cookies and tokens are encoded and decoded using a unique "machine key".  This means that if you have a server farm, or change your server, your cookie will no longer be valid.  Closing your browser fixes the issue (because the cookie is a session cookie).  However, some people leave their browser windows open in the background for a long time!
The solution is to set a "machine key" in your config file.  This will tell MVC to use the same key on all servers, ensuring that the cookie will be decryptable everywhere.
Please note: if a user keeps any browser window open, even AFTER you change your machine key, they will continue to get these error messages!  They MUST close the window (to clear the session-cookie) in order to access your website again.

A: One thing to make sure is to have the same machine key token for all requests. If you don't have this and your application pool recycles, subsequent POSTs with old cookies cause this error.
Another cause is when somebody has the privacy settings way high and thus blocking cookies. For example, in Internet Explorer from the Privacy tab if the settings are set to High or Block All Cookies you would get this error.

A: Read the section here on limitations
prevent cross site request forgery

A: Not sure if this will help but I found that when using Internet Explorer I would get this error whenever there was an underscore '_' inside the subdomain... however not on Firefox.
Still looking for a solution or reasoning.

A: Make sure that your ~/Web.config has a <machineKey> section and that you're setting the key from within that section.  The anti-XSRF system requires this to be present.

A: As mpen said in the comment on the answer I see this all the time when users leave the page sitting there for more than 20 minutes (the default session time) and the token expires.
You can trigger or force this error (if you're trying to test catching it) by opening your browser's developer tools and deleting the __RequestVerificationToken hidden field:
<input name="__RequestVerificationToken" type="hidden" value="AqJL/+e9tGCSCXdurrXDRefVL/TAdOAG9Hjrx0oMPg6sVZY3xv099OSYlH1qI8uZyu4x2xFj9eiNVSH2BGsSfJCQAqzxfQtIKoHXNkkW2FJTkxzsNRkwZo1SJUzYGvcEJ/OJ0AouiUWh98qyIzgN2ZkKP7k=">


text:
Q: How can i "externalize" material-ui from a react app i am working on an react app creadted with the "create-react-app my-app --template cra-template-pwa-typescript" command.
Also i am using the material-ui package for the interface.
Now i want to use material-ui through an cdn. so i need to exclude this package via the "externals" config. I am using "react-app-rewired" to override the default config.
But i dont find a proper way to define the externals. found several examples,
for example:
externals = [
  //...other externals working fine
  /@material-ui\/.*/
]

or
externals = [
  "@material-ui/core",
  "@material-ui/icons",
  /@material-ui\/core\/.*/,
  /@material-ui\/icons\/.*/,
}

But when using this method i got an error while compiling
Failed to compile.

Failed to minify the code from this file:

        external "@material-ui/core":1

Also tried the solution described here:
https://github.com/mui-org/material-ui/issues/11777#issuecomment-452306347
Here i dont get an error, but the material-ui package didnt excluded and is still bundled.


text:
Q: How to lump together Apache2 Server and xsp2 server in the configuration for auto start when the PC reboots? We need to lump together Apache2 Server and xsp2 server(or  mod-mono-server server) in the configuration for the auto start sample shown below when the PC reboots.
Quoting from the article, https://askubuntu.com/questions/9382/how-can-i-configure-a-service-to-run-at-startup
"sudo update-rc.d minidlna defaults
This should add the service to the automatic startup system. But if you get:

System start/stop links for /etc/init.d/minidlna already exist.
Do the command

sudo update-rc.d minidlna enable"

How could I adapt the above sample so that Apache2 Server and xsp2 server are lumped together during the automatic startup procedure?
I was thinking of launching Apache2 first directly followed by launching xsp2 next. Is this  possible to do with Ubuntu 16.04 or is there a better way?
Any help is greatly appreciated.

A: I wish to thank @garethTheRed for suggesting to use systemd instead of update-rc.d
The URL Writing basic systemd service files contains this answer.
Step 1: I created this file (note location) which essentially fires a bash process with an extended argument. You could fire your own command which could be different from bash.
[root@y500-fedora ~]# cat /usr/lib/systemd/system/foo.service
[Unit]
Description=foo

[Service]
ExecStart=/bin/bash -c "while true; do /bin/inotifywait -qq --event close_write /sys/class/backlight/acpi_video0/brightness; su myusername -c '/bin/xbacklight -display :0 -set $(cat /sys/class/backlight/acpi_video0/brightness)'; done"

[Install]
WantedBy=graphical.target
Step 2:

systemctl enable foo
(similarly you can disable it)

(optional) Step 3: It should start automatically at next reboot into graphical mode (run level 5) but if you want to start it right away:
# systemctl start foo
# systemctl status foo # optional, just to verify


text:
Q: How can I see relationship between tables in designer phpmyadmin? I just added few tables in the database but there are associations between them. I wanted to see the relations in designer but I only found tables and not the associations between them. I have looked for solutions but only found other users having the same issue.
This is a screenshot
new screenshot


text:
Q: linking issue with qttestrunner in cppunit I am working in a project based on the lib cppunit, I need to run my tests with qttestrunner
I make the libqttestrunnerd.a (qmake qttestrunnerlib.pro  and make ), obviously there is a problem of linking, here is a sample of output:
/home/oumaya/docs/UT_Cpp_Test/main/cppDir/lib/lib/libqttestrunnerd.a(moc_testbrowserdlg.o):(.rodata._ZTV15TestBrowserBase[vtable for TestBrowserBase]+0x30): undefined reference to 'QWidget::setName(char const*)'
/home/oumaya/docs/UT_Cpp_Test/main/cppDir/lib/lib/libqttestrunnerd.a(moc_testbrowserdlg.o):(.rodata._ZTV15TestBrowserBase[vtable for TestBrowserBase]+0x34): undefined reference to 'QObject::insertChild(QObject*)'
there is a lot of similar messages related to QT objects.
any help please
thank you in advance.

A: When working with qt and you get undefined reference to ... usually that means you are inheriting a class and not implementing its virtual functions. Check the documentation(s) for the Qt class(es) you are inheriting and find out which of its functions are virtual and implement them in your class.


text:
Q: How to do data driven testing using jMeter if the values are present in the body not in parameters I know using of data driven in jMeter by passing the values in parameters, but my concern is how to the data driven testing when the values are sending in request of a body. Any help will be appreciated

A: You can use CSV Data Set Config, Add > Config Element > CSV Data Set Config
In the CSV file you can set the value for the parameters.
example csv file

Provide csv file path in CSV Data Set Config

Imported CSV file will be the data to perform data driven testing for login page, where first row of the csv file is variable name and rest is test data.
Set the number of thread user  under Thread Group same as number of rows present in the csv file.

A:
Have you tried fill body like this?
MyVariable is user defined variable


text:
Q: How to abstract a JavaScript file? I've got a difficult question.
I could not find an answer on the internet...so this is my last chance.
I would like to realize the following scenario:

*

*One File JavaScript that is "abstract", i.e., when the client is mobile, I use mobile Javascript implementation; otherwise I use the classic one.

In other words:
How can I create an A.js file with functions\Other (For example a HelloWorld()) and, by delegation or inheritance (or other solution that I ignore)? Can I use the HelloWorld() of A-mobile.js or the HelloWorld() of A-classic.js?
Thanks a lot!

A: I dont think you want solve this on class level of your javascript. Instead, use different JS file for mobile and full versions. You can do this on server side (render different HTML script tag for each) or on client (javascript can load another javascript like this:
if (mobile){
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", mobileJsFilename)
  document.getElementsByTagName("head")[0].appendChild(fileref)
 }

As for detecting mobile browser, look here : http://detectmobilebrowsers.com/


text:
Q: Three.js OBJ loader Raycaster get Parent im currently building a smal 3d configurator. I stumbled upon the problem, that if I use the Raycaster to trigger an event, I have to enable recursive when using .intersectObject(). But I need to change the position of the 'parent' if you might call it that way. Is it possible to refer to the object loaded with the obj loader instead of the descendant?
Here is my mouseDown function:
function onDocumentMouseDown( event ){
event.preventDefault();

raycaster.setFromCamera( mouse, camera );

var intersects = raycaster.intersectObjects( ObjectArr, true );

if ( intersects.length > 0 ) {

    SELECTED = intersects[ 0 ].object;

    if ( raycaster.ray.intersectPlane( plane, intersection ) ) {

        console.log("Plane Intersection");
        SELECTED.doSomething...

    }

}

}

So SELECTED is not a value of ObjectArr. I need to refer to the position from another function. Is there a possibility to refer to the parent object?

A: Thanks to Derte Trdelnik.
The solution was to use SELECTED.parent.


text:
Q: Finding Element's xpath address I'm trying to get an attribute of the small arrow next to 'Date' that is shown in the pic:

I used Katalon recorder to find the element's xpath address, and it gave me the following xpath:
"//div[5]/sort-direction/iron-icon[2]"

But this xpath is not enough, because I need the "d" attribute which is inside the 'path' tag (as you can see in the pic).
I tried to modify the xpath like this :
"//div[5]/sort-direction/iron-icon[2]/svg/g/path"

But then I got an NoSuchElementException exception.
Any ideas of how to get this attribute?

A: Please check the count of iron-icon. From picture given, it seems the "d" attribute you are trying to fetch is under the hierarchy of iron-icon at index 1 not 2.
Please try the xpath as :
"//div[5]/sort-direction/iron-icon[1]/svg/g/path"

A: Remove svg, and change iron-icon[2] to iron-icon[1], which is svg. You don't need them both.


text:
Q: Subquery returns more than 1 row in like %..% i am working with bank transaction table witch contain 67000 transactions for around 800 customer from January to October so what i want is to calculate number of transactions for each customer per month i want the final result will be like cust_id , number of transaction for jan ,number of transaction for Feb ... til October i tryed this query
 SELECT
    cut_id,
    CASE WHEN tra_date LIKE '%Oct%'
        THEN
            (select count(tra_date) from tab where tra_date like '%Oct%' GROUP by cut_id)
        ELSE 0
    END AS oct,
    CASE WHEN tra_date LIKE '%Sep%'
        THEN
            (select count(tra_date) from tab where tra_date like '%Sep%' GROUP by cut_id)
        ELSE 0
    END AS sept
    FROM tab
    GROUP by cut_id

but i found this error    #1242 - Subquery returns more than 1 row

A: In this section
 (select count(tra_date) from tab where tra_date like '%Oct%' GROUP by cut_id)

When you do a count with a group by, and there are multiple values for the thing you are grouping by, you get multiple values. Based on your requirements, you need to choose which single value you want.
Maybe you need to do this instead
 (select count(tra_date) from tab t1 where t1.tra_date like '%Oct%' and t1.cut_id = tab.cut_id)

A: I'm going to assume you have a sane schema that uses actual an actual datetime type for your transaction dates, rather than the apparent insane schema in the question that uses strings. Given that, your query would look like this:
SELECT
    cut_id,
    SUM(CASE WHEN month(tra_date) = 10 THEN 1 ELSE 0 END) AS Oct,
    SUM(CASE WHEN month(tra_date) = 9 THEN 1 ELSE 0 END) AS Sept
FROM tab
GROUP by cut_id


text:
Q: How to consume infinite stream in Kotlin? I want to write a program that will consume the infinite stream from the web. The stream will come in as JSON through web sockets. I'm looking for the data structured that I should use.
Requirements are:

*

*The stream will be infinite. I don't ever want to stop listening for the new data.

*The time between new events in the stream is unknown. They can come rapidly one after another, but also it's possible to have big pauses of several hours. I want to consume when there is something, and wait in the meantime.

*I want to consume events sequentally, one after another.

My component should only transform the consumed events, and forward them further. I tried with something like that:
fun consume(stream: Stream<WebEvent>): Sequence<TransformedEvent> {
    return try {
        stream.asSequence().let { seq ->
            var currentEvent = generator.firstEvent(seq.first())

            seq.map {
                currentEvent = generator.nextEvent(currentEvent, it)
                return@map currentEvent
            }
        }
    } catch (e: NoSuchElementException) {
        throw EmptyStreamException(e)
    }
}

The generator in this example "needs" the "previous" event to generate the new one, but that's part of the transformation logic. I'm interested in consuming the stream.
This worked. But I'm wondering is there a better way to do it in Kotlin. Maybe with a blocking queue, or something like that.


text:
Q: Java hashtable or hashmap? I've been researching to find a faster alternative to list. In an algorithm book, hashtable seems to be the fastest using separate chaining. Then I found that java has an implementation of hashtable and from what I read it seems to it uses separate chaining. However, there is the overhead of synchronization so the implementation of hashmap is suggested as a faster alternative to hashtable.
My queations are:

*

*Is java hashmap the fastest data structure implemented in java to
insert/delete/search?

*While reading, a few posts had concerns about the memory usage of
hashmap. One post mentioned that an empty hashmap occupy 300
bytes. Is hashtable more memory efficient than hasmap?

*Also, is the hash function in each the most efficient for
strings?

A: There is too much context missing to be able to answer the question which suggests to me that you should use the simplest option and not worry about performance until you have measured that you have a problem.

Is java hashmap the fastest data structure implemented in java to insert/delete/search?

ArrayList is significantly faster than HashMap depending on that you need it for.  I have seen people use Maps when they should have used objects.  In this case a custom class instance can be 10 faster and smaller.

While reading, a few posts had concerns about the memory usage of hashmap. One post mentioned that an empty hashmap occupy 300 bytes.

Unless you know that 300 bytes (which costs less than what you would be paid on minimum wage to blink) matters, I would assume it doesn't.

Is hashtable more memory efficient than hasmap?

It can be but not enough to matter.  Hashtable starts with a smaller size by default. If you make a HashMap with a smaller capacity it will be smaller.

Also, is the hash function in each the most efficient for strings?

In the general case it is efficient enough. In rare cases you may want to change the strategy eg to prevent denial of service attacks.  If you really care about memory efficiency and performance perhaps you shouldn't be using String in the first place.

A: HashMap (or, more likely, HashSet) is probably a good place to start, at your point.  It's not perfect, and it does consume more memory than e.g. a list, but it should be your default when you need fast add, remove, and contains operations.  The String.hashCode() implementation is not the best hash function, though it is fast, and good enough for most purposes.

A: As you've pointed Hashtable is fully synchronized so it depends on your environment. IF you have many threads then ConcurrentHashMap will be better solution. However you can look at Trove4J - maybe it will better suite your needs. Trove uses chaining hashing similar to hashtables

A: The access time of HashMap (& HashTable as well I believe) is O(1) since the internal bucket placement of the given value during put() is determined by computing (Hash of the value's key) % (Total Number of buckets). This O(1) is average access time, if however many keys hash to the same bucket then the access time will tend towards O(n) as all the values are placed into the same bucket grow and they all grow in linked list fashion.
As you said considering the overhead of synchronization inside Hashtable, I would probably opt for Hash map. Besides you can fine tune Hashmap by setting its various params like load factor that offers means of memory optimization. I vote for HashMap...

A: As others pointed out, a set would be a good replacement for a list but don't forget that lists allow duplicate elements, while sets do not, so while certain operations are faster, e.g., exists, sets and lists represent solutions to different problems.
As a start I recommend HashSet or TreeSet (in case ordering is important). A HashMap maps keys to values which is different. Refer to this discussion to understand the differences between the HashMap and Hashtable. I personally haven't used a Hashtable since 2007.
Finally, if you don't mind using a third party library, I highly recommend to take a look at the Guava immutable collections. Immutability automatically provides thread safety and easier to understand programs.
EDIT: Regarding efficiency concerns, this is a moot point. As a guideline, use the data structure (as in the abstract concept of a data structure) that best fits your problem and choose the vanilla implementation available. If you can prove you have a performance problem in you code, you might start thinking about using something 'more efficient'. That's in quote because it's a very loose definition: are we talking about memory efficiency, computing time efficiency, garbage collection efficiency, etc. Never forget the rules for code optimization.

A: 1.HashMap is only one of the fastest data structures implemented in java to insert/delete/search,HashSet is as fast as HashMap to insert/delete/search,and ArrayList is as fast as HashMap when insert a element to the end.
2.Hashtable is not more memory efficient than HashMap,they are all implemented by separate chaining.
3.Hash function of the two data structures are the same,but you can write a subclass extends them then override the hash function to make it most fit your application.


text:
Q: C program split input string into different variables separated with comma I have to write program that takes input from user in format Name, Surname, Number and store it into struct. I cannot use or work on arrays so i have to operate only on pointers.
My current code.
struct student_t* read(struct student_t* p, int *err_code){
    if(p == NULL){
        if(err_code != NULL) *err_code = 1;
        return NULL;
    }
    printf("Input data:");
    int result = scanf("%19[^,\n], %39[^,\n], %d[^\n]", p->name, p->surname, &p->index);

    if(err_code != NULL){
        if (result == 1){
            *err_code = 2;
            }else if (result == 2){
                *err_code = 3;
            }else if (result == 3){
                *err_code = 0;
            }else{
                *err_code = 1;
            }
    }
    if (result == 3){
        printf("%d\n",*err_code);
        return p;
    }else {
        return NULL;
    }

}

Currently it works ok for inputs like :

*

*Jane  - shows error

*Jane, Kowalski - shows error

*Jane, Kowalski, 244421 - no errors and passes.
But when i input something like  Jane,  - program hangs and waits for something and i want it to stop and return error code as well...
Error code mechanics :
0 - everything ok
1 - no pointer to struct or invalid input eg. no commas
2 - only name was taken succesfully
3 - name and surname only successfull
Any tips ?


text:
Q: Can I change the width of an EditorFor with data annotations? There's a few questions on similar topics. However, they don't actually address my issue.
DisplayFormat for TextBoxFor in MVC
Display a formatted date in an EditorFor()
ASP.NET MVC EditorFor DateTime
I've been searching and reading up and cannot find an answer to this.
I'm currently using this to format my input box:
@Html.TextBoxFor(modelItem => item.Quantity, new { style = "width: 30px;" })

From my model, I have the brief data annotation:
[Required, Range(1, 100)]
public int Quantity { get; set; }

So I get this:

When I use
@Html.EditorFor(modelItem => item.Quantity, new { style = "width: 30px;" })

I get this:

What I want is the scroll, but to format the width.
I'm wondering, is there a way to format the width of an EditorFor with data annotations? If not, what is the easiest way to make such a format, to avoid repetition.. bootstrap, css? I'm not happy with the inline styling.

A: From the comments, your using MVC-4. You cannot pass html attributes to the EditorFor() method unless your using MVC-5.1 or higher (refer the release notes - the section on Bootstrap support for editor templates)
One option is to use the TextBoxFor() method and pass type="number" to render the browsers numeric control
@Html.TextBoxFor(m => m.Quantity, new { type = "number ", style = "width: 30px;" })

Another would be to create a custom EditorTemplate (say _NumericControl.cshtml)
@model System.Int32
@Html.TextBoxFor(m => m, new { type = "number ", style = "width: 30px;" })

and call it using @Html.EditorFor(m => m.Quantity, "_NumericControl")
but this would really only be of any real benefit if the template were also to include other html elements, for example @Html.LabelFor(m => m) and @Html.ValidationMessageFor(m => m) and perhaps even the associated button so that the EditorFor() method renders all elements.


text:
Q: Tabula.py doesn´t print content as expected. Multiline cell is given I try to read a pdf with tabula.py read_pdf() method and pandas. Works fine, except for multiline textfields like given below:
Multiline textfield in PDF
I´m expecting the following output after writing df to list:
['Gewürzmischung Zaatar', 'Kartoffeln (Drillinge)']

But I´m getting:
['Gewürzmischung', 'Kartoffeln (Drillinge)', 'Zaatar']

I would appreciate any tips/workarounds on how to solve this problem.
My code looks like this:
#!/usr/bin/env python3

import tabula as tb
import pandas as pd
import sys

file = sys.argv[1]

zutatenliste = tb.read_pdf(file, area = (178, 621, 600, 788),encoding='utf-8', pages = '1')[0]
zutatenliste.fillna('', inplace=True)
zutatenliste2 = []

for i in zutatenliste.values.tolist():
    for j in i:
        if j == '':
            continue
        zutatenliste2.append(j)

print(zutatenliste2) # prints ['Gewürzmischung', 'Kartoffeln (Drillinge)', '"Za\'atar"']


text:
Q: Laravel .env variable always returns null I added this variable to .env file

STRIPE_SECRET=a12345

I would like to dump the variable using routes/web.php
<?php
dd(env('STRIPE_SECRET'));

But it looks like it always returns null.
Update : Updated .env file. I only removed DB_PASSWORD.
APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:08txDXXatyYsP5WQ4ECz35Q7OyBEe8Vgb/zK5fZsHik=
APP_DEBUG=true
APP_LOG_LEVEL=debug
APP_URL=http://localhost
APP_LOCALE=tr
APP_LC_ALL=tr_TR.utf8

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=gunluk
DB_USERNAME=root
DB_PASSWORD=

BROADCAST_DRIVER=log
CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

MAIL_DRIVER=smtp
MAIL_HOST=smtp.mailtrap.io
MAIL_PORT=2525
MAIL_USERNAME=03ac580c85842d
MAIL_PASSWORD=1d6d902d296942
MAIL_ENCRYPTION=null

PUSHER_APP_ID=
PUSHER_APP_KEY=
PUSHER_APP_SECRET=

STRIPE=a123
STRIPE_SECRET=a12345

A: You can clear configuration cache using following commands
php artisan config:clear
php artisan optimize
php artisan config:cache

Also make sure
If you are using the config:cache command during deployment, you must make sure that you are only calling the env function from within your configuration files, and not from anywhere else in your application.
If you are calling env from within your application, it is strongly recommended you add proper configuration values to your configuration files and call env from that location instead, allowing you to convert your env calls to config calls.
Reference link:
Update 1:
Also make sure you have renamed .env.example to .env file by default laravel have .env.example
Update 2
As per your new update question your env file have STRIPE not STRIPE_SECRET
so you have access like this if its not typo error in question
env('STRIPE')

A: The main reason upon your issue is that you are caching your configuration. When running php artisan config:cache you're storing your configuration in your cache, and the next time Laravel will boot up it won't read the .env file because it detects that the configuration has been stored in the cache. Environment file should be used only to setup configuration files and then to access the value you're looking for you should use ONLY the config method.
Let's assume that you have the file config/stripe.php that consists of this content:
<?php

return [
    'secret' => env('STRIPE_SECRET', '')
];

Once you run php artisan config:cache access this value using ONLY the syntax config('stripe.secret') through your application code. Every time you update your config files and your .env you need to run php artisan config:cache again.

A: First, there is no STRIPE_SECRET inside your .env file(As per before edit the question). So please make sure that your .env must have this variable. You should clear your configuration cache by executing following commands in the same order
php artisan config:cache
php artisan config:clear

Laravel cache your configuration files so the execution become faster. So everytime when you change the configuration files on server, you should clear the cache.
Additionally you can run these commands also to clear the other caches
php artisan cache:clear   //for clearing the cache
php artisan view:clear    //for clearing the compiled views
php artisan route:clear   //for clearing the routes cache

You can also create the routes for these commands and call the commands from the code also as
Route::get('/cache-clear', function() {
    $exitCode = Artisan::call('cache:clear');
    echo "Cache Cleard: ".$exitCode;
});

Route::get('/view-clear', function() {
    $exitCode = Artisan::call('view:clear');
    echo "View Cleard: ".$exitCode;
});

Route::get('/route-cache', function() {
    $exitCode = Artisan::call('route:cache');
    echo "Route Cached: ".$exitCode;
});

Route::get('/route-clear', function() {
    $exitCode = Artisan::call('route:clear');
    echo "Route Cache Cleared: ".$exitCode;
});

Route::get('/config-cache', function() {
    $exitCode = Artisan::call('config:cache');
    echo "Config Cached: ".$exitCode;
});

Route::get('/config-clear', function() {
    $exitCode = Artisan::call('config:clear');
    echo "Config Cache Cleared: ".$exitCode;
});

A: if you have
STRIPE="a12345" this in .env file or if you any change in .env file or config file then you fallow these steps
one more thing write the variable value in comma's like  STRIPE="a12345"
First run these commands
 1. php artisan config:clear
 2. php artisan cache:clear
 3. composer dump-autoload

and finally used this command to get variable
dd(env('STRIPE'));

this working for me
and  also 1 stupid suggestion: restart server
I have add all possible solution

A: make sure you app is completely booted.
if you are running server with cmd then try restarting server.
and if it not works try clearing the cache using the methods above mentioned by @iCoders.

A: env(...) function will return null after you cached the config. (starting from laravel 5.2 till current 5.7)
The documentation says

If you are using the config:cache command during deployment, you must make sure that you are only calling the env function from within your configuration files, and not from anywhere else in your application.

So the correct answer would be to

If you are calling env from within your application, it is strongly recommended you add proper configuration values to your configuration files and call env from that location instead, allowing you to convert your env calls to config calls.

And I quoted it from the same documentation
But for a quick fix this will do:

php artisan config:clear

A: I would not recommend using the env('STRIPE') command to get a variable. In a loop, this command starts returning null after some iteration. Therefore, it is better to create a configuration file and use the command "config('file_name.variable_name)":
<?php
return [
    'sprite_secret' => env('STRIPE_SECRET', '')
];

Run these commands first
php artisan config:cache
php artisan config:clear

And use this command to get the value of the STRIPE_SECRET variable:
config('config_file.sprite_secret)


text:
Q: Why is this macro copying multiple times? I found this macro and it does what I need it to do however whenever it's activated it seems to copy/paste the data multiple times.  My master list should only have 75 or so lines and when this runs it ends up at 268. Why is it doing that? Also, is there a way to edit it so if a sheet has no data in it after "A1" it doesn't copy that sheet?
Option Explicit

Private Sub Worksheet_Activate()

'Merge all sheets in a workbook into one summary sheet (stacked)
Dim cs As Worksheet, ws As Worksheet, LR As Long, NR As Long

Application.ScreenUpdating = False

Set cs = Sheets("Master List")
cs.Activate
Range("A2:F" & Rows.Count).ClearContents

For Each ws In Worksheets
    If ws.Name <> "Master List" Then
        NR = cs.Range("A" & Rows.Count).End(xlUp).Row + 1
        LR = ws.Range("A" & Rows.Count).End(xlUp).Row
        ws.Range("A2:F" & LR).copy cs.Range("A" & NR)
    End If
Next ws

Application.ScreenUpdating = True

End Sub

A: You have this in the Private Sub Worksheet_Activate() event of the workbook. If this is written into the "Master List" sheet's code, then activating the sheet as you do with line cs.activate will trigger the macro again... the one that is currently running. It's hard to say why this only creates 268 and not infinite, or double... it's tough to say and may be dependant on the speed at which excel works and it's single threadiness or some other deep down dark mystery of Excel and VBA.
Instead of
cs.activate
range("a2:f" & rows.count).clearcontents

try
cs.range("a2.f" & rows.count).clearcontents

If you find yourself writing .activate or .select in your vba code, you are probably doing something not-so-great.


text:
Q: Accessing a table cell object instead of img I'm trying to access the object behind the click in the console, it return the image instead, and I want to alter that object properties which makes it impossible, how do I access the object itself and not the image sitting on it?
For example if I type in the console gBoard[0][0] it return the image itself(aka TILE), I want to access the cell object that's behind it.
I would appreciate an explanation and a proper console log for it.
const TILE =''

function cellClicked(elCell, i, j) {
    // if (!gGameInterval) return;
    console.log('Click', i, j);
    // debugger
    if(gBoard[i][j].isBomb===true){
        gBoard[i][j].isFlagged=true
        elCell.innerHTML=TWO
    }
}

function printMat(mat, selector) {
    var strHTML = '

';
    for (var i = 0; i < mat.length; i++) {
        strHTML += '
';
        for (var j = 0; j < mat[0].length; j++) {
            var cell = mat[i][j]=TILE
            var className = `cell-${i}-${j}`
            strHTML +=
                `
                ${cell}
            	`
        }
        strHTML += '
'
    }
    strHTML += '

';
    var elContainer = document.querySelector(selector);
    elContainer.innerHTML = strHTML;
}

function createBoard(size) {
    var board = []
    for (var i = 0; i < size; i++) {
        board[i] = []
        for (var j = 0; j < size; j++) {
            board[i][j] = creatCell()
        }
    }
    return board
}

function creatCell() {
    return {
        isBomb: false,
        isFlagged: false,
        isClicked: false,
        isOpen: false
    }
}

A: In javascript objects, which includes arrays, are passed by reference when they are method parameters. This means if you change a property of the object in the method, it will change it in the original instance of the object
This is you problem line:
var cell = mat[i][j]=TILE

This overwrites the object stored at this position in the mat array.
Don't do this. I would have a tile property on the underling object and use that
instead. Change createCell to:
function creatCell() {
    return {
        isBomb: false,
        isFlagged: false,
        isClicked: false,
        isOpen: false,
        image: "/img/tile.png"
    }
}

Change printMap to the following to access the new property :
function printMat(mat, selector) {
    var strHTML = '

';
    for (var i = 0; i < mat.length; i++) {
        strHTML += '
';
        for (var j = 0; j < mat[0].length; j++) {
            var className = `cell-${i}-${j}`
            strHTML +=
                `

            	`
        }
        strHTML += '
'
    }
    strHTML += '

';
    var elContainer = document.querySelector(selector);
    elContainer.innerHTML = strHTML;
}

A: this will return the parent td node if a child node was clicked:
var l_target = $(e.target);
if(!l_target.is('td')){
  l_target = l_target.closest('td');
}


text:
Q: Symfony test get form errors If I have a functional test like:
public function testCreate()
{

    $client = $this->makeClient();
    $crawler = $client->request('POST', "/post/new");

    $form = $crawler->selectButton("Create Post")->form();
    $values = $form->getPhpValues();

    $values['post']['title'] = 'test';
    $values['post']['content'] = null; // Should fail because it isn't a string.

    $crawler = $client->request($form->getMethod(), $form->getUri(), $values,
        $form->getPhpFiles());
    assertEquals() // What goes here?
}

How do I use the crawler to get the form errors and compare them?

A: I see two possible solutions for you:

*

*Use the crawler to check for the actually rendered form errors in your rendered HTML code.

*Make use of the profiler and access the form data collector: http://symfony.com/doc/current/testing/profiling.html


text:
Q: How to set chrome for best webgl-three.js performance The same three.js example (buffer geometry lines) has 10 fps at Chrome and 20 at FF. Same with other examples.
How to set Chrome for best performance ? I have search on the web and I have applied all recomended settings
(I have w xp sp3 )
Thanks in advance.


text:
Q: Leaflet Marker not static on position I have notice that my leaflet markers are "not staying put" on a given lat/lon. When I zoom in on the map, the marker moves to adjust and take the correct position. When I zoom out, it goes to a different position. It'snot static on the position. How can I fix this ?
There is nothing special about my marker. below is how I built it
var LeafIcon = L.Icon.extend({
    options: {
        iconSize:     [12, 15],
        shadowSize:   [30, 40],
        iconAnchor:   [11, 70],
        shadowAnchor: [2, 42],
        popupAnchor:  [-3, -40]
    }
});

var map_icon = new LeafIcon({iconUrl: 'icon_marker.png'});
var marker;

marker = L.marker([my_lat, my_lon], {icon: map_icon});
    marker.addTo(map);
    marker.bindPopup("My markers' popup");

A: The symptom you describe is typical of incorrect iconAnchor setting.
It is strange that your iconAnchor is outside iconSize.
To make sure your settings are properly defined, you could add an extra marker with default icon at the same lat/lng coordinates, and see if your custom icon tip is at the same position.


text:
Q: Performance issue: Load data infile is making select query slow I have a program which scans twitter, facebook, google+ 24 hours a day. Per user a searchlist is running and inserted with (100 results at one time, function runs in a loop untill there are not futher results)
Yii::app()->db->createCommand(
     "LOAD DATA INFILE '/var/tmp/inboxli_user".$user.".txt'
      INTO TABLE inbox
      FIELDS TERMINATED BY ',$%'
      LINES STARTING BY 'thisisthebeginningxxx'
          (created_on, created_at, tweet, tweet_id, profile_image,
           twitter_user_id, screenname, followers, lang, tags, type,
           positive_score, readme, answered, deleted, searchlist_id,
           handled_by, used_as_newsitem,  user_id)
     "                       )->execute();

into the database in order to keep the load as small as possible on the server. How ever when my functions are doing the bulk insert, my select functions runs very slow. Normally the inbox loads within 1.5 second but when the insertion is running sometimes it takes like 20 seconds for a page to open.
My question how can i optimize this? So insertion and select can use the database at the same time without slowing things down?

A: *

*Get off MyISAM!  Use InnoDB; it does a much better job of not locking out other actions.

*Load data is very efficient, increase the count to, say, 500.

*What indexes do you have?  Let's see SHOW CREATE TABLE.  DROP any unnecessary indexes; this will speed up the LOAD.

*Consider turning off the Query cache.

A: Well, first you should make sure you indexed your table correctly. See How does database indexing work?
that will speed up the select statements pretty much.
Second, it's possible that you split your file into multiple chunks. So the database server removes the caches and logs for each new file you loaded.
See: https://www.percona.com/blog/2008/07/03/how-to-load-large-files-safely-into-innodb-with-load-data-infile/


text:
Q: Dataframe groupby and list of lists I've the following dataframe and I am trying to create the list of all 'values' for a given 'id'
import pandas as pd

df = pd.DataFrame({'id': [1, 1, 2, 2],
                   'month': [2, 2, 4, 6],
                   'value': [4, 5, 4, 3],
                   })

print (df)
print ("\n")

print (df.apply(lambda x: list([x['id'], x['month']
                        x['value']]), axis=1),)

The expected output is
1    [[2,4], [2, 5]]
2    [[4, 4], [6, 3]]

How can I do this?

A: You can use groupby + apply to get new Series object like this:
import pandas as pd

df = pd.DataFrame({'id': [1, 1, 2, 2],
                   'month': [2, 2, 4, 6],
                   'value': [4, 5, 4, 3],
                   })

res = df.groupby('id').apply(
    lambda group: [[group.month[i], group.value[i]] for i in range(len(group))])

Output:
id
1    [[2, 4], [2, 5]]
2    [[4, 4], [6, 3]]
dtype: object

Or you could use same groupby + apply combination to get similar Dataframe like this:
import pandas as pd

df = pd.DataFrame({'id': [1, 1, 2, 2],
                   'month': [2, 2, 4, 6],
                   'value': [4, 5, 4, 3],
                   })

res = df.groupby('id').apply(
    lambda group: pd.DataFrame(
        {'result': [[[group.month[i], group.value[i]] for i in range(len(group))]]}))
res.index = res.index.droplevel(1)


text:
Q: How to add coupon printer? Im building a directory site and for each business listing I wanted to include a printable coupon.
I would want users to be able to click the coupon image (or link) and a printable version of the coupon to show up.
I looked around for solutions but couldn't find anything that could help.
Any help would be appreciated. Thanks a lot.

A: You might be probably looking for a plugin that offer's groupon-like functionality ("Groupon 1.0 started on a WordPress blog.").
By googling I learned that there is a plugin called WP Coupon (Wordpress Plugin) (review). No idea if it fits in what you need, but it looks like it does what you're looking for.
But it's probably additionally worth to checkout if groupon and other similar fast growing sites do offer a webservice so that actually the job is already done:

*

*Groupon API

A: First figure out how you want your coupons displayed.
For simple printouts you can apply a css style-sheet for a printer friendly version, but I'm assuming you want a better coupon maybe with an actual bar code in it. In that case you want to have a pdf printer friendly coupon, since it the most popular format for printing these types of things.
There are several pdf plugins for WordPress that either turn a post into a pdf/embed a pdf into your page or simpley link to a pdf version of your coupon to download.

A: I used this plugin in a similar situation. It auto generats a printable version of your content and add a click-to-print link to it.


text:
Q: example of a flat but not faithfully flat ring extension I am learning commutative algebra and there is a definition about faithfully flat modules or ring extensions. I can't think of an example of a flat but not faithfully flat ring extension or module. Can someone help me with it? thanks

A: Take $f: A \rightarrow B$ to be a ring homomorphism such that the corresponding morphism of affine schemes $\operatorname{Spec}B \rightarrow \operatorname{Spec}A$ is not surjective, but only flat. There is an easy way to do this: Remember that localizing a ring $R$ in a multiplicative subset $S$ gives a flat ring homomorphism $R \rightarrow S^{-1}R$. However, this ring homomorphism is faithfully flat iff $S^{-1}R=R$.

A: $0$ is always flat, but not faithfully flat (unless the base is $0$).

A: A possibly instructive, concrete example is $\Bbb{Q}$ as an abelian group (i.e. as a $\Bbb{Z}$-module). Of course, this is just a special case of Dedalus's answer (and YACP's comment), but let's still prove the result directly.
Clearly $\Bbb{Q}$ is not a faithfully flat abelian group, e.g. the zero morphism
$$
\Bbb{Z}/2\Bbb{Z} \rightarrow 0
$$
is not injective, but after tensoring with $\Bbb{Q}$ this morphism is the identity on the zero  group (as $\Bbb{Z}/2\Bbb{Z} \otimes \Bbb{Q} \cong 0$).
On the other hand, $\Bbb{Q}$ is a flat abelian group. To see this, assume that
$$
f: A \hookrightarrow B
$$
is an injective morphism of abelian groups, and consider the induced morphism
$$
f \otimes id: A \otimes \Bbb{Q} \rightarrow B \otimes \Bbb{Q}
$$
Now for $b \in B$ the element $b \otimes 1 \in B \otimes \Bbb{Q}$ is equal to zero, if and only if $b$ is torsion. So the kernel of $f \otimes id$ consists precisely of the elements $f(a) \otimes id$, such that $f(a)$ is torsion. But injectivity of $f$ implies that $a$ must be torsion as well, i.e. $a \otimes 1=0$. This shows that $f \otimes id$ is injective, and therefore $\Bbb{Q}$ is a flat abelian group.


text:
Q: css included in JSP is not working across browser I have an issue where my CSS is not getting picked up in chrome and firefox but works well in IE8. I didn't check in higher versions of IE though.
below is the code where you can see Soo.css is included in the top and I'm trying to access the CSS for class="TableHeader" in the 2nd td in the table.
I can see the hyperlink for 'Home' in IE8 but not in chrome and firefox. But if I remove the clas="tableheader", I can see the hyperlink for "Home" in both the browser.
I don't see why it shouldn't work across browser. What is the right way to include. I have so many pages where it just works fine. below is the code snippet:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/abc.tld" prefix="abc" %>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>

<%@ page import="java.util.*" %>
<%@ page import="java.text.*" %>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="GENERATOR" content="IBM WebSphere Studio">

<meta http-equiv="Content-Style-Type" content="text/css">
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/theme/Soo.css"/>

<%
Locale locales = Locale.US;
SimpleDateFormat SFormatDate;
DateFormat CurrentYear;
CurrentYear = DateFormat.getDateInstance(DateFormat.LONG, locales);
Date today = new Date();
SFormatDate = new SimpleDateFormat("MM/dd/yyyy", locales);
CurrentYear = new SimpleDateFormat("yyyy ", locales);
String flag = "N";
%>

                <img src="<%=request.getContextPath()%>/images/p1_abc_logo.gif" width="157" height="25" border="0" alt="Click here to go to www.abc.">

            <img alt="Skip Repetitive Navigation Links" border="0" src="<%=request.getContextPath()%>/images/test_blank.gif">
            |
            <a href="<%=request.getContextPath()%>/../../../pol1/i2_chgrequest.cfm"
               style="color: black"
               target="system_feedback"
               title="Feedback">Feedback
            |
            <a href="<%=request.getContextPath()%>/../../../pol1/profile/index.cfm?fa=profile"
               title="Click for Personal Profile"
               style="color: black">Personal Profile
            |
            <a href="<%=request.getContextPath()%>/../../../pol1/logout.cfm"
               style="color: black"
               title="Logout">Logout
            |

    <img alt="Skip Repetitive Navigation Links" border="0" src="<%=request.getContextPath()%>/images/test_blank.gif">

            <a href="<%=request.getContextPath()%>/../../../pol1/viewer001/i3_menu.cfm?fa=account_menu&group=BMEU&toplevelpage=true"
               title="Message Center"
               style="text-decoration: none; color: white">Home


text:
Q: vertical-align in div nightmare! Any way to just get it to work without knowing div's vertical height? So I've been struggling on a rather weird problem. I've tried everything from display:inline-block on spans etc., with vertical-aligns set to center and wrapping within div's with display:table and the child div as table-cell, but NOTHING seems to have any effect on vertical alignment!
I've added the code on jsfiddle: http://jsfiddle.net/rtKra/6/ and if you hover over the li's you'll know what I mean if the li content is on a single line it should be centered with the color box on it's left. If it spans more than two lines, it doesn't seem to matter since the top of the li is aligned with the top of the context box and the bottom exceeds to color box so it looks fine
The troublesome part is the 'space' below the 'labelDescriptor' div - should be in line with the color box on the left. If it does come in line, the content still remains aligned to the top of the div!!
The issue is the hover's background - it should be the same height as the color box on its left. Setting min-height works without a table/table-cell display, but it still has a lot of space from the bottom of the content to the bottom of the div and looks a bit off.
Simple padding doesn't cut it. Although it works for the small li's (with less content) it looks off for the ones that split over to the next line!
I've been working at it for quite a while now and have almost given up!!! I just can't seem to get anything to work!
I made the div's content wrap in < p > tags but it adds way too much space (above and below) and makes the whole thing a total mess. I don't want to blow up the font size just for the sake of it either.
Any ideas? Can it be fixed using simple css or would javascript/jquery have to be used?
The code of the html+css would get a bit too long to post here. But if the need be I could do it...
**UPDATE: ** Here is the image description of what it should look like and what I have been able to do (the fiddle url for the one on the right is  http://jsfiddle.net/rtKra/9/)

I wish to replicate the 'look and feel' of gmail's label menu as on the left. See how well aligned the text is with the 'color box' (note I don't need a full hover over the color box too). The middle image shows how the alignments are off. Would the text get centered on a div with min-height:16px it would align well. But it is NOT happening and looks visually appalling. The image on the right is what you get after changing font size to 16px and making the color box's (red) width and height = 1em and moving it down by 3px (top:3px) - The question still is all this could have been avoided by just having the content vertically center in the div in the first place. Since irrespective of the "number of lines" in the bullet it would 'align well' without having to hack it around like I've done. Hope that clarifies what I want to do :)

A: I think you want something like this. Edit the font size to see the working.
The key properties are:
.category {
    position: relative;
}
.category .labelColorPicker {
    width: 16px;
    height: 16px;
    border: 1px solid black;
    vertical-align: top;
    padding: 0;
    margin: 0;
}
.category .labelDescriptor {
    border: 1px solid transparent;
    display: inline-block;
    vertical-align: middle;
    line-height: 16px;
    min-height: 16px;
}
.category .hoverMenu {
    position: absolute;
    left: 100%;
    top: 0;
}

Tested on Win7 in IE8, IE9, Opera 11.50, Safari 5.0.5, FF 5.0, Chrome 12.0. I added two IE7 patch lines to the CSS, because inline-block does not work fully in IE7.

A: you have to set the container to be display: table-cell and the apply vertical-align: middle to that
check the div containing the text on the left
this also drove me frikkin insane


text:
Q: Why I have the error "store address not aligned on word boundary" I have a problem with my MIPS code... I would check the occurrences in a string passed by keyboard without a character to compare. I have the string in the stack (stack -255 position) and an array in the .data section to store the occurrences. The basic idea is that I load a letter from the stack one-by-one with a loop (lb $t1, ($a0) t1= ascii code of the letter - a0= stack passed at the function), subtract the letters read from the stack with 97 (97=a) and obtain the index of the array and with another loop, count the occurrences and save this under the index calculated before. Obviously, the array has 104 position (26 letters * 4 because I would save the number of occurrences). The problem is that when I find the index of my array position and I would save inside the position the occurrences with sw $--, myArray($--) Mars give me this error:
Runtime exception at 0x0040007c: store address not aligned on word boundary 0x10010087
I have tried to add .align in the .data section but I haven't find solution, maybe I wrong some things... Any help?
This is my code:
analizza_stringa: (function)

while_string:

# load a byte from the stack
lb $t0, ($a0)

#check end string
beq $t0, $zero, end

#check a line feed
beq $t0, 10, end

    #array index
    subi $t3, $t0, 97

    #Multiply by 4 (I would save number)
    mul $t4, $t3, 4

    while_occorrenza:
         #like before
         beq $t1, 10, continue

         #load a letter like before
         lb $t1,($a0)

         #Check the occurrences
         bne $t1, $t0, continue2

         #add 1 at the occurrences
         addi $t5, $t5, 1

         continue2:

         #add 1 for the pointer at the string
         addi $a0, $a0, 1

         #Repeat
         j while_occorrenza

    continue:

    #Save the number under the index calculated before
    sw $t5, myArray($t4)

    #counter=0 for another loop
    li $t3, 0

#next character
addi $a0, $a0, 1

# repeat the first loop
j while_string

end:
jr $ra

A: If you want to access a word in memory, the address must be word-aligned (a multiple of 4).
Assuming that $t4 contains a multiple of 4, which it appears to do, that means myArray isn't word-aligned. To fix this you would add .align 2 on the line before myArray in your data section.


text:
Q: How to run a set of functions over given list of variable names and write the output to a table? What I'm seeking to do is run a mean/standard deviation calculation, as well as a statistical test, along a set of variables. What seems right to do is build the function such that one can pass the list of column names through the function.
One possibly complicating factor is that for this specific data frame, it requires certain functions relating to survey data.
library(radiant.data) #for weighted.sd
library(survey) #survey functions
library(srvyr) #survey functions

#building a df
df <- data.frame("GroupingFactor" = c(1, 1, 0, 0),
                 "VarofInterest1" = c(1, 1, 1, 0),
                 "VarofInterest2" = c(1, 0, 0, 0),
                 "PSU" = c(1, 2, 1, 2),
                 "SAMPWEIGHT" = c(0, 23254, 343, 5652),
                 "STRATA" = c(6133, 6131, 6145, 6152))

options(survey.adjust.domain.lonely=TRUE) #adjusting for the one PSU
options(survey.lonely.psu="adjust")

svy <- svydesign(~PSU, weights = ~SAMPWEIGHT, strata = ~STRATA, data = df, nest = TRUE, check.strata = FALSE) #the design

#here is what i would like to iterate

df %>%
  group_by(GroupingFactor) %>%
  summarise(mean = weighted.mean(VarofInterest1, SAMPWEIGHT, na.rm =T), sd = weighted.sd(VarofInterest1, SAMPWEIGHT, na.rm =T)) #for mean and SD

svychisq(~GroupingFactor+VarofInterest1, svy, statistic = 'Chisq') #the test of interest

Everything AFTER creating the svy object is what I'd ideally automate across a list of variables, e.g., applied to a list including VarofInterest2, a VarofInterest3, and so on.
The final product is a table/tibble including all the variable names, each one's mean and standard deviation and the output of the Chi-squared test (e.g., test statistic/X-squared and p-value).
I would also take a reference for doing this on non-survey weighted data! (i.e., just running, say, a dozen t-tests using a similar premise of feeding a list of variables you'd like to run the t-test against with a grouping factor).
Edit: Intended output

GroupingFactor
Mean
SD
Statistic
p
Variable

0
.25
.25
341.14
.014
VarofInterest1

1
.50
.00
N/A
N/A
VarofInterest1

OR separate functions/table generating functions, one of just the means/SDs:

GroupingFactor
Mean
SD
Variable

0
.50
.25
VarofInterest1

1
.25
.00
VarofInterest1

and then a second with the test statistic and p-values:

Variable
Statistic
p

VarofInterest1
4131.11
.001

VarofInterest2
131.14
.131

A: You can write a function f() that takes the data, the group variable, and the variable of interest, and return the statistics.. You would need to modify the below example for survey data, but this might give you starting point.
f <- function(df, g, v) {

  v_string = quo_name(enquo(v))
  g_string = quo_name(enquo(v))

  chi_result = chisq.test(df[[v_string]], df[[g_string]])

   df %>%
    group_by({{g}}) %>%
    summarize(Mean = mean({{v}}, na.rm=T),SD = sd({{v}}, na.rm=T)) %>%
    mutate(variable=v_string,
           statistic=chi_result$statistic,
           pvalue=chi_result$p.value)
}

bind_rows(
  lapply(c("VarofInterest1", "VarofInterest2"),\(i) f(df,GroupingFactor,!!sym(i)))
)

Output:
# A tibble: 4 × 6
  GroupingFactor  Mean    SD variable       statistic pvalue
           <dbl> <dbl> <dbl> <chr>              <dbl>  <dbl>
1              0   0.5 0.707 VarofInterest1     0.444  0.505
2              1   1   0     VarofInterest1     0.444  0.505
3              0   0   0     VarofInterest2     0.444  0.505
4              1   0.5 0.707 VarofInterest2     0.444  0.505


text:
Q: How to parse nested JSON with aeson I am trying to parse JSON of the following form using aeson
{"field":{"name":"..."}}

or

{"tag":{"name":"..."}}

or

{"line":{"number":"..."}}

to construct the following data type
data Rule = Line Integer
          | Field L.ByteString
          | Tag L.ByteString

Unfortunately, I face two problems that I've not found solutions to, namely:

*

*How do I parse nested JSON? Looking at the implementation of (.:), it uses lookup to extract a specific key's value. I'm hesitant to do something like this as it seems to be relying too much on the specifics of how aeson implements things. Am I wrong in thinking this is an issue?

*How do I use the correct data constructor based on which key is present in the JSON? All my efforts with <|> have led me nowhere.
I would post the code I've written thus far, but I haven't even gotten to the point where I have anything worth posting.

A: How about the following?
{-# LANGUAGE OverloadedStrings #-}

import Control.Applicative
import           Data.Aeson
import           Data.Aeson.Types
import qualified Data.ByteString      as B
import qualified Data.ByteString.Lazy as L
import qualified Data.Map             as M

data Rule = Line Integer
          | Field L.ByteString
          | Tag L.ByteString
          deriving Show

instance FromJSON Rule where
  parseJSON j = do
    o <- parseJSON j -- takes care of JSON type check
    case M.toList (o :: Object) of
      [("field", Object o')] -> Field <$> o' .: "name"
      [("tag",   Object o')] -> Tag   <$> o' .: "name"
      [("line",  Object o')] -> Line  <$> o' .: "number"
      _                      -> fail "Rule: unexpected format"

A: For this problem I created a helper function that looks up a key:
lookupE :: Value -> Text -> Either String Value
lookupE (Object obj) key = case H.lookup key obj of
        Nothing -> Left $ "key " ++ show key ++ " not present"
        Just v  -> Right v
loopkupE _ _             = Left $ "not an object"

and using it two functions that nest into objects:
(.:*) :: (FromJSON a) => Value -> [Text] -> Parser a
(.:*) value = parseJSON <=< foldM ((either fail return .) . lookupE) value

(.:?*) :: (FromJSON a) => Value -> [Text] -> Parser (Maybe a)
(.:?*) value = either (\_ -> return Nothing) (liftM Just . parseJSON)
                . foldM lookupE value
-- Or more simply using Control.Alternative.optional
-- (.:?*) value keys = optional $ value .:* keys

Only lookupE depends on the internal representation so it's easy to modify it, if that changes. Then {"tag":{"name":"..."}} is parsed as v .:* ["tag", "name"]. Note that it also works for empty lists - v .:* [] is equivalent to parseJSON v.


text:
Q: Maintain Android activity Stack with notifications I'm developing a simple chat application with more than 8 activities. But my main problem is with two activities of my application. Think on whatsapp, it has a Main Activity (contact list) and chat activity, and always, whatsapp application maintains stack state starting application from application list or long pressing HOME. Also if application starts from notification, never appear duplicated activities in the stack. I would like to copy this behaviour in my application but I have tried all the possibilities and always is a case where an activity isn't destroyed, duplicate activities on the stack, all those problems trying to maintain stack state when going back to app.
Anyone knows how to implement it?

*

*Activity A-> Contact List

*Activity B-> Chat Activity

What are the parameters in the manifest for each activity?
And for the intent notification? I want notification launch activity B and pressing back button to go to activity A.

A: I'm not exactly sure what you're looking for, but here are two things that may help:

*

*android:noHistory: set this attribute to true in the manifest for activities that are supposed to leave no trace in the activity stack. So if you're going ActivityA --> ActivityB (noHistory=true) --> ActivityC, and the user presses the back button, then you go back to ActivityA, because ActivityB is already unloaded.

*Activity.finish(): the activity that this is called on quits itself. The usual callbacks (onStop(), onDestroy()) are called. If you want to prevent duplicate activities, it may help to call this in the onPause() of the activity you don't want duplicated.

If those aren't enough, then there are a lot more details in the 'back stack' documentation:
https://developer.android.com/guide/topics/fundamentals/tasks-and-back-stack.html


text:
Q: I found a way to beat my simple dice game with dice 6 sides and option to select 3 sides to win This problem was probably addressed but I am not sure how to correctly find the problem here or find a solution. I am not mathematician so I apologise if it's not described properly.
I wrote I simple dice game in c# console with algorithm randomNumber = Math.floor(Math.random() * 6 + 1); to generate random number from 1 to 6.
The game allows you to pick 3 out of 6 sides for your bet. I found a way to beat the game with potentially having 60% edge versus game on majority of cases.
My strategy is simple, I filter out the winner side of previous attempt for next roll.
An example of my 10 attempts in a row from last session:

*

*1, 2, 3 (winner 3 - WIN - since winner was 3 i exclude it from next roll, which theoretically gives me 3 divided 5 = 60% chance for next win, if I count that same side won't hit twice in a row

*1, 2, 4 (winner 2 - WIN)

*1, 4, 5 (winner 5 - WIN)

*1, 2, 3 (winner 4 - LOSS)

*1, 2, 3 (winner 1 - WIN - i reroll here the same as I assume same die wont happen twice in a row)

*2, 3, 5 (winner 1 - LOSS - let's assume same side does happen sometimes, but that's very rare, which on majority throws gives me 60% edge vs house)

*2, 3, 5 (winner 6 - LOSS)

*2, 3, 5 (winner 3 - WIN)

*2, 4, 5 (winner 2 - WIN - see how i also didn't pick 3,6 as last 2 results)

*1, 4, 5 (winner 5 - WIN)

Is this normal? Is this like counting cards in blackjack or something? Is there a way to fix this for instance add another dice to decrease the chance of counting?


text:
Q: Temporal Logic Tautology I have the following question:

if it is necessary that p -> p = tautology?

I think it's not, and I am showing my example for the contradiction, below:

And I'll explain:
For every "universe" which is reachable for S1, p is true (hence םp).
For a universe that isn't reachable for S1, p is false (and therefore, this is not a tautology).
But are my observations correct?
Thanks,
Alan

A: Your observation is not correct.   $\Box p \to p$ does not say "if $p$ is true in all accessible worlds it is true in all worlds (even the inaccessible ones)"
It just says "if $p$ is true in all worlds accessible from this one, then it is true in this world;" for an given world of interest.  Which is true if and only the world of interest is accessible to itself.

Still the point remains that necessity and possibility are relative concepts.
By definition, a predicate is necessarily true if and only if the predicate is true in all accessible worlds.   This is always evaluated relative to some world of interest.  When the world is omitted, we're usually interested in the "actual world" by default.
So $w \vDash \Box p\to p \;$ says, if predicate $p$ is true in all worlds accessible to world $w$ then $p$ is true in world $w$.
However, this is not a tautology; it is the Axiom of Reflexivity.   It only holds in models where the accessibility relation is reflexive.   (Ie: When every world in the frame can access itself.)


text:
Q: android fetching json outside of MainThread I need to fetch some data from an external source (a json-source).
The external source is a simple http-response..
The data is supposed to replace some text to be able to localize my app using a CMS.
The I tried running the request inthe mainthread, but for what I understand thats not the way to go.. since its required to run in another thread or async..
The thing I dont get is..
If I refactor my code and make it run in a seperate thread or a asynctask, then isnt it possible for the app to execute all code, display something for the user with out actually have executed and finished the other thread?..
Cause I guess I need to lock the mainthread some where anyway to make sure that the localized textes are displayed.. or am I getting this wrong?


text:
Q: Rolling Window on Dataframe, mutliple columns input and output I have a function myfunc, which does calculations on two pandas DataFrame columns. Output is a Numpy array.
def myfunc(df, args):
    import numpy
    return numpy.array([df.iloc[:,args[0]].sum,df.iloc[:,args[1]].sum])

This function is called within rolling_df_apply:
def rolling_df_apply(df, myfunc, window, *args):
    import pandas
    result = pandas.concat(pandas.DataFrame(myfunc(df.iloc[i:window+i],args), index=[df.index[i+window-1]]) for i in xrange(0,len(df)-window+1))
    return result

Running this via
import numpy
import pandas
df=pandas.DataFrame(numpy.random.randint(5,size=(5,2)))
window=3
args = [0,1]
result = rolling_df_apply(df, myfunc, window, *args)

gives ValueError within pandas.concat(): Shape of passed values is (1, 2), indices imply (1, 1).
What must be changed to get this running?
Which indices imply shape 1,1? Shape of all dataframes to concatenate should be 1,2, though.

A: *

*In myfunc, .sum should be .sum() in myfunc.

*Since myfunc returns an array of length 2,
pandas.DataFrame(myfunc(df.iloc[i:window+i],args), index=[df.index[i+window-1]])

is essentially the same as
pd.DataFrame([0,1], index=[0])

which raises
ValueError: Shape of passed values is (1, 2), indices imply (1, 1)

The error is saying that the value [0,1] implies 1 row and 2 columns,
while the index implies 1 row and 1 column.
On way to fix this would be to pass a dict instead of a list:
In [191]: pd.DataFrame({'a':0,'b':1}, index=[0])
Out[191]:
   a  b
0  0  1

So, to fix your code with minimal changes,
import pandas as pd
import numpy as np

def myfunc(df, args):
    return {'a':df.iloc[:,args[0]].sum(), 'b':df.iloc[:,args[1]].sum()}

def rolling_df_apply(df, myfunc, window, *args):

    frames = [pd.DataFrame(myfunc(df.iloc[i:window+i],args),
                           index=[df.index[i+window-1]])
              for i in xrange(0,len(df)-window+1)]
    result = pd.concat(frames)
    return result

np.random.seed(2015)
df = pd.DataFrame(np.random.randint(5,size=(5,2)))
window=3
args = [0,1]

result = rolling_df_apply(df, myfunc, window, *args)
print(result)

yields
   a  b
2  7  6
3  7  5
4  3  3

However, it would be much more efficient to replace myfunc and rolling_df_apply with a call to pd.rolling_sum:
result = pd.rolling_sum(df, window=3).dropna(axis=0)

yields the same result.


text:
Q: How to hide image if screen size is less than 480px (iPhone 4)? I have a popup image that shows up on our homepage, But i want to hide it if a viewer is visiting our website from a mobile device (such as an iPhone 4), simply because the image is to big for the phone, without having to zoom out. Here is my code:
<div class="gamedayad">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script src="http://www.jacklmoore.com/colorbox/jquery.colorbox.js"></script>

    <script>
      function openColorBox(){
        $.colorbox({href: "image url"});
      }

      function countDown(){
        seconds--
        $("#seconds").text(seconds);
        if (seconds === 0){
          openColorBox();
          clearInterval(i);
        }
      }

      var seconds = 5,
          i = setInterval(countDown, 0);
    </script>
</div>

and the CSS i have (idk if it is correct) is:
@media screen and (max-width: 480px) {
    .gamedayad {
        display: hidden !important;
    }
}

Please help? Thanks!

A: Have you tried
@media screen and (max-width: 480px) {
    .gamedayad {
        display: none;
    }
}

A: display: hidden; doesn't exist, it must be display: none;
Your media query is correct, just the wrong property value is all :)

A: I think you are confusing the property "display" and the value "hidden". Try display: none;:
.gamedayad {
   display: none !important;
}

A: The correct CSS markup is:
display: none !important;

However bear in mind you are still downloading the image in a mobile device, and hiding it. The best approach would be to only download the image if you can display it. A simple check to the window width in your script would do the trick.
var windowWidth = $(window).width();

if (windowWidth > 480) {
    //download your image here
}

A: Ok, so i think what my problem was that I didn't have this script at the top of the page, it was posted at the bottom (under other scripts). I did however put in the:
var windowWidth = $(window).width();

if (windowWidth > 480) {
    //download your image here
}

posted by denisol, and:
@media screen and (max-width: 480px) {
    .gamedayad {
        display: none;
    }
}

Thanks to everyone for the help!!


text:
Q: Reflection and checking for existance of method I have two variables, ns and method storing the namespace and a method name for working with an api. I have an api library, where once you have an instance, you access the methods as api.namespace.method()
How do I go about checking for the existance of namespace and method with the api object from the variables? At the moment I'm switching over the variables but of course, this doesn't scale too well!


text:
Q: Which word sounds better, "room" or "space"? Q1: If I have lots of things to do and think about and can't do or think anything else, can I say:

I have no room for other things in my mind.

or is it better to use the following?

I have no space for other things.

I don't know whether this sounds all right, but I'd like to know the appropriate response in this situation. Or if there's another way of saying it, please let me know.

Q2: Also, if someone asks me to do something, is it all right to say this?

I have no room for that right now.

or is it better to say the following?

I have no space for that right now.

A: Answer to Q1: You can say I have no {time / energy [CHOOSE ONE]} to do or think about other things right now. It's perfectly reasonable English.
To use only I have no {room / space [CHOOSE ONE]}", the rest of the sentence has to be restricted "to think about other things right now".
Answer to Q2: You can say I have no {time / energy [CHOOSE ONE]} {for / to do  [CHOOSE ONE]} that right now. Using room or space is semantically incorrect.

A:
I have no room for other things in my mind.
  I have no space for other things.

Both of these are figurative speech, and they are acceptable as is. One might add the word extra or spare as well:

There's no spare room for anything else in my mind.
  I have no extra space for new things in my brain right now.

(I decide to change the way you said other things, because it's hard to figure out what "things" are in your mind already, and what other things you don't have any room for.)
But, yes, you can use words like space when talking about the brain for the mind. In fact, the word attic is sometimes used to refer to the mind metaphorically, because it's in the upper part of our body, and it's used to store things. Doyle used this analogy in 1887, in a Sherlock Holmes story:

"I consider that a man's brain originally is like a little empty attic, and you have to stock it with such furniture as you choose." (Sherlock Holmes, A Study in Scarlet)

As you guessed, words like space and room can also be used for a schedule, as well as a brain:

I'm sorry, I'm too busy; I don't have room to meet this week. Can we try for next week? I have more free space on my calendar then.

In addition to brains and calendars, you could also use such words to describe, say, a person's frustration level. For example:

My car won't start! Dammit! I don't have room for this right now.

might mean that the speaker is under a lot of stress, and this isn't a good time for his car to break down. Here's another example from a book:

As much as I don't have room for this in my life right now, I can't help but be intrigued. "What kind of plan?" I ask. (N.L. Shepherd, Stealing Bases)


text:
Q: Single Sign on with Apache Shiro and Tomcat I have two separate maven modules: One of them is a rest application, and the other a web app.
They run on the same tomcat 7 server, deployed as different wars, and use Shiro for authentication and authorization.
Since the web application needs to make ajax calls to the rest services, I thought it would be nice to add this SSO thing to both applications. So as suggested by this answer, I made the necessary changes to the modules, hoping it would be an easy task, but it wasn't to me. I can authenticate in each application separately, but cannot manage to make them share the session info. Every time I log in the web app and try to access a rest service, I'm redirected to the rest service login page, and vice-versa.
Here is the shiro.ini content for the web app:
[main]

credentialsMatcher = org.apache.shiro.authc.credential.HashedCredentialsMatcher
credentialsMatcher.hashAlgorithmName = SHA-256

dataSource = com.mysql.jdbc.jdbc2.optional.MysqlDataSource
dataSource.user = ****
dataSource.password = ****
dataSource.port = ****
dataSource.url = jdbc:mysql://localhost:****/****
dataSource.databaseName = ****

jdbcRealm = com.camacua.shiro.realm.SaltAwareJdbcRealm
jdbcRealm.credentialsMatcher = $credentialsMatcher
jdbcRealm.dataSource = $dataSource
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.saltStyle = COLUMN
jdbcRealm.saltedAuthenticationQuery = select password, password_salt, userId from AccountInfo where username = ?
jdbcRealm.userRolesQuery = select role_name from AccountInfo_Role where accountInfo_username = ?
jdbcRealm.permissionsQuery = select permission_name from Role_Permission where role_name = ?
securityManager.realm = $jdbcRealm

sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
sessionManager.sessionDAO = $sessionDAO
cookie = org.apache.shiro.web.servlet.SimpleCookie
cookie.name = SSOcookie
cookie.path = /
cookie.domain = localhost
sessionManager.sessionIdCookie = $cookie
securityManager.sessionManager = $sessionManager

cacheManager = org.apache.shiro.cache.ehcache.EhCacheManager
cacheManager.cacheManagerConfigFile = classpath:ehcache.xml
securityManager.cacheManager = $cacheManager

securityManager.sessionMode = native

#Para testing:
ssl.enabled=false

shiro.loginUrl = /login.jsp

[urls]
/css/**=anon
/img/**=anon
/logout = logout
/** = ssl,authc

And the shiro.ini file for the rest app:
[main]
credentialsMatcher = org.apache.shiro.authc.credential.HashedCredentialsMatcher
credentialsMatcher.hashAlgorithmName = SHA-256

dataSource = com.mysql.jdbc.jdbc2.optional.MysqlDataSource
dataSource.user = ****
dataSource.password = ****
dataSource.port = ****
dataSource.url = jdbc:mysql://localhost:****/****
dataSource.databaseName = ****

jdbcRealm = com.camacua.shiro.realm.SaltAwareJdbcRealm
jdbcRealm.credentialsMatcher = $credentialsMatcher
jdbcRealm.dataSource = $dataSource
jdbcRealm.permissionsLookupEnabled = true
jdbcRealm.saltStyle = COLUMN
jdbcRealm.saltedAuthenticationQuery = select password, password_salt, userId from AccountInfo where username = ?
jdbcRealm.userRolesQuery = select role_name from AccountInfo_Role where accountInfo_username = ?
jdbcRealm.permissionsQuery = select permission_name from Role_Permission where role_name = ?
securityManager.realm = $jdbcRealm

sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
sessionManager.sessionDAO = $sessionDAO
cookie = org.apache.shiro.web.servlet.SimpleCookie
cookie.name = SSOcookie
cookie.path = /
cookie.domain = localhost
sessionManager.sessionIdCookie = $cookie
securityManager.sessionManager = $sessionManager

cacheManager = org.apache.shiro.cache.ehcache.EhCacheManager
cacheManager.cacheManagerConfigFile = classpath:ehcache.xml
securityManager.cacheManager = $cacheManager

securityManager.sessionMode = native

#ssl.enabled=false

authc.loginUrl = /login

[urls]
/test/** = anon
/** = authc

The ehcache.xml file contains exactly what the stormpath site suggests in both projects:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd" updateCheck="true"
         monitoring="autodetect" dynamicConfig="true">

    <diskStore path="java.io.tmpdir" />

    <cacheManagerPeerProviderFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
            properties="peerDiscovery=automatic,
                        multicastGroupAddress=230.0.0.1,
                        multicastGroupPort=4446, timeToLive=1"
            propertySeparator="," />

    <cacheManagerPeerListenerFactory
            class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory" />

    <cache name="shiro-activeSessionCache" maxElementsInMemory="600"
           eternal="true" overflowToDisk="true" memoryStoreEvictionPolicy="LFU">
        <cacheEventListenerFactory
                class="net.sf.ehcache.distribution.RMICacheReplicatorFactory" />
    </cache>

    <defaultCache maxElementsInMemory="100" eternal="true"
                  overflowToDisk="true" memoryStoreEvictionPolicy="LFU">
    </defaultCache>
</ehcache>

As you can see, I'm using a custom realm, but I'm pretty sure it's working properly, since the authentication part is not giving me problems at all. any suggestion on what I'm doing wrong? Thanks in advance.
UPDATE: I just copied the web project and renamed it. Running the two web twin applications has the same effect.

A: The problem was related with the jsp pages I created. I declared variables in them with session scope. That somehow was overriding the session cookie, and losing the session id.


text:
Q: Trying to understand exceptional divisors and Du Val singularities. I'v been trying to understand how Du Val singularities are resolved and what the exceptional divisors look like so I can work out their dynkin diagrams. A basic example I tried in the interest of getting some intuition was $z^2+y(x+y^2)=0$. First blow it up with coordinates $[x_0:y_0:z_0]$ and let $x_0=1$ so $y=xy_0$ , $z=xz_0$ to so we should get one of the affine charts $(xz_0)^2+xy_0(x+(xy_0)^2)=0$,
$\implies x^2(z_0^2+y_0+xy_0^3)=0$
My understanding is that the the exceptional divisor is set of points which are mapped to by $(0,0,0)$ during the blow up, so were looking for solutions of $x^2(z_0^2+y_0+xy_0^3)=0$ where $x=y=z=0$, but wouldn't that just be the plane $(0,y_0,z_0)$? At this point I'm not sure how to proceed as I don't know if this is actually the correct exceptional divisor.
If anyone could give a general explication of how to find exceptional divisors or show how to fully resolve this example and find all exceptional divisors and how they intersect that would be great.
Thanks.


text:
Q: variance unexplained for binary classifier I found in Wikipedia the definition of fraction of variance unexplained in the case of a regressor. Is there a meaningful definition of variance unexplained for a classifier?

A: In case of a 0-1 coded binary outcome, squared error loss on predicted probabilities (a.k.a. Brier score) is most similar to $\mathrm{VAR}_\mathrm{err}$. The variance of a single-trial binomial variable seems most similar to $\mathrm{VAR}_{\mathrm{tot}}$.
Then
$1 - R^2 = \frac{\mathrm{VAR}_{\mathrm{err}}}{\mathrm{VAR}_{\mathrm{tot}}} = \frac{\frac{1}{n}\sum_i (\hat{p}_i - y_i)^2}{\bar{y} (1-\bar{y})}$
where $n$ is the number of observations the measure of fit was computed on, $\hat{p}_i$ is the model-predicted probability of being in class 1 (versus 0) for observation $i$ and $\bar{y}$ is the baserate, or proportion of observations in class 1.
The $R^2$ thus computed is referred to as Efron's pseudo R-squared. Wikipedia provides some alternative measures, that are not computed based on squared error loss, but on binomial deviance, for example.

A: That Wikipedia article is only correct in the case of OLS linear regression. If you estimate the parameters of a linear model another way, such as with regularization, or if you have a nonlinear regression, that interpretation of $R^2$ breaks down.
Interestingly, if you use a linear probability model that you fit via OLS, $R^2$ has the usual interpretation. Linear probability models have their issues, but they do exist, and people do use them in "classification" problems.
In general, however, nonlinear regression models like logistic regressions and neural networks lack the usual interpretation of $R^2$ as the fraction or proportion of variance explained.


text:
Q: Image Path Space Issue - Php Array I don't know where the issue in my code.
There is a space automatically added to the image name after i get the value from array.
i have tried with str_replace too. but that space still shows in output.
here it is my code
<?php
$domain='localhost/test';

$id=5;

$animal = array("alligator.jpg", "
ant.jpg", "
bear.jpg", "
bee.jpg", "
butterfly.jpg", "
cat.jpg", "
camel.jpg", "
cheetah.jpg", "
cockroach.jpg", "
cow.jpg", "
crow.jpg", "
deer.jpg");

$imageName=$animal[$id];
$imageName2=str_replace(" ","",$imageName);

echo "$domain/img/$imageName";
echo "

$domain/img/$imageName2";

?>

current output: localhost/test/img/ cat.jpg  -> space added before the cat name
expected output: localhost/test/img/cat.jpg

A: $imageName2=trim($imageName);
use this
or
$imageName2= preg_replace('/\s+/', '', $imageName);


text:
Q: WPF bind collection of collections to a listview and group on parent collection object property I cannot get the databinding to work properly for the following scenario:
Model - a collection of DetailEntries, along with some collective properties form a DailyDetailSet:
[AddINotifyPropertyChangedInterface]
public class DailyDetailsSet
{
    public DailyDetailsSet(DateTime startDate, ObservableCollection<DailyDetailEntry> entries)
    {
        this.StartDate = startDate;
        this.Entries = entries;
    }

    public DateTime StartDate { get; }

    public decimal TotalHours => this.Entries.Sum(x => x.TotalHours);
    public string TotalHoursFormatted => this.TotalHours.ToFormattedDurationString();

    public ObservableCollection<DailyDetailEntry> Entries { get;  }

    public DetailsGroupingHeader DetailsGroupingHeader => new DetailsGroupingHeader(this.StartDate, this.TotalHours);

}

[AddINotifyPropertyChangedInterface]
public class DailyDetailEntry
{
    //some properties
}

public class DetailsGroupingHeader
{
    //Some text and color properties and overriden Equals() method to allow grouping
}

ViewModel - a collection of DailyDetailsSet is retrieved from database:
    [AddINotifyPropertyChangedInterface]
    public class EntryListViewModel : ViewModelBase
       {
         public ObservableCollection<DailyDetailsSet> EntrySets { get; set; }
       }
    }

A view should contain a Listbox, which should contain all the DailyDetailEntries, grouped into groups for each day, based on the DetailsGroupingHeader (it compares the entry date really)
View:
<UserControl.Resources>
            <CollectionViewSource x:Key="Sets" Source="{Binding Path=EntrySets}">
                <CollectionViewSource.GroupDescriptions>
                <PropertyGroupDescription PropertyName="DetailsGroupingHeader" />
                </CollectionViewSource.GroupDescriptions>
            </CollectionViewSource>
    </UserControl.Resources>

        <ListView ItemsSource="{Binding}" DataContext="{StaticResource Sets}"  DockPanel.Dock="Bottom" Margin="5">

            <ListView.View >
                    <GridView >
                        <GridViewColumn DisplayMemberBinding="{Binding StartTimeFormatted}" Header="Start" Width="60"  />
                        <GridViewColumn DisplayMemberBinding="{Binding Comment}" Header="Comment"  >
                    </GridViewColumn>
                    </GridView>
                </ListView.View>
            <ListView.GroupStyle>
                <GroupStyle>
                    <GroupStyle.ContainerStyle>
                        <Style TargetType="{x:Type GroupItem}">
                            <Setter Property="Margin" Value="0,0,0,5"/>
                            <Setter Property="Template">
                                <Setter.Value>
                                    <ControlTemplate TargetType="{x:Type GroupItem}">
                                        <Expander IsExpanded="False" BorderBrush="#FFA4B97F"
                                                  BorderThickness="0,0,0,1">
                                            <Expander.Header>
                                                <DockPanel>
                                                    <TextBlock Foreground="{Binding Path=Name.EntryColor}"  FontWeight="Bold" Text="{Binding Path=Name.TotalHoursFormatted}"/>
                                                    <TextBlock Foreground="{Binding Path=Name.EntryColor}"  FontWeight="Bold" Text=" hours - "/>
                                                    <TextBlock Foreground="{Binding Path=Name.EntryColor}" FontWeight="Bold" Text="{Binding Path=Name.EntryDateFormatted}"/>
                                                    <TextBlock Foreground="{Binding Path=Name.EntryColor}" FontWeight="Bold" Text=" Entries: "/>
                                                    <TextBlock Foreground="{Binding Path=Name.EntryColor}" FontWeight="Bold" Text="{Binding Path=ItemCount}"/>
                                                </DockPanel>
                                            </Expander.Header>
                                            <Expander.Content>
                                                <ItemsPresenter />
                                            </Expander.Content>
                                        </Expander>
                                    </ControlTemplate>
                                </Setter.Value>
                            </Setter>
                        </Style>
                    </GroupStyle.ContainerStyle>
                </GroupStyle>
            </ListView.GroupStyle>
            </ListView>

Now, it doesn't fully work - I cannot get the CollectionViewSource to work based on the inner collection (each EntrySet contains Entries collection which should be the actual data source - the EntrySet is used for grouping and custom group header display).
The current code gives the following result:

So, this shows that the binding 'sort of' works, but the groups don't contain the actual entries inside (only the one single property which is identical in the DailyDetailEntry and DailyDetailSet).
How do I make the listview use the collection property of a collection as the items source?
I tried lots of different declarations for ItemsSource in binding, including specifying Path, or a syntax like that <CollectionViewSource x:Key="Sets" Source="{Binding Path=EntrySets/Entries}">, but in most cases the result is even worse .


text:
Q: Skype doesn't start anymore Skype always started and logged in automatically after PC start. But today it didn't happen. Instead of this Skype login window popped up and I was asked to enter my credentials. I entered them, the login window disappeared, but nothing else happened. I didn't see the usual things after that like the main Skype widnow, contacts etc. I thought that I was hacked, but no, as I could login with the same credentials on the Skype webpage. Then I repeated the procedure, but started Skype from terminal, hoping to see some errors, but there was no output at all. skype command just exited.
Is my Skype version still supported (4.3.0.37)? I've heard that Skype had reduced the number of supported Linux versions this summer...
My OS: Ubuntu 14.04.5 LTS
My Skype version is

A: You can rewrite the skype binary to present a different (false) version:
# perl -pi -e 's/4\.3\.0\.37/8.3.0.37/g' skype

and it works for now. Of course, it is just a matter of time till it stops working.

A: As you can see here Microsoft decided to force people to upgrade to newer Skype versions and the old ones cease to work since a few weeks already. This might probably be related to Skype moving from peer-to-peer to being cloud based (mentioned by @Rsf).

As announced earlier this year, the old Skype for Linux v4.3 is at its
  end-of-life and will be decommissioned in the upcoming weeks.
You will be automatically signed out of Skype until you update.
  Please, update to the new Skype 8.x, which is ready for you with lots
  of improvements at Skype.com.
In case you hit any issues, please check known issues, system
  requirements, or post your questions directly to this forum. All your
  feedback will be greatly appreciated.
Kind regards,
The Skype Team
  (source)

To get the newer version you should download the latest .deb file from Microsoft and install it with gdebi or dpkg (shouldn't make a difference but gdebi is a bit more secure when it comes to dependencies).
Be aware, the new Skype will create a file in /etc/apt/sources.list.d/ and will do so every time it updates if the file does not exist with the exact name Skype chosen for it. So renaming the file in /etc/apt/sources.list.d/ only calls for trouble in form of duplicated source list entries. You as well want to remove any before existing files for Skype in your sources.list.d directory.

A: The only thing that worked for me was: https://answers.microsoft.com/en-us/skype/forum/skype_linux-skype_startms-skype_installms/skype-is-now-available-as-snap/732fb227-3e0a-46b3-8cbc-55dd2fae09ab.

Skype is now available to Linux users as SNAP package, which will make
  installation and updates on many Linux distributions way easier.
Feel free to install it from the Snap Store or by running the
  following command in your terminal*:
snap install --classic skype

*In order to install Snap packages, you will need the snapd installed first. Here is how: https://docs.snapcraft.io/core/install
Skype Preview for Insiders is also available.
By installing this application you agree you have read and
  accepted Terms of Use and Privacy Statement. Install it with:
snap install --channel=insider/stable --classic skype

A: this works on my Ubuntu 16.04.3 LTS
sudo perl -pi -e 's/4\.3\.0\.37/8.3.0.37/g' /usr/bin/skype