text:
Q: Unity Android Plugin for GCM is Unable to Start Service Intent on Receive I am currently working on a plugin for unity that will make use of GCM for push notifications and cannot seem to resolve this issue. I followed the steps on the Google Developers site and managed to get the app to register and receive messages from the server. However, once the GcmReceiver gets the message, my logcat outputs the following error:
Unable to start service Intent { act=com.google.android.c2dm.intent.RECEIVE flg=0x10 pkg=com.test.app.appname (has extras) } U=0: not found
The following is the manifest that i am using for the plugin:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.app.appname">

    <permission android:name="com.test.app.appname.permission.C2D_MESSAGE"
        android:protectionLevel="signature" />
    <uses-permission android:name="com.test.app.appname.permission.C2D_MESSAGE" />

    <uses-permission android:name="android.permission.WAKE_LOCK" />

  <!-- This app has permission to register and receive data message. -->
    <uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/app_icon"
        android:label="@string/app_name">

        <receiver
            android:name="com.google.android.gms.gcm.GcmReceiver"
            android:exported="true"
            android:permission="com.google.android.c2dm.permission.SEND" >
            <intent-filter>
                <action android:name="com.google.android.c2dm.intent.RECEIVE" />
                <category android:name="com.test.app.appname" />
            </intent-filter>
        </receiver>
        <service
            android:name="com.test.app.appname.MyGCMListenerService"
            android:exported="false"
            android:enabled="true">
            <intent-filter>
                <action android:name="com.google.android.c2m.intent.RECEIVE" />
            </intent-filter>
        </service>
        <service
            android:enabled="true"
            android:name="com.test.app.appname.MyRegistrationIntentService"
            android:exported="false" >
            <intent-filter>
                <action android:name="com.test.app.appname.GCMREGISTER" />
            </intent-filter>
        </service>
        <activity
            android:name=".AndroidAPI"
            android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen"
            android:screenOrientation="sensorLandscape"
            android:label="@string/app_name"
            android:windowSoftInputMode="adjustPan">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <data android:host ="startActivity" android:scheme ="LOHengqa"  />
            </intent-filter>
        </activity>
    </application>
</manifest>

One thing I was wondering was if I needed to create my own custom receiver. From the tutorial at google developers, it appeared that you could use the android.gms.gcm.GcmReceiver and that would trigger the call on your GCMListener. Yet, from what I am experiencing and attempting to debug the code, I do not know if that is right. How exactly is my GCMListenerService being triggered? Am i missing a piece that connects the receiver to the GCMListenerService?
By the way, here is the code for MyGCMListenerService

/**
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.test.app.appname;
import static com.test.app.appname.CommonUtilities.APP_CONTEXT;
import static com.test.app.appname.CommonUtilities._GetString;
import static com.test.app.appname.CommonUtilities._GetDrawable;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.google.android.gms.gcm.GcmListenerService;

public class MyGCMListenerService extends GcmListenerService
{
    private static final String TAG = "MyGCMListService";

    /**
     * Called when message is received.
     *
     * @param from SenderID of the sender.
     * @param data Data bundle containing message data as key/value pairs.
     *             For Set of keys use data.keySet().
     */
    // [START receive_message]
    @Override
    public void onMessageReceived(String from, Bundle data) {
        String message = data.getString("message");
        Log.d(TAG, "From: " + from);
        Log.d(TAG, "Message: " + message);

        if (from.startsWith("/topics/")) {
            // message received from some topic.
        } else {
            // normal downstream message.
        }

        sendNotification(message);
    }
    // [END receive_message]

    /**
     * Create and show a simple notification containing the received GCM message.
     *
     * @param message GCM message received.
     */
    private void sendNotification(String message) {

        final String appId = this.getPackageName();
        long when = System.currentTimeMillis();

        Intent intent = APP_CONTEXT.getPackageManager().getLaunchIntentForPackage(appId);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(_GetDrawable(APP_CONTEXT, "notification_icon"))
                .setContentTitle(_GetString(APP_CONTEXT, "app_name"))
                .setContentText(message)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify((int)(when % 1000), notificationBuilder.build());
    }
}

A: <service
   android:name="com.test.app.appname.MyGCMListenerService"
   android:exported="false"
    android:enabled="true">
    <intent-filter>
        <action android:name="com.google.android.c2m.intent.RECEIVE" />
    </intent-filter>
</service>

Specifically, I'm seeing: com.google.android.c2m.intent.RECEIVE which should be com.google.android.c2dm.intent.RECEIVE.
Seems like if anyone encounters this issue it has to do with the manifest.


text:
Q: Application Pool crashing? I have a Web Service running on IIS7.5. BizTalk sends the data to WS. WS open SharePoint object model and will does some transactions. After couple of BizTalk calls WS application is crashing with below information in the EventViewer.
Faulting application name: w3wp.exe, version: 7.5.7601.17514, time stamp: 0x4ce7afa2
Faulting module name: MSVCR80.dll, version: 8.0.50727.6195, time stamp: 0x4dcdd833
Exception code: 0x40000015
Fault offset: 0x0000000000006a68
Faulting process id: 0x2010
Faulting application start time: 0x01cd0161a09e2134
Faulting application path: c:\windows\system32\inetsrv\w3wp.exe
Faulting module path: C:\Windows\WinSxS\amd64_microsoft.vc80.crt_1fc8b3b9a1e18e3b_8.0.50727.6195_none_88e41e092fab0294\MSVCR80.dll

System Logs:

A process serving application pool 'WebServices' suffered a fatal communication error with the Windows Process Activation Service. The process id was '8208'. The data field contains the error number.

A: Last time I crashed IIS was because I accidentally modeled a constructor so that it'd enter to an infinite loop. If you're all managed code it is really hard for you to crash IIS unless you're hitting/filling the memory infinitely.
I'd recommend you to run a profiler on your code, and get help from Visual Studio's Code Analyze tools. See if you're disposing connections, or you have any infinite loops like I did. It's usually us, not the framework or the hardware :)
ps: if you have disposable objects, make sure you're using the "using" blocks, best way to make sure you're disposing stuff. (Code Analysis will point them out eventually)
ps2: another good way of understanding what's wrong may be logging the critical events -or stuff that you are suspicious about- on a text file. As you may know many logging libraries are available for dotnet (i'd go for NLog)

A: Since you are using the SharePoint object model I think there is a good possibility of what detay is saying but I am not sure this would lead to an application fault. I think you would probably see out of memory exceptions. It is surprising that this is not a BizTalk application fault.
If you do not see anything after doing profiling and reviewing your code, I would contact Microsoft Support about this issue. It can be difficult to diagnose an application fault and a call to support will get to the bottom of the problem much faster.
Thanks,

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is causing items from UIPasteboard to be converted to NSConcreteMutableData? I'm running the following in a playground (I've tested in Xcode 7.3.1 as well as Xcode 8.1 and see the same behavior):
import UIKit

let key: String = "some_key"
let value: String = "some_value"

UIPasteboard.general.items = [[key: value]]

let item = UIPasteboard.general.items.first
if let item = UIPasteboard.general.items.first {
    switch item[key] {
    case let x as String:
        print("This is expected")
    case let x as Any:
        type(of: x)
        print("This is unexpected")
    default:
        print("This is unexpected")
    }
} else {
    print("This is unexpected")
}

And I notice that the String that I put into the pasteboard actually gets bridged back out as NSConcreteMutableData.
My questions are the following:

*

*Is this caused by an internal UIPasteboard implementation (i.e. explicitly converting from NSString to NSConcreteMutableData), or is this standard ObjC-Swift bridging behavior?

*How can I work around this to store custom key/value pairs in UIPasteboard?
Here's what this looks like in a playground, for easy reference:

A: The Data you get for item[key] is simply the UTF-8 encoded value for the string.
If you add the following case, you will see that:
case let x as Data:
    let str = String(data: x, encoding: .utf8)
    print("str = \(str)")

The cause of the confusion is that the keys used by the items property are UTIs, not random keys. If you change your key to public.text then your code will work as expected.
Normally, you would not put a string on the pasteboard using the items property. You would use the string property to read and write the value.
UIPasteboard.general.string = "Hello"
let aStr = UIPasteboard.general.string
print("aStr = \(aStr)")

Doing this avoids the need to specify a UTI and it avoids replacing all existing items on the pasteboard.


text:
Q: Order by JSONB data type with sequelize literal I'm currently using this structure to query for all the items:
const filteredItems = await allItems.findAll({
         where: conditions,
         include: associations,
         order: sortingCriteria,
         limit: limit,
         offset: offset,
      });

The sortingCriteria currently has this structure:
const sortingCriteria = [
      ["price", "ASC NULLS LAST"],
      ["created_at", "DESC NULLS LAST"],
    ]

Being price and created_at fields of the allItems table. In the same table I have another field called details that has a JSONB per item.
And I need to add an extra sorting criteria, so I order by some specific data that can be found in that JSONB, with this structure:
details = {
            "sizes": {
               "height": 10,
               "width": 20,
            },
            "capacities": {
               "volume": 200,
               "weight": 2,
            }
          }

Let's say I want to order by volume all the items (and also by price and created_at, as I already have). How should I include that in sortingCriteria ?

The reason of using a JSONB instead of nested tables and JOINs is performace. I have already tried and, having everything in one table, for huge tables, the performance increases tremendously. I use limit and offset for pagination purposes. I'm using Sequelize version 6.6.2.


text:
Q: New TikZ arrowhead I'm looking how to use currarrow as a new arrowhead in tikz.
Especially it's of the same size of latex or stealth and way smaller than triangle 45.
Any idea how to make it?
For now I use node[currarrow, sloped,  allow upside down, pos=1] {} which is not really convenient...

A: A quick conceptual definition with hard coded values, you can combine it with Luigi's goodies. It won't work with different line widths etc. since I didn't do any right/left extend calculation.
I took the currarrow definition from circutikz library. It doesn't look too different from the scaled triangle 45. I would recommend using Luigi's definitions and modifiying them if necessary.
\documentclass[tikz]{standalone}
\usetikzlibrary{arrows}
\makeatletter
\pgfarrowsdeclare{mycurrarrow}{mycurrarrow}{
\pgfarrowsleftextend{-5\pgflinewidth}
\pgfarrowsrightextend{5\pgflinewidth}
}
{
            \newlength\pgf@my@length
            \pgf@my@length = 1cm
            \divide \pgf@my@length by 16
            \pgfpathmoveto{\pgfpoint{-.7\pgf@my@length}{0pt}}
            \pgfpathlineto{\pgfpoint{-.7\pgf@my@length}{-.8\pgf@my@length}}
            \pgfpathlineto{\pgfpoint{1\pgf@my@length}{0pt}}
            \pgfpathlineto{\pgfpoint{-.7\pgf@my@length}{.8\pgf@my@length}}
            \pgfpathlineto{\pgfpoint{-.7\pgf@my@length}{0pt}}
            \pgfusepathqfillstroke
}
\makeatother
\begin{document}
\begin{tikzpicture}
    \draw[mycurrarrow-mycurrarrow,blue] (0,0) -- (2,1);
    \draw[latex-latex,shift={(0mm,3mm)}] (0,0) -- (2,1);
    \draw[triangle 45-triangle 45,shift={(0mm,-3mm)},red] (0,0) -- (2,1);
\end{tikzpicture}
\end{document}

I don't get why you don't post five lines of code(four being documentclass and begin/end document and circutikz package)for an example instead of describing the arrow with screenshot from the manual.


text:
Q: Prove if $n\in N$ is composite then there exists an equivalence class $a\bmod n$ that does not have a multiplicative inverse Prove if $n\in N$ is composite then there exists an equivalence class $a\bmod n$ that does not have a multiplicative inverse
I know that the if $n=j*k$ with $j,k<n$ that $j\bmod n$ or $k\bmod n$ probably don't have inverses, but I don't remember the theorem for it.

A: Per lulu's comment, $0$ is an equivalence class without a multiplicative inverse $\pmod n$.
Here is a demonstration that there is a non-zero equivalence class
without a multiplicative inverse $\pmod n$ when $n$ is composite.
Say $n=jk$ with $j$ and $k$ strictly between $0$ and $n$.
Then $jk\equiv0\pmod n$ but $j,k\not\equiv0\pmod n$.
Assume, aiming for contradiction, there is $k^{-1}$ such that $kk^{-1}\equiv1\pmod n$.
Then $0\equiv0\times k^{-1}\equiv (jk)k^{-1}\equiv j(kk^{-1})\equiv j\times1 \equiv j.$
This contradiction shows that $k$ is a non-zero equivalence class
without a multiplicative inverse $\pmod n$.
Swapping the role of $j$ and $k$ would show that $j$ is also not invertible $\pmod n$.


text:
Q: Failed to connect to importexport.amazonaws.com port 443 Any body knows how to solve this
Error message after trying to convert the image to ami

Note (I already try to import via command line and it's working good)
I'm trying to convert image from row to ami using laravel 8
Here is the information
1.) "aws/aws-sdk-php": "^3.231"
2.) php 8
3.) my code to process the conversion

public function startConversion(string $s3DiskImageName, string $description): void{
    $client = ImportExportClient::factory(array(
        'credentials' => array(
            'key' => config('filesystems.disks.s3.key'),
            'secret' => config('filesystems.disks.s3.secret'),
        ),
        'region' => config('filesystems.disks.s3.region'),
        'version' => 'latest'
    ));

    $bucket = config('filesystems.disks.s3.bucket');
    $client->createJob([
        'JobType' => 'Import',
        'ValidateOnly' => false,
        'Manifest' => json_encode([
            [
                'Description' => "$s3DiskImageName - $description",
                'Format' => 'raw',
                'Url' => 's3:://'.$bucket .'/'.$s3DiskImageName
            ]
        ])
    ]);
}

Thanks in advance!


text:
Q: SQL statement to match dates that are the closest? I have the following table, let's call it Names:
Name     Id    Date
Dirk     1     27-01-2015
Jan      2     31-01-2015
Thomas   3     21-02-2015

Next I have the another table called Consumption:
Id Date       Consumption
1  26-01-2015 30
1  01-01-2015 20
2  01-01-2015 10
2  05-05-2015 20

Now the problem is, that I think that doing this using SQL is the fastest, since the table contains about 1.5 million rows.
So the problem is as follows, I would like to match each Id from the Names table with the Consumption table provided that the difference between the dates are the lowest, so we have: Dirk consumes on 27-01-2015 about 30. In case there are two dates that have the same "difference", I would like to calculate the average consumption on those two dates.
While I know how to join, I do not know how to code the difference part.
Thanks.
DBMS is Microsoft SQL Server 2012.
I believe that my question differs from the one mentioned in the comments, because it is much more complicated since it involves comparison of dates between two tables rather than having one date and comparing it with the rest of the dates in the table.

A: This is how you could it in SQL Server:
SELECT Id, Name, AVG(Consumption)
FROM (
    SELECT n.Id, Name, Consumption,
           RANK() OVER (PARTITION BY n.Id
                        ORDER BY ABS(DATEDIFF(d, n.[Date], c.[Date]))) AS rnk
    FROM Names AS n
    INNER JOIN Consumption AS c ON n.Id = c.Id ) t
WHERE t.rnk = 1
GROUP BY Id, Name

Using RANK with PARTITION BY n.Id and ORDER BY ABS(DATEDIFF(d, n.[Date], c.[Date])) you can locate all matching records per Id: all records with the smallest difference in days are going to have rnk = 1.
Then, using AVG in the outer query, you are calculating the average value of Consumption between all matching records.
SQL Fiddle Demo


text:
Q: Asana StatusCode=404 Writing a wrapper class for Asana API in Salesforce APEX, encountering this status code for any 'valid' GET command sent:
HttpResponse[Status=Object Not Found, StatusCode=404]

Even with the simplest of commands, GET /users/me
This is the HttpRequest that is generated and sent:
System.HttpRequest[Endpoint=https://app.asana.com/api/1.0/users/me, Method=GET]


text:
Q: Using vim as a git commit message writer, is it possible to autocomplete modified function names? I find myself often repeating the names of the functions I've edited, in the commit message, and it'd be nice to have autocompletion for the functions I've just changed when writing the commit messasges.
Is it possible to get vim to somehow search through the current commited files and grab the function names, or better yet, only the modified ones?
I'm using gVim7.3 and C#, if that's at all relevant.

A: Vim 7.3 ships with $VIMRUNTIME/ftplugin/gitcommit.vim, which defines a :DiffGitCached command to show the differences you're about to commit. Once you have that in a split window, the default <C-N> completion (assuming default 'complete' values) will pick those strings up automatically. (It's also good for a last check that you're really committing the right stuff.)

A: If you use the -v option to git commit that will cause git to place the diff of what you're committing in the file used to create the commit message. With most languages the headers of hunks within that diff will indicate the name of the function being modified. This will make the names of modified functions available for completing with Ctrl+N or Ctrl+P
To simplify this I long ago did
git config --global alias.ci 'commit -v'

And always use git ci rather than git commit.
Newer versions of git support configuration to turn this on for all commits.
git config --global commit.verbose true


text:
Q: Excel, Creating sum, every 144 values in a row So I have an excel file over some years with 10min values [A2;A181441].
I want to SUM every row of 144 values into [C2;C1261].
Looking forward to your answers!
edit: Thanks @Rajesh S for update: Row of 144 values not every 144th value.

A: This will solve the issue:

N.B.

*

*For better understanding in the shown example I've got the SUM of 5 rows (or bunch of 5 rows).

*Formula in Cell E98:
=SUM(OFFSET($B$98,(ROW()-98)*5,0,5,1))

*Your Formula should be written like this.
=SUM(OFFSET($B$98,(ROW()-98)*144,0,144,1))

*

*If your data are in Range A1:B1000 along with headers in Row 1 then use this Formula in Cell D2.

=SUM(OFFSET($B$2,(ROW()-2)*144,0,144,1))
Adjust cell references in the formula  as needed.

A: Here is an alternative that uses Index() rather than Offset():
=SUM(INDEX(A$2:A$181411,1+144*(ROWS($1:1)-1)):INDEX(A$2:A$181411,ROWS($1:1)*144))

and copy downward.


text:
Q: Add the debug symboles by using maven I'm trying to add the debug symboles by using mave-compiler-plugin (so that I'll be able to access the method parameters names).
Following the available configurations that can be found here,
Here is my maven-compiler-plugin configuration
                        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
                <compilerArgument>-Xlint:all</compilerArgument>
                <showWarnings>true</showWarnings>
                <showDeprecation>true</showDeprecation>
                <debug>true</debug>
                <debugLevel>lines,vars,source</debugLevel>
            </configuration>
        </plugin>

Untill now, I have no success.
Can someone please let me know how to add the debug symboles by using maven?

A: You may need to add <fork>true</fork> according to the maven-compiler-plugin documentation for compilerArgument.

Sets the unformatted single argument string to be passed to the compiler if fork is set to true.

Not sure if it's required but you may want to add <groupId>org.apache.maven.plugins</groupId> and <version>#.#.#<\version>.
Also, as @JonK mentioned in the comments, you need source instead of sources for debugLevel.


text:
Q: how to add facebook auth in old ASPnet webforms site I'm currently working on a web project using webforms and trying to add facebook authentication to the site since it seemed very easy on the tutorials I found (generate the keys, set up the facebook app side, add them to the Startup.Auth.cs).
I managed to get authenticated, but I keep getting redirected to
https://my123site.net/signin-facebook
instead of
https://my123site.net/RegisterExternalLogin
which seems the correct page to go since I need to register the user.
I found many tutorials that appear to have different version of Owin than what I use, for example if I create a new website, I see it uses "OpenAuth" instead of Identity.
Is there a way to update my project to the latest version, so that I can easily add social media login? (the way they do here https://www.youtube.com/watch?v=jaq9m2og9mY )


text:
Q: Op-amp replace problem Can we use TLV2221 op-amp for differential to single ended output,in place of TLV9062 opamp,or any issue if TLV9062 replaced with TLV2221.can anyone explain?

A: So check this out in order to figure out certain parameters that you might want to take into considertion while designing a Differential to Single Ended Output Op Amp
TLV2221 when compared to TLV9062 has significantly less slew rate compared to 9026. The common mode rejection ratio of 9062 is better than 2221. The voltage bandwidth you'll work with is better on 9062 compared to 2221.
So I suggest you stick with the 9062. Hope this helped.


text:
Q: Enumerate with \noindent I am creating a custom macro for enumerated lists, but with this attempt, I haven't been able to eliminate the indentation of the item numbers. Every time I use \myitemize, the lists still indents.
What am I doing wrong here?
\newenvironment{myitemize}
{ \noindent\begin{enumerate}
    \setlength{\itemsep}{0pt}
    \setlength{\parskip}{0pt}
    \setlength{\parsep}{0pt}     }
{ \end{enumerate}                  }

A: For jobs like this, use enumitem that provides flexible options. Here is an example.
\documentclass{article}

\usepackage{enumitem}

\newlist{myitemize}{enumerate}{10}
\setlist[myitemize]{label*=\arabic*.,nosep,leftmargin=*}
\begin{document}
Here is some text
\begin{myitemize}
  \item some text
  \item some text
\end{myitemize}
And again some more...
\end{document}

You can adjust the labels for second level by
\setlist[myitemize,2]{label=\alph*),nosep,leftmargin=*}

If label* is used instead of label, we will get 1.a), 1.b) etc.
\documentclass{article}

\usepackage{enumitem}

\newlist{myitemize}{enumerate}{10}
\setlist[myitemize]{label*=\arabic*.,nosep,leftmargin=*}
\setlist[myitemize,2]{label=\alph*),nosep,leftmargin=*}
\begin{document}
Here is some text
\begin{myitemize}
  \item some text
  \begin{myitemize}
  \item some text
  \item some text
\end{myitemize}
  \item some text
\end{myitemize}
And again some more...
\end{document}


text:
Q: Apache Camel Split List into bigger pieces I have a list in exchange object and I want it to be split into objects by the size of ten for ex. Is there any property to set to do that or should I do this manually?
Thx

A: You can use the camel splitter and then the camel aggregator with a batch size of 10. I would not do this for such a simple case though as the overhead might be substantial. A simple bean or processor with java code to split the data might be simpler.


text:
Q: Xamaring.Forms Android 8.0 - Visual Studio 2019 I'm becoming crazy. I want to compile Xamarin.Forms for Android 8.0 with Visual Studio 2019
I setup all correct, I think, but I always get:
Error       The $(TargetFrameworkVersion) for App_test32.Android (v8.0) is less than the minimum required $(TargetFrameworkVersion) for Xamarin.Forms (8.1). You need to increase the $(TargetFrameworkVersion) for App_test32.Android. App_test32.Android

A: You cannot target 8.0 and that's for a reason. Starting from August 1, 2019 Google doesn't accept new apps that doesn't have targetSdkVersion set below Android 9.0 (for new apps).
You can read more about this here (Meet Google Play's target API level requirement) and more specifically here (Target API level requirements for the Play Console).
If you open the second link, you will see that the targetSdkVersion will be bumped even to Android 10, starting from August 3, 2020 (for new apps)
This is what you are seeing - Xamarin has restricted this, so that you don't set it lower that what it must be. Otherwise, you will be able to build it, but you won't be able to upload it. You can see the minimum version set here
However, you can still set it to 8.0, but you will need to downgrade the Xamarin.Forms & Xamarin.Android to a version that is way back - probably even before 4.0. This way you will be able to build the project, but the end result will be the same - you won't be able to upload the app to the PlayStore.
Useful link to get familiar with the difference between Target Framework, Minimum Android Version & Target Android Version from the official docs
Here is the most important comparison:

Minimum Android Version <= Target Android Version <= Target Framework

To sum up, I will quote again the guys from Microsoft (see in the link above):

We recommend that you explicitly set the Target Android version to the latest version of Android that you use to test your app. Ideally, it should be set to the latest Android SDK version – this allows you to use new APIs prior to working through the behavior changes. For most developers, we do not recommend setting the Target Android version to Use Compile using SDK version.


text:
Q: Physics and logic combination papers Are there papers that combine the subjects of logic and physics? I would like to read some texts that use both logic and physics. It could be either an application of logic to physics or physics to logic.

A: One such paper (an application of Logic to Physics) is Undecidability of the spectral gap, by Toby S. Cubbitt, David Perez-Garcia, and Michael M. Wolf, (Nature, 528 (2015), pp. 207–211).


text:
Q: Proof involving non-existent limits For context: I understand the basic $\epsilon$-$\delta$ definition of a limit, but have not learned anything pertaining to limits that do not exist, other than the fact that the limit does not exist.
I am working on the following:

Suppose that $\lim_{x\to 0}f(x)$ exists and is non-zero. Prove that if $\lim_{x\to 0}g(x)$ does not exist, then $\lim_{x\to 0}f(x)g(x)$ does not exist.

Source: Calculus by Spivak
My ideas:

*

*Using contradiction is one idea that I had. Something along the lines of: Suppose that $\lim_{x\to 0}f(x)g(x)=l$, and let $\epsilon>0$ be arbitrary. Because $\lim_{x\to 0}f(x)=c\neq 0$, $|x|<\delta_1$ implies $|f(x)-c|<\epsilon$. We also have that $|x|<\delta_2$ implies $|f(x)g(x)-l|<\epsilon$. But I'm not sure how to manipulate the expressions past this point.

*I also thought of using the fact that $\lim_{x\to a}f(x)g(x)=\lim_{x\to a}f(x)\cdot\lim_{x\to a}g(x)$ to obtain $\lim_{x\to 0}f(x)g(x)=c\cdot\lim_{x\to 0}g(x)$, but I don't know how to show that $c\times\text{non-existent limit}=\text{non-existent limit}$.

A: The definition of limit is the following:
Let $a\in X\subset\mathbb{R}$ and $f:X\rightarrow \mathbb{R}$. We say the limit of $f$ when x approach to $a$ is $L$ (and we write $\lim_{x\rightarrow a}f(x)=L$) if, given $\epsilon>0$, exists $\delta=\delta(\epsilon)>0$ such that, $x\in X,$
$$<0|x-a|<\delta\Rightarrow |f(x)-L|<\epsilon $$
So, to prove  that the limit of $f$ when $x$ approach to $a$ doesn't exists if, for all $A\in X$ exists $\epsilon>0$ such that, for all $\delta>0$
$$0<|x-a|<\delta\Rightarrow |f(x)-A|\geq \epsilon. $$
So, let's go to your question, considerating the domain of $f$ and $g$ to be $\mathbb{R}$:
Suppose that $\lim_{x\rightarrow 0}f(x)=L\neq 0.$
So, given $\epsilon >0$, exists $\delta>0$ such that, $x\in\mathbb{R}$
$$|x|<\delta\Rightarrow |f(x)-L|<\epsilon. $$
Suppose that $\lim_{x\rightarrow 0}g(x)$ does not exists. So, for all $A\in\mathbb{R},$ exists $\epsilon>0$ such that for all $\delta>0,x\in\mathbb{R}$,
$$|x|<\delta\Rightarrow |g(x)-A|\geq \epsilon $$
So, to prove that the limit of $f(x)g(x)$ when $x\rightarrow 0$ is equivalent to prove that, for all $B\in\mathbb{R}$, exists $\epsilon >0$ such that for all $\delta >0, x\in\mathbb{R}$,
$$|x|<\delta\Rightarrow |f(x)g(x)-A|\geq \epsilon.$$
Try to combinate theses equations. Can you get it from here?


text:
Q: How to overplot fit results for discrete values in pymc3? I am completely new to pymc3, so please excuse the fact that this is likely trivial.  I have a very simple model where I am predicting a binary response function.  The model is almost a verbatim copy of this example: https://github.com/pymc-devs/pymc3/blob/master/pymc3/examples/gelman_bioassay.py
I get back the model parameters (alpha, beta, and theta), but I can't seem to figure out how to overplot the predictions of the model vs. the input data.  I tried doing this (using the parlance of the bioassay model):
 from scipy.stats import binom

 mean_alpha = mean(trace['alpha'])
 mean_beta = mean(trace['beta'])

 pred_death = binom.rvs(n, 1./(1.+np.exp(-(mean_alpha + mean_beta * dose))))

and then plotting dose vs. pred_death, but this is manifestly not correct as I get different draws of the binomial distribution every time.
Related to this is another question, how do I evaluate the goodness of fit?  I couldn't seem to find anything to that effect in the "getting started" pymc3 tutorial.
Thanks very much for any advice!

A: Hi a simple way to do it is as follows:
from pymc3 import *
from numpy import ones, array

# Samples for each dose level
n = 5 * ones(4, dtype=int)
# Log-dose
dose = array([-.86, -.3, -.05, .73])

def invlogit(x):
    return np.exp(x) / (1 + np.exp(x))

with Model() as model:

    # Logit-linear model parameters
    alpha = Normal('alpha', 0, 0.01)
    beta = Normal('beta', 0, 0.01)

    # Calculate probabilities of death
    theta = Deterministic('theta', invlogit(alpha + beta * dose))

    # Data likelihood
    deaths = Binomial('deaths', n=n, p=theta, observed=[0, 1, 3, 5])
    start = find_MAP()
    step = NUTS(scaling=start)
    trace = sample(2000, step, start=start, progressbar=True)

import matplotlib.pyplot as plt

death_fit = np.percentile(trace.theta,50,axis=0)

plt.plot(dose, death_fit,'g', marker='.', lw='1.25', ls='-', ms=5, mew=1)

plt.show()

A: If you want to plot dose vs pred_death, where pred_death is computed from the mean estimated values of alpha and beta, then do:
pred_death = 1./(1. + np.exp(-(mean_alpha + mean_beta * dose)))
plt.plot(dose, pred_death)

instead if you want to plot dose vs pred_death, where pred_death is computed taking into account the uncertainty in posterior for alpha and beta. Then probably the easiest way is to use the function sample_ppc:
May be something like
ppc = pm.sample_ppc(trace, samples=100, model=pmmodel)
for i in range(100):
    plt.plot(dose, ppc['deaths'][i], 'bo', alpha=0.5)

Using Posterior Predictive Checks (ppc) is a way to check how well your model behaves by comparing the predictions of the model to your actual data. Here you have an example of sample_ppc
Other options could be to plot the mean value plus some interval of interest.


text:
Q: Return New Promise Using Static Function I'm looking for a fast way to return a promise with a fulfillment without needing to create a new promise.
Is there a static way of doing what I do at Point A (below)
new Promise(function(resolve){
    resolve(data1, data2);
})
.then(function(data1, data2){
    if(something){
        // returns promise
    }
    else{
        // POINT A
        return new Promise(function(fulfill){
            fulfill(data1, data2);
        });
    }
})
.then(function(data){
    console.log(data);
});

Ideally something like return Promise.fulfill(data1, data2); which will save me from writing a function which calls a function.

A: You are looking for Promise.resolve(data):

The Promise.resolve(value) method returns a Promise object that is resolved with the given value. If the value is a thenable (i.e. has a then method), the returned promise will "follow" that thenable, adopting its eventual state; otherwise the returned promise will be fulfilled with the value.

You can always only pass a single value btw (your example wouldn't work).

A: No need for return Promise.resolve(x) inside a .then function. It's implicit. Just return x!


text:
Q: Dividing a class into two equal groups , I can't find my mistake Suppose we have know A and B are two students in a class of $2n$ pupils. We divide the class into two groups of n each. What is the probability that they will be in the same group?
I calculate the complement, that is, the probability that they are in different groups.
As they are in different groups, I need to select $n-1$ students from $2n-2$.
Thus, my answer is $1 - \frac{2n-2 \choose n-1}{2n \choose n}$, which ends up differing from the answer given at Probability of getting into the same class.
Can somebody help by explaining the mistake I have made?

A: Please note that ${2n \choose n} $ orders the groups so you need to divide it by $2!$ as you only want to find number of ways to make two groups of $n$.
So the probability using your method is,
$ \displaystyle 1 - 2! \cdot {2n-2 \choose n-1} / {2n \choose n} = \frac{n-1}{2n-1}$
The easiest way to find the probability is to first place $A$ in any group. Now that leaves $(2n-1)$ places across two groups for $B$ but if $B$ has to be in the same group as $A$ then it must be in one of the $(n-1)$ places in $A$'s group. That is probability of $ \displaystyle \frac{n-1}{2n-1}$.

A bit more explanation:
Say I have $4$ guests at home but I have only two chairs. Say I want to randomly choose two guests to sit and of course rest two stand along with me. ${4 \choose 2}$ gives me number of ways to make two groups. But these groups are ordered. One of the groups sits and the other group stands.
But if I am only interested in finding number of ways I can randomly pair my $4$ guests to play a doubles game of ping pong, there are only $\frac{1}{2!}{4 \choose 2} ~$ ways. By the way, my four guests are Alpha, Bravo, Charlie and Delta. Here are three ways to pair them -

*

*$\{$Alpha, Bravo$\}$,$\{$Charlie, Delta$\}$

*$\{$Alpha, Charlie$\}$,$\{$Bravo, Delta$\}$

*$\{$Alpha, Delta$\}$,$\{$Bravo, Charlie$\}$
So for the given question to find desired probability, you either need to have number of unordered groups in both the numerator and the denominator or number of ordered groups in both. To make the numerator ordered, note that $A$ and $B$ can swap places to be in named groups and so you multiply ${2n-2 \choose n-1}$ by $2!$.


text:
Q: Specific Formatter for NSString to NSDate Conversion I have been stuck on this for a while, and while I do believe the code I have is in working order, I am unable to convert the following string into a date due to being unable to set NSDateFormatter correctly.
2014-06-09T23:24:00.0000000
Here is some sample code:
NSString *dateString = @"2014-06-09T23:24:00.0000000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];

NSDate *date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:dateString];
NSLog(@"date: %@", date);

In this example, the log will turn up null.

A: Since your date has a fractional part, you need to add that to the date formatter, otherwise you're not giving it what it expects. Add .SSS to the end of your format string, so your code will look like this, and return the date you expect:
NSString *dateString = @"2014-06-09T23:24:00.0000000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];

NSDate* date = [dateFormatter dateFromString:dateString];
NSLog(@"date: %@", date);

Prints: 2014-06-10 06:24:00 +0000


text:
Q: How to put a static message into an HTML form if the field is empty? What if I want to check if the field is empty?
If the field is empty I want to send/append a static message like "Hello guys" which is e.target.value.
If I do a check (if the e.target.value == null), nothing happens.

<form id="user_form" action="" method="post" enctype="text/plain">
  <textarea id="msg" cols="30" rows="10" placeholder="Write a message"></textarea>
  <input type="submit" onsubmit="return test()" id="sendBtn" value="send" class="btn">
</form>

<!-- Send msg to whatsapp -->
<script>
  const url = 'https://api.whatsapp.com/send?phone=123456789&text=';
  document.getElementById('msg').addEventListener('keyup', (e) => {
    document.getElementById('user_form').setAttribute('action', url + e.target.value);
    console.log(document.getElementById('user_form').getAttribute('action'));
  });
</script>

What I want to do is:
if (e.target.value == "") {
   e.target.value = "This is a default message"
}

A: Check if the textarea is empty with document.querySelector('#msg').value.length. If the length === 0then it means that the textarea has no text. You can use a ternary conditional operator for that.
You also should implement a trim() inside your condition to check if the text only contains spaces.

document.querySelector('button').addEventListener('click', function() {
  let msg = document.querySelector('#msg');
  let text = (msg.value.trim().length != 0) ? msg.value : 'no text';
  console.log(text);
})
<textarea id="msg" cols="30" rows="10" placeholder="Write a message"></textarea>
<button>Get content of textarea</button>


text:
Q: Hide a Site Column in NewForm and EditView I have created a custom site column. I have added this to my custom content type that inherits from the document content type. I wish to hide a field on the edit and new forms. I have the following code:
  <Field
  ID="{58EB1D2B-9EF6-46EA-9EC3-C98516D73791}"
  Name="test"
  DisplayName="test"
  Group="test"
  Type="Note"
  AppendOnly="True"
  UnlimitedLengthInDocumentLibrary="True"
  ShowInNewForm="False"
  ShowInEditForm="False"
  ShowInViewForms="True"
  SourceID="http://schemas.microsoft.com/sharepoint/v3"
    >
  </Field>

I then add this to my content type using
<FieldRef ID="{58EB1D2B-9EF6-46EA-9EC3-C98516D73791}" Name="test" DisplayName="test" />

The problem is that the field is still being displayed on the new and edit form. What am I doing wrong?

A: It looks like you need to use TRUE & FALSE rather than True & False. Changing to all capitals works wonders.


text:
Q: NetSuite - How to loop thru context newRecord objects when using User Event Script When utilizing a User Event Script, I am attempting to loop through a context object to find all newRecord objects that are selected by a user in the Inventory Print screen. I am able to retrieve a single record within the context object, however, if a user selects multiple invoices to print, I am unable to retrieve the additional invoices.
When looking at the Execution log, I am unable to see the entire context object.

My script is as follows:

/** @NApiVersion 2.0 @NScriptType UserEventScript
*/
define(['N/record'], function (record) {          function
beforeLoad(context) {
  try {

      var arrInvoiceIds= []
      var arrFileNames= []

      var r = context.newRecord
      var nrf = r.getFields()

      //fetch invoice record
    var invoiceRecord = record.load({ type: record.Type.INVOICE, id: r.id })

      for(var i=0; i < nrf.length; i++){

        var customerName = ""
        var invNo = ""
        var fileName = ""

        if(nrf[i] == "entity"){
          customerName = invoiceRecord.getValue('entity');
        }
        if(nrf[i] == "tranid"){
          invNo = invoiceRecord.getValue('tranid');
        }

        if(customerName != "" && invNo != ""){
          fileName = customerName + "_" + invNo;
        }

      }

      log.debug ({
          title: 'r.id',
          details: r.id //arrInvoiceIds //arrFileNames
      });

    log.debug ({
          title: 'nrf',
          details: nrf //arrInvoiceIds //arrFileNames
      });

    log.debug ({
          title: 'nrf.length',
          details: nrf.length //arrInvoiceIds //arrFileNames
      });

    log.debug ({
          title: 'context',
          details: context //arrInvoiceIds //arrFileNames
      });
    log.debug ({
          title: 'file',
          details: fileName //arrInvoiceIds //arrFileNames
      });

  } catch (e) {

      log.error ({
          title: e.name,
          details: e.message
      });

  }
}

return {
  beforeLoad: beforeLoad
}; });

A: When you print multiple invoices, the UserEvent is simply triggered multiple times. You should see that in your logs. The invoices are not combined on a single instance of context within a single UserEvent.


text:
Q: Android AccessibilityDelegate force reading of ViewGroup not children I'm using a viewpager which is made up of some number of relative layout siblings which are quite complex.
If I click on the relative layout, it will highlight the entire page and read the title and a few textviews one after the other as expected.
If I scroll the viewpager I'd like talkback to read the next page in the same way it reads the first if I click. Secondly, if I scroll to the second, third, etc. pages and click on those layouts, talkback will read as expected.
I am trying to achieve the click behavior after the scroll event has completed.
Here is what I have for the accessibilityDelegate.
    viewPager.setAccessibilityDelegate(new AccessibilityDelegate () {
        @Override
        public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child, AccessibilityEvent event) {
            if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
                View page = viewPager.getCurrentPageView();
                performAccessibilityAction(page, AccessibilityNodeInfo.ACTION_CLICK, Bundle.EMPTY);
            }
            return super.onRequestSendAccessibilityEvent(host, child, event);
        }
    });

I've verified that 'page' is the RelativeLayout parent that I think it is. I've also confirmed that the onRequestSendAccessibilityEvent is being fired, but it doesn't read the contents of its children. Am I missing something?
Updated
I've also tried using
viewpager.getCurrentPageView().sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED);

The above worked for another example when I needed to force talkback to reread a single item but does not have any affect if I try it on the page.
Thanks

A: Some background -- When you tap on the relative layout, TalkBack generates speech based on the layout's contents. On ICS, this is triggered by a HOVER_ENTER event. On Jelly Bean, it's triggered by an ACCESSIBILITY_FOCUS event. These events are sent automatically by the framework and should, generally speaking, never be sent manually from an app. The same goes for FOCUS events, except in the special case of custom views (see Accessibility talk from Google I/O 2013 for more details).
So, back on topic.
You can control the speech for SCROLLED events by populating the outgoing event with the text you want read. The down side of this is that you'll need to manually generate the text you want read, and it's very likely that this text will differ from what TalkBack will read if the user touches the layout.
viewPager.setAccessibilityDelegate(new AccessibilityDelegate () {
    @Override
    public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) {
        super.onPopulateAccessibilityEvent(host, event);

        if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SCROLLED) {
            event.setContentDescription(/** your text */);
        }
    }
});

Another option is to do nothing and let the user explore the view on their own. This is the preferred interaction model for Android accessibility.
Edit:  Video URL is broken, Changed.

A: This issue was reported on google check

where ViewPager does not set AccessibilityEvent parameters properly
  when scrolling.

But after releas of Android Support Library, revision 23.2.1  (March 2016) This issue has been resolved.
update Support Library to Android Support Library to 23.2.1

A: I had the same issue before. And now I add android:focusable="true" to the ViewGroup, the TalkBalk will read the ViewGroup, instead of its children


text:
Q: how can i show notice on top in my application I want to add custom notification in my app so how can i do this in my application :
Please Click for Screenshot.

A: give the following a try, thit works like a charm: https://github.com/keyboardsurfer/Crouton

A: You should use custom Toast.
An example;
Custom Toast


text:
Q: How to Create Task Items With Custom List Dataview I have created 2 custom lists in Sharepoint 2010:
List #1: INTERNAL PROCESSES (fields: Process Title, Reference)
List #2: PROCESS STEPS (fields: Step Title, Step Description, Process Title[lookup of 1 item in previous list], Department Assigned)
I created an action in the display form for list INTERNAL PROCESSES called "Create Instance"; when user clicks on it, it redirects the user to mypage.aspx?processID={itemID}
(I couldn't find a way to pass the title instead of the ID in the querystring).
So now I need to accomplish the following in mypage.aspx:

*

*Find the item in INTERNAL PROCESSES using the ID received in the querystring. If field Reference is not NULL, ask the user to enter a value for Reference (e.g. if the Reference contains the word "Member", ask the user to enter the Member Name).

*Get the Process Title from list INTERNAL PROCESSES for the ID received in querystring

*For each list item in PROCESS STEPS where field Process Title matches Process Title looked up in step#2 , create a new TASK list item with the following values:
a) TASK Title = Step Title + Value entered in step#1 (if any)
b) TASK Description = Step Description
c) TASK Assigned to = Department Assigned
I'd like to avoid using code, if at all possible, because I've never done it. If code is required then please point me in the right direction.

A: I think you have two "no code" options to do this, but both require some scripting (which to me is code):

*

*Have mypage.aspx be an initiation page for a SharePoint Designer workflow. You'd set the initiation values for the workflow in the page, probably using some script to get the value for Reference and pass it into the workflow.

*Do the whole thing with script, using my SPServices library for the lookups and creating the tasks real time:
CodePlex: SPServices


text:
Q: Find documents whose analyzed field contains slash and underscore My documents have an analyzed field url with content looking like this
http://sub.example.com/data/11/222/333/filename.txt

I would like to find all documents whose filename starts with an underscore. I've tried multiple approaches (wildcard, pattern, query_string, span queries) but I never got the right result. I expect this is because the the underscore is a term separator. How can I write such a query? Is it possible at all without changing the field to not analyzed (which I cannot do at the moment)?
It's ElasticSearch 1.5, but we'll be migrating to at least 2.4 in foreseeable future.

A: You might be able to write a script that would do that, but it would be amazingly slow.
You best bet (even though you say you can't right now) is changing the field from analyzed to a multi-field.  This way you could have both analyzed and not-analyzed versions to work work.
You could use the Reindex API to migrate all the data from the old version to the new version (assuming you're using ES 2.3 or greater).


text:
Q: VueJS and Axios POST- $_POST empty on server side I am at witts end with axios/vue currently, hoping someone can see something I am missing.
I am using axios documentation and doing a basic post.
                       axios({
                            method: 'POST',
                            url: 'myurlhere',
                            data: {
                                    firstName: 'Fred',
                                    lastName: 'Flintstone'
                                  },
                            headers: {'Content-Type': 'multipart/form-data' }
                        })
                        .then(function (response) {
                            //handle success
                            console.log(response);
                        })
                        .catch(function (response) {
                            //handle error
                            console.log(response);
                        });

The api is absolutely hit, I am logging it on the server side. The console log on the axios side does not throw any errors. I am printing out the $_REQUEST variable on the server side just to see what is coming through and the $_POST is empty. The console log does show the returned array but post is empty.
<?php
$data=array('worked'=>true,"data"=>$_REQUEST);
echo json_encode($data);
?>

If i use $_GET variables they work. Post does not though. what am I doing wrong???


text:
Q: Error in rock paper scissors game with Python I'm trying to create a rock paper scissors game for a class assignment with Python, but I can't get the result out.
The game is supposed to start with the 1) user's input, 2) show what computer randomly chose, 3) the result (You win, You lose, or Tie with how you won or lost), 4) then ask if you want to Play again, and 5) finally escape.
I did succeed on the first 2 parts, but I can't figure out why 3, 4, 5 is not printing...
The result after showing what the computer played(2), it says 'None' then it loops back to (1) getting the input from the user.
Below is the code. Please advise me on how to fix them. Thank you so much!!

import random
while True :
     player = input("Enter a number (0 for rock, 1 for paper, 2 for scissors) >>")
     RPS = [0,1,2]
     computer = random.choics(RPS)
     RPS_dict = {0:'Rock', 1:'Paper', 2:'Scissors'}
     print("The computer played", RPC_dict.get(computer))

     def game(player, computer):
          RPS_dict = {0:'Rock', 1:'Paper', 2:'Scissors'}
          if player == computer:
              print("Tie!")
          elif player == 0:
               if computer == 1:
                  print("You lose!", RPS_dict.get(computer), 'covers', RPS_dict.get(player))
               else:
                  print("You win!", RPS_dict.get(player), 'cut', RPS_dict.get(computer))
          elif player == 1:
             if computer == 2:
                  print("You lose!", RPS_dict.get(computer), 'cut', RPS_dict.get(player))
             else:
                  print("You win!", RPS_dict.get(player), 'covers', RPS_dict.get(computer))
     game(player, computer)
     print(game(player, computer))
again = input("Play again? 0 for no, 1 for yes\n")

A: Your function should be outside your while loop and you don't need to call it within a print statement...
import random

def game(player, computer):
    if player == computer:
        print('game tied')
    else:
        if (player == 1 and computer == 3) or (player == 2 and computer == 1) or (player == 3 and computer == 2):
            print('you win')
        else:
            print('computer wins')

def choice(x):
    y = None
    if x == 1:
        y = 'rock'
    elif x == 2:
        y = 'paper'
    elif x == 3:
        y = 'scissors'
    return y

playing = True
while playing == True:
    player_input = int(input("Enter 1 for rock, 2 for paper, 3 for scissors"))
    print('You chose:'+ choice(player_input))
    computer_input = random.choice([1,2,3])
    print('Computer chose:'+ choice(computer_input))
    game(player_input, computer_input)
    restart = int(input("Enter 1 to play again or 2 to quit"))
    if restart == 2:
        playing = False


text:
Q: How can I track a change in Power BI report? I would like to track changes made in a PowerBI report, for example which visual is added, deleted or changed.
I can track the Dataset with ALM toolkit but it does not allow tracking of report. Is there any app for that?


text:
Q: Most frequently triggered android receiver? What is the most frequently triggered android intent action that my app could have a BroadcastReceiver listening for without a service running in order to receive it?
Background
I have a foreground service that needs to run roughly whenever the user is present at the phone.  When the screen gets turned off I shut down the service so Doze mode can be achieved (and yes, foreground running services block Doze mode even though documentation doesn't clearly state so).
The problem comes when trying to turn the service back on.
I've already looked into SCREEN_ON and USER_PRESENT but both appear to require a running background service in order to be received which negates what i am trying to achieve.
So my thought is, I wonder if there's a action triggered frequently enough when the user is present that I could listen for that instead of SCREEN_ON/USER_PRESENT?

A: I've found that the best way to do this is to register a BroadcastReceiver on the "android.intent.action.USER_PRESENT" action.
To distinguish between cases where the user has turned on his screen when it wasn't locked to when he actually unlocked it use the KeyguardManager to check the security settings.
add this in activity
registerReceiver(new PhoneUnlockedReceiver(), new IntentFilter("android.intent.action.USER_PRESENT"));

and use this :
public class PhoneUnlockedReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        KeyguardManager keyguardManager = (KeyguardManager)context.getSystemService(Context.KEYGUARD_SERVICE);
        if (keyguardManager.isKeyguardSecure()) {

            //do stuff here
        }
    }
}

Happy coding!!


text:
Q: Error when importing pylab in python 2.6.6 I'm trying to import pylab using Python 2.6.6 on REHL 6.4.
#!/usr/bin/env python
import os, zipfile,glob, shutil,time,scipy,numpy,matplotlib
from pylab import *

I get the error:
# ./script.py
Traceback (most recent call last):
  File "./script.py", line 3, in <module>
    from pylab import *
  File "/usr/lib64/python2.6/site-packages/pylab.py", line 1, in <module>
    from matplotlib.pylab import *
  File "/usr/lib64/python2.6/site-packages/matplotlib/pylab.py", line 247, in <module>
    from matplotlib.pyplot import *
  File "/usr/lib64/python2.6/site-packages/matplotlib/pyplot.py", line 78, in <module>
    new_figure_manager, draw_if_interactive, show = pylab_setup()
  File "/usr/lib64/python2.6/site-packages/matplotlib/backends/__init__.py", line 25, in pylab_setup
    globals(),locals(),[backend_name])
  File "/usr/lib64/python2.6/site-packages/matplotlib/backends/backend_gtkagg.py", line 10, in <module>
    from matplotlib.backends.backend_gtk import gtk, FigureManagerGTK, FigureCanvasGTK,\
  File "/usr/lib64/python2.6/site-packages/matplotlib/backends/backend_gtk.py", line 8, in <module>
    import gtk; gdk = gtk.gdk
  File "/usr/lib64/python2.6/site-packages/gtk-2.0/gtk/__init__.py", line 64, in <module>
    _init()
  File "/usr/lib64/python2.6/site-packages/gtk-2.0/gtk/__init__.py", line 52, in _init
    _gtk.init_check()
RuntimeError: could not open display

All of scipy, numpy and matplotlib are installed but I still can't import pylab. Is there a problem in the way I'm importing pylab?

A: fixed using :
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt


text:
Q: Elasticsearch Cluster fails on shutting down one node I setup an Elasticsearch Cluster with 3 nodes. Here are the values i changed in elasticsearch.yml
Node Earth:
cluster.name: FederationOfPlanets
node.rack: Sol
node.name: Earth
node.master: true
node.data: false
discovery.zen.minimum_master_nodes: 2
index.routing.allocation.disable_allocation: false

Node Enterprise:
cluster.name: FederationOfPlanets
node.rack: Sol
node.name: Enterprise
node.master: true
node.data: true
discovery.zen.minimum_master_nodes: 2
index.number_of_shards: 2
index.number_of_replicas: 2
index.routing.allocation.disable_allocation: false

Node Defiant:
cluster.name: FederationOfPlanets
node.rack: Bajor
node.name: Defiant
node.master: true
node.data: true
discovery.zen.minimum_master_nodes: 2
index.number_of_shards: 2
index.number_of_replicas: 2
index.routing.allocation.disable_allocation: false

The nodes Enterprise and Defient are running with logstash agents to get logs from the system and put it into the elasticsearch instance. Earth is running with a logstash web instance to show the logs in a webinterface. Everything works well until i shutdown the Defiant node. If I shutdown the Enterprise node, everything works well.
How can i avoid the the cluster failure if one node stops working?


text:
Q: How to remove dialog margins? I'm trying to create a custom dialog to show a list of values at the bottom of screen.
How can I remove the dialog margins?
I want this...

I have this...

Dialog code:
Dialog d = new Dialog(this);
    d.requestWindowFeature(Window.FEATURE_NO_TITLE);
    d.setContentView(R.layout.dialog_options);
    Window window = d.getWindow();
    WindowManager.LayoutParams wlp = window.getAttributes();
    wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
    wlp.gravity = Gravity.BOTTOM;
    window.setAttributes(wlp);
    d.show();

Solved! Better solution:
<style name="BottomOptionsDialogTheme" parent="Theme.AppCompat.Light.Dialog">
    <item name="android:windowBackground">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">false</item>
    <item name="android:layout_margin">0dp</item>
    <item name="android:padding">0dp</item>
    <item name="android:layout_gravity">bottom</item>

    <item name="colorPrimary">@color/orange_dark</item>
    <item name="colorPrimaryDark">@color/orange_dark</item>
    <item name="colorAccent">@color/gray_light</item>
</style>

And use new Dialog(context, R.theme.BottomOptionsDialogTheme);

A: Change your line:
Dialog d = new Dialog(this);

to:
Dialog d = new Dialog(this, R.style.DialogTheme);

and add in your styles.xml with parent corresponding to your theme version.
<style name="DialogTheme" parent="Theme.AppCompat.Light.Dialog">
    <!-- Customize your theme here. -->
    <item name="android:windowBackground">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">false</item>
</style>

But in your situation it can be better to use Snackbar in my opinion. Here is tutorial.


text:
Q: initctl: Unable to connect to Upstart: Failed to connect to socket /com/ubuntu/upstart: Connection refused in docker image I am getting
$ sudo initctl list
initctl: Unable to connect to Upstart: Failed to connect to socket /com/ubuntu/upstart: Connection refused

On a docker image that has
$ uname -a
Linux 7276b783e0bf 4.9.125-linuxkit #1 SMP Fri Sep 7 08:20:28 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux

$ cat /etc/redhat-release
CentOS release 6.10 (Final)

Any ideas what is going on? I thought CentOS6 is using Upstart by default.

A: You should just broadly assume that commands like initctl (and systemctl and service) don't work in Docker.  If you're trying to interactively start some new service in a running Docker container, that's not generally a best practice: you need to write a Dockerfile that causes the service to start on its own when the container starts up, usually by just running the server as a foreground process.
A Docker container runs one process (and its children).  Usually that's not an init-type process.  If you docker run --rm -it centos:6 and get a GNU bash shell, that shell is the only process that's running in the container.  Upstart, systemd, and the assorted other system daemons they start won't be there.  (Try ps -e in your shell to see.)
If your actual question is "what Upstart-managed services are running in my CentOS 6 container", the answer is "none".


text:
Q: insert a map in mongodb with java I'm trying to insert a map in mongodb ( in java), but I d'ont know what's the best way to do it.
I translated the contents of an XML file in jsonObject and I put it in a map : XML=>JsonObject JsonObject=>map, now i want to store it in mongodb.
here is the code that store the map in mongodb :
                 Mongo mongo = new Mongo("localhost",27017);
                 DB db = mongo.getDB("mydb");
                 //get a single collection
                 DBCollection collection = db.getCollection("test");

                 //convert JSON to DBObject directly
                  collection.insert(new BasicDBObject(map));
                 DBCursor cursorDoMap = collection.find();
                  while (cursorDoMap.hasNext()){
                      System.out.println(cursorDoMap.next());

                  }

                inputStream.close();
                 mongo.close();}

                catch (UnknownHostException e)
                  {
                            e.printStackTrace();
                  }

                catch (MongoException e)
                  {
                        e.printStackTrace();
                  }
  }

but when I run it I get this error message:
java.lang.IllegalAccessError: tried to access method org.bson.types.ObjectId.<init>(III)V from class com.mongodb.Bytes


text:
Q: Detecting Volume Key press on BlackBerry 10 Java Android Runtime I am trying to port my Android app to the BlackBerry 10, and the detection of the Volume Key press does not seem to work - the key press does not result in my code getting invoked. Here's my code snippet:
public boolean onKeyDown(int keyCode, KeyEvent event)  {
   if (keyCode == KeyEvent.KEYCODE_VOLUME_UP || keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
       // We override the volume key to trigger a special event in our app
       return true;
   } else {
       return super.onKeyDown(keyCode, event);
   }
}

That code above works on an Android phone.
Is there another way for an Android app on BB10 to detect the Volume key press?

A: Apparently detecting the Volume Key press is not supported even for the Native BB10 platform - from the BlackBerry support forums


text:
Q: Introduce a format in a group of tuples I have a tuple:
Tuple = (1, 2, 3)
"to aply str.format in the Tuple"
 def str_sume(Tuple):
     return '{} + {} = {}'.format(*Tuple)
I have two lists:
 L1 = [1, 2, 5]
 L2 = [5, 6, 8]
"to sum L1 and L2"
 def Sum(L1, L2):
     return list(map(lambda x, y: x + y, L1, L2))
SUM = Sum(L1, L2)
table = zip(L1, L2, SUM)
"to create a list of various tuples in wich all them have the str.format"
 def TABLE(table):
     return list(map(lambda triplet: str_sum(triplet), table))
TABLE(table)
 [ ]
The output I was waiting was:
 [('1 + 5 = 6'), ('2 + 6 = 8'), ('5 + 8 = 13')]
I don't understand was the output was an empty list
 I will appreciate somebody explain me way and tell me how to proceed to solve the problem. Thanks


text:
Q: handling a well-formed JSON file of an array of objects A JSON string string passes the jsonlint test.
response = [
  {
    "article" : {
      "info" : {
        "initial" : {
          "articleIds" : [
            "7461221587662919569"
          ],
        }
      },
      "text" : "where they would 'transfer to' next.",
      "lang" : "en",
    }
  },
  {
    "article" : {
      "info" : {
        "initial" : {
          "articleIds" : [
            "6613144915874808065"
          ],
        }
      },
      "text" : "produto regional.",
      "lang" : "pt"
    }
  }
]

However, after processing
require 'json'
file = File.read('/Users/main/jugg//article_samples.js')
data_hash = JSON.parse(file)

One is left with an array, whereas more frequently a hash with a name labels a subsequent array, where one works with that nomenclature such as response['data']
But in this case the array is not accessible via response[0].  How can this be considered as an array in order to process each individual element collection.each do |member|?
A curiosity: data_hash.class => NilClass

A: The response = ... code from article_samples.js is JavaScript, not JSON. This initializes a variable named response with a JavaScript array.
To use this as JSON, then rename the file to article_samples.json and remove response =  from the file. The first line should start with [.
Now your second block of code should work just fine as long as the article_samples.json file is in the correct path.
On a side note, I suggest that you find a way to make the path more flexible. The way you have it currently hard coded is tied directly to your current machine's file system. This won't work if you want to run this code from another machine because the folder /Users/main/jugg probalby won't exist.
If this is a web server with ruby on rails, then one solution is to create an environment variable with the path where this file is stored.


text:
Q: Flipping coin $20$ times
Amy flipped a coin $20$ times, and got the sequence THHTTTHTTHHTHTTTTTHH. She noticed that $3$ times a heads followed a heads, $7$ times a tails followed a tails, $4$ times a tails followed a heads, and $5$ times a heads followed a tails. How many such sequences are possible?

Here's the solution given in the back of the book:

Counting heads and tails based on Amy's observations, we see that

*

*$8$ times a heads follows something,

*$7$ times something follows a heads,

*$11$ times a tails follows something,

*$12$ times something follows a tails.

This implies that any such sequence must have $8$ heads and $12$ tails, and must start with a T and end with an H.

Okay, I've followed the reasoning up to this point. But this next part I don't get.

"$3$ times a heads followed a head" means that the $8$ heads must occur in $8 - 3 = 5$ groups. There are $\binom{7}{4} = 35$ ways to split the $8$ heads into $5$ positive groups. Similarly, "$7$ times a tail followed a tail" means that the $12$ tails must occur in $12 - 7 = 5$ groups; there are $\binom{11}{4} = 330$ ways to split the into groups.
Therefore, there are $(35)(330) = 11550$ solutions.

Can anyone explain why it follows that $8$ heads must occur in $8 -3 = 5$ groups? And why $12$ tails must occur in $12 - 7 = 5$ groups?

A:
Can anyone explain why it follows that $8$ heads must occur in $8−3=5$ groups?

As pointed out in comments, it seems they were counting number of beginnings of groups of $H$. Out of all $H$'s, we are given 3 of $H$s are preceeded by another $H$, so these 3 cannot be a beginning of a group, hence only the remaining $8-3=5$ of $H$s correspond to a group beginning.
However this seems unnecessarily complicated, as we can count number of these groups "directly", without complementing (subtracting) ... Since the whole sequence starts with $T$ (already recognized in the solution), we know all groups of $H$ must start with $TH$, and by problem statement there are exactly $5$ of these...
Or we can also count the number of ends of these groups directly - there are $4$ cases of $HT$, plus there is one case of $H$ at the end of the whole sequence (these are the only two ways the group of $H$ can end), so $4+1=5$ groups in total.
The tails case is similar...


text:
Q: Active class not working in nested routes In my application.hbs file I have an application wide nav bar.

{{#linkTo "about.philosophy"}}ABOUT{{/linkTo}}

//

CONDITIONS

//

PROGRAMS

//

TESTIMONIALS

      {{#if renderAboutSubNav}}
        {{render 'about/subnav'}}
      {{/if}}

{{outlet}}

subnav.hbs:

{{#linkTo "about.philosophy"}}philosophy{{/linkTo}}

//

{{#linkTo "about.leadership"}}leadership{{/linkTo}}

//

staff

The ABOUT link, when clicked, displays a subnav -- displayed whenever the url contains 'about'. In that subnav are about subpages -- philosophy, leadership, staff. Philosophy is actually the index page of the about section, which is why I am linking ABOUT to about.philosophy:
{{#linkTo "about.philosophy"}}ABOUT{{/linkTo}}

When I click ABOUT, the ember app renders /about/philosophy as it is supposed to, and the ABOUT link and philosophy link in the subnav are set to active.
However, when I click 'Leadership' the leadership link on the subnav is active but not the ABOUT link in the main nav, even though the url reads /about/leadership.
I don't understand why it is doing this.
My router looks like this:
Ew.Router.reopen(location: 'history')

Ew.Router.map ->
@.resource "about", ->
    @.route "philosophy"
    @.route "leadership"
    @.resource "staff"
@.route "conditions"
@.route "programs"
@.route "testimonials"

about.hbs:

Eskridge & White

{{outlet}}

    {{partial 'sidebar'}}

A: The problem here is you are linking to about.philosophy, so when you navigate to about.leadership active class won't be applied.
So make your link-to to point about route,
{{#link-to "about"}}ABOUT{{/link-to}}
And from your about.index route, redirect to about.philosophy route,
so that active class will be always applied to about's link-to whenever you are in the child of about route.
A bin for your case.


text:
Q: Export Grid object to pdf without border? When I try to export a Grid object with a White background, I get a gray border around 3 of the 4 sides in the resulting pdf:
grid4pdf = Grid[{{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}}, Background -> White]
Export["thepdfhasborders.pdf", grid4pdf]

I get this as the output pdf:

(the light gray is the Adobe Acrobat Reader background). Any idea why the dark gray border shows up in the pdf, and how I can get rid of it? I typically use the ReverseColor.nb stylesheet, but this behavior persists even in a Default.nb stylesheet notebook.
Thanks in advance!

A:
 Please read up the end: there are white borders with the default stylesheet, and I consider that as a bug in Export!

I don't get the gray borders with Mathematica 12.3.1 on Windows 10 x64:
grid4pdf =
 Grid[{{"a", "b", "c"}, {"d", "e", "f"}, {"g", "h", "i"}},
  Background -> White]
Export["thepdfhasborders.pdf", grid4pdf] // SystemOpen

But there is something interesting that I noticed in the FrontEnd when I selected the Grid object in the output by the mouse. Notice how the FrontEnd draws the blue border around 3 of the 4 sides of the selection:

Since it is the FrontEnd who generates the exported PDF file, I suspect it may be related to the issue you observe. The following experiment supports this:
grid4pdf =
  Grid[{{"█", "█", "█"}, {"█", "█", "█"}, {"█", "█", "█"}},
   Background -> Red];
Image[image = Rasterize[grid4pdf, Background -> Yellow],
 Magnification -> 6]
BorderDimensions[image]

Notice the yellow borders around 3 of the 4 sides in the rasterized version of the grid. In the PDF with the default stylesheet we get white borders:
Export["thepdfhasborders.pdf", grid4pdf] // SystemOpen

Since you mention that you use a custom stylesheet, I suspect that the gray color of the borders may be related to the Background setting in that stylesheet. If you have set your stylesheet as the default one by changing the global DefaultStyleDefinitions option, you can temporarily return it back using the method from this answer:
CurrentValue[$FrontEndSession, DefaultStyleDefinitions] = "Default.nb"
FrontEndTokenExecute["ToggleShowExpression"]
Export["thepdfhasborders.pdf", grid4pdf] // SystemOpen

Or you can try the method from this answer.
Another method is to export a Cell expression with explicit Background option:
Export["thepdfhasborders.pdf",
  Cell[BoxData[ToBoxes[grid4pdf]], "Output",
   Background -> White]] // SystemOpen

P.S. I consider the addition of the borders as a bug in Export since even explicit addition of the options CellFrameMargins -> 0, CellFrame -> False, ShowCellBracket -> False doesn't remove the borders. Please report it to the support.


text:
Q: Angularjs Protractor Test: protractor.Key.DELETE......is this a proper modifier key? I'm trying to the 'protractor.Key.DELETE' to make protractor press the delete key. Any thoughts on how to go about doing this? The following does not work for me:
browser.actions().keyDown(protractor.Key.DELETE).sendKeys().perform();

Protractor give me the following error message:
Failed: Not a modifier key

A: keyDown can only work for modifier keys, such as Alt, SHIFT, CONTROL.
To make protractor press the DELETE key, you can use senKeys like this:
browser.actions().sendKeys(protractor.Key.DELETE).perform();


text:
Q: How to get Array of JSON from SQL select I want to get an array of objects inside of my SQL select.
SELECT id, a.name antibodyName, c.name colorName, c.location colorLocation
FROM Antibodies a
JOIN AssignedColors c ON id = antiId
WHERE colorId IS NOT NULL

and I get this response:
[
  { id: 1, antibodyName: 'antibody 1', colorName: 'red', colorLocation: 'A5/C3' },
  { id: 2, antibodyName: 'antibody 2', colorName: 'red', colorLocation: 'C3/A1' },
  { id: 2, antibodyName: 'antibody 2', colorName: 'yellow', colorLocation: 'E4/F2' }
]

is it possible to get something like this?
[
  { id: 1, antibodyName: 'antibody 1', colors: [{name: 'red, location: 'A5/C3'}] },
  { id: 2, antibodyName: 'antibody 2', colors: [{name: 'red, location: 'C3/A1'}, {name: 'yellow', location: 'E4/F2'}] },
]

A: Use json_build_object and array_agg.
WITH foobar AS (
    SELECT id, a.name antibodyName, c.name colorName, c.location colorLocation
    FROM Antibodies a JOIN AssignedColors c
    ON id = antiId WHERE colorId IS NOT NULL
    )
SELECT
     json_build_object('data',array_agg(json_build_object('id', id, 'antibodyName', antibodyName, 'colorName', colorName, 'colorLocation', colorLocation))
FROM
    foobar

A: a bit rusty, but try this:
SELECT
a.id AS 'Id',
a.Name AS 'antibodyName',
c.Name AS 'name',
c.location AS 'location'
FROM Antibodies a
LEFT JOIN AssignedColors c ON c.id = a.Id
FOR JSON AUTO;

UPDATE: the above is not for SQLite. For SQLite you should checkout the json1 extension here: https://www.sqlite.org/json1.html
ANOTHER UPDATE:
it can be done without the JSON extention...
SELECT
a.id AS 'id',
a.Name AS 'antibodyName',
(SELECT '[' || GROUP_CONCAT('{name:"' || Name || '", location:"' || location || '"}') ||']'
 FROM AssignedColors
 WHERE c.id=Id) AS colors
 FROM Antibodies a
 LEFT JOIN AssignedColors c ON c.id = a.id
 GROUP BY a.id

theres a small issue here: the colors column/node is treated as a string and not an array... this is normal as sqlite doesnt support a column of type array. some parsing will need to be done to convert from string to array...


text:
Q: Interpreting interaction effect with ln(time) in Cox regression I am fitting a Cox proportional hazards model with the interaction effect dummy:ln(time). How would you interpret the result? Is it a simple exp(x)-1)*100 to receive the percentage increase in y?
Edit: I indeed made the mistake @EdM mentioned. This interaction is now set up according to Therneau et al. (2022, pp. 21). I originally wanted to replicate the following model of Schmitt et al. (2011):

In their results, the interaction term was not significant. I added stratification to increase the efficiency of the model. mgm_acquired is a time-invariant binary variable. The result now looks the following:
Call:
coxph(formula = Surv(time, status) ~ mgm_acquired + tt(mgm_acquired) +
    strata(most_frequent_community) + strata(age_group) + strata(reg_month) +
    strata(cluster), data = RG, tt = function(x, t, ...) x *
    log(t))

  n= 119130, number of events= 71720

                      coef exp(coef)  se(coef)      z Pr(>|z|)
mgm_acquired     -0.179475  0.835709  0.047095 -3.811 0.000138 ***
tt(mgm_acquired)  0.011930  1.012002  0.009219  1.294 0.195648
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

                 exp(coef) exp(-coef) lower .95 upper .95
mgm_acquired        0.8357     1.1966    0.7620    0.9165
tt(mgm_acquired)    1.0120     0.9881    0.9939    1.0305

Concordance= 0.503  (se = 0 )
Likelihood ratio test= 46.1  on 2 df,   p=1e-10
Wald test            = 44.28  on 2 df,   p=2e-10
Score (logrank) test = 44.35  on 2 df,   p=2e-10

Four questions emerged in my head:

*

*Is this more realistic now?

*How do I interpret the new coefficient of mgm_acquired?

*How to interpret the interaction effect? Does the absolute value of the coeffcient tell me something?

*Why did Therneau add log(t+20) "to make the first
200 days of the plot roughly linear"? What is the point of the 20?

Thanks!

A: Although the large number of cases makes most of your coefficients "statistically significant," your model is not distinguishing cases very successfully.
The concordance of 0.503 is the fraction of comparable pairs of cases in which the observed and predicted event order agreed. That's barely better than a chance value of 0.500. It's not clear whether all of the stratification you used in the model was necessary or even helpful. For your first question, you must decide if that model and its result is "realistic" based on your understanding of the subject matter.
For the second and third questions, following the example in Section 4.2 of the time dependence vignette, the full mgm_acquired coefficient is $-0.179475 + 0.011930 \log t$. That total association of mgm_acquired with the log-hazard of your event is what you need to focus on.
For example, the value displayed for mgm_acquired itself is for the specific situation $\log t = 0$ or $t=1$. The value of what you call the "interaction effect" (the tt() coefficient) shows how much a change of one log unit in t changes the contribution of mgm_acquired to the log hazard.
Despite the very large number of cases, the time-transformed part of the mgm_acquired coefficient isn't significantly different from 0. So it's hard to argue that there's any substantial time-varying part of the coefficient for mgm_acquired.


text:
Q: Change in node_modules doesn't take effect I have a JS project which installs many modules under node_modules directory. The project is configured to be bundled using webpack. When I make changes to index.js at the root of the project, and then issue "webpack" command, I see the changes. However, when I make a change to a file in a module under node_modules, and then issue "webpack" command, I don't see the changes. Do you have any idea why?
The project is Monaco Editor samples, browser-esm-webpack: https://github.com/Microsoft/monaco-editor-samples/tree/master/browser-esm-webpack
PS: I have already seen comments regarding not to change modules under node_modules. I made sure that all my installations are local and I am not planning to publish this project since it is customized for a very specific need.


text:
Q: Calculating image size ratio for resizing I have a defined fixed width and height to resize an image. However, I have problem a with this, because the image can have any kind of size ratio (it can be vertical or the horizontal). In this case, fixed width and height cause a problem. I want to calculate width and height in a smarter way.
For example lets say I have defined width 1024px and height 768px. And I want to resize an image which is vertical (height 1100px and width 200px). So in my case it will resize to fixed size (1024x768), so the width will be increased from 100px to 768px, and it will be very ugly. Similarly if the image has height less than 768px, it will increase the height by force to 768px.
Therefore I would like to calculate the new image size based on the original image size ratio. Lets say if the above example image should be resized to maximum height of 768px, but then what about the width? it's already less than my "maximum width", which is 200px, so should the width remain unchanged? or should it be further decreased?
Similarly, if the image has the height 200px, and the width 1100px. So the width should be decreased to 1024px, but what about the height?
The third problem is that, let's suppose if both height and width are more than the maximum height and maximum width, let's say width: 1100px and height:4000px. Now since width and height both are more than the maximum width and maximum height but the image is vertical, it will make it horizontal. So how can I check if in this case if I should resize the image according to maximum height, or according to maximum width?
I appreciate any help with this.

A: Here's code from my personal grab bag of image resizing code. First, data you need:
list($originalWidth, $originalHeight) = getimagesize($imageFile);
$ratio = $originalWidth / $originalHeight;

Then, this algorithm fits the image into the target size as best it can, keeping the original aspect ratio, not stretching the image larger than the original:
$targetWidth = $targetHeight = min($size, max($originalWidth, $originalHeight));

if ($ratio < 1) {
    $targetWidth = $targetHeight * $ratio;
} else {
    $targetHeight = $targetWidth / $ratio;
}

$srcWidth = $originalWidth;
$srcHeight = $originalHeight;
$srcX = $srcY = 0;

This crops the image to fill the target size completely, not stretching it:
$targetWidth = $targetHeight = min($originalWidth, $originalHeight, $size);

if ($ratio < 1) {
    $srcX = 0;
    $srcY = ($originalHeight / 2) - ($originalWidth / 2);
    $srcWidth = $srcHeight = $originalWidth;
} else {
    $srcY = 0;
    $srcX = ($originalWidth / 2) - ($originalHeight / 2);
    $srcWidth = $srcHeight = $originalHeight;
}

And this does the actual resizing:
$targetImage = imagecreatetruecolor($targetWidth, $targetHeight);
imagecopyresampled($targetImage, $originalImage, 0, 0, $srcX, $srcY, $targetWidth, $targetHeight, $srcWidth, $srcHeight);

In this case the $size is just one number for both width and height (square target size). I'm sure you can modify it to use non-square targets. It should also give you an inspiration on what other resizing algorithms you can use.

A: $ratio = $originalWidth / $originalHeight

if you want to change the Height:
$targetWidth = $targetHeight * $ratio

if you want to change the Width:
$targetHeight = $targetWidth / $ratio

A: How about this:
double ratio = imageWidth/imageHeight;
int newHeight = Math.min(displayHeight, displayWidth / ratio);
int newWidth =  Math.min(displayWidth, displayHeight * ratio);

A: What you want is to maintain the aspect ratio of your original image. This is the ratio between the width and the height of the image. So you calculate the factor by which you have to resize the image in the vertical and horizontal direction and then you keep the higher of the two. In pseudocode:
target_height = 768
target_width = 1024
# v_fact and h_fact are the factor by which the original vertical / horizontal
# image sizes should be multiplied to get the image to your target size.
v_fact = target_height / im_height
h_fact = target_width / im_width
# you want to resize the image by the same factor in both vertical
# and horizontal direction, so you need to pick the correct factor from
# v_fact / h_fact so that the largest (relative to target) of the new height/width
# equals the target height/width and the smallest is lower than the target.
# this is the lowest of the two factors
im_fact = min(v_fact, h_fact)
new_height = im_height * im_fact
new_width = im_width * im_fact
image.resize(new_width, new_height)

A: this is working.
function calculateDimensions($width,$height,$maxwidth,$maxheight)
{

        if($width != $height)
        {
            if($width > $height)
            {
                $t_width = $maxwidth;
                $t_height = (($t_width * $height)/$width);
                //fix height
                if($t_height > $maxheight)
                {
                    $t_height = $maxheight;
                    $t_width = (($width * $t_height)/$height);
                }
            }
            else
            {
                $t_height = $maxheight;
                $t_width = (($width * $t_height)/$height);
                //fix width
                if($t_width > $maxwidth)
                {
                    $t_width = $maxwidth;
                    $t_height = (($t_width * $height)/$width);
                }
            }
        }
        else
            $t_width = $t_height = min($maxheight,$maxwidth);

        return array('height'=>(int)$t_height,'width'=>(int)$t_width);
    }

A: What you need is to 'maintain' the width/height ratio.
Originally you have an image of size (wxh) 500x1000, this width/height ratio is 0.5 .  Assuming you are changing 1000 to 768 in height, your result width would be 0.5 * 768 = 384.
Another example, 1800 x 1200 and your new height is 200, then your new width is 300 because 300/200 is 1.5 and 1800/1200 is also 1.5.
Good luck.

A: Check the php code below :
$new_width  = 1024;
$new_height = 768;
$this_image = "images/my_image";

list($width, $height, $type, $attr) = getimagesize("$this_image");

if ($width > $height) {
  $image_height = floor(($height/$width)*$new_width);
  $image_width  = $new_width;
} else {
  $image_width  = floor(($width/$height)*$new_height);
  $image_height = $new_height;
}
echo "<img src='$this_image' height='$image_height' width='$image_width'>";

A: You should resize it depending on what property is farer away from the maximum value. Then, calculate the ratio.
if(($w - $w_max) > ($h - $h_max)) {
    $w_new = $w_max;
    $h_new = (int) ($h * ($w_max / $w));
}
else {
    $h_new = $h_max;
    $w_new = (int) ($w * ($h_max / $h));
}

A: I reached this question and didn't find a suitable answer, so i set out on my own to answer the question.
i started with some basic logic, and after consulting a friend of mine who is a bit better at math, this is what we came up with.
function calculate_dimensions($width,$height,$max){
    if($width != $height){
        if($width > $height){
            $t_height = $max;
            $t_width = min(($width * $t_height)/$height);
        }
        if($height > $width){
            $t_width = $max;
            $t_height = min(($t_width * $height)/$width)
        }
    }else{
        if($width > $max){
            $t_width = $t_height = $max;
        }
    }
    $res = ['height'=>$t_height,'width'=>$t_width]
    return $res;
}

This snippet of code is reusable, so knock yourself out. just pass it the maximum smallest dimension allowed, and it will calculate the largest side's dimension, so you will get back a correctly scaled dimension, in which you can then center crop, resulting in a correctly shrinked and cropped image square image. this is useful for things like profile pictures and thumbnails.
credit to my friend, Justin Gillett for his brilliant suggestion of cross multiplication.

A: This example will shrink an image to fit a defined pixel perfect aspect ratio ( 16:9 ) creating an image no larger than a specified limit ( 1200 x 675 ).
Set your image ratio and any upper limit:
const RATIO_W                       = 16;
const RATIO_H                       = 9;
const RATIO_MULIPLIER_UPPER_LIMIT   = 75;

Calculate the new image width and height
list($imageWidth, $imageHeight) = getimagesize($path_to_image);

if( ($imageWidth / $imageHeight) === (self::RATIO_W / self::RATIO_H) ){
    return;

// Find closest ratio multiple to image size
if($imageWidth > $imageHeight){
    // landscape
    $ratioMultiple  = round($imageHeight / self::RATIO_H, 0, PHP_ROUND_HALF_DOWN);
}else{
    // portrait
    $ratioMultiple  = round($imageWidth / self::RATIO_W, 0, PHP_ROUND_HALF_DOWN);
}

$newWidth   = $ratioMultiple * self::RATIO_W;
$newHeight = $ratioMultiple * self::RATIO_H;

if($newWidth > self::RATIO_W * self::RATIO_MULIPLIER_UPPER_LIMIT|| $newHeight > self::RATIO_H * self::RATIO_MULIPLIER_UPPER_LIMIT){
    // File is larger than upper limit
    $ratioMultiple = self::RATIO_MULIPLIER_UPPER_LIMIT;
}

$this->tweakMultiplier($ratioMultiple, $imageWidth, $imageHeight);

$newWidth   = $ratioMultiple * self::RATIO_W;
$newHeight = $ratioMultiple * self::RATIO_H;

Resize image
$originalImage  = imagecreatefromjpeg( $tempImagePath );
$newImage       = imagecreatetruecolor($newWidth, $newHeight);
imagefilledrectangle($newImage, 0, 0, $newWidth, $newHeight, imagecolorallocate($newImage, 255, 255, 255));
imagecopyresampled($newImage, $originalImage, 0, 0, 0, 0, $newWidth, $newHeight, $imageWidth, $imageHeight);
imagejpeg($newImage, $tempImagePath, 100);

Loop through factors until both dimensions are less than the original image size
protected function tweakMultiplier( &$ratioMultiple, $fitInsideWidth, $fitInsideHeight ){
    $newWidth   = $ratioMultiple * self::RATIO_W;
    $newHeight  = $ratioMultiple * self::RATIO_H;

    if($newWidth > $fitInsideWidth || $newHeight > $fitInsideHeight){
        echo " Tweak ";
        $ratioMultiple--;
        $this->tweakMultiplier($ratioMultiple, $fitInsideWidth, $fitInsideHeight);
    }else{
        return;
    }
}

A: If max height or width given or not, using @(jilles de wit) logic
considerations : these should already be defined!
$mh = given height limit; //optional
$mw = given width limit; //optional

$height = $nh =[your original height];
$width = $nw =[your original width];

The Code
if($mh || $mw){
if(is_numeric($mh)){$h_fact = $mh / $nh;}
if(is_numeric($mw)){$v_fact = $mw / $nw;}

if(is_numeric($v_fact) && is_numeric($h_fact)  ){$im_fact = min($v_fact, $h_fact);}else{$im_fact=is_numeric($v_fact)?$v_fact:$h_fact;}
$nw = $nw * $im_fact;
$nh = $nh * $im_fact;
}

resampling
$dst_img = imagecreatetruecolor($nw,$nh);
imagecopyresampled ($dst_img, $image, 0, 0, 0, 0, $nw, $nh, $width , $height);

A: get the nearest Ratio
$r=getRatio(820,460);//41:23
$r=getRatio(160,40);//4:1
$r=getRatio(1743,367);//1743:367

function getRatio($num1, $num2){

    if(abs($num1-$num2)<10 && $num1>100){
        $num1=$num2;
    }
    for($i = $num2; $i > 1; $i--) {
        if((($num1 % $i) == 0 && ($num2 % $i) == 0) ) {
            $num1 = $num1 / $i;
            $num2 = $num2 / $i;
        }
    }
    return round($num1,1).':'.round($num2,1);
}

A: class Image_Aspect_Ratio_Resize {
var $image_to_resize;
var $new_width;
var $new_height;
var $ratio;
var $new_image_name;
var $save_folder;

function resize() {
    if (!file_exists($this->image_to_resize)) {
        exit("File " . $this->image_to_resize . " does not exist.");
    }

    $info = GetImageSize($this->image_to_resize);

    if (empty($info)) {
        exit("The file " . $this->image_to_resize . " doesn't seem to be an image.");
    }

    $width = $info[0];
    $height = $info[1];
    $mime = $info['mime'];

    /* Keep Aspect Ratio? */

    if ($this->ratio) {
        $thumb = ($this->new_width < $width && $this->new_height < $height) ? true : false; // Thumbnail
        $bigger_image = ($this->new_width > $width || $this->new_height > $height) ? true : false; // Bigger Image

        if ($thumb) {
            if ($this->new_width >= $this->new_height) {
                $x = ($width / $this->new_width);

                $this->new_height = ($height / $x);
            } else if ($this->new_height >= $this->new_width) {
                $x = ($height / $this->new_height);

                $this->new_width = ($width / $x);
            }
        } else if ($bigger_image) {
            if ($this->new_width >= $width) {
                $x = ($this->new_width / $width);

                $this->new_height = ($height * $x);
            } else if ($this->new_height >= $height) {
                $x = ($this->new_height / $height);

                $this->new_width = ($width * $x);
            }
        }
    }

    $type = substr(strrchr($mime, '/'), 1);

    switch ($type) {
        case 'jpeg':
            $image_create_func = 'ImageCreateFromJPEG';
            $image_save_func = 'ImageJPEG';
            $new_image_ext = 'jpg';
            break;

        case 'png':
            $image_create_func = 'ImageCreateFromPNG';
            $image_save_func = 'ImagePNG';
            $new_image_ext = 'png';
            break;

        case 'bmp':
            $image_create_func = 'ImageCreateFromBMP';
            $image_save_func = 'ImageBMP';
            $new_image_ext = 'bmp';
            break;

        case 'gif':
            $image_create_func = 'ImageCreateFromGIF';
            $image_save_func = 'ImageGIF';
            $new_image_ext = 'gif';
            break;

        case 'vnd.wap.wbmp':
            $image_create_func = 'ImageCreateFromWBMP';
            $image_save_func = 'ImageWBMP';
            $new_image_ext = 'bmp';
            break;

        case 'xbm':
            $image_create_func = 'ImageCreateFromXBM';
            $image_save_func = 'ImageXBM';
            $new_image_ext = 'xbm';
            break;

        default:
            $image_create_func = 'ImageCreateFromJPEG';
            $image_save_func = 'ImageJPEG';
            $new_image_ext = 'jpg';
    }

    // New Image
    $image_c = ImageCreateTrueColor($this->new_width, $this->new_height);

    $new_image = $image_create_func($this->image_to_resize);

    ImageCopyResampled($image_c, $new_image, 0, 0, 0, 0, $this->new_width, $this->new_height, $width, $height);

    if ($this->save_folder) {
        if ($this->new_image_name) {
            $new_name = $this->new_image_name . '.' . $new_image_ext;
        } else {
            $new_name = $this->new_thumb_name(basename($this->image_to_resize)) . '_resized.' . $new_image_ext;
        }

        $save_path = $this->save_folder . $new_name;
    } else {
        /* Show the image without saving it to a folder */
        header("Content-Type: " . $mime);

        $image_save_func($image_c);

        $save_path = '';
    }

    $process = $image_save_func($image_c, $save_path);

    return array('result' => $process, 'new_file_path' => $save_path);
}}

/* Function Call */
$resize_image = new Image_Aspect_Ratio_Resize;
$new_width = (int) $_POST['new_width'];
$new_height = (int) $_POST['new_height'];
$resize_image->new_width = $new_width;
$resize_image->new_height = $new_height;
$resize_image->image_to_resize = $image; // Full Path to the file
$resize_image->ratio = true; // Keep aspect ratio
// Name of the new image (optional) - If it's not set a new will be added automatically
$resize_image->new_image_name = 'water_lilies_thumbnail';
/* Path where the new image should be saved. If it's not set the script will output the image without saving it */
$resize_image->save_folder = 'thumbs/';
$process = $resize_image->resize(); // Output image