text:
Q: Tastypie ajax POST obj_create - How to return json Im sending a POST that creates a new User, and that works.
My question is how do I get back for example the pk of the created user to the ajax response?
         $.ajax({
                url: 'http://localhost:8080/api/v1/create/user/',
                type: 'POST',
                contentType: 'application/json',
                data: '{"uuid": "12345"}',
                dataType: 'json',
                processData: false,
                success: function (r) {
                    console.log(r)
                },
            });

def obj_create(self, bundle, request=None, **kwargs):
        try:
            user = User.objects.create_user(bundle.data['uuid'],'1')
            user.save()

        except:
            pass
        return bundle

A: you can set always_return_data=True within your UserResource's Meta and on POST and PUT request it will return the created object back.
From the docs

always_return_data
Specifies all HTTP methods (except DELETE) should return a serialized form of the data. Default is False.
If False, HttpNoContent (204) is returned on POST/PUT with an empty body & a Location header of where to request the full resource.
If True, HttpAccepted (202) is returned on POST/PUT with a body containing all the data in a serialized form.

A: Each resource has dehydrate method. You can use it to add any data to response. Here are the docs - http://django-tastypie.readthedocs.org/en/latest/cookbook.html#adding-custom-values

A: You could either use the Location header (set by Tastypie by default) or you could try to make Tastypie send the newly created entity back. I believe the first one is simpler. You may also take a look at related SO question: Is it ok by REST to return content after POST?
First you need to slightly modify jQuery XHR objects,
// Required for reading Location header of POST responses.
var _super = $.ajaxSettings.xhr;
$.ajaxSetup({
    xhr: function () {
        var xhr = _super();
        var getAllResponseHeaders = xhr.getAllResponseHeaders;
        xhr.getAllResponseHeaders = function () {
            var allHeaders = getAllResponseHeaders.call(xhr);
            if (allHeaders) {
                return allHeaders;
            }
            allHeaders = "";
            $(["Cache-Control", "Content-Language", "Content-Type", "Expires", "Last-Modified", "Pragma", "Location"]).each(function (i, header_name) {
                if (xhr.getResponseHeader(header_name)) {
                    allHeaders += header_name + ": " + xhr.getResponseHeader(header_name) + "\n";
                }
            });
            return allHeaders;
        };
        return xhr;
    }
});

This is required because (after jQuery $.ajax docs):

At present, due to a bug in Firefox where .getAllResponseHeaders() returns the empty string although .getResponseHeader('Content-Type') returns a non-empty string, automatically decoding JSON CORS responses in Firefox with jQuery is not supported.
A workaround to this is possible by overriding jQuery.ajaxSettings.xhr as follows:

Then you can read the header in the successCallback, like so:
successCallback: errorAwareCall(function (data, t, textStatus, XMLHttpRequest) {
    var loc = XMLHttpRequest.getAllResponseHeaders();
    var pk = parseInt(loc.match(/\/(\d+)(\/)*/)[1]);
    // Do something with the PK
})


text:
Q: Why does the quality of this video suck when converted with ffmpeg as opposed to mencoder?
Here's the command line that I'm using for both and the output. Any ideas? The bitrate of the two videos is comparable: both around 1500Kbps.
ffmpeg command:
ffmpeg -y -i aud.mp4 -acodec copy -i input.mp4 -ac 2 -vcodec libx264 -s 1280x720
-b 1850k -keyint_min 25 -g 250 -deinterlace -coder 1 -trellis 1 -directpred 1
-b_strategy 1 -bf 3 -refs 3 -subq 5 -me_method hex -me_range 16
-partitions +parti8x8+parti4x4+partp8x8+partb8x8 -flags +loop
-flags2 +bpyramid+wpred+mixed_refs+dct8x8+fastpskip+mbtree -bufsize 2000k
-sc_threshold 40 -cmp +chroma -qdiff 4 -qmin 5 -qmax 51 -qcomp 0.6 -i_qfactor 0.71
-t 0:0:20 -wpredp 2 -r 25 -bt 1500000 output.mp4

ffmpeg output:
FFmpeg version SVN-r21602, Copyright (c) 2000-2010 Fabrice Bellard, et al.
  built on Feb 24 2010 18:28:53 with gcc 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)
  configuration: --prefix=/var/jails/build/ --enable-static --disable-altivec --disable-debug --disable-network --enable-libvorbis --enable-libtheora --enable-libxvid --enable-libx264 --enable-libfaad --enable-libfaac --enable-gpl --disable-ffplay --disable-ffserver --enable-nonfree --enable-avfilter --enable-avfilter-lavf --enable-libmp3lame --enable-pthreads --enable-postproc --disable-shared --enable-static --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-version3 --enable-avfilter --enable-avfilter-lavf
  libavutil     50. 8. 0 / 50. 8. 0
  libavcodec    52.51. 0 / 52.51. 0
  libavformat   52.50. 0 / 52.50. 0
  libavdevice   52. 2. 0 / 52. 2. 0
  libavfilter    1.17. 0 /  1.17. 0
  libswscale     0. 9. 0 /  0. 9. 0
  libpostproc   51. 2. 0 / 51. 2. 0
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'bad.aud.mp4':
  Metadata:
    major_brand     : mp42
    minor_version   : 0
    compatible_brands: M4A mp42isomndia
    encoder         : Nero AAC codec / 1.3.3.0
  Duration: 00:07:24.30, start: 0.000000, bitrate: 90 kb/s
    Stream #0.0(und): Audio: aac, 44100 Hz, stereo, s16, 89 kb/s
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x8b6fe10]max_analyze_duration reached

Seems stream 1 codec frame rate differs from container frame rate: 50.00 (50/1) -> 25.00 (25/1)
Input #1, mov,mp4,m4a,3gp,3g2,mj2, from 'bad.mp4':
  Metadata:
    major_brand     : mp42
    minor_version   : 0
    compatible_brands: mp42isomavc1
    encoder         : Sorenson Squeeze 5.0
  Duration: 00:07:24.32, start: 0.000000, bitrate: 910 kb/s
    Stream #1.0(und): Audio: aac, 48000 Hz, stereo, s16, 320 kb/s
    Stream #1.1(und): Video: h264, yuv420p, 1280x720 [PAR 1:1 DAR 16:9], 524 kb/s, 25 fps, 25 tbr, 90k tbn, 50 tbc
    Stream #1.2(und): Data: mp4s / 0x7334706D
    Stream #1.3(und): Data: mp4s / 0x7334706D
    Stream #1.4(eng): Data: rtp  / 0x20707472, 23 kb/s
    Stream #1.5(eng): Data: rtp  / 0x20707472, 34 kb/s
[libx264 @ 0x8bae2c0]using SAR=1/1
[libx264 @ 0x8bae2c0]using cpu capabilities: MMX2 SSE2 SSE3 Cache64
[libx264 @ 0x8bae2c0]profile High, level 3.1
Output #0, mp4, to 'out.mp4':
    Stream #0.0(und): Video: libx264, yuv420p, 1280x720 [PAR 1:1 DAR 16:9], q=5-51, 1850 kb/s, 25 tbn, 25 tbc
    Stream #0.1(und): Audio: aac, 44100 Hz, stereo, 89 kb/s
Stream mapping:
  Stream #1.1 -> #0.0
  Stream #0.0 -> #0.1
Press [q] to stop encoding
frame=  499 fps= 10 q=-1.0 Lsize=    3514kB time=19.92 bitrate=1445.3kbits/s
video:3279kB audio:220kB global headers:0kB muxing overhead 0.432718%
[libx264 @ 0x8bae2c0]frame I:3     Avg QP: 7.77  size: 66763
[libx264 @ 0x8bae2c0]frame P:208   Avg QP: 6.89  size: 12756
[libx264 @ 0x8bae2c0]frame B:288   Avg QP:11.95  size:  1748
[libx264 @ 0x8bae2c0]consecutive B-frames: 22.0%  1.2%  1.8% 75.0%
[libx264 @ 0x8bae2c0]mb I  I16..4: 66.1% 10.0% 23.9%
[libx264 @ 0x8bae2c0]mb P  I16..4:  3.1%  1.4%  1.6%  P16..4: 14.5%  2.0%  1.5%  0.0%  0.0%    skip:75.9%
[libx264 @ 0x8bae2c0]mb B  I16..4:  1.0%  0.6%  0.2%  B16..8:  2.6%  0.2%  0.2%  direct: 5.7%  skip:89.4%  L0:45.2% L1:46.4% BI: 8.4%
[libx264 @ 0x8bae2c0]8x8 transform intra:23.9% inter:38.3%
[libx264 @ 0x8bae2c0]coded y,uvDC,uvAC intra: 38.0% 34.2% 18.6% inter: 4.9% 6.7% 2.1%
[libx264 @ 0x8bae2c0]i16 v,h,dc,p: 59% 34%  4%  3%
[libx264 @ 0x8bae2c0]i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 25% 35% 28%  2%  2%  2%  2%  2%  3%
[libx264 @ 0x8bae2c0]i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 26% 35% 15%  4%  4%  5%  4%  4%  4%
[libx264 @ 0x8bae2c0]Weighted P-Frames: Y:9.1%
[libx264 @ 0x8bae2c0]ref P L0: 71.5% 18.0%  3.2%  3.5%  3.7%
[libx264 @ 0x8bae2c0]ref B L0: 90.3%  7.4%  2.3%
[libx264 @ 0x8bae2c0]ref B L1: 91.5%  8.5%
[libx264 @ 0x8bae2c0]kb/s:1345.52

MEncoder command:
mencoder bad.mp4 -oac pcm -ovc x264 -ofps 25.0 -vf scale=1280:720,harddup
-o out2.mp4 -srate 48000 -endpos 20
-x264encopts threads=1:bitrate=1850:vbv_bufsize=2000:bframes=3:frameref=3:subq=5:me=hex:b_pyramid=normal:partitions=all

MEncoder output:
MEncoder SVN-r30554-4.1.2 (C) 2000-2010 MPlayer Team

WARNING: OUTPUT FILE FORMAT IS _AVI_. See -of help.
success: format: 0  data: 0x0 - 0x3036dc5
libavformat file format detected.
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x8ed2b70]max_analyze_duration reached
[lavf] Audio stream found, -aid 0
[lavf] Video stream found, -vid 1
VIDEO:  [H264]  1280x720  24bpp  25.000 fps  524.0 kbps (64.0 kbyte/s)
[V] filefmt:44  fourcc:0x34363248  size:1280x720  fps:25.000  ftime:=0.0400
==========================================================================
Opening audio decoder: [faad] AAC (MPEG2/4 Advanced Audio Coding)
AUDIO: 48000 Hz, 2 ch, s16le, 320.0 kbit/20.83% (ratio: 40000->192000)
Selected audio codec: [faad] afm: faad (FAAD AAC (MPEG-2/MPEG-4 Audio))
==========================================================================
Opening video filter: [expand osd=1]
Expand: -1 x -1, -1 ; -1, osd: 1, aspect: 0.000000, round: 1
Opening video filter: [harddup]
Opening video filter: [scale w=1280 h=720]
==========================================================================
Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family
Selected video codec: [ffh264] vfm: ffmpeg (FFmpeg H.264)
==========================================================================
Movie-Aspect is 1.78:1 - prescaling to correct movie aspect..000 [0:0]
[swscaler @ 0x8938400]using unscaled yuv420p -> yuv420p special converter
x264 [info]: using SAR=1/1
x264 [info]: using cpu capabilities: MMX2 SSE2 SSE3 Cache64
x264 [info]: profile High, level 3.1
New_Face failed. Maybe the font path is wrong.
Please supply the text font file (~/.mplayer/subfont.ttf).
subtitle font: load_sub_face failed.
New_Face failed. Maybe the font path is wrong.
Please supply the text font file (~/.mplayer/subfont.ttf).
subtitle font: load_sub_face failed.
Writing header...1f ( 2%)  0.00fps Trem:   0min   0mb  A-V:0.044 [0:0]]
ODML: vprp aspect is 16:9.
Setting audio delay to 0.080s.
Writing header...
ODML: vprp aspect is 16:9.
Setting audio delay to 0.080s.
Pos:  20.0s    542f ( 8%) 10.06fps Trem:  10min  79mb  A-V:0.053 [1144:1536]
Flushing video frames.
Writing index...
Writing header...
ODML: vprp aspect is 16:9.
Setting audio delay to 0.080s.

Video stream: 1063.410 kbit/s  (132926 B/s)  size: 2876525 bytes  21.640 secs  542 frames

Audio stream: 1536.000 kbit/s  (192000 B/s)  size: 3840000 bytes  20.000 secs
x264 [info]: frame I:3     Avg QP:10.62  size:106222
x264 [info]: frame P:216   Avg QP:10.67  size:  9236
x264 [info]: frame B:322   Avg QP:13.29  size:  1748
x264 [info]: consecutive B-frames: 19.7%  0.7%  2.2% 77.3%
x264 [info]: mb I  I16..4: 58.7%  8.0% 33.3%
x264 [info]: mb P  I16..4:  2.8%  1.4%  1.3%  P16..4: 12.8%  1.6%  1.0%  0.2%  0.2%    skip:78.7%
x264 [info]: mb B  I16..4:  0.7%  0.6%  0.2%  B16..8:  2.4%  0.3%  0.2%  direct: 6.7%  skip:88.9%  L0:44.3% L1:47.1% BI: 8.5%
x264 [info]: 8x8 transform intra:26.2% inter:52.8%
x264 [info]: coded y,uvDC,uvAC intra: 38.7% 35.5% 16.8% inter: 3.9% 6.7% 1.0%
x264 [info]: i16 v,h,dc,p: 56% 37%  4%  4%
x264 [info]: i8 v,h,dc,ddl,ddr,vr,hd,vl,hu: 25% 33% 29%  2%  2%  2%  2%  2%  3%
x264 [info]: i4 v,h,dc,ddl,ddr,vr,hd,vl,hu: 27% 33% 16%  4%  4%  5%  4%  4%  4%
x264 [info]: Weighted P-Frames: Y:8.8%
x264 [info]: ref P L0: 69.0% 20.1%  3.6%  3.3%  4.0%
x264 [info]: ref B L0: 91.5%  6.9%  1.6%
x264 [info]: ref B L1: 95.0%  5.0%
x264 [info]: kb/s:1063.41

A: I'm an idiot. The video is non-interlaced and I was passing the -deinterlace flag to ffmpeg. This was the source of the artifacts.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get drop down value on post back I have a view with a drop down, which is tied to the view model...
One of the view model's properties:
public int selectDTypeID { get; set; }

the view has a drop down:
   Html.DropDownListFor(
       model => model.selectDTypeID ,
       new SelectList(
              new List<Object>{
                   new { value = 1 , text = "Test1"  },
                   new { value = 2 , text = "Test2" },
                   new { value = 3 , text = "Test3"}
                },
              "value",
              "text"
       )
    )

How can I get the the value of the drop down list on post back without using an extra parameter... I'd just like to be able to do this...
[HttpPost]
public ActionResult ContinueDonation(AddDonationViewModel model)
{
 var id = model.selectDTypeID;

}

Can I do something like this?

A: If your View is a strongly typed view like this,
@model AddDonationViewModel
@using (Html.BeginForm())
{
   @Html.DropDownListFor(
       model => model.selectDTypeID ,
       new SelectList(
              new List<Object>{
                   new { value = 1 , text = "Test1"  },
                   new { value = 2 , text = "Test2" },
                   new { value = 3 , text = "Test3"}
                },
              "value",  "text"))

    <input type="submit" value="go" />
}

When you click on submit, the selected value will be available in the SelectdTYpeID property in your HttpPost Action method
[HttpPost]
public ActionResult ContinueDonation(AddDonationViewModel model)
{
  var id = model.selectDTypeID;  // You have your selected ID here
}


text:
Q: Android: Amplify SignOut closes app before actually signin out I decided to use Amplify on a school project, after I went through the Login process following this guide: https://docs.amplify.aws/lib/auth/signin/q/platform/android/
And also after adding the social sign in: https://docs.amplify.aws/lib/auth/social_signin_web_ui/q/platform/android/
After following these guides I decided to also add a signout feature and test it out: https://docs.amplify.aws/lib/auth/signOut/q/platform/android/
It should have worked fine but when i lauch the signout method in the guide (literally after copying and pasting it in the project) the app closes as soon as I test it, and it isn't even consistent with the errors, the usual pattern is: it closes, after a while the console says that the signout timed out (obviously) when I reopen the app from the VM it says that it signout successfully then crashes giving this error (the project is called natour):
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.natour, PID: 7330
java.lang.RuntimeException: Unable to resume activity {com.example.natour/com.amazonaws.mobileconnectors.cognitoauth.activities.CustomTabsManagerActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.content.Intent.migrateExtraStreamToClipData()' on a null object reference
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3400)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3440)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2713)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.content.Intent.migrateExtraStreamToClipData()' on a null object reference
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1516)
    at android.app.Activity.startActivityForResult(Activity.java:4224)
    at android.app.Activity.startActivityForResult(Activity.java:4183)
    at android.app.Activity.startActivity(Activity.java:4507)
    at android.app.Activity.startActivity(Activity.java:4475)
    at com.amazonaws.mobileconnectors.cognitoauth.activities.CustomTabsManagerActivity.onResume(CustomTabsManagerActivity.java:69)
    at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1269)
    at android.app.Activity.performResume(Activity.java:6766)
    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3377)
    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3440)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2713)
    at android.app.ActivityThread.-wrap12(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6077)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)

I tried different things, thinking that if the login worked just fine, then something weird happened for the logout redirect uri, but nope, i changed it with "amplify update auth" on the console, changed the callback uri and nothing appened, the same error, the login worked just fine too even though I wrote an activity that wasn't even launched.
I changed the manifest because maybe the custom tab manager activity gave problems but to no avail (meaning it either gives far worse problems to which I know the cause or the same)
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.natour">
    <uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" tools:ignore="QueryAllPackagesPermission" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission
        android:name="android.permission.GET_ACCOUNTS"
        android:maxSdkVersion="22" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />

    <queries>
        <intent>
            <action android:name="android.intent.action.VIEW" />

            <data android:scheme="natour" />
        </intent>
        <intent>
            <action android:name="android.support.customtabs.action.CustomTabsService" />

        </intent>
    </queries>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.NaTour">

        <activity
            android:name=".view.TransazioneRegister"
            android:exported="false" />
        <activity
            android:name=".visualizza_foto_inserite"
            android:exported="false" />
        <activity
            android:name=".visualizza_segnalazioni_effettuate"
            android:exported="false" />
        <activity
            android:name=".visualizza_itinerari_inseriti"
            android:exported="false" />
        <activity
            android:name=".visualizza_recensioni_inserite"
            android:exported="false" />
        <activity
            android:name=".view.InserimentoItinerario"
            android:exported="false" />
        <activity
            android:name=".view.Profile"
            android:exported="false" />
        <activity
            android:name=".view.Register"
            android:exported="false" />
        <activity
            android:name=".view.Login"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".view.VisualizzaItinerario"
            android:exported="false" />
        <activity
            android:name=".view.TabActivity"
            android:exported="false" /> <!-- Facebook Requirements -->
        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />

        <activity
            android:name="com.amplifyframework.auth.cognito.activities.HostedUIRedirectActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="natour"/>
            </intent-filter>
        </activity>
        <activity
            android:name=".view.Signout"
            android:exported="true">
            <intent-filter>
                <data android:scheme="natour"/>
            </intent-filter>

        </activity>
        <!--<activity
            android:name="com.amazonaws.mobileconnectors.cognitoauth.activities.CustomTabsRedirectActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="natour" />
            </intent-filter>
        </activity>-->
    </application>

</manifest>

this is the manifest in the final attempt, after that i gave up.
I searched this problem online and even though they got pretty close to our problem, either they didn't show the solution, the code is written in other programming language, they didn't explain what was going on. I hope to find some help here, thanks in advance.

A: I know this has been a while but I found that you need to change launchMode. I tried singleTask it works fine. Maybe singleInstance also works. But I get a time out error: Timed out while waiting for sign-out redirect response.
I found amplify is difficult to deal with because lack of documents and potential bugs, maybe also because not many people use it.


text:
Q: Open app with package name using ADB How do I open an app using ADB when I know the app's package name but not the component name of the main activity?

A: If you only know the package name of the app you want to launch but not the name of it's main activity, use this command
adb shell monkey -p com.android.chrome -c android.intent.category.LAUNCHER 1

Where com.android.chrome is the package name of the app you want to open.
The monkey command is used for making random touch and keyboard inputs on the connected device. The command above specifies that only one event can be issued, which is the open activity event. The -c option is to specify that only activities with the category android.intent.category.LAUNCHER can be opened, which is the action that is used as an entry point for the app.


text:
Q: what are the leading XSL-FO implementations? How do I decide among them? I'm evaluating PDF rendering technologies. XSL-FO is our chosen path because its an open standard and our source data is XML.  What experiences have people had with the various implementations of XSL-FO?
The implementations I've found so far are:

*

*renderX

*ecrion

*Antenna House

*Apache FOP
The criteria I'm using to evaluate are: performance, stability, supportability,
price, template management tools. Also important: good java APIs and ability to run on Unix.
Whatever product we end up choosing, we will also be asked to find consulting services to help us build our templates, so the ability to find developers versed in the the technology is important.
Update:
The Ecrion folks did a performance comparison  which is disputed by the renderX
people. However, renderX has so far declined to offer their own benchmarks or tests for comparison. I guess I'll have to run my own benchmarks.
So far I'm leaning toward Ecrion because it supports WordML output, and the renderX guy was kind of rude.

A: Ibex pdf creator is a good XSL-FO engine with Java and .NET implementations.
I have used their Java implementation and it did pretty much everything we needed and was performant.  Their licensing model is really good, especially if you are building clients that need XSL-FO processing.  You pay a per-developer fee, not a per-client distribution.
Antenna House and renderX. are the leaders in the XSL-FO space.  They have great tools and overall support/implementation for the XSL-FO specification.
Regardless of which FO engine you decide on, it is helpful to have several available for development.  Rendering through different FO engines helps test out your XSL-FO and determine if incorrect output is due to a problem with the rendering engine or with your XSL-FO.

A: Ecrion has the most advanced report designer. It's way above Antenna's tool, and you can see the actual XSL-FO that is being edited. This is important because you can use Ecrion's Designer with all XSL-FO formatters including FOP. Other vendors are trying to achieve a vendor lock-in to their own FO formatter.

A: Antennahouse is another major XSL-FO implementation:

A: Late entry, but to complete: I'm using XML2PDF Workstation from www.alt-soft.com
 - it's fast, cheap and does the job, even SVG and Bookmarks.


text:
Q: PlayFramework+GAE+Siena using Datastore and Cloud SQL simultaneously Does anyone knows if is there way to use Datastore and Cloud SQL in GAE application simultaneously (PlayFramework 1.2.7 with GAE plugin).
E.g.
@Table("sometable1")
class Model1 extends siena.Model{}

@Table("sometable2")
class Model2 extends siena.Model{}

I want to make possible to store Model1 to Cloud SQL (via Siena), and Model2 to Datastore (also via Siena)
Does anybody faced such problem?


text:
Q: print decision tree in text nicely / with custom control [r] I'd like to print a decision tree in text nicely. For example, I can print the tree object itself:
library(rpart)

f = as.formula('Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species')
fit = rpart(f, data = iris, control = rpart.control(xval = 3))

fit

yields
n= 150

node), split, n, deviance, yval
      * denotes terminal node

 1) root 150 102.1683000 5.843333
   2) Petal.Length< 4.25 73  13.1391800 5.179452
     4) Petal.Length< 3.4 53   6.1083020 5.005660
       8) Sepal.Width< 3.25 20   1.0855000 4.735000 *
       9) Sepal.Width>=3.25 33   2.6696970 5.169697 *
... # omitted

partykit prints it neater:
library(partykit)

as.party(fit)

yields
Model formula:
Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species

Fitted party:
[1] root
|   [2] Petal.Length < 4.25
|   |   [3] Petal.Length < 3.4
|   |   |   [4] Sepal.Width < 3.25: 4.735 (n = 20, err = 1.1)
|   |   |   [5] Sepal.Width >= 3.25: 5.170 (n = 33, err = 2.7)
|   |   [6] Petal.Length >= 3.4: 5.640 (n = 20, err = 1.2)
...# omitted

Number of inner nodes:    6
Number of terminal nodes: 7

Is there a way I have have more control? Eg, I don't want to print n and err, or want standard deviation instead of err printed.

A: Not a very elegant answer, but if you just want to get rid of n= and err= you can capture the output and edit it.
CO = capture.output(print(as.party(fit)))
CO2 = sub("\\(.*\\)", "", CO)
cat(paste(CO2, collapse="\n"))

Model formula:
Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species

Fitted party:
[1] root
|   [2] Petal.Length < 4.25
|   |   [3] Petal.Length < 3.4
|   |   |   [4] Sepal.Width < 3.25: 4.735
|   |   |   [5] Sepal.Width >= 3.25: 5.170
|   |   [6] Petal.Length >= 3.4: 5.640
|   [7] Petal.Length >= 4.25

I am not sure what standard deviation you want to insert, but I expect you could edit that in the same way.

A: The print() method for party objects is quite flexible and can be controlled through various panel functions and customizations. See ?print.party for an overview. The documentation is somewhat short and technical, though.
In your case, the easiest solution is to set up a function of the response y, the case weights w (defaulting to all 1 in your case), and the desired number of digits:
myfun <- function(y, w, digits = 2) {
  n <- sum(w)
  m <- weighted.mean(y, w)
  s <- sqrt(weighted.mean((y - m)^2, w) * n/(n - 1))
  sprintf("%s (serr = %s)",
    round(m, digits = digits),
    round(s, digits = digits))
}

And then you can pass that to your print() call:
p <- as.party(fit)
print(p, FUN = myfun)
## Model formula:
## Sepal.Length ~ Sepal.Width + Petal.Length + Petal.Width + Species
##
## Fitted party:
## [1] root
## |   [2] Petal.Length < 4.25
## |   |   [3] Petal.Length < 3.4
## |   |   |   [4] Sepal.Width < 3.25: 4.735 (serr = 0.239)
## |   |   |   [5] Sepal.Width >= 3.25: 5.17 (serr = 0.289)
## |   |   [6] Petal.Length >= 3.4: 5.64 (serr = 0.25)
## |   [7] Petal.Length >= 4.25
## |   |   [8] Petal.Length < 6.05
## |   |   |   [9] Petal.Length < 5.15
## |   |   |   |   [10] Sepal.Width < 3.05: 6.055 (serr = 0.404)
## |   |   |   |   [11] Sepal.Width >= 3.05: 6.53 (serr = 0.38)
## |   |   |   [12] Petal.Length >= 5.15: 6.604 (serr = 0.302)
## |   |   [13] Petal.Length >= 6.05: 7.578 (serr = 0.228)
##
## Number of inner nodes:    6
## Number of terminal nodes: 7


text:
Q: Checking if user has a certain extension installed I just found out that the Screen Capture by Google extension makes my website's window.onresize event not fire.
I want to perform a javascript check to see if the user has ScreenCapture installed and if so,  warn the user of the problem.
A year ago I think I heard of some javascript code that could do this, maybe using some google API, but I don't remember.
Any insight on this? I haven't developed any extensions so I don't really know how they work.
[EDIT]
So I have been asked to show some code. As seen in my previous question ( window.onresize not firing in Chrome but firing in Chrome Incognito ), the problem occurs on any window.onresize event function, so I don't think my code really matters.
Also, there is quite a lot of my code, I don't know how much of it to paste or if it would be helpful.
        var debounce = function (func, threshold, execAsap)
    {
        var timeout;

        return function debounced () {//alert("1.1 Y U NO WORK?");
            var obj = this, args = arguments;
            function delayed () {
                if (!execAsap)
                    func.apply(obj, args);
                timeout = null;
            }

            if (timeout)
                clearTimeout(timeout);
            else if (execAsap)
                func.apply(obj, args);

            timeout = setTimeout(delayed, threshold || 100);
        };
    };

    window.onresize = debounce(function (e) { //alert("1.2 Y U NO WORK?");
        flag = true;
        var point = window.center({width:1,height:1});
        doCenter(point);
        // does something here, but only once after mouse cursor stops
    }, 100, false);

I would like to stress that the problem is not due to the debounce. window.onresize = t; function t (e) { alert("wtf?");} won't work either.
[EDIT2]
Here's the result:
    var screenCapture = null;
    var screenCaptureImg = document.createElement("img");
     screenCaptureImg.setAttribute("src", "chrome-extension://cpngackimfmofbokmjmljamhdncknpmg/images/arrow.png");
    /*
     * Add event listeners for both "load"- and "error"-event
     * Set the variable showing the existence of the extension by
     * setting it to "true" or "false" according to the fired event
     */
    screenCaptureImg.addEventListener("load", doLoad, false);
    function doLoad(e){
        screenCapture = true; //removeImgTag(e);

        alert("I've so cleverly detected that your Chrome has the ScreenCapture extension enabled. \n\nThis extension interferes with my website's DOM and long story short, it won't be able to scale properly.\n\nSo please disable it. \nConsider this extension: \"Disable All Extensions Plus\", it's a handy selective disabler.");
    }

    screenCaptureImg.addEventListener("error", function(e){
        screenCapture = false; //removeImgTag(e);
    }, false);
    /*
    function removeImgTag(e) {
        e.currentTarget.parentNode.removeChild(e.currentTarget);
    }
    */

Note that I couldn't get removeImgTag to work, because (at least in chrome), I don't seem to have access to the document object in order to create or remove elements from my page, from within these event functions. This is also why I'm displaying an alert instead of elegantly writing up a document.getElementById("something").innerHTML=...

A: To detect if an extension is installed in Chrome, you can check for a known resource included in the extension such as an image. Resources for the extension are referenced using the following URL pattern:
chrome-extension://<extensionID>/<pathToFile>

The basic detection technique involves creating a hidden image tag and attaching load and error events to it to see if the image loads (as described here for Firefox):
extensionImg.setAttribute("src", "chrome-extension://<INSERT EXTENSION ID HERE>/images/someImage.png"); // See below for discussion of how to find this

/*
 * Add event listeners for both "load"- and "error"-event
 * Set the variable showing the existence of the extension by
 * setting it to "true" or "false" according to the fired event
 */
extensionImg.addEventListener("load", function(e) {
    extensionExists = true;
    removeImgTag(e);
}, false);
extensionImg.addEventListener("error", function(e) {
    extensionExists = false;
    removeImgTag(e);
}, false);

function removeImgTag(e) {
    e.currentTarget.parentNode.removeChild(e.currentTarget);
}

Check the installation directory of the extension in the Chrome configuration to find a likely target for detection. On my Linux workstation extensions are located in:
 ~/.config/chromium/Default/Extensions

You can see that I have 3 extensions installed right now:
~/.config/chromium/Default/Extensions$ ls
cpecbmjeidppdiampimghndkikcmoadk  nmpeeekfhbmikbdhlpjbfmnpgcbeggic
cpngackimfmofbokmjmljamhdncknpmg

The odd looking names are the unique IDs given to the extension when it is uploaded to the Chrome webstore. You can obtain the ID either from the webstore or by going to the Extensions tab (wrench -> Extensions) and hovering over the link to the extension in question, or "Screen Capture (by Google)" in this case (note the asterisked extension ID):
https://chrome.google.com/webstore/detail/**cpngackimfmofbokmjmljamhdncknpmg**

In the extension directory there will be one or more versions; you can ignore this. Within the version directory is the actual content of the extension:
~/.config/chromium/Default/Extensions/cpngackimfmofbokmjmljamhdncknpmg/5.0.3_0$ ls
account.js         images             page.js         sina_microblog.js
ajax.js            isLoad.js          picasa.js       site.js
background.html    _locales           plugin          style.css
editor.js          manifest.json      popup.html      ui.js
facebook.js        notification.html  sha1.js         upload_ui.js
hotkey_storage.js  oauth.js           shortcut.js
hub.html           options.html       showimage.css
i18n_styles        page_context.js    showimage.html

In the case of the Screen Capture extension there are a number of images to use:
~/.config/chromium/Default/Extensions/cpngackimfmofbokmjmljamhdncknpmg/5.0.3_0/images$ ls
arrow.png                icon_128.png    icon_save.png     print.png
copy.png                 icon_16.png     line.png          region.png
cross.png                icon_19.png     loading.gif       screen.png
custom.png               icon_32.png     loading_icon.gif  sina_icon.png
delete_account_icon.png  icon_48.png     mark.png          toolbar_bg.png
down_arrow.png           icon_close.png  picasa_icon.png   upload.png
facebook_icon.png        icon_copy.png   popup_bg.jpg      whole.png

These can be referenced under this URL:
chrome-extension://cpngackimfmofbokmjmljamhdncknpmg/images/arrow.png

This technique obviously depends on the stability of the content of the extension. I recommend using an image that looks likely to remain through all versions.

As mentioned above, the same technique can be used to detect Firefox extensions. In this case the content URL looks like this:
chrome://<EXTENSION NAME>/content/<PATH TO RESOURCE>

On my Linux workstation Firefox extensions are located in:
 ~/.mozilla/firefox/<USER PROFILE ID>/extensions

Where <USER PROFILE ID> looks something like this: "h4aqaewq.default"
You can see that I have 2 extensions installed right now, one of which is a directory installation and the other of which is a XPI (pronounced "zippy") file:
~/.mozilla/firefox/h4aqaewq.default/extensions$ ls
{3e9a3920-1b27-11da-8cd6-0800200c9a66}  staged
firebug@software.joehewitt.com.xpi

The "staged" directory is where Firefox keeps extensions that will be updated (I think). The GUID directory with the brackets is a directory-based extension installation, and the .xpi file is Firebug.
Note: XPI is going away (see the link above). It's basically a zip file that can be opened and inspected by anything that understands zip. I used Emacs.
Finding the extension ID in Firefox is a bit more involved. Go to "Tools -> Add-ons", click the Extensions tab,  click the "More" link next to the extension description, then click the "reviews" link to go to the Firefox extension site and get the ID from the URL (note the asterisked extension ID):
https://addons.mozilla.org/en-US/firefox/addon/**firebug**/reviews/?src=api

There's probably an easier way to do this; suggestions welcome.
TODO: how to find a likely image in a Firefox extension.

As an extra note, in Chrome you can only communicate with an extension via the shared DOM of the page: Host page communication


text:
Q: Create object of objects from arrays I have two arrays in JavaScript:
a = [2, 5, 8, 10, 12, 15]

and
b = ["2022-01-01", "2022-01-02", "2022-01-03", "2022-01-04", "2022-01-05", "2022-01-06"]

I want to turn this into an object of objects, like so:
ts = {
  {
    value: 2,
    time: "2022-01-01"
  },
  {
    value: 5,
    time: "2022-01-02"
  },
  {
    value: 8,
    time: "2022-01-03"
  },
  {
    value: 10,
    time: "2022-01-04"
  },
  {
    value: 12,
    time: "2022-01-05"
  },
  {
    value: 15,
    time: "2022-01-06"
  }
}

I have looked at the forEach method and the reduce method, e.g. from https://bobbyhadz.com/blog/javascript-create-object-from-two-arrays , but I am struggling. Edit: my attempt was along the lines of:
const ts = {};
a.forEach((a_value, index) => {
  ts.value[index] = a_value[index];
});

A: A simple for loop will work if both lists are the same size.

let a = [2, 5, 8, 10, 12, 15]
let b = ["2022-01-01", "2022-01-02", "2022-01-03", "2022-01-04", "2022-01-05", "2022-01-06"]

let ts = []

for (let idx in a) {
  ts.push({value: a[idx],
    time: b[idx]})
}

console.log(ts)


text:
Q: Error when Open Redis server I download Redis 2.8.19 on windows, it run properly. But after i reboot my computer, i try to open it and an error show up :

[]5880] 14 May 15:42:12.227# The Windows version of Redis allocates a large memory mapped file for sharing the heap with the forked process used in persistence operations. This file will be created in the current working directory or the directory specified by the 'heapdir' directive in the .conf file. Windows is reporting that there is insufficient disk space available for this file (Windows error 0x70).
You may fix this problem by either reducing the size of the Redis heap with the --maxheap flag, or by moving the heap file to a local drive with sufficient space. Please see the documentation included with the binary distributions for more details on the --maxheap and --heapdir flags.
Redis can not continue. Exiting.

I cant find the heap file and dont know how to reduce the size of Redis heap.
Thanks !

A:
During fork() operations the total page file commit will max out at around:

(size of physical memory) + (2 * size of maxheap)

For instance, on a machine with 8GB of physical RAM, the max page file commit with the default maxheap size will be (8)+(2*8) GB , or 24GB.
If you don't give any hints to Redis, you get an error similar to the following:
The Windows version of Redis allocates a large memory mapped file for sharing
the heap with the forked process used in persistence operations. This file
will be created in the current working directory or the directory specified by
the 'heapdir' directive in the .conf file. Windows is reporting that there is
insufficient disk space available for this file (Windows error 0x70).

You may fix this problem by either reducing the size of the Redis heap with
the –maxheap flag, or by moving the heap file to a local drive with sufficient
space.
Please see the documentation included with the binary distributions for more
details on the –maxheap and –heapdir flags.

Redis can not continue. Exiting.

To get around this limitation, specify the –maxheap flag when starting Redis, using a value that is relevant to your machine:
redis-server –-maxheap 1gb

Link : Installing Redis Cache Locally in a Development Environment

A: You can find a file named "redis.windows.conf" in Redis folder.Search text "maxheap " and insert "maxheap 1024000000" in next line(Or you can set more than 1024000000).Restart redis server after modify file.


text:
Q: identifying the substring when the number of characters in between don't matter def checkPattern(x, string):
    e = len(string)
    if len(x) < e:
        return False
    for i in range(e - 1):
        x = string[i]
        y = string[i + 1]
        last = x.rindex(x)
        first = x.index(y)
        if last == -1 or first == -1 or last > first:
            return False
    return True
if __name__ == "__main__":
    x = str(input())
    string = "hello"
    if checkPattern(x, string) is True:
        print('YES')
    if checkPattern(x, string) is False:
        print('NO')

So basically the code is supposed to identify a substring when the number of characters between the substring's letters don't matter. string = "hello" is supposed to be the substring. While the characters in between don't matter the order still matters so If I type "h.e.l.l.o" for example it's a YES, but if it's something like "hlelo" it's a NO. I sorta copied the base of the code and I'm still a little new to python so sorry if the question and code aren't clear.

A: Assuming I understand, and the input hlelo is No and the input h.e..l.l.!o is Yes, then the following code should work:
def checkPattern(x, string):

    assert x and string, "Error. Both inputs should be non-empty. "
    count_idx = 0   # index which counts where you are.

    for letter in x:
        if letter == string[count_idx]:
            count_idx += 1 # increment to check the next string
            if count_idx == len(string):
                return True

    # pattern was found if counter found matches equal to string length
    return False

if __name__ == "__main__":
    inp = input()
    string = "hello"
    if checkPattern(inp, string) is True:
        print('YES')
    if checkPattern(inp, string) is False:
        print('NO')

Explaination: Regardless of the input string, x, you want to loop through each character of the search-string hello, to check if you find each character in the correct order. What my solution does is that it counts how many of the characters h, e, l, l, o it has found, starting from 0. If it finds a match for h, it moves on to check for a match for e, and so on. Ultimately, if you search through the entire string x, and the counter does not equal to the length of the search string (i.e. you could not find all the hello characters), it returns false.
EDIT: Small debug in the way the return worked. Instead returns if ever the counter goes over the length. Also added more examples given in comments

A: Here is my solution to this problem:
pattern = "hello"

def patternCheck(word, pattern) -> bool:
    plist = list(pattern)
    wlist = list(word)

    for p in plist:
        if p in wlist:
            for _ in range(wlist.index(p) , -1, -1):
                wlist.pop(_)
        else:
            return False
    return True

print(patternCheck("h.e.l.l.o", pattern))
print(patternCheck("aalohel", pattern))
print(patternCheck("hhhhheeelllooo", pattern))

Explanation
First we convert our strings to a list
plist = list(pattern)
wlist = list(word)

Now we check using a for loop if every element in our pattern list is in the word list.
for p in plist:
    if p in wlist:

If yes then we remove all the elements from index 0 to the index of that element.
        for _ in range(wlist.index(p) , -1, -1):
            wlist.pop(_)

We are removing elements in decreasing order of there indices to protect ourself from the IndexError: pop index out of range.

If the for loop ends normally then there was a match and we return True. Else if the element was not found in the word list in the first place then we return false as there is no match.


text:
Q: split an array in known fragment I have an array of hashes that contain a boolean key, like
    [{"n"=>"img01", "h"=>1},
     {"n"=>"img02", "h"=>1},
     {"n"=>"img03", "h"=>0},
     {"n"=>"img04", "h"=>1}]

my goal is split the in groups that have one of these condition of h key:
  [1,1,1] or [1,0] or [0,1] or [1,1] or single value if any of these condition is not possible. In this example the only way to split the array is
     [{"n"=>"img01", "h"=>1},{"n"=>"img02", "h"=>1}]

and
     [{"n"=>"img03", "h"=>0},{"n"=>"img04", "h"=>1}]

but first it should search for an array done in this way
          [{"n"=>"img01", "h"=>1},
           {"n"=>"img02", "h"=>1},
           {"n"=>"img03", "h"=>1}]

and then looking for the other combinations
I've tried to splice the original array in groups of 3 (in test used just an array of 1 and 0)
 irb(main):030:0> b=a.each_slice(3).to_a => [[0, 1, 1], [1, 1, 0], [0, 0, 0], [0]]

and then confront the result to the biggest array first [1,1,1], and then try to split again if not
 irb(main):055:0> (b[0] -  [1,1,1]).count => 1

so move to next sub array the last value
 irb(main):060:0> b[1].push(b[0].pop)=> [1, 1, 0, 1]

repeat the search in the first two-elements array
(irb(main):061:0> b[0] - [1,0]).count
(irb(main):061:0> b[0] - [1,1]).count
(irb(main):061:0> b[0] - [0,1]).count

and then merge the other sub-array, split it again and repeat the search, but it is definitely
 messed up

A: You can use the 1 and 0 as sort of an imaginary image width. A horizontal image is assumed to be double the width of a vertical image.
You can then proceed to use that to calculate how wide the images on the current row of images is and will the next image still fit on that row.
When width + next element width is larger than what fits a "row of images", you start a new row.
Example:
input = [{"n"=>"img01", "h"=>1},
   {"n"=>"img02", "h"=>1},
   {"n"=>"img03", "h"=>0},
   {"n"=>"img04", "h"=>1}]

image_rows = []
current_row = []
current_width = 0.0
input.each.with_index(1) do |image_data, idx|

  image_width = image_data['h'] == 1 ? 0.5 : 1.0

  if current_width + image_width > 1.5
    image_rows << current_row
    current_row = [image_data]
    current_width = image_width
  else
    current_row << image_data
    current_width += image_width
  end

  if idx == input.size
    image_rows << current_row
  end
end

require 'json'
puts JSON.pretty_generate(image_rows)

Outputs:
[
  [
    {
      "n": "img01",
      "h": 1
    },
    {
      "n": "img02",
      "h": 1
    }
  ],
  [
    {
      "n": "img03",
      "h": 0
    },
    {
      "n": "img04",
      "h": 1
    }
  ]
]

*

*When current row has 111 the width is 0.5 + 0.5 + 0.5 = 1.5 => nothing fits in

*When current row has 10 the width is 1.0 + 0.5 = 1.5 => nothing fits in

*When current row has 01 the width is 0.5 + 1.0 = 1.5 => nothing fits in

*When current row has 11 the width is 0.5 + 0.5 = 1.0 => only 0.5 fits in

*When current row has 1 the width is 0.5 => either 1.0 or 0.5 fits in

*When current row has 0 the width is 1.0 => only 0.5 fits in

You can find the first group containing 111 by doing image_rows.find { |row| row.size == 3 }.


text:
Q: Java - render HTML, JS and CSS and send output html as a string im working on a server-side html render.
The case: The user has a simpel page with 3 cells. In each cell he can fill the html, css and JS code. After that, it will be send to the server which render the html and css code considering the javascript code.
My idea was to "simulate" a headless-browser. Till now i just found PhantomJS but i think its not really comfortable.
My result should be only the rendered HTML DOM
thank you

A: Try headless Chrome, this works on all operating systems:
https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md
On Linux you have one more option. You can run any normal browser with virtual screen buffer.

A: Thank you for your response. As far as i see i have to use node.js. Is there a way to stay in the java envoirment without node.js?


text:
Q: Data Truncated using SUM I have run a query in MySQL and I get a result back, while running it as a python script is giving me an error. I am unsure why this is happening. I am trying to get the sum of a single column and inserting that value into another column on another table.
Code:
HAND_HISTORY_DB_TABLES['Hands'] = (
    "CREATE TABLE `Hands` ("
    "   `HandResults` float"
    ") ENGINE=InnoDB")
HAND_HISTORY_DB_TABLES['Players'] = (
    "CREATE TABLE `Players` ("
    "   `PlayerName` varchar(16) PRIMARY KEY,"
    "   `PlayerResults` float"
    ") ENGINE=InnoDB")
...

    def insert_player_results(self):
        """
        Insert Player Results
        :return:
        """
        try:
            cursor.execute("INSERT INTO Players (PlayerResults) SELECT ROUND(SUM(HandResults), 2) FROM Hands")
            sql_connection.commit()
            print("Player Results inserted succesfully")
        except mysql.IntegrityError as err:
            print(f"Error: {err}")
...
    plyr.insert_player_results()
...

Error: mysql.connector.errors.DatabaseError: 1364 (HY000): Field 'PlayerName' doesn't have a default value
Edited to include suggestion from answer below

A: Not sure where sql_connection is defined, but you are using a prepared statement, which requires that the second argument is a tuple with the actual value(s) to insert, not the string representing the query that would obtain those value(s). This would require doing two operations, one to fetch the results and store them in a designated variable, and one to perform the insert.
An alternative is to directly use a single query:
    def insert_player_results(self):
        try:
            cursor.execute('INSERT INTO Players SELECT ROUND(SUM(HandResults), 2) FROM Hands')
            sql_connection.commit()
            print('Player Results inserted successfully')
        except mysql.IntegrityError as err:
            print(f'Error: {err}')


text:
Q: Preenchimento automático com select woocommerce checkout Tenho o seguinte código para gerar um select e trazer os valores dentro dos options:
add_action( 'woocommerce_after_order_notes', 'cliente_woocommerce' );
function cliente_woocommerce( $checkout )
{
global $wpdb;

$results = $wpdb->get_results( "SELECT * FROM tab_clientes" );
$options  = array( '' => __('Selecione o cliente') );

// Loop through the data query results
foreach($results as $result) {
    $options[$result->nome] = $result->razao_social;

}

echo '

' . __('Cliente') . '
';

woocommerce_form_field( 'cliente', array(
    'type' => 'select',
    'class' => array('cliente form-row-wide'),
    'label' => __('Campo de Teste (Cliente)'),
    'options'   =>  $options,
), $checkout->get_value( 'cliente' ) );

woocommerce_form_field( 'nome', array(
    'type' => 'text',
    'class' => array('nome form-row-wide'),
    'label' => __('Razão Social'),
    'default'   =>  '',

), $checkout->get_value( 'nome' ) );
woocommerce_form_field( 'cnpj', array(
    'type' => 'text',
    'class' => array('cnpj form-row-wide'),
    'label' => __('CNPJ'),
    'default'   =>  '',

), $checkout->get_value( 'cnpj' ) );

echo '
';

com o seguinte script:

Quando seleciono o cliente, o campo #nome (razão social - na tabela = razao_social) aparece com o valor correto, porém o valor se repete dentro de CNPJ.
O que estou fazendo errado?


text:
Q: WordPress deployment using docker-compose yaml - error establishing database I'm working on a school project and can't get past this issue. I've created a docker-compose yaml file to build a WordPress container and setup. After I run the "docker-compose up -d" everything seems to run fine. The issue I'm having is that when opening to WP page, I get an "Error establishing database connection"
Here is my docker-compose.yml file. Thank you.
version: '3.3'

services:
   db:
     image: mysql:5.7
     volumes:
       - db_data:/var/lib/mysql
     restart: always
     environment:
       MYSQL_ROOT_PASSWORD: somewordpress
       MYSQL_DATABASE: wordpress
       MYSQL_USER: wordpress
       MYSQL_PASSWORD: wordpress

   wordpress:
     depends_on:
       - db
     image: wordpress:latest
     ports:
       - "8000:80"
     restart: always
     environment:
       WORDPRESS_DB_HOST: db:3306
       WORDPRESS_DB_USER: wordpress
       WORDPRESS_DB_PASSWORD: wordpress
       WORDPRESS_DB_NAME: wordpress
volumes:
    db_data: {}

A: Make sure the db service environment variables match with the database information defined in your wp-config.php.
/** The name of the database for WordPress */
define( 'DB_NAME', 'wordpress' );
/** MySQL database username */
define( 'DB_USER', 'wordpress' );
/** MySQL database password */
define( 'DB_PASSWORD', 'wordpress' );
/** MySQL hostname */
define( 'DB_HOST', 'db' );

You can test if wordpress container can access the database by bashing into the wordpress container and pinging the database container:
$ docker-compose exec wordpress bash
$ apt-get -y install iputils-ping && ping db


text:
Q: Got error "Service principal was not found" when trying to add a certificate to an azure app I am following the example on https://azure.microsoft.com/en-us/documentation/samples/active-directory-dotnet-daemon-certificate-credential/ to authenticate a daemon app with certificate to a service app using Azure AD. I have done the following:

*

*create my own Active Directory

*create the daemon application in the AD
Name: TodoListDaemonWithCertYanlin
Sign-On URL: http ://TodoListDaemonWithCertYanlin
App Id Url: http ://TodoListDaemonWithCertYanlin

*create a self-signed certificate
makecert -r -pe -n "CN=TodoListDaemonWithCertYanlin" -ss My -len 2048 TodoListDaemonWithCert.cer

When I try to add the certificate to the daemon application in PowerShell, I got an error.
The PowerShell command that I used:  New-MsolServicePrincipalCredential -AppPrincipalId  "e5dedde0-2221-4ce4-a74d-af4e96705c01" -Type asy
mmetric -Value $credValue -StartDate $cer.GetEffectiveDateString() -EndDate $cer.GetExpirationDateString() -Usage verify
The error is: New-MsolServicePrincipalCredential : Service principal was not found.
"Get-MsolServicePrincipal -SearchString TodoListDaemonWithCert" returned a bunch of applications, but mine is not included.
I doubt that Azure might search my org's AD instead of the AD that I created. But I have no idea how to debug the issue.

A: Problem solved.
Here are why it happened: I logged into Azure using my org's credential, then created a testing Active Directory, and created the Todo List Daemon application in my testing Active Directory. When I signed into Azure in PowerShell, I used my org's credential. Seems Azure PowerShell will look for application principle in my org's AD only, not in my testing AD - there might have a way to switch AD, but I do not know yet.
Here are how I solved the problem:

*

*Went to https://manage.windowsazure.com and tried to sign in using a user in my testing AD.

*Azure prompted that the user was not associated with any subscription. Follow the "Sign up" link to sign up with a free trial subscription.

*Wait a couple minutes for the tenant to be provisioned

*In PowerShell, sign into azure using the user in my testing Azure AD, and run the PowerShell again. Now it succeeded.

Here are the PowerShell cmdlets that I ran:
connect-msolservice
$cer = New-Object System.Security.Cryptography.X509Certificates.X509Certificate
$cer.Import("D:\Fast1\dev\TodoListDaemonWithCert.cer")
$binCert = $cer.GetRawCertData()
$credValue = [System.Convert]::ToBase64String($binCert)
New-MsolServicePrincipalCredential -AppPrincipalId  "e5dedde0-2221-4ce4-a74d-af4e96705c01" -Type asymmetric -Value $credValue -StartDate $cer.GetEffectiveDateString() -EndDate $cer.GetExpirationDateString() -Usage verify


text:
Q: Adding document in Couchbase and missing JSON body I am trying to use Couchbase REST API to add a document to the existing documents. I am just testing this in Postman while writing on the code.
POST:

http://<ip>:8091/pools/default/buckets/<bucketname>/docs/testdoc1?rev=1

Headers:

Accept: application/json
Authorization : xxxxx

Body:

Raw JSON (application/json)
{
  "Name": "xxx",
  "Address": "yyy",
  "Phone number": "xxxx",
  "Badge": "yyy",
  "BadgeType": "xxx"
}

When I send above in Postman, It is adding this new doc. under couchbase documents/bucket, but on the body field it shows like, "Binary Document, base64 not available"
I tried even from my html code, but json body didn't receive at couchbase end.
<!DOCTYPE html>

<input type="submit" value="Start" onclick="submit()">

Click on the submit button.

Can someone guide me why is that JSON not going to couchbase in a correct way?

A: First off: as far as I know, this endpoint is not supported and it is not documented. If you see somewhere that it is supported, let me know, because I think that needs corrected. You should use one of the SDKs (Java, .NET, Node, etc) instead.
That being said, I was able to get it working via Postman. You can't just send raw JSON as the document. You need to POST encoded form data. One of the values this endpoint expects is "value", which contains the encoded JSON document.
Here's an example of what I did (I called my bucket "so"):
POST /pools/default/buckets/so/docs/testdoc2 HTTP/1.1
Host: localhost
cache-control: no-cache
Postman-Token: ba87ef4e-4bba-42b4-84da-ae775b26dbcb
value=%7B%0A%09%22Name%22%3A+%22xxx%22%2C%0A%09%22Address%22%3A+%22yyy%22%2C%0A%09%22Phone+number%22%3A+%22xxxx%22%2C%0A%09%22Badge%22%3A+%22yyy%22%2C%0A%09%22BadgeType%22%3A+%22xxx%22%0A%7D%0A

Note that value above is just the URL-encoded JSON from your question (Postman encoded it for me, and Postman must have added the cache-control header on its own too, because I did not specify that):


text:
Q: Django Set custom field in form not required ModelAdmin
class InstrumentAdmin(admin.ModelAdmin):
    def get_form(self,request, obj=None, **kwargs):
        if obj:
            return UpdateForm
        else:
            return CreateForm

Update Form
class UpdateForm(forms.ModelForm):
    connector = forms.ModelChoiceField(queryset=Connector.objects.all(), widget=forms.Select(attrs={'disabled':'disabled'}), initial='multiplate')

    class Meta:
        model = Instrument
        fields = ['connector','name']

I have set initial value for the ChoiceField. But when i access the change of the model and Save, it prompt me "This field is required" for the field connector.
How can I make the field not mandatory in this case? Because it will always have a value there.

A: Fixes:

*

*initial=pk instead of name

*Add required=False

A: The problem is with your attributes.
Change:
attrs={'disabled':'disabled'}

to
attrs={'readonly':'readonly'}

Disabled does not send back data to the server while readonly does it.


text:
Q: Locating sublists of one list in another list in Python I have two lists G3, G333. I want to locate the sublists of G333 in G3 and print the indices i. For example, [0, 4, 5, 9] occurs at i=0 in G3, [10, 14, 15, 19] occurs at i=5 in G3. But I am getting an error. I present the expected output.
G3=[[0, 4, 5, 9], [1, 5, 6, 10], [2, 6, 7, 11], [3, 7, 8, 12], [9, 13, 14, 18], [10, 14, 15, 19]]

G333=[[0, 4, 5, 9], [1, 5, 6, 10], [10, 14, 15, 19]]

G3s = set(map(tuple, G3))
G333s = set(map(tuple, G333))

for i in range(0,len(G3s)):
    if (G3s[i] & G333s[i]):
        print(i)

The error is
in <module>
    if (G3s[i] & G333s[i]):

TypeError: 'set' object is not subscriptable

The expected output is
i=[0,1,5]

A: You can directly use list.index to get the index.
for l in G333:
    print(G3.index(l))

Or, with a list comprehension:
i = [G3.index(l) for l in G333] # [0, 1, 5]

A: Here's another way to do it:
G3 = [
    [0, 4, 5, 9],
    [1, 5, 6, 10],
    [2, 6, 7, 11],
    [3, 7, 8, 12],
    [9, 13, 14, 18],
    [10, 14, 15, 19],
]

G333 = [[0, 4, 5, 9], [1, 5, 6, 10], [10, 14, 15, 19]]

for idx, sublist in enumerate(G3):
    if sublist in G333:
        print(idx)

The above solution uses enumerate to iterate through G3 members, while also retrieving each element from G3 to compare with the sub-lists from
G333.
If you want to use the same approach as your current solution, you could
use something like:
G3 = [
    [0, 4, 5, 9],
    [1, 5, 6, 10],
    [2, 6, 7, 11],
    [3, 7, 8, 12],
    [9, 13, 14, 18],
    [10, 14, 15, 19],
]

G333 = [[0, 4, 5, 9], [1, 5, 6, 10], [10, 14, 15, 19]]

G3s = set(map(tuple, G3))
G333s = set(map(tuple, G333))

for element in G333s & G3s:
    print(G3.index(list(element)))

However, I personally find the first option to be easier to understand and use.

Side-note: when using for...loops, avoid using i as name for the elements of your iterator. Rather, try names that better explain what each element represents. For iterating through indexes, for example, I prefer using the name idx (it's a common shorthand for index).

A: You can use index function and if any item is missing that can be handled like below:
G3=[[0, 4, 5, 9], [1, 5, 6, 10], [2, 6, 7, 11], [3, 7, 8, 12], [9, 13, 14, 18], [10, 14, 15, 19]]

G333=[[0, 4, 5, 9], [1, 5, 6, 10], [10, 14, 15, 19]]

i = []

for item in G333:
    try:
        i.append(G3.index(item))
    except ValueError:
        pass

print(i)


text:
Q: Работа Box2D в Xcode Я делаю игру с использованием LevelHelper (SpriteKit + Box2D) и столкнулся с проблемой.
Box2D зависит от количества FPS. Т.е. если в игре 60FPS, то тело двигается со скоростью 10 метров в секунду, если 30FPS, то со скоростью 5 метров в секунду.. надо что бы независимо от количества FPS была постоянная скорость.
Есть какое то решение что бы отвязать Box2D от количества FPS?

A: Можно сделать зависимость скорости от FPS, и при проседании FPS увеличивать скорость на множитель


text:
Q: Need assistance with SQL in Excel, specifically the "?" Parameter I've set up this SQL query in excel:
SELECT * FROM acct.view_op_seremain

WHERE SEC_ID = (?)

I've directed the "?" parameter to cell A1 in Excel. Now, I want this A1 parameter cell to contain multiple values but I am unsure if it requires special formatting? So far I have tried to do the following in Cell A1:
Justin, John, James

('Justin','John','James')

'Justin','John','James'

None of those formats are giving me results. Do you know what I am doing wrong?

A: You're close. It's just that = compares only a single value, and you're trying to give it multiple ones. Try an IN statement:
WHERE SEC_ID IN (?)

And then this input string should work:
'Justin','John','James'

A: You can't pass multiple parameters in that way.
Depending on what database you're using, you may be able to pass a single string parameter to the databaase engine, and have the database engine split the string for you.
For example, this answer has a solution for SQL Server.


text:
Q: Deploy an Azrue VM from an ARM template via Powershell Runbook without downloading template This article shows a tutorial how to deploy some resources from ARM templates in a powershell runbook. And as I understand, it will download the template and the parameters files in the specific path. But how can that work in an automated Runbook without having any directly attached storage to the automation account. Obviously, I'm misunderstanding something...
I mean the Get-AzureStorageFileContent command:
# Create a new context
$Context = New-AzureStorageContext -StorageAccountName $StorageAccountName -
StorageAccountKey $StorageAccountKey

Get-AzureStorageFileContent -ShareName 'resource-templates' -Context
$Context -path 'TemplateTest.json' -Destination 'C:\Temp'

$TemplateFile = Join-Path -Path 'C:\Temp' -ChildPath $StorageFileName

# Deploy the storage account
New-AzureRmResourceGroupDeployment -ResourceGroupName $ResourceGroupName -
TemplateFile $TemplateFile -TemplateParameterObject $Parameters

Do you know how to understand this, or are there some better methods to reach the goal?

A: You can use -TemplateParameterUri and -TemplateUri and give publicly available urls that where the tempaltes are stored.


text:
Q: Rebase onto upstream changes with non-trivial merge commits present locally As a developer on php-src I recently find myself in the following situation:
A   B   C
o---o---o         version1
         \
o---o-----o---o   master
x   y     D   E

o---o---o         upstream/master
x   y   z

So when I do git push --dry-run upstream master version1 I get the typical:
! [rejected]        master -> master (fetch first)

My natural response is to rebase the affected branch and preserve merge commits:
git fetch upstream
git rebase -p upstream/master

It's important to note that the original merge commit wasn't trivial, because there are so many changes between the version branch and the master; it takes an effort to resolve such a merge.
Doing the above rebase operation causes a merge conflict and I have to resolve it again; this is almost exactly the same job that I had already done.
Is there a better way to do this? Or did I forget an obvious rebase option?

A: Ideally you would "reuse the recorded resolution" with rerere:

In a workflow employing relatively long lived topic branches, the developer sometimes needs to resolve the same conflicts over and over again until the topic branches are done either merged to the "release" branch, or sent out and accepted upstream).
This command assists the developer in this process by recording conflicted automerge results and corresponding hand resolve results on the initial manual merge, and applying previously recorded hand resolutions to their corresponding automerge results.

Unfortunately, this feature must be enabled before you first do the merge:

Note: You need to set the configuration variable rerere.enabled in order to enable this command.

As far as I know, there is no shortcut to do something like this after the fact. I recommend enabling rerere globally and then redoing the merge:
git config --global rerere.enabled true

In the future, this setting could save you lots of time!


text:
Q: Wordpress meta_query taxonomy don't work On my blogI tried sucessfully to make a research for articles titles and content, but after I tried to make a research for custom taxonomy of articles 'categories' with meta_query() and REGEXP, didn't work.
My form :

  <form action="" method="GET">
    <input type="hidden" name="page_id" value="249" />
    <input type="text" name="search_input" />
    <select name="type">
        <option value="title">titre et texte</option>
        <option value="category">catégorie</option>
    </select>
    <select name="orderby">
        <option value="DESC">plus récent</option>
        <option value="ASC">plus ancien</option>
    </select>
    <button type="submit">OK</button>
  </form>

My arguments :
<?php

$orderby = 'DESC';

if($_GET['orderby']) {

    $orderby = $_GET['orderby'];
}

$args = array(
    'post_type' => 'article',
    'posts_per_page' => 3,
    'paged' => get_query_var('paged') ? get_query_var('paged') : 1,
    'orderby' => array('date' => $orderby)
);

if($_GET['type'] == 'title') {

    $args['s'] = $_GET['search_input'];
}
elseif($_GET['type'] == 'category') {

    $value = '^[a-zA-Z|\s]*(' . strtoupper( $_GET['search_input']) . '|' . strtolower( $_GET['search_input']) . ')[a-zA-Z|\s]*$';

    $args['meta_query'] = array(array('key' => 'categories', 'value' => $value, 'compare' => 'REGEXP'));

}

$query = new WP_Query($args);?>

I learned it from the Codex
and I can't found the differences between my code and the doc.

A: Use tax query for category.
$args['tax_query'] = array(array('taxonomy' => 'categories', 'field' => 'slug', 'terms' => $value));

as per your html

  <form action="" method="GET">
    <input type="hidden" name="page_id" value="249" />
    <input type="text" name="search_input" />
    <select name="type">
        <option value="">titre et texte</option>
        <option value="category-1">Category 1</option>
        <option value="category-2">Category 2</option>
        <option value="category-3">Category 3</option>
    </select>
    <select name="orderby">
        <option value="DESC">plus récent</option>
        <option value="ASC">plus ancien</option>
    </select>
    <button type="submit">OK</button>
  </form>

<?php

$orderby = 'DESC';

if($_GET['orderby']) {

    $orderby = $_GET['orderby'];
}

$args = array(
    'post_type' => 'article',
    'posts_per_page' => 3,
    'paged' => get_query_var('paged') ? get_query_var('paged') : 1,
    'orderby' => array('date' => $orderby)
);

if($_GET['type'] == 'title') {

    $args['s'] = $_GET['search_input'];
}
elseif($_GET['type'] == 'category') {

    $value = '^[a-zA-Z|\s]*(' . strtoupper( $_GET['search_input']) . '|' . strtolower( $_GET['search_input']) . ')[a-zA-Z|\s]*$';

    $args['tax_query'] = array(array('taxonomy' => 'categories', 'field' => 'slug', 'terms' => $value));

}

$query = new WP_Query($args);?>

A: It's working this way :
Form :

    <form action="" method="GET">
        <input type="hidden" name="page_id" value="249" />
        <input type="text" name="search_input" />
        <select name="categories">

            <?php $allterms = get_terms('categories');

            foreach($allterms as $term) : ?>

                <option value="<?php echo $term->slug; ?>"><?php echo $term->name; ?></option>

            <?php endforeach ?>
        </select>
        <select name="orderby">
            <option value="DESC">plus récent</option>
            <option value="ASC">plus ancien</option>
        </select>
        <button type="submit">OK</button>
    </form>

The arguments :
<?php

$orderby = 'DESC';

if($_GET['orderby']) {

    $orderby = $_GET['orderby'];
}

$args = array(
    'post_type' => 'article',
    'posts_per_page' => 3,
    'paged' => get_query_var('paged') ? get_query_var('paged') : 1,
    'orderby' => array('date' => $orderby)
);

if($_GET['search_input'] != '') {

    $args['s'] = $_GET['search_input'];
}
elseif($_GET['categories']) {

    $args['categories'] = $_GET['categories'];
}

$query = new WP_Query($args);?>


text:
Q: PHP Parsing error - unexpected '[' - PHP 5.3.29 I am facing the following error in PHP 5.3.29 environment

Parse error: syntax error, unexpected '[' in
  /home/deltaweb/www/schooler/templates/yoo_master2/schooler.php on line
  1721

The code is snippet is
function getUserClassPermissions()
{
  $classStr = ['I','II','III','IV','V','VI','VII','VIII','IX','X'];
  $classes = array();
  $user = JFactory::getUser();
  $groups = implode(',',$user->getAuthorisedGroups());
  $results = getTableData("#__usergroups", "title", "id IN ($groups)");
  foreach ($results as $row) {
    if (preg_match("/Teacher Class (\S+)/",$row[0], $matches)) {
      $classes[] = array_search($matches[1], $classStr) + 1;
    }
  }
  if (count($classes)==0) return 0;
  return implode(',',$classes);
}

The statement in line number 1721 is
$classStr = ['I','II','III','IV','V','VI','VII','VIII','IX','X'];

A: Short array syntax, [] is only available in PHP5.4+. You need to update your code to use the standard array() syntax.
OR
Update your version of PHP to one that isn't EOL.


text:
Q: Create relationships when scaffolding Hi I am new to Ruby on Rails. I am trying to create a small blog site. I have two tables Posts and Comments. Each Post will have many comments. I generate the tables using these commands.
rails g scaffold Post title:string body:text author:string
rails g scaffold Comment body:string author:string

Now I want to add the relationship to the model classes. I add has_many :comments to the Post class and belongs_to :post to the Comment class. However when I try to call post.comments I get a runtime error saying SQLException: no such column: comments.post_id. Should I create a migration and add post_id under Comment or is there a way to achieve this when scaffolding?

A: You are definitely on the right track. If you add the post_id column when generating the Comment scaffold your relationship will then work (although you still need to add the has_many :comments and belongs_to :post)
So the updated generator call would look like this:
rails g scaffold Comment body:string author:string post_id:integer

A: You can also use belongs_to like this:
rails g scaffold Comment body:string author:string post:belongs_to

A: Scaffold actually provides a way to generate relationships, you should use the :references data type
rails g scaffold Comment body:string author:string post:references

This will generate a migration for the comments table with a post_id field and index for it. The generator will also add belongs_to :post to the Comment model.
It will not however generate the reverse side of the relationship so you'll need to add
has_many :comments

to the Post model yourself. You will also need to add nested resource routing if this is something you need as the generator can not handle this.


text:
Q: raspbian Node.js executable looking for wrong path based on this post here I tried to create an executable in folder /etc/init.d/ with the name raumserver with the following content:
#! /bin/sh
# /etc/init.d/raumserver

### BEGIN INIT INFO
# Provides:          raumserver
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Example initscript
# Description:       This file should be used to construct scripts to be
#                    placed in /etc/init.d.
### END INIT INFO

# Carry out specific functions when asked to by the system
case "$1" in
   start)
    echo "Starting raumserver.js"
    # run application you want to start
    node /home/openhabian/node_modules/node-raumserver/raumserver.js > /home/openhabian/node_modules/node-raumserver/logs/RPiraumserver.js
    #/home/pi/downloads/node-v0.10.24-linux-arm-pi/bin/node /home/pi/test.js >> /home/pi/test.log
   ;;
   stop)
    echo "Stopping raumserver.js"
    # kill application you want to stop
    killall -9 node
    # Not a great approach for running
    # multiple node instances
    ;;
  *)
    echo "Usage: /etc/init.d/raumserver {start|stop}"
    exit 1
    ;;
esac

exit 0

You see that my nodeJS application resides in /home/openhabian/node_modules/node-raumserver/ and is named raumserver.js
When I run this executable via /etc/init.d/raumserver start I get the errormessage that WARNING: No configurations found in configuration directory:/etc/init.d/config which leads to an error because within this configuration it's stated to use another port instead of 8080 which is already in use. Thus the executable itself doesn't run.
This is based on the fact that this executable is looking for the folder config in the current path the executable resides in /etc/init.d/config which doesn't exist there. As the path to the nodeJS application is /home/openhabian/node_modules/node-raumserver/ I would expect it to look for the folder there which would be available there.
Why does this happen and how can I change that?
My plan is to get this executable running on startup via daemon. My plan there is to go for chmod +x /etc/init.d/raumserver and then sudo update-rc.d raumserver defaults which I read online and should work.
Any idea of how to tell the application to look in referenced nodeJS-application folder? I shortly thought about copying the config folder to /etc/init.d/ but I guess this would be very unclever for future updates etc etc.
Thanks in advance

A: It seems that some of your code is using . as the path base rather than using __dirname which is the dirname of the module.
If you want to address files relative to the module, you need to use:
absolute_path = path.join(__dirname, relative_path)

Rather than letting . resolve to process.cwd()
When setting up services it helps to print process.cwd() also process.env specifically process.env.PATH. If those don't output the right values, you can fix them in the service setup or in your program,

A: As the nodeJS app is not mine and I'm not capable of changing it I guess this will be no option. :-(
But another question:
Would it be possible to have the current executable run (on startup) another executable which lies in the relativ path which will then run smoothly?
What I tried is to change the content of the executable raumserver to the following:
### BEGIN INIT INFO
# Provides:          raumserver
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Example initscript
# Description:       This file should be used to construct scripts to be
#                    placed in /etc/init.d.
### END INIT INFO

# Carry out specific functions when asked to by the system
case "$1" in
   start)
    echo "Starting raumserver.js"
    # run application you want to start
    #node /home/openhabian/node_modules/node-raumserver/raumserver.js > /home/openhabian/node_modules/node-raumserver/logs/RPiraumserver.js
    /home/openhabian/node_modules/node-raumserver/raumstartup >> /home/openhabian/node_modules/node-raumserver/logs/raumstartup.log
   ;;
   stop)
    echo "Stopping raumserver.js"
    # kill application you want to stop
    killall -9 node
    # Not a great approach for running
    # multiple node instances
    ;;
  *)
    echo "Usage: /etc/init.d/raumserver {start|stop}"
    exit 1
    ;;
esac

exit 0

and the raumstartup looks like this:
### BEGIN INIT INFO
# Provides:          raumserver
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: Example initscript
# Description:       This file should be used to construct scripts to be
#                    placed in /etc/init.d.
### END INIT INFO

# Carry out specific functions when asked to by the system
case "$1" in
   start)
    echo "Starting raumserver.js"
    # run application you want to start
    node /home/openhabian/node_modules/node-raumserver/raumserver.js > /home/openhabian/node_modules/node-raumserver/logs/RPiraumserver.js
    #/home/openhabian/node_modules/node-raumserver/raumstartup >> /home/openhabian/node_modules/node-raumserver/logs/raumstartup.log
   ;;
   stop)
    echo "Stopping raumserver.js"
    # kill application you want to stop
    killall -9 node
    # Not a great approach for running
    # multiple node instances
    ;;
  *)
    echo "Usage: /etc/init.d/raumserver {start|stop}"
    exit 1
    ;;
esac

exit 0

But somehow this approach doesn't work. :-( I know it's not best practice but as of now this still seems like a legit way...
Any thoughts on my approach or - even better - a reason why it doesn't work?
I can manually start the first file via sudo /etc/init.d/raumserver start but it doesn't start the raumstartup :-(


text:
Q: Is there a functional cooldown for TPS Let me start by saying I have a very limited knowledge of python and pygame. After working through a few tutorials I decided to try making a Top-Down Shooter game using pygame, based on  a few online tutorials I found. The program works so far, but I am struggling with a reload function that will initiate a cooldown on the player's gun for a few seconds while out of ammo.  I have searched for several hours for anything relating to a cooldown that I could use, and I haven't been able to make anything work. Thanks in advance for any help or advice, anything to point me in the right direction.
Here is the link to the tutorial the game is based on:
http://www.raywenderlich.com/24252/beginning-game-programming-for-teens-with-python
and here is the code I am struggling with:
if event.type==pygame.MOUSEBUTTONDOWN:
                shoot.play()
                position=pygame.mouse.get_pos()
                acc[1]+=1
                arrows.append([math.atan2(position[1]-(playerpos1[1]+32), position[0]-(playerpos1[0]+26)),playerpos1[0]+32,playerpos[1]+32])

This fires the projectile, but I want to add an ammo count and a function to cooldown once ammo is 0
Some things I've tried have been using pygame's timer function, and also the utils mod, but I couldn't get either to work for my scenario.
Here's an example of what i've tried:
def fire():
    global ammo # ammo = 10
    if ammo == 0:
        cooldown #  cooldown would be the timer, which i can't figure out
        ammo == 10
    else:
        arrows.append([math.atan2(position[1]-(playerpos1[1]+32), position[0]-(playerpos1[0]+26)),playerpos1[0]+32,playerpos[1]+32])
        ammo-=1

if event.type==pygame.MOUSEBUTTONDOWN:
    shoot.play()
    position=pygame.mouse.get_pos()
    acc[1]+=1
    fire()

Thanks for any help and suggestions, sorry if my post is poorly formatted.

A: There's a little bit of syntax error in your fire() function. Firstly, cooldown (which I assume is a function) must be called with empty parentheses: cooldown(). Secondly, you aren't resetting ammo to 10. Instead, you ask whether ammo is already equal to 10. Here's the fixes:
def fire():
    global ammo
    if ammo == 0:
        cooldown() # call cooldown function with
        ammo = 10 # reset ammo

Hope this helped, comment if I left something out and I'll edit :)
EDIT: You asked for a cooldown() example, so here you go.
One way to do this without stopping your whole game would be to create a counter variable to run parallel with your game loop. For example:
COUNTER = 0
can_fire = True
while True:
    COUNTER += 1

    def fire():
        global ammo
        if not can_fire:
            if COUNTER == cooldown_count + 50: # Or however many loops
                can_fire = True
                ammo = 10
        else:
            pass
        if ammo == 0 and can_fire:
            cooldown_count = COUNTER
            can_fire = False


text:
Q: Why is there no increment to change the case in my switch statement? What I intend to achieve with this code is that on click of the "Click Me!" button it should increment num +1 so it would change then the case. Eg. from case 0 to case 1 in the switch statement. But all I get back is undefined. I tried to have the switch statement and the num++ function on their own but didn't work as well. Any help is appreciated towards the solution.

var btn=document.querySelector("button")
    var text="test"
    var num

function changeCase () {
  btn.addEventListener(onclick, function (){num++})
  switch (num) {
  case 0:
    text = "Off";
    break;
  case 1:
    text = "On";
    break;
  default:
    text = "No value found";
  }
}

    document.getElementById("demo").innerHTML = text;

Hello!

      <button onclick="changeCase()">Click Me!</button>

A: A couple of things:

*

*You're not doing anything with text after changing it in changeCase. You've only used it once, on page load.

*You're using both an onclick attribute and then also, when that's clicked, you're trying to add an event listener for click.

*You're using onclick as an identifier in the addEventListener call, but you wanted "click" as a string (and no "on").

*You probably want to set an initial value for num, instead of leting it default to the value undefined. If you do num++ when num has undefined in it, you'll get NaN, which doesn't match any of your cases.
To fix it:

*

*Don't use onclick attributes, use addEventListener.

*Use text after changing it.

*Add the value for num.
Here's an example:

var btn=document.querySelector("button");
var text="test";
var num = 0;

btn.addEventListener("click", function (){
    num++;
    changeCase();
});

function changeCase () {
    switch (num) {
        case 0:
            text = "Off";
            break;
        case 1:
            text = "On";
            break;
        default:
            text = "No value found";
            break;
    }
    document.getElementById("demo").innerHTML = text;
}

changeCase();

Hello!

      <button>Click Me!</button>


text:
Q: Post files in list of ASP.NET MVC objects I have an ASP.NET MVC 5 site using Entity Framework where each item submitted in form has several fields, where one of which is supposed to be an uploaded Excel spreadsheet that is to be saved in the database. Here is what the data model looks like.
public partial class CostBreakdown
{
    [Key]
    [Column(Order = 0)]
    [StringLength(10)]
    public string CUSTOMER_ID { get; set; }

    [Key]
    [Column(Order = 1)]
    [StringLength(6)]
    public DateTime BILLING_DATE { get; set; }

    public decimal TOTAL_COSTS { get; set; }

    public byte[] DOCUMENT { get; set; }  //The Excel document
}

Since files in ASP.NET MVC actions are posted as an HttpPostedFileBase object, I made a view model to try to bind everything to the view.
public class CostsVM
{
    public int TransactionFlag { get; set; }    //Used for update tracking

    public CostBreakdown Cost { get; set; }

    public HttpPostedFileBase UploadedFile { get; set; }
}

Since users would need several files at once, it is a List that is bound to the view. I did this in the loop of the view file to try to bind the files to several HTML file controls. This was based on an example that I found on another page (that I'm unfortunately having trouble going back and finding).
@for (int i = 0; i < Model.Count(); i++)
{
    @* All my other fields are bound here *@
    @Html.TextBoxFor(m => Model[i].UploadedFile, new { type = "file", accept = ".xlsx", @class = "fileBox", id = "[" + i + "].UploadedFile" })
}

Ultimately, the file would be converted to a byte[] by the controller. However, the the values that I get back for the UploadedFile variables are always null. Is there a way that I could allow multiple rows of data to be bound, each with a file control and each allowing the user to upload a file that would be saved to the database for that record?

A: So, this was my own doing. I had everything right with the method that I was trying, however I was attempting to do this in a call to Ajax.BeginForm, which doesn't accept files. Once I changed this to Html.BeginForm, it worked.


text:
Q: multipart/form with backbone and spring boot addVendorLicense:function(){
                    var self=this;
                    if(app.vendorId){

                     $('#licenseForm').ajaxSubmit({
                        url: "vendorLicense/create/"+app.vendorId,
                        async:false,
                        success: function (res) {
                            alert(res.message);
                           self.addLicenseRow();
                        },
                        error:function(res){
                            alert(res.message);
                        }
                    });
                    }
                    else{
                        alert("Please Add a vendor First");
                    }
                    return false;
             },**

***Spring Controller***

@RequestMapping(value = "/create/{vendorId}", method = RequestMethod.POST)
    public ResponseEntity<VendorLicenseResponse> createLicense(LicenseRequest licenserequest,@PathVariable("vendorId") String vendorId) {}

***Request Object***

public class LicenseRequest extends BaseRepresentation {

@JsonIgnore

    private String licenseType;

    private String licenseName;

private String licenseNumber;

    @JsonIgnore
    private String expirationDate;

    @JsonIgnore
    private List<String> statesCovered;

    private String terms;

    private String brokerNumber;

    private String organizationId;

    @JsonIgnore
    private CommonsMultipartFile insuranceFiles;

}

I am trying to map a multipart form data to LicenseRequest object.When the form is submitted with File then the rquest is parsed properly but when form is submitted without file then server gives 400 bad request error.Can some one tell me How to make the file optional in multipart/form-data.

A: Instead of putting it in  the request object you can grab it directly and make it optional, I'm not sure if you can specify the optional part in a custom object.
@RequestMapping(value = "/create/{vendorId}", method = RequestMethod.POST)
public ResponseEntity<VendorLicenseResponse> createLicense(LicenseRequest licenserequest,@PathVariable("vendorId") String vendorId,
@RequestParam(value = "insuranceFiles", required = false) CommonsMultipartFile insuranceFiles) {
   if(insuranceFiles != null){}
}


text:
Q: Integrability of the mean sum (or sample mean) Suppose that $X \in \mathcal{X}$ and $X\sim P$, is integrable, i.e., $\int |X| \mathrm{d}P<\infty$. Let $(X_1,\ldots,X_n)$ be a vector of $n$ i.i.d. instances of $X$. Hence, $X^n\sim P^{\otimes n}$. Consider $\{\mathcal{S}_n\}_{n\in \mathbb{N}}$, $\mathcal{S}_n \subseteq \mathcal{X}^n$, be a sequence of sets, such that
\begin{align}
\lim \limits_{n \rightarrow \infty}\int_{\mathcal{S}_n} \mathrm{d}P^{\otimes n}=0.
\end{align}
Then, is the following argument true?
\begin{align}
\lim \limits_{n \rightarrow \infty} \int_{\mathcal{S}_n} \frac{1}{n}\sum \limits_{i=1}^n |X_i| \mathrm{d}P^{\otimes n}=0.
\end{align}
Thanks.


text:
Q: Netty Server throws invalid version format error One of my play framework 2.4 applications in production on the EC2 console started throwing the below error though no changes were made to the server in the last 3 weeks. As you can see the error was not thrown from the app itself, but from the HttpVersion class of the Netty server. Any help in isolating the cause would be very helpful.
Exception caught in Netty
java.lang.IllegalArgumentException: invalid version format: (WINDOWS NT 6.1; RV:31.0) GECKO/20100101 FIREFOX/31.0
    at org.jboss.netty.handler.codec.http.HttpVersion.<init>(HttpVersion.java:94) ~[io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.handler.codec.http.HttpVersion.valueOf(HttpVersion.java:62) ~[io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.handler.codec.http.HttpRequestDecoder.createMessage(HttpRequestDecoder.java:75) ~[io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.handler.codec.http.HttpMessageDecoder.decode(HttpMessageDecoder.java:191) ~[io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.handler.codec.http.HttpMessageDecoder.decode(HttpMessageDecoder.java:102) ~[io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.handler.codec.replay.ReplayingDecoder.callDecode(ReplayingDecoder.java:500) ~[io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.handler.codec.replay.ReplayingDecoder.cleanup(ReplayingDecoder.java:554) ~[io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.handler.codec.frame.FrameDecoder.channelDisconnected(FrameDecoder.java:365) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:102) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:559) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.Channels.fireChannelDisconnected(Channels.java:396) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.socket.nio.AbstractNioWorker.close(AbstractNioWorker.java:360) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.socket.nio.NioServerSocketPipelineSink.handleAcceptedSocket(NioServerSocketPipelineSink.java:81) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.socket.nio.NioServerSocketPipelineSink.eventSunk(NioServerSocketPipelineSink.java:36) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendDownstream(DefaultChannelPipeline.java:779) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.handler.codec.oneone.OneToOneEncoder.handleDownstream(OneToOneEncoder.java:54) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline.sendDownstream(DefaultChannelPipeline.java:591) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendDownstream(DefaultChannelPipeline.java:784) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.SimpleChannelHandler.closeRequested(SimpleChannelHandler.java:334) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.SimpleChannelHandler.handleDownstream(SimpleChannelHandler.java:260) [io.netty.netty-3.10.4.Final.jar:na]
    at com.typesafe.netty.http.pipelining.HttpPipeliningHandler.handleDownstream(HttpPipeliningHandler.java:106) [com.typesafe.netty.netty-http-pipelining-1.1.4.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline.sendDownstream(DefaultChannelPipeline.java:591) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline.sendDownstream(DefaultChannelPipeline.java:582) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.Channels.close(Channels.java:812) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.AbstractChannel.close(AbstractChannel.java:206) [io.netty.netty-3.10.4.Final.jar:na]
    at play.core.server.netty.PlayDefaultUpstreamHandler.exceptionCaught(PlayDefaultUpstreamHandler.scala:66) [com.typesafe.play.play-netty-server_2.11-2.4.6.jar:2.4.6]
    at org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:112) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.SimpleChannelHandler.exceptionCaught(SimpleChannelHandler.java:156) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.SimpleChannelHandler.handleUpstream(SimpleChannelHandler.java:130) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.SimpleChannelUpstreamHandler.exceptionCaught(SimpleChannelUpstreamHandler.java:153) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:112) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline$DefaultChannelHandlerContext.sendUpstream(DefaultChannelPipeline.java:791) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.handler.codec.frame.FrameDecoder.exceptionCaught(FrameDecoder.java:377) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.SimpleChannelUpstreamHandler.handleUpstream(SimpleChannelUpstreamHandler.java:112) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:564) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:559) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.Channels.fireExceptionCaught(Channels.java:525) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.AbstractChannelSink.exceptionCaught(AbstractChannelSink.java:48) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline.notifyHandlerException(DefaultChannelPipeline.java:658) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:566) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.DefaultChannelPipeline.sendUpstream(DefaultChannelPipeline.java:559) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:268) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.Channels.fireMessageReceived(Channels.java:255) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.socket.nio.NioWorker.read(NioWorker.java:88) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.socket.nio.AbstractNioWorker.process(AbstractNioWorker.java:108) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.socket.nio.AbstractNioSelector.run(AbstractNioSelector.java:337) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.socket.nio.AbstractNioWorker.run(AbstractNioWorker.java:89) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.channel.socket.nio.NioWorker.run(NioWorker.java:178) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.util.ThreadRenamingRunnable.run(ThreadRenamingRunnable.java:108) [io.netty.netty-3.10.4.Final.jar:na]
    at org.jboss.netty.util.internal.DeadLockProofWorker$1.run(DeadLockProofWorker.java:42) [io.netty.netty-3.10.4.Final.jar:na]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_45]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_45]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_45]


text:
Q: How to Send Password Forget mail to User upon activation of Account in Rails In our Application Users are created by Admin with a Random Password . So we send Activation Mail to User (http://localhost:3000/users/confirmation?confirmation_token=1xxxxxxxxxxxxxx")
We Use devise_for :users
def confirmation_required?
    true
end

So now We want when User activate his Account then automatically they send a Password Forget mail to him on his mail ID