text:
Q: Coefficient of $x^9$ in the Product Find the Coefficient of $x^9$ in $$G(x)=(1+x)(1+x^2)(1+x^3)(1+x^4)\cdots(1+x^{100})$$
My Try:
$$G(x)=P(x)(1+x^{10})(1+x^{11})\cdots(1+x^{100})=P(x)(1+O(x^{10}))$$ Hence Coefficient of $x^9$ in $G(x)$ is Coefficient of $x^9$ in $P(x)$ where $$P(x)=(1+x)(1+x^2)(1+x^3)\cdots(1+x^9)=R(x)+x^9R(x)$$  So Coefficient of $x^9$ in $P(x)$ is $1$+coeff of $x^9$ in $ R(x)$ where $$R(x)=(1+x)(1+x^2)\cdots(1+x^8)$$
But the method is becoming lengthy. Can i have any good approach

A: HINT: The desired coefficient is the number of ways to express $9$ as a sum of distinct positive integers. Since $1+2+3+4>9$, you need only consider sums of at most three integers.

A: Take some of the terms say like 1, $x^1 , x^3 , x^5 $ then their product will be $x^{9}$ with coefficient 1, similarly for other $x^9$ terms you need terms whose products give $x^9$, i.e no of ways to express 9 as a product of integers (order does not matter).

A: You can just try to find the different ways to decompose $9$ into different integers:
$$ 9 = a_1 + a_2 + \cdots + a_k, \, \, k\in \mathbb{N}, \, 1 \le a_1 < a_2 < \cdots < a_k$$
Since those would be the only possible ways a monome in the developed expression of $G(x)$ to have degree of $9$.

A: Just as other answers, the coefficient of $x^9$ is the number of ways to express $9$ into sum of distinct integers.
And this remind me of Euler's Partition function and the Pentagonal number theorem.
Euler has proved that for number of ways to express an integer into sum of distinct integers, $q(n)$, there is a recurrence relation:
$$q(n)=a_k+q(n-1)+q(n-2)-q(n-5)-q(n-7)+...$$
where $q(n)=0$ if $n<0$ and $a_k$ is $(−1)^m$ if $\exists m\in{\Bbb{N}},k = 3m^2 − m $ and is $0$ otherwise.
So you may reduce $q(9)$ into $q(8)+q(7)-q(4)-q(2)$ and to reduce further to make it simplier to calculate. For instance it is easy to check value of $q(0), q(1)$, etc for small value of $n$.
For more straightforward way, you may just check the sequence A000009 in OEIS. And we get $q(9)=8$
Reference:
Wiki
https://en.wikipedia.org/wiki/Partition_(number_theory)
OEIS
https://oeis.org/A000009


text:
Q: RestAssured: Post Request return 500 Server Error I practicing web services using RestAssured. In the post request, it return 500 server error where i using postman to send the request and there is no error.
Can anyone help me debug the error? Please give some opinion. Any help is appreciate? Thanks in advance.
@BeforeSuite
    public void setup() {
        RestAssured.reset();
        ProxySpecification ps = new ProxySpecification("localhost", 8080, "http");
        RestAssured.proxy(ps);

        RestAssured.baseURI = "https://jsonplaceholder.typicode.com/";
        RestAssured.port = 443;
    }

@Test(groups="createUser")
    public void createUser() {
        given()
            .param("userId", 1234)
            .param("id", 82342)
            .param("title", "Senior Software Engineer")
            .param("body", "Scrum Org").
        when()
            .request("POST", "/posts").
        then()
            .statusCode(200);

    }

Error Message is Expected status code <200> but was <500>.
Stacktrace:

at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native
  Method)   at
  sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown
  Source)   at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at
  org.codehaus.groovy.reflection.CachedConstructor.invoke(CachedConstructor.java:83)
    at
  org.codehaus.groovy.reflection.CachedConstructor.doConstructorInvoke(CachedConstructor.java:77)
    at
  org.codehaus.groovy.runtime.callsite.ConstructorSite$ConstructorSiteNoUnwrap.callConstructor(ConstructorSite.java:84)
    at
  org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallConstructor(CallSiteArray.java:59)
    at
  org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:238)
    at
  org.codehaus.groovy.runtime.callsite.AbstractCallSite.callConstructor(AbstractCallSite.java:250)
    at
  io.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure.validate(ResponseSpecificationImpl.groovy:483)
    at
  io.restassured.internal.ResponseSpecificationImpl$HamcrestAssertionClosure$validate$1.call(Unknown
  Source)   at
  org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:47)
    at
  org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at
  org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:128)
    at
  io.restassured.internal.ResponseSpecificationImpl.validateResponseIfRequired(ResponseSpecificationImpl.groovy:655)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  at
  sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)   at
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)   at
  java.lang.reflect.Method.invoke(Unknown Source)   at
  org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite$PogoCachedMethodSiteNoUnwrapNoCoerce.invoke(PogoMetaMethodSite.java:210)
    at
  org.codehaus.groovy.runtime.callsite.PogoMetaMethodSite.callCurrent(PogoMetaMethodSite.java:59)
    at
  org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:51)
    at
  org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:157)
    at
  org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:169)
    at
  io.restassured.internal.ResponseSpecificationImpl.statusCode(ResponseSpecificationImpl.groovy:123)
    at
  io.restassured.specification.ResponseSpecification$statusCode$0.callCurrent(Unknown
  Source)   at
  org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCallCurrent(CallSiteArray.java:51)
    at
  org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:157)
    at
  org.codehaus.groovy.runtime.callsite.AbstractCallSite.callCurrent(AbstractCallSite.java:169)
    at
  io.restassured.internal.ResponseSpecificationImpl.statusCode(ResponseSpecificationImpl.groovy:131)
    at
  io.restassured.internal.ValidatableResponseOptionsImpl.statusCode(ValidatableResponseOptionsImpl.java:119)
    at com.peterwkc.services.Main.createUser(Main.java:75)

A: You have to send JSON body instead of parameters. Then your request will look like this:
given()
    .contentType(ContentType.JSON)
    .body("{"
        + "\"userId\": 1234,"
        + "\"id\": 823823,"
        + "\"title\": \"Title\","
        + "\"body\": \"Scrum\""
        + "}"
    )
    .when()
    .request("POST", "/posts").
    then()
    .statusCode(201);

There is official wiki page with a lot of useful examples here:
https://github.com/rest-assured/rest-assured/wiki

A: Add given().contentType(ContentType.JSON) as a first step in the chain started from given() to send JSON as is instead of the request body being infered from parameters.
Example:
given()
    .contentType(ContentType.JSON)
        .body(request.toJSONString())
        .when()
            .post("https:xvz.com")
            .then().statusCode(200);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Find overlapping prescriptions I have a bunch of patient prescriptions, each having a certain start date and an end date. I would like to find the instances where a patient has been taking more than one drug in the same drug category for more than 2 days. duration should overlap.
Table structure looks like this:
PatientID  StartDate  EndDate    Drug        DrugCategory
1          1/1/2013   1/5/2013   A           Cat1
1          1/1/2013   1/4/2013   B           Cat1
1          1/10/2013  1/12/2013  C           Cat1
2     .......    ........   .............  .........

As seen above, Patient-1 was prescribed 3 drugs in the same category and the first two drug overlapped in duration more than 2 days. So, for this example, I would like the query return the first two records for Patient-1 along with drug name, patientid.
Hope someone can help. This is using SQL Server 2008 R2 btw.

A: Do you want them as separate rows or as one row?  If you want them as separate rows, this should work; otherwise you can pivot the result.
create table want as
    select H.* from have H, have V
        where H.drug ne V.drug
            and H.PatientID=V.PatientID
            and H.startDate <= V.startDate
            and V.startDate <= H.endDate-2
    union select V.* from have H, have V
        where H.drug ne V.drug
            and H.PatientID=V.PatientID
            and H.startDate <= V.startDate
            and V.startDate <= H.endDate-2
            ;

I union the H and V records, I'm sure there's a more efficient way to do that but couldn't easily come up with one.  (Just H works for the example given, but for a more proper example where the start dates are not always equal you need the V row as well.)

A: Please test this thoroughly before using. I have tested it and so far it looks good but not done an exhaustive testing. Would be great if you can test it out further sufficient to your requirements and can point any anomalies in the result if present or take it forward and modify if required.
--Test data:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Prescriptions](
    [PatientID] [int] NULL,
    [StartDate] [datetime] NULL,
    [EndDate] [datetime] NULL,
    [Drug] [varchar](50) NULL,
    [DrugCategory] [varchar](50) NULL
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
INSERT [dbo].[Prescriptions] ([PatientID], [StartDate], [EndDate], [Drug], [DrugCategory]) VALUES (1, CAST(0x0000A13A00000000 AS DateTime), CAST(0x0000A13E00000000 AS DateTime), N'D', N'Cat1')
INSERT [dbo].[Prescriptions] ([PatientID], [StartDate], [EndDate], [Drug], [DrugCategory]) VALUES (1, CAST(0x0000A13A00000000 AS DateTime), CAST(0x0000A13B00000000 AS DateTime), N'E', N'Cat1')
INSERT [dbo].[Prescriptions] ([PatientID], [StartDate], [EndDate], [Drug], [DrugCategory]) VALUES (1, CAST(0x0000A13800000000 AS DateTime), CAST(0x0000A13B00000000 AS DateTime), N'F', N'Cat1')
INSERT [dbo].[Prescriptions] ([PatientID], [StartDate], [EndDate], [Drug], [DrugCategory]) VALUES (1, CAST(0x0000A13800000000 AS DateTime), CAST(0x0000A13900000000 AS DateTime), N'G', N'Cat1')
INSERT [dbo].[Prescriptions] ([PatientID], [StartDate], [EndDate], [Drug], [DrugCategory]) VALUES (1, CAST(0x0000A12300000000 AS DateTime), CAST(0x0000A13900000000 AS DateTime), N'Z', N'Cat1')
INSERT [dbo].[Prescriptions] ([PatientID], [StartDate], [EndDate], [Drug], [DrugCategory]) VALUES (1, CAST(0x0000A12300000000 AS DateTime), CAST(0x0000A13A00000000 AS DateTime), N'Y', N'Cat1')
INSERT [dbo].[Prescriptions] ([PatientID], [StartDate], [EndDate], [Drug], [DrugCategory]) VALUES (1, CAST(0x0000A13900000000 AS DateTime), CAST(0x0000A13D00000000 AS DateTime), N'A', N'Cat1')
INSERT [dbo].[Prescriptions] ([PatientID], [StartDate], [EndDate], [Drug], [DrugCategory]) VALUES (1, CAST(0x0000A13900000000 AS DateTime), CAST(0x0000A13C00000000 AS DateTime), N'B', N'Cat1')
INSERT [dbo].[Prescriptions] ([PatientID], [StartDate], [EndDate], [Drug], [DrugCategory]) VALUES (1, CAST(0x0000A14200000000 AS DateTime), CAST(0x0000A14400000000 AS DateTime), N'C', N'Cat1')

Query Used:
SELECT DISTINCT PatientID,StartDate,EndDate,Drug,DrugCategory FROM (
SELECT
    DATEDIFF(dd,a.startdate,b.startdate) c1
    ,DATEDIFF(dd,a.enddate,b.enddate)c2
    ,DATEDIFF(dd,a.startdate,b.enddate) c3
    ,DATEDIFF(dd,a.enddate,b.startdate) c4
    ,DATEDIFF(dd,a.startdate,b.enddate)+DATEDIFF(dd,a.enddate,b.startdate) c34
    ,a.PatientID
    ,a.StartDate
    ,a.EndDate
    ,a.Drug
    ,a.DrugCategory
    ,b.PatientID  AS PatientID1
    ,b.StartDate  AS StartDate1
    ,b.EndDate   AS EndDate1
    ,b.Drug   AS Drug1
    ,b.DrugCategory  DrugCategory1
FROM Prescriptions a
,Prescriptions b
WHERE a.patientid=b.patientid
AND a.DrugCategory= b.DrugCategory
and a.drug<>b.drug
)a
WHERE c1*c2*c3*c4 <0
AND c3>2
and c4<=-2
ORDER BY 1,2,3,4

Results:
PatientID   StartDate               EndDate                 Drug                                               DrugCategory
----------- ----------------------- ----------------------- -------------------------------------------------- --------------------------------------------------
1           2012-12-10 00:00:00.000 2013-01-02 00:00:00.000 Y                                                  Cat1
1           2012-12-31 00:00:00.000 2013-01-03 00:00:00.000 F                                                  Cat1
1           2013-01-01 00:00:00.000 2013-01-04 00:00:00.000 B                                                  Cat1
1           2013-01-01 00:00:00.000 2013-01-05 00:00:00.000 A                                                  Cat1
1           2013-01-02 00:00:00.000 2013-01-06 00:00:00.000 D                                                  Cat1

(5 row(s) affected)

A: what you should be able to do is join the prescription table to itself on the patientID and drugCategory fields where the drugName differs and the startDate OR endDate of the 2nd instance spans the startDate/endDate of the first.  Then, determine the overlap range by subtracting the number of days between the max(startDates) and min(endDates).  If the overlap is greater than 2 days, return the row:
select *, datediff(d, start_max, end_min) as overlap
from (
    SELECT
      P.PatientID, P.StartDate, P.EndDate, P.Drug, P.DrugCategory,
      P1.StartDate AS p1_start, P1.EndDate AS p1_end, P1.Drug AS p1_drug,
      CASE WHEN p.startdate >= P1.startdate THEN p.startdate ELSE P1.startdate END AS start_max,
      CASE WHEN p.EndDate <= P1.EndDate THEN p.EndDate ELSE P1.EndDate END AS end_min
    FROM
      dbo.Prescriptions p INNER JOIN
      dbo.Prescriptions AS P1 ON
      P.PatientID = P1.PatientID AND
      P.DrugCategory = P1.DrugCategory AND
      P.Drug <> P1.Drug
    WHERE
      (P1.StartDate >= P.StartDate AND P1.StartDate <= P.EndDate) OR
      (P1.EndDate >= P.StartDate AND P1.EndDate <= P.EndDate)
) t
where
datediff(d, start_max, end_min) > 2


text:
Q: Can someone give an example of a function that is not Henstock-Kurzweil/gauge integrable? I am looking for an example of a function that is not Henstock-Kurzweil integrable. Can anybody help me?

A: Take any infinite series $a$, and let $f(x)$ be $a_{\lfloor{x}\rfloor}$ (where $\lfloor{x}\rfloor$ is the greatest integer that is not greater than $x$, that is $x$ rounded down to an integer).  In general, $$ \int_i^j f(x) \,\mathrm{d}x = \sum_{n = i}^{j-1} a_n ,$$ whenever $i$ and $j$ are integers.  As stated, this is a fine Riemann integral, but change $j$ to $\infty$ and we have:

*

*$ \int_i^\infty f(x) \,\mathrm{d}x = \sum_{n = i}^\infty a_n $ as a Lebesgue integral iff $a$ is absolutely convergent;

*$ \int_i^\infty f(x) \,\mathrm{d}x = \sum_{n = i}^\infty a_n $ as an improper Riemann integral iff $a$ is convergent (possibly conditionally);

*$ \int_i^\infty f(x) \,\mathrm{d}x = \sum_{n = i}^\infty a_n $ also as a Henstock–Kurzweil integral iff $a$ is convergent (possibly conditionally).

So any divergent series gives a Henstock–Kurzweil nonintegrable function.  The harmonic series, for example, gives $f(x) = 1/\lfloor{x}\rfloor$, which is not integrable.
OK, so just plain $1/x$ is an even simpler nonintegrable function, but I think that if you keep in mind the relationship between Lebesgue vs Henstock and absolute vs conditional convergence, then it will seem more obvious to you that, while Henstock–Kurzweil makes more functions integrable, it does not make all functions integrable.

A: Theorem. If function $f: [a,b] \to \mathbb{R}$ is Henstock-Kurzweil integrable, then $f$ is a Lebesgue measurable function.
You can find proof of the above theorem in "The integrals of Lebesgue, Denjoy, Perron, and Henstock" by Russel Gordon (Theorem 9.12).
Thus a characteristic function of a non-measurable set would be an example you are looking for.


text:
Q: Background image on Phonegap causes incredible slowness? So after much frustration, I finally pin-pointed the problem. The following causes severe decline in speed in my phonegap app:
body.default {
    background: #000000 url(../img/background.jpg) no-repeat center top fixed;
    background-size: cover;
}

The image was 1500 x 1500 pixels and about 350Kb. I optimized it a bit and decreased the dimensions to 1000 x 1000. This resulted in a final size of 106Kb.
The problem is, even when I make it smaller like this, it still slows down the app considerably. However if I have this:
body.default {
    background: none;
    background-size: cover;
}

Then the speed is nice and fast. So I know the background is causing the slowness.
What can I do to still show a good quality as the background, without killing performance?
UPDATE
I've managed to get an "ok" result if I decrease the image size to 36 kb. Of course, then I loose a lot of the quality, but it has an overlay, so it's not that noticeable. However, I think that it might be background-size: cover, that might be inefficient, but I haven't tested that yet. I will keep trying...


text:
Q: Python match filenames and put in a folder Im trying to match all filenames in a folder, and put them into there own seperate folder with the name of the files.  Heres an example:
2015-05-14#6449618a-f819-4d71-83ad-a1e4c2fe9bc1.csv
2015-05-14#6449618a-f819-4d71-83ad-a1e4c2fe9bc1.xml
2015-05-14#6449618a-f819-4d71-83ad-a1e4c2fe9bc1.doc
2015-05-14#6449618a-f819-4d71-83ad-a1e4c2fe9bc1.dox

2015-05-14#7449618a-f819-4d71-83ad-a1e4c2fe9bc1.csv
2015-05-14#7459618a-f819-4d71-83ad-a1e4c2fe9bc1.xml
2015-05-14#7459618a-f819-4d71-83ad-a1e4c2fe9bc1.doc
2015-05-14#7459618a-f819-4d71-83ad-a1e4c2fe9bc1.doc

I want to group these files into a folder, with the foldername being
2015-05-14#7449618a-f819-4d71-83ad-a1e4c2fe9bc1
2015-05-14#6449618a-f819-4d71-83ad-a1e4c2fe9bc1

Keep in mind there are hundreds of these files in a folder, I am trying to make them neater :)
What I got so far..
for file in os.listdir(src_path):
    if not os.path.isdir(dest_path + file.split("-")[:11]):
       os.mkdir(dest_path + file.split("-")[0])
shutil.copy(src_path + file, dest_path + file.split("-")[:11])

My thoughts were to match the first 11 digits..

A: If you are looking to extract this:
2015-05-14#7449618a-f819-4d71-83ad-a1e4c2fe9bc1
You could grab the folder name you want much easier by simply splitting on the dot using splitext from os.path:
fname, fext = os.path.splitext('2015-05-14#6449618a-f819-4d71-83ad-a1e4c2fe9bc1.csv')

fname will hold 2015-05-14#7449618a-f819-4d71-83ad-a1e4c2fe9bc1
fext will hold csv
Extra bit of information. Refrain from using file, it is a built-in for Python: https://docs.python.org/2/library/functions.html#file
It could lead to problems. Try fname or simply f.

A: I think that you would be better off running with:
file.rsplit(".",1)[0]

which would give you the path name to use for your directory.
The reason for using rsplit rather than split is just in case your files names have more than one full-stop in them
Note that you could achieve the same result with:
file.rpartition(".")[0]


text:
Q: Android Auto Reject After Change to API 32 after forcing change to api 32 my app are reject every time i try to publish a new app or an update.
The reason is every time the same
"Your app does not respond (no music played or error message shown) after issuing a voice command."
Or:
Voice commands
Media Apps
Your app does not respond (no music played or error message shown) after issuing a voice command.
Messaging Apps
Your app does not respond to "Reply" when confirming or editing custom messages.
Your app does not respond to "Reply," "Send It," or "Cancel".
Nav Apps
Your app does not respond after issuing a voice command.
But on my side the app works fine!
I cannot able to search what is happened, i've only change the api level to 32.
I've ask to review team an help and they reply that can't help me.
What can i do? this manifest will be ok?
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.inmystream.radiox">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
    <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

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

    <uses-feature
        android:name="android.hardware.telephony"
        android:required="false" />

    <uses-feature
        android:name="android.hardware.wifi"
        android:required="false" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">
        <meta-data
            android:name="com.google.android.gms.car.application"
            android:resource="@xml/automotive_app_desc" />

        <activity
            android:name="stereopesaro.mactechinteractiv.stereopesaro.MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:launchMode="singleInstance"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.media.action.MEDIA_PLAY_FROM_SEARCH" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
        <meta-data
            android:name="com.google.android.gms.car.notification.SmallIcon"
            android:resource="@mipmap/ic_launcher" />

        <service
            android:name="stereopesaro.mactechinteractiv.stereopesaro.AutoMediaBrowserService"
            android:exported="true"
            tools:ignore="ExportedService">
            <intent-filter>
                <action android:name="android.media.browse.MediaBrowserService" />
                <action android:name="android.intent.action.MEDIA_BUTTON" />
            </intent-filter>
        </service>
        <!--<receiver-->
        <!--android:name="stereopesaro.mactechinteractiv.stereopesaro.Utils.NetworkChangeReceiver"-->
        <!--android:label="NetworkChangeReceiver">-->
        <!--<intent-filter>-->
        <!--<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />-->
        <!--</intent-filter>-->
        <!--</receiver>-->

        <!-- END PushWoosh activities and services -->
        <service android:name="stereopesaro.mactechinteractiv.stereopesaro.radio.RadioService" />
        <!-- A receiver that will receive media buttons and send as
          intents to your MediaBrowserServiceCompat implementation.
          Required on pre-Lollipop. More information at
          https://developer.android.com/reference/androidx/media/session/MediaButtonReceiver -->

        <receiver android:name="androidx.media.session.MediaButtonReceiver"
            android:exported="true"
            >

            <intent-filter>
                <action android:name="android.intent.action.MEDIA_BUTTON" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

this is my build grade:
apply plugin: 'com.android.application'
android {
    compileSdkVersion 31
    buildToolsVersion '30.0.3'

    defaultConfig {
        applicationId "com.inmystream.studio54radio"
        minSdkVersion 21
        targetSdkVersion 31
        versionCode 9
        versionName '1.2'
        multiDexEnabled true

        /*lintOptions {
            checkReleaseBuilds false
            // Or, if you prefer, you can continue to check for errors in release builds,
            // but continue the build even when errors are found:
            abortOnError false
        }*/

    }
    compileOptions {
        targetCompatibility JavaVersion.VERSION_1_8
                sourceCompatibility JavaVersion.VERSION_1_8

    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
        debug {

        }
    }

    productFlavors {
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'jp.wasabeef:blurry:4.0.0'
    implementation 'com.android.support:multidex:1.0.3'
    implementation 'org.greenrobot:eventbus:3.2.0'
    implementation 'androidx.work:work-runtime-ktx:2.7.0'
    implementation 'androidx.appcompat:appcompat:1.5.0'
    implementation "androidx.media:media:1.6.0"
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.squareup.picasso:picasso:2.5.2'
    implementation 'com.squareup.okhttp3:okhttp:4.5.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.recyclerview:recyclerview:1.2.1'
    implementation 'com.karumi:dexter:6.1.2'
    implementation 'pub.devrel:easypermissions:0.4.3'
    implementation 'com.google.android.exoplayer:exoplayer:2.14.0'
}

before of api change it works and approved...
thanks who can help me!
help to solve this issue


text:
Q: How to find link between /dev/video and lsusb output Linux exposes camera interfaces at /dev/video* but that interface doesn't describe the make/model of the camera. Meanwhile, lsusb reports the make/model of all USB devices, including the cameras, but it doesn't tell you which /dev file they correspond to. How do I link a device reported by lsusb to a /dev/video* file?

A: Checking /sys/class/video4linux/video$N/name and /sys/class/video4linux/video$N/device/driver/* will give give you data, that you will let you find the lsusb line.


text:
Q: Placing an object on right position (Java) I have a simple test that looks like
public class Game {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Board b1 = new Board();
        Knight bk = new Knight(Player.BLACK);
        b1.placePiece(0, 0, bk);
        System.out.println(b1.getPiece(0, 0));

    }

}

And this is supposed to print out "bk" since that is placed on (0, 0) of Board b1. But it returns null in reality.
My Board class looks like this:
the getPiece should return the piece on board[x][y] but of course it won't since there is nothing on board[x][y]. I know what's wrong, but I am not sure how to fix this.
My Piece class looks like:
public abstract class Piece {

    Player color;
    int x, y;

    Piece(Player color){
        this.color = color;

    }

...

}

So, I am not sure how to make it possible to have board[x][y] a correct value which is the right Piece object.
EDIT:
EDIT2:
public class Board {

....

}

A: You need to initialize Board
board = new Piece[rows][cols]

Consider do that inside the constructor
Update:
To get name you should add member name to Piece class
abstract class Piece {

        java.awt.Color color;
        String name;
        int x, y;

        Piece(java.awt.Color color, String name) {
            this.color = color;
            this.name = name;

        }

        @Override
        public String toString() {
            return "Piece{" +
                    "color=" + color +
                    ", name='" + name + '\'' +
                    ", x=" + x +
                    ", y=" + y +
                    '}';
        }
    }

class Knight extends Piece {

        Knight(Color color, String name) {
            super(color, name);
        }

        @Override
        public boolean equals(Object obj) {
            Knight that = (Knight) obj;
            return this.color == that.color && this.name.equals(that.name);
        }
    }

Overriding string will cause
System.out.println(new Knight(Color.BLACK, "Robin Hood"));

to print
Piece{color=java.awt.Color[r=0,g=0,b=0], name='Robin Hood', x=0, y=0}


text:
Q: Is there a way to retrieve the HTML code of a webpage which is generated based on input values on a different webpage? I'm trying to get the HTML code of https://www.example.com/mcqRegionList which otherwise "doesn't exist", but is generated based on the value selected on "Select Level" dropdown menu on the page https://www.example.com/mcqLevelList.
Snapshot of the HTML code of https://www.example.com/mcqLevelList is like:

And then we have:

    Select Level
     Select Region
     Select City

      <select name="levelCode" id="mcqLevel">
        <option value="-1">Select Level</option>
        <option value="05">UPPER</option>
        <option value="03">LOWER</option>
        <option value="01">MIDDLE</option>
        <option value="02">LEFT</option>
        <option value="04">RIGHT</option>
      </select>

      <select>
        <option value="">Select Region</option>
      </select>

      <select>
        <option value="">Select City</option>
      </select>

So far, I've tried this:
from selenium import webdriver
from selenium.webdriver.support.ui import Select

Stdriver = webdriver.Firefox()
Stdriver.get('https://www.example.com/mcqLevelList')

Select(Stdriver.find_element_by_tag_name("select")).select_by_index(2)
Stdriver.get('https://www.example.com/mcqRegionList')
Stdriver.find_element_by_id('mcqRegion').select_by_index(2)

However, getting an error message at the last line:
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="mcqRegion"]


text:
Q: Ubuntu 18.04 - Second External Monitor not Working [Nvidia GTX 1650] I searched on the web for many different solutions. Nothing worked.
Situation:
I have a Dell XPS 15 with a Nvidia GTX 1650.
Installed Ubuntu 18.04 and ran a tweak script (https://github.com/JackHack96/dell-xps-9570-ubuntu-respin/blob/master/xps-tweaks.sh) which adds the xorg configuration file: https://github.com/JackHack96/dell-xps-9570-ubuntu-respin/blob/master/10-prime-offload.conf. I use an original Dell docking station and have monitors linked with Display Port.
Problem:
I cannot connect two external monitors. One external monitor is working perfect.

*

*Connecting the second external monitor during startup ends in a freeze.

*Connecting after start up: The monitor is listed in "Displays" Settings of Ubuntu. But I cannot active it. Running the command xrandr --output DP-1-2 --mode 2560x1440 --pos 3840x0 --rotate normal is not working with error: xrandr: Configure crtc 2 failed. When I activate the display in the Display settings, it gets switched off after applying the changes.

I have nvidia-prime installed and selected nvidia as the default gpu.
I have the driver: nvidia-driver-435 (open source) installed. Tried also with different kernels as I read that there probably is a problem. Now running on 5.2.17-050217-generic.
When changing to terminal (Ctrl + Alt + F2 / F3) all three displays are showing up as mirrors.
Thanks in advance for any help.

A: I would check different versions of driver.
In my case nvidia-418 is the newest one, with works properly with external monitors.
sudo apt-get purge nvidia*

sudo apt-get install nvidia-xxx


text:
Q: Determine orthotropic axes of Stiffness Tensor Consider a fourth oder stiffness tensor $\mathbb{C}$. The components $C_{ijkl}$ are given with respect to a global coordinate system. Is there a way to determine the orthotropic axes from this representation?
In Mandel-Kelvin-Notation we can express the tensor as $6\times6$-Matrix
\begin{equation}
\mathbb{C} =
\begin{pmatrix}
\tilde{C}_{11} & \tilde{C}_{12} & \tilde{C}_{13} & \tilde{C}_{14} & \tilde{C}_{15} & \tilde{C}_{16} \\
 & \tilde{C}_{22} & \tilde{C}_{23} & \tilde{C}_{24} & \tilde{C}_{25} & \tilde{C}_{26} \\
& & \tilde{C}_{33} & \tilde{C}_{34} & \tilde{C}_{35} & \tilde{C}_{36}  \\
& & & \tilde{C}_{44} & \tilde{C}_{45} & \tilde{C}_{46} \\
&  \text{sym} & & & \tilde{C}_{55} & \tilde{C}_{56} \\
 & & & & & \tilde{C}_{66}
\end{pmatrix} \tilde{\boldsymbol{B}}_\alpha \otimes \tilde{\boldsymbol{B}}_\beta =
 \begin{pmatrix}
C_{11} & C_{12} & C_{13} & 0 & 0 & 0 \\
& C_{22} & C_{23}  & 0 & 0 & 0 \\
 & & C_{33} & 0 & 0 & 0 \\
& & & C_{44} & 0 & 0 \\
& \text{sym} & & & C_{55}  & 0 \\
& & & & & C_{66} \\
\end{pmatrix} \boldsymbol{B}_\alpha \otimes \boldsymbol{B}_\beta
\end{equation}
with the global basis $\lbrace \tilde{\boldsymbol{B}}_\alpha \rbrace$:
\begin{align}
\tilde{\boldsymbol{B}}_1 &= \boldsymbol{e}_x \otimes \boldsymbol{e}_x \\
\tilde{\boldsymbol{B}}_2 &= \boldsymbol{e}_y \otimes \boldsymbol{e}_y \\
\tilde{\boldsymbol{B}}_3 &= \boldsymbol{e}_z \otimes \boldsymbol{e}_z \\
\tilde{\boldsymbol{B}}_4 &= \frac{1}{\sqrt{2}}\left(\boldsymbol{e}_y \otimes \boldsymbol{e}_z + \boldsymbol{e}_z \otimes \boldsymbol{e}_y \right) \\
\tilde{\boldsymbol{B}}_5 &= \frac{1}{\sqrt{2}}\left(\boldsymbol{e}_x \otimes \boldsymbol{e}_z + \boldsymbol{e}_z \otimes \boldsymbol{e}_x \right) \\
\tilde{\boldsymbol{B}}_6 &= \frac{1}{\sqrt{2}}\left(\boldsymbol{e}_x \otimes \boldsymbol{e}_y + \boldsymbol{e}_y \otimes \boldsymbol{e}_x \right) \\
\end{align}
and the orthotropic basis $\lbrace \boldsymbol{B}_\alpha \rbrace$
\begin{align}
\boldsymbol{B}_1 &= \boldsymbol{e}_1 \otimes \boldsymbol{e}_1 \\
\boldsymbol{B}_2 &= \boldsymbol{e}_2 \otimes \boldsymbol{e}_2 \\
\boldsymbol{B}_3 &= \boldsymbol{e}_3 \otimes \boldsymbol{e}_3 \\
\boldsymbol{B}_4 &= \frac{1}{\sqrt{2}}\left(\boldsymbol{e}_2 \otimes \boldsymbol{e}_3 + \boldsymbol{e}_3 \otimes \boldsymbol{e}_2 \right) \\
\boldsymbol{B}_5 &= \frac{1}{\sqrt{2}}\left(\boldsymbol{e}_1 \otimes \boldsymbol{e}_3 + \boldsymbol{e}_3 \otimes \boldsymbol{e}_1 \right) \\
\boldsymbol{B}_6 &= \frac{1}{\sqrt{2}}\left(\boldsymbol{e}_1 \otimes \boldsymbol{e}_2 + \boldsymbol{e}_2 \otimes \boldsymbol{e}_1 \right) \\
\end{align}
The orthonormal-system $\lbrace \boldsymbol{e}_1, \boldsymbol{e}_2, \boldsymbol{e}_3 \rbrace$ would represent the orthtropic axes, I am looking for.
Help would be really much appreciated. TIA


text:
Q: how to create movable nodes and edges in java swing GUI? In my java project, I need to create a GUI with swing where I will have a canvas like space. The user should be able to click and create nodes and then link nodes with edges (like you would create a UML diagram in MS Visio). The user should also be able to move the nodes along with edges. Then my application would save the network and run the selfish nodes algorithm and user should be able to see it live on GUI (creation and elimination of edges). I am not sure which swing tools I would need to use to accomplish this. (and can it be done in WPF, what tools I have to use for that)

A: try this one
<dependency>
        <groupId>jgraph</groupId>
        <artifactId>jgraph</artifactId>
        <version>5.13.0.0</version>
    </dependency>

we really created very complex swing UI screen with a lot of graph oriented structures with this lib. take a look here http://www.jgraph.com or directly here http://www.jgraph.com/images/business-large.png Is this something you are looking for?

A: If you're trying to "roll your own" solution, I have a few suggestions:

*

*Obviously you will need to use a MouseListener and MouseMotionListener which can be combined into a single entity by using a MouseAdapter.

*Your lines will likely be drawn in a JPanel's paintComponent method.

*Then your choices for nodes diverge. You can use components such as JLabels, each with a MouseAdapter attached (again as both a MouseListener and a MouseMotionListener)

*or you can use a single MouseAdapter added to a JPanel and render your nodes as rectangles again in the JPanel's paintComponent(...) method.

*The data for the nodes and connections should be held separate from the GUI, perhaps in its own "model" class as part of an MVC (model-view-controller) application.

*The MouseAdapter would be part of the "control" of your MVC structure and would change the model.

*I prefer to be able to add listeners to my models, such as a PropertyChangeListener, and have the view, the Swing GUI, instigate a change of its display based on its listener being fired.

Since this is probably homework, I'll leave you to work out the details and code, but feel free to come back with your code if you get stuck at a specific step.

A: I suggest you to try out JUNG library.
I've created an application with this library (instead of JGraph) because I thought that JUNG is easier to learn than JGraph for newbies (even if it provide less features). I needed only simple nodes and edges between them.
It look like this (probably this is more or less what you're trying to do):

Here is basic code snippet from core JUNG functionality:
public ArchitectureEditor(String title, MainWindow mainWindow, ArchObjContextConcern contextConcern) {
    super(title);
    setName(NAME);

    graph = new DirectedSparseGraph<ArchObject, EdgeKey>();

    layout = new StaticLayout<ArchObject, EdgeKey>(graph);
    vv = new AutoCropVisualizationViewer(layout); //extends VisualizationViewer<ArchObject, EdgeKey>
    vv.getRenderContext().setEdgeShapeTransformer(new EdgeShape.Line<ArchObject, EdgeKey>());

    VERTEX_ICON_TRANSFORMER = new ArchObjIconTransformer(vv);
    VERTEX_SHAPE_TRANSFORMER = new ArchObjShapeTransformer(vv);
    vv.getRenderContext().setVertexShapeTransformer(VERTEX_SHAPE_TRANSFORMER);
    vv.getRenderContext().setVertexIconTransformer(VERTEX_ICON_TRANSFORMER);

    graphMouse = new ArchGraphMouse(mainWindow, contextConcern);
    vv.setGraphMouse(graphMouse);
    vv.addKeyListener(new ArchGraphKeyboard(mainWindow, this));
    vv.setBackground(Color.WHITE);

    ComponentUtils.setForcedSize(vv, 1, 1);
    setLayout(new BorderLayout());
    add(new JScrollPane(vv));
}

And objects in graph are represented by:


text:
Q: usar .htacces adequadamente para links Então, tenho no meu .htaccess a seguinte condição:
RewriteCond %{REQUEST_URI} !.(jpe?g?|png|gif|css|js) [NC]

que me diz para liberar as extensões acima no caso do redirecionamento abaixo
RewriteRule .* index.php [NC,L]

Código completo do .htaccess
<ifModule mod_rewrite.c>
  # LIGA O MOTOR DE REESCRITA (Rewrite)
  RewriteEngine on
  # BUSCA PELA BASE /crud/ NO HOST ACESSADO
  RewriteBase /crud/
  # FAZ UMA ESCESSÃO DE REDIRECIONAMENTO PARA A PÁGINA manutencao.php CASO O NAVEGADOR RECEBA ELA NA URL
  # PERCEBA O ! ANTES DO NOME DO ARQUIVO. ISSO DIZ AO .htaccess QUE O ARQUIVO EM QUESTÃO NÃO SEGUE A REGRA E ABRE NORMALMENTE
  RewriteCond %{REQUEST_URI} !/manutencao.php$ [NC]
  # FAZ UMA ESCESSÃO E LIBERA IMAGENS NESTA PAGINA
  # NOTE QUE PAR ESAS EXTENSÕES, O REDIRECIONAMENTO NÃO ACONTECE E DÁ ERRO 404 CASO A IMAGEM NÃO EXISTA
  # AS DEMAIS EXTENSÕES SÃO TODAS REENVIADAS PARA A INDEX
  RewriteCond %{REQUEST_URI} !.(jpe?g?|png|gif|css|js) [NC]
  # REENVIA QUALQUER ACESSO AO SITE PARA A PÁGINA index.php NO HOST INDICADO LIBERANDO AS EXCESSÕES ACIMA DESCRITAS
  RewriteRule .* index.php [NC,L]

  ErrorDocument 401 http://localhost/crud/401.php
  ErrorDocument 403 http://localhost/crud/403.php
  ErrorDocument 404 http://localhost/crud/404.php
  ErrorDocument 500 http://localhost/crud/500.php

</ifModule>

Imagine o caso em que o usuário acesse:
http://www.seusite.com.br/pasta/arquivo.php

e considere ainda o caso em que o arquivo arquivo.php não exista na pasta.
O redirecionamento para a página 404.php ocorrerá normalmente; Porém, as imagens da pagina não abriram tampouco os links de .css's e .js's abriram por causa do endereços das imens:
404.php
<?php
  require_once 'global/erros/erros.ini';
  $titulo = "CRUD - Página não encontrada";
?>

<!DOCTYPE html>

   <title>CRUD - Página não encontrada</title>
   <?php  require_once("global/meta/meta.ini"); ?>
   <link rel="shortcut icon" type="image/x-png" href="img/favicon.png">
   <link type="text/css" rel="stylesheet" href="global/css/erros.css" />

<?php echo $titulo; ?>

<?php require_once("404Conteudo.php"); ?>

<?php require_once("public/requeridos/finalErros.php"); ?>

404Conteudo.php

Oh não! Página Não Encontrada!

O que você esperava encontrar não está aqui?

Detalhes:

A página que Você tentou acessar não existe.

Data atual: <?php echo date("d/m/Y"); ?>

Notem que os endereços dos links e das imagens NÃO são absolutos.
Alguma forma de contornar esse problema pelo .htaccess? Ou terei mesmo que que adicionar endereços absolutos em todos os arquivos?


text:
Q: Disabling anchor using preventDefault() & event ordering In my application I am using styling anchor tags in the same way as buttons. I need to be able to disable buttons, but the anchor tag does not have a disabled attribute. The way around this that I have attempted is by using preventDefault() in the anchor click event like so:
$('a.disabled').click(function (e) {
    e.preventDefault();
});

This is not disabling the link. However, if I simply use the 'a' selector $('a').click(function()... it does disable the link. I assume this is something to do with priority of events or event ordering based on the selectors.
Anyone know a way around this??
UPDATE
I have just realied that the above code works if referencing an anchors id in the selector, again this leads me to believe it is something to do with CSS selector priority, i.e. id referenced styles override class styles etc.

A: I'm guessing you're setting the disabled class AFTER you've bound the click event handler. If your element doesn't match the selector at the time of binding, it won't work. In case you want to run your handler in case your element will match your selector in the future, you need to use live().
$('a.disabled').live("click", function(e){
    e.preventDefault();
});

A: It seems you didn't set disabled class to anchors. Are you sure they look like

?

A: Even if you had several events on the same link and this one wasn't the first executed preventDefault() should work anyway; as the default action is done after the whole event queue is done running.
What I think happens instead is that your event is never run; make sure that you affected the disabled class to your link

And that you don't have any of your events on it cancelling the queue during its run. Here is what you should be looking for:
event.stopPropagation() // stop event bubbling, prevent the event to apply on his parent eg if your  is in a div, prevent the div click event queue to run -- SHOULDN'T BE YOUR PROBLEM
event.stopImmediatePropagation() // same as stopPropagation() and in addition stop the event queue on this element (so if you have 3 clicks event on your link and the first calls this, the other two won't run)
return false; // fully cancel the event, has the effect to also stop the event queue, similar to calling preventDefault() AND stopImmediatePropagation() -- SHOULDN'T BE YOUR PROBLEM

To be 100% sure you can check that your event is running by changing your link to  (so that the page won't reload) and doing a console.log('test') during the event. If it isn't called, it either isn't affected or has been cancelled.


text:
Q: Complete a function to check if ascending is true. No idea what I am doing wrong def sortList(mylist, ascending):
 enter code here

# expected output: [4, 12, 19, 33]
print(sortList([19,4,33,12], True))

# expected output: [33, 19, 12, 4]
print(sortList([19,4,33,12], False))

A: You can do this to check if a list is sorted in ascending order:
def is_ascending(l):
    return all(l[i] <= l[i+1] for i in range(len(l) - 1))

Or you can do this if you need a variable that tells if the list must be sorted or not:
def is_ascending(l, must_be_sorted):
        return not (all(l[i] <= l[i+1] for i in range(len(l) - 1)) ^ must_be_sorted)


text:
Q: Typescript Error ';' expected. 'EventNameString' only refers to a type, but is being used as a value here I'm trying to add firebase phone authentication to an old ionic project, followed several tutorials. I manged to implement it, but every time I do ionic serve -l this error appears:

However I noticed that the errors disappear if I commented one of those lines in app.modules.ts after I do ionic serve -l :
import { AngularFireModule } from "@angular/fire";
import { AngularFireAuth } from "@angular/fire/auth";

since the errors is in the node-modules folder, I tried removing it multiple times and even tried it on other PC, followed some answers here and there but I couldn't solve it.
Errors text:
Typescript Error
';' expected.
gtagName?: string;
/** Sets custom name for `dataLayer` array used by gtag. */
dataLayerName?: string;

Typescript Error
'EventNameString' only refers to a type, but is being used as a value here.
/** Sets custom name for `dataLayer` array used by gtag. */
dataLayerName?: string;

Typescript Error
'never' only refers to a type, but is being used as a value here.
/** Sets custom name for `dataLayer` array used by gtag. */
dataLayerName?: string;

Typescript Error
Cannot find name 'T'.
/** Sets custom name for `dataLayer` array used by gtag. */
dataLayerName?: string;

ionic info :
Ionic Framework: ^3.9.8
Ionic App Scripts: 3.2.4
Angular Core: ^5.2.7
Angular Compiler CLI: ^5.2.7
Node: 12.13.1
OS Platform: Windows 10
Navigator Platform: Win32
User Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36

app.modules.ts imported dependencies:
import { ErrorHandler, Injectable, Injector, NgModule } from "@angular/core";
import { IonicApp, IonicErrorHandler, IonicModule } from "ionic-angular";
import { BrowserModule } from "@angular/platform-browser";
import { HttpModule } from "@angular/http";
import { HttpClient, HttpClientModule } from "@angular/common/http";

import { Geolocation } from "@ionic-native/geolocation";
import { NativeGeocoder } from "@ionic-native/native-geocoder";

import { MyApp } from "./app.component";
import { TabsPage } from "../pages/tabs/tabs";
import { Loading } from "../pages/loading/loading";
import { Welcome } from "../pages/welcome/welcome";
import { GeoPage } from "../pages/geo/geo";

import { IonicStorageModule } from "@ionic/storage";
import { StatusBar } from "@ionic-native/status-bar";
import { SplashScreen } from "@ionic-native/splash-screen";

import { APIService } from "../services/api_service";
import { CartService } from "../services/cart_service";
import { PushService } from "../services/push_service";
import { UtilService } from "../services/util_service";
import { OrderHistoryService } from "../services/order_history_service";

import { TranslateLoader, TranslateModule } from "@ngx-translate/core";
import { TranslateHttpLoader } from "@ngx-translate/http-loader";
import { RestaurantsPageModule } from "../pages/catalog/restaurants/restaurants.module";
import { GeoPageModule } from "../pages/geo/geo.module";
import { AngularFireModule } from "@angular/fire";
import { AngularFireAuth } from "@angular/fire/auth";
import { firebaseConfig } from "../config";
import { LoginPage } from "../pages/personal/login/login";
import { AuthService } from "../services/auth.service";
import { NgxErrorsModule } from '@ultimate/ngxerrors';

A: The main thing is you must have being you are using = instead of : with EventNameString when attempting to set the type to EventNameString. Thats why you are getting the error 'EventNameString' only refers to a type, but is being used as a value here.
For other please those are mainly syntax errors as I see. As @nircraft suggested you should try cleaning node_modules and it's cache and reinstall it fresh.


text:
Q: IDLE refuses to launch in terminal. What should I do? I am attempting to open IDLE from my terminal, but am constantly faced with this error:
File "/opt/local/bin/idle", line 5, in <module>
main()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/idlelib/PyShell.py", line 1553, in main
root = Tk(className="Idle")
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1820, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: no display name and no $DISPLAY environment variable

What does this error mean and how do I remedy it? I've tried reinstalling python, and installing the latest version of X11. I've also tried installing py27-tkinter (as suggested by answers to similar questions) but still with no luck. I am new to Python and would appreciate any suggestions that anyone can offer! I am using a Mac and Python 2.7.13.
Thank you!

A: Have you taken a look at this answer?
Mac OS X: _tkinter.TclError: no display name and no $DISPLAY environment variable
It is very similar to your situation. Since you have already reinstalled a lot of your components, you should be familiar with these steps.
Try it in this way (taken from the link above):

Using macports, install py33-tkinter
sudo port install py33-tkinter
Edit: Make sure you have X11 or Xquartz installed too.

You just need to replace py33-tkinter with your version of Python instead, which is probably py27-tkinter
EDIT:
Take a look at your current value of the environment variable. Use echo $DISPLAY. If its not set, can you try setting your environment variable as the error suggests?
Using export DISPLAY=:0.0


text:
Q: Use JeroenvO/html5-colorpicker in React and Meteor project I want to make a react component with this https://github.com/JeroenvO/html5-colorpicker
So I copied colorPicker.js and exported the constructor. Then I made a component like this
import React, { Component } from 'react'
import colorPicker from '../../../../../imports/colorPicker/colorPicker.js'

export default class ColorPicker extends Component {
  myDiv = null
  myPicker = null
  componentDidMount = () => {
    const { onColorChange } = this.props
    this.myPicker = new colorPicker(this.myDiv, {
        bgcolor: 'rgba(50,50,50,0)',
        onColorChange: function () {
          console.log('color in HSV', this.getColorHSV())
          console.log('color in HSL', this.getColorHSL())
          console.log('color in RGB', this.getColorRGB())
          onColorChange()
        },
        onCenterClick: function () {
              window.alert('You clicked the center!')
        }
    })
  }

  render () {
    return (
      <canvas ref={(elem) => this.myDiv = elem} width="500" height="500" id="colorPicker1"></canvas>
    )
  }
}

Then I get an error like this
Uncaught DOMException: Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state.
I guess I should also provide the images for the canvas as is in the repository. So I put the images where the colorPicker.js is located, in imports/colorPicker.
However I still get the same error. Somehow the image is not accessible if the problem is in the image at all. Can you help me with this please?

A: One solution is to just pass an image url as an option
image: 'http://hayk94.gitlab.io/plain-html/color-500.png',


text:
Q: Run a python script in a webpage I have a python script saved in my local.The script basically takes a csv file as input and runs it from my local.
So now I want to do the same thing but from a webpage so that it becomes more user friendly.I want to make a webpage where it takes a csv file as input and runs the script after I click a button.Please help me with ideas on how to do this.


text:
Q: Currency Formatting for euro in word using VBA I did currency formatting for Dollar. It works fine. Same currency formatting I want to do for other currencies also like Euro, Pound.
Below is the code that I tried. Pls help.
Code:
Sub CurrencyFormat_UK()
'
' Currency formating
'

Dim oCl As Word.Cell
Dim oRng As Range
'
' Condition to check the selected data
'
  If Selection.Type = wdSelectionIP Or _
      Not Selection.Information(wdWithInTable) Then
    MsgBox "Select a cell or range of cells before running" _
      & " this macro.", , "Nothing Selected"
    Exit Sub
  End If
  For Each oCl In Selection.Cells
    Set oRng = oCl.Range
    '
    'Drop of the end of cell mark
    '
    oRng.End = oRng.End - 1
    With oRng
      If IsNumeric(oRng) Then
        .Text = FormatCurrency(Expression:=.Text, NumDigitsAfterDecimal:=2, _
                IncludeLeadingDigit:=vbTrue, UseParensForNegativeNumbers:=vbTrue)
      End If
      If oRng.Characters.count = 1 Then GoTo Skip
      On Error GoTo Skip
      'Catch errors here
      If InStr(oRng.Text, "€") = False Then
        oRng.Font.Color = wdColorRed
        oRng.Select
        MsgBox "Cell content is not numerical.", , "Error"
        Selection.Collapse wdCollapseEnd
      End If
Skip:
    End With
  Next oCl
lbl_Exit:
Exit Sub
End Sub

A: Just use NumberFormat instead.
Let's say I want to format the whole B column to GBP ( £ ) from the SheetCur sheet. The code would be:
Worksheets("SheetCur").Columns("A").NumberFormat = "£#,##0.00_)"

This would create stuff looking like £555,00. If you want to leave a space between the currency and the number just leave a space in the string as well:
.NumberFormat = "£ #,##0.00_)"

Likewise if you want the currency after the number, you could use:
.NumberFormat = "#,##0.00 £_)"


text:
Q: Set visibilitytimeout to 7days means automatically delete for azure queue? It seems that new azure SDK extends the visibilitytimeout to <= 7 days. I know by default, when I add a message to an azure queue, the live time is 7days. When I get message out, and set the visibilitytimeout to 7days. Does that mean I don't need to delete this message if I don't care about message reliable? the message will disappear later 7 days.
I want to take this way because DeleteMessage is very slow. If I don't delete message, doesn't it have any impact on performance of GetMessage?

A: Based on the documentation for Get Messages, I believe it is certainly possible to set the VisibilityTimeout period to 7 days so that messages are fetched only once. However I see some issues with this approach instead of just deleting the message once the process is done:

*

*What happens when you get the message and start processing it and somehow the process fails? If you set the visibility timeout to be 7 days, then the message would never appear in the queue again and thus the process it was supposed to do never gets done.

*Even though the message is hidden, it is still there in the queue thus you keep on incurring storage charges for that message. Even though the cost is trivial but why keep the message when you don't really need it.

*A lot of systems rely on Approximate Messages Count property of a queue to check on the health of processes which are performed by messages in a queue. Please note that even though you make the message hidden, it is still there in the queue and thus will be included in total messages count in the queue. So if you're building a system which relies on this for health check, you will always find your system to be unhealthy because you're never deleting the messages.

I'm curious to know why you find deleting messages to be very slow. In my experience this is quite fast. How are you monitoring message deletion?

A: Rather than hacking around the problem I think you should drill into understanding why the deletes are slow. Have you enabled logs and looked at the e2elatency and serverlatency numbers across all your queue operations. Ideally you shouldn't be seeing a large difference between the two for all your queue operations. If you do see a large difference then it implies something is happening on the client that you should investigate further.
For more information on logging take a look at the following articles:
http://blogs.msdn.com/b/windowsazurestorage/archive/tags/analytics+2d00+logging+_2600_amp_3b00_+metrics/
http://msdn.microsoft.com/en-us/library/azure/hh343262.aspx
Information on client side logging can also be found in this post: e client side logging – which you can learn more about in this blog post. http://blogs.msdn.com/b/windowsazurestorage/archive/2013/09/07/announcing-storage-client-library-2-1-rtm.aspx
Please let me know what you find.
Jason


text:
Q: Sorting Data in Workbook2 from Workbook1 I'm not sure why the code below isn't working. I'm using this as a part of a larger VBA sub, but I'll just post the relevant code below
I want to sort a range (by A to Z) on a separate Workbook. The range is "A5:M600" and the worksheet is "Leaders". This is stored on the Workbook declared as 'wb2'.
The code below will get as far as opening the file where I want to execute the sort, select the range I want to sort, but it won't actually sort the selection.
Any ideas?
Sub SortWB2()
Dim wb2 As Workbook
Dim RetFilePath

'~~> Get the file path
RetFilePath = "T:\Purchasing\ADVENTURE RMS\Data Files\2015\Data.xlsx"

'if file path is not found, then exit the sub below
If RetFilePath = False Then Exit Sub

'set wb2 to open the file
Set wb2 = Workbooks.Open(RetFilePath)

With wb2.Worksheets("Leaders").Sort
    .SetRange Range("A5:M600")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

Application.DisplayAlerts = False
wb2.Close SaveChanges:=True
Application.DisplayAlerts = True

Set wb2 = Nothing

End Sub

A: Try to stay away from .Activate and .Select as ways to direct the target of your code.
Set wb2 = Workbooks.Open(RetFilePath)

With wb2.Worksheets("Leaders").Range("A5:M600")
    .Cells.Sort Key1:=.Columns(1), Order1:=xlAscending, _
                Key2:=.Columns(3), Order2:=xlDescending, _
                Orientation:=xlTopToBottom, Header:=xlNo
End With

That will sort on column A as the primary key then column C as the secondary key. You can remove the secondary key if it is not needed. You can add a third key (e.g. Key3:=.Columns(14), Order3:=xlAscending for column N ascending) but it has a maximum of three keys. You can double up the command if you require more.
See How to avoid using Select in Excel VBA macros for more methods on getting away from relying on select and activate to accomplish your goals.

A: Hm, it may be that you should be explicit with your ranges.  Try this for the With statement:
With wb2.Worksheets("Leaders").Sort
    .SetRange wb2.worksheets("Leaders").Range("A5:M600")
    .Header = xlNo
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

I think (hope!) that does it.


text:
Q: How do I put ArsClip to start on windows boot? I used to put it on the Startup folder but since I upgraded to Windows 8, now if I put the .exe over on that folder it opens 5 file explorer windows and 5 notepad files on system bootup. I also notice there's no more option during installation to start the program on system bootup and it gives me this message about it not functioning properly on Win Vista and higher, although I've never had a problem with ArsClip on Win 7. Anyone knows any workaround for this issue?

A: Add it to the Startup folder directly, not through the shortcut path;
Windows Key + R
Type %appdata& and press enter
Navigate to "\Microsoft\WIndows\Start Menu\Programs\Startup"
You can try that. Let me know if it works.


text:
Q: Undefined function 'fftOneSide' for input arguments of type 'double' I am using MATLAB R2013.
fs=8000;
t=(1:512)'/fs; %'// <-- prevents string markdown
f=306.396;
original=sin(2*pi*f*t)+0.2*randn(length(t),1);
windowed=original.*hamming(length(t));
[mag1,phase1,freq1]=fftOneSide(original,fs);

Error:

Undefined function 'fftOneSide' for input arguments of type 'double'

A: This question was raised in a previous SO question, with apparently no response until now:
error in using fftoneside
Using your input for the signal, without using the hamming function (I don't have the signal toolbox on my computer), after defining the function below (I commented out the demo code at the bottom part and the first line with if nargin <1 obv!!), I ran it on Matlab2015a. It ran fine! Setting plotOpt=1 (that is calling with three arguments, the final equal to 1) provides proof:

The only thing I can think of, is that in the sourcecode it asks for a file as input - which I'm assuming you don't have. If you comment out the nargin <1 part, and the whole selfdemo at the end, see if this doesn't work as you want it to. If it doesn't, I'm completely baffled!
I've taken a look at the source code (below) for this function, which also shows proper usage. As you can see they're reading the signal and fs values in from a file, rather than defining them as you have here. It's a bit of a pain we can't see what values they chose.
Notice the call asks for plotOpt to be specified, though if you don't specify it, the nargin calls at the beginning should set it to 0 for you (right?). I don't think default function declarations have changed since 2012 - but if they have, calling the function with three arguments will take care of that. Note: if don't set plotOpt=1, the plots won't proceed.
http://read.pudn.com/downloads99/sourcecode/others/404673/audioProcessing/fftOneSide.m__.htm
function [magSpec, phaseSpec, freq, powerSpecInDb]=fftOneSide(signal, fs, plotOpt)
% fftOneSide: One-sided FFT for real signals
%   Usage: [magSpec, phaseSpec, freq, powerSpecInDb]=fftOneSide(signal, fs)
%
%   For example:
%       [y, fs]=wavread('welcome.wav');
%       frameSize=512;
%       startIndex=2047;
%       signal=y(startIndex:startIndex+frameSize+1);
%       signal=signal.*hamming(length(signal));
%       plotOpt=1;
%       [magSpec, phaseSpec, freq, powerSpecInDb]=fftOneSide(signal, fs, plotOpt);

%   Roger Jang, 20060411, 20070506

if nargin<1, selfdemo; return; end % MBio: comment out
if nargin<2, fs=1; end
if nargin<3, plotOpt=0; end

N = length(signal);         % Signal length
freqStep = fs/N;            % Frequency resolution
time = (0:N-1)/fs;          % Time vector
z = fft(signal);            % Spectrum
freq = freqStep*(0:N/2);        % Frequency vector
z = z(1:length(freq));          % One side
z(2:end-1)=2*z(2:end-1);        % Assuming N is even, symmetric data is multiplied by 2
magSpec=abs(z);             % Magnitude spectrum
phaseSpec=unwrap(angle(z));     % Phase spectrum
powerSpecInDb=20*log(magSpec+realmin);  % Power in db

if plotOpt
    % ====== Plot time-domain signals
    subplot(3,1,1);
    plot(time, signal, '.-');
    title(sprintf('Input signals (fs=%d)', fs));
    xlabel('Time (seconds)'); ylabel('Amplitude'); axis tight
    % ====== Plot spectral power
    subplot(3,1,2);
    plot(freq, powerSpecInDb, '.-'); grid on
    title('Power spectrum');
    xlabel('Frequency (Hz)'); ylabel('Power (db)'); axis tight
    % ====== Plot phase
    subplot(3,1,3);
    plot(freq, phaseSpec, '.-'); grid on
    title('Phase');
    xlabel('Frequency (Hz)'); ylabel('Phase (Radian)'); axis tight
end

% ====== Self demo MBio: comment ALL this code out!
function selfdemo
[y, fs]=wavread('welcome.wav');
frameSize=512;
startIndex=2047;
signal=y(startIndex:startIndex+frameSize+1);
signal=signal.*hamming(length(signal));
[magSpec, phaseSpec, freq, powerSpecInDb]=feval(mfilename, signal, fs, 1);


text:
Q: How to clone Bitbucket git into cPanel Git™ Version Control I have git into my Bitbucket account and I want clone those git into my cPanel Git™ Version Control. How to do that?
I was able pull git using cPanel terminal. but I want to make clone using cPanel Git™ Version Control.
We want to make bitbucket git clone using cPanel Git™ Version Control so that we can create more branches from cPanel git and do version control for cPanel copy. I tried to clone bitbucket git using https, git and ssh url into cPanel Git™ Version Control but then I am getting following error.
From BitBucket
git clone https://<AccountName>@bitbucket.org/<RepositoryName>/<BranchName>.git

Into cPanel Git™ Version Control But I am getting following error.
https://<AccountName>@bitbucket.org/<RepositoryName>/<BranchName>.git

Then i have tested with SSH and Git path from bitbucket
For SSH path I am getting following error.
ssh://git@bitbucket.org/<workspace_ID>/<repo_name>.git

Fog git url which is copied from Clone button in bitbucket, I am getting following error.
git@bitbucket.org:<workspace_ID>/<repo_name>.git

*

*I have created SSH Access keys into cPanel, Do i have to use that anywhere for cloning ??

*Can you guide me steps in details for cloning git from bitbucket into cPanel Git™ Version Control

Thank You.

A: *

*Go to repository settings on Your Bitbucket Repository Console

*Under General menu, click Access keys

*Click Add key button

*Open id_rsa.pub file from cpanel file manager that you have created

*Copy and paste its contents to Bitbucket Access keys under Key form input, and click Add SSH Key button

*On the CPanel Git™ Version Control, add and clone repository, if any error message, it will be create a known_hosts file in cpanel file manager.

*Repeat step 6 one more time

A: One of the issue can be that your keys are passphrase protected. The cPanle documentation link below has a note they passphrase protected keys are not supported:
NOTE: Keys that are passphrase protected are not compatible with cPanel Git™ Version Control.
If your existing keys require a passphrase, please make use of the section labeled: Option #1 - Generate a New Private and Public Key Pair to learn how to generate a compatible set of keys.
https://support.cpanel.net/hc/en-us/articles/4404218477207-How-to-Configure-SSH-Key-Authentication-for-Use-with-cPanel-Git-Version-Control
Interestingly enough, the built in SSH Key Generator does not allow to generate keys without passphrase, which makes it very confusing as the cPanel Git™ Version Control will not work with any generated keys via cPanel SSH Key Generator. The workaround is to generate passphrase less keys using terminal access.


text:
Q: Reseting the redux store/state when a User Logs Out I'm making a fitness app and running into an issue that I do not think will be too hard to fix, but I have been stuck.
When User 1 logouts, and user 2 logs in, user 2 will have user 1s workout log until they refresh the page. This is because the state isn't clearing the workout log when logging out.
I tried to fix this in my sessionsReducer, but haven't succeeded.
My idea with the if conditional was to pass back an empty state if currentUser is null. Null is passed back with my logout thunk action.
I wasn't sure what other action creator I could make to help fix this problem.
My reducer and logout is below.
import merge from 'lodash/merge';

import { RECEIVE_CURRENT_USER, RECEIVE_ERRORS } from '../actions/session_actions'

const nullUser = Object.freeze({
  currentUser: null,
  errors: []
});

const sessionReducer = (state = nullUser, action) => {
  Object.freeze(state);
  let newState;

  switch(action.type) {
    case RECEIVE_CURRENT_USER:
      if (action.currentUser === null) {
        newState = merge({}, {});
     } else {
       newState = merge({}, state);
     }
      const currentUser = action.currentUser;
      return merge({}, newState, {
        currentUser
      });
   case RECEIVE_ERRORS:
     const errors = action.errors;
     return merge({}, nullUser, {
        errors
     });
   default:
     return state;
  }
}

 export default sessionReducer;

Thunk action creator.
export const logout = () => (dispatch) => {
  return APIUtil.logout().then(() => dispatch(receiveCurrentUser(null)),
    err => dispatch(receiveErrors(err.responseJSON)));
};

A: To clear store after logout I usually do something like:
const createReducer = () => {
  const reducer = combineReducers({
    app: appReducer,
    // rest of your reducers
  });
  return (state, action) => {
    if (action.type === 'SIGN_OUT') {
      state = undefined;
    }
    return reducer(state, action);
  };
};

You can read more about cleaning store problem here.


text:
Q: Updating Lambda function to new runtime. Why is cURL no longer working in Node 10 on AWS Lambda? This is the line in my Lambda function that's raising an error:
// running in Node 8
const { execSync } = require('child_process');
execSync('curl https://github.com');

I'm trying to upgrade my Lambda function from Node 8 to Node 10 or Node 12, since Node 8 on Lambda is being deprecated at the end of December, 2019 (so I won't be able to update it). However, when I dig into my CloudWatch logs I'm seeing the following error:
bin/sh: curl: command not found
And when I update my Lambda function to just run which curl I get a similar error:
bin/sh: which: command not found
Per documentation here, I know that Node 8+, Python 3.8+ and Java 11+ are using the new AWS Lambda Runtime, Amazon Linux 2.
Any help is appreciated.

A: Node V10 and V12  above is based on Amazon Linux 2 and you can not run curl.

cURL on AWS Lambda gives command not found error
You have two options

*

*Use native binary package in AWS Lambda

*Use nodejs request or http built-in module

How do I use Amazon Linux AMI native binary packages in an AWS Lambda deployment package?
Short Description

A Lambda deployment package is a .zip file that contains your code and
  any dependencies. The Lambda execution environment is based on a
  specific Amazon Linux AMI and kernel version. Any native binaries that
  are used in a Lambda deployment package must be compiled in this
  environment, and only 64-bit binaries are supported.
To use the Amazon Linux AMI native binary packages, you can extract
  the 64-bit libraries and then include them in your Lambda deployment
  package. (Another option, that is not covered in this article, is to
  download the source code to the shared library and then recompile the
  package.)

lambda-runtimes
So as suggested in the comment the other way is to use the node package.
you can try for testing purpose something like
exports.handler = async (event) => {
  const https = require('https');
  var response=https.get('https://api.github.com');
  return JSON.stringify(response.output)
}

A: Instead of zipping the native binary package with lambda function, I would suggest to have a look at AWS Lambda Layers (https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html)
This way if you have multiple lambda functions, they could share these binary packages. You will have a to upload the content in a nodejs folder and zip it. In your code you could access it /opt/nodejs/ path
By the way I would prefer to use nodejs to make http calls instead of using curl from nodejs.


text:
Q: How to remove the use of ES6 arrow function in this code I am not familiar with ES6 arrow functions and I received the code below from a vendor:
Highcharts.seriesType('linearregression', 'pareto', {
  name: 'Linear Regression'
}, {
  setDerivedData: function() {
    if (this.baseSeries.yData.length > 1) {
      var xValues = this.baseSeries.xData,
        yData = this.baseSeries.yData,
        mainData = this.baseSeries.data;
      var sum = [0, 0, 0, 0, 0],
        len = xValues.length,
        data, rise, gradient, intercept;
      Highcharts.each(xValues, function(x, i) {
        sum[0] += x;
        sum[1] += yData[i];
        sum[2] += x * x;
        sum[3] += x * yData[i];
        sum[4] += yData[i] * yData[i];
      });
      run = ((len * sum[2]) - (sum[0] * sum[0]));
      rise = ((len * sum[3]) - (sum[0] * sum[1]));
      gradient = run === 0 ? 0 : (rise / run);
      intercept = (sum[1] / len) - ((gradient * sum[0]) / len);
      function round(value, decimals) {
        return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
      };
      function predict(x) {
        return [mainData[x].name, round((gradient * x) + intercept, 5)];
      };
      points = xValues.map(p => predict(p));
      this.setData(points, false);
    }
  }
});

I wanted to put this into production today but just found out that ES6 is not supported in IE.  How can this be rewritten to remove the arrow function (the line below)?
      points = xValues.map(p => predict(p));

A: How about
points = xValues.map(function(p) { return predict(p); });


text:
Q: JPanel to be resizeable with the components in the center so below is my code for this game i am makeing. its a number guessing game. anyway my main question is how do i make the contents of the gamePanel so that when you resize the screen the components are still in the centre. and so if the screen gets bunched up smaller then the components move automatically to be squashed in and seen still in the panel.
i have been trying to figure this out for ages.
public class GameScreen {

    public static void main(String[] args) {
        final JFrame game;
        final JButton playButton, guessButton;
        final JPanel topPanel, gamePanel, rangePanel, guessPanel;
        final JTextArea gameStatus;
        final GuessingGame gameNumbers;

        game = new JFrame();
        gameNumbers = new GuessingGame();
        game.setTitle("Guessing Game");
        game.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JLabel playerLabel = new JLabel("Player: ");
        JLabel guessLabel = new JLabel("Guess: ");
        final JLabel rangeLabel = new JLabel("Range: ");

        final JTextField playerName = new JTextField("", 20);
        final JTextField guessInput = new JTextField("", 20);

        playButton = new JButton("Play");
        guessButton = new JButton("Guess");

        topPanel = new JPanel();
        gamePanel = new JPanel();
        rangePanel = new JPanel(new BorderLayout());
        guessPanel = new JPanel(new FlowLayout());
        CountDownProgressBar countDownPanel = new CountDownProgressBar();

        gameStatus = new JTextArea(10, 20);
        JScrollPane scroll = new JScrollPane(gameStatus);

        game.add(topPanel, BorderLayout.NORTH);
        game.add(scroll, BorderLayout.EAST);
        game.add(gamePanel, BorderLayout.WEST);
        game.add(countDownPanel, BorderLayout.SOUTH);

        gamePanel.add(rangePanel);
        gamePanel.add(guessPanel);

        topPanel.setBackground(Color.yellow);
        topPanel.add(playerLabel);
        topPanel.add(playerName);
        topPanel.add(playButton);

        rangePanel.add(rangeLabel);

        guessPanel.add(guessLabel);
        guessPanel.add(guessInput);
        guessPanel.add(guessButton);

        gameStatus.setFocusable(false);
        guessButton.setEnabled(false);
        guessInput.setEnabled(false);
        playButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (playerName.getText().equals("")) {
                    JOptionPane.showMessageDialog(gamePanel, "Invalid Player Name");
                } else {
                    gameNumbers.play();
                    gameStatus.append("Game Started!\n");
                    rangeLabel.setText(gameNumbers.toString());
                    guessButton.setEnabled(true);
                    guessInput.setEnabled(true);
                    playButton.setEnabled(false);
                    playerName.setEnabled(false);
                }
            }
        });
        guessButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int playerGuess = Integer.parseInt(guessInput.getText());
                if (gameNumbers.isGuessCorrect(playerGuess)) {
                    gameStatus.append("Game Over!\n");
                    guessButton.setEnabled(false);
                    guessInput.setEnabled(false);
                    playButton.setEnabled(true);
                    playerName.setEnabled(true);
                    JOptionPane.showMessageDialog(gamePanel, "" + playerName.getText() + " wins!");
                } if (gameNumbers.isGuessAlmostCorrect(playerGuess)) {
                    gameStatus.append("very close!\n");
                    guessInput.requestFocus();
                } if (gameNumbers.isGuessLarger(playerGuess)) {
                    gameStatus.append("try something smaller...\n");
                    guessInput.requestFocus();
                } if (gameNumbers.isGuessSmaller(playerGuess)) {
                    gameStatus.append("try something larger...\n");
                    guessInput.requestFocus();
                }
            }
        });
        game.pack();
        game.setVisible(true);
    }

}

A: There's a lot missing, but, if I read this right, change the layout manager for the gamePanel to something like GridBagLayout (gamePanel = new JPanel(new GridBagLayout())) and add it to the center position of your game panel (game.add(gamePanel, BorderLayout.CENTER)).


text:
Q: Serializing access to a table row in HANA Whereas I am not allowed to use either identity columns or HANA sequences, I am forced manually to generate unique autoincrementing keys for tables. Here is my unsafe and naive key generation procedure, which stores unique counters in table TABLEKEYS and increments them at every execution:
CREATE PROCEDURE NewKey
(   IN  SeqName   NVARCHAR( 32),
    OUT NewKey    BIGINT
)
AS  rec_exists  INT;
    row_num     INT;
BEGIN
    SELECT SUM(1) INTO rec_exists
    FROM ( SELECT TOP 1 1 FROM TABLEKEYS WHERE "Name" = :SeqName ) T;
    IF :rec_exists IS NULL THEN
        SELECT COALESCE(SUM(1),0) INTO row_num FROM TABLEKEYS;

        INSERT INTO TABLEKEYS("Code",  "Name",    "U_CurrentKey")
        VALUES               (row_num, :SeqName,  -1            );
    END IF;

    UPDATE TABLEKEYS SET "U_CurrentKey" = "U_CurrentKey" + 1
    WHERE "Name" = :SeqName;

    SELECT "CurrentKey" INTO NewKey FROM TABLEKEYS
    WHERE "Name" = :SeqName;
END;

How to make it reliable, so that it shall not return two identical keys under any circumstances, even when it is being called intensively from an hundred simultaneous connections? In MSSQL Server I should wrap its body in a transaction and apply locking hints to the table in the initial query, but I am not aware of their analogs in HANA. Is there a way in HANA to ensure that a table row is accessed strictly sequencially?
My procedure with corrections suggested by Lars and adapted for Business One user-defined tables:
CREATE PROCEDURE GTGetNewKeyInt
(   IN  TableName NVARCHAR( 32),
    OUT NewKey    BIGINT
)
AS  cur_key     INT;
    row_num     INT;
    row_num_txt VARCHAR(8);
BEGIN
    BEGIN
        DECLARE EXIT HANDLER FOR SQLEXCEPTION
        BEGIN
        END;
        SELECT "U_CurrentKey" INTO cur_key FROM "@GTTABLEKEYS"
        WHERE "Name" = :TableName
        FOR UPDATE;
    END;

    IF :cur_key IS NULL THEN
        LOCK TABLE "@GTTABLEKEYS" IN EXCLUSIVE MODE;
        SELECT COALESCE(SUM(1),0) INTO row_num FROM "@GTTABLEKEYS";
        row_num_txt = LPAD( CAST( row_num AS varchar ), 8, '0' );
        NewKey = 0;
        INSERT INTO "@GTTABLEKEYS"("Code",      "Name",      "U_CurrentKey")
        VALUES                    (row_num_txt, :TableName,  :NewKey       );
    ELSE
        NewKey = :cur_key + 1;
        UPDATE "@GTTABLEKEYS" SET "U_CurrentKey" = :NewKey
        WHERE "Name" = :TableName;
    END IF;
END;

A: First off: not using the built-in features like sequences or the IDENTITY column seems rather not like a great idea.
Anything you build yourself here, will be inferior in one or the other regard.
But, hey, it's your code after all.
So, for selecting with locking, there is the standard SQL command
SELECT ... FOR UPDATE FROM...

(also see the documentation here)
Your program logic will be to

*

*SELECT ... FOR UPDATE

*do whatever you have to do

*Update the sequence table

*COMMIT or ROLLBACK

Your record will be locked as of step 1.
In order to make the whole process more efficient and to decouple the performance for managing the sequence from the amount of data in the actual data table, you may want to keep the sequence in its own table (row store might be a good idea for this one, as you deal with a single record and lots of updates). That's rather close to how sequences work as well.


text:
Q: flattern a dictionary and change key names how shoud i solve this ?
i have a dictionary like this
i wanna flattern this and If a key is already present in the result dict, add a suffix like "_1" to distinguish between keys with the same name.
student_da = {
    'id1': {
        'name': 'mike',
        'age': 28,
        'salary': 2000
    },
    'id2': {
        'name': 'Sara',
        'age': 18,
        'salary': 1000
    },
    "a": "A",
    'id3': {
         'name': 'Omid',
         "age": 20,
         'salary': 1000
    },
    'id4': dict(name="Amir", age=28, salary=2000),
    "last_name": "messi",
}

output:
{name_0: mike, age_0: 28, salary_0: 2000, ..., a: A, ...,  name_1: sara, ..., last_name: messi}

A: Since datasource is not clean. So the process will not straightforward. Not sure do you need output like this?
records = {'id1': {'name': 'mike', 'age': 28, 'salary': 2000 }, 'id2': {'name': 'Sara', 'age': 18, 'salary': 1000 }, "a": "A", 'id3': {'name': 'Omid', "age": 20, 'salary': 1000 }, 'id4': dict(name="Amir", age=28, salary=2000), "last_name": "messi", }
new_records = {}
n = 0

for r in records:
    if isinstance(records[r],dict):
        new_records[f"name_{n}"] = records[r]["name"]
        new_records[f"age_{n}"] = records[r]["age"]
        new_records[f"salary_{n}"] = records[r]["salary"]
        n += 1
    else:
        new_records.update({r: records[r]})

print(new_records)

print(new_records)
# {
'name_0': 'mike', 'age_0': 28, 'salary_0': 2000,
'name_1': 'Sara', 'age_1': 18, 'salary_1': 1000,
'a': 'A',
'name_2': 'Omid', 'age_2': 20, 'salary_2': 1000,
'name_3': 'Amir', 'age_3': 28, 'salary_3': 2000,
'last_name': 'messi'
}


text:
Q: Stack Exchange claims bounty will be auto-awarded even if there are no answers Stack Exchange informed me that my bounty has expired and will be auto-awarded.
But there are no answers, so it cannot be awarded.

A: From How does the bounty system work?:

Note that even if you don't have an answer, or only a self-answer, the grace period is still in effect for 24 hours. Answers posted during this time period may be awarded the bounty.

So, even if you do not have an answer now, you may still get one and if this answer happens to be eligible for auto-awarding. So, technically, the statement "[the bounty] will be auto-awarded 24 hours" is more or less correct: After said time, the system will perform the auto-awarding process and only then is it possible to tell whether there will be an answer to be auto-awarded.


text:
Q: Can I edit the datetime field before saving in database in django? I am uploading an excelsheet in which date is in format 08-10-2020(DD-MM-YYYY). When it's saved in the database, it becomes, Oct. 8,2020 8:50 p.m.
But I want the date to be saved in YYYY-MM-DD format.
Is this posssible?
My models.py looks like this:
from django.db import models

# Create your models here.
class Person(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()
    bday = models.DateTimeField(auto_now_add=True)
    year = models.IntegerField()

    def __str__(self):
        return self.name


text:
Q: How to show that $\lim_{n\to \infty} f_n(x) = 0$. I hate to admit it, but I don't know how to begin solving this problem:
Let $f\in L^1(\mathbb R)$. Let $\displaystyle f_n(x) = \frac{f(nx)}{n},~n\geqslant 1$. Then $\displaystyle \lim_{n\to \infty} f_n(x) = 0$ for almost every $x\in \mathbb{R}$.
Please this is not a home problem, so hints and full solutions will be very much appreciated.

A: First method: we use Fubini's theorem, applied to Lebesgue measure and counting measure, which are both $\sigma$-finite. Using a substitution
$$\sum_{n=0}^{+\infty}\int_{\mathbb R}\frac{|f(nx)|}n\lambda(x)=\sum_{n=0}^{+\infty}\frac 1{n^2}\int_{\mathbb R}|f(x)|\lambda(x)$$ so $\sum_{n=0}^{+\infty}\frac{|f(nx)|}n$ is convergent for almost every $x$ and we are done.

Second method, using only basis facts of measures and sequences.
Fix $\delta>0$ and an integer $n$ and put $A_{\delta}^n:=\left\{x\in\mathbb R,\left|\frac{f(nx)}n\right|\geq \delta\right\}$. Then
$$\delta \mu(A_{\delta}^n)\leq \int_{A_{\delta}^n}\left|\frac{f(nx)}n\right|d\lambda(x)=\int_{nA_{\delta}^n}\frac{f(t)}{n^2}d\lambda(t)\leq \frac{||f||_{L_1}}{n^2}$$
so $\lambda(A_{\delta}^n)\leq \frac{||f||_{L_1}}{\delta n^2}$ and therefore $\lambda\left(\bigcap_{k\geq 1}\bigcup_{n\geq k}A_{\delta}^n\right)=0$. Denote $B_{\delta}=\bigcap_{k\geq 1}\bigcup_{n\geq k}A_{\delta}^n$. Then $\lambda\left(\bigcup_{p\geq 1}B_{p^{-1}}\right)=0$ and $N:=\bigcup_{p\geq 1}B_{p^{-1}}$ is exactly the set of the $x$ such that $\frac{f(nx)}x$ doesn't converge to $0$. Indeed, if $x\in N$ then $x\in B_{p^{-1}}$ for some $p$ so there are infinitely many $n$ such that $x\in A_{p^{-1}}^n$ i.e. $\left|\frac{f(nx)}n\right|\geq \frac 1p$ so in particular $\frac{f(nx)}n$ doesn't converge to $0$. Conversely, if $\frac{f(nx)}n$ doens't converge to $0$, then we can find an integer $n_0$ and $J\subset \mathbb N$ infinite such that for all $n\in J$, $\left|\frac{f(nx)}n\right|\geq n_0^{-1}$, so $x\in B_{n_0^{-1}}$.


text:
Q: illegal harware instruction when trying to run flask application First of all here is my mac info:
macOS Big Sur
Apple M1 Chip
16 GB memory
Python 3.7.9

I tried to run a python application in my computer. After I input flask run, the terminal returns
 * Serving Flask app "demo" (lazy loading)
 * Environment: development
 * Debug mode: on
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with fsevents reloader
 * Debugger is active!
 * Debugger PIN: 260-335-544
I0806 10:14:55.217031 12914655232 file_utils.py:40] PyTorch version 1.6.0 available.
I0806 10:14:55.217122 13005393920 file_utils.py:40] PyTorch version 1.6.0 available.
zsh: illegal hardware instruction  flask run

Does anyone know what that mean and how to solve it? (Pretty sure there is no bug in the code. And I installed all the required packages)


text:
Q: Incomprehensible condition and incorrect operation of the function There is the following code (demo here), the function (with recursion) go the matrix in a spiral collecting values:
function spiralmatrix($arr)
{
    return  $arr
            ? array_merge(
                    array_shift($arr),
                    spiralmatrix(array_reverse(transpose($arr)))
            )
            : $arr;
}

function transpose($arr)
{
    return $arr
            ? count($arr) == 1
                ? array_chunk($arr[0], 1)
                : array_map(null, ...$arr)
            : $arr;
}

I understand that using multiple ternary expressions contributes to unreadable code. But there is more predominant sporting interest for code-Golf.
And so, to the question, is it possible to somehow change the condition to cut more characters? Can use any methods.
I would also like to ask, it is strange that the following works fine (demo):
function transpose($arr)
{
    return $arr
            ? count($arr) == 1
                ? array_chunk($arr[0], 1)
                : array_map(null, ...$arr)
            : $arr;
}

And the expression works a little wrong (demo):
function transpose($arr)
{
    return count($arr) > 1 ? array_map(null, ...$arr) : $arr;
}

Although, in separate tests (not in this function spiralmatrix) they show the same results what can is this problem? (demo comparisons). Grateful for any help..

A: The issue with your:
return count($arr) > 1 ? array_map(null, ...$arr) : $arr;

is that you are overlooking the truthy/falsey initial check:
return $arr
//      v----------------------------truthy----
        ? count($arr) == 1                    |
            ? array_chunk($arr[0], 1)         |
            : array_map(null, ...$arr)        |
        : $arr;                               |
//      ^----------------------------falsey----

Now, I'm not a code golfer, so I don't know if the spaces that you have posted "count" as characters.  I don't know if when it's "game time", everyone smashes their code down and you are simply doing us a favor in making the code readable.  That said here are a couple of ideas:
function transpose($arr)
{
    return $arr
            ? //count($arr) == 1
              //!isset($arr[1])                  <-- if spaces "count", this is shorter
              //!next($arr)                      <-- because no 0 in the arrays
              @!$arr[1]                  //      <-- the dirty stfu operator
                ? array_chunk($arr[0], 1)
                : array_map(null, ...$arr)
            : $arr;
}

Now, I never use the stfu operator in my career, but if the gloves are off, maybe it's worth a look.  Demo
I'll keep staring at the code and chime in if anything strikes me.
Edit: I just realized !next($arr) works because there are no zeros in the sample data.
Actually, why am I playing with negation, flip everything around.  Duh!
function transpose($arr)
{
    return $arr
            ? //isset($arr[1])                  <-- if spaces "count", this is shorter
              //next($arr)                      <-- because no 0 in the arrays
              @$arr[1]                  //      <-- the dirty stfu operator
                ? array_map(null, ...$arr)
                : array_chunk($arr[0], 1)
            : $arr;
}


text:
Q: How to properly align icon and text in a table? I am having trouble trying to vertically align the icon with the text. Basically, I'm trying to have the image icon to the top of the  tag, right now, it's in the middle as shown in the jsfiddle: http://jsfiddle.net/TheAmazingKnight/N6fLp/
I put border:1px dotted blue; to see clearly where each element is being spaced. By default, the td tag that wraps the img tag is centered. How do I put the img tag and title header to the very top of the table's td tag and align adjacently with the text?
I tried to imitate the result by putting vertical-align:text-top but that didn't work. I also tried position:relative to the table and then setting the image to top:0; but to no avail that didn't work either. What am I missing here?
HTML:

            Title header

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

View Lorem ipsum

            Title Header

            Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

View Lorem ipsum

            Title Header

            Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

View Lorem ipsum

            Title Header

            Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

Lorem ipsum

Hola Google

Include completed Lorem ipsum

Mail to:

            Lorem Ipsum

            Attn: Lorem Ipsum

            1234 Main Street

            NY NY 12345

            Title Header

            Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

            Title Header

            Lorem Lorem website Lorem ipsum

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.

CSS:
*{border:1px dotted blue;}
ul,li{padding-left:15px !important;padding:0;margin:0;}
/*table, tr, td, p{margin:0;padding:0;}*/
img{margin-right:10px;}
img{width:50px;height:50px;}

A: To vertically align an element to the top of a table cell, you can use the CSS vertical-align:top definition.
td {
    vertical-align:top;
}

Documentation
Working Example

A: i tried this in your jsfiddle and i only add this
td {
    padding: 6px;
    text-align: left;
    vertical-align: top;
    border-bottom:1px solid #ddd;
}

to the css

A: It is generally an old style using tables and gives you limited functionality.
if you choose to use a table you can either add to the html code where needed:

or use css (this will affect all td's):
td {
    vertical-align:top;
}

if  you choose not to use tables, I would recommend reading this article:
http://css-tricks.com/centering-in-the-unknown/

A:

   Text

.wrapper {
   display: flex;
   align-items: center;
   justify-content: center;
}


text:
Q: 19 digit prime number? I am searching for a particular type of prime number.
It is of 19 digit.If I removew unit place it will reduce to an 18 digit prime number.
If I again remove digit from unit place it will become 17 digit prime number..and so on...
What I obtained is each place except first one cannot be filled by even number and $5$. First digit can be filled by $2,3,5$,and $7$
So there are $4.18^4=274877906944$ possible numbers.
sum of digits should not be  a multiple of $3$..
How to proceed ?

A: Sequence A024770 in the OEIS has the full list of what are called right-truncatable primes. You can see in the b-file
https://oeis.org/A024785/b024785.txt
that none have 19 digits.


text:
Q: Mysql treat column value as a regex for select is it possible to query a result depending on the regex pattern of a column?
assuming i have 2 tables
table A
legs     fur                name
4        red                 cat
4        blue || spots       dog
1                            dolphin
1        black               shark
1        yellow              shark
1        white|| black       whale
2        [0-9]{4}-[0-9]{2}   exp1
2        [0-9]{4}            expA-1

table B
cageNumber   weight      legs     fur
192910       26          4        red
332192       12          1        black
119199       32          4        blue
111000       19          4        spots
192991       11          4        green
000001       14          2        0913-11
000002       11          2        1102
000003       16          2

what I need to do is to have a select statement which describes cage number and name depending on fur color
cageNumber name
192910     cat
332192     shark
111000     dog
119199     dog
192991     null
000001     exp1
000002     expA-1
000003     null

A: Change blue || spots to blue|spots to make it a correct regular expression.
Then this should work:
ON B.fur REGEXP CONCAT('^(', A.fur, ')$')

I added ^ and $ in order to anchor to the ends.  That way, blue will match, but blueblood will not.
I added ( and ) so that blue|sports would match only blue and sports, not blueblood and teamsports.  Think about what happens with ^blue|sports$ -- that means "start with blue or end with sports".

A: Yes you can do this, look at my little example. It delivers only expertId=1, contingentId=59 and description starts with ## followed by a number.
select * from entry where expert_id=1 and contingent_id=59 and (description REGEXP '^##[0-9]');

A: SELECT B.cageNumber, A.name FROM A JOIN B ON B.fur LIKE A.fur;

A: Use join with like
SELECT b.id, a.initiatorWallet FROM ledTest a
INNER JOIN ledTestB b ON a.transtype = b.transType
WHERE b.wallet RLIKE ( a.regex)


text:
Q: Disabling Price Ranges on Bundle Items I am working on my first website hosted on Magento, and am having a problem with my bundle items.  I am using a bundle item to allow users to select upgrades to the materials for their products, and it is not required so they can leave the stock material.
The problem is that the product on the frontend displays a price range for between the lowest material upgrade and the highest.  Is there a way to stop that from the displaying?
I figured out how to change it to display an "As Low As" price, but I want it gone completely.

A: If you edit the following file, you can change the way that bundle prices are displayed:
DOCROOT\app\design\frontend\<package>\<theme>\template\bundle\catalog\product\price.phtml

There some complex logic in there to cope with price ranges, "As low as", tax and other considerations, but you should be able to work your way through it.
Make sure that you edit the version of this file that is in your theme (if it only exists in base/default then copy it to the same path under default/yourtheme).
Cheers,
JD


text:
Q: How can I fit this sinusoidal wave with my current data? I have some data I gathered analyzing the change of acceleration regarding time. But when I wrote the code below to have a good fit for the sinusoidal wave, this was the result. Is this because I don't have enough data or am I doing something wrong here?
Here you can see my graph:
Measurements plotted directly(no fit)

Fit with horizontal and vertical shift (curve_fit)

Increased data by linspace

Manually manipulated amplitude

Edit: I increased the data size by using the linspace function and plotting it but I am not sure why the amplitude doesn't match, is it because there are very few data to analyze? (I was able to manipulate the amplitude manually but I don't understand why it can't do it)
The code I am using for the fit
def model(x, a, b):

    return a * np.sin(b * x)

param, parav_cov = cf(model, time, z_values)

array_x = np.linspace(800, 1400, 1000)

fig = plt.figure(figsize = (9, 4))

plt.scatter(time, z_values, color = "#3333cc", label = "Data")

plt.plot(array_x, model(array_x, param[0], param[1], param[2], param[3]), label = "Sin Fit")

A: I'd use an FFT to get a first guess at parameters, as this sort of thing is highly non-linear and curve_fit is unlikely to get very far otherwise.  the reason for using a FFT is to get an initial idea of the frequency involved, not much more.  3Blue1Brown has a great video on FFTs if you've not seem it
I used web plot digitizer to get your data out of your plots, then pulled into Python and made sure it looked OK with:
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('sinfit2.csv')
print(df.head())

giving me:
       x     y
0  809.3   0.3
1  820.0   0.3
2  830.3  19.6
3  839.9  19.6
4  849.6   0.4

I started by doing a basic FFT with NumPy (SciPy has the full fftpack which is more complete, but not needed here):
import numpy as np
from numpy.fft import fft

d = fft(df.y)

plt.plot(np.abs(d)[:len(d)//2], '.')

the np.abs(d) is because you get a complex number back containing both phase and amplitude, and [:len(d)//2] is because (for real valued input) the output is symmetric about the midpoint, i.e. d[5] == d[-5].
this says the largest component was 18, I tried plotting this by hand and it looked OK:
x = np.linspace(0, np.pi * 2, len(df))

plt.plot(df.x, df.y, '.-', lw=1)
plt.plot(df.x, np.sin(x * 18) * 10 + 10)

I'm multiplying by 10 and adding 10 is because the range of a sine is (-1, +1) and we need to take it to (0, 20).
next I passed these to curve_fit with a simplified model to help it along:
from scipy.optimize import curve_fit

def model(x, a, b):
    return np.sin(x * a + b) * 10 + 10

(a, b), cov = curve_fit(model, x, df.y, [18, 0])

again I'm hardcoding the * 10 + 10 to get the range to match your data, which gives me a=17.8 and b=2.97
finally I plot the function sampled at a higher frequency to make sure all is OK:
plt.plot(df.x, df.y)
plt.plot(
    np.linspace(810, 1400, 501),
    model(np.linspace(0, np.pi*2, 501), a, b)
)

giving me:

which seems to look OK.  note you might want to change these parameters so they fit your original X, and note my df.x starts at 810, so I might have missed the first point.