text:
Q: Android: Display current track Info in mediaplayer using webpage I am a learner and developing an Android App to play live stream. It is working properly except 1 issue. I want to show title of currently playing Track which is available on a webpge. For this purpose I have used a textView and tried to use Asynchronous Task and called a method containing a Runnable in that Asynchronous task with which I can update text of textView at an interval on 30 seconds.In runnable I called a method which loads a webpage and give its content as a string.
Problem: When it tries to update text of textView, app crashes. THANKS IN ADVANCE.
Following is my code:
import java.io.IOException;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import java.net.URLConnection;
import java.net.URL;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import android.util.Log;
import java.net.MalformedURLException;
import android.widget.TextView;
import android.os.AsyncTask;

public class MusicAndroidActivity extends Activity {

static MediaPlayer mPlayer;
    Button buttonPlay;
    Button buttonStop;
    Button buttonPause;
    public TextView txtMessage;
    private StringBuilder response;
    private String text="***";
    ProgressDialog progDailog;
    private final static int INTERVAL = 1000 * 30; //2 minutes
    Handler mHandler;
    int length=0;
    String url = "http://www.s8.voscast.com:9630/;stream.mp3";
    private final Handler handler = new Handler();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        buttonStop = (Button) findViewById(R.id.stop);
        txtMessage=(TextView)findViewById(R.id.txtMessage);
        buttonStop.setEnabled(false);
        buttonPause=(Button) findViewById(R.id.pause);
        buttonPause.setEnabled(false);
        buttonPlay = (Button) findViewById(R.id.play);

        buttonPlay.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                mPlayer = new MediaPlayer();
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    buttonPlay.setEnabled(false);
                    buttonStop.setEnabled(true);
                    buttonPause.setEnabled(true);
                    //txtMessage.setText("Loading...");
                    progDailog = ProgressDialog.show(MusicAndroidActivity.this, "", "Buffering ... \n It can take upto 1 Minute, depending upon your internet speed", true);
                    mPlayer.setDataSource(url);
                } catch (IllegalArgumentException e) {
                    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                } catch (SecurityException e) {
                    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                } catch (IllegalStateException e) {
                    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {

                    mPlayer.setOnPreparedListener(new OnPreparedListener() {

                        public void onPrepared(MediaPlayer mPlayer) {
                            // TODO Auto-generated method stub
                            mPlayer.start();
                            progDailog.dismiss();
                            LoadWebPageASYNC task = new LoadWebPageASYNC();
                            task.execute(new String[]{"http://khilare.com/swltest/sms.html"});

                        }
                    });
                    mPlayer.prepareAsync();
                } catch (IllegalStateException e) {
                    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                } //catch (IOException e) {
                //Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                //}

            }

        });

        buttonStop.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(mPlayer!=null && mPlayer.isPlaying()){
                    mPlayer.stop();
                    buttonPlay.setEnabled(true);
                    buttonStop.setEnabled(false);
                    buttonPause.setEnabled(false);
                }
            }
        });

        buttonPause.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(mPlayer!=null && mPlayer.isPlaying()){
                    mPlayer.pause();
                    length=mPlayer.getCurrentPosition();
                    buttonPause.setText("Resume");
                    //buttonPlay.setEnabled(true);
                    buttonStop.setEnabled(true);
                    buttonPlay.setEnabled(false);
                    //sapp();
                    //getHTML();
                    //txtMessage.setText(text);
                    txtMessage.setText(text);
                }
                else {
                //mPlayer.seekTo(length);
                    mPlayer.start();
                //  mPlayer.seekTo(length);
                    buttonPause.setText("Pause");

                }
            }
        });

    }

    protected void onDestroy() {
        super.onDestroy();
        // TODO Auto-generated method stub
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }

    private class LoadWebPageASYNC extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... urls) {
            getHTML();
            //sapp();
            txtMessage.setText(text);
            return null;
        }
    }
    private void sapp()
    {
        //Runnable updater1 = new Runnable() {
            handler.postDelayed(new Runnable() {
                //@Override
                public void run() {
                    getHTML();
                    txtMessage.setText(text);
                }
            }, INTERVAL);

            /*public void run() {
                getHTML();
                txtMessage.setText(text);
            }
        };*/
        //handler.post(updater1);
    }
    private void getHTML()
    {
        try {
            URLConnection connection = new URL("http://khilare.com/swltest/sms.html").openConnection();
            connection.setRequestProperty("Accept-Charset", "UTF-8");
            InputStream responseStream = connection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(responseStream));
            response = new StringBuilder();
            String line;
            line = br.readLine();
            {
                response.append(line);
            }
            text = response.toString();
            //txtMessage.setText(text);
            //Log.i("Output", text);
        } catch (MalformedURLException e) {
            txtMessage.setText(e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            txtMessage.setText(e.getMessage());
            e.printStackTrace();
        }
        //textStreamed.setText(text);
    }

}

Here is Logcat:
    java.lang.SecurityException: Permission denial: writing to settings requires android.permission.WRITE_SETTINGS
            at com.android.providers.settings.SettingsProvider.callFromPackage(SettingsProvider.java:645)
            at android.content.ContentProvider$Transport.call(ContentProvider.java:279)
            at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:273)
            at android.os.Binder.execTransact(Binder.java:388)
            at dalvik.system.NativeStart.run(Native Method)
05-29 10:56:45.772      302-302/? E/Parcel﹕ Reading a NULL string not supported here.
05-29 10:56:45.772      302-302/? E/Parcel﹕ Reading a NULL string not supported here.
05-29 10:56:48.462      302-302/? E/Parcel﹕ Reading a NULL string not supported here.
05-29 10:56:48.462      302-302/? E/Parcel﹕ Reading a NULL string not supported here.
05-29 10:56:50.702      302-302/? E/Parcel﹕ Reading a NULL string not supported here.
05-29 10:56:50.702      302-302/? E/Parcel﹕ Reading a NULL string not supported here.
05-29 10:56:50.712      302-302/? E/Parcel﹕ Reading a NULL string not supported here.
05-29 10:56:50.712      302-302/? E/Parcel﹕ Reading a NULL string not supported here.

05-29 10:57:01.772  28164-28569/com.prgguru.example E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
    java.lang.RuntimeException: An error occured while executing doInBackground()
            at android.os.AsyncTask$3.done(AsyncTask.java:299)
            at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
            at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
            at java.util.concurrent.FutureTask.run(FutureTask.java:239)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:841)
     Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
            at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:5969)
            at android.view.ViewRootImpl.invalidateChildInParent(ViewRootImpl.java:921)
            at android.view.ViewGroup.invalidateChild(ViewGroup.java:4276)
            at android.view.View.invalidate(View.java:10552)
            at android.view.View.invalidate(View.java:10507)
            at android.widget.TextView.checkForRelayout(TextView.java:6531)
            at android.widget.TextView.setText(TextView.java:3789)
            at android.widget.TextView.setText(TextView.java:3643)
            at android.widget.TextView.setText(TextView.java:3618)
            at com.prgguru.example.MusicAndroidActivity$LoadWebPageASYNC.doInBackground(MusicAndroidActivity.java:158)
            at com.prgguru.example.MusicAndroidActivity$LoadWebPageASYNC.doInBackground(MusicAndroidActivity.java:152)
            at android.os.AsyncTask$2.call(AsyncTask.java:287)
            at java.util.concurrent.FutureTask.run(FutureTask.java:234)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
            at java.lang.Thread.run(Thread.java:841)

A: I got it.
I have used a TimeTask, which calls a method UpdateGUI();  in every 10 Seconds. This method "UpdateGUI();" further calls a method "getHTML();" which load webpage's content to String text. Also this method calls myRunnable via myHandler at
myHandler.post(myRunnable);
and myRunnable set the text of textView txtMessage
To Understand the process completely, Please read this Article
The code is now:
import java.io.IOException;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Handler;
import java.net.URLConnection;
import java.net.URL;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import android.util.Log;
import java.net.MalformedURLException;
import android.widget.TextView;
import java.util.TimerTask;
import java.util.Timer;

public class MusicAndroidActivity extends Activity {

    static MediaPlayer mPlayer;
    Button buttonPlay;
    Button buttonStop;
    Button buttonPause;
    public TextView txtMessage;
    private StringBuilder response;
    private String text="***";
    ProgressDialog progDailog;
    final Handler myHandler = new Handler();
    int length=0;
    String url = "http://www.example.com:port/;stream.mp3";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        buttonStop = (Button) findViewById(R.id.stop);
        txtMessage=(TextView)findViewById(R.id.txtMessage);
        buttonStop.setEnabled(false);
        buttonPause=(Button) findViewById(R.id.pause);
        buttonPause.setEnabled(false);
        buttonPlay = (Button) findViewById(R.id.play);

        buttonPlay.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                mPlayer = new MediaPlayer();
                mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                try {
                    buttonPlay.setEnabled(false);
                    buttonStop.setEnabled(true);
                    buttonPause.setEnabled(true);
                    progDailog = ProgressDialog.show(MusicAndroidActivity.this, "", "Buffering ... \n It can take upto 1 Minute, depending upon your internet speed", true);
                    mPlayer.setDataSource(url);
                } catch (IllegalArgumentException e) {
                    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                } catch (SecurityException e) {
                    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                } catch (IllegalStateException e) {
                    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    mPlayer.setOnPreparedListener(new OnPreparedListener() {
                            public void onPrepared(MediaPlayer mPlayer) {
                            // TODO Auto-generated method stub
                            mPlayer.start();
                            progDailog.dismiss();
                        }
                    });
                    mPlayer.prepareAsync();
                    Timer myTimer = new Timer();        // Declared Timer
                    myTimer.schedule(new TimerTask() {  // Started Time Task, it will repeat as per given duration (Ours is 1000 or 10 Second)
                        @Override
                        public void run() {
                            UpdateGUI();  // Called Method UdateGUI
                        }                 //   v
                    }, 0, 10000);         // After Every 10 Seconds

                } catch (IllegalStateException e) {
                    Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show();
                }
            }
        });

        buttonStop.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if(mPlayer!=null && mPlayer.isPlaying()){
                    mPlayer.stop();
                    buttonPlay.setEnabled(true);
                    buttonStop.setEnabled(false);
                    buttonPause.setEnabled(false);
                }
            }
        });

        buttonPause.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if(mPlayer!=null && mPlayer.isPlaying()){
                    mPlayer.pause();
                    length=mPlayer.getCurrentPosition();
                    buttonPause.setText("Play");
                    buttonStop.setEnabled(true);
                    buttonPlay.setEnabled(false);
                }
                else {
                    mPlayer.start();
                    buttonPause.setText("Pause");
                }
            }
        });

    }

    protected void onDestroy() {
        super.onDestroy();
        // TODO Auto-generated method stub
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }

    private void UpdateGUI() {
        getHTML();
        myHandler.post(myRunnable);  // Posted MyRunnable  to myHandler
    }

    final Runnable myRunnable = new Runnable() {
        public void run() {
            txtMessage.setText(text);       //Set txtMessage's value to text (text is a string declared above)
        }
    };

    private void getHTML()
    {
        try {
            URLConnection connection = new URL("http://example.com/stats/index.php").openConnection();
            connection.setRequestProperty("Accept-Charset", "UTF-8");
            InputStream responseStream = connection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(responseStream));
            response = new StringBuilder();
            String line;
            line = br.readLine();
            {
                response.append(line);
            }
            text = response.toString();
        } catch (MalformedURLException e) {
            txtMessage.setText(e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            txtMessage.setText(e.getMessage());
            e.printStackTrace();
        }
    }
}


text:
Q: How to disable number input types using javascript and php I'm working on a small project that contains a php page that will ask the user to enter a number of questions for a test and after writing a number for example 10 he will then allocate number of question for each type of the exam (addition, subtraction, multiplication, division) until the number of questions finish for example after choosing 10 total questions he can then choose 5 in addition 3 in multiplication and 2 in division but he cant allocate anymore questions because the 10 total questions have finished. And he is allocating these numbers in a number input type in html so I want to get the first input type which is the total number of questions and then decrement that number every time he increase any of the exam types(addition, ..) and when it reaches 0 it will disable the input types here is what I did so far:

var numInput = document.getElementById('numInput');
var Input1 = document.getElementById('Input1');
var Input2 = document.getElementById('Input2');
var Input3 = document.getElementById('Input3');
var Input4 = document.getElementById('Input4');

Input1.disabled = true;
Input2.disabled = true;
Input3.disabled = true;
Input4.disabled = true;

var Checker = setInterval(function Checker() {
var numValue = numInput.value;
//thats what I tried to do to solve my problem but it didn't work properly because it must decrement only 1 but the condition will still be true so it will decrement for ever or at least that is what I think.
if (Input1.value > 0) {
 numValue = numValue - 1;
}
//and this part is working fine.
if (numValue > 0) {
 Input1.disabled = false;
 Input2.disabled = false;
 Input3.disabled = false;
 Input4.disabled = false;
} else if (numValue <= 0) {
 Input1.disabled = true;
 Input2.disabled = true;
 Input3.disabled = true;
 Input4.disabled = true;
}
}, 100);
<form method="GET" action="">

How many questions do you want to answer?

 <input id="numInput" type="number" name="Text" value="0" min="0">

Addition:
&nbsp<input id="Input1" type="number" name="Text" value="0" min="0">

Subtraction:
&nbsp<input id="Input2" type="number" name="Text" value="0" min="0">

Multiplication:
&nbsp<input id="Input3" type="number" name="Text" value="0" min="0">

Division:
&nbsp<input id="Input4" type="number" name="Text" value="0" min="0">
</form>

And I don't have any idea on how can I solve this so please help me.

A: Instead of decrementing numValue, you should compare it with sum of other inputs
function Checker() {
var sum=parseInt(Input1.value)+parseInt(Input2.value)+parseInt(Input3.value)+parseInt(Input4.value);
var numValue = numInput.value;
if (numValue > sum)
{
    Input1.disabled = false;
    Input2.disabled = false;
    Input3.disabled = false;
    Input4.disabled = false;
} else
{
    Input1.disabled = true;
    Input2.disabled = true;
    Input3.disabled = true;
    Input4.disabled = true;
    }
}

Also, better then setInterval, use onchange event
numInput.addEventListener("change", Checker);
Input1.addEventListener("change", Checker);
Input2.addEventListener("change", Checker);
Input3.addEventListener("change", Checker);
Input4.addEventListener("change", Checker);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django: Real-time logging to browser In PHP, I used to be able to use the echo command and see scripts in real time.
For example:
Applying settings to 001...
* a second later *
Applying settings to 002...

This would be shown to the user in the browser.
Is there anyways I can use a command like echo in Django?
It's nice to know my application is actually doing something and seeing the progress.

A:
It's nice to know my application is actually doing something and seeing the progress.

I'm assuming you want to inform an actual user of the progress of some long running task, and not merely print debugging statements. As for debugging or code tracing, use Django's logging subsystem in combination with django-debugtoolbar.

Is there anyways I can use a command like echo in Django?

Since Django 1.5, there is a StreamingHttpResponse that kind of allows you to emulate php's echo behavior, under some circumstances.
However, take into account what it says in the Documentation:

Django is designed for short-lived requests. Streaming responses will tie a worker process for the entire duration of the response. This may result in poor performance.

That said, there is an example.
Really?
Note that the recommended and stable way of doing this, in any HTTP request/response driven context (which Django is designed for), is to use an asynchronous task processor like Celery for any long-lived processes. Then use a polling client to check on the progress, e.g. as proposed in this answer.


text:
Q: Accessing individual bits of unsigned integer through pointer to struct with bit fields in C Let's say we have a struct defined like:
struct S_BF {
    unsigned first_bit : 1;
    unsigned second_bit : 1;
    unsigned rest : 30;
}

And a pointer to S_BF struct:
struct S_BF*  bf;

If we have a variable:
unsigned int p = 0;

How can we make bf point to p so we can modify the value of p by modifying its bit fields, for example, if we want to change the value of p to 2, we can do this:
bf->second_bit = 1;

A: The problem with wanting to access the bits of unsigned p with a pointer of type struct S_BF* is that it violates the strict alias rule C11 Standard - §6.5 Expressions (p6,7). The rule is designed to prevent accessing an object of one type by using a pointer to another. (there are various exceptions, but the intent of the rule is to prevent the type-punning of pointers)
The only standard conforming way to access the bits of an unsigned through a pointer to struct S_BF it to make the bits the same bits through a union between struct S_BF and unsigned. You must can access the bits of struct S_BF through a pointer to struct S_BF, and make the struct S_BF and unsigned the same through the union without violating the string aliasing rule. A short example would be:
#include <stdio.h>

struct S_BF {               /* bitfield struct */
    unsigned first_bit : 1;
    unsigned second_bit : 1;
    unsigned rest : 30;
};

union s2u {                 /* union bitfield struct/unsigned */
    struct S_BF s;
    unsigned u;
};

int main (void) {

    union s2u s2u = { .u = 0 };             /* union initialized zero */
    struct S_BF *bf = &s2u.s;               /* pointer to bitfield */
    unsigned sz = 32;                       /* no. of bits in unsigned */

    bf->second_bit = 1;         /* set second bit 1 */
    bf->rest = 0x2aaaaaaa;      /* alternating bits 1010101... */

    while (sz--)    /* loop sz times, using unsigned value in union */
        putchar (s2u.u >> sz & 1 ? '1' : '0');  /* output bits */

    putchar ('\n');
}

Example Use/Output
The above example would result in the following output:
$ ./bin/bitfield_union
10101010101010101010101010101010


text:
Q: Equipvalent of VB6's PaintPicture() method in VB.NET? As I researched. Graphics.DrawImage() can replace PaintPicture() when upgrade from VB6 to VB.Net.
However, DrawImage() lacks of argument like Opcode which defines bit-wise operation.
Please help me to find a correct solution for the replacement.
Thanks.

A: It would seem you have to do it yourself.
If anyone knows the managed way to do it, please post another answer.
Create a separate module:
Module PaintPicture

    <System.Runtime.InteropServices.DllImport("gdi32.dll", ExactSpelling:=True, SetLastError:=False)> _
    Private Function StretchBlt(ByVal hdc As IntPtr, ByVal x As Integer, ByVal y As Integer, ByVal nWidth As Integer, ByVal nHeight As Integer, ByVal hSrcDC As IntPtr, ByVal xSrc As Long, ByVal ySrc As Integer, ByVal nSrcWidth As Integer, ByVal nSrcHeight As Integer, ByVal dwRop As Integer) As Integer
    End Function

    <System.Runtime.InteropServices.DllImport("gdi32.dll", ExactSpelling:=True, SetLastError:=False)> _
    Private Function SelectObject(ByVal hdc As IntPtr, ByVal hObject As IntPtr) As IntPtr
    End Function

    <System.Runtime.InteropServices.DllImport("gdi32.dll", ExactSpelling:=True, SetLastError:=False)> _
    Private Function CreateCompatibleDC(ByVal hdc As IntPtr) As IntPtr
    End Function

    <System.Runtime.InteropServices.DllImport("gdi32.dll", ExactSpelling:=True, SetLastError:=False)> _
    Private Function DeleteDC(ByVal hdc As IntPtr) As Integer
    End Function

    <System.Runtime.InteropServices.DllImport("gdi32.dll", ExactSpelling:=True, SetLastError:=False)> _
    Private Function DeleteObject(ByVal hObject As IntPtr) As Integer
    End Function

    Private Class DCHandle
        Inherits Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid

        Public Sub New(ByVal hDC As IntPtr)
            MyBase.New(True)

            Me.SetHandle(hDC)
        End Sub

        Protected Overrides Function ReleaseHandle() As Boolean
            Return DeleteDC(Me.handle) <> 0
        End Function
    End Class

    Private Class BitmapHandle
        Inherits Microsoft.Win32.SafeHandles.SafeHandleZeroOrMinusOneIsInvalid

        Public Sub New(ByVal hBitmap As IntPtr)
            MyBase.New(True)

            Me.SetHandle(hBitmap)
        End Sub

        Protected Overrides Function ReleaseHandle() As Boolean
            Return DeleteObject(Me.handle) <> 0
        End Function
    End Class

    Public Enum Opcodes As Integer
        vbDstInvert = &H550009
        vbMergeCopy = &HC000CA
        vbMergePaint = &HBB0226
        vbNotSrcCopy = &H330008
        vbNotSrcErase = &H1100A6
        vbPatCopy = &HF00021
        vbPatInvert = &H5A0049
        vbPatPaint = &HFB0A09
        vbSrcAnd = &H8800C6
        vbSrcCopy = &HCC0020
        vbSrcErase = &H440328
        vbSrcInvert = &H660046
        vbSrcPaint = &HEE0086
    End Enum

    <System.Runtime.CompilerServices.Extension()> _
    Public Sub PaintPicture(ByVal g As Graphics, ByVal Picture As System.Drawing.Bitmap, ByVal X1 As Integer, ByVal Y1 As Integer, Optional ByVal Width1 As Integer = 0, Optional ByVal Height1 As Integer = 0, Optional ByVal X2 As Integer = 0, Optional ByVal Y2 As Integer = 0, Optional ByVal Width2 As Integer = 0, Optional ByVal Height2 As Integer = 0, Optional ByVal Opcode As Opcodes = Opcodes.vbSrcCopy)

        Dim hDCTarget As IntPtr = g.GetHdc()

        Try
            Using hDCSource = New DCHandle(CreateCompatibleDC(hDCTarget))
                If hDCSource.IsInvalid Then Throw New Exception("Failed to create compatible DC")

                Using hBitmap = New BitmapHandle(Picture.GetHbitmap())
                    Dim prev As IntPtr = SelectObject(hDCSource.DangerousGetHandle(), hBitmap.DangerousGetHandle())

                    Try
                        If prev = IntPtr.Zero Then Throw New Exception("Failed to select bitmap into the compatible DC")

                        If StretchBlt(hDCTarget, X1, Y1, If(Width1 = 0, Picture.Width, Width1), If(Height1 = 0, Picture.Height, Height1), hDCSource.DangerousGetHandle(), X2, Y2, If(Width2 = 0, Picture.Width, Width2), If(Height2 = 0, Picture.Height, Height2), Opcode) = 0 Then
                            Throw New Exception("Failed to draw picture")
                        End If
                    Finally
                        SelectObject(hDCSource.DangerousGetHandle(), prev)
                    End Try

                End Using
            End Using
        Finally
            g.ReleaseHdc(hDCTarget)
        End Try

    End Sub

End Module

Then use it:
Using p = New Drawing.Bitmap("picture.jpg")
    Using g = Me.CreateGraphics()

        g.PaintPicture(p, 10, 10, Opcode:=Opcodes.vbSrcInvert)

    End Using
End Using


text:
Q: Did my son get hacked? My son just received a used PS3 system from a good friend who had upgraded.  He was playing Call of Duty last night online.  I was watching him play.  Suddenly he got really upset and started going on about the game being hacked.  I just laughed it off because 1) games are always hacked and you just learn to live with it and 2) I didn't fully believe him as he is new to the game and might just be upset that he was getting slaughtered...
And then suddenly...  My son went from a level 7 to level 55 and all of these guns became available.  And all of the players who started low were suddenly at 55.  And then the game got glitchy and things stopped working...
Did my son get hacked?  Is there a way to fix what was done? Is there something that he can do to prevent it from happening?
Thanks.

A: Call of Duty, especially the older games in the series that nobody really plays anymore (although the newer games have it too in some extent) Have hacked lobbies that screw with the game settings in various ways. Everything unlocked, unlimited ammo, fast movement, etc. Naturally some of these "modifications" can mess up the game itself and cause it to crash or just act funny.
I can't promise this, but generally your account will remain "OK", as Activison doesn't really even monitor these games anymore.
Simply restart the game, and try to join a different server (your results may vary).
If it is as bad as I'm guessing... you're most likely better off just shelving the game entirely and trying something else.

A: This definitely sounds like a hack.
Having played Modern Warfare 2 online for the past few years (ie many years after the game was released), I can confirm that these hacked lobbies exist. Often they will simply level everyone in the lobby up, unlocking all weapons, weapon skins, weapon mods, and every other unlockable that would otherwise take hundreds of hours of play to unlock. This is easy enough to verify - simply look through your son's weapons and see if indeed everything is unlocked.
To see if this was a one-time hack while on the hacked lobby, try joining another game that does not appear to be hacked - is your son still at level 55 with everything unlocked?
If not, then you're fine! You can probably continue playing as normal.
If so, then your son's account was leveled up through a hack. So what are the consequences of this?
Well, on the one hand you'll have everything unlocked. This for some people is a dream come true, since again, what normally would have taken hundreds of hours in game is almost instantaneously accomplished on a hacked server. Further, Activision (or whoever the developer of the particular COD game is) is unlikely to care, as this usually only happens in older entries in the series which they no longer monitor.
However, if you're like me and want to feel the sense of accomplishment from unlocking everything myself, then you'll likely need to reset your online account. There is usually an option to do this in the multiplayer options of the game (though you haven't provided the specific COD you're using, finding the option itself should be fairly intuitive via the in-game menus).
Regarding prevention in the future, unfortunately there is not much to be done. If you join a server you suspect to be a hacked lobby, you can try to leave before any of the more permanent hacks (like leveling up) are done to your profile. Otherwise this may be something you need to get used to.

A: Yes, he did get hacked. Leave the game, then join back, and if it still is happening, take the disk out and put it back in.
I also use a PS3 and this happens a lot,  but this should work. If it doesn't, take the game to the store and tell them whats wrong.


text:
Q: Motivation for gradient descent method over OLS/MLE for simple linear regression? I am beginner in machine learning and I am currently trying to find the motivation for gradient descent method. I am confused why we want to employ gradient descent method for linear regression? I see the cost function the same as the OLS function, and gradient descent method here actually takes more effort than simply getting the derivatives equal one. Then why we always try to use gradient descent here? I am when the model gets more complicated , and also when we make more assumptions on the prior distribution of the theta(parameters). The optimization problem will become much more complicated. Then will gradient descent method still survive in terms of this? And OLS/MLE method will not be able to predict the parameters? I see OLS as minimize the cost, and the MLE method as maximize the prob, which is in essence the same.(reference http://www.cs.ubc.ca/~nando/540-2013/lectures/l3.pdf) Should I think gradient descent method as a improvement from the OLS method, while the E-M method(maximize the expected likelihood) as a imporvement from the MLE method. Thanks in advance!

A: In the case of linear regression, we want to obtain estimates of the coefficients $\theta_1, \theta_2 $ where:
$$y = \theta_0 + \theta_1x_1 + ...+ \theta_nx_n + \epsilon$$
where $\epsilon $ is the error modeled as $N(0,\sigma^2)$.
The optimal parameters will then be
$\hat\theta = argmin_\theta L(\theta)$
where L is the OLS function you want to minimize
$L(\theta) = \frac{1}{m}\sum_{i=1}^{m}(y_i - \theta^Tx_i)^2$
On finding the first derivative of this function, equating it to zero, you will find the optimal vector of $\theta$ as:
$\hat\theta = (XX^T)^{-1}XY$
Now the problem here is that matrix inversion is a very expensive operation and so for problems with a lot of data when X and Y are large matrices, it is better to use the gradient descent method even though it is a heuristic that gets us the locally optimal parameter values.
I didn't quite understand this part of your question:
"I am when the model gets more complicated , and also when we make more assumptions on the prior distribution of the theta(parameters). The optimization problem will become much more complicated."
If you re-phrase it, I will edit my response and try to answer that part as well.


text:
Q: RXJS: How can I generate a stream of numbers at random intervals (within a specified range)? I want to use RXJS to set up an ORDERED data stream that emits a number at a random interval (say every 1-5 seconds) which I want to use as a time-randomized data source for testing other parts of RXJS. The following code is generating the items in a random order (due to the delay) but I would like the order preserved only the time randomized.
function randomDelay(bottom, top) {
  return Math.floor( Math.random() * ( 1 + top - bottom ) ) + bottom;
}

var source = Rx.Observable
  .range(1, 10)
  .flatMap(function (x) {
    return Rx.Observable
      .of(x)
      .delay(randomDelay(1000,5000));
  })
 .timeInterval();

var subscription = source.subscribe(
  function (x) {
     $("#result").append('Next: ' +  JSON.stringify(x) +  '<br>');
  },
  function (err) {
     $("#result").append('Error: ' + err);
  },
  function () {
     $("#result").append('Completed');
  });

is giving me variants of the following output:
Next: {"value":1,"interval":1229}
Next: {"value":2,"interval":321}
Next: {"value":4,"interval":645}
Next: {"value":5,"interval":28}
Next: {"value":9,"interval":728}
Next: {"value":10,"interval":269}
Next: {"value":3,"interval":107}
Next: {"value":6,"interval":265}
Next: {"value":8,"interval":1038}
Next: {"value":7,"interval":199}

A: Use concatMap instead of flatMap.
Documentation here:
https://github.com/Reactive-Extensions/RxJS/blob/master/doc/api/core/operators/concatmap.md
var source = Rx.Observable
  .range(1, 10)
  .concatMap(function (x) {
    return Rx.Observable
      .of(x)
      .delay(randomDelay(1000,5000));
  })
 .timeInterval();

A: I just used this question as my base to another and had to update it to RxJs 6 if anyone is interested.

const { range, of } = rxjs;
const { concatMap, delay } = rxjs.operators;

range(1, 10).pipe(
  concatMap(i => of(i).pipe(delay(1000 + (Math.random() * 4000))))
).subscribe(val => { console.log(val); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.4.0/rxjs.umd.min.js"></script>

A: I would suggest dividing this problem into two subproblems: i) emitting at random intervals and ii) generating random values. The first problem could be solved by a suitable custom RxJS observer (that is what crazyObservable is meant to do); the second problem can be solved by a custom subscription to the crazyObservable.
crazyObservable has three parameters: totalNumberOfEmissions, timeInterval and totalNumberOfTimeIntervals; it returns a custom observable that emits randomly totalNumberOfEmissions over the totalNumberOfTimeIntervals.
To get your desired behavior, set totalNumberOfEmissions, timeInterval, and totalNumberOfTimeIntervals at your willing. This Marble diagram can be of help.
var oneHourRandomTenHundredRequisitions$ = crazyObservable(1000,1000,60*60);

let testComponent1 = oneHourRandomTenHundredRequisitions$.subscribe({
next() { <a call to your random generator> } ,
error() { <your custom error call> },
complete() { <your custom complete call> }
});


text:
Q: Can not find script file "Z:\Scripts\LiteTouch.wsf" I installed and configured MDT 2013 yesterday on server 2012. I have a WDS also. I am able to create a WIM file. I did PXE boot into a test virtual machine and I was able to install Windows 10. My MDT is also on vmware ESXI. MDT server is joined to my domain.
I created a task sequence with "sysprep and capture". On the vm that I want to capture I mapped the deployment share and I tried to run the "LiteTouch.vbs" I got the following error:
Can not find script file "Z:\Scripts\LiteTouch.wsf"

I am confused because "LiteTouch.wsf" is just below the vbs file.
This is the first time I am trying to capture an image on the newly built MDT.
Please let me know what I am doing wrong or what I can do to resolve this.

A: The file share to the WDS server has been created wrong. Remove the file share. Then open an elevated command prompt and use:
net use z: \\servername\deploymentshare$

and it will work as expected.
Another issue is you cannot create an image of a computer joined to a domain.
It has to be in a workgroup.


text:
Q: PreparedStatement and ORA-01652( unable to extend temp segment) I have a vey huge query. It is rather large, so i will not post it here(it has 6 levels of nested queries with ordering and grouping). Query has 2 parameters that are passed to it via PreparedStatement.setString(index, value). When I execute my query through SQL Developer(replacing query parameters to actual values before it by hand) the query runs about 10 seconds and return approximately 15000 rows. But when I try to run it through java program using PreparedStament with varibales it fails with ORA-01652(unable to extend temp segment). I have tried to use simple Statement from java program - it works fine. Also when I use preparedStatement without variables(don't use setString(), but specify parameters by hand) it works fine too.
So, I suspect that problem is in PreparedStatemnt parameters.
How does the mechanism of that parameters work? Why simple statement works fine but prepared one fails?

A: You're probably running into issues with bind variable peeking.
For the same query, the best plan can be significantly different depending on the actual bind variables.  In 10g, Oracle builds the execution plan based on the first set of bind variables used.  11g mostly fixed this problem with adaptive cursor sharing, a feature that creates multiple plans for different bind variables.
Here are some ideas for solving this problem:
Use literals  This isn't always as bad as people assume.  If the good version of your query runs in 10 seconds, the overhead of hard-parsing the query will be negligible.  But you may need to be careful to avoid SQL injection.
Force a hard-parse  There are a few ways to force Oracle to hard-parse every query.  One method is to call DBMS_STATS with NO_INVALIDATE=>FALSE on one of the tables in the query.
Disable bind-variable peeking / hints  You can do this by removing the relevant histograms, or using one of the parameters in the link provided by OldProgrammer. This will stabilize your plan, but will not necessarily pick the correct plan.  You may also need to use hints to pick the right plan. But then you may not have the right plan for every combination of inputs.
Upgrade to 11g  This may not be an option, but this issue is another good reason to start planning an upgrade.


text:
Q: Deleting my old Wordpress site. - issues Im trying to delete my Wordpress site.
I am the admin but every time I go to the dashboard, under settings there is no option to delete site just export and import.
I want this site gone.

A: There is no default option for delete a WordPress site from WordPress admin. If you want the website gone, you can just delete the database from cPanel/phpMyAdmin and delete all files.
Of course, if you used a software install like Softaculous, there you will find an option to uninstall the website.


text:
Q: Python conditionally initialize subclass from one of two parents I am using a module that I don't develop that provides two classes Class2D and Class3D.  These classes construct some object from a set of points based on if the points are 2 dimensional or 3 dimensional. I'm trying to write a class that will inherit from one or the other depending on user input.  I want something like below
def MyClass(Class2D,Class3D):
    def __init__(self,points):
        if points.dimension==2:
            Class2D.__init__(self,points)
        else:
            Class3D.__init__(self,points)

        #other initialization now that class is determined

    #other methods and attributes of MyClass

This code doesn't work because Class2D is getting priority for methods but I'm not sure how to work out an alternative.


text:
Q: Why does Java main() method accept an array of String args? Since its possibly one of the most widely used methods of the Java language, why does it have to accept an array of Strings and doesn't work without it? For example, I could always live with:
public static void main() {}

over
public static void main(String[] args) {}

Is there a higher purpose to this than just being able to accept command-line arguments, especially since a vast majority of Java programs are GUI driven and don't need to receive args through command line?

A: even a gui driven java app will start with some main method.
The "higher purpose" has never been to accept command line arguments.
The purpose is just to accept arguments. Period. Whenever you start any program not just Java you will always need some syntax to pass arguments

A: Programs always take commandline arguments. It's up to the programmer to decide if they are used for anything.
So implementing a main without a string-array would lead to more complex startup-logic and potentially confusing and errorneous behavior, for the more than debatable gain of not writing a single parameter declaration less (in your whole program!)
And given the overall verbosity of Java & the support for common templates for boilerplate code in IDEs like Eclipse, I fail to see where that's really an issue.

A: "Is there a higher purpose to this (..)"
Yes: legacy.

A: What "vast-majority" of programs do does not really make much difference in terms of what is needed to be done. There are still lots of command line programs that are driven by command line args.

A: Lots of GUI programs provide facilities to accept command-line switches to control their behaviour at start up.

A: I guess it's because many Java programs will take at least some parameters.  Like C (a syntactical inspiration of Java if nothing else), Java considers the best way to provide these as parameters to main.
Even a GUI program will often take command line parameters.  Just because the shell it's launched from typically doesn't ask for these parameters (by default), doesn't mean they're not supported.

A: I agree that it could be more flexible. In C# for instance, all of these are acceptable entry points:
static void Main()
static void Main(string[] args)
static int Main()
static int Main(string[] args)

The versions returning int use the return value as the exit code for the process. If you don't care about receiving any arguments, you can use one of the versions which doesn't take any. Any arguments given when the program is launched are ignored.
So yes, it could be more flexible - but it's never struck me as a significant problem in Java.

A: there are also many java programs that receive args through command line. Think of javac, ant, maven, etc

A: A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched. For example, we can pass username, password from the command line itself.
class Test {

    static void connectDB(String username, String password) {
        System.out.print(String.format("Username: %s, Password: %s", username, password));
        // code to connect DB
    }

    public static void main(String args[]) {
        connectDB(args[0], args[1]);
    }
}

Now compile the program using javac Test.java
and Execute using java Test rootuser Test1234
The output will be:
Username: rootuser, Password: Test1234

So, we can use commandline-argument this kind of purposes.


text:
Q: How to go about sensing AC power in existing wiring Is there a practical way to sense 60Hz AC power in a pair of wires? Measuring the exact power or even current isn't necessary; it would be sufficient to know whether the load is pulling more than, say 5 amps, or not. For example, suppose you have a well pump wired directly into the house distribution panel, and you only want to monitor when it turns on and off.
This would be a piece of cake if it were possible to separate the conductors and get a regular AC current probe around one of them, but cutting into the romex is unsatisfactory. Finding a place where the conductors are already separate is an obvious angle of attack, but let's leave taking the face off the distribution panel for last resort.
Ideally there are already commercial sensors for this, but it's proving to be an awkward thing to google for. Seems like 8 or 10 amps through two conductors 3/8" or so apart should give off enough stray field to at least tell the difference between on and off.

A: I don't believe there is a cost efficient wait to sense AC power in a pair, no.
Cheap home energy monitors use a lump of ferrite and a coil to clamp around a single wire in the fuse box.
All of the monitors for single appliances I've seen have to be plugged in between the appliance and the wall.
Eg.
http://www.automatedhome.co.uk/New-Products/AlertMe-Add-More-New-Features.html
http://www.vesternet.com/Technologies/Energy-packages/Z-Wave-Energy-Starter-Pack-BASIC
http://www.vesternet.com/Technologies/Energy-packages/Plugwise-9-Piece-Starter-Kit
One possible approach is to take a reading from the main power meter, then try to identify and isolate your target device.
http://www.georgehart.com/research/nalm.html

A: I agree that the stray magnetic field from your power cables seems like it would be enough to at least discriminate between "at least 5 amps on" or "0 amps off".
Perhaps you could build up a system based on one of the magnetic field sensors listed at Open Circuits and press it against the power cord at some convenient point.
As Joby Taffey pointed out, most equipment plugs into an electric socket, and so inserting a meter between the equipment and the electric socket is common:

*

*AC Line Seperator for Current Clamps solves the "cutting into the power cord" problem, and assumes you already have some clamp meter or another clamp meter.

*The "watt usage" meters at ThinkGeek.

These things are generally calibrated to linearly measure current, so they are total overkill for merely discriminating between "on" and "off".
And they won't work as-is for your application, since there is no socket between your well pump and the distribution panel.
But perhaps using one of these off-the-shelf devices, hacking it open and pressing the magnetic sensor against the weak magnetic field that leaks out of your romex cable, will be able to discriminate between "on" and "off" and take much less time and effort than building up something from scratch.


text:
Q: Inserting auto-incremented value in another table row I've been scouring the internet for over an hour now searching for the solution to this problem I'm having, and I've probably found it but I'm still confused:
I have this MySQL table that contains information about my band's gigs, including but not limited to: the date, start time, an event description, etc., and then a column called venue_id, which is a foreign key related to a table which contains information about venues we've played at (venue name, address, website, etc.).
The way I've set up the form we'll use to create new gigs in the Gigs table is, for the venue info, there is a drop-down select menu which gets populated with options selected from the Venues table:
<?php
function venueSelectPopper($conn) {
    $queryVenueNames = mysqli_query($conn, 'SELECT ID, venue_name FROM venues_played_at ORDER BY venue_name;');

    while($DB_venueName = mysqli_fetch_array($queryVenueNames)) {
        $DOC_venueName .=  '<option value="' . $DB_venueName[ID] . '">' . $DB_venueName[venue_name] . '</option>\n';
    }
    return $DOC_venueName;
}
?>

// HTML

<select name='venues-played-at' id='pick-venue'>
    <option value="">Select Venue</option>
    <?php echo venueSelectPopper($conn);?>
</select>

Works fine, no problems here, however, if we're playing at a new venue then we'll obviously have create that new row in the Venues table first in order for the venue_id column in the Gigs table to have any reference.
So how would I go about creating AND retrieving that value all in one go when submitting to Gigs table?
As I said, I've been looking for a solution for some time and I'm gathering that AJAX might come to my rescue here, but the only answers that come up are either in jQuery, which I'm avoiding learning for the time being as I'm still working on learning the fundamentals; or they're referring to other languages like Java or C+ that I'm not even close to learning yet.


text:
Q: Aspx Views in Mvc 5 In visual studio 2013 when you create a new mvc 5 project there is no way of adding an ASPX view.
You can add razor views normally and it works perfectly.
What is the solution here?
Do I need to add a new scaffolding template to VS so it can add ASPX views?
Some say currently it only supports Razor and ASPX is going to be added later. Is it updated yet?
Screenshots added:

Add view screen:

A: You are still able to use the 2012 Templates for MVC 4 with 2013 if you need to use ASPX views.  If you use MVC selection from ASP.NET Web project, then you don't seem to have any option other than Razor, unless you can download it with NuGet.
Kirk

A: From ASP.NET MVC 5, there is no option to select an ASPX View Engine only just RAZOR :
https://social.msdn.microsoft.com/Forums/vstudio/en-US/87cf9775-242b-4eb6-923d-7c83106d0293/visual-studio-2017-mvc-web-application-controller-add-view-missing-aspx-rendering-only-razor?forum=visualstudiogeneral


text:
Q: Why Second Monitor Could Not Load the Desktop Background? I've installed Ubuntu 16.10.
When I attached second monitor to my laptop, it works fine but the second monitor's background is black until I change the background while the laptop's background (first monitor) is loaded correctly.


text:
Q: How to calculate Bayesian probability between two variables? I have 1000 data for two continuous variables (pressure and temperature). I'd like to calculate Bayesian probability between two variables.
In other words, I would like to determine probability that temperature will increase/decrease if pressure is changed?

A: I think there is a relationship between pressure, temperature and volume (if my memory of high school chemistry serves me correctly - confirmed by wikipedia):
$$T=\frac{PV}{kN}$$
$$\begin{array} \\
P=\text{Pressure} \\
V=\text{Volume} \\
k=\text{Boltzman's constant}\\
N=\text{Number of molecules}\\
T=\text{Temperature}
\end{array}
$$
Note that this is an approximate relation this page shows some more complex ways of modeling pressure on temperature.  The principle would be the same as below, just different (harder) equations.  To remind us that this is the information, an $I$ will be put as part of the conditions.
Now you have some data on part of this equation, but I'm sure you would also have some less precise information on Volume.  If you were to take the logarithm of both sides, you get:
$$log(T)=log(P)+log(V)-log(k)-log(N)$$
A very simple procedure is to assume that the volume and number of molecules is approximately a constant, and thus we can model this part as a normal distribution.  So we have:
$$log(T_{i})=log(P_{i})-log(k)+n_{i}$$
Where we assume $n_{i}\sim N(\mu,\sigma)$.  You can look at the noise level estimate $\sigma$ to decide if its worthwhile in getting a more complex model.  So this model has two parameters which you need to estimate.
So you have a new starting pressure $P_{old}$ and  starting temperature $T_{old}$ and the pressure then changes to $P_{new}=P_{old}(1+\delta_{P})$, with a corresponding change in temperature $T_{new}=T_{old}(1+\delta_{T})$.  You want the probability that $-1<\delta_{T}<0$.  Note that this would be conditional on $I$, that you are making predictions in similar Volumes and number of molecules to that which was present when you took the data.  The golden rule is to calculate this probability, conditional on what you know, integrating or averaging over what you don't know.  I'll add more details later.
MORE DETAILS
Any $T_{new}$ will be greater than $T_{old}$ when $log(T_{new})>log(T_{old})$, substituting in the model equation and simplifying gives:
$$log(1+\delta_{P})>n_{old}-n_{new}$$
Thus we require the probability
$$P(log(1+\delta_{P})>n_{old}-n_{new}|n_{1},\dots,n_{N},I)$$
Fitting the model is a straight forward exercise.  You may have reasonable prior knowledge about, but since you have lots of data, it isn't necessary and a non-informative prior will do fine.  This is $p(\mu,\sigma|I)\propto\frac{1}{\sigma}$.  And the likelihood of the data is just the probability that the noise will make up the difference:
$$p(n_{1},\dots,n_{N}|\mu,\sigma,I)\propto\frac{1}{\sigma^{N}}exp\left(-\frac{\sum_{i}n_{i}^{2}}{2\sigma^{2}}\right)=\frac{1}{\sigma^{N}}exp\left(-\frac{\sum_{i}\left(d_{i}-\mu\right)^{2}}{2\sigma^{2}}\right)$$
Where
$$d_{i}=log\left[\frac{T_{i}k}{P_{i}}\right]$$
Now you will only need 3 numbers from your data in this solution, the sample size, $N$, the mean of $d_{i}$ denoted by $\overline{d}=\frac{1}{N}\sum_{i}d_{i}$, and its standard deviation, $s_{d}^{2}=\frac{1}{N}\sum_{i}(d_{i}-\overline{d})^{2}=\overline{d^{2}}-\overline{d}^{2}$.  The posterior predictive distribution for the noise is given by:
$$p(n_{old},n_{new}|N,\overline{d},s_{d}^{2},I)=\int_{0}^{\infty}\int_{-\infty}^{\infty}p(n_{old},n_{new}|\mu,\sigma,I)p(n_{1},\dots,n_{N}|\mu,\sigma,I)p(\mu,\sigma|I)d\mu d\sigma$$
$$=St_{2}\left(\begin{pmatrix}n_{new}\\n_{old}\end{pmatrix}|\begin{pmatrix}\overline{d}\\\overline{d}\end{pmatrix},\frac{s_{d}^{2}}{N-1}\begin{pmatrix} N+1 & 1\\ 1 & N+1 \end{pmatrix},N-1\right)$$
where $St(x|\mu,\Sigma,\nu)$ is a bivariate student distribution with location $\mu$, scatter matrix $\Sigma$, and $\nu$ degrees of freedom.  Now we simply integrate over the region that we want the probability
$$P(log(1+\delta_{P})>n_{old}-n_{new}|n_{1},\dots,n_{N},I)$$
$$=\int_{-\infty}^{\infty}\int_{-\infty}^{log(1+\delta_{P})+t}St_{2}\left(\begin{pmatrix}t\\s\end{pmatrix}|\begin{pmatrix}\overline{d}\\\overline{d}\end{pmatrix},\frac{s_{d}^{2}}{N-1}\begin{pmatrix} N+1 & 1\\ 1 & N+1 \end{pmatrix},N-1\right)dsdt$$
This integral can be done using the t-tables, but at the moment I can't remember exactly how to do it.  You get an 1-D integral over a regularised incomplete beta function.

A: Relationships between physical quantities (like pressure and temperature) often may be described using functions or equations, and sometimes the measurement error is small – this might be the case here as well. If so you could derive the type of relationship and the specific function from physics knowledge you could use statistical (including Bayesian) techniques to determine the values and uncertainties of the parameters.
If the error is large the relationship between the variables will be less apparent and (compared to the physical equation behind the phenomenon) a more simple function could be fitted on the data. Linear regression is a widely used, simple method.
You tagged your question "machine-learning", so the relationship between your variables may be more complex, but you may not be able to derive it from physics. In this case you can choose from a wide spectrum of non-linear machine learning and statistical techniques.
In any case I suggest you to plot your data using a scatterplot, think about the possible mechanisms between the variables. Although machine learning can be Bayesian, too, the best Bayesian approach may be fitting plausible models on the data.


text:
Q: GridView RowCommand is not firing on click edit / delete in asp.net c# I have a Asp Gridview Control with OnRowCommand .i have asp:ButtonField for edit / delete the values.
When I click the any one of the button
protected void gvStaffList_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "DeleteStaff")
    {
    }
}

is not firing can you please help where i am in wrong.
Below I included the entire code stuff
StaffList.aspx
<asp:GridView ID="gvStaffList" runat="server"
    AllowPaging="false"
    AllowSorting="True"
    OnPageIndexChanging="gvStaffList_PageIndexChanging"
    GridLines="Horizontal"
    AutoGenerateColumns="False"
    Width="100%"
    OnRowCommand="gvStaffList_RowCommand"
    DataKeyNames="AliasID"
    OnRowDataBound="gvStaffList_RowDataBound"
    OnSorting="gvStaffList_Sorting"
    CssClass="gvHeader">
    <Columns>
        <asp:BoundField
            DataField="AliasID"
            HeaderText="S.No" SortExpression="AliasId" HeaderStyle-
            HorizontalAlign="Left"
            ItemStyle-HorizontalAlign="Left" />
        <asp:BoundField
            DataField="Name"
            ItemStyle-
            Wrap="true"
            HeaderText="Name"
            SortExpression="Name"
            HeaderStyle-HorizontalAlign="Left"
            ItemStyle-HorizontalAlign="Left" />
        <asp:BoundField DataField="Description"
            ItemStyle-Wrap="true"
            HeaderText="Title"
            SortExpression="Description"
            HeaderStyle-HorizontalAlign="Left"
            ItemStyle-HorizontalAlign="Left" />
        <asp:ButtonField
            CommandName="EditStaff"
            Text="Edit"
            ItemStyle-HorizontalAlign="Left" />
        <asp:ButtonField
            CommandName="DeleteStaff"
            Text="Delete"
            ItemStyle-HorizontalAlign="Left" />
    </Columns>
    <HeaderStyle CssClass="gvHeader" />
    <RowStyle CssClass="gvRow" />
    <AlternatingRowStyle CssClass="gvAltRow" />
</asp:GridView>

StaffList.aspx.cs
using System;
using System.Linq;
using System.Web.UI.WebControls;

public partial class CMS_StaffList : Page_Base_Admin
{
#region Properties, Constants, Enums etc.
public const string vwStatSort = "sortOrder";
public const string ascOrder = "asc";
public const string descOrder = "desc";
public const string titleAddmbr = "Add Staff Member";
public string sortOrder
{
    get
    {
        if (ViewState[vwStatSort].ToString() == descOrder || ViewState[vwStatSort] == null)
            ViewState[vwStatSort] = ascOrder;
        else
            ViewState[vwStatSort] = descOrder;

        return ViewState[vwStatSort].ToString();
    }
    set
    {
        ViewState[vwStatSort] = value;
    }
}
#endregion

#region Page related Events
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        ViewState[vwStatSort] = descOrder;
        Fill_gvStaffList(StaffListSort.AliasId.ToString());
        this.divAddNewStaffMember.Visible = false;
        this.divNewStaffMember.Visible = true;
    }
}
#endregion

#region Events of Grid view 'gvStaffList'
protected void gvStaffList_PageIndexChanging(object sender, GridViewPageEventArgs e)
{

    //Fill_gvStaffList(StaffListSort.AliasId.ToString());
}
protected void gvStaffList_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "DeleteStaff")
    {
        try
        {
            NotificationAlias ntfnAlias = new NotificationAlias
            {
                AliasId = Convert.ToInt32(gvStaffList.DataKeys[Convert.ToInt32(e.CommandArgument)].Values[0]),
                Description = "",
                Name = ""
            };
            int result = Core.SaveOrUpdateNotificationAlias(ntfnAlias, true);
            ViewState[vwStatSort] = descOrder;
            Fill_gvStaffList(StaffListSort.AliasId.ToString());
        }
        catch (Exception)
        {

        }
    }
    else if (e.CommandName == "EditStaff")
    {
        try
        {
            txtStaffName.Text = gvStaffList.DataKeys[Convert.ToInt32(e.CommandArgument)].Values[1].ToString();
            txtStaffTitle.Text = gvStaffList.DataKeys[Convert.ToInt32(e.CommandArgument)].Values[2].ToString();
        }
        catch (Exception)
        {

        }
    }
}

/// <summary>
/// Handles the RowDataBound event of the gvStaffList control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
protected void gvStaffList_RowDataBound(object sender, GridViewRowEventArgs e)
{
    GridViewRow row = e.Row;
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        NotificationAlias drv = (NotificationAlias)e.Row.DataItem;
        if (drv.AliasIsActive == false)
        {
            e.Row.Enabled = false;
            row.CssClass = "disabled";
            e.Row.Attributes["style"] = "none";
        }
        else
        {
            //For deleting
            LinkButton button = (LinkButton)e.Row.Cells[4].Controls[0];
            button.Attributes.Add("onclick", "return confirm('Do you want to deactivate this user. This action cannot be undone. This will not affect past course updates sent by user.');");
        }
    }
}

/// <summary>
/// Handles the Sorting event of the gvStaffList control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewSortEventArgs"/> instance containing the event data.</param>
protected void gvStaffList_Sorting(object sender, GridViewSortEventArgs e)
{
    string directn = e.SortDirection.ToString();
    if (this.Sort == e.SortExpression)
    {
        this.Sort = this.Sort;

    }
    else
    {
        this.Sort = e.SortExpression;
    }
    Fill_gvStaffList(this.Sort);
}

/// <summary>
/// Fill grid view gvstafflist.
/// </summary>
protected void Fill_gvStaffList(string sortfield)
{
    StaffListSort gvstaffSort = (StaffListSort)Enum.Parse(typeof(StaffListSort), sortfield);
    switch (gvstaffSort)
    {
        case StaffListSort.AliasId:
            if (sortOrder == ascOrder)
                gvStaffList.DataSource = Core.GetAllNotificationAlias().OrderBy(x => x.AliasId).ToList();
            else
                gvStaffList.DataSource = Core.GetAllNotificationAlias().OrderByDescending(x => x.AliasId);
            break;
        case StaffListSort.Description:
            if (sortOrder == ascOrder)
                gvStaffList.DataSource = Core.GetAllNotificationAlias().OrderBy(x => x.Description).ToList();
            else
                gvStaffList.DataSource = Core.GetAllNotificationAlias().OrderByDescending(x => x.Description).ToList();
            break;
        case StaffListSort.Name:
            if (sortOrder == ascOrder)
                gvStaffList.DataSource = Core.GetAllNotificationAlias().OrderBy(x => x.Name).ToList();
            else
                gvStaffList.DataSource = Core.GetAllNotificationAlias().OrderByDescending(x => x.Name).ToList();
            break;
        default:
            if (sortOrder == ascOrder)
                gvStaffList.DataSource = Core.GetAllNotificationAlias().OrderBy(x => x.AliasId).ToList();
            else
                gvStaffList.DataSource = Core.GetAllNotificationAlias().OrderByDescending(x => x.AliasId).ToList();
            break;
    }
    gvStaffList.DataBind();
}
#endregion

#region Button Click events
/// <summary>
/// Handles the Click event of the btnNewStaffMember control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void btnNewStaffMember_Click(object sender, EventArgs e)
{
    this.divAddNewStaffMember.Visible = true;
    this.divNewStaffMember.Visible = false;
    lblAddStaff.Text = titleAddmbr;
    txtStaffName.Focus();
}

/// <summary>
/// Handles the Click event of the btnSave control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void btnSave_Click(object sender, EventArgs e)
{
    int saveAlias;
    var alias = new NotificationAlias();
    alias.Name = txtStaffName.Text.Trim();
    alias.Description = txtStaffTitle.Text.Trim();
    saveAlias = Core.SaveOrUpdateNotificationAlias(alias, false);
    if (saveAlias >= 0)
    {
        ViewState[vwStatSort] = descOrder;
        Fill_gvStaffList(StaffListSort.AliasId.ToString());
        txtStaffName.Text = "";
        txtStaffTitle.Text = "";
        txtStaffName.Focus();
    }
}

/// <summary>
/// Handles the Click event of the btnCancel control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void btnCancel_Click(object sender, EventArgs e)
{
    this.txtStaffName.Text = "";
    this.txtStaffTitle.Text = "";
    this.divAddNewStaffMember.Visible = false;
    this.divNewStaffMember.Visible = true;
}
#endregion

}
Javascript code
    <script type="text/javascript" language="javascript">
    function pageLoad(sender, args) {
        //  register for our events
        Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequest);
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);
    }

    function beginRequest(sender, args) {
        ShowLoadingPanel();
    }

    function endRequest(sender, args) {
        HideLoadingPanel();
    }
    function Validate() {
        var name = trim(document.getElementById("<%=txtStaffName.ClientID%>").value.toString());
        if (name == "") {
            alert("Please enter staff name.");
            document.getElementById("<%=txtStaffName.ClientID%>").value = "";
            document.getElementById("<%=txtStaffName.ClientID%>").focus();
            return false;
        }

        var title = trim(document.getElementById("<%=txtStaffTitle.ClientID%>").value.toString());
        if (title == "") {
            alert("Please enter title.");
            document.getElementById("<%=txtStaffTitle.ClientID%>").value = "";
            document.getElementById("<%=txtStaffTitle.ClientID%>").focus();
            return false;
        }
        return true;
    }
    function trim(stringToTrim) {
        return stringToTrim.replace(/^\s+|\s+$/g, "");
    }

    function ValidateLength(label) {
        if (label.toString() == 'name') {
            if ((document.getElementById("<%=txtStaffName.ClientID%>").value).length == 500)
                document.getElementById("<%=dvNameLabel.ClientID%>").style.display = 'block';
            else
                document.getElementById("<%=dvNameLabel.ClientID%>").style.display = 'none';
        }

        if (label.toString() == 'title') {
            if ((document.getElementById("<%=txtStaffTitle.ClientID%>").value).length == 500)
                document.getElementById("<%=dvTitleLabel.ClientID%>").style.display = 'block';
            else
                document.getElementById("<%=dvTitleLabel.ClientID%>").style.display = 'none';
        }
    }
</script>

thanks in Advance


text:
Q: htaccess selective redirect I am trying to redirect all sub-directory pages to main directory, except of a few pages (e.g. (somepage1.html).
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/(de|ru)/somepage1.html
RewriteRule ^([a-z]{2}|zh-CN|zh-TW)/(.*)$ /$2 [R=301,L]

Everything working except de/somepage1.html is redirected to home page (/), which is not acceptable. I wont it not redirected at all.
How can I achieve it
Thanks1

A: Well above rules are clearly excluding de/somepage1.html URL so it is most likely some other rule that is redirecting de/somepage1.html to /. Are you using wordpress or some other CMS tool by any chance? That might have its own rules in .htaccess file, check that please.
Also it would help to check web server's access log when this redirection happens.

A: the code I provided is working perfectly, so if somebody looking for this kind of a solution can use it without a fought.
The reason for not working is that my website were keeping cash and therefore was not renew frequently.


text:
Q: How do I set my printer up or check the printers status under the Unity interface Unity has me very confused. My printer had a jam but there wasn't any status letting me know under Unity. When I sent a job to the printer the print job icon display and just showed waiting. Pointed firefox at the printer it showed a jam. I tried to dig deeper in Unitys interface but did not find anything referring to printer or any system settings. How do I get to the settings, especially the printer?
The printer is a HP C4750 connected through WIFI.

A: Use Alt+F2
system-config-printer


text:
Q: Appending HTML to pages when specific IPs request them? I host three websites on the same physical server, and of course by the Host header I know which website the user requests. For the sake of the example these are the domains:

*

*blog.website1.example

*shop.com

*users.website2.example
There are around 4-5 companies which should use these websites, and I know their IP addresses. One of the companies requested that for their users, I add Javascript tracking (like google analytics). So I was wondering, how could I (based on the company IP addresses) analyze only their clients?
I wouldn't want to add it to one page / all companies.
I want to append the script tag to all requested pages, requested by clients with specific IP address and I don't want to touch any of the website's code, and I also don't want all the clients receiving it (I dont want to do clientside filtering).
I really just want the script appended to specific IP's pages. Is it possible on both apache/nginx?


text:
Q: Download multiple files with different names Python New to Python, mostly used R before. I am trying to download multiple files from a webpages API (climatic data), see link
https://opendata-download-grid-archive.smhi.se/data/6/201604/MESAN_201604050000+000H00M
I want to download a file for each hour of every day of every month of every year (from 2008- 2019), that is changing the "201604050000" part to "201604050100", "201604050200", "201604050300", etc. Everything else looks the same, I only need to change the time/day/month/year to download a file.
This is my Python code for getting every file, but I feel lost in how to download it.
for a in [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019]:
    for b in [1,2,3,4,5,6,7,8,9,10,11,12]:
        for c in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,
                    28,29,30,31]:
            for d in ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11",
                      "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"]:
                s = "grib_%d_%d_%d_%s" %(a,b,c,d)
                print(s)

How can I download all these files? I understand that it will fill my memory quite, so I am happy if I can start by downloading 24 files to start, which is one day. Anyone else has experienced this problem?
In the end, when I have managed my files, I also want to delete them (so I don't allocate too much memory).

A: Not a full answer, but some suggestions:
Use nicer variable names
Use range() instead of rather long constant lists (where applicable)
for year in range(2010, 2019 + 1):
    for month in range(1, 12 + 1):
        for day in range(1, 31 + 1):  # beware, not every month has 31 days
            for hour in ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11",
                      "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"]:
                s = "grib_%d_%d_%d_%s" %(year, month, day, hour)
                print(s)


text:
Q: Heroku not allowing MavenCli do maven install (NoSuchElementException) I'm working on a project where I need to run the maven install command in other projects. To resolve this, I used MavenCli which allows the execution of Maven commands by a Java Spring Boot project. A snippet of the executed code:
private int install(File pom, PrintStream out) throws IOException {
        log.info("Maven install started: " + pom.getCanonicalPath());
        System.setProperty("maven.multiModuleProjectDirectory", pom.getCanonicalPath());
        return this.maven.doMain(new String[]{
                        "install"},
                pom.getCanonicalPath(), out, out);
    }

The this.maven  is initialized in the constructor with this.maven = new MavenCli(). The pom file have the path: "./src/main/resources/github-tasks/main/java-coding-tasks".
In localhost, the code works perfect, but when I deploy in Heroku and call this method, Heroku throw a NoSuchElementException:
2022-04-07T19:21:44.993728+00:00 app[web.1]: 2022-04-07 19:21:44.993  INFO 4 --- [onPool-worker-3] c.x.c.repository.MavenRepository         : 2022-04-07 19:21:44.574 ERROR 4 --- [onPool-worker-3] org.apache.maven.cli.MavenCli            : Error executing Maven.
2022-04-07T19:21:44.993735+00:00 app[web.1]: 2022-04-07 19:21:44.943 ERROR 4 --- [onPool-worker-3] org.apache.maven.cli.MavenCli            : java.util.NoSuchElementException
2022-04-07T19:21:44.993735+00:00 app[web.1]: role: org.apache.maven.eventspy.internal.EventSpyDispatcher
2022-04-07T19:21:44.993736+00:00 app[web.1]: roleHint:
2022-04-07T19:21:44.993737+00:00 app[web.1]: 2022-04-07 19:21:44.969 ERROR 4 --- [onPool-worker-3] org.apache.maven.cli.MavenCli            : Caused by: null

I already tried to change the pom file to relativePath, absolutePath, "./src/main/resources/github-tasks/main/java-coding-tasks/pom.xml", mixed the paths( in the system property "maven.multiModuleProjectDirectory" used relativePath and in the maven.doMain used absolutePath and vice versa), etc.
By the way, if I try to list the files in the directory that gives the NoSuchElementException, the files are there:
log.info("Directory in maven install: {}", Arrays.toString(pom.list()));

Log:
Directory in maven install: [pom.xml, .github, src, .git, README.md, .gitignore]

Does anyone know what's causing this and how to fix it?


text:
Q: I need to get must recent run of a workflow from a SharePoint site using PowerShell I am trying to get the most recent run time of a list of workflows. I have an export of data that gives me the Site URL and the Subscription ID of the workflow.
My thought process is to some how connect to the Workflow History list for each site URL, then filter the data by the Subscription ID. I would then sort by either the Created Date or ID, then return the first entry. This would give me the most recent run. I've been able to do this with Power Automate but the Flow that I started has been running for 5 days now and only outputted 1,000 out of the 3,000 workflows I'm interested in.
I was thinking about using PowerShell for this issue because it can query SharePoint faster and handles the data faster. I've looked at the PNP command to get list items but it doesn't work well with the Workflow history list.
Does anyone know how to get items from a SharePoint list and filter them like I describe above?

A: SharePoint Online: Get All running Workflows using PowerShell
$url = "https://xxx.sharepoint.com/sites/projects"
$userName = "username@xxx.onmicrosoft.com"
$password = Read-Host "Please enter the password for $($userName)" -AsSecureString

#Create credential variable and enable
$SPOCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $password)
$context = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$context.Credentials = $SPOcredentials

#ObjectArray
$WorkflowDetails=@()

Function Get-WorkflowAssociations($WorkflowDetails, $SPOCredentials, $Web){
    #Get Web information and subsites
    $context = New-Object Microsoft.SharePoint.Client.ClientContext($web)
    $context.Credentials = $SPOCredentials
    $web = $context.Web
    $context.Load($web)
    $context.Load($web.Webs)

    try{
        $context.executeQuery()
        #check any subweb if present
        if ($web.Webs.Count -ne 0){
            foreach ($subweb in $web.Webs){
                Get-WorkflowAssociations -WorkflowDetails $WorkflowDetails -SPOCredentials $SPOCredentials -Web $subweb.url
            }
        }

        write-host $web.url
        $context.Load($web.Lists)
        $context.ExecuteQuery()

        foreach($list in $web.Lists) {
            $context.Load($list.WorkflowAssociations)
            $context.ExecuteQuery()

            foreach($wfAssociation in $list.WorkflowAssociations | Where {$_.Status -eq "Started"}) {
                if($wfAssociation.name -notlike "*Previous Version*"){
                    $row=new-object PSObject
                    add-Member -inputObject $row -memberType NoteProperty -name "SiteURL" -Value $web.Url
                    add-Member -inputObject $row -memberType NoteProperty -name "ListTitle" -Value $list.Title
                    add-Member -inputObject $row -memberType NoteProperty -name "WorkflowName" -Value $wfAssociation.Name
                    $WorkflowDetails+=$row
                }
            }
        }
        return $WorkflowDetails
    }
    catch{
        write-host "Error: $($_.Exception.Message)" -foregroundcolor green
    }
}

$WorkflowDetails = Get-WorkflowAssociations -WorkflowDetails $WorkflowDetails -SPOCredentials $SPOCredentials -Web $url


text:
Q: unchecking a checkbox from a button Angular2 I am developing a project using Angular2. I have a list called brands which contain other list called descriptions.
this list will create checkboxes:
<div *ngFor="let brand of brands">
    {{ brand.category }}
    <div*ngFor="let description of brand.descriptions" >
        <input type="checkbox" name="checkbox" />{{ description.value }}
    </div>
</div>

and I have two text boxes:
<input name="brand" />
<input name="description" />
<button>uncheck</button>

the button event will uncheck only the checkbox with the brand and the description that mentioned in the input without changing or rebuilding the list because I need to keep checkboxes' status correct.
any idea?

A: To have two-way data-binding you need to assign the value to your model.
<input [(ngModel)]="checkboxFlag" type="checkbox"/>

This answers your question

A: You will need to hold the value of it somewhere, like add the field isChecked to the description object and then bind it like Gabriel said.
<input [(ngModel)]="description.isChecked" type="checkbox"/>

A: I found a solution, I just have to give the checkboxes an Id then I will change call it from typescript:
    <div *ngFor="let brand of brands">
        {{ brand.category }}
        <div*ngFor="let description of brand.descriptions" >
            <input type="checkbox" name="checkbox"
             [id]="brand.category.replace(' ', '') + description.value.replace(' ','')"/>
            {{ description.value }}
        </div>
    </div>

and then from typescript:
onclick(category, description) {
  const element = <HTMLInputElement> document.getElementById(category.replace(' ', '') + description.replace(' ', ''));
  element.checked = false;
}


text:
Q: Is it practical to make home-made membrane switches in low quantities? I'd like to custom-make membrane keyboard switches as a replacement for the cheap push buttons I am currently using. You have all seen these kinds of buttons. If you have experience making these membrane keyboard switches, can you shed some light on that? Or if it's really something that should only be done in a large manufacturing environment, let me know. Alternatives are just as well - I appreciate it.
EDIT AFTER ANSWERS
i am considering capacitative switches after review of methods used to make membrane switches,  as i am not sure whether the membrane switches i can produce are of professional quality. as an alternative, there is a capacitative switch in my lamp ( these act as a proximity sensor almost.. detecting the capacitance change , from the human body, interacting on the switch) i hover my finger over a solid transparent plate where the switch is under and then it switches. This may be a more consistent, quality way to switch the power.
the switch uses a transparent solid plate.. then a decal over it, then another transparent solid plate. Where the switch (sensor switch) detects my movement is left transparent.

A: There's a 'metal snap dome' style button that you can use which simply sits loose on the keypad. It can be held in place with adhesive, in a membrane, or with some kind of a housing. This overlays your PCB with the contact pattern.
They give a nice tactile feel without consuming a lot of height. And because their placement is defined by the PCB, button arrangement is easy to customize.
Keystone (and a billion other places in China) make them. Here they are on Digi-key for reference: https://www.digikey.com/en/product-highlight/k/keystone/metal-key-pad-dome-switches.
Here's more description of their application: https://www.sager.com/manufacturers/keystone-electronics/metal-key-pad-dome-switches-from-keystone/

A: Mechanical keys are actually much cheaper and easier to DIY as an individual despite their reputation as being expensive and high end for consumer products.
It's just because the discrete nature of mechanical keys makes them expensive per unit, but you have no setup costs. All you have to do is buy each key pre-made. This makes them good for low quantities but means they don't lend themselves as well to cheap mass production as membranes which have very high setup costs but you can churn a million of them out at much cheaper cost per unit.
Plus the discrete nature of mechanical keys makes them well suited for DIYer since it comes in discrete components that you can arrange together however you need, whereas a membrane keys all come together integrated onto one big piece so what you have is what you get and useless for repurposing into another arrangement (which means they always need to be custom, more or less).
Or just search Grayhill, Apem, Digikey, or Mouser for pushbuttons if you need pushbuttons and not keyboard keys.

A: There are 2 ways to make them, start with either a flexible PCB or a rigid PCB depending on your application, then fit a spacer sheet usually out of a soft plastic, this way the sticker does not need to stretch around the bump caps, with holes cut in it for the buttons place the bump caps in the holes, and lastly the decal over the top to hold it all in place.
The better the adhesive you use, the better the final product,
Have made a short run of 5 in the past, the better the adhesive, the better the end result, and you want that spacer to be slightly thinner than the bump caps, about the average of the idle and depressed states, I believe I used the clear covers off a plastic school folder for the spacer, and very thin 3M tape, I'm afraid I do not remember the decal material, It was cut on a vinyl cutter, but believe it was a different material.
I have had a look, but sadly am unable to find any photos from that project.

A: You could some conductive ink and polycarbonate sheeting and apropriate connectors  and have a go for yourself.
However for the price of the ink I can buy hundreds of tactile switches (at less than 1c each).


text:
Q: How do I title a section pertaining to "things I can do" on my CV? I am putting together my CV and I have a section that shows a breakdown of all the things I can do as a Graphic Designer. For example,
Logos & Branding
Technical Drawings
Pitch Decks etc.

I already have a section called Key Skills, in which I have the following list
Planning and Organising
Verbal Communication
Visual Communication etc.

How would I title the section pertaining to the things I can do?

A: They're still Skills or Key Skills.
In an American resume, these items would most likely be grouped under Skills, which would be a catch-all for the things you can do. For instance, The Muse advises creating individual headers under Skills for each field or area of expertise you want to emphasize. For example:

Visual Design: InDesign, Illustrator, Photoshop, After Effects, Premiere, XD, Animate, Lightroom
3D Modeling & 2D Drafting: Rhino, VRay, AutoCAD, Vectorworks, Autodesk Fusion 360

First, note the use of subheaders. If you already have Key Skills, you can develop two or more subheaders. For example, you could label "Leadership" for the interpersonal bits and "Communication" or "Design" for the genres you do. If you go this route, the number and names of these subheaders are personal to you.
The previous example's list was largely software / tool-based. However, the usage of Skills is expansive and can include soft skills and common genres as well. Here's an example from Career Sidekick, deformatted into a comma list:

Phone sales, In-person sales, Lead generation/prospecting, Qualifying leads, Sales presentations, Sales team leadership/training, Customer service, Client on-boarding, Client relationship management

This list is commonly genres (sales presentations) and tasks (qualifying leads), rather than tools.
It is also an example of someone who lumped them together rather than using subheaders, showing that multiple approaches may be valid. Even the section title can vary based on the individual resume/CV writer (I've seen Skills and Certifications, for instance, as well as your own Key Skills), and many resumes and CVs choose to emphasize skills exclusively through work experience and project sections. So beyond knowing that this individual usage (Skills) exists, I would ask multiple people in your field and country what they do.

A: While one could argue that they are synonyms, I think Expertise and Skills work well together. Or, better yet, Expertise and Strengths. If you need an additional heading for the applications you work with, try Tools.

strength, n. 13. An aspect in which a person or thing is strong or strongest; a powerful or beneficial attribute or quality, a strong
  point.
skill, n.1 6. a. Capability of accomplishing something with precision and certainty; practical knowledge in
  combination with ability; cleverness, expertness. Also, an ability to
  perform a function, acquired or learnt with practice (usually
  plural).
expertise, n. (b) The quality or state of being expert; skill or expertness in a particular branch of study or sport.
Source: Oxford Englsih Dictionary (login
  required)

Expertise

*

*Logos & Branding

*Technical Drawings

*Pitch Decks

Strengths

*

*Planning and Organising

*Verbal Communication

*Visual Communication

Tools

*

*Illustrator

*CAD

*PowerPoint

A: I guess you could say:
"Special capabilities, not easily categorized."
But I probably would simply list it under "skills and capabilities".


text:
Q: Wordpress: Advances Custom Field multiple select I've been wracking my brain tonight trying to figure out how to display multiple labels from a select field.
First I tried it with a single field and that is working. Now I want to make use of multiple fields but can't get it working. Can someone help me?
Thanks!
<?php if ( get_field( 'locationCompany', $joboffer->ID) ) : ?>
    <? echo (get_field('locationCompany', $joboffer->ID))?>
<?php endif ?>

A: Make sure that you enable the Select multiple values? in the ACF settings. Here's your code:
<?php

    $locationcompany = get_field( 'locationCompany', $joboffer->ID);

    if ( $locationcompany ) :

        foreach ($locationcompany as $value): ?>

            <?php echo $value; ?>

        <?php

        endforeach;

    endif;

?>

A: You can use the same approach as above but you need to wrap the whole div with the foreach:
<?php

$locationcompany = get_field( 'locationCompany', $joboffer->ID);

if ( $locationcompany ) :

    foreach ($locationcompany as $value): ?>

        <div id="job-offer-filter"
            class="col-xl-4 col-lg-6 col-md-6 col-sm-12 col-xs-12 height-130 job-offer-card all
            <? echo (get_field('company', $joboffer->ID))?>
            <? echo ($value) /*** HERE ***/?>
            <? echo (get_field('workingtime', $joboffer->ID) === "fulltime" ? "Fulltime" : "Parttime")?>
            <? echo (get_field('jobCategories', $joboffer->ID))?>">

    <?php

    endforeach;

endif;

?>

Please note if this div is in the same file with the span tag from above, you can just put this div inside the foreach. To avoid repetition of code.


text:
Q: How do torrent uploader generate video file specs and preview? On the different Torrent websites, how does the uploaders generate the video file specs as well as the images preview. Is this all done automatically?
An example of a torrent description can be seen here: http://thepiratebay.se/torrent/11273201/Lets.Be.Cops.2014.BRRip.XViD-juggs[ETRG]
Format          :  Audio Video Interleave
Bitrate         :  799 kbps
Resolution      :  640 X 344
Aspect Ratio    :  1.85:1
Frame Rate      :  23.976 fps
Quality Frame   :  0.151

Audio :-

Codec ID        :   MP3
Bitrate         :   128kbps
Channel(s)      :   2
Sample Rate     :   48.0 KHZ

Encoder         :   juggs
File Size       :   700MB
Duration        :   01h44m
Source          :   720 SPARKS
Release Date    :   23-10-2014
Language        :   English
Subtitles       :   English
Sample          :   Yes

http://i.imgur.com/xf26QG4.png
http://i.imgur.com/ITZKIKA.png
http://i.imgur.com/b9uT7Th.png
http://i.imgur.com/3W4kiMy.png

A: The information from the media file displayed is extracted using the application 'mediainfo'. The screenshots are usually done using custom scripts using other applications that can extract the screenshots and then place them in a folder inside the torrent directory and create a new torrent from them as well as posting the screenshots to the torrent tracker when it makes the upload. This is all automated and either done on the webserver or on an external server running a torrent auto uploader script.
If your goal is to have the mediainfo and the screenshts posted automatically on your site I would recommend google with something like "torrent auto uploader", or "mediainfo autopost torrent" or similar stuff.


text:
Q: Use a string to call a variable in C# I am trying to use a loop to edit the data of multiple text boxes, but I cannot figure out how to convert a string of which the contents are the name of my box to access the text element of each box.
       private void reset_Click(object sender, EventArgs e)
    {
        string cell;
        for(int i = 0; i < 9; i++)
        {
            for (int j = 0; j < 9; j++)
            {
                cell = "c" + Convert.ToChar(i) + Convert.ToChar(j);
                cell.text = "";
            }
    }

My text boxes are named "c00, c01, .... c87, c88" which is what the contents of my "cell" variable would be during each iteration, however the code above does not work because it is trying to access the "text" element of a string which obviously does not make sense.
Obviously I could clear the contents of each box individually but since I will have multiple events which will change the contents of the text boxes it would be ideal to be able to implement a loop to do so as opposed to having 81 lines for each event.

A: It's far better to use an array. Either a 2D array like this:
TextBox[,] textboxes = ...

private void reset_Click(object sender, EventArgs e)
{
    for(int i = 0; i < textboxes.GetLength(0); i++)
    {
        for (int j = 0; j < textboxes.GetLength(1); j++)
        {
            textboxes[i,j].Text = "";
        }
    }
}

Or a jagged array like this:
TextBox[][] textboxes = ...

private void reset_Click(object sender, EventArgs e)
{
    for(int i = 0; i < textboxes.Length; i++)
    {
        for (int j = 0; j < textboxes[i].Length; j++)
        {
            textboxes[i][j].Text = "";
        }
    }
}

A: I recommend you using of two-dimentional array of TextBoxes. This will make your life easier.
Anyway try this this.Controls.Find()

A: You should be able to linq to it.
TextBox txtBox = this.Controls.Select( c => c.Name == cell );
txtBox.Text = "";


text:
Q: Perl program using wrong arguments I am trying to create simple startup script in perl that will launch various programs on system startup. It is as follows
my @startupPrograms = qw(google-chrome thunderbird skype pidgin );
my @pagesToBeOpenedInChrome = qw(http://www.google.com/ http://stackoverflow.com/ https://mail.google.com/mail/u/0/#inbox);

sub runPrograms() {
    print("Starting startup Programs... \n");
    foreach (@startupPrograms) {
        my $command = $_;
        print "Starting Program " . $command . "\n";
        if($command == "google-chrome") {
            foreach (@pagesToBeOpenedInChrome) {
                $command = $command . " " . $_;
            }
        }
        `$command &`;
        print "Program " . $command . " started \n";
    }

}

But the output I am getting is
[aniket@localhost TestCodes]$ ./startUp.pl
***** Welcome to startup program! *****
Starting startup Programs...
Starting Program google-chrome
Program google-chrome http://www.google.com/ http://stackoverflow.com/ https://mail.google.com/mail/u/0/#inbox started
Starting Program thunderbird
Program thunderbird http://www.google.com/ http://stackoverflow.com/ https://mail.google.com/mail/u/0/#inbox started
Starting Program skype
Program skype http://www.google.com/ http://stackoverflow.com/ https://mail.google.com/mail/u/0/#inbox started
Starting Program pidgin
Program pidgin http://www.google.com/ http://stackoverflow.com/ https://mail.google.com/mail/u/0/#inbox started

Why is taking the pagesToBeOpenedInChrome array contents in each command to be executed? Also it looks like if i put pidgin before other programs it takes forever to start pidgin(other programs are locked). Any help or suggestion is appreciated.

A: change
if($command == "google-chrome") {

to
if($command eq "google-chrome") {

in perl, you use eq or ne for text comparisons and == for numeric comparisons!
use the == for text basically says if $command is not empty or 0


text:
Q: Inline CSS, for Href styling I don't believe it's a typical thing to see, but I'm curious if this is a possible inline scenario.
I have a table with several rows. Some of those rows may or may not have hrefs.
Can I specify link styles inside the  or  tags?  Rather than inside the href tags?

Here's how I want to affect links only:
.a { text-decoration:underline;color:#EEE; }

I already placed a style in the
 tag, which affects regular text.  Can I specify link styles inside there too?  Or is that a limit that can only be done from within stylesheets or inside the  tag itself?

A: Link colors are not inherited from their parent elements. You'll need to specify the color for the links specifically.

A: Firstly, let's get some terminology clear so we're all on the same page.
Elements such as the anchor tag  can be styled using CSS. Attributes, such as href give certain meaning to the tag they belong too. You cannot style attributes alone.
In order to change the style of all anchor tags (all links) in your site you can simply do:
a{
 /* my styles here */
}

As @ceejayoz pointed out above, link colours are not inherited from their parent and so you either need to style them individually inline  (which I sugest you avoid doing), or you style them from a stylesheet/css code block.