text:
Q: android query only returns last row I am building a weather app that gets data from the openweathermap api and inserts them into a database in the doInBackgroudMethod of AsyncTask. In the onPostExecute, i query the database table and set the cursor to a SimpleCursorAdapter. Here's the problem: While the bulkInsert shows that 14 rows have been inserted into the database, the query in the onPostExecute only return one row (which appears to be the last row if i compare the values obtained with the JSON returned from the OWM server). This last row is what appears on the test device when i run the app. Here's the code i'm using to insert in doInBackGround. I should add that the doInBackground gets the data, parses the JSON and formats it accordingly. The last step is where i bulk insert 14 days of weather data into the database which appears to work. Since the insert() method isn't returning -1 or any weird errors. The query() doesnt return what it should.
   public int bulkInsert(Uri uri, ContentValues[] values) {

        final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        final int match = sUriMatcher.match(uri);
        switch (match) {
            case WEATHER:
                db.beginTransaction();
                int returnCount = 0;
                try {
                    for (ContentValues value : values) {
                        normalizeDate(value);
                        long _id = db.insert(WeatherContract.WeatherEntry.TABLE_NAME, null, value);

//this log increases with every insert. The logs are shown below
                        Log.d(MainActivity.TAG, " row id value? "+ _id);
                        if (_id != -1) {
                            returnCount++;
                        }
                    }
                    db.setTransactionSuccessful();
                } finally {
                    db.endTransaction();
                }
                getContext().getContentResolver().notifyChange(uri, null);
                db.close();

                mOpenHelper.close();

                return returnCount;
            default:
                return super.bulkInsert(uri, values);
        }

}

I am using the following to query the table in onPostExecute
protected void onPostExecute(String[] strings) {
            super.onPostExecute(strings);
            mForecastAdapter.notifyDataSetChanged();
            Cursor countCursor = getContext().getContentResolver().query(WeatherEntry.CONTENT_URI, null, null, null, null);

            countCursor.moveToFirst();
            int count = countCursor.getCount();

            Log.d(MainActivity.TAG,"row count? "+count);

          if(countCursor.moveToFirst()){
              Log.d(MainActivity.TAG, "swapping cursor");

              mForecastAdapter.swapCursor(countCursor);
          }

            Log.d(MainActivity.TAG, "cursor?: "+countCursor.moveToFirst());

            String countQuery = "SELECT  * FROM " + WeatherEntry.TABLE_NAME;
            SQLiteDatabase db = new WeatherDbHelper(getContext()).getReadableDatabase();
            Cursor cursor = db.rawQuery(countQuery, null);
            int cnt = cursor.getCount();
            cursor.close();

            Log.d(MainActivity.TAG, " HOW MANY ROWS? "+cnt);

        }

Here's the implementation of the query method in my content provider
  @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
                        String sortOrder) {
        // Here's the switch statement that, given a URI, will determine what kind of request it is,
        // and query the database accordingly.
        Cursor retCursor;
        switch (sUriMatcher.match(uri)) {
            // "weather/*/*"
            case WEATHER_WITH_LOCATION_AND_DATE:
            {
                retCursor = getWeatherByLocationSettingAndDate(uri, projection, sortOrder);
                break;
            }
            // "weather/*"
            case WEATHER_WITH_LOCATION: {
                retCursor = getWeatherByLocationSetting(uri, projection, sortOrder);
                break;
            }
            // "weather"
            case WEATHER: {
                retCursor = mOpenHelper.getReadableDatabase().query(
                        WeatherContract.WeatherEntry.TABLE_NAME,
                        projection,
                        selection,
                        selectionArgs,
                        null,
                        null,
                        sortOrder
                );
                break;
            }
            // "location"
            case LOCATION: {
                retCursor = mOpenHelper.getReadableDatabase().query(
                        WeatherContract.LocationEntry.TABLE_NAME,
                        projection,
                        selection,
                        selectionArgs,
                        null,
                        null,
                        sortOrder
                );
                break;
            }

            default:
                throw new UnsupportedOperationException("Unknown uri: " + uri);
        }
        retCursor.setNotificationUri(getContext().getContentResolver(), uri);

        return retCursor;
    }

Here are the logs:
10-13 09:13:08.416 27330-27330/com.example.android.mysunshine.app D/mainTag: onCreate called:
10-13 09:13:08.424 27330-27330/com.example.android.mysunshine.app D/mainTag: ON START CALLED
10-13 09:13:08.426 27330-27330/com.example.android.mysunshine.app D/mainTag: 90210
10-13 09:13:10.604 27330-27355/com.example.android.mysunshine.app
10-13 09:13:10.787 27330-27355/com.example.android.mysunshine.app D/mainTag:  row id value? 1
10-13 09:13:10.788 27330-27355/com.example.android.mysunshine.app D/mainTag:  row id value? 2
10-13 09:13:10.791 27330-27355/com.example.android.mysunshine.app D/mainTag:  row id value? 3
10-13 09:13:10.792 27330-27355/com.example.android.mysunshine.app D/mainTag:  row id value? 4
10-13 09:13:10.794 27330-27355/com.example.android.mysunshine.app D/mainTag:  row id value? 5
10-13 09:13:10.795 27330-27355/com.example.android.mysunshine.app D/mainTag:  row id value? 6
10-13 09:13:10.797 27330-27355/com.example.android.mysunshine.app D/mainTag:  row id value? 7
10-13 09:13:10.799 27330-27355/com.example.android.mysunshine.app D/mainTag:  row id value? 8
10-13 09:13:10.800 27330-27355/com.example.android.mysunshine.app D/mainTag:  row id value? 9
10-13 09:13:10.801 27330-27355/com.example.android.mysunshine.app D/mainTag:  row id value? 10
10-13 09:13:10.803 27330-27355/com.example.android.mysunshine.app D/mainTag:  row id value? 11
10-13 09:13:10.804 27330-27355/com.example.android.mysunshine.app D/mainTag:  row id value? 12
10-13 09:13:10.806 27330-27355/com.example.android.mysunshine.app D/mainTag:  row id value? 13
10-13 09:13:10.807 27330-27355/com.example.android.mysunshine.app D/mainTag:  row id value? 14
10-13 09:13:10.825 27330-27355/com.example.android.mysunshine.app D/mainTag: FetchWeatherTask Complete. 14 rows Inserted
10-13 09:13:10.832 27330-27355/com.example.android.mysunshine.app D/mainTag: immediate count: 1
10-13 09:13:10.834 27330-27330/com.example.android.mysunshine.app D/mainTag: row count? 1
10-13 09:13:10.834 27330-27330/com.example.android.mysunshine.app D/mainTag: swapping cursor
10-13 09:13:10.835 27330-27330/com.example.android.mysunshine.app D/mainTag: cursor?: true
10-13 09:13:10.842 27330-27330/com.example.android.mysunshine.app D/mainTag:  HOW MANY ROWS? 1

You see? The code in the bulkInsert shows that i have inserted 14 rows but the query only returns one row.
Could anyone help please?


text:
Q: Simpler method for decoding JSON from multiple services in Swift Premise
I have a struct that conforms to Decodable, so it can decode JSON from a variety of responses via init(from:). For each type of JSON response I expect to decode, I have an enum that conforms to CodingKey.
Example
Here's a simplified example, which can be dropped into a Swift playground:
import Foundation

// MARK: - Services -

struct Service1 {}
struct Service2 {}

// MARK: - Person Model -

struct Person {
    let name: String
}

extension Person: Decodable {
    enum CodingKeys: String, CodingKey {
        case name = "name"
    }

    enum Service2CodingKeys: String, CodingKey {
        case name = "person_name"
    }

    // And so on through service n...

    init(from decoder: Decoder) throws {
        switch decoder.userInfo[.service] {
        case is Service1.Type:
            let container = try decoder.container(keyedBy: CodingKeys.self)
            name = try container.decode(String.self, forKey: .name)
        case is Service2.Type:
            let container = try decoder.container(keyedBy: Service2CodingKeys.self)
            name = try container.decode(String.self, forKey: .name)
        // And so on through service n...
        default:
            fatalError("Missing implementation for service.")
        }
    }
}

// MARK: - CodingUserInfoKey -

extension CodingUserInfoKey {
    static let service = CodingUserInfoKey(rawValue: "service")!
}

// MARK: - Responses -

// The JSON response from service 1.
let service1JSONResponse = """
[
    {
        "name": "Peter",
    }
]
""".data(using: .utf8)!

// The JSON response from service 2.
let service2JSONResponse = """
[
    {
        "person_name": "Paul",
    }
]
""".data(using: .utf8)!

// And so on through service n... where other services have JSON responses with keys of varied names ("full_name", "personName").

// MARK: - Decoding -

let decoder = JSONDecoder()

decoder.userInfo[.service] = Service1.self
let service1Persons = try decoder.decode([Person].self, from: service1JSONResponse)

decoder.userInfo[.service] = Service2.self
let service2Persons = try decoder.decode([Person].self, from: service2JSONResponse)

Problem
The problem I'm running into is that I have a lot of different services that I needed to decode responses from, and a model with many more properties than this simplified example. As the number of services increases, so does the number of cases needed to decode those responses.
Question
How can I simplify my init(from:) implementation to reduce all this code duplication?
Attempts
I've tried storing the correct CodingKey.Type for each service and passing that into container(keyedBy:), but I get this error:

Cannot invoke 'container' with an argument list of type '(keyedBy: CodingKey.Type)'.

init(from decoder: Decoder) throws {
    let codingKeyType: CodingKey.Type

    switch decoder.userInfo[.service] {
    case is Service1.Type: codingKeyType = CodingKeys.self
    case is Service2.Type: codingKeyType = Service2CodingKeys.self
    default: fatalError("Missing implementation for service.")
    }

    let container = try decoder.container(keyedBy: codingKeyType) // ← Error
    name = try container.decode(String.self, forKey: .name)
}

A: Rather than trying to solve this with CodingKeys and an increasingly complicated init, I suggest composing it via a protocol:
protocol PersonLoader: Decodable {
    var name: String { get }
    // additional properties
}

extension Person {
    init(loader: PersonLoader) {
        self.name = loader.name
        // additional properties, but this is one-time
    }
}

Alternately, particularly if Person is a read-only simple data object, you could just make Person a protocol, and then you could avoid this extra copying step.
You can then define the interfaces for each service independently:
struct Service1Person: PersonLoader {
    let name: String
}

struct Service2Person: PersonLoader {
    let person_name: String

    var name: String { person_name }
}

And then map into Persons when you're done:
let service2Persons = try decoder.decode([Service2Person].self,
                                         from: service2JSONResponse)
    .map(Person.init)

If you went with a protocol-only approach, it would look like this instead:
protocol Person: Decodable {
    var name: String { get }
    // additional properties
}

struct Service1Person: Person {
    let name: String
}

struct Service2Person: Person {
    var name: String { person_name }
    let person_name: String
}

let service2Personsx = try decoder.decode([Service2Person].self,
                                         from: service2JSONResponse) as [Person]

A: Without a bunch of custom per-service (or per-service type) functionality in Person's init(from:), I think it would be difficult to do. You can't pass custom CodingKey-conformant enums into decoder.container(keyedBy:) because it is generic over the type of that enum.
One way you could do it is by using a custom key decoding strategy and perform the mapping from a dictionary or by a function in the custom key decoding method/closure.
In the example below, I've used an enum to represent the services. The mapping dictionary is keyed off the enum case, so reflects the service/service type key mapping. Hopefully, this can serve as a useful roadmap for your more complex real-world use case.
import Foundation

// MARK: - Custom Key Decoding -

struct MyCodingKey: CodingKey {
    var stringValue: String
    var intValue: Int?

    init?(stringValue: String) {
        self.stringValue = stringValue
        self.intValue = nil
    }

    init?(intValue: Int) {
        self.stringValue = String(intValue)
        self.intValue = intValue
    }
}

// MARK: - Services -

enum Services: String {
    case service1
    case service2
}

extension Services {

    var mapping: [String:String] {
        switch self {
        case .service1: return [:]
        case .service2: return ["person_name": "name"]
        }
    }

    func getPersons(jsonData: Data) throws -> [Person] {
        let decoder = JSONDecoder()

        decoder.keyDecodingStrategy = .custom { (keys: [CodingKey]) -> CodingKey in
            let lastKey = keys.last!
            guard lastKey.intValue == nil else {
                return MyCodingKey(intValue: lastKey.intValue!)!
            }
            guard let stringValue = self.mapping[lastKey.stringValue] else {
                return lastKey
            }

            return MyCodingKey(stringValue: stringValue)!
        }

        let persons = try decoder.decode([Person].self, from: jsonData)
        return persons
    }
}

// MARK: - Person Model -

struct Person: Decodable {
    let name: String
}

// MARK: - Responses -

// The JSON response from service 1.
let service1JSONResponse = """
[ {  "name": "Peter", } ]
""".data(using: .utf8)!

// The JSON response from service 2.
let service2JSONResponse = """
[ { "person_name": "Paul", } ]
""".data(using: .utf8)!

// MARK: - Sample Calls -

print((try? Services.service1.getPersons(jsonData: service1JSONResponse))!)
print((try? Services.service2.getPersons(jsonData: service2JSONResponse))!)

redpajama_set_name: RedPajamaStackExchange


text:
Q: R ftpUplad error: cannot open the connection I am trying to upload a data.frame called 'ftp_test' via ftpUpload command
library(RCurl)
ftpUpload("Localfile.html", "ftp://User:Password@FTPServer/Destination.html")

and am getting an error:

Error in file(what, "rb") : cannot open the connection
  In addition: Warning message:
  In file(what, "rb") :
  cannot open file 'ftp_test': No such file or directory

Could anyone tell me what is the issue here? Can I actually use data.frame and upload from r global environment ?
If I can't use the data.frame is there any workaround?
Many thanks,
Artur

A: You problem is, that you are trying to send an R object with an file transfer protocol. Since you are saving it there, you have to tell how to save it. A workaround is to save it as a file, upload it and then delete it on your local afterwards. Also saving as R.History is fine, but you need to transfer the R object to a file in some way. This example is used with an open ftp sever (uploads get deleted immediately, but you can try if it works)
filename="test.csv"
write.csv(df, file=filename)
#use your path to the csv file here instead of ".~/test.csv", you can check with getwd()
ftpUpload("~/test.csv", paste("ftp://speedtest.tele2.net/upload/",filename, sep=""))

file.remove(filename)

Also make sure your server is running. You can try your code with the open ftp server.


text:
Q: Autofocusing on a newly added element via javascript This should be simple but I can't get it to work so would appreciate any pointers.
I have a function in my webpage that adds a new line into a table with inputs etc.  This is a pretty basic POST that looks something like this...
$.post(url, {
    newRow : newRow
}, function(data) {
    $('#' + tableName + ' > tbody > tr').eq(rowLoc).before(data);
}).done(function() {
    reNumberTableIDName($tb)
});

The reNumberTableIDName function is pretty straightforward, it runs through all the objects in the table and changes their id/name so that they are in order relevant to the row they are in the table for other reasons.
Now, one of the elements added in to this table is an auto complete input which looks like so...
<input id="autoLook[9]" class="required yui-ac-input" type="text" title="" value="" name="autoLook[9].id" style="width:500px" autocomplete="off" required="required">

Note that the name and ID are not altered as part of the reNumberTableIDName function.
I tried adding in a line to the "done"portion of the post to then put the focus/carat into that new input but it doesn't work (focus stays on the button previously clicked to add the row).
$("#autoLook[" + (newRow -1) + "]").focus();

I've checked with an alert that "#autoLook[" + (newRow -1) + "]" does indeed come up with the right string so I'm at a loss as to why this doesn't work.  What obvious litle gotcha am I missing?
Its also worth noting that I tried to add in a autofocus property to the input being added, but I'm working in grails and this type of auto complete doesn't allow me to do this.
Thanks!
Worth noting that the solution should be to use setTimeout as mentioned below else it will continually put focus back to the object!

A: The selector #autoLook[9] matches an element with the id autoLook and the attribute 9; which is obviously wrong. Add backslashes around the square brackets to escape them:
$("#autoLook\\[" + (newRow - 1) + "\\]").focus();

Quote from jQuery Documentation: Selectors:

To use any of the meta-characters (such as
  !"#$%&'()*+,./:;<=>?@[\]^``{|}~) as a literal part of a name, it
  must be escaped with with two backslashes: \\. For example, an
  element with id="foo.bar", can use the selector $("#foo\\.bar").
  The W3C CSS specification contains the complete set of rules regarding
  valid CSS selectors. Also useful is the blog entry by Mathias Bynens
  on CSS character escape sequences for identifiers.


text:
Q: how can i resize the captcha image + MvcCaptchaExtensionMVC3 I am using MVCcaptcha in my MVC3 site, now i want to resize the default captcha image size to customized size
there is one good post about use of MVCcaptchaExtention here
but it didn't specify how to resize image
how can i resize the captcha image ?

A: In SSB.Web.Mvc.MvcCaptcha.Properties.Settings set
<setting name="MvcCaptchaWidth" serializeAs="String">
    <value>130</value>
</setting>
<setting name="MvcCaptchaHeight" serializeAs="String">
    <value>40</value>
</setting>


text:
Q: Rename file using batch file I know there are many examples of this but I just can't get it and this shouldn't be THAT difficult but I am finding it to be.
I have a folder with 4 files in it:
rtcc_current_pnp_data1-2018-12-26-061000.txt
rtcc_current_pnp_data2-2018-12-26-061000.txt
rtcc_current_pnp_data3-2018-12-26-061000.txt
rtcc_current_pnp_data4-2018-12-26-061000.txt

the date/time at the end changes daily.
Each day I want to run a batch file to rename these to:
data1.txt
data2.txt
data3.txt
data4.txt

That's it...can someone please help me extract the correct name from the files and rename them?
So I tried this and it doesn't do anything:
for %%A in (\\apdwhdb01\D$\ProbationImportFolder\Current\rtcc*.*) do (
  set "filename=%%A"
  set "newName=EXP_!filename:~18!"

  rem ** remove the ECHO when it seems to work
  ren !filename! !newName!
)

A: The easiest way is with this:
 ren "\\apdwhdb01\D$\ProbationImportFolder\Current\*data1*.txt" data1.txt
 ren "\\apdwhdb01\D$\ProbationImportFolder\Current\*data2*.txt" data2.txt
 ren "\\apdwhdb01\D$\ProbationImportFolder\Current\*data3*.txt" data3.txt
 ren "\\apdwhdb01\D$\ProbationImportFolder\Current\*data4*.txt" data4.txt

However, the problem you are probably facing is that the network connection isn't active/valid for your connection. The easiest way to find out is with this:
 dir "\\apdwhdb01\D$\ProbationImportFolder\Current"

If it returns your file list then you're okay. If not then you'll want to map the drive first in the same batch file:
 :: temporarily map the network share to the Q: drive.
 :: make sure you update the username and password
 net use q: "\\apdwhdb01\D$\ProbationImportFolder\Current" /user:MyUserName myPassword

 :: rename the files
 ren "q:\*data1*.txt" data1.txt
 ren "q:\*data2*.txt" data2.txt
 ren "q:\*data3*.txt" data3.txt
 ren "q:\*data4*.txt" data4.txt

 :: remove the mapped drive
 net use q: /delete

A: @echo off

pushd "\\apdwhdb01\D$\ProbationImportFolder\Current" || exit /b 1

for %%A in (data1 data2 data3 data4) do (
    for %%B in ("rtcc_current_pnp_%%~A-20*.txt") do (
        ren "%%~B" "%%~A.txt"
    )
)

popd

The pushd will map the network share to a temporary mapped drive.
The || is if the command on the left fails,
do the command on the right,
which is exit /b 1 that ends the script.
The for loop iterates through
data1, data2, data3 and data4.
The nested for loop iterates the file names using %%A
with a value of i.e. data1, and uses a wildcard for the datestamp variation.
%~B is the current filename which is renamed to %%~A.txt,
in which %%~A holds the current value of i.e data1.
The ~ in %%~A is a modifier which will remove surrounding double quotes.
The popd will retore the previous current working directory
that pushd changed. It should remove the temporary mapped drive.
To get help on a command, use i.e. pushd /?, which will print
out help information.
for /? prints help information about for, ren /? ... etc.

A: A two line script example:
@PushD "\\apdwhdb01\D$\ProbationImportFolder\Current" 2>Nul || Exit /B
@For %%A In ("rtcc_*.txt") Do @For /F "Tokens=4 Delims=_-" %%B In ("%%A") Do @Ren "%%A" "EXP_%%B%%~xA"

For information on the commands used, open a Command Prompt and enter each of:

PushD /?
  Exit /?
  For /?
  Ren /?


text:
Q: What is the difference between Direct Variation and a proportion? So Both DV and a proportion can be represented as
$y = kx$
So I was wondering- is there a difference?

A: I believe that "x varies directly with y" means exactly the same as "x is directly proportional to y".
This is anecdotal, but it seems to be trendy in secondary math education these days to use the former terminology, although (as evidenced by the references on the wiki page for Proportionality), the latter was used more 10 years ago. I don't know the reason for the change.


text:
Q: I need to know how to round numbers to a certain decimal place in C++ I Have this code to find out the total purchase price of some numbers and i need to know how to round the numbers to only 2 decimal places.
#include <iostream.h>
#include <cstdlib.h>
#include <string.h>

int main() {
    float sale_price;
    float tax_rate;
    float discount_rate;

    system("cls");
    system("color 07");
    cout << "\n\nWelcome to the second version of my total purchase price calculator!\n";
    cout << "How much did your recently purchased item cost? ";
    cin >> sale_price;
    cout << "What is the tax rate in your area? ";
    cin >> tax_rate;
    cout << "What was the discount rate, if any (if none, just put down 1) ";
    cin >> discount_rate;
    float tax = sale_price*(tax_rate/100);
    float discount = sale_price*(discount_rate/100);
    float total_price = sale_price + tax - discount;
    cout << "The total price of your item is $"<<total_price<<" with $"<<tax<<" tax minus $"<<discount<<" due to discount.\n";
    cout << "Would you like a reciept? y or n. ";
    string answer;
    End:
    cin >> answer;
    if (answer == "y") {
        goto Reciept;
    }
    else if (answer == "n") {
        return 0;
    }
    else {
        cout << "Try another answer\n";
        goto End;
    }
    Reciept:
    system("cls");
    system("color 70");
    cout << "\xda\xc4\xc4\xc4\xc4\xc4\xc4\xc4\xc4\\xc4\xc4\xc4\xc4\xc4\xc4\xc4\xc4\xbf\n";
}

this usually gives me 4 decimal places just FYI

A: Round to 2 decimals: int((n * 100.0) + 0.5) / 100;
Round to 3 decimals: int((n * 1000.0) + 0.5) / 1000;
etc.

A: The easy way is to use setprecision:
 std::cout << "The total price of your item is $"
           << std::setprecision(2) << total_price ...

This will occasionally get things wrong. A better solution is to use an improved rounding function that is not a part of the standard (e.g., How does Excel successfully Rounds Floating numbers even though they are imprecise?). An even better solution is to implement your own fixed point arithmetic algorithm so as to avoid this problem entirely. You can still go one better than that: Use a fixed point arithmetic package that someone else has already written and tested to the nth degree.

A: You should use Iomanip's setprecision:
setprecision reference

A: When you output with cout, use the setprecision() operator.
cout << fixed;
cout << setprecision(2) << sale_price*(tax_rate/100);

A: Do
cout.precision(2);
cout << fixed;

before you output the floats.


text:
Q: GRASS Hough transform issue Via GRASS
I installed the Hough transform.
I start the Hough transform but it doesn't give any rendering time and the rendering doesn't finish.

The image I used;
(Canny edge detection applied image)
QGIS Hough Transform Error


text:
Q: Is it possible to create a full-screen UIImagePickerController (with camera source) on an iPad 2? My goal seems simple: Replicate the behavior of the iPad 2 camera app with regard to previewing/taking still photos.  Namely, I want to display the preview in a full-screen window.
Unfortunately this seems impossible on the iPad 2 with a UIImagePickerController.  A UIImagePickerController must be hosted within a UIPopoverController, and according to the docs:

When changing the size of the popover's content, the width value you specify must be at least 320 points and no more than 600 points.

This is fairly consistent with the results I've been seeing.  Regardless of the size I specify, I see a small preview window.  Is there a way to get around this with the UIImagePickerController?

A: The docs are confusing/wrong on this.  You can also present the camera full screen using a navigation controller with presentModalViewController.  This is exactly the same as on iPhone.
Note, this only works on a device, not on the simulator.


text:
Q: How to find the execution time of a method of the class under test using Junit? I need to find the execution time of methods and document them in a report to identify the execution times of different methods. This has to be done regularly, so whenever tests run in build the execution time is recorded.
One approach is to capture start and end time and take difference. Is there a way where we can annotate the method under test and only when the method is executed from Junit, the execution time is recorded?
For example:
@Test
public void test() {
    classUndetTest.method1();
}

void method1(){
  method2();
}

void method2() {
}

I would like to find the time taken for executing method2, when the test is run.

A: Not exactly what you want, but maybe helpful: JUnit Stopwatch.


text:
Q: Change word emphasis in a sentence with Azure Text-To-Speech SSML I want to change the emphasis to a different word and SSML supports the <emphasis> element, but it isn't listed in the Microsoft documentation. It was ignored when I added it to the SSML markup.
It seems like you could use the prosody-element to change the emphasis.
Update: It looks like the following prosody element results in a similar output than the <emphasis> element. The pitch is raised in this case by 30% for the word that has to be emphasised:
This is a <prosody pitch="+30.00%">Test</prosody>

May be there are other suggestions on how to best emulate emphasis on a word.

A: Adding a short break before the emphasized word(s) seems to increase the importance. Around 70-200ms seems to be nice.
Also, I tend to slow the rate instead of increasing the pitch.
This is a <break time="100ms"/><prosody rate="-10.00%">test</prosody>

A: <emphasis> is now a supported element (https://learn.microsoft.com/en-us/azure/cognitive-services/speech-service/speech-synthesis-markup?tabs=csharp#adjust-emphasis). Currently it is only supported for some English voices however.


text:
Q: onClick to another JSP doesn't work I been having problems on my onclick function to another JSP.
I wanted to check whether if the session attribute is the same as John or Mark from my display.jsp, then it will display on new.jsp with that name.
I have a login.jsp and successfully works on display.jsp where it able to display name out by using session in ValidationServlet.
After implementing the code in display.jsp, I keep getting requested resource () is not available.
Stuck there for 3 days already and kinda lost now.
Hope you guys could help me out with it, thanks in advance.
This is my display.jsp code
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Application</title>

Display

        Welcome <%=session.getAttribute("name")%>,

                    <form action="loan" method="post">
                        <input type="submit" value="New" onClick="new()"/>
                    </form>

This is my new.jsp code
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Application</title>

New

        Hello <%=session.getAttribute("name")%>

A: You will get the session variable like beelow:
var firstName='<%= session.getAttribute("name")%>';

A: I don't think you can access session variable from java script, since it executes on client side, what is the output for this piece of code session.getAttribute("name") , Are you getting expected value?
Alternatively you can fallow this link Access session variables in js


text:
Q: Encrypt address bar url in Asp.net Since this very important for every secure website to encrypt or encode its address bar URL to prevent end user from being viewing. How can I achieve this in asp.net at client side (by javascript). It should be display encoded URL but should work fine at server side. Means should decode appropriately. There are three questions you can provide answer for

*

*Encode or decode URL by javascript.

*Hide address bar

*Prevent copying of address bar
Please share your views/Answer for any one of above as per your specification. It will helpful.
Thanks

A: *

*You can use encodeURIComponent(str) and encodeURI(str) functions for encoding URLs in java-script but I am not sure what purpose it would serve because URLs are still be valid and can be used by user. Some parts of it may get obfuscated as far as ordinary user is concerned but for any sophisticated user (who I guess would be your target for encoding scheme) could easily figure it out.

*While launching the browser window (popup) from java-script, you can show it without address bar. For example,
var popup = window.open("http://someurl", "myPopup", 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=120,height=120')
But then its quite possible to have a browser that would allow to get the address bar back on some hot key or menu. Browser is the user agent and hence as such needs to allow user to control its UI rather than the content developer.

*AFAIK, you cannot prevent user copying the address bar text.
Hiding or preventing address bar copying is anyway pointless as one can easily figure out address by checking page properties or say sniffing network etc.
All said, I simply don't understand the idea behind what you want to do because it does not seems to server any purpose as far as security goes.


text:
Q: Browser hisory not stored url while using php redirect This problem occurs in all browsers except firefox.
In my website, for ex, the home page will be like this www.example.com
After click signin link, it will be www.example.com/signin.php
After finsihed authentication, I will redirect the page using header function in php to user's prfoile. So after logged in my page wil be like this. www.example.com
If the user clicked back button, I will check the session in signin.php and again redirect to user's profile page.
It works fine for me in firefox. Other than that all browsers, If I used header redirection, it will not store the page in browser's history.
I mean, I am redirecting the user after authentication in signin page. So the signin.php url not stored in browser history.
So If I use back button, it will go to previous site what I opened before opening my site.
Can anyone help?? Thanks in advance.

A: use $_SERVER['HTTP_REFERER'] for redirection where user came from


text:
Q: .aspnetcore.identity.Application cookie not set in the production environment I have created a abp.io version 7.0-rc2 solution using the starter template.
I have chosen a tiered solution with separate authserver project(OpenIdDict) and Blazor-server as UI project. The solution works fine when I launch the AuthServer, HttpApi.Host and Blazor server UI client on localhost using development environment.
But this doesn't work in the production environment with nginx reverse proxy and using kestrel to serve the application.(The Https configuration has been done.)
The issue is, that the admin does not have some permissions after login, although I have checked with the database, all the permissions have been granted to admin.
I have checked the cookies of the blazor project domain in my browser, the .aspnetcore.identity.application cookie is not set. Of course the permission check will not pass without cookie.
The cookie has been returned from the authserver while logging in. The set-cookie does exist in the response header from authserver login form submission, as I checked using browser developer tool, but not set finally to the browser after the login process.
Then I made an experiment. I made changes to my appsettings.development.json in my blazor server UI project to let the AuthServer and HttpApi.Host running in the Production environment, and run the Blazor server on my development pc(localhost), let the blazor server using the production authserver and call the production API server too. Only the blazor server ui itself is running locally. It works then fine. The aspnetcore.identity.application cookie(localhost domain) is then successfully set to the browser.And the permissions are also successfully authorized.
I am not quite familiar with how the cookies are set in asp.net or Abp.Could somebody give me a hint, what could be the problem in the production environment? Or what should I check to find the problems out?
Thank you very much.


text:
Q: How to fetch an  tag which is inside an anchor  tag I want to retrieve the  tag which is inside an anchor tag.

    ****

I need to get whole .
What I am doing is:
if($(img_ads[k]).has("img").length) {
    console.log ($(img_ads[k]).children('img'));
}

It returns this:
Output of above Jquery code
Please suggest some simple alternative which can output the contents of image tag as simple text or HTML.
Thanks. ;)

A: use $('a').html() this will give you the  in text format
https://jsfiddle.net/ugeshgupta000/nzeb0zuy/


text:
Q: How to test for inequality in the presence of non-independent noise? I have multiple samples which include a response time of a system. I want to test if no sample is significantly different (primarily the expected value). For two sample testing I'm using the sign test and for testing multiple ones at a time I'm using the Friedman test.
Unfortunately, the samples have non-independent noise (verified with Hoeffding's test, p-value < 1e-8). In practice that means that for samples with over 10000 observations, the sign test and Friedman test show statistically significant differences (p-value < 1e-6) for samples that were measurements of exactly the same input.
What is the recommended practice for dealing with with non-independent, non-uniform, multimodal, heteroskedastic noise for repeated measurements data?
Data acquisition
The measurements are performed as follows:

*

*First create a list of randomly ordered tuples of tests to perform (e.g., given three inputs, A, B, and C, it could be something like ABC, CBA, CAB, BCA, etc.)

*Run the tests in that random order (e.g. send input A, wait for reply, send B, wait for reply, send C, wait for reply, send C, wait for reply, send B, wait for reply, etc.)

*

*The inputs are sent by a Python application over a regular TCP connection, the "protocol" is just connect, send query, wait for response, close connection

*Have a system running in the background that monitors the communication, noting the time between query and response, saves that as a list (continuing the example: 68028 ns, 69667 ns, 67971 ns, 68535 ns, 69458 ns, 67767 ns, 68335 ns, ...)

*

*This is done by tcpdump

*Combine the knowledge of the ordering of the tests to the noted times to get measurements for specific tests (continuing the example, for A I then get 68028 ns, 67767 ns, 67822 ns, ..., for B I get 69667 ns, 69458 ns, 68314 ns, ..., and for C I get 67971 ns, 68535 ns, 68335 ns, ...)

Data example
Example scatter plot of a pair of samples (axes are in
seconds):

A: More data
I did an additional run with N=12800, where all the probes were sending the exact same values, but were generated by 2 different objects. (Same classes, initialised with the same values, but separate instances).
The first 4 were generated by one object, while the last 3 were generated by a second object.
I've then bootstrapped confidence intervals for the calculated medians of differences:

Reinterpreting the data from question
Neither looking at the PACF of the differences between B and A:

Nor running tests like the Wald-Wolfowitz runs test strongly point to lack of independence of the differences between samples (p-value=0.017).
But if we look at the windowed median (window=1000, step=1):

It's fairly clear that the false positive in the sign test isn't caused by one large single excess or periodic excess in one sample over the other, but rather in systematic departure from the zero median.
Hypothesis
The false positives are caused by small, but constant differences in how the different instances of objects are handled in the python interpreter.
This in turn has effect on the delay between when the connection is opened and when the data over it is sent. And that affects how quickly the server responds.
In other words, it's the effect of PYTHONHASHSEED and/or ASLR.
Solution
The solution is to send probes from new processes, so that any effect from PYTHONHASHSEED and/or ASLR is the same for different instances.
Verification
I've thus modified the execution of the tests so that any single process isn't used to send more than 100 probes.
I've then repeated the experiment few dozen times with large sample sizes (>100k) and not only are the false positives gone, the distribution of the p-values of those tests is perfectly uniform.


text:
Q: Why does replacing malloc() require knowledge of the linker but ::operator new() does not? See linked question.
Difference between global operator new and malloc
The accepted answer states,
"Replacing malloc opens up a can of worms. It can be done, but not portably, because it requires knowledge of the linker."
Why does replacing malloc require knowledge of the linker and why does replacing ::operator new() not?

A: Standard C++ makes provisions for overriding ::operator new. While the implementation is certainly messy and linker-related, a C++ program can just define a different ::operator new and it works. The C++ standard explicitly says: Programs can replace these with their own definitions (etc. etc. various restrictions and details).
malloc on the other hand is an ordinary function defined in an ordinary library, and C (and C++, for that matter) has no facilities for replacing a function like that. You can convince virtually every linker under the sun to link to your libc sans malloc and resolve references to malloc to some code from another library/object file. But you can't just define a different malloc functions since that violates the one-definition rule: You end up with two functions called "malloc" in the program, which is both prohibited by the standard (for non-static, non-anonymous-namespace, non-inline, ... functions) and a serious problem for linkers (most likely, an error or one of the two definitions is dropped).


text:
Q: Safari makes weird noises, even when the sound is closed My netbook is 1.5 years old and it only happens when Safari is opened. Why it happens? I think that the sounds are coming from my HDD. Should I remove Safari completely? Does it harm my netbook?
Latest Safari (5.0.5) on Windows 7 Starter
Netbook with Intel Atom 1.6 Ghz 1.6 GHz processor and 1 GB ram, 160 GB HDD
Brand: Casper

A: I would be more interested in looking at the resources being taken up by your computer when you run Safari (CPU, memory, etc.). Safari in and of itself does not harm the hardware or software.
See if there is a heavy load on the computer during operation of Safari to verify that the computer isn't straining under a bug or something else getting stuck when it runs.


text:
Q: Finding parent of child in breadth first search I'm trying to find the parent of children in breadth first search, considering an unweighted,undirected graph the neighbours are easy to find but I don't get how can I print the parents along with the childs. Here is the code
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package bfs;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;

public class BreadthFirstSearchExample
{

 private Queue<Node> queue;
 static ArrayList<Node> nodes=new ArrayList<Node>();
 static class Node
 {
  int data;
  boolean visited;

  Node(int data)
  {
   this.data=data;

  }
 }

 public BreadthFirstSearchExample()
 {
  queue = new LinkedList<Node>();
 }

 // find neighbors of node using adjacency matrix
 // if adjacency_matrix[i][j]==1, then nodes at index i and index j are connected
 public ArrayList<Node> findNeighbours(int adjacency_matrix[][],Node x)
 {
  int nodeIndex=-1;

  ArrayList<Node> neighbours=new ArrayList<Node>();
  for (int i = 0; i < nodes.size(); i++) {
   if(nodes.get(i).equals(x))
   {
    nodeIndex=i;
    break;
   }
  }

  if(nodeIndex!=-1)
  {
   for (int j = 0; j < adjacency_matrix[nodeIndex].length; j++) {
    if(adjacency_matrix[nodeIndex][j]==1)
    {
     neighbours.add(nodes.get(j));
    }
   }
  }
  return neighbours;
 }

 public  void bfs(int adjacency_matrix[][], Node node)
 {
  queue.add(node);
  node.visited=true;
  int nf =0;
  while (!queue.isEmpty())
  {
   nf = queue.size();
   Node element=queue.remove();
   System.out.print(element.data + "\t");

   ArrayList<Node> neighbours=findNeighbours(adjacency_matrix,element);
   for (int i = 0; i < neighbours.size(); i++) {
    Node n=neighbours.get(i);
    int mf = neighbours.size();

    if(n!=null && !n.visited)
    {
     queue.add(n);
     n.visited=true;
     //System.out.print("neighbours"+ n.data + "\t");
//     System.out.print("vertices" + nf + "\t");
//     System.out.print("degree" + mf + "\t");

    }
   }

  }
 }

 public static void main(String arg[])
 {

   Node node40 =new Node(40);
   Node node10 =new Node(10);
   Node node20 =new Node(20);
   Node node30 =new Node(30);
   Node node60 =new Node(60);
   Node node50 =new Node(50);
   Node node70 =new Node(70);

   nodes.add(node40);
   nodes.add(node10);
   nodes.add(node20);
   nodes.add(node30);
   nodes.add(node60);
   nodes.add(node50);
   nodes.add(node70);
   int adjacency_matrix[][] = {
     {0,1,1,0,0,0,0},  // Node 1: 40
     {1,0,0,1,0,0,0},  // Node 2 :10
     {1,0,0,1,1,1,0},  // Node 3: 20
     {0,1,1,0,1,0,0},  // Node 4: 30
     {0,0,1,1,0,0,1},  // Node 5: 60
     {0,0,1,0,0,0,1},  // Node 6: 50
     {0,0,0,0,1,1,0},  // Node 7: 70
   };
   System.out.println("The BFS traversal of the graph is ");
   BreadthFirstSearchExample bfsExample = new BreadthFirstSearchExample();
   bfsExample.bfs(adjacency_matrix, node40);

 }
}

The output is 40 10 20 30 60 50 70
I want the program to show output as
40 10 parent:40 20 parent:40 30 parent:10 60 parent:20 50 parent:20 70  parent:60


text:
Q: Equality of functors I am wondering how is defined the equality of functors, seems that it is only necessary to show their equality on objects and morphisms, is it necessary to show that the natural transformation between them is the identity?
Thanks for any suggestion

A: There is no "the natural transformation between them".  There is no natural transformation involved at all.  If two functors are equal on all objects and equal on all morphisms, then they are equal, since a functor by definition is just a function on objects together with a function on morphisms (satisfying certain axioms).


text:
Q: How to open webpage in app Im building an app and within this app I want it so when the user clicks a link to open a webpage. I want the webpage to open in-application... so in the app. How would I go about doing this? I know this requires a cordova plugin to do this. I don't want the webpage to open in a browser.

A: You have to use inAppBrowser plugin https://github.com/apache/cordova-plugin-inappbrowser
Then you can use this code to open the web inside the inAppBrowser and the user won't leave your app:
var ref = window.open('http://apache.org', '_blank', 'location=yes');

On a button
<input type="button" value="Open"
    onClick="window.open('http://apache.org', '_blank', 'location=yes');">


text:
Q: Grouping based on most common value I'm having trouble trying to group based on the most common value.
The data that I have is:
ID  Name
327 TypeA
327 TypeA
327 TypeA
327 TypeB
327 TypeB
327 TypeB
327 TypeB

In this case I would want to select ID and the Name "TypeB" as it is the most common value for that ID. So the output would look like:
ID  Name
327 TypeB

Hopefully someone can help with this, thanks.

A: This is called the mode in statistics.  Here is one method:
select id, name
from (select id, name, count(*) as cnt,
             row_number() over (partition by id order by count(*) desc) as seqnum
      from t
      group by id, name
     ) t
where seqnum = 1;

A: here is how to do it using a group by in a subquery
select
    ID,
    Name
from
(
    Select
        ID,
        Name,
        Count(distinct(Name)) as [Count]
    from tablename
    group by
        ID,
        Name
    having Count(distinct(Name)) = MAX(Count(distinct(Name)))
)


text:
Q: Can you have an external user as a manager in a SharePoint profile? In the SharePoint user profiles, there is a field to enter in the manager of a user.

This field is a lookup field, and you can search for internal users to be added to the field as supervisors, but is it at all possible to have external users be assigned as managers?

A: You cannot. Even though external users have a user profile created for them one, the Manager picker will only resolve Users who are member of the tenant and not external accounts (or Guest Users).

A: Manager is synchronized from Active Directory so probably you can't
But you can try invite external user to your AAD. Post HERE. In this scenario you should set this accout (haven't tested).


text:
Q: Nonconvex programming through DCA or CCCP I have an optimization problem in the form of:
$\min_x \quad  u^Tx \\ s.t. \quad (x-\textbf{1/2})^2 - \vert x-\textbf{1/2}\vert \leq \textbf{-1/4}$.
Since the constrained of this problem is not convex, the standard convex programming methods cannot be applied. I learned that DC (difference of convex) programming and convex-concave programming (CCCP) can be used to solve this problem. However, I did understand their differences, or their capability to provide an algorithm (e.g., DCA) to converge to the global optimal solution.
Just to recap, I have two questions:

*

*What are the differences of CCCP and DC programming, especially in terms of their convergence to the global optimal solution?

*Are they convergent to the global optimal solution?!
Any help is appreciated!
Edit:
The shape of the constraint function is as below:

A: I am not sure whether I misunderstand OP's problem.
To solve this problem, why not Dividing the constraint into two parts such that it becomes two convex optimization problems:
\begin{equation}
\begin{array}{cl}
{\min} & {u^T x} \\
{\text{s.t.}} & {(x-\frac{1}{2})^2+(x-\frac{1}{2}) \leq -\frac{1}{4}} \\
{} & {x \leq \frac{1}{2}}
\end{array}
\end{equation}
and
\begin{equation}
\begin{array}{cl}
{\min} & {u^T x} \\
{\text{s.t.}} & {(x-\frac{1}{2})^2-(x-\frac{1}{2}) \leq -\frac{1}{4}} \\
{} & {x \ge \frac{1}{2}}
\end{array}
\end{equation}
Then solve these two convex optimization problem at the same time, and the optimal solution of original problem is the lower objective value.
For DC programming and CCCP, in my humble opinion, I think these two method is the same method, although the first one analyze the problem in dual perspective and the second one describe the method in a more friendly way. In addition, the author of DC programming discusses some more DC decomposition methods.
And both DC programming and CCCP could not converge to global optimal solution.
They are both convergent globally, that means they can converge for any initial point.


text:
Q: Reducing code complexity for GWT I started learn GWT by example on google and my first conclusion is: too much code
Like this:
stocks.add(symbol);
        stocksFlexTable.setText(row, 0, symbol);
        stocksFlexTable.setWidget(row, 2, new Label());
        stocksFlexTable.getCellFormatter().addStyleName(row, 1,
                "watchListNumericColumn");
        stocksFlexTable.getCellFormatter().addStyleName(row, 2,
                "watchListNumericColumn");
        stocksFlexTable.getCellFormatter().addStyleName(row, 3,
                "watchListRemoveColumn");

Does GWT have any extensions for reducing code size and simplifying creating GWT forms?

A: UiBinder (GWT 2.0) could be helpful

A: Nice example (oversimplified but clean conceptually) of GWT UI Design with CSS and HTML is Tags First GWT.
I agree with you that if one follows generic examples from Google documentation it's not a pleasant experience. The things changed lately though but they don't yet get fully reflected in the Google docs. Try the following: before going on with GWT development watch these 2 presentations: Best Practices and Performance Tips.
Without using CSS-based UI design, Event Bus, Command Pattern based GWT-RPC, MVP presentation tier and google-gin (GWT implementation of Guice) it's hard to overcome complexity in GWT just like in any other heavy GUI framework.
If you liked these ideas (described in the presentations above) you might want to consider gwt-dispatch and gwt-presenter that implement some of these patterns.
Few examples are: GWT MVP Example and
Apache Labs Hupa GWT-based webmail
UPDATE:
for latest in MVP design for GWT look for GWT MVP in GWT 2.1 and/or gwt-platform frameworks (among others that may work for you).

A: Geez might help you.
Geez provides easy to use style layouts for GWT and a series of static methods to build commonly used widgets.

A: We use a FormBuilder class to easily and compactly construct forms in code:
ListBox type = ...
TextBox notes = ...

FormBuilder b = new FormBuilder();
b.label("Chart type").field(type).endRow();
b.label("Notes").field(notes).wrap().endRow();
b.add("Some help text").style("help").wrap().endRow();

FlexTable form = b.getForm();
...

It keeps track of the current row and column, styles cells consistently depending on the method used to add them (label, field etc.), ensures consistent spacing, etc etc. Each method returns a FormBuilder to support chaining calls. Things like wrap() apply to the previously added cell.
This class is part of the GWT Portlets framework.

A: Check out http://code.google.com/p/gwt-pectin/ in combination with UiBinder


text:
Q: Splash Image for android I made a splash image to show at the start of my activity..
The image show perfectly.But the problem is when i call this
public class SplashImageActivity extends Activity {
    protected boolean active = true;
    protected int splashTime = 5000; // time to display the splash screen in ms

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);

        // thread for displaying the SplashScreen
        Thread splashTread = new Thread() {
            @Override
            public void run() {
                try {
                    int waited = 0;
                    while(active && (waited < splashTime)) {
                        sleep(100);
                        if(active) {
                            waited += 100;
                        }
                    }
                } catch(InterruptedException e) {
                    // do nothing
                } finally {
                    startActivity(new Intent(SplashImageActivity.this,Myapps.class));
                    finish();
                    //startActivity(new Intent("com.splash.com.MyApps"));
                    //startActivity( new Intent(getApplicationContext(), Myapps.class));
                }
            }
        };
        splashTread.start();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            active = false;
        }
    return true;
    }
}

go for next activity the stop() does not work. And it does not go to this activity. I add all activity in manifest. The stop() shows in code like this

what's the problem?

A: No need to call stop() and call finish() after starting activity
finally
{

    startActivity(new Intent(currentclass.this,nextActivity.class);
    finish();
}

A: I use thread to show the Splash screen, and it works for me:
       @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash);

    mSplashThread =  new Thread(){
        @Override
        public void run(){
            try {
                synchronized(this){
                    wait(4000);
                }
            }catch(InterruptedException ex){
            }
            finish();

            Intent i=new Intent(getApplicationContext(),NextActivity.class);
            startActivity(i);

            interrupt();
        }

    };
    mSplashThread.start();
}

A: Please try below code..
public class Splashscreen extends Activity {
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            Thread t2 = new Thread() {
                public void run() {
                    try {
                        sleep(2000);
                        startActivity( new Intent(getApplicationContext(), Exercise.class));
                        finish();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            t2.start();
        }
    }

A: first thing it is not onStop of Activity so looks you are calling stop function of thread which is Deprecated that's why you are getting the strike line so use other way to stop the thread of use better way to implement the splash ........
as looks you try some thing like this link

A: No need to call stop() just call finish() after starting activity
finally {
startActivity(new Intent(currentclass.this,nextActivity.class);
finish();
}

You can also use handler an postdelayed() to make a splash screen like below
 public class SplashScreenActivity extends Activity{

        private Handler handler;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_splash_screen);

            final Runnable runnable = new Runnable() {

                @Override
                public void run() {
                       Intent intent=new Intent(SplashScreenActivity.this, nextActivity.class);
                       startActivity(intent);
                       finish();

                }
            };
            handler = new Handler();
            handler.postDelayed(runnable, 5000);

        }

    }

You will show your splash screen for 5 seconds and then move to next Activity


text:
Q: Examples of "undoable" applicative functors? I declared a group on applicative functors. Judging by what we usually call "actions", it seems that such group would enable the action to be undone:
import Control.Applicative

class Alternative f => Undoable f where
    undo :: f a -> f a

Being a group, for all x :: Undoable f => f a, the following laws shall satisfy:
x <|> undo x ≡ empty
undo x <|> x ≡ empty

Some instances:
import Control.Arrow
import Data.Functor.Compose
import Data.Functor.Product
import Data.Proxy

instance Undoable Proxy where
    undo _ = Proxy

instance (Undoable f, Applicative g) => Undoable (Compose f g) where
    undo (Compose x) = Compose (undo x)

instance (Undoable f, Undoable g) => Undoable (Product f g) where
    undo (Pair x y) = Pair (undo x) (undo y)

instance Undoable m => Undoable (Kleisli m a) where
    undo (Kleisli f) = Kleisli (undo . f)

At least for me, these instances are of no interest. Some non-instances include:

*

*Maybe: Once successful, it will be always a success regardless of other options.

*[] and ZipList: Options always add nondeterminism, not subtract from it.

*

*ReadP and ReadPrec: As implied by above.

*IO: Taken literally, this instance would be a time machine. Even though we may take the quotient of the reality over time-space, there is a practical counterexample: A new IORef cannot be forgotten.
Is there any particularly interesting instance of Undoable?

A: I would consider something like this. Not a Prelude.Functor because the keys need to be orderable (could also be Hashable or only Eq, you know the tradeoffs).
It's basically a multiset that allows negative multiplicities. Antimatter elements as it were.
import qualified Data.Map as Map
import qualified Prelude as Hask
import Data.List (sortOn)
import Control.Category.Constrained.Prelude
import Control.Arrow.Constrained
import Control.Applicative.Constrained

data Dirac n k = Dirac { getOccurences :: Map.Map k n }

instance Real n => Functor (Dirac n) (Ord⊢(->)) (->) where
  fmap (ConstrainedMorphism f) (Dirac m)
    = Dirac . Map.fromAscList
            . concatMap (\((k,n₀):grp) -> case sum $ n₀ : map snd grp of
                     0 -> []
                     μ -> [(k,μ)] )
            . groupBy (comparing fst)
            . sortOn fst
            . map (first f)
            $ Map.toList m

with
instance Num n => Undoable (Dirac n) where
  undo (Dirac m) = Dirac $ Map.map negate m

I think there can be a conforming Applicative / Alternative built around this, but I'm not completely sure.

A: Any monoid can be lifted to an Alternative:
newtype ViaMonoid m a = ViaMonoid m

instance Monoid m => Applicative (ViaMonoid m) where
    pure _ = ViaMonoid mempty
    ViaMonoid f <*> ViaMonoid x = ViaMonoid (f <> x)

instance Monoid m => Alternative (ViaMonoid m) where
    empty = ViaMonoid mempty
    ViaMonoid m <|> ViaMonoid m' = ViaMonoid (m <> m')

Any group can be lifted to Undo:
class Monoid g => Group g where
    -- law: g <> inverse g = inverse g <> g = mempty
    inverse :: g -> g

instance Group g => Undoable (ViaMonoid g) where
    undo (ViaMonoid m) = ViaMonoid (inverse m)

ViaMonoid is also known by the more traditional name Const, and is used to good effect in e.g. lens and friends.


text:
Q: Product form in admin: adding a field in the basic area I have added a custom attribute to the product entity. It is visible in the back-office, and the value is properly saved, it works fine.
However, using the .xml file, I would like to override the display (for exemple, for a select yes/no, I would like to use the built-in switch icon of Magento).
To do that, I have to add a xml file to my module, and write inside the data related to my field, in a specific fieldset.
The problem is here, I don't know the name of the basic (default) fieldset in the product form. I managed to do it in the category form, but not in the product one. Any Idea?


text:
Q: Laravel difference between command and jobs I'm trying to understand what are the differences between jobs and commands.
I was reading the documentation and it seems that both jobs and commands have similar structure and both of the can be scheduled with the difference that jobs can also be queued.
And i was wondering if the only difference is that jobs can be queued, because it seems to me that they have overlap functionalities.

A: Usually, we use the command to execute a particular function or a job at a particular time or frequency. And we can call command via terminal. But the job cannot be called via terminal. Jobs can be queued. Also, you can execute Job at a particular time. But it is not a repetitive event.


text:
Q: Platform and Plugin Updates: A new version of Android Studio is available! (show balloon)  I am getting this in my Log cat Window from last week. What if I will update? I am little nervous if new version will be different from which i m using Android 1.5.1
After pressing "Available" in Log Cat I get
What to do now.?

A: Change is always good in the long run.
If the new version is a stable version,you should switch.You can check latest stable build here.
You can see this video to run 2 different versions parallely if you want to have a preview
You can see release notes to see what has been updated .
Android Studio 2.0 has instant run for builds which will save you a lot of time.

A: Update wouldn't change IDE drastically. You will only get newly features which are added in every updated addition.
like Android Studio v2.0.0 has Instant Run feature

Android Studio now deploys clean builds faster than ever before.
  Additionally, pushing incremental code changes to the emulator or a
  physical device is now almost instantaneous. Review your updates
  without redeploying a new debug build or, in many cases, without
  restarting the app.

Read Android Studio Release Notes.


text:
Q: Function to add and delete from JSON object I have two categories "A" and "B". On Click any button of category "A" removes the button and must move to category "B", On Click any button of category "B" adds the button to category "A" and must move from category "B".
export const LauncherButtons = [
{
    linked: false,
    type: 'ABC',
    name: 'ReactJs'
},
{
    linked: false,
    type: 'ABC',
    name: 'VueJS'
},
{
    linked: true,
    type: 'XYZ',
    name: 'Angular'
},
{
    linked: true,
    type: 'XYZ',
    name: 'Javascript'
}
];

This is what I am rendering for category "A".
 { LauncherButtons.map((button,index) => {
                return(
                button.linked === true &&
               <LauncherActionButton
                text={button.name}
                onClick = {this.removeAction}/>
                 );
            })}

Rendering category "B".
{ LauncherButtons.map((button,index) => {
                  return(
                  button.linked !== true &&
                 <LauncherActionButtonAdd
                  textAdd={button.name}
                  onClick = {this.addAction}/>
                   );
                })}

So basically, when I click on a button of category "A" (True) it should move to category "B" and become false, similarly, when I click on a button of category "B" (False) it should become true and move to category "A".

A: Try something like this: https://codesandbox.io/s/holy-leftpad-hw1oe
I've laid out two sections, an active and inactive section. By clicking on a button, you move it to the opposite side. I don't know what your LauncherActionButton component looks like so consider this like a bare-bones template.
import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

export const LauncherButtons = [
  {
    linked: false,
    type: "ABC",
    name: "ReactJs"
  },
  {
    linked: false,
    type: "ABC",
    name: "VueJS"
  },
  {
    linked: true,
    type: "XYZ",
    name: "Angular"
  },
  {
    linked: true,
    type: "XYZ",
    name: "Javascript"
  }
];

class App extends React.Component {
  state = {
    buttons: LauncherButtons
  };

  createActiveButtons = () => {
    const { buttons } = this.state;
    return buttons
      .filter(button => {
        return button.linked;
      })
      .map(activeButton => {
        return (
          <button onClick={this.handleOnClick} name={activeButton.name}>
            {activeButton.name}
          </button>
        );
      });
  };

  createInactiveButtons = () => {
    const { buttons } = this.state;
    return buttons
      .filter(button => {
        return !button.linked;
      })
      .map(inactiveButton => {
        return (
          <button onClick={this.handleOnClick} name={inactiveButton.name}>
            {inactiveButton.name}
          </button>
        );
      });
  };

  handleOnClick = event => {
    const { buttons } = this.state;
    const { name } = event.target;

    let updatedButtons = buttons.map(button => {
      if (button.name === name) {
        return {
          ...button,
          linked: !button.linked
        };
      } else {
        return button;
      }
    });

    this.setState({
      buttons: updatedButtons
    });
  };

  render() {
    return (

          {this.createActiveButtons()}

          {this.createInactiveButtons()}

    );
  }
}

A: What about using the item as a parameter? for example:
removeAction(button) {
  // change button however you like
}

// in the render method
{
  LauncherButtons.map((button, index) => {
    return (
      button.linked  &&
      <LauncherActionButton
        text={button.name}
        onClick={() => removeAction(button)}/>
    );
  })
}


text:
Q: How do I cycle through multiple lines with a javascript letter randomiser? Ok so I have this code for a JavaScript letter randomiser that works perfectly fine, i'm just having trouble figuring out how i'd get it to produce more than just one line while still keeping my code relatively efficient.
Ideally id like it to say something like this and then cycle back to the start:
Hi, my name is Yeet
this is my website
I like making cool stuff
take a look around :)
Any help would be greatly appreciated :)))
window.onload = function() {
    var theLetters = "abcdefghijklmnopqrstuvwxyz#%&^+=-";
    var cntnt = "Hi, my name is Yeet";
    var speed = 20; // ms per frame
    var increment = 2; // frames per step
    var clen = cntnt.length;
    var si = 0;
    var stri = 0;
    var block = "";
    var fixed = "";
    //Call self x times, whole function wrapped in setTimeout
    (function rustle(i) {
        setTimeout(function() {
            if (--i) {
                rustle(i);
            }
            nextFrame(i);
            si = si + 1;
        }, speed);
    })(clen * increment + 1);

    function nextFrame(pos) {
        for (var i = 0; i < clen - stri; i++) {

            var num = Math.floor(theLetters.length * Math.random());
            //Get random letter
            var letter = theLetters.charAt(num);
            block = block + letter;
        }
        if (si == (increment - 1)) {
            stri++;
        }
        if (si == increment) {
            // Add a letter;
            // every speed*10 ms
            fixed = fixed + cntnt.charAt(stri - 1);
            si = 0;
        }
        $("#output").html(fixed + block);
        block = "";
    }
};

A: Make cntnt an array
    var cntnt = ["Hi, my name is Yeet", "This is my website", "I like making cool stuff", "take a look around :)"];

and use pos % cntnt.length as the array index.
            fixed = fixed + cntnt[pos % cntnt.length].charAt(stri - 1);


text:
Q: Limiting behavior of an integral involving incomplete Gamma function I am wondering about the limiting behavior as $k\rightarrow\infty$ of the following integral:
$$I(k)=\frac{2^{-k/2}}{\Gamma(k/2)}\int_{f(k)}^\infty t^{k/2-1}e^{-t/2}\left(\frac{\gamma\left(\frac{k}{2},\frac{t-f(k)}{2}\right)}{\Gamma(k/2)}\right)^{g(k)-1}dt$$
where $\Gamma(z)=\int_0^\infty t^{z-1}e^{-t}dt$ is the Gamma function, $\gamma(s,x)=\int_0^x t^{s-1}e^{-t}dt$ is the lower incomplete Gamma function, function $g(x)$ is asymptotically greater than $k$, i.e. $g(k)=\omega(k)$ (for example, $g(k)$ could be $k^2$), and $f(k)$ is function that is asymptotically greater than $\sqrt{k/\log(g(k))}$ (that is, $f(k)=\omega(\sqrt{k/\log(g(k))})$).  Specifically, I am wondering if $\lim_{k\rightarrow\infty}I(k)=1$ or $\lim_{k\rightarrow\infty}I(k)=0$ or if it converges to some other number.

Where this comes from
Suppose that I have a sequence of $g(k)$ i.i.d. random variables $X_1,X_2,\ldots,X_{g(k)}$ on $[0,\infty)$ and that I order their realizations in a decreasing order: $X^{(1)}\geq X^{(2)}\geq\ldots\geq X^{(g(x))}$.  The probability that the difference between the maximum $X^{(1)}$ in this sequence and the second largest $X^{(2)}$ exceeds $f(k)$ can be written down as follows:
$$P\left[X^{(1)}-X^{(2)}\geq f(k)\right]=\int_{f(k)}^\infty f_X(t)[F_X(t-f(k))]^{g(k)-1}dt$$
where $f_X(t)$ and $F_X(t)$ are respectively the probability density and cumulative distribution functions of $X$.
I am interested in learning the complimentary cumulative distribution function for the difference between largest and second-largest elements in a sequence of i.i.d. chi-squared random variables with $k$ degrees of freedom.


text:
Q: RESTful Web Service in JSON format I'm new in Restful. i need to create a simple restful that adding 2 inputs in JSON format and return the result also in JSON that i can test it in Postman. if introduce any tutorial or article would be great.
Regards
Babak

A: You can also find a simple spring boot restful web service project under below github link
github Spring boot Employee Service


text:
Q: Forecasting with ARIMA and dummy variables I am attempting to include a dummy regressor that notes the beginning of the pandemic and runs a regression with ARIMA errors.
My dataset revolves around breaking & entering's happening in Toronto from 2014 to 2021. The issue is that the trend takes a turn due to covid-19 around 2020.
Auto.arima provides me with a ARIMA(1,0,1) model as it is not taking into account the impact of covid-19 and is performing according to the implied return to the series average.
When trying to include a dummy regressor that notes the beginning of the pandemic and run a regression with ARIMA errors I get the following error:
In ifelse(time(BEDATA_GROUPEDtsssarima) >= yearmonth("2020-03"),  :
  Incompatible methods ("Ops.ts", ">=.vctrs_vctr") for ">="

Code:
# Create a binary time series that indicates the start of the pandemic
library(fpp3)
library(forecast)
library(zoo)

# Check if timeseries
class(BEDATA_GROUPED)

#Convert timeseries
BEDATA_GROUPEDtsssarima <- ts(BEDATA_GROUPED[,2], frequency = 12, start = c(2014, 1))
class(BEDATA_GROUPEDtsssarima)

#Plot
forecast::autoplot(BEDATA_GROUPEDtsssarima)

# Assume that the pandemic began in March 2020
pandemic_dummy <- ifelse(time(BEDATA_GROUPEDtsssarima) >= yearmonth("2020-03"), 1, 0)

# Use auto.arima() to fit an ARIMA model with the dummy variable as an exogenous variable
beddatamodel <- auto.arima(BEDATA_GROUPEDtsssarima, xreg = pandemic_dummy, ic="aic", trace = TRUE)

# Create a binary time series that indicates the start of the pandemic
# In this example, we will assume that the pandemic began in March 2020
pandemic_dummy <- ifelse(time(BEDATA_GROUPEDtsssarima) >= yearmonth("2020-03"), 1, 0)

# Use auto.arima() to fit an ARIMA model with the dummy variable as an exogenous variable
beddatamodel <- auto.arima(BEDATA_GROUPEDtsssarima, xreg = pandemic_dummy, ic="aic", trace = TRUE)

# Create a binary time series for the forecast period that includes the pandemic dummy variable
forecast_period <- time(BEDATA_GROUPEDtsssarima)["2022/01/01/":"2023/12/31/"]
pandemic_dummy_forecast <- ifelse(forecast_period >= yearmonth("2020-03"), 1, 0)

# Use the forecast()
forecast(pandemic_dummy_forecast)

Dataset:
structure(list(occurrence_yrmn = c("2014-January", "2014-February",
"2014-March", "2014-April", "2014-May", "2014-June", "2014-July",
"2014-August", "2014-September", "2014-October", "2014-November",
"2014-December", "2015-January", "2015-February", "2015-March",
"2015-April", "2015-May", "2015-June", "2015-July", "2015-August",
"2015-September", "2015-October", "2015-November", "2015-December",
"2016-January", "2016-February", "2016-March", "2016-April",
"2016-May", "2016-June", "2016-July", "2016-August", "2016-September",
"2016-October", "2016-November", "2016-December", "2017-January",
"2017-February", "2017-March", "2017-April", "2017-May", "2017-June",
"2017-July", "2017-August", "2017-September", "2017-October",
"2017-November", "2017-December", "2018-January", "2018-February",
"2018-March", "2018-April", "2018-May", "2018-June", "2018-July",
"2018-August", "2018-September", "2018-October", "2018-November",
"2018-December", "2019-January", "2019-February", "2019-March",
"2019-April", "2019-May", "2019-June", "2019-July", "2019-August",
"2019-September", "2019-October", "2019-November", "2019-December",
"2020-January", "2020-February", "2020-March", "2020-April",
"2020-May", "2020-June", "2020-July", "2020-August", "2020-September",
"2020-October", "2020-November", "2020-December", "2021-January",
"2021-February", "2021-March", "2021-April", "2021-May", "2021-June",
"2021-July", "2021-August", "2021-September", "2021-October",
"2021-November", "2021-December"), MCI = c(586, 482, 567, 626,
625, 610, 576, 634, 636, 663, 657, 556, 513, 415, 510, 542, 549,
618, 623, 666, 641, 632, 593, 617, 541, 523, 504, 536, 498, 552,
522, 519, 496, 541, 602, 570, 571, 492, 560, 525, 507, 523, 593,
623, 578, 657, 683, 588, 664, 582, 619, 512, 630, 644, 563, 654,
635, 732, 639, 748, 719, 567, 607, 746, 739, 686, 805, 762, 696,
777, 755, 675, 704, 617, 732, 609, 464, 487, 565, 609, 513, 533,
505, 578, 526, 418, 428, 421, 502, 452, 509, 492, 478, 469, 457,
457)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
-96L))

A: I see you have used the fpp3 library, so I've had a go using the tidyverts tools. I've had a go at three models: a plain ARIMA, a plain regression using the pandemic dummy variable, and a dynamic model using both ARIMA and the dummy variable.
Hope this helps! :-)
library(tsibble)
library(fable)
library(fabletools)
library(feasts)
library(dplyr)

Create a tsibble:
BEDATA_GROUPED <- BEDATA_GROUPED |>
  mutate(Month = yearmonth(occurrence_yrmn)) |>
  as_tsibble(index = Month)

autoplot(BEDATA_GROUPED)

Assume that the pandemic began in March 2020
and create a dummy variable:
pandemic_start <- yearmonth("2020-03-01")
BEDATA_GROUPED <- BEDATA_GROUPED |>
  mutate(pandemic_dummy = ifelse(Month >= pandemic_start, 1, 0))

Work up a plain ARIMA:
BEDATA_GROUPED_arima <- BEDATA_GROUPED |>
  model(ARIMA(MCI, stepwise = FALSE))

BEDATA_GROUPED_arima |>
  gg_tsresiduals()

BEDATA_GROUPED_arima |>
  forecast(h = 5) |>
  autoplot()

Work up a plain regression:
BEDATA_GROUPED_TSLM <- BEDATA_GROUPED |>
  model(TSLM(MCI ~ pandemic_dummy)) |>
  report()

BEDATA_GROUPED_TSLM |>
  gg_tsresiduals()

Make a data set to predict on:
new_data <- structure(list(Month = structure(c(18993, 19024, 19052, 19083,
                                               19113), class = c("yearmonth", "vctrs_vctr")), pandemic_dummy = c(1,
                                                                                1, 1, 1, 1)), class = c("tbl_ts", "tbl_df", "tbl", "data.frame"
                                                                                ), row.names = c(NA, -5L), key = structure(list(.rows = structure(list(
                                                                                1:5), ptype = integer(0), class = c("vctrs_list_of", "vctrs_vctr",
                                                                                "list"))), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA,
                                                                                -1L)), index = structure("Month", ordered = TRUE), index2 = "Month", interval = structure(list(
                                                                                year = 0, quarter = 0, month = 1, week = 0, day = 0, hour = 0,
                                                                                minute = 0, second = 0, millisecond = 0, microsecond = 0,
                                                                                nanosecond = 0, unit = 0), .regular = TRUE, class = c("interval",
                                                                                "vctrs_rcrd", "vctrs_vctr")))

Forecast plain regression:
BEDATA_GROUPED_TSLM |>
  forecast(new_data = new_data) |>
  autoplot()

Work up a dynamic regression, with ARIMA and the pandemic dummy variablee:
BEDATA_GROUPED_dyn_ARIMA <- BEDATA_GROUPED |>
  model(ARIMA(MCI ~ pandemic_dummy)) |>
  report()

BEDATA_GROUPED_dyn_ARIMA |>
  gg_tsresiduals()

BEDATA_GROUPED_dyn_ARIMA |>
  forecast(new_data = new_data) |>
  autoplot()


text:
Q: How to manage raw data (bitstream or bytestream) in .NET 4.0? My C# .NET 4.0 application needs to access data in the filesystem and access them as a bitstream or bytestream. What I need is the following:

*

*Splitting a data block into two sequential data blocks.

*Merging two datablocks by attaching one to the other.

*Access bytes or bits.

*Storing the data block in the filesystem.

*Loading a data block from the filesystem.

That's it. What is the best practice to do this in .NET 4.0?
Thankyou

A: Start reading this: C# Input/Output Classes Simplified


text:
Q: Building 64 bit rpm on 32 bit rpmbuild system Are there any way for building x86_64 arch target rpm on a 32 bit rpmbuild build system?
$ rpmbuild -ba --target=x86_64 kernel64.spec
Building target platforms: x86_64
Building for target x86_64
error: No compatible architectures found for build

I have also tried setarch.
$ setarch x86_64 rpmbuild -ba --target=x86_64 kernel64.spec
setarch: x86_64: Unrecognized architecture

A: You can set up an x86_64 chroot (assuming the cpu can do both x86_64/ix86),
or you can attempt a cross compiler to build x86_64 on ix86.
The issue is often that ix86 gcc tools do not support x86_64.


text:
Q: Add a value to pandas index I have 2 dataframes which i want to merge without duplicating columns:
First i'm getting only unique columns from second dataframe( As in this answer):
cols_to_use = df2.columns.difference(df1)

I need to keep one column which is the unique identifier for me, with the name complete_name
Right now, cols_to_use does not contain complete_name because it was marked as duplicate, how can i add it? I've tried:
cols_to_use.append(pd.Index(['complete_name']))

But it does nothing. Any help?

A: For me it working nice:
df1 = pd.DataFrame({'A':list('abcdef'),
                   'B':[4,5,4,5,5,4],
                   'C':[7,8,9,4,2,3],
                   'D':[1,3,5,7,1,0],
                   'E':[5,3,6,9,2,4],
                   'F':list('aaabbb')})

cols_to_use = df1.columns.difference(['A','C'])
print (cols_to_use)
Index(['B', 'D', 'E', 'F'], dtype='object')

print (cols_to_use.append(pd.Index(['complete_name'])))
Index(['B', 'D', 'E', 'F', 'complete_name'], dtype='object')

print (cols_to_use.union(['complete_name']))
Index(['B', 'D', 'E', 'F', 'complete_name'], dtype='object')


text:
Q: In which format are images gathered from the getUser function from the kik API With the functions
kik.photo.get(options, callback)

kik.photo.getFromCamera(options, callback)

kik.photo.getFromGallery(options, callback)

I can receive photos in Data URL Format.
I also can receive the profile picture and thumbnail with
kik.getUser()

However the documentation ( http://dev.kik.com/docs/ ) doesn`t state in which format the images are received using this function and it doesn't seem to be Data-URL, so my question is.
In which format are thumbnail and profile pictures returned when using the kik.getUser() function.

A: It returns a URL to an image hosted on a CDN (not a data URI). That images on the CDN are jpeg-encoded


text:
Q: Reporting regression tables using rmarkdown in Word format Trying to report regression tables in Word format using rmarkdown seems impossible. After trying hours and several options like here no one worked in my case. I want to report lm models using markdown and render to a .doc file.
Method 1:
Using memisc package to create a mtable object and render using pander:
> lm0 <- lm(hp ~ wt, mtcars)
> lm1 <- lm(qsec ~ hp, mtcars)
> lm2 <- lm(qsec ~ wt, mtcars)
>
> library(memisc)
>
> mt <- mtable(lm0, lm1, lm2)
>
> pander::pander(mt)
Error in x[[i]] : subíndice fuera de  los límites
Además: Warning message:
In pander.default(mt) :
  No pander.method for "memisc_mtable", reverting to default.

Method 2:
Create a html object and include using includeHTML. So far this is the closed method to my desire output. However the table only contains one column like this:
```{r}
stargazer::stargazer(lm0, lm1, lm2, type = "html", title = "Results", out = "./pp.html")
shiny::includeHTML("pp.html")
```

Code above produces this in a word document:

Method 3:
Using xtable also produces the same output above.
Any suggestions?

A: Use write_html (from the memisc package):
write_html(mt, "mt.html")

Now open the mt.html file in Word.  This is what it looks like in Word. (continued after screenshot)

Alternately use this to convert filePathIn (which is the path to the html file created) to filePathOut (which is the path to the docx file to be created from it).  This works on Windows and even in cases where pandoc does not as it uses Word itself to do the translation from html to docx. (If you want a doc file rather than docx then replace "docx" with "doc" in the filePathOut definition and replace 16 with 0 in the SaveAs line.  See wdSaveFormat Enumeration.)
library(RDCOMClient)

filePathIn <- file.path(getwd(), "mt.html")
filePathOut <- sub("html$", "docx", filePathIn)

w <- COMCreate("Word.Application")
doc <- w[["Documents"]]
od <- doc$Open(filePathIn)
od$SaveAs(filePathOut, 16)
w$Quit()

A: Here is a simplistic way to store regression outputs:
sink("myresult.doc", append=T)

All outputs will be appending automatically as long as this is specified: append=T
HTH


text:
Q: Can't get user email from Plumier social login with Google provider I created a React app with social login like this example, but the email field returned always null.
I check my configuration on the google developer console its already include email scope.
My auth controller is just simply like the example
class AuthController {
    @oAuthCallback(new GoogleProvider(process.env.GOOGLE_CLIENT_ID, process.env.GOOGLE_SECRET))
    async google(@bind.loginStatus() login: GoogleLoginStatus, state: string, @bind.cookie("csrf:key") secret: string) {

        //the login.data.email <--- always null

    }
}

Am I missing something?

A: On current version 1.0.0-beta.11, the default scope parameter for the google authorize endpoint (dialog endpoint) is just https://www.googleapis.com/auth/userinfo.profile, I will fix this issue and will be ready on the next stable release.
For workaround, you can return the scope parameter manually on your dialog endpoint like below
export class DialogsController {

    @oAuthDialogEndPoint(new GoogleDialogProvider(<your callback>, <your client id>))
    google() {
        return { scope: "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile" }
    }
}

Note that the scope parameter is a space separated scope like described here


text:
Q: Buffer overflow protection for stackalloc in .Net From C# reference for stackalloc:

the use of stackalloc automatically enables buffer overrun detection features in the common language runtime (CLR). If a buffer overrun is detected, the process is terminated as quickly as possible to minimize the chance that malicious code is executed.

Specifically, what kind of protection mechanism is implemented for .NET?
And will it also detect buffer underruns?
Against which known attacks is the protection weaker?
For a context, for example for MS C++ compiler the information is available here:
Windows ISV Software Security Defenses:

The Stack Buffer Overrun Detection capability was introduced to the C/C++ compiler in Visual Studio .NET 2002 and has been updated in subsequent versions. /GS is a compiler switch that instructs the compiler to add startup code, and function epilog and prolog code, to generate and check a random number that is placed in a function's stack.
Note that Visual C++ 2005 (and later) also reorders data on the stack to make it harder to predictably corrupt that data. Examples include:
  • Moving buffers to higher memory than non-buffers. This step can help protect function pointers that reside on the stack.
  • Moving pointer and buffer arguments to lower memory at run time to mitigate various buffer overrun attacks.

A: Yes, the .NET jitter generates the kind of stack canary checking that also exists in native code generated by the Microsoft C/C++ compiler with the /GS compiler option.  The basic scheme is to store a random 32-bit value at the top of the stack, written at method entry.  At method exit it checks if the value is still there.  A change in the value is a very high predictor for a stack buffer overflow, the kind that malware uses to take control of a program.
Some code to play with:
class Program {
    static void Main(string[] args) {
        Kaboom();
    }
    static unsafe void Kaboom() {
        byte* ptr = stackalloc byte[1];
        for (int ix = 0; ix < 42; ++ix) ptr[ix] = 0;
    }
}

Running this code triggers the Windows Error Reporting dialog, even with the debugger attached.  You can see the crash reason in the Output window:

The program '[3636] ConsoleApplication33.exe: Native' has exited with code -1073740791 (0xc0000409).

The exception code is defined in the ntstatus.h SDK header file:
//
// MessageId: STATUS_STACK_BUFFER_OVERRUN
//
// MessageText:
//
// The system detected an overrun of a stack-based buffer in this application. This overrun could
// potentially allow a malicious user to gain control of this application.
//
#define STATUS_STACK_BUFFER_OVERRUN      ((NTSTATUS)0xC0000409L)    // winnt

You can see the code that does this with Debug + Windows + Disassembly.  The essential parts of Kaboom:
00000000  push        ebp                               ; setup stack frame
00000001  mov         ebp,esp
00000003  sub         esp,8                             ; stack space for local variables
00000006  xor         eax,eax
00000008  mov         dword ptr [ebp-8],eax             ; zero-initialize local variables
0000000b  mov         dword ptr [ebp-4],eax
0000000e  mov         dword ptr [ebp-4],esp
00000011  mov         dword ptr [ebp-8],0EDDB7EDFh      ; canary stored here

// For loop code omitted

0000002d  cmp         dword ptr [ebp-8],0EDDB7EDFh      ; check canary value
00000034  je          0000003B
00000036  call        727767A8                          ; crash program
0000003b  lea         esp,[ebp]                         ; normal exit, pop stack frame
0000003e  pop         ebp
0000003f  ret

The actual canary value changes every time the code is jitted.


text:
Q: Remove Etag from favicon.ico using yslow on a project I am experiencing a "problem" I can not solve.
Yslow keeps complaining:

There is 1 component with misconfigured ETags http://www.domain.com/favicon.ico

I have the following in my .htaccess file
# Add Proper MIME-Type for Favicon
AddType image/x-icon .ico

# Enable Apache's mod_expires Module
ExpiresActive On
ExpiresByType image/x-icon "access plus 6 month"

<ifModule mod_headers.c>
  Header unset ETag
</ifModule>
FileETag None

Does anybody have an idea how to fix it?

A: Add this:
ExpiresByType image/ico "access plus 1 years"

My .htaccess file:
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault A0
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/ico "access plus 1 month"
    ExpiresByType text/css "access plus 1 week"
    ExpiresByType text/javascript "access plus 1 week"
    ExpiresByType application/javascript "access plus 1 week"
    ExpiresByType application/x-javascript "access plus 1 week"
    ExpiresByType image/x-icon "access plus 1 year"
    ExpiresByType image/ico "access plus 1 years"
</IfModule>

Header unset ETag
FileETag None

A: Hmmm. this did not fix the issue for me in Drupal ( 7 ).
Adding these lines to my .htaccess file:
  ExpiresActive On
  ExpiresByType image/x-icon A604800

Also added this line to my apache http config: (but can also be in your .htaccess file)
  FileETag None

And i disabled the icon / default icon on the admin/appearance/settings/[theme_name] page.
And finally copied the favicon.ico file to my site root and this DID fix this problem for me.
Kinda looks like something is wrong in Drupal here? :/

A: none above helped for me but this works excellent:
<FilesMatch "favicon.ico">
    Header unset ETag
    FileETag None
</FilesMatch>


text:
Q: como importar um projeto play framework 2.5 para o eclipse Olá como poderia importar um projeto lay framework para o eclipse, nas versões anteriores apenas o comando eclipse dentro do projeto já era o bastante mas agora a documentação está um pouco confusa nesse aspecto.

A: Apos iniciar o console do play, de o camando eclipse na pasta do projeto:
$ play new projeto_01
$ cd projeto_01
$ play

[projeto_01] $ eclipse

o comando eclipse vai gerar os arquivos para importar o projeto. Depois é só abrir o eclipse e ir em File->import, n janela que aparecerá, escolha General->Existing Projects into Workspace e click em Next. A próxima janela pedira o caminho do projeto (tente deixar o seu projeto play no mesmo diretório dos projetos eclipse) e selecione seu projeto play e confirma.


text:
Q: can I transform the values into columns on a dataframe? In Python imagine I have this as my dataframe, a list of songs and their groups

Song Title
Category

Hello
Pop

Night Fever
Rock

Dancing
Pop

My Star
Metal

I want to be able to transform all the values under "category" into a new dataframe, so the values are columns, and under each column, it lists the songs. See below for desired outcome...

Pop
Rock
Metal

Hello
Night Fever
My Star

Dancing

I'm sure theres a simple code for this in either pyhton or pandas, any help would be appreciated.
Thanks


text:
Q: How to get requested librairies of gridwars? I would like to get a list of libraries requested by Gridwars executable.
I one year ago used ldd but
moi@myComputer:/opt/gridwars/gridwars_lin$ ldd gridwars
    not a dynamic executable

After browsing the Internet, I found
moi@myComputer:/opt/gridwars/gridwars_lin$ readelf -d gridwars

Dynamic section at offset 0x70014 contains 27 entries:
  Tag        Type                         Name/Value
 0x00000001 (NEEDED)                     Shared library: [libX11.so.6]
 0x00000001 (NEEDED)                     Shared library: [libGL.so.1]
 0x00000001 (NEEDED)                     Shared library: [libGLU.so.1]
 0x00000001 (NEEDED)                     Shared library: [libXxf86vm.so.1]
 0x00000001 (NEEDED)                     Shared library: [libstdc++.so.5]
 0x00000001 (NEEDED)                     Shared library: [libm.so.6]
 0x00000001 (NEEDED)                     Shared library: [libpthread.so.0]
 0x00000001 (NEEDED)                     Shared library: [libc.so.6]
 0x0000000c (INIT)                       0x804a284
 0x0000000d (FINI)                       0x80b29bd
 0x00000004 (HASH)                       0x8048168
 0x00000005 (STRTAB)                     0x8049268
 0x00000006 (SYMTAB)                     0x8048678
 0x0000000a (STRSZ)                      2091 (bytes)
 0x0000000b (SYMENT)                     16 (bytes)
 0x00000015 (DEBUG)                      0x0
 0x00000003 (PLTGOT)                     0x80b811c
 0x00000002 (PLTRELSZ)                   1408 (bytes)
 0x00000014 (PLTREL)                     REL
 0x00000017 (JMPREL)                     0x8049d04
 0x00000011 (REL)                        0x8049cd4
 0x00000012 (RELSZ)                      48 (bytes)
 0x00000013 (RELENT)                     8 (bytes)
 0x6ffffffe (VERNEED)                    0x8049c14
 0x6fffffff (VERNEEDNUM)                 4
 0x6ffffff0 (VERSYM)                     0x8049a94
 0x00000000 (NULL)                       0x0

Right I have a list of the requested shared objects.  But this still cause me some trouble : I cannot understand two things...
As proposed in comment, we may want to run file utility on the executable.
moi@mycomputer:/opt/gridwars/gridwars_lin$ file gridwars
gridwars: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.2.0, stripped

*

*How can I check if one ".so" file/shared object is available?

*Why the hell the gridwars executable is not an executable?  I remember the thing to be a executable and even having found a magic command in three letters that list requested shared objects and if there were available.
Thanks for any help.

A: After installing the following package,
sudo apt-get install libc6:i386
sudo apt-get install libxxf86vm1:i386
sudo apt-get install libglu1-mesa:i386
sudo apt-get install libstdc++5:i386

You get
moi@somewhere:/opt/gridwars/gridwars_lin$ ldd gridwars
    linux-gate.so.1 =>  (0xf77b2000)
    libX11.so.6 => /usr/lib/i386-linux-gnu/libX11.so.6 (0xf765d000)
    libGL.so.1 => /usr/lib/i386-linux-gnu/mesa/libGL.so.1 (0xf7604000)
    libGLU.so.1 => /usr/lib/i386-linux-gnu/libGLU.so.1 (0xf757c000)
    libXxf86vm.so.1 => /usr/lib/i386-linux-gnu/libXxf86vm.so.1 (0xf7576000)
    libstdc++.so.5 => /usr/lib/i386-linux-gnu/libstdc++.so.5 (0xf74bc000)
    libm.so.6 => /lib/i386-linux-gnu/libm.so.6 (0xf7479000)
    libpthread.so.0 => /lib/i386-linux-gnu/libpthread.so.0 (0xf745e000)
    libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xf72a9000)
    libxcb.so.1 => /usr/lib/i386-linux-gnu/libxcb.so.1 (0xf7287000)
    libdl.so.2 => /lib/i386-linux-gnu/libdl.so.2 (0xf7282000)
    libglapi.so.0 => /usr/lib/i386-linux-gnu/libglapi.so.0 (0xf726b000)
    libXext.so.6 => /usr/lib/i386-linux-gnu/libXext.so.6 (0xf7259000)
    libXdamage.so.1 => /usr/lib/i386-linux-gnu/libXdamage.so.1 (0xf7254000)
    libXfixes.so.3 => /usr/lib/i386-linux-gnu/libXfixes.so.3 (0xf724d000)
    libX11-xcb.so.1 => /usr/lib/i386-linux-gnu/libX11-xcb.so.1 (0xf724a000)
    libxcb-glx.so.0 => /usr/lib/i386-linux-gnu/libxcb-glx.so.0 (0xf7232000)
    libxcb-dri2.so.0 => /usr/lib/i386-linux-gnu/libxcb-dri2.so.0 (0xf722d000)
    libdrm.so.2 => /usr/lib/i386-linux-gnu/libdrm.so.2 (0xf721f000)
    libstdc++.so.6 => /usr/lib/i386-linux-gnu/libstdc++.so.6 (0xf7136000)
    libgcc_s.so.1 => /lib/i386-linux-gnu/libgcc_s.so.1 (0xf7119000)
    /lib/ld-linux.so.2 (0xf77b3000)
    libXau.so.6 => /usr/lib/i386-linux-gnu/libXau.so.6 (0xf7115000)
    libXdmcp.so.6 => /usr/lib/i386-linux-gnu/libXdmcp.so.6 (0xf710e000)

And the game works.

A: How to install Gridwars 2
Open terminal and run these:
mkdir gridwars && cd gridwars
wget http://gridwars.marune.de/bin/gridwars_lin.zip
unzip gridwars_lin.zip
./gridwars

I then got this error:
[wilf@comp gridwars]$ ./gridwars
./gridwars: error while loading shared libraries: libstdc++.so.5: cannot open shared object file: No such file or directory

So I had to install the libstdc 5 - I - I found an rpm instead so installed that on my Fedora 19 machine.
It then worked very well - nice game