text:
Q: Firebase toObject with ref With cloud firestore, you can convert a document to your object with document.toObject(YourClass.class); where the class's variables match those in your database.  However, if one of the variables in the database is a reference, which data type would you use in the java class?  Note that I need to not only store it in my data model but retrieve it and set it with the override methods of the form:
protected MyDataModel(Parcel in) {
    mString = in.readString();
}

and
@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(mString);
}

If I use a DocumentReference, then in writeToParcel(), how would I write it?  Also, how would I read it in the protected Parcel in constructor?  I have tried writeSerializable() and readSerializable() but DocumentReference does not implement Serializable.

A: I haven't used the Java API yet but I imagine you'll want to use the DocumentReference type. Here are some links in the firebase documentation:
DocumentReference

CollectionReference

getDocumentReference

A: If you need to serialize a DocumentReference, use its getPath() method to get a string that describes the document's location in the database.  To deserialize that path string back into a DocumentReference, use FirebaseFirestore.getInstance().document(path).
When you have conversions like this to make, sometimes it more convenient to write all the code yourself rather than using the built-in object serialization provided by the Firestore SDK.

A: I had the same problem with document.toObject(YourClass.class);
I have an Event class, this class contains the id (document id) and a reference to another collection subCategoryReference.
I have created simples converters on my Event
For example:
val event = document
      .toObject(Event::class.java)
      .withId<Event>(document.id)
      .withReference<Event>((document.data["subCategoryReference"] as DocumentReference).path)

In my Event class as you guessed I have two function withId and withReference
that look like this:
fun <T : Event?> withId(id: String): T {
  this.id = id
  return this as T
}

fun <T : Event?> withReference(reference: String): T {
  this.subCategoryRef = reference
  return this as T
}

Your class variables must have different names from your firestore variables/fields (just the variables you want to apply the converter on) - see the pic below
In my case on firestore, the reference field (variable) called subCategoryReference and in the Event class the variable name is subCategoryRef.
Let me know if you didn't get me.
I hope it helps...
Firestore console

Event Class


text:
Q: Let two different item use same adapter and each data of item will not to be replaced by other item in RecyclerView I want to make my app with two item(Post and Ad) in the same RecyclerView.
But my item will be replaced by another item, not insert it.
How can I fix it!
I want the right side, but now my code is the left side and will be crashed!

Here is my Adapter:
public class PostCardImageAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    public static final int Post_Layout = 0;
    public static final int AD_Layout = 1;

    private Context mContext;
    private ArrayList<PostCard> mData;

    private int mAdCount;
    public static NativeAd nativeAd = HomePageActivity.nativeAd;

    public PostCardImageAdapter(Context context, ArrayList<PostCard> data) {
        this.mContext = context;
        this.mData = data;
    }

    public int getmAdCount(){
        mAdCount = mData.size() / 2;
        return mAdCount;
    }

    @Override
    public int getItemViewType(int position) {

        /*if(mAdCount != 0 && position >= dataItemCount){
            return AD_Layout;
        }

        else{
            return Post_Layout;
        }*/

        if(position!=0 && (position % 2 == 0)){
            return AD_Layout;
        }

        else{
            return Post_Layout;
        }
    }

    public static class PostViewHolder extends RecyclerView.ViewHolder {
        private ImageView postcard_userIcon;
        private TextView postcard_name;
        private TextView postcard_time;
        private TextView postcard_postText;
        private ImageView postcard_postPic;
        private TextView postcard_likes;
        private TextView postcard_comments;

        public PostViewHolder(View postView) {
            super(postView);
            postcard_userIcon = (ImageView) postView.findViewById(R.id.postcard_userIcon);
            postcard_name = (TextView) postView.findViewById(R.id.postcard_name);
            postcard_time = (TextView) postView.findViewById(R.id.postcard_time);
            postcard_postText = (TextView) postView.findViewById(R.id.postcard_postText);
            postcard_postPic = (ImageView) postView.findViewById(R.id.postcard_postPic);
            postcard_likes = (TextView) postView.findViewById(R.id.postcard_likes);
            postcard_comments = (TextView) postView.findViewById(R.id.postcard_comments);
        }
    }

    public static class AdViewHolder extends RecyclerView.ViewHolder {

        NativeAdLayout nativeAdContainer;
        TextView nativeAdTitle;
        TextView sponsoredLabel;
        TextView nativeAdBody;
        TextView nativeAdSocialContext;

        AdIconView nativeAdIcon;
        MediaView nativeAdMedia;

        Button nativeAdCallToAction;

        //LinearLayout adChoicesContainer;

        public AdViewHolder(View adView) {
            super(adView);
            nativeAdContainer = adView.findViewById(R.id.native_ad_container);
            nativeAdTitle = adView.findViewById(R.id.native_ad_title);
            sponsoredLabel = adView.findViewById(R.id.native_ad_sponsored_label);
            nativeAdBody = adView.findViewById(R.id.native_ad_body);
            nativeAdSocialContext = adView.findViewById(R.id.native_ad_social_context);

            nativeAdIcon = adView.findViewById(R.id.native_ad_icon);
            nativeAdMedia = adView.findViewById(R.id.native_ad_media);

            nativeAdCallToAction = adView.findViewById(R.id.native_ad_call_to_action);

            /*adChoicesContainer = adView.findViewById(R.id.ad_choices_container);
            AdOptionsView adOptionsView = new AdOptionsView(mLayoutInflater.this, nativeAd, nativeAdContainer);
            adChoicesContainer.removeAllViews();
            adChoicesContainer.addView(adOptionsView, 0);*/
        }
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        if(viewType == Post_Layout){
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.postcard_layout, parent, false);
            return new PostViewHolder(v);
        }

        else {
          View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.native_ad_layout, parent, false);
          return new AdViewHolder(v);
      }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

        if(holder instanceof PostViewHolder){
            PostCard post = mData.get(position);

            ((PostViewHolder) holder).postcard_name.setText(post.name);
            ((PostViewHolder) holder).postcard_time.setText(post.time);
            ((PostViewHolder) holder).postcard_postText.setText(post.postText);
            ((PostViewHolder) holder).postcard_likes.setText(post.likes);
            ((PostViewHolder) holder).postcard_comments.setText(post.comments);
            Glide.with(mContext)
                    .load(post.userIconUrl)
                    .into(((PostViewHolder) holder).postcard_userIcon);
            Glide.with(mContext)
                    .load(post.postPicUrl)
                    .into(((PostViewHolder) holder).postcard_postPic);
        }

        else if(holder instanceof AdViewHolder){

            AdViewHolder adViewHolder = (AdViewHolder) holder;

            View adView = NativeAdView.render(mContext, nativeAd);
            adViewHolder.nativeAdTitle.setText(nativeAd.getAdvertiserName());
            adViewHolder.sponsoredLabel.setText(nativeAd.getSponsoredTranslation());
            adViewHolder.nativeAdBody.setText(nativeAd.getAdBodyText());
            adViewHolder.nativeAdSocialContext.setText(nativeAd.getAdSocialContext());

            adViewHolder.nativeAdCallToAction.setVisibility(nativeAd.hasCallToAction() ? View.VISIBLE : View.INVISIBLE);
            adViewHolder.nativeAdCallToAction.setText(nativeAd.getAdCallToAction());

            List<View> clickableViews = new ArrayList<>();
            clickableViews.add(adViewHolder.nativeAdTitle);
            clickableViews.add(adViewHolder.nativeAdCallToAction);

            nativeAd.registerViewForInteraction(
                    adView,
                    adViewHolder.nativeAdMedia,
                    adViewHolder.nativeAdIcon,
                    clickableViews);
        }
    }

    @Override
    public int getItemCount() {
        return mData.size() + getmAdCount();
    }
}

Here is the Log:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: playground.com.pgapp, PID: 29719
    java.lang.IndexOutOfBoundsException: Index: 5, Size: 5
        at java.util.ArrayList.get(ArrayList.java:411)
        at playground.com.pgapp.PostCardImageAdapter.onBindViewHolder(PostCardImageAdapter.java:156)
        at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
        at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
        at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
        at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
        at android.support.v7.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:286)
        at android.support.v7.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:343)
        at android.support.v7.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:359)
        at android.support.v7.widget.GapWorker.prefetch(GapWorker.java:366)
        at android.support.v7.widget.GapWorker.run(GapWorker.java:397)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:241)
        at android.app.ActivityThread.main(ActivityThread.java:6274)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

A:     public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {

            if(holder instanceof PostViewHolder){
                int index = position - position / 2;
                PostCard post = mData.get(index);

                ((PostViewHolder) holder).postcard_name.setText(post.name);
                ((PostViewHolder) holder).postcard_time.setText(post.time);
                ((PostViewHolder) holder).postcard_postText.setText(post.postText);
                ((PostViewHolder) holder).postcard_likes.setText(post.likes);
                ((PostViewHolder) holder).postcard_comments.setText(post.comments);
                Glide.with(mContext)
                        .load(post.userIconUrl)
                        .into(((PostViewHolder) holder).postcard_userIcon);
                Glide.with(mContext)
                        .load(post.postPicUrl)
                        .into(((PostViewHolder) holder).postcard_postPic);
            }

            ...
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to log make output without buffering from stdout and stderr I am having a problem with logging to output from an automated build.
The build is done with a Makefile and the makefile utility.
The problem is that normal output like compiler command lines go to stdout and compile errors go to stderr.
I want to get the output from the build as it would show on the screen. So something like:
(stdout) CC -c file.cpp
(stderr) Compile error at file.cpp line 232, blah blah blah
(stdout) CC -c file2.cpp

What I tried (from a ksh script) is:
make -k > build.log 2> build.log
This results in a single log file but the problem is that the streams are buffered and so the result in the log file is all mixed up.
I could capture the output into 2 separate log files but then I would have no info on how to glue them back together into a single log file.
Is there a way to turn off buffering for stdout and stderr in this case?

A: Try this
make -k > build.log 2>&1

A: make -k > build.log 2>&1

This should work better for you because it is not redirecting stderr and stdout separately, but redirecting stderr to stdout, which should make the buffering sync up.
If you want to log it to a file as well as print it to the console:
make -k 2>&1 | tee build.log

A:
I could capture the output into 2
  separate log files but then I would
  have no info on how to glue them back
  together into a single log file.

Gluing them back together is tricky but there is a right answer for that too, and it works! See "How do I save or redirect stdout and stderr into different files?" by Vivek Gite.

A: setbuf(stdout,NULL); ->turns off stdout buffering


text:
Q: Why such a complicated definition of recursion for $\mathbb{N}$ in HoTT? The HoTT book defines $\mathbb{N}$ to have $0:\mathbb{N}, succ: \mathbb{N\to N}$ and a recursion constructor $\prod_{C:\mathcal{U}}C\to (\mathbb{N}\to C\to C)\to \mathbb{N}\to C$ with a certain defining relation.
I'm wondering why the constructor is not more simply defined as a term  $rec:\prod_{C:\mathcal{U}}C\to (C\to C)\to \mathbb{N}\to C$ with defining relations $rec(C,c_0,f,succ(n)) \equiv f(rec(C,c_0,f,n))$ and $rec(C,c_0,f,0) \equiv c_0$ ?
Indeed that recursion type would correspond to $\mathbb{N}$ being an "NNO" (natural numbers object) by analogy with a topos for instance; and the one given by the HoTT book seems equivalent by currying :
Indeed we can define a term $Hrec : \prod_{C:\mathcal{U}}C\to (\mathbb{N}\to C\to C)\to \mathbb{N}\to C$ as $\lambda C:\mathcal{U}. \lambda c_0: C. \lambda c_s: (\mathbb{N}\to C\to C).\lambda n : \mathbb{N}. pr_2(rec(\mathbb{N}\times C, (0,c_0),H(c_s),n)) $ where $H(c_s) :\equiv \lambda n:\mathbb{N}.\lambda x:C. (succ(n),c_s(n)(x))$.
What I'm saying is just that the recursion they define seems to be a special case of the one I propose (of course the converse is also true); and that mine seems way simpler in its definition.
While writing a proof that the defining equations the HoTT book gives for their $rec$ were satisfied by my  $Hrec$, I realized that I used $x \equiv (pr_1(x),pr_2(x))$ for $x:A\times B$, which isn't true : we "only" have $uniq_{A\times B} : x=(pr_1(x),pr_2(x))$ and so my constructor doesn't actually allow to define the one in HoTT (or at least it doesn't seem to allow that), although there is probably a term $p: Hrec(blabla) = rec_{HoTT}(blabla)$ : is that the case ?
Am I right in thinking that the reason I just gave is the one why the HoTT book didn't go with my "simpler looking" recursion operator ?
But in that case, why assume we have this stronger one ? And why not go further, like have $u_{n+1}$ depend on $n,u_n$ and all the $u_k$'s below, or I don't know, something that wouldn't be judgmentally equal either but that would be stronger ? Indeed, classically, most, if not all ($\mathbb{N}$-)recursion principles derive from the one I gave, even the more sophisticated-looking ones, so why give this specific one ?
( a question that might be more complicated to answer and even formalize is : is there a way to prove that my recursion operator doesn't allow us to build the one from the HoTT book ?)
EDIT : I just realized that the recursion operator proposed in HoTT makes way more sense if we want to allow an induction operator to allow for dependent types. That is, if we have a dependent type $C:\mathbb{N}\to \mathcal{U}$, we can't just afford to have "$f:C\to C$" because it doesn't make sense, we have to have something like "$f_n:C(n)\to C(succ(n))$" and so there has to be a dependency in $n$ : hence $\mathbb{N}\to C\to C$ instead of $C\to C$. Is it the actual reason ?

A: I asked a very similar question last year on the Hott Cafe forum:
https://groups.google.com/forum/#!topic/hott-cafe/PQe7SI3nwcE
The answer is that the induction principle can indeed be derived from the recursion principle, however only if you have a judgemental eta rule for the recursor, which is not the case in the HoTT book.


text:
Q: Monitoring ReplicatedMap on Management center? There are tabs for Map, List, Queue, Executors etc in the left navigation pane of Management center.
But, I don't see any tab for ReplicatedMap. Is there a way I can query it?

A: We're working on adding RelpicatedMap view to the Management Center (No ETA at this point though). Meanwhile, you can use Scripts view to query replicated map using JavaScript or Groovy.


text:
Q: Installing Java8 in Dockerfile I have a Docker container in which I was installing Java/JDK in order to power Pentaho. Starting at some point withing the last ~9 days ( I believe ), I've been getting an error when trying to build this container.
I'm not sure if the speciic jdk has been archived by oracle, but I've spent a solid day trying to find a way around this one and hitting dead ends.
Looking for a PPA or active dist to get me out of this mess.
From the Dockerfile:
# Pentaho
ENV PDI_RELEASE=6.1 \
    PDI_VERSION=6.1.0.1-196 \
    PDI_HOME=/opt/pentaho-di \
    KETTLE_HOME=/pentaho-di

# Java
# auto validate license
RUN echo oracle-java8-installer shared/accepted-oracle-license-v1-1 select true | /usr/bin/debconf-set-selections && \
    echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" | tee /etc/apt/sources.list.d/webupd8team-java.list && \
    echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu trusty main" | tee -a /etc/apt/sources.list.d/webupd8team-java.list && \
    apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886 && \
    apt-get update && \
    apt-get -y install oracle-java8-installer unzip && \
    apt-get clean && \
    curl -sS -L -o /tmp/pdi-ce-${PDI_VERSION}.zip http://downloads.sourceforge.net/project/pentaho/Data%20Integration/${PDI_RELEASE}/pdi-ce-${PDI_VERSION}.zip && \
    unzip -q /tmp/pdi-ce-${PDI_VERSION}.zip -d $PDI_HOME && \
    rm /tmp/pdi-ce-${PDI_VERSION}.zip

Here's the failure I'm getting from the build:
2018-01-18T17:59:31.674ZUnpacking locales (2.19-18+deb8u10) ...
2018-01-18T17:59:32.569ZSelecting previously unselected package oracle-java8-installer.
2018-01-18T17:59:32.571ZPreparing to unpack .../oracle-java8-installer_8u151-1~webupd8~0_all.deb ...
2018-01-18T17:59:32.742Zdebconf: unable to initialize frontend: Dialog
debconf: (TERM is not set, so the dialog frontend is not usable.)
debconf: falling back to frontend: Readline
2018-01-18T17:59:32.966Zoracle-license-v1-1 license has already been accepted
2018-01-18T17:59:32.983ZUnpacking oracle-java8-installer (8u151-1~webupd8~0) ...
2018-01-18T17:59:33.245ZProcessing triggers for mime-support (3.58) ...
2018-01-18T17:59:33.636ZProcessing triggers for hicolor-icon-theme (0.13-1) ...
2018-01-18T17:59:33.644ZProcessing triggers for shared-mime-info (1.3-1) ...
2018-01-18T17:59:36.221ZSetting up java-common (0.52) ...
2018-01-18T17:59:36.333ZSetting up locales (2.19-18+deb8u10) ...
2018-01-18T17:59:36.421Zdebconf: unable to initialize frontend: Dialog
debconf: (TERM is not set, so the dialog frontend is not usable.)
debconf: falling back to frontend: Readline
2018-01-18T17:59:36.839ZGenerating locales (this might take a while)...
2018-01-18T17:59:36.842ZGeneration complete.
2018-01-18T17:59:36.877ZSetting up oracle-java8-installer (8u151-1~webupd8~0) ...
2018-01-18T17:59:36.969Zdebconf: unable to initialize frontend: Dialog
debconf: (TERM is not set, so the dialog frontend is not usable.)
debconf: falling back to frontend: Readline
2018-01-18T17:59:37.411ZNo /var/cache/oracle-jdk8-installer/wgetrc file found.
Creating /var/cache/oracle-jdk8-installer/wgetrc and
using default oracle-java8-installer wgetrc settings for it.
Downloading Oracle Java 8...
2018-01-18T17:59:38.406Z--2018-01-18 17:59:38--  http://download.oracle.com/otn-pub/java/jdk/8u151-b12/e758a0de34e24606bca991d704f6dcbf/jdk-8u151-linux-x64.tar.gz
Resolving download.oracle.com (download.oracle.com)...
2018-01-18T17:59:38.488Z184.84.129.202
Connecting to download.oracle.com (download.oracle.com)|184.84.129.202|:80...
2018-01-18T17:59:38.488Zconnected.
HTTP request sent, awaiting response...
2018-01-18T17:59:38.490Z302 Moved Temporarily
Location: https://edelivery.oracle.com/otn-pub/java/jdk/8u151-b12/e758a0de34e24606bca991d704f6dcbf/jdk-8u151-linux-x64.tar.gz [following]
--2018-01-18 17:59:38--  https://edelivery.oracle.com/otn-pub/java/jdk/8u151-b12/e758a0de34e24606bca991d704f6dcbf/jdk-8u151-linux-x64.tar.gz
2018-01-18T17:59:38.501ZResolving edelivery.oracle.com (edelivery.oracle.com)...
2018-01-18T17:59:38.635Z23.212.176.23, 2600:1408:10:397::2d3e, 2600:1408:10:3b5::2d3e
Connecting to edelivery.oracle.com (edelivery.oracle.com)|23.212.176.23|:443...
2018-01-18T17:59:38.636Zconnected.
2018-01-18T17:59:38.644ZHTTP request sent, awaiting response...
2018-01-18T17:59:38.738Z302 Moved Temporarily
Location: http://download.oracle.com/otn-pub/java/jdk/8u151-b12/e758a0de34e24606bca991d704f6dcbf/jdk-8u151-linux-x64.tar.gz?AuthParam=1516298498_6fba300d1f634adc9f84ee54d5966fce [following]
--2018-01-18 17:59:38--  http://download.oracle.com/otn-pub/java/jdk/8u151-b12/e758a0de34e24606bca991d704f6dcbf/jdk-8u151-linux-x64.tar.gz?AuthParam=1516298498_6fba300d1f634adc9f84ee54d5966fce
2018-01-18T17:59:38.738ZConnecting to download.oracle.com (download.oracle.com)|184.84.129.202|:80...
2018-01-18T17:59:38.739Zconnected.
2018-01-18T17:59:38.739ZHTTP request sent, awaiting response...
2018-01-18T17:59:38.758Z404 Not Found
2018-01-18 17:59:38 ERROR 404: Not Found.

2018-01-18T17:59:38.808Zdownload failed
Oracle JDK 8 is NOT installed.

A workaround I've been trying per SO and the internets' guidance:
RUN apt-get -y install software-properties-common python-software-properties && \
    add-apt-repository ppa:webupd8team/java && \
    apt-get update
RUN cd /var/lib/dpkg/info && \
    sed -i 's|JAVA_VERSION=8u151|JAVA_VERSION=8u161|' oracle-java8-installer.* && \
    sed -i 's|PARTNER_URL=http://download.oracle.com/otn-pub/java/jdk/8u151-b12/e758a0de34e24606bca991d704f6dcbf/|PARTNER_URL=http://download.oracle.com/otn-pub/java/jdk/8u161-b12/2f38c3b165be4555a1fa6e98c45e0808/|' oracle-java8-installer.* && \
    sed -i 's|SHA256SUM_TGZ="c78200ce409367b296ec39be4427f020e2c585470c4eed01021feada576f027f"|SHA256SUM_TGZ="6dbc56a0e3310b69e91bb64db63a485bd7b6a8083f08e48047276380a0e2021e"|' oracle-java8-installer.* && \
    sed -i 's|J_DIR=jdk1.8.0_151|J_DIR=jdk1.8.0_161|' oracle-java8-installer.*
RUN apt-get -y install oracle-java8-installer unzip

Unfortunately it looks like the jessie dist is missing -- here's the error:
(image: pre-deps) (service: rails_pre_deps) OK
(image: pre-deps) (service: rails_pre_deps) Get:1 http://security.debian.org jessie/updates InRelease [63.1 kB]
(image: pre-deps) (service: rails_pre_deps) Ign http://ppa.launchpad.net jessie InRelease
(image: pre-deps) (service: rails_pre_deps) Hit http://ppa.launchpad.net trusty InRelease
(image: pre-deps) (service: rails_pre_deps) Ign http://deb.debian.org jessie InRelease
(image: pre-deps) (service: rails_pre_deps) Hit http://deb.debian.org jessie-updates InRelease
(image: pre-deps) (service: rails_pre_deps) Hit http://deb.debian.org jessie Release.gpg
(image: pre-deps) (service: rails_pre_deps) Ign http://ppa.launchpad.net jessie Release.gpg
(image: pre-deps) (service: rails_pre_deps) Hit http://deb.debian.org jessie Release
(image: pre-deps) (service: rails_pre_deps) Ign http://ppa.launchpad.net jessie Release
(image: pre-deps) (service: rails_pre_deps) Err http://ppa.launchpad.net jessie/main amd64 Packages
(image: pre-deps) (service: rails_pre_deps)
(image: pre-deps) (service: rails_pre_deps) Err http://ppa.launchpad.net jessie/main amd64 Packages
(image: pre-deps) (service: rails_pre_deps)
(image: pre-deps) (service: rails_pre_deps) Err http://ppa.launchpad.net jessie/main amd64 Packages
(image: pre-deps) (service: rails_pre_deps)
(image: pre-deps) (service: rails_pre_deps) Err http://ppa.launchpad.net jessie/main amd64 Packages
(image: pre-deps) (service: rails_pre_deps)
(image: pre-deps) (service: rails_pre_deps) Err http://ppa.launchpad.net jessie/main amd64 Packages
(image: pre-deps) (service: rails_pre_deps)   404  Not Found

Apologies for the differences in output. One is coming from jet, and the other is from codeship.
Thanks for any help


text:
Q: SAML response and assertion is signed/unsigned? I have deployed and run spring saml sample successfully.  From SAML Response (IdP -> SP) shown below, can it be identified whether:

*

*the SAML response is signed or unsigned?

*the assertion is encrypted or not? (I guess it's encrypted)

*the assertion is signed or unsigned?

    <?xml version="1.0" encoding="UTF-8"?><samlp:Response xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified" Destination="https://MY_SP/spring-security-saml2-sample/saml/SSO" ID="_22bf0c00-9cfa-5dbb-7af7-d34eec7d9b6f" InResponseTo="we3977191e5g4try1b3g52j4f84e43f" IssueInstant="2016-07-22T08:22:41.568Z" Version="2.0">
       <Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">http://MY_ADFS_SERVER/adfs/services/trust</Issuer>
       <samlp:Status>
          <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
       </samlp:Status>
       <EncryptedAssertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
          <xenc:EncryptedData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Type="http://www.w3.org/2001/04/xmlenc#Element">
             <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc"/>
             <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
                <e:EncryptedKey xmlns:e="http://www.w3.org/2001/04/xmlenc#">
                   <e:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p">
                      <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
                   </e:EncryptionMethod>
                   <KeyInfo>
                      <ds:X509Data xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                         <ds:X509IssuerSerial>
                            <ds:X509IssuerName>CN=apollo, OU=R&D, O=RM5 Software Oy, L=Helsinki, S=Uusimaa, C=FI</ds:X509IssuerName>
                            <ds:X509SerialNumber>2343092425</ds:X509SerialNumber>
                         </ds:X509IssuerSerial>
                      </ds:X509Data>
                   </KeyInfo>
                   <e:CipherData>
                      <e:CipherValue>Mpz3raT40LBmwUfzz+a52+ryijTMqVqtnk8T2YOJ27Xs/dS
    jMZHShDfMGsD1wwXb2a2jGjpjCLgLWsZ1t8LWgxevSbmTZuGGSfAMhfdOwmJMijRYdKrHdiyn+syFUof
    0MDMykI135ulCL9MGWVUvR1pNz+W+tZzQKcQ+is6USH4OGnUKiMSaow==</e:CipherValue>
                   </e:CipherData>
                </e:EncryptedKey>
             </KeyInfo>
             <xenc:CipherData>
                <xenc:CipherValue>iefcMnnYFLtb
    EObkQpItoZk4tRuMDX9dqt1DucK91ZZRigHeQ2DuUYe2FZpGtQ2vFVtS2ycXSnVR2V4wx4Vd2VeR/G3I
    GHkqQ9GtOxv8RvkRtEbJTptmjoMT1t7ZNE4tn+hDmzMMK7Xy9f+xkk/z5IHvNKlscnsG/wXoRuMykKnJ
    tODd0ILiVF/ygQqY477lxVFDlaa4HH/rcx+DZOcDFiFjiuLj41dF1rdG90XCmWvr2BfUTzYl3SHakoyK
    AmmgesyCJQcHN54ckFiO/wvLttw09wdvC4sg92xlhhfGtQqMuvfT7YESOvHnC1FOEsf4CjoMaByZjwN2
    QBRHPRJTBPjwmfVgTk+g==</xenc:CipherValue>
             </xenc:CipherData>
          </xenc:EncryptedData>
       </EncryptedAssertion>
    </samlp:Response>

From debug log of my SP server, right after the above SAML response is parsed, below is seen.  This makes me confused whether the message and/or assertion has not been signed.
- Evaluating security policy of type 'org.opensaml.ws.security.provider.BasicSecurityPolicy' for decoded message
- Evaluating simple signature rule of type: org.opensaml.saml2.binding.security.SAML2HTTPPostSimpleSignRule
- HTTP request was not signed via simple signature mechanism, skipping
- SAML protocol message was not signed, skipping XML signature processing
- Successfully decoded message.

A: *

*SAML Response is NOT signed.

*SAML Assertion is encrypted. (you can see "EncryptedAssertion")

*SAML Assertion is NOT signed.

Try setting WantAssertionsSigned="true" in your SP metadata, exchange with IdP and check whether you receive signed SAML Response or not.
Refer: http://docs.spring.io/spring-security-saml/docs/current/reference/html/configuration-metadata.html


text:
Q: Elasticbeanstalk giving health check errors I keep getting the below error when I deploy my backend (NestJS) to the elasticbeanstalk. I am new to AWS, can any tell me what this error entails ? I have a health endpoint set up in my backend.
*1 connect() failed (111: Connection refused) while connecting to upstream, client: 10.0.74.74, server: , request: "GET /health HTTP/1.1", upstream: "http://127.0.0.1:8080/health", host: "10.0.87.89"

I get a 503 Service Unavailable: Back-end server is at capacity.
My backend shows that has successfully started at port 8080


text:
Q: How to combine two unrelated tables in Mysql There are two tables that are not related to each other(No foreign keys).
How to show them together in MySQL?
TABLE1

TABLE2

Result

A: Try This..
 SELECT t2.date, t1.name FROM table1 t1, table2 t2 ORDER BY t1.name ASC

A: You can use this too:
SELECT t2.date, t1.name
FROM table1 t1
CROSS JOIN table2 t2

A: Try simply
SELECT t2.date, t1.name FROM table1 t1, table2 t2

A: Try this: SELECT DATE, NAME FROM TABLE1, TABLE2

A: None of those will work.
If you want to learn how to do this properly, I'd suggest you take a look at this
http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/
CROSS JOIN is not what you are looking for.
SQL will not be able to process this query. What I suggest you do is to get both record sets with two different queries and then sort them by the field you want, using PHP/Python/C or whatever the code your app is based on. Just don't leave that to the MySQL server because it can't.


text:
Q: Reseting password for Azure Linux ARM VM gives ERROR I am resetting the password of a Linux(Redhat) VM in ARM Azure. Using following command.
I am getting a error as below ...

PS C:\WINDOWS\system32> azure vm reset-access rgname vmname -u hadoop -p redhat@123
  info:
Executing command vm reset-access
  + Looking up the VM "hadoop"
  + Installing extension "VMAccessForLinux", VM: "hadoop"
  error:   Long running operation failed with error: 'VM has reported a failure when processing extension 'VMAccessForLinu
  x'. Error message: "Enable failed.".'.
info:    Error information has been recorded to C:\Users\Amitkumar.patil.azure\azure.err
  error:   vm reset-access command failed

Error File Contains
            2016-05-05T09:21:14.934Z:
            { [Error: Long running operation failed with error: 'VM has reported a failure when processing extension 'VMAccessForLinux'. Error message: "Enable failed.".'.]
              stack: [Getter/Setter],
              request:
               { rawResponse: false,
                 queryString: {},
                 method: 'GET',
                 headers: { 'user-agent': 'WindowsAzureXplatCLI/0.9.15' },
                 url: 'https://management.azure.com/subscriptions/75706c1b-8db8-49f6-8295-1c36c0b4e0c3/providers/Microsoft.Compute/locations/eastus/operations/72d61126-96e0-407d-a28e-b724d7efee6e?api-version=2015-06-15' },
              response:
               { body: '{\r\n  "operationId": "72d61126-96e0-407d-a28e-b724d7efee6e",\r\n  "startTime": "2016-05-05T09:19:40.0598247+00:00",\r\n  "endTime": "2016-05-05T09:20:59.4442674+00:00",\r\n  "status": "Failed",\r\n  "error": {\r\n    "code": "VMExtensionProvisioningError",\r\n    "message": "VM has reported a failure when processing extension \'VMAccessForLinux\'. Error message: \\"Enable failed.\\"."\r\n  }\r\n}',
                 headers:
                  { 'cache-control': 'no-cache',
                    pragma: 'no-cache',
                    'content-length': '378',
                    'content-type': 'application/json; charset=utf-8',
                    expires: '-1',
                    'strict-transport-security': 'max-age=31536000; includeSubDomains',
                    'x-ms-served-by': '0309f20e-ba97-4cfa-a387-af57e4db0559_131067724814019554',
                    'x-ms-request-id': '4e2f8f12-06e7-4b8c-b76e-0e9706c7b490',
                    server: 'Microsoft-HTTPAPI/2.0, Microsoft-HTTPAPI/2.0',
                    'x-ms-ratelimit-remaining-subscription-reads': '14851',
                    'x-ms-correlation-request-id': 'a0e647c1-afda-4f0f-a02c-bc3cf0bced14',
                    'x-ms-routing-request-id': 'NORTHCENTRALUS:20160505T092114Z:a0e647c1-afda-4f0f-a02c-bc3cf0bced14',
                    date: 'Thu, 05 May 2016 09:21:14 GMT',
                    connection: 'close' },
                 statusCode: 200 },
              message: 'Long running operation failed with error: \'VM has reported a failure when processing extension \'VMAccessForLinux\'. Error message: "Enable failed.".\'.',
              code: 'VMExtensionProvisioningError',
              body:
               { operationId: '72d61126-96e0-407d-a28e-b724d7efee6e',
                 startTime: '2016-05-05T09:19:40.0598247+00:00',
                 endTime: '2016-05-05T09:20:59.4442674+00:00',
                 status: 'Failed',
                 error:
                  { code: 'VMExtensionProvisioningError',
                    message: 'VM has reported a failure when processing extension \'VMAccessForLinux\'. Error message: "Enable failed.".' } },
              __frame:
               { name: 'createOrUpdateVMExtension__18',
                 line: 248,
                 file: 'C:\\Program Files (x86)\\Microsoft SDKs\\Azure\\CLI\\lib\\commands\\arm\\vm\\virtualMachine.js',
                 prev:
                  { name: '_createOrUpdateExtension__38',
                    line: 1400,
                    file: 'C:\\Program Files (x86)\\Microsoft SDKs\\Azure\\CLI\\lib\\commands\\arm\\vm\\vmClient.js',
                    prev: [Object],
                    calls: 1,
                    active: false,
                    offset: 9,
                    col: 19 },
                 calls: 0,
                 active: false,
                 offset: 4,
                 col: 88 },
              rawStack: [Getter] }
            Error: Long running operation failed with error: 'VM has reported a failure when processing extension 'VMAccessForLinux'. Error message: "Enable failed.".'.
              <<< async stack >>>
              at createOrUpdateVMExtension__18 (C:\Program Files (x86)\Microsoft SDKs\Azure\CLI\lib\commands\arm\vm\virtualMachine.js:252:89)
              at _createOrUpdateExtension__38 (C:\Program Files (x86)\Microsoft SDKs\Azure\CLI\lib\commands\arm\vm\vmClient.js:1409:20)
              at setExtension__24 (C:\Program Files (x86)\Microsoft SDKs\Azure\CLI\lib\commands\arm\vm\vmClient.js:979:10)
              at __26 (C:\Program Files (x86)\Microsoft SDKs\Azure\CLI\lib\commands\arm\vm\vm.js:555:18)
              <<< raw stack >>>
                at PollingState.getCloudError (C:\Program Files (x86)\Microsoft SDKs\Azure\CLI\node_modules\ms-rest-azure\lib\pollingState.js:119:15)
                at C:\Program Files (x86)\Microsoft SDKs\Azure\CLI\node_modules\ms-rest-azure\lib\azureServiceClient.js:133:38
                at Object.async.whilst (C:\Program Files (x86)\Microsoft SDKs\Azure\CLI\node_modules\ms-rest-azure\node_modules\async\lib\async.js:621:13)
                at C:\Program Files (x86)\Microsoft SDKs\Azure\CLI\node_modules\ms-rest-azure\node_modules\async\lib\async.js:617:23
                at C:\Program Files (x86)\Microsoft SDKs\Azure\CLI\node_modules\ms-rest-azure\lib\azureServiceClient.js:109:20
                at C:\Program Files (x86)\Microsoft SDKs\Azure\CLI\node_modules\ms-rest-azure\lib\azureServiceClient.js:231:5
                at C:\Program Files (x86)\Microsoft SDKs\Azure\CLI\node_modules\ms-rest-azure\lib\azureServiceClient.js:399:12
                at retryCallback (C:\Program Files (x86)\Microsoft SDKs\Azure\CLI\node_modules\ms-rest-azure\node_modules\ms-rest\lib\filters\exponentialRetryPolicyFilter.js:140:9)
                at handleRedirect (C:\Program Files (x86)\Microsoft SDKs\Azure\CLI\node_modules\ms-rest-azure\node_modules\ms-rest\lib\filters\redirectFilter.js:36:9)
                at C:\Program Files (x86)\Microsoft SDKs\Azure\CLI\lib\util\utils.js:482:7

A: If I had to guess, I'd say that the 'azure vm reset-access' command has a bug. As the error message suggests, though, under the hood, it's just using the VMAccessForLinux extension, so you can use that directly to bypass the bug.
In Azure CLI 2.0, the command looks like:
az vm extension set -g YOUR_RESOURCE_GROUP_NAME --vm-name YOUR_LINUX_VM_NAME --publisher Microsoft.OSTCExtensions --name VMAccessForLinux --protected-settings '{"reset_ssh": true, "username": "YOUR_USERNAME", "password": "YOUR_NEW_PASSWORD"}'

It's been a while since I used Azure CLI 1.0, but If I recall correctly, it has an equivalent azure vm extension set command that takes the same parameters.
Hope this helps! For more examples of different configs (changing ssh keys and the like), check out this blog post:
https://negatblog.wordpress.com/2018/07/03/changing-admin-credentials-of-vms-and-scale-sets/


text:
Q: converting jpeg image to transparent png image I have an image with text and white background. I want to retain the text, i want to create a png image with that text and a transparent background. Could anyone guide me.
Thank u.

A: I hope this will guide you to what you want. You need to do something similar to following steps:

*

*Read the image,

*extract RGB values,

*create another image with ARGB
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

*And apply the operation similar to Image Thresholding to check the white background on image bi, If current pixel is white -> make that pixel transparant. Otherwise(for text image of other color) copy the pixel as it is.

*And finally save bi as PNG image using
ImageIO.write(bi, "PNG", new File("C:\yourImageName.PNG"));
Do some research.


text:
Q: Irreducible decomposition of a Dyadic operator Recently, I've been studying $SO(3)$ Group Theory for physics application and for a couple of days I'm struggling to understand how to get a 3D cartesian tensor, like: $T_{ij}=a_i\,b_j$ to be decomposed as $$\frac{\vec{a}\cdot\vec{b}}{3}\delta_{ij}+\frac{a_i\,b_j-a_j\,b_i}{2}+\left(\frac{a_i\,b_j+a_i\,b_j}{2}-\frac{\vec{a}\cdot\vec{b}}{3}\delta_{ij}\right),$$ i.e., this irreducible representation is invariant under rotation and it's commonly said that $3\otimes3=1+3+5$. I already know that a second order tensor can be decomposed as antisymmetric and symmetric parts, but I don't get it why in decomposition above there is a trace part (you may say that is because is a traceless tensor, but why it has to be?).

A: The so-called natural form of a rank $N$ tensor is symmetric in all its indices and is traceless. It has $2N+1$ degrees of freedom that transform like $2N+1$ order-$N$ spherical harmonics: $Y_{l=N}^{m}(\theta, \phi)$.
So for rank-2, the natural form is:
$$ N_{ij} = \frac 1 2 (T_{ij}+T_{ji}) - \frac 1 3 \delta_{ij} T_{kk}$$
$$ N_{ij} = S_{ij} - \frac 1 3 \delta_{ij} T_{kk}$$
where $S_{ij}$ refers to the symmetric part (but not trace free).
The relation between spherical($T^{l,m}$) form and cartesian is:
$$ T^{2,\pm 2} =  \frac 1 2 [S_{xx}-S_{yy}\pm 2iS_{xy}]$$
$$ T^{2,\pm 1} =  \frac 1 2 [S_{zx}\pm iS_{yz}]$$
$$ T^{2,0} =  \sqrt{\frac 2 3} S_{zz}$$
You will find that the $T^{2,m}$ are rotated just as the $Y_2^m(\theta,\phi)$ are.
At higher ranks, it gets involved. The symmetrized rank-3 tensor is:
$$ S_{ijk} = \frac 1 6 [T_{ijk}+T_{kij}+T_{jki}+T_{kji}+T_{jik}+T_{ikj}]$$
and the trace free version is:
$$ N_{ijk} = S_{ijk} - \frac 1 {30}[(\delta_{ij}+\delta_{ji})(T_{llk}+T_{lkl}+T_{kll})+ (\delta_{ik}+\delta_{ki})(T_{llj}+T_{ljl}+T_{jll})+(\delta_{kj}+\delta_{jk})(T_{lli}+T_{lil}+T_{ill})]$$
where
and the $(2\cdot 3+1)=7$ spherical tensors that transform like $Y_3^m$ are (according to my notes):
$$ T^{3,\pm3} = \frac 1 {\sqrt 8}[(-S_{xxx}+3S_{xyy}) \mp i(S_{yyy}-S_{xxy})]$$
$$ T^{3,\pm2} = \frac 1 2[-S_{xxz}-S_{yyz} \mp 2iS_{xyz}]$$
$$ T^{3,\pm 1} = \frac {\sqrt{15}} 3\big(\frac 1 {\sqrt 2}[\mp S_{zzz}-iS_{zzz}] + \frac 1 {\sqrt  8}[\mp(S_{xxx}-S_{xyy})+i(S_{yyy}\pm S_{xxy}]\big) $$
$$ T^{3,0} =\frac {\sqrt{10}} 3[\frac 1 {\sqrt 2}(S_{xzz}+iS_{yzz}) + S_{zzz}]$$
Rank-3 breaks down according to:
$${\bf 3} \otimes {\bf 3} \otimes {\bf 3} = {\bf 10} \oplus {\bf 8}  \oplus {\bf 8} \oplus {\bf 1} $$
(where the ${\bf 1}$ is the familiar $\epsilon_{ijk})$. So what happened in creating the natural form tensor $S_{ijk}$ is that we subtracted off a vector trace: $S_{ijj}$ from the original 10 degrees-of-freedom:
$${\bf 10} \rightarrow {\bf 7} + {\bf 3} $$
Likewise, the octet is split into a rank-2 like object and a vector trace:
$${\bf 8} \rightarrow {\bf 5} + {\bf 3} $$
See Physical Review A, "Irreducible fourt-rank Cartesian tensors", Andrews and Ghoul, Volume 25, Number 5,  Page 2647, [1992], for Rank-4, though it has typos in the indices, and looks something like this:


text:
Q: No "pull" in Git Gui? How can I make a pull using Git GUI tool? It seems there is no pull command anywhere.
Is there an equivalent menu option using Git GUI?
Any help will be appreciated.

A: There is also a way to add the pull command to git gui.
When you open GIT GUI you can open the tab Tools and choose Add option.
You can enter a name, and as command enter git pull
This will add an option under the Tools tab. Just click this and a git pull will be done.
Considering this answer: it's not because a pull can be done that it should be done

A: This entry in .gitconfig works nicely for me:
[guitool "Pull"]
cmd = git pull $(git for-each-ref --format='%(upstream:short)' $(git symbolic-ref -q HEAD) | tr / " ")

It automatically selects current remote branch.
Instruction above assumes that you've set your upstream prior. If you haven't done so then you can do it using command below. [NOTE: Run the command inside of your repository.]
git branch --set-upstream-to=origin/main master

Above command to set upstream is for a case where your remote is origin and current branch is main.

A: Well, I found this useful forum post:
https://web.archive.org/web/20200211180001/http://git.661346.n2.nabble.com/No-quot-pull-quot-in-git-gui-td1121058.html
A fetch and merge should be done.
It seems you need to go to "Remote" menu, then "Fetch from" option , in my case origin, and then go to "Merge Menu" and then "Local Merge...".


text:
Q: how do i run this .py code for a discord bot? This code isnt mine btw. I was trying to code a discord bot for the heck of it, i did basic stuff like it will respond to certain pieces of text in a channel, but i wanted to add mod stuff bc why not, saw this and idk how to use the command
async def kick(ctx, userName: discord.User):
    if True: #ctx.message.author.Permissions.administrator
        await BSL.kick(userName)
    else:
        permission_error = str('Sorry ' + ctx.message.author + ' you do not have permissions
to do that!')
        await BSL.send_message(ctx.message.channel, permission_error)

A: To use a discord bot you need to go through a lot of steps. Here is the things you need to do to be able to run this script of yours:

*

*Go to the application page on discord, and click the "New Application" button.

*Give the application a name, and go to the "Bot" tab, and then click "Add Bot" button, then give your bot a name.

*Keep the default settings for Public Bot (checked) and Require OAuth2 Code Grant (unchecked).

*Click on the "Copy" button under Token, and store this in a text file somewhere on your computer. (This is the bot's password).

*Go to the "OAuth2" tab. Then select "bot" under the "scopes" section.

*Select the permissions that your bot needs. (Do not overdo it).

*Click on the "Copy" button, and paste this URL into a browser tab.

*Choose a server to invite the bot to, and click "Authorize" (To add the bot, your account needs "Manage Server" permissions)

*Install the discord.py library to access discord API, by running: python3 -m pip install -U discord.py.

*Add these lines on top of your script for your bot:

import discord
import os

client = discord.Client()

@client.event

*

*And finally add client.run(TOKEN) to end on your script - where TOKEN is the token you copied earlier.

*Now that the bot is created and registered, you can simply type: python3 main.py to run it. (main.py can be something else, depending on what you named your bot file)


text:
Q: Differentiate active language between Simplified and Traditional Chinese Is there a way to differentiate between traditional and simplified chinese language without delving into country codes.
Using this …
[[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode]

… the language code for both is zh.
Is there a good way to query if the current language or locale is zh-HANS or zh-HANZ, without further distinction by country (zh_TW, zh_CN, etc.)?

A: You can try this: used NSLocal.preferredLanguages. Get array first one, it can be zh-Hant or zh-Hants.
func getCurrentLanguage() -> String {
   let languages = NSLocale.preferredLanguages()
   let currentLanguage = languages[0] as? String
   return currentLanguage ?? ""
}

A: Rewrite Zhengjie's answer in Swift 4:
func getCurrentLanguage() -> String {
    let languages = NSLocale.preferredLanguages
    let currentLanguage = languages[0]
    return currentLanguage
}


text:
Q: Confusion on C++ return reference from function I have been having some confusion on the reference in C++, so I did a little experiment with the following function
std::vector<float> & fun(std::vector<float> & x) {
    return x;
}

Then I call the function using the following two ways:
std::vector<float> x(10000);
std::vector<float> result1 = fun(x);
std::vector<float> & result2 = fun(x);

Now the variable result2 is indeed a reference of x, but result1 seems to be a copy of x instead of a reference. So here I am confused:
Why can I declare a non-reference variable to be the return value of a function that returns a reference?
Does C++ changes my returned reference to a non-reference variable because my declaration of result1 is not a reference?

A: That's basically the same as
std::vector<float> x(10000);
std::vector<float> & result2 = x;
std::vector<float> result1 = result2;

The language allows it since result2 is a reference of x, each mention of result2 is the same as x. You could see the reference as being an alias, result2 is an alias of x.

A: Since fun(x) simply accepts a reference to x and returns it, your code (on the left) is equivalent to the code on the right:
a std::vector<float> x(10000);          a std::vector<float> x(10000);

std::vector<float> result1 = fun(x);    std::vector<float> result1 = x;
std::vector<float> &result2 = fun(x);   std::vector<float> &result2 = x;

In other words, result1 becomes a copy of x, while result2 becomes a reference to x. That means result1 is distinct from x, while result2 and x refer to the same underlying data.
It's really no different to:
int a = 42;
int b = a;
int &c = a;

At that point, b is an independent copy that, if changed, will not affect the other two variables. However, since a and c refer to the same underlying data, changing one will affect the other.

A: There's no real change happening.
What happens is that a reference refers to something, and when you use the reference in an expression, you (usually) get what it refers to. So, if I have something like:
int x = 1;
int &rx = x;

std::cout << rx;

What gets printed out is the value of x--the reference gets dereferenced to get the value, and that's what gets printed out. Likewise, if I had something like:
int x = 1;
int y = 2;
int rx = x;
int ry = y;
int z = rx + ry;

...the compiler is going to dereference rx and ry to get the values of x and y. Then it adds those together, and assigns the result to z.
Summary
A reference is an alias for some object. Under most circumstances (essentially anything other than initializing another reference) using the reference in an expression uses the object that the reference refers to, not the reference itself.


text:
Q: Synchronize two tables in MySQL I am creating two websites. The thing common about both websites is the company tables.
What I want to do is this: If one company table is updated, the other company table is also updated accordingly.
Both databases are on the same server.
What would be the best way to do this? (Doing this via code is not possible, due to the type of framework I am using.)
I would prefer a solution at the database level.

A: MySQL can join tables across two different databases, so maybe you can get away with a single table. Otherwise, triggers would be useful to keep two tables in sync.


text:
Q: Cannot resolve (or import) Android widget OnEditorActionListener I am new to coding and keep getting errors when trying to use OnEditorActionListener to help perform an action once the user inputs data into EditText and presses "Go" on the softkeyboard.  I have searched and most solutions offered assume that OnEditorActionListener is already imported.
Articles used as a guide to generate my own code:
https://developer.android.com/training/keyboard-input/style.html
https://github.com/codepath/android_guides/wiki/Basic-Event-Listeners
My XML Code:
<EditText
        android:id="@+id/editTextCurrentBalance"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ems="10"
        android:imeOptions="actionGo"
        android:inputType="numberDecimal"
        android:singleLine="true">
        <requestFocus />
</EditText>

My Java Code (snippet):
import android.widget.TextView.OnEditorActionListener;

EditText editTextListener = (EditText) findViewById(R.id.editTextCurrentBalance);
editTextListener.setOnEditorActionListener(new OnEditorActionListener(){...});

First Error: " import android.widget.TextView.OnEditorActionListener; " gives me an error that says "Unused Import Statement" and the whole line of code is grey'd out.
Second Error: " Cannot Resolve Symbol 'setOnEditorActionListener' "
Fix Attempt: When I press CTRL + I, I get a message "No methods to implement have been found".
Appreciate any help!
UPDATE: My Java Code for the OnEditorActionListener was outside of the OnCreate method brackets.  Once put inside, the errors cleared up.

A: Hello and welcome to SO
1st error: well this is actually not an error, it's just a warning your IDE is giving you meaning you have imported a class you are not using. It's a good practice to remove any unused imports (Ctrl + Alt + O in Android Studio)
2nd error: I believe this one is popping up because you haven't imported EditText class, but I'm not sure
Anyway, take a loot at this
//We are import the classes you need here
import android.widget.EditText;
import android.widget.TextView;

//here is just the onCreate method from an Activity,
//I have left out most of the boilerplate code

public class MainActivity extends AppCompatActivity {
    //make sure you are placing the code in onCreate method, or
    //a method called from onCreate, or any method other life cycle
    //method that suits yours needs
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        /*snip*/

        //grabing the EditText object by it's ID you defined in the layout file
        //I have renamed the object to "editText" because "listener"
        //suffix made no sense here, it's an EditText class you are
        //crating, which is not a listener
        EditText editText = (EditText) findViewById(R.id.editTextCurrentBalance);

        //here we are creating a new anonymous class and setting to
        //trigger when an "Editor Action" happens on editTextListener
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                //do something here
                return false;
            }
        });
    }

Anonymous classes are just a simpler way of creating a new class if we don't intent to reuse that class somewhere else ie. it's specific to your current need
Hope this helps :) and good luck learning Android and Java


text:
Q: Issue with sonar-pmd-plugin for sonarqube5.5 I'm gettingbelow error when im trying to install pmd plugin in SonarQube5.5. Installation is successfull if I remove the plugin from extensions/plugins.
    Can anyone advice what could be doneto resolve the same.
    Thanks.
2016.05.18 16:30:15 INFO  ce[o.s.s.p.DefaultServerFileSyst`enter code here`em] SonarQube home: C:\ATT\sonarqube-5.5
2016.05.18 16:30:16 INFO  ce[o.e.plugins] [sonar-1463569153699] loaded [], sites []
2016.05.18 16:30:19 INFO  ce[o.s.c.c.CePluginRepository] Load plugins
2016.05.18 16:30:20 ERROR ce[o.s.ce.app.CeServer] Compute Engine startup failed
java.lang.NullPointerException: null
    at org.sonar.core.platform.PluginLoader.basePluginKey(PluginLoader.java:176) ~[sonar-core-5.5.jar:na]
    at org.sonar.core.platform.PluginLoader.defineClassloaders(PluginLoader.java:85) ~[sonar-core-5.5.jar:na]
    at org.sonar.core.platform.PluginLoader.load(PluginLoader.java:71) ~[sonar-core-5.5.jar:na]
    at org.sonar.ce.container.CePluginRepository.start(CePluginRepository.java:71) ~[sonar-ce-5.5.jar:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_91]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_91]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_91]
    at org.picocontainer.lifecycle.ReflectionLifecycleStrategy.invokeMethod(ReflectionLifecycleStrategy.java:110) ~[picocontainer-2.15.jar:na]
    at org.picocontainer.lifecycle.ReflectionLifecycleStrategy.start(ReflectionLifecycleStrategy.java:89) ~[picocontainer-2.15.jar:na]
    at org.sonar.core.platform.ComponentContainer$1.start(ComponentContainer.java:320) ~[sonar-core-5.5.jar:na]
    at org.picocontainer.injectors.AbstractInjectionFactory$LifecycleAdapter.start(AbstractInjectionFactory.java:84) ~[picocontainer-2.15.jar:na]
    at org.picocontainer.behaviors.AbstractBehavior.start(AbstractBehavior.java:169) ~[picocontainer-2.15.jar:na]
    at org.picocontainer.behaviors.Stored$RealComponentLifecycle.start(Stored.java:132) ~[picocontainer-2.15.jar:na]
    at org.picocontainer.behaviors.Stored.start(Stored.java:110) ~[picocontainer-2.15.jar:na]
    at org.picocontainer.DefaultPicoContainer.potentiallyStartAdapter(DefaultPicoContainer.java:1016) ~[picocontainer-2.15.jar:na]
    at org.picocontainer.DefaultPicoContainer.startAdapters(DefaultPicoContainer.java:1009) ~[picocontainer-2.15.jar:na]
    at org.picocontainer.DefaultPicoContainer.start(DefaultPicoContainer.java:767) ~[picocontainer-2.15.jar:na]
    at org.sonar.core.platform.ComponentContainer.startComponents(ComponentContainer.java:141) ~[sonar-core-5.5.jar:na]
    at org.sonar.ce.container.ComputeEngineContainerImpl.start(ComputeEngineContainerImpl.java:605) ~[sonar-ce-5.5.jar:na]
    at org.sonar.ce.ComputeEngineImpl.startup(ComputeEngineImpl.java:43) ~[sonar-ce-5.5.jar:na]
    at org.sonar.ce.app.CeServer$CeMainThread.startup(CeServer.java:176) [sonar-ce-5.5.jar:na]
    at org.sonar.ce.app.CeServer$CeMainThread.attemptStartup(CeServer.java:166) [sonar-ce-5.5.jar:na]
    at org.sonar.ce.app.CeServer$CeMainThread.run(CeServer.java:154) [sonar-ce-5.5.jar:na]
Java HotSpot(TM) 64-Bit Server VM warning: ignoring option MaxPermSize=160m; support was removed in 8.0

When Im Using sonar-pmd 2.5 without changes, below is the error:
2016.05.19 16:26:20 ERROR web[o.s.s.p.Platform] Fail to stop server - ignored
java.lang.IllegalStateException: Cannot stop.  Current container state was: CONSTRUCTED
    at org.picocontainer.lifecycle.DefaultLifecycleState.stopping(DefaultLifecycleState.java:72) ~[picocontainer-2.15.jar:na]
    at org.picocontainer.DefaultPicoContainer.stop(DefaultPicoContainer.java:794) ~[picocontainer-2.15.jar:na]
    at org.picocontainer.DefaultPicoContainer.stop(DefaultPicoContainer.java:799) ~[picocontainer-2.15.jar:na]
    at org.picocontainer.DefaultPicoContainer.stop(DefaultPicoContainer.java:799) ~[picocontainer-2.15.jar:na]
    at org.sonar.core.platform.ComponentContainer.stopComponents(ComponentContainer.java:173) ~[sonar-core-5.5.jar:na]
    at org.sonar.core.platform.ComponentContainer.stopComponents(ComponentContainer.java:168) ~[sonar-core-5.5.jar:na]
    at org.sonar.server.platform.platformlevel.PlatformLevel.stop(PlatformLevel.java:93) ~[sonar-server-5.5.jar:na]
    at org.sonar.server.platform.Platform.stopLevel234Containers(Platform.java:240) ~[sonar-server-5.5.jar:na]
    at org.sonar.server.platform.Platform.doStop(Platform.java:269) ~[sonar-server-5.5.jar:na]
    at org.sonar.server.platform.PlatformServletContextListener.stopQuietly(PlatformServletContextListener.java:59) [sonar-server-5.5.jar:na]
    at org.sonar.server.platform.PlatformServletContextListener.contextInitialized(PlatformServletContextListener.java:52) [sonar-server-5.5.jar:na]
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4812) [tomcat-embed-core-8.0.30.jar:8.0.30]
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5255) [tomcat-embed-core-8.0.30.jar:8.0.30]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.0.30.jar:8.0.30]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408) [tomcat-embed-core-8.0.30.jar:8.0.30]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398) [tomcat-embed-core-8.0.30.jar:8.0.30]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_91]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_91]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_91]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91]
2016.05.19 16:26:20 ERROR web[o.a.c.c.C.[.[.[/]] Exception sending context initialized event to listener instance of class org.sonar.server.platform.PlatformServletContextListener
java.lang.IllegalStateException: Fail to load plugin PMD [pmd]
    at org.sonar.server.plugins.ServerExtensionInstaller.installExtensions(ServerExtensionInstaller.java:74) ~[sonar-server-5.5.jar:na]
    at org.sonar.server.platform.platformlevel.PlatformLevel4.start(PlatformLevel4.java:687) ~[sonar-server-5.5.jar:na]
    at org.sonar.server.platform.Platform.start(Platform.java:216) ~[sonar-server-5.5.jar:na]
    at org.sonar.server.platform.Platform.startLevel34Containers(Platform.java:190) ~[sonar-server-5.5.jar:na]
    at org.sonar.server.platform.Platform.doStart(Platform.java:113) ~[sonar-server-5.5.jar:na]
    at org.sonar.server.platform.Platform.doStart(Platform.java:99) ~[sonar-server-5.5.jar:na]
    at org.sonar.server.platform.PlatformServletContextListener.contextInitialized(PlatformServletContextListener.java:44) ~[sonar-server-5.5.jar:na]
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4812) [tomcat-embed-core-8.0.30.jar:8.0.30]
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5255) [tomcat-embed-core-8.0.30.jar:8.0.30]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) [tomcat-embed-core-8.0.30.jar:8.0.30]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1408) [tomcat-embed-core-8.0.30.jar:8.0.30]
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1398) [tomcat-embed-core-8.0.30.jar:8.0.30]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) [na:1.8.0_91]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) [na:1.8.0_91]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) [na:1.8.0_91]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_91]
Caused by: java.lang.AbstractMethodError: null
    at org.sonar.server.plugins.ServerExtensionInstaller.installExtensions(ServerExtensionInstaller.java:64) ~[sonar-server-5.5.jar:na]
... 15 common frames omitted


text:
Q: WCF: Exposed Object Model - stuck in a loop I'm working on a pretty big WSSF project. I have a normal object model in the business layer. Eg a customer has an orders collection property, when this is accessed then it loads from the data layer (lazy loading). An order has a productCollection property etc etc..
Now the bit I'm finding tricky is exposing this via WCF. I want to export a collection of orders. The client app will also need information about the customers. Using the WSSF data contract designer I have set it up so that customers have a property called "order collection". This is fine if you have a customer object and would like to look at the orders but if you have an order object there is no customer property so it doesn't work going up the hierarchy.
I've tried adding a customer property to the orders object but then the code gets stuck in a loop when it loads the data contracts up. This is because it doesn't load on demand like in the business layer. I need to load all properties up before the objects can be sent out via WCF. It ends up loading an order, then the customer for that order, then the orders for that customer, then the customer for that order etc etc...
I'm sure I've got all this wrong. Help!!

A: Generally, with WCF, it's best to think of contracts not as 'remote objects', but as interfaces that you can call to get data from or pass data to.
Any methods called on a returned object are processed locally, rather than where the object originated.  In fact, getting the 'same' object from the server twice will generally result in two entirely separate objects on the client side!
To get the kind of functionality you're asking about, you would probably need to write some client-side code to create a remote object 'illusion' for you.


text:
Q: Rename excel file with os.rename() Python I was writing a quick script which would change the names of every excel file located in a directory:
[...]
for file_ in os.listdir(path):
   if 'Analytics Android' in file_:
      os.rename(file_, 'Android Orders.xlsx')

But, I get an error: [Error 2] The system cannot find the file specified. Shouldn't the rename function change the name to the second argument?

A: os.listdir does not give absolute paths, but relative paths to the given path to list, so you'll still have to create the full path:
for file_ in os.listdir(path):
    if 'Analytics Android' in file_:
        os.rename(os.path.join(path, file_), os.path.join(path, 'Android Orders.xlsx'))

A: You have to give the absolute path to the file.
>>> os.rename(os.path.join(path, file_), 'Android Orders.xlsx')


text:
Q: Insert Link from table to mail (ASP.NET MVC) I want to send Email from my ASP.NET MVC website
I write this method on my controller
public ActionResult SendEmail(SmartSolutions.Models.InvitationMail _objModelMail)
{
    if (ModelState.IsValid)
    {
        var emailList = db.InvitationMails.Select(model => model.To);
        var emails = String.Join(",", emailList);
        MailMessage mail = new MailMessage();
        mail.To.Add(emails);
        mail.From = new MailAddress(_objModelMail.From = "xxxxxxxx@gmail.com");
        mail.Subject = _objModelMail.Subject = "Видео интервью";

        string Body = _objModelMail.Body = "Предлагаем пройти интервью";
        mail.Body = Body;
        mail.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new System.Net.NetworkCredential
        ("xxxxxxxx@gmail.com", "*********************");// Enter seders User name and password
        smtp.EnableSsl = true;
        smtp.Send(mail);
        return View("SendEmail", _objModelMail as IEnumerable<InvitationMail>);
    }
     else
     {
         return View();
     }
}

But when I try to write like this string Body = _objModelMail.Body = "Предлагаем пройти интервью" + __objModelMail.Link;
Link not pasting to Body.
In table Link is filled.
Where is my problem?

A: I found solution
Here is code
  public ActionResult SendEmail(SmartSolutions.Models.InvitationMail _objModelMail)
    {

         if (ModelState.IsValid)
        {
            var emailList = db.InvitationMails.Select(model => model.To);
            var emailList2 = db.InvitationMails.Select(model => model.Link);
            var link2 = emailList2.FirstOrDefault();
            var emails = String.Join(",", emailList);
            MailMessage mail = new MailMessage();
            mail.To.Add(emails);
            mail.From = new MailAddress(_objModelMail.From = "xxxxxxxx@gmail.com");
            mail.Subject = _objModelMail.Subject = "Видео интервью";

            string Body = _objModelMail.Body= "Предлагаем пройти интервью"+ link2;

            mail.Body = Body;
            mail.IsBodyHtml = true;
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.UseDefaultCredentials = false;
            smtp.Credentials = new System.Net.NetworkCredential
            ("xxxxxxxx@gmail.com", "********");// Enter senders User name and password
            smtp.EnableSsl = true;
            smtp.Send(mail);
            return View("SendEmail", _objModelMail as IEnumerable<InvitationMail>);
        }
         else
         {
             return View();
         }
    }


text:
Q: Javascript access functions of constructor I have an object called twillioObject.
When I do a console.log of twillioObject, I get this output in developer tools:

I want an object of the Connection and Device classes. It seems that I can't reach it.
I have experience in JavaScript but I haven't seen this situation before. How does this work?


text:
Q: File movement issue on NFS file system on Unix box Currently there are 4.5 million files in a single directory on an NFS file system. As a result any read or write operation on that directory is causing a huge delay.
In order to over come this problem, all the files in that directory will be moved onto different directories based on the year of its creation.
Apparently, the find command that we are using with the -ctime option is not working because of the huge file volume.
We tried listing the files based on the year of creation and then feed the list to a script that will move them in a for loop. But even this failed as ls -lrt went for a hang.
Is there any other way to tackle this problem?
Please help.
Script contents:
1) filelist.sh
    ls -tlr|awk '{print $8,$9,$6,$7}'|grep ^2011|awk '{print $2,$1,$3,$4}' 1>>inboundstore_$1.txt 2>>Error_$1.log
    ls -tlr|awk '{print $8,$9,$6,$7}'|grep ^2011|wc -l 1>>count_$1.log

2) filemove.sh
    INPUT_FILE=$1  ##text file which has the list of files from the previous script
    FINAL_LOCATION=$2  ##destination directory
    if [ -r $INPUT_FILE ]
    then
       for file in `cat $INPUT_FILE`
       do
           echo "TIME OF FILE COPY OF [$file] IS : `date`" >> xyz/IBSCopyTime.log
           mv $file $FINAL_LOCATION
       done
    else
       echo "$INPUT_FILE does not exist"
    fi

A: Use the readdir iterator.


text:
Q: Javascript/JQuery Firefox and double monitor I have to write a web application with two monitor support.
I'm using a window.open to load the second window in the second monitor.
It works, and when I want to close the main window I run this:
$(window).unload(function(){
    if(window2) window2.close();
});

This successufly close the second windows but I have a trouble: the last closing window is the second one, than the browser (firefox) save the second windows coordinates as default and when I open the browser again it will load that in the second windows.
Opening and closing the browser windows flip from second to first monitor...
How to close the second windows BEFORE the first one? I try something like "sleep" inside the unload function but seems that firefox stores last coordinates on close request and not after the unload.


text:
Q: Blank dates coming up as weird dates instead of NULL in SQL I am importing data from postgres into sql server. Fields where data type is 'timestamp without (or with) time zone' i used datetimeoffset in sql table but couldn't create package with the same. So i changed the datatype as datetime.
Now, when I import data,all the dates and time are coming perfectly alright but where there is no data ( blank) then its displayed as some weird date instead of NULL in my SQL table.
Those weird dates are  -
1899-12-30 00:00:00.000
1753-01-01 00:00:00.000
What am i missing and how to resolve this?
Maybe that's a simple thing but I am quite new to SQL so apologies if its really easy but any help is appreciated.
Thanks,
AP

A: Suppose your meaningful data is from 2000 onwards, then run a update statement like:
update table
set column = NULL
where column < cast('01-01-2000' as datetime)


text:
Q: Good implementation of unit test with EasyMock I have a question about good implementation of unit test with EasyMock.
First implementation:
Capture<String> capturedString = newCapture();
myService.doSomething(capture(capturedString));
expectLastCall();

assertEquals("stringValue", catpuredString.getValue());

Second implementation:
myService.doSomething("stringValue");
expectLastCall();

I feel comfortable with the first implementation because an assertion is present. But in the second implementation I expect "stringValue" passed to my service. If it's not the case an exception will be thrown by EasyMock. So is there a difference between the 2 implementations ? If not, is one better than the other ?
Thanks.

A: GreenGiant's answer is quite good. Both ways are equivalent in result but have a different feeling. And btw, there's no need to add expectLastCall(). It's implicit on void methods.
To add to the answer:
An expectation is something you expect to happen. Something you care about. For instance, if you care about doSomething being called but you don't care about the parameter passed, you would use any() as a matcher. To show your intention (that you don't care). If the parameter does matter, the equals matcher make sense.
Then, indeed the capture is frequently used because your not quite sure what will be passed. For instance, if there is no equals() method defined on the object.
I tend to use the capture and a list of asserts when I have complex objects to check. If I have a bean with many fields, it is easier to have a list of asserts then to use a cmpEq matcher.
Then only drawback of this method is that you won't know right away that the parameter passed isn't valid. The tested method will continue to execute and might fail afterwards. So you will never reach your assertions and think the bug is farther in the code than it really is.
But is the tested code is nicely atomic and not too complicated, this shouldn't happen too much.

A: I guess it just depends on whether you know the string value up-front, before you record your mock calls.

*

*If you already know the string value, then use the second implementation, because it's simpler.

*But if you don't know it ahead of time, then use the first implementation. For example, if the value passed into your service is dynamic and you don't know what it should be before you actually run your test.


text:
Q: How do I fix TypeError: sequence item 0: expected str instance, NoneType found This is the code that I have and I am trying to fix TypeError: sequence item 0: expected str instance, NoneType found
The error I believe is when I try to open the file that is entered
def sendEmail():
    message = EmailMessage()
    sender = input("Please enter the email address of the sender: ")
    password = getpass.getpass("Please enter the password for the senders email: ")
    recipient = input("Please enter the email address of the recipient: ")
    subject = input("Please enter the subject of the email: ")
    compromisedUser = input("Please enter the username of the compromised user: ")
    mailServer = smtplib.SMTP_SSL("smtp.gmail.com")
    mailServer.login(sender, password)
    # Email headers
    message["From: "] = sender
    message["To: "] = recipient
    message["Subject: "] = subject

    # body of the email
    body = """Hello,
    the following files and user have been compromised: """ "\nUser:" + compromisedUser
    message.set_content(body)

    # Send file with compromised files
    attach = input("Do you have a file to attach to the email? (Y or N): ")
    if attach.upper() == "Y":
        filename = input("Enter the file name of one of the compromised files: ")
        mime_type, _ = mimetypes.guess_type("filename")
        mime_type = mimetypes.MimeTypes().guess_type(filename)[0]
        print(mime_type)
        mime_type, mime_subtype = mime_type.split("/")
        with open(filename, "rb") as file:
            message.add_attachment(file.read(), maintype=mime_type, subtype=mime_subtype, filename=filename)
            mailServer.send_message(message)
            mailServer.quit()
    # if no file was sent then the body message is sent
    else:
         mailServer.send_message(message)
         mailServer.quit()


text:
Q: Links between difference and differential equations? Does there exist any correspondence between difference equations and differential equations?
In particular, can one cast some classes of ODEs into difference equations or vice versa?

A: (Adding to user26872's answer as this was not obvious to me so it might help someone else going through his derivation)
The identity
$$x_{n+1} = Ex_n = \sum\limits_{k=0}^\infty \frac{h^k}{k!}D^k x_n=e^{hD}x_n$$
is true if we consider the following. Let $x_n = x(t_n)$. Let's assume that $x(t)$ is differentiable around some point $t_n$, then it's Taylor series can be defined as
$$x(t) = \sum\limits_{k=0}^\infty \frac{x^{(k)}(t_n)}{k!}(t-t_n)^k.$$
If we now perform the same expansion at $t' = t_n+h$ we have
$$x(t_n+h) = \sum\limits_{k=0}^\infty \frac{x^{(k)}(t_n)}{k!}h^k = \sum\limits_{k=0}^\infty \frac{h^k D^k}{k!}x(t) = e^{hD} x(t_n)$$
and so
$$x_{n+1} = Ex_n \leftrightarrow x(t_n + h) = E x(t_n)$$
thus giving
$$E = e^{hD}.$$

A: First order example
Consider the difference equation
$$\begin{equation*}
x_{n+1} = a x_n,\tag{1}
\end{equation*}$$
where $x_0$ is given, with solution
$$\begin{equation*}
x_n = a^n x_0. \tag{2}
\end{equation*}$$
Let $x_n = x(t_n)$, where $t_{n+1} = t_n + h$ and $t_0 = 0$, so $t_n = n h$.
Rewrite the difference equation (1) as
$$\frac{x(t_{n}+h)-x(t_n)}{h} = \frac{(a-1)}{h} x(t_n).$$
If $h$ is small, this can be approximated by the differential equation
$$\begin{equation*}
x'(t) = \frac{a-1}{h}x(t),\tag{3}
\end{equation*}$$
with solution
$$\begin{equation*}
x(t) = x(0) \exp \left(\frac{a-1}{h} t\right).\tag{4}
\end{equation*}$$
Notice that $\exp\left(\frac{a-1}{h} t\right) = a^{n} + O(n(a-1)^2)$, so for $n\ll 1/(a-1)^2$ we find good agreement with (2).
Going in the reverse direction, from the differential equation (3) to the difference equation (1), is called Euler's method.
There is a subtlety when approximating a difference equation by a differential equation.
For this problem we require that $|a-1| \ll 1$ since we need $x_{n+1}- x_n = O(h) \ll 1$.
Otherwise, we should expect (and will find) the approximation of (1) by (3) to be poor.
Sometimes it is necessary to reformulate the difference equation so the difference between successive terms is small.${}^\dagger$
${}^\dagger$ For example, suppose $a$ in (1) were large and positive.
Let $y_0=x_0$ and let $y_{n+1} = a^{1/p} y_n$,
where $p$ is some large integer so $|a^{1/p} - 1|\ll 1$.
Note that $y_{n p} = x_n$.
The solution to the corresponding differential equation for $y$ will be a good approximation to $y_n$, and this in turn can be used to approximate $x_n$.
Second order example
Consider the differential equation for the harmonic oscillator
$$\begin{equation*}
x''+x = 0, \hspace{5ex} x(0)=1, \hspace{5ex}x'(0)=0, \tag{5}
\end{equation*}$$
the solution for which is $x(t) = \cos t$.
The simplest related difference equation is
$$\begin{equation*}
\frac{1}{h^2}(x_{n+2}-2x_{n+1}+x_n) + x_n = 0, \tag{6}
\end{equation*}$$
with $x_0 = x_1 = 1$.
(We show how to get (6) from (5) below.)
There are standard techniques for solving simple recurrence relations such as (6) in closed form.
We find
$$\begin{equation*}
x_n = \frac{1}{2} \left((1+i h)^{n}+(1 - i h)^{n}\right).
\end{equation*}$$
Note that $x_n$ is real since $x_n^* = x_n$.
This is the closed form for the solution a computer would find solving (6) iteratively.
Recall that $n=t_n/h$.
For small $h$,
$x_n = \cos t_n + \frac{1}{2} h t_n \cos t_n + O(h^2)$,
so the numerical solution to (6) will well approximate $\cos t_n$ for $h t_n \ll 1$.
In the limit $h\to 0$,
$x_n \to \cos t_n,$
as expected.
Derivatives and finite differences
Morally, a difference equation is a discrete version of a differential equation and
a differential equation is a continuous version of a difference equation.
The method of numerical integration of ODEs is essentially the rewriting of a differential equation as a difference equation which is then solved iteratively by a computer.
This is a big subject with many subtleties.
The method can also be applied to nonlinear and partial differential equations.
Below we give a brief dictionary between finite difference and differential operators.
Define the shift operator $E$ such that $E x_n = x_{n+1}$.
The difference operator $\Delta = E-1$ then gives $\Delta x_n = x_{n+1}-x_n$.
These operators are connected to differentiation by Taylor series.
Let $D x_n = x_n' = d x(t)/d t|_{t=t_n}$. Then
$$x_{n+1} = E x_n = \sum_{k=0}^\infty \frac{h^k}{k!} D^k x_n
= e^{h D}x_n.$$
Thus, as an operator,
$$E = e^{h D},$$ and so
$$D = \frac{1}{h} \ln E = \frac{1}{h} \ln(1+\Delta)
= \frac{1}{h}\sum_{k=1}^\infty (-1)^{k+1} \frac{\Delta^k}{k}.$$
(Think of these operators as acting on polynomials, possibly of very high order.)
This formalism gives us a way to convert any ODE into a difference equation and vice-versa.
Notice that higher order derivatives can be approximated by $D^k\approx (\Delta/h)^k$.
Thus, for example,
$$x'' = D^2 x \rightarrow \frac{1}{h^2}\Delta^2x_n
= \frac{1}{h^2}\Delta(x_{n+1}-x_n)
= \frac{1}{h^2} (x_{n+2}-2 x_{n+1} + x_n).$$
When using Euler's method we let $D \approx \Delta/h$.
We could just as well keep higher order terms in $\Delta$ to get recursion relations with three or more terms.
It is a sign of the nontrivial nature of the subject that this simple change leads to numerical instabilities.
There are many named algorithms that do improve and generalize Euler's method, building on the ideas sketched above.
(See, for example, the Runge-Kutta
methods, a family of robust algorithms used to numerically solve linear and nonlinear differential equations.)
Addendum
This is in response to Drew N's question about seeing directly that
$$D = \frac{1}{h}\sum_{k=1}^\infty (-1)^{k+1} \frac{\Delta^k}{k}$$
is the differential operator.
Here we show that $D t^n = n t^{n-1}$ for $n=0,1,\ldots$, which shows that $D$ is the differential operator on polynomials of arbitrarily high degree.
(It is straightforward to extend this proof to $n\in\mathbb{C}$.)
We have
\begin{align*}
D t^n &= \frac{1}{h} \sum_{k=1}^\infty (-1)^{k+1}\frac{1}{k}\Delta^k t^n \\
&= \frac{1}{h} \sum_{k=1}^\infty (-1)^{k+1}\frac{1}{k}(E-1)^k t^n \\
&= \frac{1}{h} \sum_{k=1}^\infty (-1)^{k+1}\frac{1}{k}
    \sum_{j=0}^k{k\choose j}(-1)^{k-j}E^j t^n
        & \textrm{binomial theorem} \\
&= \frac{1}{h} \sum_{k,j} (-1)^{j+1}\frac{1}{k}{k\choose j}(t+j h)^n \\
&= \frac{1}{h} \sum_{k,j} (-1)^{j+1}\frac{1}{k}{k\choose j}
    \sum_{l=0}^n {n\choose l}j^l h^l t^{n-l}
        & \textrm{binomial theorem} \\
&= \left.\frac{1}{h} \sum_{k,j,l} (-1)^{j+1}\frac{1}{k}
    {k\choose j}{n\choose l}
    (x D)^l x^j h^l t^{n-l}\right|_{x=1}
        & D = d/dx, (x D)^l = \underbrace{(x D)\cdots (x D)}_{l} \\
&= \left.-\frac{1}{h} \sum_{k,l} \frac{1}{k}
    {n\choose l} h^l t^{n-l}
    (x D)^l \sum_{j=0}^k {k\choose j}(-x)^j \right|_{x=1} \\
&= \left.-\frac{1}{h} \sum_{k,l} \frac{1}{k}
    {n\choose l} h^l t^{n-l}
    (x D)^l (1-x)^k \right|_{x=1}
        & \textrm{binomial theorem} \\
&= \left.-\frac{1}{h} \sum_{l} {n\choose l} h^l t^{n-l}
    (x D)^l \sum_{k=1}^\infty \frac{1}{k} (1-x)^k \right|_{x=1} \\
&= \left.\frac{1}{h} \sum_{l} {n\choose l} h^l t^{n-l}
    (x D)^l \log x\right|_{x=1}
        & \textrm{series for natural logarithm} \\
&= \frac{1}{h} \sum_{l=0}^n {n\choose l} h^l t^{n-l}
    \delta_{l1}
        & \textrm{see below} \\
&= \frac{1}{h} {n\choose 1} h t^{n-1} \\
&= n t^{n-1}.
\end{align*}
Note that
$(x D)x^j = j x^j$
so
$$(x D)^l x^j = j^l x^j.$$
Also
\begin{align*}
(x D)^0 \log x|_{x=1} &= \log 1 = 0 \\
(x D)^1 \log x &= x \frac{1}{x} = 1 \\
(x D)^2 \log x &= (x D)1 = 0 \\
(x D)^3 \log x &= (x D)^2 0 = 0.
\end{align*}
Thus,
$$(x D)^l \log x|_{x=1} = \delta_{l1},$$
where $\delta_{ij}$ is the Kronecker delta.

A: One example:
You can take the Laplace transform of a discrete function by expressing the target of the Laplace transform as the product of a continuous function and a sequence of shifted delta functions and summing up: $\sum_{k=0}^\infty\int_{0}^\infty f(t)\delta(t - kT)e^{-st}dt$ = $\sum_{k=0}^\infty f(kT)e^{-skT}$, where T is the sampling period.
The (unilateral) Z transform is defined as $\sum_{n=0}^{\infty}x[k]z^{-k}$, for a discrete time signal $x[k]$.  By substituting $z = e^{sT}$ in the formula for the discretized Laplace transform, the Z transform is obtained, and the s and Z domains are related by $s = \frac{1}{T}\log(Z)$.  This is obviously a nonlinear transformation; points left of the imaginary axis in the s plane are mapped to the interior of the unit circle of the Z plane, while points to the right of the imaginary axis are mapped to the exterior.  One can use the Bilinear transform, $s = \frac{2(z -1)}{T(z + 1)}$, as a first order approximation to $s = \frac{1}{T}\log(Z)$.
So it's possible to (approximately) transform any equation in the s domain into a corresponding equation in the Z domain.  This is useful for deriving a difference equation, since it can be shown that the Z transform of a shift, $Z(x[k - n])$, is equal to simply $z^{-n}X(z).$  Due to this property it is often possible to go easily from the Z transform of an expression to a difference equation, simply by inspecting inverse powers of Z and their coefficients in the equation.  In short, if the differential equation is amenable to the Laplace transform (i.e. linear time invariant), it can be quite straightforward using this method to get a difference equation representation.

A: First see the correspondence between discrete and continuous dynamical systems. Both are acts of a monoid on some set $X$.
For discrete dynamical systems the monoid that acts is $\mathbb{N}$. For continuous dynamical systems the monoid that acts is $\mathbb{R}$.
This action comes in the form of a left multiplication
$(.,.):\mathbb{N}\times X \rightarrow X$ or $(.,.):\mathbb{R}\times X \rightarrow X$
and is compatible with the addition structure of $\mathbb{N}$ and $\mathbb{R}$ respectively.
I.e. for all $n,m \in \mathbb{N}$ or $\mathbb{R}$ and $x \in X$ we have $(0,x) = x$ and $(n,(m,x)) = (n + m,x)$.
Now on the story of difference and differential equations. A first order difference equation equals a discrete dynamical system. Note that any difference equation can be converted to a system of first order difference equations (see higher order difference equations). Hence any difference equation equals a discrete dynamical system. Note that the $\mathbb{N}$-act is given by $(n,x) = f^n(x)$.
If the differential condition is sufficiently smooth there exists a unique solution for any point ($\phi_x^t$). We use this solution as the $\mathbb{R}$-act. I.e. $(t,x) = \phi_x^t$. Hence any sufficiently smooth differential equation equals a continuous dynamical system.

A: Yes, obviously there is some correspondence (numerical solutions of ordinary differential equations are discrete dynamical systems, many proofs in bifurcation theory uses continuous time dynamical systems to analyze discrete original problems, etc).
However, the most profound attempt to build a theory that unites difference and differential equations is the time scale calculus.


text:
Q: Error trying to run mod_wsgi on a apache server I have a Flask Project structure directory inside /var/www:
item-catalog-fullstacknd\
    itemCatalogApp.wsgi
    itemCatalogApp\
        __init__.py

This is th WSGI file above:
import sys
import logging
logging.basicConfig(stream=sys.stderr)
sys.path.insert(0,"/var/www/item-catalog-fullstacknd/")
from itemCatalogApp import app as application
application.secret_key = 'Add your secret key'

This is the /etc/apache2/sites-enabled/000-default.conf
WSGIPythonPath /var/www/item-catalog-fullstacknd/itemCatalogApp/
<VirtualHost *:80>
    WSGIScriptAlias / /var/www/item-catalog-fullstacknd/itemCatalogApp.wsgi

            <Directory /var/www/item-catalog-fullstacknd/itemCatalogApp>
                    Order allow,deny
                    Allow from all
            </Directory>

            Alias /static /var/www/item-catalog-fullstacknd/itemCatalogApp/static

            <Directory /var/www/item-catalog-fullstacknd/itemCatalogApp/static/>
                    Order allow,deny
                    Allow from all
            </Directory>

</VirtualHost>

And I am getting the following error:
mod_wsgi (pid=17586): Exception occurred processing WSGI script '/var/www/item-catalog-fullstacknd/itemCatalogApp.wsgi'.
 Traceback (most recent call last):
   File "/var/www/item-catalog-fullstacknd/itemCatalogApp.wsgi", line 6, in <module>
     from itemCatalogApp import app as application
   File "/var/www/item-catalog-fullstacknd/itemCatalogApp/__init__.py", line 3, in <module>
     from flask import Flask, jsonify, render_template, request
 ImportError: No module named flask

I already pip install all the modules contained in the requirements.txt file.
I have no idea what to do anymore.

A: It's possible that you've installed modules for a different python executable, not the one that your mod_wsgi uses by default. To check that, add to the beggining of your WSGI file:
import sys
print(sys.executable)

Then, open shell, run a python and type the same code there. If path is different, you should specify WSGIPythonHome to point at the desired python executable.


text:
Q: What is the proper way of mongoose populate? Hello im new to nodejs and mongoose, i need help in mongoose populate, please help me to understand. Thanks in Advance!
here is my schema's
PropertySchema.js
const mongoose = require('mongoose')
const { Schema } = mongoose
require('./MemberSchema')

const propertySchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  pname: String,
  ptype: String,
  price: Number,
  owner: { type: mongoose.Schema.Types.ObjectId, ref: 'Members' }
})

const Props = mongoose.model('Property', propertySchema)

module.exports = Property

MemberSchema.js
const mongoose = require('mongoose')
const { Schema } = mongoose
require('./PropertySchema')

const memberSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  fname: String,
  lname: String,
  dob: Number,
  email: String,
  address: String,
  phone: Number,
  memtype: String,
  username: {type: String, required: true},
  password: {type: String, required:true},
  properties: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Property' }]
})

const Members = mongoose.model('Members', memberSchema)

module.exports = Members

addPropertyRoutes.js
router.post('/add', isAuthenticated, (req, res, next) => {
  const props = new Property({
    _id: new mongoose.Types.ObjectId(),
    pname: req.body.pname,
    ptype: req.body.ptype,
    price: req.body.price,
    owner: new mongoose.Types.ObjectId()
  })
  props.save( (err, props) => {
    if (err) {
      console.log('Unable to register your data: ' + err)
      throw err
    }
    console.log('Property Added Successful!')
    res.redirect('/property/add')
  })
})

Im using mongoose 3.6 and expressjs.
When i check my Robo 3t after adding properties it shows like this check this screenshot:

A: In your, property schema you have to store ownerId, not to generate new ObjectId.
The proper way to do Populate in mongoose, you can find it here.

A: i think the solution is this:
change your addPropertyRoutes into this :)
router.post('/add', isAuthenticated, (req, res, next) => {
      const member = req.user
      Members.findOne({})
      const props = new Property({
        pname: req.body.pname,
        ptype: req.body.ptype,
        price: req.body.price,
        owner: member._id
      })
      props.save( (err, props) => {
        if (err) {
          console.log('Unable to register your data: ' + err)
          throw err
        }
        console.log('Registration Successful!')
        res.redirect('/property/add')
      })
    })

Your Welcome from noobs


text:
Q: Javascript message box doesnot get closed after ajax call aMy scenario is like this. I want to delete a resource. When I click on delete href I pop-up a javascript message box (delete confirmation) When The okay button is clicked my call is going to backend though ajax function as I want to capture the response of the backend.
This is the href
[Delete]

My confirmation message box pops-up correctly. Then I click on okay button on that box. The resource is deleting but my message box don't get closed. Also I want to open ajax dialog box to capture the response. What would be the reason for this ?
Here is my ajax function


text:
Q: Spring cloud sleuth for propagating baggage with otel configuration I am using spring cloud sleuth for propagating baggage with otel configuration. I want to send baggage with extra fields across applications. I am following this documentation:
https://docs.spring.io/spring-cloud-sleuth/docs/3.1.1-SNAPSHOT/reference/html/project-features.html#features-baggage
This is working fine with sleuth brave but with spring-cloud-sleuth-otel it seems some extra configuration is required. Please suggest where I can get related information.


text:
Q: AJAX stacks response from PHP I've recently started using and learning JS and jquery. I'm sending a user email from a form to my PHP page to check if any user exists in DB via ajax, then I get a response from my PHP file if the user exists or not and display the text in a div. It's working fine, but because the page doesn't refresh when the button for sending form data is pressed, ajax just stacks the response from PHP.
I probably need to clear the response every time the button is clicked first and then append the response but I can't find the right command for it :/
JS
function sendnewpass() {
        var email = document.getElementById("useremail").value;

        $.ajax({
            type : "POST",
            url  : "login.php", //my php page
            data : { passemail : email },  //passing the email
            success: function(res){  //to do if successful
                $("#emailsentmsg").append(res);  //the the div that i put the response in
            }
        });

}

A: Use empty() like:
$("#emailsentmsg").empty().append(res);

A: Use the following:
$("#emailsentmsg").html("");
$("#emailsentmsg").append(res);

Or shorter (thanks @Ivar):
$("#emailsentmsg").html(res);


text:
Q: How do I access Data inside a JDA event Listener? I'm trying to do a discordBOT using Java and JDA. I've tried to work with them for several hours now and I don't get it to work. My Bot needs to process data which depends on the user. In JDA's event Handlers you cannot return any data types since they extend the ListenerAdapter. Its my first time working with Eventlisteners and I already googled a lot.

A: I'm not sure if this is what you are asking for, but your class needs to extend from ListenerAdapter.
public class yourClass extends ListenerAdapter {
    //Your code.
}

Inside a class you can use the method you need for doing what you want. e.g.
@Override
public void onMessageReceived(MessageReceivedEvent event) {
    //Your code again.
}

If you want to transfer data between two classes, you can use your own methods and just give the event to it.
[Method1]
public static void yourMethod(MessageReceivedEvent event) {
    //Your code.
}

[Method2]
@Override
public void onMessageReceived(MessageReceivedEvent event) {
    yourMethod(event);
}

A: Create a ListenerAdapter and associate it to the JDA instance.
I'll show you an example code so you can understand:
    /**
     * Logs the bot into Discord and sets the event listeners.
     */
    public static void launchJDA(String botToken) {
        try {
            jdaInstance = new JDABuilder(AccountType.BOT).setToken(loadToken()).build().awaitReady();
            jdaInstance.addEventListener(new EventsManager());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

public class EventsManager extends ListenerAdapter {

    @Override
    public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
        //Do what you want with the event here, for example replying with the message received:
        String msg = event.getMessage().getContentDisplay();
        event.getChannel().sendMessage(msg).queue();
    }
}


text:
Q: ASP.NET MVC 2 DropDownListFor without database I am new with MVC I am trying to create a small product form with TextBox and DropDownList field, I have created a Class in Model with personName, productName. I have only 5 Products so I don't want to use db for it.
I tried all that I can by doing google but still not able to get my dropdown list
Thanks

A: If you don't want to use a database you could create a XML document that stores all of the product information.
Then you can create a Model that uses a XML parser to get all of the values from the XML document.
Once you have the values in the Model, you can bind it to the DropDownListFor<Model>.
You can also hard-code the Products into the DropDownList if they do not change.

A: Assuming you have a PersonsProduct class to represent your model/viewmodel like this
public class PersonsProduct
{

    public string PersonName { set;get;}
    public IEnumerable<SelectListItem> Products { get; set; }
    public string SelectedProductId { get; set; }
    //Other Properties
}

In your GET action method, you may initialize the values like this
public ActionResult AddProduct()
{
    var objProduct = new PersonsProduct();
    objProduct.Products = new[]
    {
          new SelectListItem { Value = "1", Text = "Book" },
          new SelectListItem { Value = "2", Text = "Pen" },
          new SelectListItem { Value = "3", Text = "Computer" },
          new SelectListItem { Value = "4", Text = "Table" },
          new SelectListItem { Value = "5", Text = "Mouse" }
    };
    // can replace the above line with loading data from Data access layer.
    return View(objProduct);
}

And in your View which is strongly typed to PersonsProduct viewmodel
@model PersonsProduct
@using (Html.BeginForm())
{
  @Html.DropDownListFor(x => x.SelectedProductId, new SelectList(Model.Products ,"Value","Text"), "Select..")
  <input type="submit" value="save" />
}

And in your HTTPPost action, you can get the selected productId like this
[HttpPost]
public ActionResult Index(PersonsProduct model)
{
 //  check model.SelectedProductId here

}

NEVER HARDCODE LIKE THIS. It is UGLY UGLY UGLY !
This answers your question (without using Database and XML). But I strongly recommend to avoid this hardcoding approach. You should better use different source for the list of products like database / XML file etc.. Otherwise whenever you want to add a new product to the list, you need a recompilation.  I hope you will change this code to read Product data from a different source instead of hard coded values.


text:
Q: Javascript 'select' on change go to anchor (anchor id is the select value) I have my script creating a dropdown box (select) and populating the values with items from an array that I looped through. The values of these items are also the same as the id's for anchor points throughout the page. I'm trying to make it so when the select is changed, it goes to the anchor point that matches the value of the select.
error_anchor is an array of items where the values are also the same as the anchor id's
for (var i = 0; i < error_anchor.length; i++) {
  var option = document.createElement("option");

  option.setAttribute("value", error_anchor[i]);
  option.text = error_anchor[I];
  option.onChange="window.location.hash=this.value";

  selectList.appendChild(option);
};

This doesn't throw an error but it doesn't do anything when I change the select value. I read online about using this.value and figured it would use the selected value, but perhaps it was just a placeholder in someone else's example?
I tried placing the onChange line outside of the loop, as I suppose it doesn't need to be in there, but it doesn't seem to have made a difference.
Would appreciate the help! Thanks

A: The event name is onchange not onChange and you should assign a function to it (not a string).
Also, the event should be on the select, not the options. this.value will contain the current chosen option value.
You can see a demo here


text:
Q: Spam filtering in bridging I'm using sendmail with spamassasin, one of my server is working behind it. All the port 25 traffic for the server behind it is being filtered.
User are using SMTP authentication enabled in Microsoft Outlook 2007 or 2010. All user has to face error "none of the authentication methods are supported by your server".
Is there any way that I could filter Spam in bridging without breaking authentication?

A: One approach may be to setup a "dummy" account on the SMTP server answering on port 25. The users can then configure the Outlook clients with the credentials matching that of the "dummy" account for SMTP authentication.


text:
Q: Method to work out win/loss/tie and return points (football) static final int WIN = 3;
    static final int TIE = 1;
    static final int LOSS = 0;

public static int berekenWedstrijdPunten(int[] mpUserTeamPunten, int[] mpTegenstanderTeamPunten){
        if (mpUserTeamPunten > mpTegenstanderTeamPunten){
            return WIN;
        }
        if (mpUserTeamPunten == mpTegenstanderTeamPunten){
            return TIE;
        }
        if (mpUserTeamPunten < mpTegenstanderTeamPunten) {
            return LOSS;
        }
    }

getting error lines under the if statements with > & <, trying to get a return of the win/tie/loss point into a print statement.

A: You can't compare two arrays with logical operators.