text:
Q: How to make custom listSelector on custom listView I'm trying to figure out how to set up a custom listSelector to my listView. The code is more-or-less copy&paste from solutions that worked for others in stackoverflow, but it doesn't work for me.
When I turn on the CAB mode, then I can select and deselect the items, and I see the number of selected items in the CAB navbar, but I don't see any indication in the list. I would like to see which items are selected. Any idea why it doesn't work?
layout/category_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/categories_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ListView
            android:id="@+id/category_browser"
            android:layout_width="match_parent"
            android:layout_height="0dip"
            android:layout_weight="1"
            android:dividerHeight="1dp"
                    android:listSelector="@drawable/list_selector"
                    android:drawSelectorOnTop="true"
            tools:listitem="@layout/category_list_item" >
    </ListView>
    <include layout="@layout/ad"/>
</LinearLayout>

layout/category_list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<com.fletech.smartbaby.api.CheckableLinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/category_browser_list_item"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="fill"
        android:clickable="true"
        android:gravity="fill"
        android:orientation="horizontal">
        <ImageView
                android:id="@+id/category_item_icon"
                android:layout_width="90dp"
                android:layout_height="90dp"
                android:layout_gravity="fill"
                android:layout_weight="0"
                        android:background="#ffffff"
                android:src="@drawable/ic_launcher" />
        <TextView
                android:id="@+id/category_browser_list_title"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center_vertical|start"
                android:paddingLeft="10dp"
                android:paddingRight="10dp"
                        tools:text="Category name"
                android:textColor="#000000"
                android:textSize="24sp" />

        <include layout="@layout/category_features"
            android:layout_centerInParent="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            />

        <include layout="@layout/category_status"
            android:layout_centerInParent="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            />
</com.fletech.smartbaby.api.CheckableLinearLayout>

drawable/list_selector.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#40777777"/>
        </shape>
    </item>
    <item android:state_long_pressable="true">
        <shape android:shape="rectangle">
            <solid android:color="#400000ff"/>
        </shape>
    </item>
    <item android:state_checkable="true">
        <shape android:shape="rectangle">
            <solid android:color="#400000ff"/>
        </shape>
    </item>
    <item android:state_checked="true">
        <shape android:shape="rectangle">
            <solid android:color="#800000ff"/>
        </shape>
    </item>
</selector>

and CheckableLinearLayout.java:
package com.fletech.smartbaby.api;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Parcel;
import android.os.Parcelable;
//import android.support.v7.widget.LinearLayoutCompat; // do I need this? I can't see any difference
import android.util.AttributeSet;
import android.util.Log;
import android.widget.Checkable;
import android.widget.LinearLayout;

public class CheckableLinearLayout extends LinearLayout implements Checkable {
    private static final String TAG = CheckableLinearLayout.class.getSimpleName();
    private static final int[] CHECKED_STATE_SET = {android.R.attr.state_checked};

    private boolean mChecked;

    public CheckableLinearLayout(Context context) {
        super(context);
    }

    public CheckableLinearLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    public CheckableLinearLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setChecked(boolean checked) {
        Log.v(TAG, "setChecked: " + checked);
        if (mChecked != checked) {
            mChecked = checked;
            refreshDrawableState();
        }
    }

    @Override
    public boolean isChecked() {
        return mChecked;
    }

    @Override
    public void toggle() {
        Log.v(TAG, "toggle: " + mChecked + " -> " + (!mChecked));
        setChecked(!mChecked);
    }

    @Override
    // not sure if needed, as it seems to work without this as well
    public boolean performClick() {
        Log.v(TAG, "performClick");
        toggle();
        return super.performClick();
    }

    @Override
    // this might be unnecessary
    protected void drawableStateChanged() {
        Log.v(TAG, "drawableStateChanged");
        super.drawableStateChanged();
        final Drawable drawable=getBackground();
        if(drawable!=null)
        {
            final int[] myDrawableState=getDrawableState();
            drawable.setState(myDrawableState);
            invalidate();
        }
    }

    @Override
    protected int[] onCreateDrawableState(int extraSpace) {
        Log.v(TAG, "onCreateDrawableState: " + extraSpace);
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
        if (isChecked()) {
            mergeDrawableStates(drawableState, CHECKED_STATE_SET);
        }

        return drawableState;
    }

    @Override
    protected Parcelable onSaveInstanceState() {
        SavedState result = new SavedState(super.onSaveInstanceState());
        result.checked = mChecked;
        return result;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (!(state instanceof SavedState)) {
            super.onRestoreInstanceState(state);
            return;
        }

        SavedState ss = (SavedState) state;
        super.onRestoreInstanceState(ss.getSuperState());

        setChecked(ss.checked);
    }

    protected static class SavedState extends BaseSavedState {
        protected boolean checked;

        protected SavedState(Parcelable superState) {
            super(superState);
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeInt(checked ? 1 : 0);
        }

        public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>() {
            public SavedState createFromParcel(Parcel in) {
                return new SavedState(in);
            }

            public SavedState[] newArray(int size) {
                return new SavedState[size];
            }
        };

        private SavedState(Parcel in) {
            super(in);
            checked = in.readInt() == 1;
        }
    }
}

A: I took me more than a week to find out why this thing that works for everyone doesn't work for me. The answer is simple. I hope it'll help others.
The solution was to change the order of the items in the selector xml. The item without any states has to be the last one:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_long_pressable="true">
        <shape android:shape="rectangle">
            <solid android:color="#400000ff"/>
        </shape>
    </item>
    <item android:state_checkable="true">
        <shape android:shape="rectangle">
            <solid android:color="#400000ff"/>
        </shape>
    </item>
    <item android:state_checked="true">
        <shape android:shape="rectangle">
            <solid android:color="#800000ff"/>
        </shape>
    </item>

    <!-- the item without any states has to be the last: -->
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#40777777"/>
        </shape>
    </item>
</selector>

The reason is that it seems that the parser looks for the 1st item in the xml file that matches. It means that if you have items with different number of states, then you should always have those that have more states defined in the top of the xml. For example:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checkable="true" android:state_long_pressable="true">
        <shape android:shape="rectangle">
            <solid android:color="#ffff00"/>
        </shape>
    </item>
    <item android:state_long_pressable="true">
        <shape android:shape="rectangle">
            <solid android:color="#ff0000"/>
        </shape>
    </item>
    <item android:state_checkable="true">
        <shape android:shape="rectangle">
            <solid android:color="#00ff00"/>
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#40777777"/>
        </shape>
    </item>
</selector>

This way, and only this way, you'll see a different color on items that are:
- both checkable and long_pressable
- checkable, but not long_pressable
- long_pressable but not checkable
- everything else


text:
Q: Multiclass classification and unbalanced dataset I have a five-class SVM multiclass problem. The dataset is small (about 160 examples) and unbalanced i.e. I have classes with few examples. So far I further limited the dataset to 110 examples in order to work with a balanced training set... Is this a correct approach? Or should I work with an unbalanced training set? What are the advantages in this latter case? Thank you in advance!

A: reducing a small set is a bad idea. keep all samples. if the classes are separable everything is fine. if not you can use the 'weight' feature to boost classes with little representation.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Enable hardware virtualization on Asus P8P67 motherboard? I have the aforementioend motherboard and it appears that hardware virtualization is disabled on it (as according to vmware). I've looked at the bios options as well as the manual and haven't found any option to be able to turn it on. Am I buggered or is there something I'm missing?

A: On most P8P67 motherboards (you don't specify which), this should be under Advanced - CPU Configuration - Intel Virtualization Technology.  If you don't have this option, then your processor probably doesn't support it.


text:
Q: OleDbConnection - object reference not set to an instance of an object I have a form an one button on it,
below is very really simple my code:
private void ConnectDb()
    {
        try
        {
            connect = new OleDbConnection();
            connect.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.15.0;Data Source=MySong.accdb;Persist Security Info=false;";
            connect.Open();
            statusText.Text = "Database connected";
            command = connect.CreateCommand();
        }
        catch (Exception)
        {
            statusText.Text = "ERROR::Database failed";
        }
    }

    private void CloseConnectDb()
    {
        if (connect != null)
        {
            connect.Close();
            statusText.Text = "Database Closed";
        }
    }

    private void btnTambah_Click(object sender, EventArgs e)
    {
        DateTime tanggal = DateTime.Today;

        Band = txtArtis.Text;
        Title = txtJudul.Text;

        this.ConnectDb();
        command.CommandText = "INSERT INTO TableLagu (Tanggal, Artis, Title, Status) VALUES ('" + tanggal + "', '" + Band + "', '" + Title + "', 'Belum ada')";
        if (command.ExecuteNonQuery() != 0) //executenonquery returns number of row affected
        {
            statusText.Text = "ADD--Data Success inserted";
            txtArtis.Text = "";
            txtJudul.Text = "";

        }
        else statusText.Text = "ERROR::Insert failed";
        this.CloseConnectDb();
    }

When i click on my 'btnTambah' button, it always say "object reference not set to an instance of an object" and display "ERROR::Database failed" on its statusText.
any solution??
i think this code doesn't run while try to call ConnectDb method.
you can see my connection string
Provider=Microsoft.ACE.OLEDB.15.0;
actually, when i creating it, i have microsoft access database 2013 installed on my machine. it works good.
now, i'm trying to run my application on my friends computer that microsoft access installed version 2007. and got an error like above.


text:
Q: UIAlertView delegate crashing the app I am setting the delegate to a UIAlertView in the following way:
PhotoViewController *controller = [[PhotoViewController alloc] init];

UIAlertView *alert = [[UIAlertView alloc]
                      initWithTitle: @"Announcement"
                      message: @"It turns out that you are playing Addicus!"
                      delegate: controller
                      cancelButtonTitle:@"OK"
                      otherButtonTitles:nil];
[alert show];

Where PhotoViewController is not the current UIviewContorller. THe alert loads fine, but as soon as I press on the ok button, the app crashes and I get this error:
0x3a61a5b0:  ldr    r3, [r4, #8]  EXC BAD ACCESS
What does this mean?
EDIT:
+ (DejalActivityView *)activityViewForView:(UIView *)addToView withLabel:(NSString *)labelText width:(NSUInteger)aLabelWidth;
{
// Immediately remove any existing activity view:
if (dejalActivityView)
    [self removeView];

// Remember the new view (so this is a singleton):
dejalActivityView = [[self alloc] initForView:addToView withLabel:labelText width:aLabelWidth];

if ([labelText isEqualToString:@"Uploading photo (this process might take a while)"]) {
buttonCancel = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[buttonCancel addTarget:dejalActivityView
                 action:@selector(callCancelAlert:)
       forControlEvents:UIControlEventTouchDown];
buttonCancel.frame = CGRectMake(230, 540, 265, 40);
[addToView addSubview:buttonCancel];
[buttonCancel setImage:[UIImage imageNamed:@"socialize-navbar-bg.png"] forState:UIControlStateNormal];
[buttonCancel setTitle:@"Cancel upload" forState:UIControlStateNormal];
}

return dejalActivityView;
}

-(IBAction)callCancelAlert:(id)sender{

PhotoViewController *controller = [[PhotoViewController alloc] init];

UIAlertView *alert = [[UIAlertView alloc]
                      initWithTitle: @"Announcement"
                      message: @"It turns out that you are playing Addicus!"
                      delegate: controller
                      cancelButtonTitle:@"OK"
                      otherButtonTitles:nil];
[alert show];
//[alert release];
}

A: Delegates are not retained properties. This means that when controller goes out of scope, ARC will release it and, since it hasn't been retained by another object, it will be deallocated. When the alert view attempts to send a message to its delegate, the address is no longer valid and you get an exception.
The alert view's delegate will need to live longer than the alert view itself. Typically the object that creates an alert view should be the delegate. You should move the delegate code into the class that creates the alert view.


text:
Q: Data Binding - C# I want to bind TextBox's Text property to FolderBrowser's SelectedPath property. But it's not working, I don't know why. Please help me out why it's not working?

A: Data binding makes very little sense here.  Just make your code look like this:
  if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) {
    // User picked a path and didn't cancel the dialog...
    textBox1.Text = folderBrowserDialog1.SelectedPath;
  }


text:
Q: Java RMI: Cannot rebind from a non-local host I am working in a distributed application model where I have 3 applications running on 3 different machines (Say A,B and C). I would like machine A to be a dedicated RMI Registry host. Now I want an application running on B to register an RMI service on registry in A so that another application running on machine C to access this service through A.
As I understand now Java RMI registry does not allow binding from  a non-local host.
Is there any solution to achieve such remote communication among JVMs running across several machines?

A: Use something other than a Registry: for example, an LDAP server.


text:
Q: Laurent series $\sin(\frac{z}{1-z})$ at point $z_0 = \infty$ I need to find the Laurent series of $$\sin\left( \frac{z}{1-z} \right)$$ at the point $z_0 = \infty$.
How I can decompose this? At point $z_0 = 1$ everything turned out well. There I tried 2 things. Firstly, I tried
$$\frac{z}{1-z} = \frac{1}{\frac{1}{z} -1} \Rightarrow \sin\left(\frac{1}{\frac{1}{z} - 1}\right) = \sum_{n=0}^{\infty} (-1)^n \frac{1}{\left(\frac{1}{\frac{1}{z} - 1}\right)^{2n+1} (2n+1)!}
$$
but it looks ridiculous. Next, I tried
$$
\sin\left(\frac{1}{z-1} -1\right) = \sin\left(\frac{1}{z}\left(\frac{1}{1-\frac{1}{z}}\right)\right).$$
But from there on, I don't know what I should do.

A: The Laurent series you want is the same as the Laurent series of $f(1/z)$ at $z=0$.
$$f(1/z)=\sin\left(\frac1{z-1}\right)$$ which is indeed analytic at $0$.
Therefore, just proceed as you are finding its Taylor series. I do not expect that the series has a nice form.


text:
Q: How can I list the OPC DA (OPC Classic) Servers of a remote PC in C# I want to list the OPC DA Servers of a remote machine. Actually I use a code that can list the OPC DA (OPC classic) servers just on the local machine. How should I extend this code in order to be able to list the OPC DA servers on a remote pc? The remote PC is not in the same domain as the C# code running PC. I can ping the remote PC with its IP.
private void List_OPC_Server()
    {
        try
        {
            Opc.IDiscovery opcDiscovery = new OpcCom.ServerEnumerator();
            Opc.Server[] opcServers = opcDiscovery.GetAvailableServers(
                Opc.Specification.COM_DA_20);

            foreach (Opc.Server opcServer in opcServers)
            {
                using (StreamWriter sw = File.AppendText(OPC_Log))
                {
                    sw.WriteLine("OPC Server");
                    sw.WriteLine(opcServer.Url.Path);
                }
            }
        }
        catch (Exception except)
        {
            using (StreamWriter sw = File.AppendText(OPC_Log))
            {
                sw.WriteLine(except);
            }
        }
    }


text:
Q: How do I test functions on jsPerf without it executing? I'm trying to test two snippets, but jsPerf keeps executing the code
myWindow=window.open("myurl.tld","_top");
myWindow.document

\\vs

window.location = "https://myurl.tld"

How do I make it so I don't get redirected while the codes are being tested?


text:
Q: Starting countdown timer in background on receiving push notification I want to start a countdown timer when a push notification is received.
I can receive the notification successfully.
Now I want to ask, is it possible to start countdown timer in onReceive of BroadcastReceiver when a notification is received and my application is in background or foreground?
Simply, I should say that the timer should start whether the app is in foreground or not.
And when the timer is finished it should send some data to server.
And I need to show the remaining time in a text view as soon as app comes to foreground during the countdown.
I am adding some code, please help me out.
This is code to start the timer and this function is called in onReceive.
void startOrderCountDown() {
    CountDownTimer orderCountDown = new CountDownTimer(40000, 1000) {

        public void onTick(long millisUntilFinished) {
            Constant.remainingTimeOfOrder = millisUntilFinished / 1000;
            Log.v("Timer", "Time left: " + millisUntilFinished
                    / 1000);
        }

        public void onFinish() {
            new Thread(new Runnable() {

                @Override
                public void run() {

                    String dr_id = myPreferences.getDRIVERID();
                    String res = new ServerConnection()
                            .updateOrderMissedRejected(
                                    Constant.UPDATE_MISSED_REJECTED_ORDER,
                                    dr_id, "", "0");
                    Log.e("Timer", "finished..." + res);
                }
            }).start();
        }
    };
    orderCountDown.start();
}

But When the notification arrives, it just prints "Time left: 39" in logcat.
Thanks in advance.

A: No need for countdown timer.
Just follow the steps.
1) Create AlarmManagerBroadcastReceiver.java
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver implements IjoomerSharedPreferences {
    @Override
    public void onReceive(Context context, Intent intent) {
            // Call your sever task.
    }
}

2) set alarm from current time when you receive push notification.
long INTERVAL = 40000;
AlarmManager am=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmManagerBroadcastReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 1010, intent, 0);

try{
    am.cancel(pi);
}catch (Exception e){
}
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + INTERVAL, pi);

2) Manifest.xml
<receiver  android:process=":remote" android:name="com.XXX.ZZZZ.AlarmManagerBroadcastReceiver"></receiver>


text:
Q: Using wire and assign vs. wire in Verilog Is there any difference between
wire A = B & C;

and
wire A;
assign A = B & C;

?
I do not think so but I have seen code using the latter and I wonder if that was done for a reason.

A: They are functionally the same in your example. There are slight differences when adding a delay to a wire declaration.
wire #5 A = B & C;

wire A;
assign #5 A = B & C;

In the first form, the delay gets added to all other net drivers. You can also use SDF back annotation to modify the wire delay.
In the second form, the delay applies to only that continuous assignment, and you cannot use SDF back annotation to modify the delay.
My observation is that most people use the second form in RTL to keep the declarations and functionality separated.


text:
Q: Was there a Biggs Darklighter scene on Tatooine in "A New Hope"? I was recently watching Star Wars: A New Hope on DVD with my grandson. Biggs Darklighter spoke to Luke in the hangar bay and I was asked "Who is he, grandpa?"
I explained he's the one who was with the girl in the cafeteria on Tatooine, they were teasing Luke about being a farmboy.  I got a puzzled look because it wasn't on DVD.
I dragged out my VHS player and put in my old shop-bought A New Hope videotape from the 1980's - no such scene.
I then searched and found another tape of it that I'd recorded from television many years ago - no such scene.
I mentioned this to a lifelong friend, we'd went to see A New Hope original run as teenagers in the 1970's. He looked puzzled and said he hadn't seen this scene.
It's like a reverse Mandela Effect, I know I saw this cafeteria scene.  Was there ever a version of Episode IV that showed it?

A: There was an interactive DVD-ROM released on PC in 1998 called Star Wars - Behind the Magic that this, and a few of other deleted scenes, appeared on.
If you ever owned that, it's possible that this is where you saw it.

A: There was a Star Wars Storybook that was published in the late 1970s or early 1980s, and it showed a photo of Biggs and Luke meeting on Tatooine, along with a summary of that scene. Thanks to that book, for the longest time I thought that scene had been included in the theatrical run, but got cut whenever the movie was shown on TV. It wasn't until the late 1990s that I realized it was a deleted scene.
Star Wars Storybook at Wookieepedia

A: The scenes with Biggs, Cammie and Luke's other friends were included on (among others) the (2011) Complete Bluray edition, which is where you're most likely to have seen it since it was never included in a release version.

There is, however, the possibility that you saw it on one of the various bootlegged "despecialised" editions that have popped up on the internet (incorporating these scenes into A New Hope) or read the Official Novelisation or Comic Novelisation in which these scenes also appear.

A: The scenes with Luke at the moisture evaporator looking up with binoculars at a space battle and also at Tosche station talking to Biggs, were included in prints that went to only about 12 theaters. I saw it myself in Louisville KY. opening night. I was 16 at the time and returned to see the same version several more times.
A couple years later I saw it again at the same theater and noticed the first several minutes of the movie were missing. I have talked to others that also remember seeing the deleted scenes. This information used to be on the web, but has disappeared over time.

A: I'm familiar with that scene from having watched this YouTube video, about how the movie was saved in the edit.  (Link queued to the part I believe you've mentioned)

A: In addition to prior answers, another place one might have seen this (and perhaps the earliest) is in Marvel Comics Star Wars #1 (July 1977), with art by Howard Chaykin. Clearly this was based on an early cut of the movie including that scene. I similarly had this moment in my head for many years, thinking it was in the movie, before ever seeing the actual film footage.

A: Daniel Collins, I fondly remember that illustrated Scholastic Star Wars book of the movie.
The Yavin hangar scene was included in a rough cut reportedly shown to Stephen Spielberg and Brian De Palma by George Lucas during post production. This version had certain issues with pacing of narrative structure, among other things. Marcia Lucas won an Oscar (best editor) for her significant work on the original theatrical release, of which the Biggs scenes at Toschi Station (?) and the Yavin hangar were dropped.
Images, and TV and 8mm footage did reach the public during this period though. I remember being introduced to Star Wars thanks to a friend of my Dad's, a work colleague showing off his 8mm film projector. He only had the scene where Uncle Owen purchases the Droids. I wonder if anyone saw leaked footage in this manner.
There were a lot of stills featured in magazines like Starlog, and cut footage such as original Jabba, Biggs, Luke watching the opening space battle from the ground etc. may have featured in televised special effects documentaries of the era.
The hype surrounding Star Wars was almost insane, and without the benefit of the internet, fans relied upon leakers, TV broadcasts, videotape and laser disc, magazines, postal fan clubs, and word of mouth for exciting and obscure crumbs of info.


text:
Q: Web speech api returning old transcript I have this service in angular to translate speech into text through webspeech
import { Injectable } from '@angular/core';
declare var webkitSpeechRecognition: any;

@Injectable({
  providedIn: 'root'
})
export class VoiceRecognitionService {

  recognition =  new webkitSpeechRecognition();
  isListening = false;
  public text = '';
  public tempWords : any;
  public transcript_arr = [];
  public confidence_arr = [];

  constructor() { }
  getTranscriptValue()
  {
    return this.transcript_arr;
  }
  getConfidenceValue()
  {
    return this.confidence_arr;
  }
  init() {
    this.recognition.continuous = true;
    this.recognition.interimResults = false;
    this.recognition.maxAlternatives = 1;
    this.recognition.lang = 'en-US';

      this.recognition.addEventListener('result', (e:any) => {
        let last = e.results.length - 1;
        let temp_trans = e.results[last][0].transcript;
        let confidence = e.results[last][0].confidence;
        this.confidence_arr.push(confidence);
        this.transcript_arr.push(temp_trans);
        const transcript = Array.from(e.results)
          .map((result:any) => result[0])
          .map((result) => result.transcript)
          .join('');
        this.tempWords = transcript;
      });

  }

  start() {
    if(this.isListening==false)
    {
      this.isListening = true;
      this.recognition.start();
    }

    this.recognition.addEventListener('end', (condition:any) => {
      if (!this.isListening) {
        this.recognition.stop();
      } else {
        this.wordConcat()
        this.recognition.start();
      }
    });
  }
  stop() {
    this.isListening = false;
    this.wordConcat();
    this.recognition.stop();
  }
  reinit()
  {
    this.transcript_arr=[];
    this.confidence_arr=[];
    this.tempWords='';
    this.text='';
  }
  wordConcat() {
    this.text = this.text + ' ' + this.tempWords + '.';
    this.tempWords = '';
  }
}

I call this service function from .ts file like i call this.service.init() on start and then this.service.start() after that i call this.service.stop() and this.service.reinit() but i still get old values with the new values in the result event listener in temp_trans variable i don't want to old values i want new values if i stop it through this.service.stop().
Any solution is highly appreciated. Thanks

A: Try to also clear temp_trans when you reinit.
@Injectable({
  providedIn: 'root'
})
export class VoiceRecognitionService {

  recognition = new webkitSpeechRecognition();
  isListening = false;
  temp_trans = '';
  public text = '';
  public tempWords: any;
  public transcript_arr: string[] = [];
  public confidence_arr: string[] = [];

  constructor() { }

  getTranscriptValue() {
    return this.transcript_arr;
  }

  getConfidenceValue() {
    return this.confidence_arr;
  }

  init() {
    this.recognition.continuous = true;
    this.recognition.interimResults = false;
    this.recognition.maxAlternatives = 1;
    this.recognition.lang = 'en-US';
    this.startListening();
  }

  startListening() {
    this.recognition.addEventListener('result', (e: any) => {
      let last = e.results.length - 1;
      this.temp_trans = e.results[last][0].transcript;
      let confidence = e.results[last][0].confidence;
      this.confidence_arr.push(confidence);
      this.transcript_arr.push(this.temp_trans);
      this.tempWords = Array.from(e.results)
                            .map((result: any) => result[0])
                            .map((result) => result.transcript)
                            .join('');
    });
  }

  stopListening() {
    this.recognition.removeEventListener('result', () => ());
  }

  start() {
    if (!this.isListening) {
      this.isListening = true;
      this.recognition.start();
    }

    this.recognition.addEventListener('end', (condition: any) => {
      if (!this.isListening) {
        this.recognition.stop();
      } else {
        this.wordConcat();
        this.recognition.start();
      }
    });
  }

  stop() {
    this.isListening = false;
    this.wordConcat();
    this.recognition.stop();
    this.stopListening();
  }

  reinit() {
    this.startListening();
    this.transcript_arr = [];
    this.confidence_arr = [];
    this.temp_trans = '';
    this.tempWords = '';
    this.text = '';
  }

  wordConcat() {
    this.text = this.text + ' ' + this.tempWords + '.';
    this.tempWords = '';
  }
}


text:
Q: Implementing a scala method using a partial function I have a class, as follows:
trait Foo {
  def greet(name: String) : String
}

trait Bar {
  def hello(name: String) = s"Hello ${name}!"
}

class Greeter extends Foo with Bar {
  def greet(name: String) = hello(name)
}

I'm curious if it is possible to implement greet using a partial application of the hello method? Something like:
class Greeter extends Foo with Bar {
  def greet = hello
}

(Obviously this doesn't work)

A: In Scala you often have to explicitly state when you want to apply a method only partially. This is done by writing an underscore behind the method name (but do not forget a space before that). In your case it would work as follows:
def greet = hello _

EDIT: After what @Richard Sitze observed, you could amend the situation by slightly changing the definition of Foo as follows:
trait Foo {
  def greet : String => String
}

Whether this is appropriate of course depends on your specific setup.

A: While you can certainly implement greet, as noted by @chris, that code snippet overloads Foo.greet(name:String); it does not override it:
class Greeter extends Foo with Bar {
    def greet = hello _
}

<console>:9: error: class Greeter needs to be abstract, since method
       greet in trait Foo of type (name: String)String is not defined
       class Greeter extends Foo with Bar { def greet = hello _ }

While the following does compile:
class Greeter extends Foo with Bar {
    def greet(name: String) = hello(name)
    def greet = hello  _
}

As an aside, you can also define greet with an explicit type decl, without the trailing underscore:
def greet: String=> String = hello


text:
Q: Determining all the adjacent spaces on a 2D grid I can't seems to find a good way to solve this problem I'm working on.
Suppose I have a point on a 2D grid describing the location of a character(board game):
                                 [n,m]

Now, on each turn I can move the character depending on the roll of a dice (1,2,3...), and I want to find all possible ways the character can move.
Moving the character once means changing only n or m in which a diagonal movement counts as 2 movements (i.e. [n+1,m] moved once, [n+1,m+1] moved twice).
For example, if I roll a 2 then all possible movements are:
                                 [n,m+2]
                        [n-1,m+1][n,m+1][n+1,m+1]
                    [n-2,m][n-1,m][n,m][n+1,m][n+2,m]
                        [n-1,m-1][n,m-1][n+1,m-1]
                                 [n,m-2]

I can't seem to get a clear algorithm for this.
What I have so far is another suggestion from Daniel Lew
position = [3,2] #position
n = 2 #number of moves allowed
for i in range(position[0]-n,position[0]+n):
    for j in range(position[1]-n,position[1]+n):
        if abs(position[0]-i) + abs(position[1]-j) <= n:
                print i,j,'works\n'

However, it misses the [n][m+2],[n+2,m] (or the way I wrote it misses it).
Any suggestions for concise answers or fixes?

A: Walk through (inclined) lines of diamond and transform into normal coordinates. Python code
n = 2 #number of moves allowed
for i in range(0, n+1):
    for j in range(0,n+1):
       print i + j - n, i - j,'\n'

Alternative approach: you can shift along the first coordinate in range of n in both directions. If some moves are left (movesleft), you can shift along the second coordinate in any direction using movesleft steps. The second stage must preserve oddity (parity?), so step 2 is used.
pseudocode
n_moves = 2
for dy = -n_moves to n_moves do
     movesleft = n_moves - Abs(dy)
     for dx = - movesleft to movesleft] step 2 do
         make_turn(pos_x + dx, pos_y + dy)

Delphi code for n=2 and n=3 gives results
var
  n, ml, dx, dy: Integer;
begin
  n := 3;
  for dy := - n to n do begin
    ml := n - Abs(dy);
    dx := - ml;
    repeat
      Memo1.Lines.Add(Format('[%d, %d]', [dy, dx]));
      dx := dx + 2;
    until dx > ml;

  end;
[-2, 0]
[-1, -1]
[-1, 1]
[0, -2]
[0, 0]
[0, 2]
[1, -1]
[1, 1]
[2, 0]

[-3, 0]
[-2, -1]
[-2, 1]
[-1, -2]
[-1, 0]
[-1, 2]
[0, -3]
[0, -1]
[0, 1]
[0, 3]
[1, -2]
[1, 0]
[1, 2]
[2, -1]
[2, 1]
[3, 0]

1st method (the same result in another order):
for  i := 0 to n do
    for j := 0 to n do begin
        dx := i + j - n;
        dy := i - j;
        Memo1.Lines.Add(Format('[%d, %d]', [dy, dx]));
    end;

[0, -2]
[-1, -1]
[-2, 0]
[1, -1]
[0, 0]
[-1, 1]
[2, 0]
[1, 1]
[0, 2]

A: Suppose the dice shows p.
Now you want to know how many points are there from your current location having manhattan distance p.
Now what you can do it simply do this.
Pseudocode:
for i=0..p
   if( x+i or x-i is valid and y+p-i or y-p+i is valid )
      then move in (x+i,y+p-i) or/and (x-i,y-p+i) or/and (x-i,y+p-i) or/and (x-i,y+-i)

A: With Python 2.7:
import math

# Get coordinates of possible dislocations

def get_possible_dislocations(initial_x, initial_y, max_steps):
    possible_dislocations = []

    for x in range(-max_steps,max_steps+1):
        for y in range(-max_steps,max_steps+1):
            if math.pow(x, 2) + math.pow(y, 2) <= math.pow(max_steps, 2):
                possible_dislocations += [[initial_x + x, initial_y + y]]
    return possible_dislocations

print get_possible_dislocations(0,0,2)

# Returns [[-2, 0], [-1, -1], [-1, 0], [-1, 1], [0, -2], [0, -1], [0, 0], [0, 1], [0, 2], [1, -1], [1, 0], [1, 1], [2, 0]]

If you wanted to test it with PyGame, you could do it like:
import math
import pygame, sys
from pygame.locals import *

# Get coordinates of possible dislocations

def get_possible_dislocations(initial_x, initial_y, max_steps):
    possible_dislocations = []

    for x in range(-max_steps,max_steps+1):
        for y in range(-max_steps,max_steps+1):
            if math.pow(x, 2) + math.pow(y, 2) <= math.pow(max_steps, 2):
                possible_dislocations += [[initial_x + x, initial_y + y]]
    return possible_dislocations

# Initialize Pygame

pygame.init()

crashed = False
display_width = 500
display_height = 500
clock = pygame.time.Clock()
display=pygame.display.set_mode((display_width,display_height),0,32)
white=(255,255,255)
blue=(0,0,255)

display.fill(white)

center_w = display_width/2
center_h = display_height/2

# Calculate possible dislocations
possible_dislocations = get_possible_dislocations(center_w, center_h, 50)

# Draw pixels on every possible dislocation, starting from the center of the display

for loc in possible_dislocations:
    pygame.draw.rect(display,blue,(loc[0],loc[1],2,2))

# Run the display
while not crashed:
    for event in pygame.event.get():
        if event.type==QUIT:
            pygame.quit()
            sys.exit()
    pygame.display.update()

    clock.tick(60)

In this example, the character can move 50 steps. If you move around a point keeping the same distance to the center, the result is a circle. If you can go anywhere inside that circle, you get the cartesian coordinates of a disk.


text: Q: Using multiple private packages from npm We are currently using a private npm package in our project and we would like to use another private npm package in the same project. Both of our packages are created from members from our company who belong to different teams. For example, lets say we are using the private package @team_1/database and like to use the package @team_2/wrapper as well. The .npmrc allows us to have only one authToken in it. Is there any way for us to use both private packages using different authentication tokens without adding the packages under the same private account? Adding both authTokens in the .npmrc file won't do the job.


text:
Q: Undefined index Laravel 5.1 In my blade template I have:
 {{ [ 'label' => 'Author:'  , 'custom'=> \Auth::User()->name ] }}

But when I want to use like this:
 ( null !== $options['custom']) ? $set = $options['custom'] : false;

I see the error Undefined index: custom? What is wrong?


text:
Q: How can I track a value of a boolean at runtime? I want to define a boolean which tracks the values of two other booleans and updates dynamically when they change, how can I achieve this?
#include <stdio.h>

typedef struct candle_s {
    bool is_on;
    int flame_size;
}candle_t;

typedef struct led_s {
    bool is_on;
    int ampers;
}led_t;

typedef struct light_s {
    bool is_any_on;
    candle_t candle;
    led_t led;
}light_t;

int main()
{
    light_t light1;

    light1.led = {0, 10};
    light1.candle = {1, 20};
    light1.is_any_on = light1.led.is_on | light1.candle.is_on;

    printf("Is any on: %d, is light on %d, is candle on %d\n",
            light1.is_any_on, light1.led.is_on, light1.candle.is_on);

    light1.candle.is_on = 0;

    printf("Is any on: %d, is light on %d, is candle on %d\n",
            light1.is_any_on, light1.led.is_on, light1.candle.is_on);

    return 0;
}

Program output:
Is any on: 1, is light on 0, is candle on 1
Is any on: 1, is light on 0, is candle on 0

How can I make is_any_on "0"?
I could achieve this with a function, but can I do it otherwise?
I guess using boolean pointer won't help much either, since I am interested in the result of two boolean values.

A: You need to use a function:
bool is_any_on(light_t *light)
{
    return light->led.is_on || light->candle.is_on;
}

And call it like this:
is_any_on(&light1)


text:
Q: How to continuously get counter values with F# WMI type provider Hi I'm trying out F# WMI type provider code sample looks like this
type Local = WmiProvider<"localhost">
let data = Local.GetDataContext()
let memory = [for d in data.Win32_PerfFormattedData_PerfOS_Memory -> d.AvailableBytes]

memory in this case is System.Nullable list. So the question is how to get continuous updates for this list? Currently my code looks like this
let printMemory () =
    let rec outerLoop =
        let memory = [for d in data.Win32_PerfFormattedData_PerfOS_Memory -> d.AvailableBytes]
        let rec loop (values:Nullable<uint64> list) =
            Thread.Sleep(1000)
            match values with
            |[] -> printfn "empty"
                   outerLoop
            |h::t -> printfn "value = %d" h.Value
                     loop t
        loop memory
    outerLoop

So I have to request new list (memory) every time, is this correct approach?
For example PerformanceCounter counter from System.Diagnostics implements NextValue, is there something similar for WMI type provider? Thanks!

A: If you don't want to block the current thread, Rx provides a nice API for handling that:
// nuget FSharp.Management
#I "packages/FSharp.Management/lib/net40"
// nuget System.Reactive
#I "packages/System.Reactive.Core/lib/net46"
#I "packages/System.Reactive.Linq/lib/net46"
#I "packages/System.Reactive.Interfaces/lib/net45"

#r "System.Management.dll"
#r "FSharp.Management.WMI.dll"
#r "System.Reactive.Core.dll"
#r "System.Reactive.Interfaces.dll"
#r "System.Reactive.Linq.dll"

open FSharp.Management
open System
open System.Reactive.Linq
open System.Runtime.InteropServices
open System.Text

[<DllImport("shlwapi.dll", CharSet = CharSet.Unicode)>]
extern int64 StrFormatKBSize(int64 qdw, [<MarshalAs(UnmanagedType.LPTStr)>] StringBuilder pszBuf, int cchBuf);

let bytesToString byteCount =
    let sb = StringBuilder(32);
    StrFormatKBSize(byteCount, sb, sb.Capacity) |> ignore
    sb.ToString()

type Local = WmiProvider<"localhost">
let memory = Local.GetDataContext().Win32_PerfFormattedData_PerfOS_Memory
let freeMem() =
    // I don't know the semantics of Win32_PerfFormattedData_PerfOS_Memory
    // you might want to adjust the following
    memory
    |> Seq.choose (fun d -> d.AvailableBytes |> Option.ofNullable)
    |> Seq.exactlyOne

let print m =
    printfn "At %A: free %s" DateTime.UtcNow (bytesToString(int64 m))

// Immediately start to produce values every 1 second (on thread pool)
Observable.Timer(TimeSpan.Zero, TimeSpan.FromSeconds 1.0)
|> Observable.map(fun _ -> freeMem())
// only propagate a value if it differs from the previous one
|> Observable.DistinctUntilChanged
|> Observable.subscribe print

// Causes a non-fatal error in VS Interactive, works in FSI
Console.ReadKey() |> ignore

This script produces e.g.

At 27.09.2016 10:24:10: free 8'053'600 KB
  At 27.09.2016 10:24:11: free 8'053'604 KB
  At 27.09.2016 10:24:13: free 8'053'600 KB
  At 27.09.2016 10:24:14: free 8'053'604 KB
  At 27.09.2016 10:24:15: free 8'054'472 KB
  At 27.09.2016 10:24:16: free 8'054'468 KB
  At 27.09.2016 10:24:17: free 8'054'496 KB
  At 27.09.2016 10:24:18: free 8'054'480 KB
  At 27.09.2016 10:24:20: free 8'054'492 KB

A: You will have to make call explicitly for new values or use refresh object WmiSmoObject.Refresh
F#
abstract Refresh : unit -> unit
override Refresh : unit -> unit


text:
Q: mod_rewrite and hyperlinks I'm trying to get my head around mod_rewrite and friendly URLS.
OK, on a very basic level I have the following rule:
RewriteRule ^register$ register.php [L]

This allows me to browse to www.mydomain.com/register
The hyperlink within my pages shows register.php. Do I have to manually change my links to register?
Esentiallly, I do not want the .php extension on any of my links.
Thanks!!

A: Yes, you must manually change the hyperlinks (or use your favourite search-and-replace tool). mod_rewrite can't do this for you; it can only rewrite incoming requests, not outgoing HTML.

A: Yes, you'll need to change the URL in your code if that's not what you want to show up in the address bar.

A: Just an addition:
Note that RewriteRule ^(.*)$ /$1.php rewrites all files for you which saves you typing a lot of rules ;) Offcourse you can add more validation to it by using something like RewriteRule ^(.*)$ /index.php?pageId=$1.


text:
Q: jblas blas lapack - dsysv slower than dgesv - Why solveSymmetric is slower than solve I have a Java program making linear algebra. I use the jblas library that, according to my understanding, is supposed to call native libraries implementing Blas and Lapack for faster results.
This code is running within a Docker and launched in AWS Batch managed jobs.
Excerpt from Dockerfile :
FROM debian:stretch
RUN apt-get -y update && apt-get -y upgrade
RUN apt-get -y install libgfortran3 # install fortran
RUN apt-get -y install openjdk-8-jdk # install java 8

I try to improve the speed to inverse a 24000 by 24000 square symmetric matrix.
I see there is 2 methods provided by jblas library. One for general purpose linear system solving using native dgesv procedure and another one for symmetric matrix solving using native dsysv procedure.
DoubleMatrix A = ...; // my 24k symmetric square matrix
DoubleMatrix B = DoubleMatrix.eye(A.rows);// Identity matrix
DoubleMatrix C = Solve.solve(A, B);// takes 4020 s
DoubleMatrix D = Solve.solveSymmetric(A, B);// takes 5040 s, longer than the calculation of C

Question 1 : is it normal that solving a 24k square matrix takes so much time when native Blas and Lapack libraries are supposed to be used ? If no, how to improve the speed while running in the context of a AWS Batch job ?
Question 2 : Why solve symmetric (dsysv) is slower than general solve (dgesv) ? My expectation is that if we let the native library know that the input matrix is symmetric, it gives it a hint that should allow it to solve the linear system faster.
By the way, I checked that the 2 ways of doing gives the same numerical results. This is the case.

A: I will answer only one of your questions.

*

*is it normal that solving a 24k square matrix takes so much time.
A: Yes, matrix inversion is O(n^3) so you are doing dozens of trillions of operations. What are you using the matrix inverse for? If you just want to solve a system then it may be better to use an iterative algorithms that resembles gradient descent methods popular for neural networks, e.g. Gauss-Seidel, or Richardson.

The other question is tricky, not all the operations in a symmetric matrix are more efficient than in a general matrix.
For sake of the argument suppose that you want one single element in a general matrix in column-major 1D array form. A[i,j] = A_ge[j*N+i], but in the symmetric representation where the lower triangular part A[i,j] = i > j ? A_sy[i*(i+1)/2 + j] : A_sy[j*(j+1)/2 + i], the redundancy in the memory made it simpler to retrieve the desired element.
I think the answer should be a no if the most efficient algorithm was implemented. But the main motivation for having a symmetric matrix representation may be to save memory or numerical stability, and not speed.
This 20% increase in run-time may be due to less efficient indexing, for instance,


text:
Q: Unable to correctly parse Dialogflow fulfillmentMessages I'm having an issue parsing DialogFlow responses in a Flutter app when BOTH default response and Facebook integration responses are defined.
Setup: DEFAULT response contains a simple custom payload

Facebook integration response is set of quick replies.

The JSON representation of both the above responses can be examined when the Intent is downloaded, as below.
        "messages": [
    {
      "type": "quick_reply",
      "platform": "facebook",
      "condition": "",
      "title": "What can I help you with today?",
      "replies": [
        "Facebook option 1",
        "Facebook option 2"
      ]
    },
    {
      "type": "custom_payload",
      "condition": "",
      "payload": {
        "replies": [
          "option 1",
          "option 2"
        ],
        "text": "this is some text!"
      }
    }
  ],

In this simple Flutter app, I connect to DialogFlow and send a query that is mapped to the above intent. Since the response to detectIntent() is of type List, I print the length of the List and key/value of each Message in the List.
    var request = Dialogflow.getRequestTextInput(query, "en-US");
var response = await df.detectIntent(request, sessionPath);

List<GoogleCloudDialogflowV2IntentMessage> payloads = response.queryResult.fulfillmentMessages;
debugPrint("Got response length: ${payloads.length}");
debugPrint(response.toString());

GoogleCloudDialogflowV2IntentMessage firstEntry = payloads[0];
Map<String, dynamic> payload0 = firstEntry.payload;
payload0.forEach((key, value) => debugPrint("Key: $key  Value: $value"));

debugPrint("Printing second entry");
GoogleCloudDialogflowV2IntentMessage secondEntry = payloads[1];
Map<String, dynamic> payload1 = secondEntry.payload;
payload1.forEach((key, value) => debugPrint("Key: $key  Value: $value"));

debugPrint("Printing third entry");
GoogleCloudDialogflowV2IntentMessage thirdEntry = payloads[2];
Map<String, dynamic> payload2 = thirdEntry.payload;
payload2.forEach((key, value) => debugPrint("Key: $key  Value: $value"));

Here are the scenarios and my observations for each scenario:
Scenario 1: Slider button for using responses from Default tab as first responses is ENABLED.
Observations:

*

*Count of responses returned is 3

*Printing first element of list => key/value of custom payload is printed

*Printing second element of list => program throws an Unhandled exception(The method 'forEach' was called on null). This makes sense because there is no payload object in the Facebook response (see JSON).

Scenario 2: Slider button for using responses from Default tab as first responses is DISABLED.
Observations:

*

*Count of responses returned is 2. Why?

*The program then throws an Unhandled exception(The method 'forEach' was called on null).

Scenario 3: Delete the Facebook response, so the only response for the intent is the custom payload in Default tab.
Observations:

*

*Response count is 2.

*Printing first two elements of the response list returns duplicates, i.e. identical key/value pairs.

*Attempting to print the third element throws exception(RangeError), which makes sense since array only has 2 elements)

My questions:

*

*Why are the lengths/counts different in each scenario? Is there a way to introspect the different response objects to figure out what each is composed of?

*It appears the order of elements in the response differs, based on whether the slider button is Enabled/Disabled. Why?
If enabled (count=3): Element 0 has the custom payload, Element 1 has the Facebook quick reply payload, Element 2 has the custom payload (duplicate).
If disabled (count=2): Element 0 has the Facebook quick reply payload, Element 1 has the custom payload.

*The response list often contains duplicates. Scenario 3 above is one example. Another example is, say for Scenario 1, I query the title (instead of payload). Now all 3 elements are printed, with the first and third elements duplicated.

A: Just to be clear, the length that you are counting are the objects inside response.queryResult.fulfillmentMessages.
Below is the raw printed response.queryResult.fulfillmentMessages for reference of the bulleted answers:
Got response length:3
[payload {
  fields {
    key: "replies"
    value {
      list_value {
        values {
          string_value: "option 1"
        }
        values {
          string_value: "option 2"
        }
      }
    }
  }
  fields {
    key: "text"
    value {
      string_value: "this is some text!"
    }
  }
}
platform: FACEBOOK
, quick_replies {
  title: "What can I help you with today?"
  quick_replies: "Facebook option 1"
  quick_replies: "Facebook option 2"
}
platform: FACEBOOK
, payload {
  fields {
    key: "replies"
    value {
      list_value {
        values {
          string_value: "option 1"
        }
        values {
          string_value: "option 2"
        }
      }
    }
  }
  fields {
    key: "text"
    value {
      string_value: "this is some text!"
    }
  }
}
]

Will answer your 3 questions based on the order of the bullets.

*

*You can just print the raw response.queryResult.fulfillmentMessages to examine the differences in the total number of objects. In the above example the 3 objects are the ff:

index[0] will be the payload object of the Default Response
index[1] will be the quick_replies inside facebook platform
index[2] will be the payload object inside facebook platform.

*

*When you disable the "Use responses from the DEFAULT tab as the first responses." slider button, this means that, from the above example, payload object of the Default Response will be omitted that's why the count of length will be 2 only. Namely, the quick_replies inside facebook platform and the payload object inside facebook platform.

*The elements are not duplicate. Based your sample screenshot, the first key-value are the payload of the Default Response while the second key-value are the payload of the Facebook Platform.
As you can see on my above sample raw output, it has an indicator "platform: FACEBOOK" which means the custom payload response is for facebook platform.


text:
Q: Frobenius homomorphism Its easy to proof that any non-zero field homomorphism is injective:
Proof
Assume that $\exists a, b\in F: a\neq b~~and~~\psi(a)=\psi(b)$ then:
$$\psi(1)=\psi((a-b)^{-1}(a-b))=\psi((a-b)^{-1})\cdot 0,$$
$$\forall x\in F:~~\psi(x)=\psi(x\cdot 1)=\psi(x)\cdot\psi(1)=\psi(x)\cdot0=0.$$
So, $\psi\equiv 0.$
$$~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\square$$
But lets consider Frobenius homomorphism of algebraically closed field $F$:
$$F\ni x\stackrel{\Phi}{\longmapsto} x^p\in F.$$
Equation
$$x^p-a=0$$
have p different roots. So, $\Phi$ isn't injective. Where is mistake?
Thanks.

A: Over a field of characteristic $p$ such an equation has either a single root or no roots at all. If $\xi$ is one solution of the equation $x^p-a=0$, then $\xi^p=a$. Consequently
$$
x^p-a=x^p-\xi^p=(x-\xi)^p,
$$
and $\xi$ is a root of multiplicity $p$.
The mistake was assuming that the $p$ roots would be distinct.


text:
Q: mysql triggers to multiply two column values by using triggers i have 4 columns in my table, vrms,irms,total,id.
i have created a trigger  where i want to insert the result of the trigger in another table.
  my code:
    CREATE TRIGGER total_sum BEFORE INSERT ON meter5
    FOR EACH ROW BEGIN
    INSERT INTO hourly
    SELECT vrms,irms,id,
    NEW.irms * NEW.vrms AS total;
    END
error:
not allowed to return a resultset from a trigger in mysql.

A: You need the trigger to be after insert something as
delimiter //
create trigger total_sum after insert on meter5
for each row
begin
 insert into hourly (id,vrms,irms,total) values (new.id,new.vrms,new.irms,new.vrms*new.irms);
end ; //
delimiter ;


text:
Q: Java encode image URL correctly I have a problem with the encoding of image URLs on my website and I tried 2 different encoding methods but they both have problems.
For example my image file has the following name: "Some special Characters;.jpg"
If I use URLEncoder.encode(imageName, "UTF-8"); I get the following URL:
/some/url/Some+special+Characters%3B_92631.jpg

If I use UrlEscapers.urlPathSegmentEscaper().escape(imageName) I get:
/some/url/Some%20special%20Characters;_63414.jpg

I tried to find the correct URL of the image and I found this one:
/some/url/Some%20special%20Characters%3B_63414.jpg

It looks like URLEncoder is not encoding spaces correctly while URLEscapers does not encode the semicolon. Other special characters like ! or , work without any problems.
How can I encode my URL correctly?


text:
Q: need help Setting QoS via command line (telnet or ssh) I have read on this post: http://www.dd-wrt.com/phpBB2/viewtopic.php?p=1047158#1047158 that "QoS on the DD-WRT is broken via GUI" i need help setting up Services Priority, Interface Priority, Netmask Priority, etc trought telnet or ssh, please i need help
also after trying htb/fq_codel, discovered that it is not giving me full ul speed (does not work as supposed to),then tried codel and pie, found they work as intended, however when i tried to enable TCP-Packet Priority (SYN, FIN, RST), Services Priority and some Netmask Priority im not able to access my home server (http and ftp). also  im trying to use htb/pie under qos because i discovered/think that it is more efficient than fq_codel but now it has messed all up, because i can not access my home server (http). ftp is not working as well, please help


text:
Q: REST vs SOAP C# Requester I have read a lot of articles that say that the RESTfull services should be faster than SOAP services.
I tried to test this claim by creating two RESTFull servies: RESTCaller and RESTCalled and another two ASMX services: SOAPCaller and SOAPCalled.
The idea is that RESTCaller sends iCount requests to RESTCalled and returns the total execution time RESTResponseTime, and SOAPCaller sends the same iCount requests to SOAPCalled and returns the total exection time SOAPResponseTime.
Notice that the four services are on my local machine.
Unexpectedly, SOAPResponseTime is a bit less than RESTResponseTime.
Is there any clue of the reason of this unexpected results?

A: If you are focusing on which approach is "faster", you're focusing on the wrong features that differentiate REST from SOAP.  REST and SOAP are two different philosophies (though, SOAP is really more an example of the RPC philosophy than a philosophy of its own).  They are generally not interchangeable.  Your application design will be heavily influenced by which approach you choose to follow. For any non-trivial application, your performance is going to depend on your back-end code, not whether you use REST or SOAP.
Do not let the results of these tests be the deciding factor on which way you choose to go.


text:
Q: Nested Expected Value that Aren't Independent I'd like to mention this is a homework problem and I am interested in the process of finding the answer, not the answer itself.
The problem is, we have:
A random variable X uniformly distributed on the interval [L-S, L+S]
A random variable Y uniformly distributed on the interval [X-S, X+S]
Where 0 < S < L
We are looking to find E[XY], My understanding is that if X and Y had been independent we could have used the property:
E[XY] = E[X]E[Y] since cov[X,Y] would have been equal to zero. (And if I am not mistaken, Y is dependent on X in this case).
Is it mathematically correct to substitute X's min and max possible values into the interval [X-S, X+S] as to say that Y is uniformly distributed on that interval: [L-2S, L+2S]?
Then, that E[XY] = L^2?
If not, how would I need to look at the problem? Is it possible to calculate cov(X,Y) directly?
Thanks for any help :)

A: $E[XY] = E[E[XY|X]] = E[X E[Y|X] ] = E[X X] = E[X^2]$. Now you need to compute $E[X^2]$.

A: it is because Y is uniforn on [X-S,  X+S]  given X that E[Y|X]=X.
Since X is uniformly distributed on [L-S, L+S] to evaluate E[X$^2$] you integrate x$^2$/(2S) dx over the interval [L-S, L+S] to get your answer.


text:
Q: UndHandled Exception Has Occured i have some problem with my visual studio this is some logcat from visual studio
Severity    Code    Description Project File    Line
Error       Error : DEP6100 : The following unexpected error occurred during bootstrapping stage 'Connecting to the device '30F105C9-681E-420b-A277-7C086EAD8A4E'.':
DeviceException - Deployment failed because no Windows Phone was detected. Make sure a phone is connected and powered on.   Kelompok1
Error       Error : DEP6200 : Bootstrapping 'Device' failed. Device cannot be found. Deployment failed because no Windows Phone was detected. Make sure a phone is connected and powered on.    Kelompok1

then i have some clue in here
System.Exception
To install this application you need either a Windows developer license or a sideloading-enabled system.

Deployment of package App.a033e7614.afc07.a40e2.a80a7.aac85aa4b485c_1.0.0.0_x86_NorthAmerica_8wekyb3d8bbwe failed because no valid license or sideloading policy could be applied. A developer license (http://go.microsoft.com/fwlink/?LinkId=233074) or enterprise sideloading configuration (http://go.microsoft.com/fwlink/?LinkId=231020) may be required.
   at Microsoft.VisualStudio.DesignTools.HostUtility.Platform.AppContainerProcessDomainFactory.CreateDesignerProcess(String applicationPath, String clientPort, Uri hostUri, IDictionary environmentVariables, Int32& processId, Object& processData)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.ProcessDomainFactory.ProcessIsolationDomain..ctor(ProcessDomainFactory factory, IIsolationBoundary boundary, AppDomainSetup appDomainInfo, IIsolationTarget isolationTarget, String baseDirectory)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.ProcessDomainFactory.CreateIsolationDomain(IIsolationBoundary boundary)
   at Microsoft.VisualStudio.DesignTools.HostUtility.Platform.AppContainerProcessDomainFactory.CreateIsolationDomain(IIsolationBoundary boundary)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.IsolationBoundary.Initialize()
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.Primitives.IsolationBoundary.CreateInstance[T](Type type)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedObjectFactory.Initialize()
   at Microsoft.VisualStudio.DesignTools.DesignerHost.Services.VSIsolationService.CreateObjectFactory(IIsolationTarget isolationTarget, IObjectCatalog catalog)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolationService.CreateLease(IIsolationTarget isolationTarget)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.IsolatedDesignerService.CreateLease(IIsolationTarget isolationTarget, CancellationToken cancelToken, DesignerServiceEntry& entry, IServiceProvider serviceOverrides)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.IsolatedDesignerService.IsolatedDesignerView.CreateDesignerViewInfo(CancellationToken cancelToken)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedTaskScheduler.InvokeWithCulture[T](CultureInfo culture, Func`2 func, CancellationToken cancelToken)
   at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.IsolatedTaskScheduler.<>c__DisplayClass10_0`1.<StartTask>b__0()
   at System.Threading.Tasks.Task`1.InnerInvoke()
   at System.Threading.Tasks.Task.Execute()

can anyone help me?

A: I had the same issue and I solved it by enabling Developer Mode for my windows phone.
GOTO:

*

*SETTINGS

*Phone UPDATE AND SECURITY

*FOR DEVELOPERS

*SELECT DEVELOPER MODE. scroll down and:

*Select MAKE your device visible to USB connections and your local network.

Hope this helps as it solved it for me and it will ask you to deploy the solution before running on your device.

A: Had the issue again today and could not even see the phone in windows  explorer and this time the solution was that Visual Studio had an update that needed to be applied as well as the phone had an update ready to be installed.
Once both updated I could see the phone in windows explorer and was able to deploy the app to the phone.  Hope this helps.


text:
Q: How to do logout using retrofit in android I would like to do logout function in my android application. First, I use retrofit to do login and now, I want to logout using retrofit. I have one button (logout) in FinalConfirm.java, When I click it, I want to do logout.
private void LoginUser() {
    NetworkEngine.getInstance().postLogin(edt_login_email_phone.getText().toString(), edt_login_password.getText().toString(), new Callback<User>() {
        @Override
        public void success(User user, Response response) {
            if (chk_login_remember_password.isChecked()) {
                StoreUtil.getInstance().saveTo("users", user);
            }
            Intent intent = new Intent(LoginActivity.this, FirstActivity.class);
            startActivity(intent);
        }

        @Override
        public void failure(RetrofitError arg0) {

        }
    });
}


text:
Q: Getting logs for Azure Container Instance that freezes We have an Azure Container instance that seems to be freezing under heavy load. And we are able to cause this through a load test. I am not looking for the exact solution to that right now, but what I am confused about is that I can't seem to get any logs from the Container Instance when this happens that would tell me exactly what is going.
My instance is Docker container that runs a NodeJS application.  I added Application Insights to the application, and have been successful in getting any exceptions that arise from the application itself.  But when we experience the freezing behavior, it is not actually getting to the application inside the container, so Application Insights doesn't help me in this case.
Also, if I go to my Container Instance in Azure, and look under the Events tab, I am not seeing any kind of error, or anything really that would tell me my container instance is in a "not-working" state, even though we are not able to reach it.

A: What do you see in the "Logs" and "Connect" tab in the Azure portal?
Can you also check the overview page in the Azure portal to see the CPU/memory/network usage?

A: You can use the Azure CLI command az container attach to check the container instance state and also the logs. There are three ways to get the different logs, see Retrieve container logs and events in Azure Container Instances. The restart policy will also help when the container instance gets some problems on it.


text:
Q: firefox, chromium, and brave browsers force http to https on docker container localhost:8889 Step 1
I dockerized some legacy php 5.3 app
in some folder on Ubuntu 22.04.1 LTS
docker-compose.yml
version: "3.9"
services:
  # docker-compose up
  # works with Mysql db and with Xdebug.
  app:
    build:
      context: .
      dockerfile: .docker/Dockerfile
    depends_on:
      - mysql
    restart: always
    ports:
      - '${APP_PORT}:80'
    volumes:
      - .:/var/www/html/srv/mipo
    environment:
      DB_HOST: mysql
      DB_USER: '${DB_USER}'
      DB_PASSWORD: '${DB_PASSWORD}'
      DB_DATABASE: '${DB_DATABASE}'
      # @link:https://www.youtube.com/watch?v=9MhHQJjMulk
      XDEBUG_CONFIG: "remote_host=host.docker.internal remote_enable=1 remote_connect_back=1"
      PHP_IDE_CONFIG: "serverName=localhost"

# at mipo-test/protected/config/database.php
# 'connectionString' => 'mysql:host=mysql;port=3306;dbname=yii_davidson_copy',
  mysql:
    image: mysql:5.5
    restart: always
    ports:
      - '${DB_HOST_PORT}:3306'
    volumes:
      - dbdata:/var/lib/mysql
    environment:
      MYSQL_DATABASE: '${MYSQL_DATABASE}'
      MYSQL_ROOT_PASSWORD: '${MYSQL_ROOT_PASSWORD}'

volumes:
  dbdata:

Dockerfile
FROM phpstorm/php-56-apache-xdebug-25

RUN docker-php-ext-install pdo_mysql \
    && a2enmod rewrite \
&& rm -f /etc/apache2/sites-available/* \
&& rm -f /etc/apache2/sites-enabled/* \
&& a2enmod rewrite

COPY .docker/httpd-foreground /usr/local/bin/
COPY .docker/vhost.conf /etc/apache2/sites-available/000-default.conf
COPY . /var/www/html/srv/mipo

RUN ln -s /etc/apache2/sites-available/000-default.conf \
/etc/apache2/sites-enabled/000-default.conf \
&& chmod +x /usr/local/bin/httpd-foreground \
&& chown -R www-data:www-data /var/www/html/srv/mipo \
&& chmod 777 -R /var/www/html/srv/mipo

WORKDIR /var/www/html/srv/mipo

RUN chmod +x /usr/local/bin/httpd-foreground

EXPOSE 80

CMD ["httpd-foreground"]

vhost.conf
<VirtualHost *:80>
    ServerName localhost

    DocumentRoot /var/www/html/srv/mipo

    <Directory "/var/www/html/srv/mipo">
        # use mod_rewrite for pretty URL support
        RewriteEngine on

        # if $showScriptName is false in UrlManager, do not allow accessing URLs with script name
        RewriteRule ^index.php/ - [L,R=404]

        # If a directory or a file exists, use the request directly
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d

        # Otherwise forward the request to index.php
        RewriteRule . index.php
        ### YII additions

        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
        Require all granted

    </Directory>

    ErrorLog /dev/stderr
    CustomLog /dev/stdout combined
</VirtualHost>

httpd-foreground
#!/bin/bash
set -e

# Apache gets grumpy about PID files pre-existing
rm -f /usr/local/apache2/logs/httpd.pid
source /etc/apache2/envvars && exec apachectl -D FOREGROUND

avraham@avraham-IdeaPad-L3-15ITL6:/var/www/wz/davidson/mipo-test$ docker ps
CONTAINER ID   IMAGE           COMMAND                  CREATED          STATUS          PORTS                                         NAMES
1ddbe01eaf9b   mipo-test_app   "docker-php-entrypoi…"   32 seconds ago   Up 30 seconds   0.0.0.0:8888->80/tcp, :::8888->80/tcp         mipo-test_app_1
99740e8fddf5   mysql:5.5       "docker-entrypoint.s…"   3 hours ago      Up 31 seconds   0.0.0.0:13307->3306/tcp, :::13307->3306/tcp   mipo-test_mysql_1
avraham@avraham-IdeaPad-L3-15ITL6:/var/www/wz/davidson/mipo-test$

and it worked in firefox by http://localhost:8888
$ curl --verbose -L http://localhost:8888
*   Trying 127.0.0.1:8888...
* Connected to localhost (127.0.0.1) port 8888 (#0)
> GET / HTTP/1.1
> Host: localhost:8888
> User-Agent: curl/7.81.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 302 Found
< Date: Wed, 14 Dec 2022 17:46:14 GMT
< Server: Apache/2.4.25 (Debian)
< X-Powered-By: PHP/5.6.40
< Location: /dashboard/
< Content-Length: 0
< Content-Type: text/html; charset=UTF-8
<
* Connection #0 to host localhost left intact
* Issue another request to this URL: 'http://localhost:8888/dashboard/'
* Found bundle for host localhost: 0x55c35fc40ff0 [serially]
* Can not multiplex, even if we wanted to!
* Re-using existing connection! (#0) with host localhost
* Connected to localhost (127.0.0.1) port 8888 (#0)
> GET /dashboard/ HTTP/1.1
> Host: localhost:8888
> User-Agent: curl/7.81.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 302 Found
< Date: Wed, 14 Dec 2022 17:46:14 GMT
< Server: Apache/2.4.25 (Debian)
< X-Powered-By: PHP/5.6.40
< Set-Cookie: PHPSESSID=ed04279896a644c270343c37abf8077f; path=/
< Expires: Thu, 19 Nov 1981 08:52:00 GMT
< Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
< Pragma: no-cache
< Set-Cookie: PHPSESSID=aff7d70cc34295026fb8d8b520fcc991; path=/
< Set-Cookie: dashboard_=a47300809cc366cc7f5283df983a40385c6009bda%3A4%3A%7Bi%3A0%3Bs%3A5%3A%22guest%22%3Bi%3A1%3Bs%3A5%3A%22guest%22%3Bi%3A2%3Bi%3A18000%3Bi%3A3%3Ba%3A8%3A%7Bs%3A2%3A%22id%22%3Bs%3A2%3A%2268%22%3Bs%3A9%3A%22user_role%22%3Bi%3A1%3Bs%3A9%3A%22user_name%22%3Bs%3A5%3A%22Guest%22%3Bs%3A9%3A%22user_type%22%3Bs%3A1%3A%224%22%3Bs%3A14%3A%22user_back_role%22%3Bs%3A2%3A%2210%22%3Bs%3A9%3A%22user_perm%22%3Bs%3A15%3A%2211_view%3B19_view%22%3Bs%3A17%3A%22user_modules_perm%22%3Ba%3A2%3A%7Bs%3A5%3A%22order%22%3Bs%3A4%3A%22view%22%3Bs%3A30%3A%22activity%2FroomOccupancyTimeline%22%3Bs%3A4%3A%22view%22%3B%7Ds%3A24%3A%22user_modules_perm_update%22%3Bi%3A1671039974%3B%7D%7D; expires=Wed, 14-Dec-2022 22:46:14 GMT; Max-Age=18000; path=/
< Location: http://localhost:8888/dashboard
< Content-Length: 0
< Content-Type: text/html; charset=UTF-8
<
* Connection #0 to host localhost left intact
* Issue another request to this URL: 'http://localhost:8888/dashboard'
* Found bundle for host localhost: 0x55c35fc40ff0 [serially]
* Can not multiplex, even if we wanted to!
* Re-using existing connection! (#0) with host localhost
* Connected to localhost (127.0.0.1) port 8888 (#0)
> GET /dashboard HTTP/1.1
> Host: localhost:8888
> User-Agent: curl/7.81.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 302 Found
< Date: Wed, 14 Dec 2022 17:46:14 GMT
< Server: Apache/2.4.25 (Debian)
< X-Powered-By: PHP/5.6.40
< Set-Cookie: PHPSESSID=507b0536633ef1583757985c1c21ce5d; path=/
< Expires: Thu, 19 Nov 1981 08:52:00 GMT
< Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
< Pragma: no-cache
< Set-Cookie: PHPSESSID=68fdffe47dd2b1740883bd77ce33387c; path=/
< Set-Cookie: dashboard_=67d9f27ff40a268e89c0fcd49b54fd85d7617751a%3A4%3A%7Bi%3A0%3Bs%3A5%3A%22guest%22%3Bi%3A1%3Bs%3A5%3A%22guest%22%3Bi%3A2%3Bi%3A18000%3Bi%3A3%3Ba%3A8%3A%7Bs%3A2%3A%22id%22%3Bs%3A2%3A%2268%22%3Bs%3A9%3A%22user_role%22%3Bi%3A1%3Bs%3A9%3A%22user_name%22%3Bs%3A5%3A%22Guest%22%3Bs%3A9%3A%22user_type%22%3Bs%3A1%3A%224%22%3Bs%3A14%3A%22user_back_role%22%3Bs%3A2%3A%2210%22%3Bs%3A9%3A%22user_perm%22%3Bs%3A15%3A%2211_view%3B19_view%22%3Bs%3A17%3A%22user_modules_perm%22%3Ba%3A2%3A%7Bs%3A5%3A%22order%22%3Bs%3A4%3A%22view%22%3Bs%3A30%3A%22activity%2FroomOccupancyTimeline%22%3Bs%3A4%3A%22view%22%3B%7Ds%3A24%3A%22user_modules_perm_update%22%3Bi%3A1671039975%3B%7D%7D; expires=Wed, 14-Dec-2022 22:46:15 GMT; Max-Age=18000; path=/
< Location: http://localhost:8888/dashboard
< Content-Length: 0
< Content-Type: text/html; charset=UTF-8

.
.
.

* Mark bundle as not supporting multiuse
< HTTP/1.1 302 Found
< Date: Wed, 14 Dec 2022 17:46:34 GMT
< Server: Apache/2.4.25 (Debian)
< X-Powered-By: PHP/5.6.40
< Set-Cookie: PHPSESSID=36045b9806a8f6e6af86439602540f6e; path=/
< Expires: Thu, 19 Nov 1981 08:52:00 GMT
< Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
< Pragma: no-cache
< Set-Cookie: PHPSESSID=e7b47ba2ccb26e557ff25ef0defd86e5; path=/
< Set-Cookie: dashboard_=7e42ce5af703a90da1fe0db91faf7de75e1fbb71a%3A4%3A%7Bi%3A0%3Bs%3A5%3A%22guest%22%3Bi%3A1%3Bs%3A5%3A%22guest%22%3Bi%3A2%3Bi%3A18000%3Bi%3A3%3Ba%3A8%3A%7Bs%3A2%3A%22id%22%3Bs%3A2%3A%2268%22%3Bs%3A9%3A%22user_role%22%3Bi%3A1%3Bs%3A9%3A%22user_name%22%3Bs%3A5%3A%22Guest%22%3Bs%3A9%3A%22user_type%22%3Bs%3A1%3A%224%22%3Bs%3A14%3A%22user_back_role%22%3Bs%3A2%3A%2210%22%3Bs%3A9%3A%22user_perm%22%3Bs%3A15%3A%2211_view%3B19_view%22%3Bs%3A17%3A%22user_modules_perm%22%3Ba%3A2%3A%7Bs%3A5%3A%22order%22%3Bs%3A4%3A%22view%22%3Bs%3A30%3A%22activity%2FroomOccupancyTimeline%22%3Bs%3A4%3A%22view%22%3B%7Ds%3A24%3A%22user_modules_perm_update%22%3Bi%3A1671039995%3B%7D%7D; expires=Wed, 14-Dec-2022 22:46:35 GMT; Max-Age=18000; path=/
< Location: http://localhost:8888/dashboard
< Content-Length: 0
< Content-Type: text/html; charset=UTF-8
<
* Connection #0 to host localhost left intact
* Maximum (50) redirects followed
curl: (47) Maximum (50) redirects followed

I stopped these containers.
Step 2
Recreated the same folder in other location,
set a bit different .env variables, ports and etc..,
launched by
/var/www/wz/mipo-iqdesk-testing/davidson$ docker-compose up --build

Yet this time when opened in firefox
http://localhost:8889/ => https://localhost:8889/ => SSL_ERROR_RX_RECORD_TOO_LONG
I had no intentions to use SSL, same apache vhost.conf file worked in Step 1
yet fails in other location with SSL error.
$ curl --verbose -L http://localhost:8889
*   Trying 127.0.0.1:8889...
* Connected to localhost (127.0.0.1) port 8889 (#0)
> GET / HTTP/1.1
> Host: localhost:8889
> User-Agent: curl/7.81.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 301 Moved Permanently
< Date: Wed, 14 Dec 2022 17:24:56 GMT
< Server: Apache/2.4.25 (Debian)
< Location: https://localhost:8889//
< Content-Length: 309
< Content-Type: text/html; charset=iso-8859-1
<
* Ignoring the response-body
* Connection #0 to host localhost left intact
* Clear auth, redirects scheme from HTTP to https
* Issue another request to this URL: 'https://localhost:8889//'
* Found bundle for host localhost: 0x559b267feff0 [serially]
* Can not multiplex, even if we wanted to!
* Hostname localhost was found in DNS cache
*   Trying 127.0.0.1:8889...
* Connected to localhost (127.0.0.1) port 8889 (#1)
* ALPN, offering h2
* ALPN, offering http/1.1
*  CAfile: /etc/ssl/certs/ca-certificates.crt
*  CApath: /etc/ssl/certs
* TLSv1.0 (OUT), TLS header, Certificate Status (22):
* TLSv1.3 (OUT), TLS handshake, Client hello (1):
* (5454) (IN), , Unknown (72):
* error:0A00010B:SSL routines::wrong version number
* Closing connection 1
curl: (35) error:0A00010B:SSL routines::wrong version number

Then changed 8889 to 18889, rebuilt and
http://localhost:18889/
was forced to https://localhost:18889/
with same error.
Any ideas?


text:
Q: How to interpret the results of a Discrete Fourier Transform I'm trying to understand the Discrete Fourier Transform so that I can understand the Fast Fourier Transform so that I can write a program to calculate it. I know that there are existing libraries that already do this, but if I use one of them I won't understand the maths behind the DFT.
I understand the general theory that you run different frequencies through the DFT and when the frequency matches a frequency in the signal, you get a spike in the amplitude and that the phase of the signal frequency can also be measured.
What I don't understand is which frequencies are represented in the results, and if the amplitude is normalised.
I've been mucking around with signals with only 8 data points. It seems that the wavelengths measured are $8/1$, $8/2$, $8/3$, etc. and the amplitudes seem to be multiplied by 8. I don't understand the usefulness of frequency 0, because it just sums all the data points.
I am wondering, if I have a signal that only is a sine wave at Concert A (440 Hz) with an amplitude of 1, sampled 44100 times per second (CD sample rate), and I do a DFT on the first 2048 samples, how do I detect the frequency at 440 Hz? The wavelength is 100.23 data points, which repeats 20.43 times in my sample. If I understand the measurable frequencies, they must be integer fractions of the sample size, so $2048/20=430.66$ or $2048/21=452.20$. Do I get a partial match for both close frequencies? If this is the case, how do I recognise that the true frequency is 440 Hz? What do the result data look like (the 2048 transformed values)?

A: The discrete Fourier transform implicitly regards the input data as periodic. The length of the input data is an integer multiple of the frequencies that the output data correspond to. If you generate the input data from a sinusoidal that has a different period that doesn't evenly divide the length of the data, then you're effectively creating a jump at the point where the first data point follows the last in the periodic continuation. A jump has appreciable Fourier components at all frequencies, and this is superimposed on your signal.
Nevertheless, you do get a signal with a clear maximum around the input frequency. I tried this using this online FFT calculator. In your case, as you calculated, we'd expect the maximum to be around the $21$st and $22$nd output data point (with the first data point corresponding to frequency $0$), and indeed, the first $40$ output values are:
30.322000,0.000000
30.391603,-0.332305
30.619103,-0.635705
30.983132,-0.983397
31.541176,-1.314554
32.258933,-1.685996
33.213385,-2.076468
34.383753,-2.509669
35.850294,-2.989665
37.679693,-3.538320
39.950279,-4.172808
42.781442,-4.897551
46.400390,-5.801462
51.088228,-6.910079
57.343876,-8.338977
66.017176,-10.282208
78.721064,-13.088380
98.974578,-17.487260
136.068697,-25.448952
225.318492,-44.421047
727.024048,-150.774758
-543.414483,118.240910
-191.999756,43.727082
-114.594042,27.275221
-80.661116,20.008091
-61.661208,15.918785
-49.536603,13.289953
-41.141647,11.459233
-35.002598,10.087933
-30.321248,9.041060
-26.630074,8.216618
-23.664950,7.534937
-21.230810,6.967688
-19.199079,6.488785
-17.492157,6.083581
-16.004951,5.723743
-14.733225,5.416510
-13.616822,5.138707
-12.640339,4.905611
-11.768659,4.665358

So it seems you must have been doing something wrong when you got spikes all over the place at roughly the same amplitude.
You can actually calculate the output in closed form in this case by writing the sinusoidals in terms of complex exponentials and summing the resulting partial geometric series.
Edit:
Here's that last suggestion written out.
You have the time-domain signal $\sin2\pi\nu t$ with $\nu=440\text{Hz}$, and you sample it at the frequency $f=44100\text{Hz}$, so you have the samples
$$
s_k=\sin\frac{2\pi\nu k}f=\frac1{2\mathrm i}\left(\exp\left(\frac{2\pi\mathrm i\nu k}f\right)-\exp\left(-\frac{2\pi\mathrm i\nu k}f\right)\right)
$$
for $0\le k\lt n$, with $n=2048$. Performing a discrete Fourier transform on these samples yields
\begin{eqnarray*}
\tilde s_j
&=&
\sum_{k=0}^{n-1}s_k\exp\left(\frac{2\pi\mathrm i jk}n\right)
\\
&=&
\sum_{k=0}^{n-1}\frac1{2\mathrm i}\left(\exp\left(\frac{2\pi\mathrm i\nu k}f\right)-\exp\left(-\frac{2\pi\mathrm i\nu k}f\right)\right)\exp\left(\frac{2\pi\mathrm i jk}n\right)
\\
&=&
\frac1{2\mathrm i}\sum_{k=0}^{n-1}\left(\exp\left(2\pi\mathrm i\left(\frac jn+\frac\nu f\right)k\right)-\exp\left(2\pi\mathrm i\left(\frac jn-\frac\nu f\right)k\right)\right)
\\
&=&
\frac1{2\mathrm i}\sum_{k=0}^{n-1}\left(\omega_{j+}^k-\omega_{j-}^k\right)
\\
&=&
\frac1{2\mathrm i}\left(\frac{1-\omega_{j+}^n}{1-\omega_{j+}}-\frac{1-\omega_{j-}^n}{1-\omega_{j-}}\right)\end{eqnarray*}
with $\omega_{j\pm}=2\pi\mathrm i\left(\frac jn\pm\frac\nu f\right)$. The second term dominates and is maximal at $\frac jn=\frac\nu f$ (which in your case is at the fractional value $j=\frac{n\nu}f$). It's a phase factor times
$$
\frac{\sin n\pi\left(\frac jn-\frac\nu f\right)}{\sin\pi\left(\frac jn-\frac\nu f\right)}\;,
$$
which is a discrete periodic analogue of the $\operatorname{sinc}$ function. Fitting to this functional form might improve your estimate of the frequency from the output data of the Fourier transform.


text:
Q: Get row of functions from a matrix of functions Before overwhelming you with examples where I try to encapsulate every aspect of my issue I'll try to just state the problem as simply as possible:
If f11 , ... , fnm is n*m real valued funtions that I wish to evaluate m at a time in n steps, through some higher order function b i.e.
v = []
f1 = @(x) [f11(x) f12(x) ... f1m(x)]
v = [v b(f1)]
f2 = @(x) [f21(x) f22(x) ... f2m(x)]
v = [v b(f2)]

How would I solve this through iteration? i.e. something like this:
f = @(x) [f11(x) ... f1m(x) ; ... ; fn1(x) ... fnm(x)];
% now iterate over the rows of f
for i=1:n
    v = [v b(f(i,:)) ]
end

Here's an example of what I have (it grew in order to not miss out any details of my actual real-world problem but I have tried to make it as small as possible):
% 4 functions that take a 1x2 real valued vector as argument
% and return a real value
f11 = @(x) x(1) + x(2);
f12 = @(x) x(1) - x(2);
f21 = @(x) x(2) - x(1);
f22 = @(x) x(1) * x(2);

% we'll run function b for 2 steps, then 4 steps
steps = [2 4];

% start value
x = [1 2];
% vector to hold results
v = []

% get the result of passing the 1:st 2 functions to b with steps(1)
f1 = @(x) [f11(x) f12(x)];
v = [v ;b(x, f1, steps(1))]
% update x
x = v(end,:)

% add the result of passing the 2:nd 2 functions to b with steps(2)
f2 = @(x) [f21(x) f22(x)];
v = [v ;b(x, f2, steps(2))];
% update x
x = v(end,:)

Where b is a function defined as follows:
function [ X ] = b( x, f, n )
%   @param:
%   x = an 1x2 real valued vector
%   f = a real valued function returning
%       a 1x2 real valued vector
%   n = an integer defining the rows of return matrix
%
%   @return:
%   X = an nx2 real valued matrix defined as below

    X = zeros(n,2);
    for i=1:n
        % apply the functions on x
        a = f(x+1);
        b = f(x+2);
        % update x
        x = a+b
        % add x to return matrix
        X(i,:) = x;
    end
end

The above code could be generalized as:
% n*m functions that take a 1xm real valued vector as argument
% and return a real value
f11 = @(x) ... ;
f12 = @(x) ... ;
.
.
.
fnm = @(x) ... ;

% we'll run function b for a1 steps, then a2 steps, ... , then an steps
steps = [a1 a2 ... an];

% start value
x = [1 2 ... m];
% vector to hold results
v = []

% get the result of passing the 1:st m functions to b with steps(1)
f1 = @(x) [f11(x) ... f1m(x)];
v = [v ;b(x, f1, steps(1))]
% update x
x = v(end,:)

% add the result of passing the 2:nd m functions to b with steps(2)
f2 = @(x) [f21(x) ... f2m(x)];
v = [v ;b(x, f2, steps(2))];
% update x
x = v(end,:)

.
.
.

% add the result of passing the n:ed m functions to b with steps(n)
fn = @(x) [fn1(x) ... fnm(x)];
v = [v ;b(x, fn, steps(n))];
% update x
x = v(end,:)

Where b is any function that returns an steps(i) x m matrix.
I wonder if both the small concrete example and the general example should be solvable through a general iteration, something like this:
% let f hold all the functions as a matrix
f = @(x) [f11(x) ... f1m(x) ; ... ; fn1(x) ... fnm(x)];
% now iterate over the rows of f
for i=1:n
    v = [v ; b(x, f(i,:), steps(i)) ]
end

A: So the trick is in defining your functions as a cell matrix and then using some vectorization to solve the problem. This is the code that I came up with:
%First define your functions in a cell matrix
fn_mat = {@(x) x(1) + x(2), @(x) x(1) - x(2); ...
          @(x) x(2) - x(1), @(x) x(1) * x(2)};
%Store the sixe of this matrix in two variables
[n, m] = size(fn_mat);
%Number of steps
steps = [2, 4];
% start value
x = [1 2];
% vector to hold results
v = [];
%This will run the required code for n iterations
for ii = 1:n
    %This is the tricky part. What I have done is used arrayfun to run over
    %all the functions in the row defined by ii and pass x as an argument
    %each time. The rest is same as before
    fn = @(x) arrayfun(@(a, b) fn_mat{ii, a}(b{:}), 1:m, repmat({x}, 1, m));
    v = [v; b(x, fn, steps(ii))];
    x = v(ii, :);
end

For the current values, the output is:
v =
          12          -2
          26          28
         -28         -13
          30         610
        1160       38525
       74730    89497060

The for loop is general enough to accommodate any size of fn_mat.


text:
Q: Rails/Pundit - Restrict certain attributes to certain user roles So I'm using the Pundit gem to allow/disallow users to access routes, and it's working fine for that. I have a certain requirement where for users, both admin and non-admin can create a user, but only admin can restrict a user(Users are restricted by setting restricted_at to DateTime.now).
So the #create and #update actions are allowed to be accessed by both admin/non-admin, but it's the specific attribute I want to authorize.
My options are:

*

*I could just create the model, but nil the restricted_at(if set), if the user is non-admin

class UserPolicy
  def create?
    @record.assign_attributes({restricted_at: nil}) unless @user.admin?
    return true
  end
end

But I don't think this is the best way to do it. I'd much rather return an error here. However if I try to add an error like @record.errors.add(:restricted_at, "can only be set by admin"), then later in the controller when save is called, it'll revalidate, and since the models validations don't validate who is changing something.
So is there way to do this with Pundit? What makes the most sense from a user/UX perspective?
- Return a 401 Unauthorized if a non-admin tries to create a user with restricted_at set, or update the attribute on an existing user. I personally think this is bad because the users isn't unauthorized for the route, just for the model. And a blanket 401 doesn't explain WHY.
- Create the model, but just nix anything a non-admin does to that attribute, like I do above
- Some alternate where I either add a model error with Pundit(if possible) or in the controller(less ideal, i'd rather keep all the validation/permission stuff in the model or pundit. If I put logic in the controller, then I'll have validations in three places, the model, the controller, and pundit, which seems smelly to me)
Just to make it clear, those are the possibilites, but what I want, and what I think is best, is to NOT create the model (if a non admin sets the retricted_at on create), and return an error message.
How can I sort this out? Thanks.

A: One way to achieve that is to use different controllers and policy methods for admins and users. For instance:
class UsersController < ApplicationController

  def create
    @user = User.create(user_params)
    # ...
  end

  def update
    @user.update_attributes(user_params)
    # ...
  end

  private

  def user_params
    params.require(:user).permit(
      # permit only attributes that are accessible by non-admins
    )
  end
end

and there would be Admins::UsersController with actions that accept all available parameters:
class Admins::UsersController < ApplicationController
  before_action :authorize_user!

  # ...

  private

  def authorize_user!
    authorize @user, :admin_manage?
  end

  def user_params
    params.require(:user).permit(
      # permit all attributes that are accessible by admins
    )
  end
end

Then in the UserPolicy:
class UserPolicy
  def admin_manage?
    @user.admin?
  end
end


text:
Q: Dynamic callback url with omniauth strategies In my project im using omniauth-facebook(g+) gems to provide users with ability to create accoutns in 1 click. However after user signed in into facebook(g+) he's being redirected to callback url. In my case it looks like www.example.com/users/omniauth_callbacks/facebook
facebook actions looks like
def facebook
@user = User.find_by_email(ENV['omniauth'].email)
if @user
sign_in @user
redirect_to root_path
else
create_user_account(ENV['omniauth'])
end

But instead of redirect_to root_path i'd like to return user back to page where he called sign_in process. I tried to user redirect_to :back, but this throws me error with empty HTTP_REFERRER. Is there any other way to track controller and action before user start sign_in process and then store it and use after callback?

A: Omniauth itself doesn't provide any instrument to do so. However, you can implement something fairy simple by yourself. For example, you can store current url in cookie/session and redirect to it in your facebook method. Here's a similar answered question.

A: Answering own question. THere is piece of hash, that contains this information. Its stored in
request.env['omniauth.origin']


text:
Q: Bug with Bresenham's Line Drawing algorithm I'm trying to use Bresenham's Line Drawing Algorithm to draw a line on a 20x20 grid of tiles.
So basically, when the variable deltaerror (from the wiki) is greater than 1 (when the change in y is greater than the change in x), the y value becomes almost double what it should be. Hopefully, I explain it better in the comments of the code. I also think I found the source of the error, which I'll also explain in the comments.
This is the code I made, mostly copied from the pseudocode in the wiki.
public static void drawLine(Tile t1, Tile t2) {
    int dx = t2.x_index - t1.x_index;
    int dy = t2.y_index - t1.y_index;
    double error = 0;
    double d_error = Math.abs((double) dy / dx); // dx =/= 0, therefore no vertical lines

    // when d_error is greater than 1, the bug occurs

    int y = t1.y_index;
    if (d_error <= 1) { // if related acute angle is < 45 degrees
        if (dx < 0) { // line drawn towards left side of screen
            for (int x=t1.x_index; x>=t2.x_index; x--) {
                Board.tiles[x][y].setColour(Color.red);
                error += d_error;
                while (error >= 0.5) {
                    Board.tiles[x][y].setColour(Color.red);
                    y += dy > 0 ? +1 : -1;// this is where I think the error occurs. In the
                                          // wiki for the algorithm, this should be some
                                          // function sign(T) which "decides whether t is
                                          // positive or negative". I wasn't really sure
                                          // what this meant, so I just assumed it returned
                                          // -1 if it was negative and +1 if it was positive.
                                          // Also it's the only place where y is edited
                                          // that seems to be where the error is occurring.
                    error -= 1.0;
                }
            }
        } else if (dx > 0) { // line drawn towards right side of screen
            for (int x=t1.x_index; x<=t2.x_index; x++) {
                Board.tiles[x][y].setColour(Color.red);
                error += d_error;
                while (error >= 0.5) {
                    Board.tiles[x][y].setColour(Color.red);
                    y += dy > 0 ? +1 : -1;
                    error -= 1.0;
                }
            }
        }

    // update: switched x and y values when d_error is greater than 1.

    } else { // if related acute angle is > 45 degrees
        dx = t2.y_index - t1.y_index; // switch x and y values
        dy = t2.x_index - t1.x_index;

        d_error = Math.abs((double) dy / dx); // recalculate d_error
        y = t1.x_index;
        if (dx < 0) { // line drawn towards left side of screen
            for (int x=t1.y_index; x>=t2.y_index; x--) {
                Board.tiles[x][y].setColour(Color.red);
                error += d_error;
                while (error >= 0.5) {
                    Board.tiles[x][y].setColour(Color.red);
                    y += dy > 0 ? +1 : -1;
                    error -= 1.0;
                }
            }
        } else if (dx > 0) { // line drawn towards right side of screen
            for (int x=t1.y_index; x<=t2.y_index; x++) {
                Board.tiles[x][y].setColour(Color.red);
                error += d_error;
                while (error >= 0.5) {
                    Board.tiles[x][y].setColour(Color.red);
                    y += dy > 0 ? +1 : -1;
                    error -= 1.0;
                }
            }
        }
    }
}

Thanks for your help!
EDIT: Switched x and y values when d_error is greater than 1. The line disappears when the slope is above 1 and below -1.

A: To quote from a quick google-result:
http://www.math.ubc.ca/~cass/courses/m308-02b/projects/puhalovic/#alldirections
"With slopes greater than 1 or less than -1, we must take the previous implementation and swap all x and y values to "move" the calculations back into the "First Octant"."
IOW: The textbook implementation of the bresenham only works for lines with (in your terms) d_error<=1. You'll have to implement the swapping mentioned in the link above.


text:
Q: Excel VBA Costum ribbon tab order I'm trying to make a custom tab for others with some macro's.
I found this article: How to add a custom Ribbon tab using VBA?
In this article, the reply of Roi-Kyi Bryant is very helpful and works great for me.
But I have one question about it. Can I reorder the tabs with this VBA code? I know its possible to move it by myself when I click on the ribbon with the right button on the mouse and choose edit ribbon.
any ideas?
The code I use from Roi-Kyi Bryant is as following:
Sub LoadCustRibbon()

Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String

hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"

ribbonXML = "<mso:customUI      xmlns:mso='http://schemas.microsoft.com/office/2009/07/customui'>" &     vbNewLine
ribbonXML = ribbonXML + "  <mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + "    <mso:qat/>" & vbNewLine
ribbonXML = ribbonXML + "    <mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + "      <mso:tab id='reportTab' label='Reports' insertBeforeQ='mso:TabFormat'>" & vbNewLine
ribbonXML = ribbonXML + "        <mso:group id='reportGroup' label='Reports' autoScale='true'>" &             vbNewLine
ribbonXML = ribbonXML + "          <mso:button id='runReport' label='PTO' "   & vbNewLine
ribbonXML = ribbonXML + "imageMso='AppointmentColor3'      onAction='GenReport'/>" & vbNewLine
ribbonXML = ribbonXML + "        </mso:group>" & vbNewLine
ribbonXML = ribbonXML + "      </mso:tab>" & vbNewLine
ribbonXML = ribbonXML + "    </mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + "  </mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + "</mso:customUI>"

ribbonXML = Replace(ribbonXML, """", "")

Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile

End Sub


text:
Q: JQuery Bootstrap-slider function within AJAX/another Function I am using the JQuery bootstrap-slider setValue and this works:
$("#sensor1slide").slider('setValue', [30, 85], false);

However, I want to update the slider value with some values returned from an AJAX call, within another function, like this:
function LoadData() {

    $.ajax({
        url: '/SensorDatas/LoadSettings',
        type: 'GET',
        contentType: 'application/json;',
        dataType: "json",
        async: true,
        processData: false,
        cache: false,
        success: function (result) {
            $("#sensor1slide").slider('setValue', [result.min, result.max], false);
        },
        error: function (xhr, ajaxOptions, thrownError) { alert(xhr.responseText); $("#loading").val("Error"); }

    })
}

When I place the same (previously working and recognized) function in this way, I get a error from the browser console:
TypeError: $(...).slider is not a function
$("#sensor1slide").slider('setValue', [result.sensor1min, result.sensor1max], fa...

I guess the question might be a general one, rather than specific to this function, in that how do you implement a JQuery function with another function for it still be be recognized?