text:
Q: Emacs: Cannot disable "file changed since visited" check I am running emacs26 on an ubuntu azure VM and am running into problems when trying to save files on a particular mounted CIFS volume.  Emacs will randomly ask  "has changed since visited or saved.  Save anyway? (yes or no)".  When saving to local home storage this is not an issue.  I've tried suggestions from this thread: Emacs: how to disable 'file changed on disk' checking? but none have worked.  I have tried adding
(defun ask-user-about-supersession-threat (fn)
  "ignore")

(defun ask-user-about-lock (file opponent)
  "always grab lock"
  t)

to my .emacs file and this does not help.
Suggestions?


text:
Q: TemplateDoesNotExist error in Django version 2.0.2 My Django project structure
The codes are:
settings.py is:
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        # 'DIRS': ['templates', ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'python_django_blog',
        'USER': 'root',
        'PASSWORD': 'Coder123',
        'HOST': '127.0.0.1',
        'PORT': '3306',
    }
}

urls.py is:
from django.contrib import admin
from django.urls import path, re_path, include

from first import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('post-list/', views.postlist, name='post-list'),
]

views.py is:
from django.shortcuts import render
from django.template.loader import render_to_string

from .models import Post

def postlist(request):
    all_post=Post.objects.all()
    # return render(request,'post_list.html', all_post)
    return render_to_string(request,'post_list.html', {'all_post_list': all_post})

post_list.html is:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Oh No</title>

Problem and problem

Problem is
I think, all the settings are alright. http://127.0.0.1:8000/admin/ also works fine. But I'm getting errors entering http://127.0.0.1:8000/post-list/. I've searched many question similar to this. After fixing, I've made the above codes. But those codes shows errors. I cannot figure out what the problem is. Help me to solve this problem.
Thanks in advance.

A: Try this - 'DIRS': [os.path.join(BASE_DIR, 'first/templates')],

redpajama_set_name: RedPajamaStackExchange


text:
Q: Passing CFLAGS to configure via bash variable Just when I think I know how the shell works fairly, something comes along and stumps me. The following commands were executed on GNU bash, version 3.2.25.
I have several ./configure scripts that all share a group of common configure options, one of them being CFLAGS.
To that end, I have two variables
CFLAGS="-fPIC -O3"
COMMON_CONFIGURE_OPTIONS="CFLAGS=\"$CFLAGS\" --enable-static --disable-shared --prefix=$PREFIX"

When this gets passed to `./configure', it is done so like,
"$FOO/configure" $COMMON_CONFIGURE_OPTIONS

For the life of me, I cannot seem to get this to expand correctly. I have tried manually substituting the value of $CFLAGS into $COMMON_CONFIGURE_OPTIONS. I have tried every combination of single and double quotes under the sun. I have even tried quoting the entire "CFLAGS=..." argument.
The version I gave above yields the following (when set -x is enabled)
../configure 'CFLAGS="-fPIC' '-O3"' --enable-static --disable-shared --prefix=../install
configure: error: unrecognized option: `-O3"'
Try `../configure --help' for more information

What I expected, and what I desire, is for configure to be invoked like
./configure CFLAGS="-fPIC -O3" --enable-static --disable-shared --prefix="$PREFIX"

How can I achieve what I want, and additionally, are there good resources/tips on how to avoid this problem in the future?

A: To achieve what you want, I think you want to fundamentally change your approach.  Assuming your configure scripts are generated by autoconf, I would suggest using a config.site file.  That is, simply do something like:
mkdir -p $PREFIX/share
echo 'CFLAGS="--enable-static --disable-shared"' > $PREFIX/share/config.site

And then invoke configure as:
/path/to/configure --prefix=$PREFIX

Make sure that CONFIG_SITE is not set in the environment when you invoke configure, else the defaults will come from the file named there.


text:
Q: How do I make a chrome app write to a file I just started learning about chrome applications and I'm fairly new to the javascript aspect of it while I do have some experience with the HTML side of it. How do I create an application that has a check box (The check box will be html) and then have a button (which all also be in html) and this button will write to a file on my desktop whether the check box is checked or unchecked? i.e. it will write either true or false?

A: Saving to a file is not as as easy as it sounds. I suggest checking the Chrome App examples (found here), loading the extensions and seeing which one does what you want. THEN you go and check the code. The example that would work best for you would be the mini-code-edit one, which has both loading a file and saving to a file.
Still, if you won't do that, this example code should work:
//Selector for your "Save" button
document.querySelector("#saveButton").onclick = saveToFile;
//Save variables
var fileEntry;
var hasWriteAccess;
//Save methods
function saveToFile()
{
    if (fileEntry && hasWriteAccess) {
    writeEditorToFile(fileEntry);
    } else {
        chrome.fileSystem.chooseEntry({ type: 'saveFile', suggestedName: "suggestedFileName.txt"}, onChosenFileToSave);
    }
}

function setFile(theFileEntry, isWritable) {
  fileEntry = theFileEntry;
  hasWriteAccess = isWritable;
}

function writeEditorToFile(theFileEntry) {
  theFileEntry.createWriter(function(fileWriter) {
    fileWriter.onerror = function(e) {
      console.log("Write failed: " + e.toString());
    };

    var blob = new Blob(["You put whatever you want written to your file here."]);
    fileWriter.truncate(blob.size);
    fileWriter.onwriteend = function() {
      fileWriter.onwriteend = function(e) {
        //handleDocumentChange(theFileEntry.fullPath);
        console.log("Write completed.");
      };

      fileWriter.write(blob);
    }
  }, errorHandler);
}

var onChosenFileToSave = function(theFileEntry) {
  setFile(theFileEntry, true);
  writeEditorToFile(theFileEntry);
};

This was taken from the example I mentioned. Also, remember to add "fileSystem": ["write"] to your manifest.


text:
Q: How we can control the internet of our faculty at university? I have a problem, in my faculty at university (CS)
we will have our own internet line(30Mb), this is fast compared to the regular internet that provides us the university (really more slow and very restricted). Well, we are approximately 150 ~ 200 students and we need do a management of the network, to avoid downloads or games that could do more slowly the internet. Almost all students wanna do more investigation and learn more, and for do much better the assignments of the courses. I wanna know if there is a possible solution for do this and We really want that it don't will have a high cost(we are in an state college), we have computers for make a network server or some else. Thank you!!

A: pfSense can do most the things I think you're looking for. It's fairly easy to use without prior experience and provides many of the features you'd find in an enterprise firewall/router.
There are dozens of these firewall/router distributions out there, but it sounds like you're most interested in something that can do QoS or "Traffic Shaping"; adding those keywords to your Google searches might help find what you're looking for.


text:
Q: Can't PlaySong From My ListView.onItemClickListner? I'm Trying StandOutWindow Library In which I tried to Create MusicPlayer from this This Tutorial My ListView is Showing songs but When i Click on songs the App Crashes. What am i Missing ? Thanks.
MainActivity
public void createAndAttachView(int id, FrameLayout frame) {
    LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.musicplayer, frame, true);

    songView = (ListView) view.findViewById(R.id.lvMusicPlayer_songList);
    songList = new ArrayList<Song>();
    getSonglist();
    Collections.sort(songList, new Comparator<Song>() {
        public int compare(Song a, Song b) {
            return a.getTitle().compareTo(b.getTitle());
        }
    });
    SongAdapter songAdapter = new SongAdapter(this, songList);
    songView.setAdapter(songAdapter);

    songView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            musicService.playSong();
        }
    });
}

private void getSonglist() {
    ContentResolver musicResolver = getContentResolver();
    Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
    Cursor musicCursor = musicResolver.query(musicUri, null, null, null,
            null);
    if (musicCursor != null && musicCursor.moveToFirst()) {
        int titleColumn = musicCursor
                .getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
        int idColumn = musicCursor
                .getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
        int artistColumn = musicCursor
                .getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
        do {
            long thisId = musicCursor.getLong(idColumn);
            String thisTitle = musicCursor.getString(titleColumn);
            String thisArtist = musicCursor.getString(artistColumn);
            songList.add(new Song(thisId, thisTitle, thisArtist));
        } while (musicCursor.moveToNext());
    }

}

MusicService
public void onCreate() {
    super.onCreate();
    songPosition = 0;
    random = new Random();
    mp = new MediaPlayer();
    initMusicPlayer();
}

private void initMusicPlayer() {
    mp.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
    mp.setAudioStreamType(AudioManager.STREAM_MUSIC);

    mp.setOnPreparedListener(this);
    mp.setOnCompletionListener(this);
    mp.setOnErrorListener(this);
}

public void setList(ArrayList<Song> theSong) {
    songs = theSong;
}

public class MusicBinder extends Binder {
    MusicService getService() {
        return MusicService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return musicBind;
}

@Override
public boolean onUnbind(Intent intent) {
    mp.stop();
    mp.release();
    return false;
}

public void playSong() {
    mp.reset();
    Song playSong = songs.get(songPosition);
    songTitle = playSong.getTitle();
    long currSong = playSong.getID();
    Uri trackUri = ContentUris.withAppendedId(
            android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
            currSong);
    try {
        mp.setDataSource(getApplicationContext(), trackUri);
    } catch (Exception e) {
        Log.e("MUSIC SERVICR", "Error setting data source", e);
    }
    mp.prepareAsync();
}

public void setSong(int songIndex) {
    songPosition = songIndex;
}

@Override
public void onCompletion(MediaPlayer mp) {
    if (mp.getCurrentPosition() > 0) {
        mp.reset();
        playNext();
    }
}

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    Log.v("MUSIC PLAYER", " Playback Error");
    mp.reset();
    return false;
}

@Override
public void onPrepared(MediaPlayer mp) {
    mp.start();
}

public int getPosition() {
    return mp.getCurrentPosition();
}

public int getDur() {
    return mp.getDuration();
}

public boolean isPng() {
    return mp.isPlaying();
}

public void pausePlayer() {
    mp.pause();
}

public void seek(int position) {
    mp.seekTo(position);
}

public void go() {
    mp.start();
}

public void playPrev() {
    songPosition--;
    if (songPosition < 0)
        songPosition = songs.size() - 1;
    playSong();
}

public void playNext() {
    if (shuffle) {
        int newSong = songPosition;
        while (newSong == songPosition) {
            newSong = random.nextInt(songs.size());
        }
        songPosition = newSong;
    } else {
        songPosition++;
        if (songPosition >= songs.size())
            songPosition = 0;
    }
    playSong();
}

public void onDestroy() {
    stopForeground(true);
    ;
}

public void setShuffle() {
    if (shuffle)
        shuffle = false;
    else
        shuffle = true;
}

LOGCAT

04-19 23:37:04.917:E/AndroidRuntime(8932):at android.widget.AdapterView.performItemClick(AdapterView.java:301)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.widget.AbsListView.performItemClick(AbsListView.java:1510)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.widget.AbsListView$PerformClick.run(AbsListView.java:3339)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.widget.AbsListView.onTouchEvent(AbsListView.java:4635)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.View.dispatchTouchEvent(View.java:7817)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2435)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2159)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2441)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2174)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2441)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2174)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2441)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2174)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewGroup.dispatchTransformedTouchEvent(ViewGroup.java:2441)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewGroup.dispatchTouchEvent(ViewGroup.java:2174)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.View.dispatchPointerEvent(View.java:8025)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewRootImpl$ViewPostImeInputStage.processPointerEvent(ViewRootImpl.java:4675)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:4563)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4157)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4214)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4183)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:4268)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4191)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:4325)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4157)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:4214)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:4183)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:4191)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:4157)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewRootImpl.deliverInputEvent(ViewRootImpl.java:6317)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewRootImpl.doProcessInputEvents(ViewRootImpl.java:6255)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewRootImpl.enqueueInputEvent(ViewRootImpl.java:6226)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.ViewRootImpl$WindowInputEventReceiver.onInputEvent(ViewRootImpl.java:6397)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.view.InputEventReceiver.dispatchInputEvent(InputEventReceiver.java:188)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.os.MessageQueue.nativePollOnce(Native Method)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.os.MessageQueue.next(MessageQueue.java:132)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.os.Looper.loop(Looper.java:124)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at android.app.ActivityThread.main(ActivityThread.java:5493)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at java.lang.reflect.Method.invokeNative(Native Method)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at java.lang.reflect.Method.invoke(Method.java:525)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1209)
  04-19 23:37:04.917:E/AndroidRuntime(8932): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1025)
  04-19 23:37:04.917:E/AndroidRuntime(8932):at dalvik.system.NativeStart.main(Native Method)

A: You need to add a public method songPicked() in your Activity.
If you read the complete tutorial on Step 3
Remember that we added an onClick attribute to the layout for each item in the song list. Add that method to the main Activity class
So , when an item is clicked this songPicked will be called , which is expected to be public method in your Activity.
 public void songPicked(View view){
    musicService.setSong(Integer.parseInt(view.getTag().toString()));
    musicService.playSong();
}

You can remove the setOnItemClickListener code if you add the method or remove the onClick="songPicked" from the layout


text:
Q: how do i make a 3d character move in unity with WASD? I am new to Unity, and I want to make a 3d character movement. Please help me. I have tried tutorials, but they don't work.

A: You first have to choose what kind of movement you want to accomplish i.e: 1st person, 3rd person etc. And saying that YouTube tutorials don't work definitely means you are missing something. Here are some good tutorials for different 3d movement. Please follow them thoroughly.
1st Person:

*

*https://www.youtube.com/watch?v=_QajrabyTJc

*https://www.youtube.com/watch?v=XAC8U9-dTZU
3rd Person:

*

*https://www.youtube.com/watch?v=4HpC--2iowE
You can find a ton more movement systems on Google.
Your movement depends on your usage. You have to use a different approach if you want it to be Character Controller based than Rigidbody based. So learn the basics, and then experiment on your own until you are happy with it.

A: There are tons of ways to make a player move in 3D, and there are just as many tutorials that explain it.  If you need a place to start, see the character controller component.
If you have a 3d model of the character, just add this component and it will start moving right away.
the gameobject does not have to have rigidbody or collider components, because it takes care of the whole character controller.
If I gave you a hand to get started, you can mark my answer as accepted, and vote it positively :)


text:
Q: Find Jordan Decomposition of $\left(\begin{smallmatrix} 4 & 0 & 1 \\ 0 & 1 & 0 \\ 1 & 0 & 3 \end{smallmatrix}\right)$ over $\mathbb{F}_5$
Find the Jordan decomposition of
$$
A := \begin{pmatrix} 4 & 0 & 1 \\ 0 & 1 & 0 \\ 1 & 0 & 3 \end{pmatrix}
\in M_3(\mathbb{F}_5),
$$
where $\mathbb{F}_5$ is the field modulo 5.

What I've done so far
The characteristic polynomial is
\begin{equation}
P_A(t) = (4 - t)(1-t)(3-t) - (1-t)
= -t^3 + 8t^2-18t+1
\equiv 4t^3 + 3t^2 + 2t + 1 \mod5.
\end{equation}
Therefore, $\lambda = 1$ is a zero of $P_A$, since $4+3+2+1 = 10 \equiv 0 \mod 5$.
By polynomial division one obtains
$$
P_A(t)
= (t + 4)(4t^2 + 2t + 4)
= (t + 4)(t + 4) (4t + 1)
\equiv 4 (t + 4)^3
$$
Therefore $\lambda = 1$ is the only eigenvalue of $A$.
To find the eigenspace we calculate the kernel of $A + 4 E_3$ and obtain
$$
\text{span}\left( \begin{pmatrix} 1 \\ 0 \\ 2 \end{pmatrix}, \begin{pmatrix} 1 \\ 1 \\ 2 \end{pmatrix} \right)
$$
Since $(A + 4 E_3)^2 = 0$, the kernel of $(A + 4 E_3)^2$ is the whole space.
Now, I choose $v := (1, 0, 0) \in \text{ker}(A + 4 E_3)^2$ such that $v \not\in \text{ker}(A + 4 E_3)$.
We calculate $(A + 4E)v = (3, 0, 1)$ and then
$$
(A + 4E)
\begin{pmatrix} 3 \\ 0 \\ 1\end{pmatrix}
= \begin{pmatrix} 0 \\ 0 \\ 0 \end{pmatrix},
$$
but the zero vector can't be a basis vector of our Jordan decomposition.
Have I made a mistake in my calculations?

A: Your calculations are fine. However, by definition of kernels, an element of the kernel of $(A+4E)^2$ vanishes when applying $A+4E$ to it twice, so you should not be surprised. You just made the wrong conclusion. The eigenvector $(3,0,1)$ together with the generalized eigenvector $(1,0,0)$ form part of a Jordan basis giving you a Jordan block of size $2$. All you need to do is add another eigenvector which is linear independent to $(3,0,1)$, for example $(1,1,2)$.
Then
$$
\begin{pmatrix}
3 & 1 & 1 \\
0 & 0 & 1 \\
1 & 0 & 2
\end{pmatrix}^{-1}
\begin{pmatrix}
4 & 0 & 1 \\
0 & 1 & 0 \\
1 & 0 & 3
\end{pmatrix}
\begin{pmatrix}
3 & 1 & 1 \\
0 & 0 & 1 \\
1 & 0 & 2
\end{pmatrix}
=
\begin{pmatrix}
1 & 1 & 0 \\
0 & 1 & 0 \\
0 & 0 & 1
\end{pmatrix}.
$$

A: Since $(A-I)(1,0,0)^T=(3,0,1)^T=3(1,0,2)^T$, a desired ordered basis is given by $\{(1,0,2)^T,\frac13(1,0,0)^T,(1,1,2)^T\}=\{(1,0,2)^T,(2,0,0)^T,(1,1,2)^T\}$.

A: You want three independent vectors, $v_1,v_2,v_3$ that have the properties:
$$Av_1=v_1, Av_2=v_2+v_1, Av_3=v_3.\tag{1}$$
For $v_2=(1,0,0)^T$ not in the eigenspace, we get $v_1=Av_2-v_2=(3,0,1)^T$ [*] and then you need a $v_3$ which is in the eigenspace of $A$ but not a multiple of $v_1.$ We'll choose $v_3=(0,1,0)^T.$ Then if $$S=\begin{pmatrix}v_1&v_2&v_3\end{pmatrix}=\begin{pmatrix}3&1&0\\0&0&1\\1&0&0\end{pmatrix}$$ then we can show:
$$J=\begin{pmatrix}1&1&0\\0&1&0\\0&0&1\end{pmatrix}=S^{-1}AS$$
Since $Se_i=v_i$ and the equalities in (1) and and $S^{-1}v_i=e_i,$ so we get $$Je_1=e_1,Je_2=e_1+e_2,Je_3=e_3$$
Since $\det S = 1$ even in the integers, we can use Wolfram Alpha to invert $S$ over the integers and get $$S^{-1}=\begin{pmatrix}0&0&1\\1&0&-3\\0&1&0
\end{pmatrix}$$

[*] Note that since $(A-E_3)^2=0,$ you have $A^2-A=A-E_3$ and hence, when $v_1=Av_2-v_2,$ you have $Av_1=(A^2-A)v_2=(A-E_3)v_2=Av_2-v_2=v_1.$

We could have started with any $v_2$ not in the eigenspace. We'll always get some multiple of our original $v_1$ for $v_1.$ Then $v_3$ can be any of $20$ vectors in the eigenspace not a multiple of $v_1.$

A: Here is a 4th answer that takes into account that we are in a particular case yielding a reduction to a $2 \times 2$ matrix.
Indeed, up to a simultaneous permutation $P$ on lines and columns, $A=PBP^{-1}$ is similar to
$$B:= \left(\begin{array}{cc|c} 4 & 1 & 0 \\ 1 & 3 & 0 \\ \hline 0 & 0 & 1 \end{array}\right)$$
On this form, we have reduced the issue to find a Jordan form for $2 \times 2$ upper block $U$.
A quick computation shows that $1$ is a double eigenvalue of $U$.
The Jordan form of $U$ is :
$$\left(\begin{array}{cc} 1 & 1 \\ 0 & 1  \end{array}\right)$$
because (due to a quick reasoning, that has been developed in the other answers, but with simpler computations) :
$$\underbrace{\left(\begin{array}{cc} 1 & 2 \\ 2 & 0  \end{array}\right)}_{Q}\left(\begin{array}{cc} 1 & 1 \\ 0 & 1  \end{array}\right)\underbrace{\left(\begin{array}{cc} 0 & 3 \\ 3 & 1  \end{array}\right)}_{Q^{-1}}=\left(\begin{array}{cc} 4 & 1 \\ 1 & 3  \end{array}\right).$$
The Jordan form of $B$, which is the same as the Jordan form of $A$, is thus :
$$J:= \left(\begin{array}{cc|c} 1 & 1 & 0 \\ 0 & 1 & 0 \\ \hline 0 & 0 & 1 \end{array}\right).$$


text:
Q: Meaning of you in the sentence

I believe in love and hope.
  In jamming out by yourself in your room.
  I believe in having someone tell you
  You're beautiful.
  I believe in miracles.
  I believe in smiling until your cheeks hurt
  and laughing until you cry.
  But above all... I believe in God
  and His unfailing Love.

What is the meaning of you here?
I guess you here refers to you all....

A: In very formal English, people use the word one to mean people in general.

One should always be polite
  ..meaning
People in general should always be polite

In informal English, people use the word you in the same way, meaning people in general. I think that is the intended meaning in this collection of maxims.

I believe in smiling till your cheeks hurt
  ...meaning
  I believe that people in general should smile until their cheeks hurt.


text:
Q: How to assign a name for a pytorch layer? Following a previous question, I want to plot weights, biases, activations and gradients to achieve a similar result to this.
Using
for name, param in model.named_parameters():
    summary_writer.add_histogram(f'{name}.grad', param.grad, step_index)

as was suggested in the previous question gives sub-optimal results, since layer names come out similar to '_decoder._decoder.4.weight', which is hard to follow, especially since the architecture is changing due to research. 4 in this run won't be the same in the next, and is really meaningless.
Thus, I wanted to give my own string names to each layer.

I found this Pytorch forum discussion, but no single best practice was agreed upon.
What is the recommended way to assign names to Pytorch layers?
Namely, layers defined in various ways:

*

*Sequential:

self._seq = nn.Sequential(nn.Linear(1, 2), nn.Linear(3, 4),)

*Dynamic:

self._dynamic = nn.ModuleList()
    for _ in range(self._n_features):
        self._last_layer.append(nn.Conv1d(in_channels=5, out_channels=6, kernel_size=3, stride=1, padding=1,),)

*Direct:

self._direct = nn.Linear(7, 8)

*Other ways I didn't think about

I would like to be able to give a string name to each layer, defined in each of the above ways.

A: Sequential
Pass an instance of collections.OrderedDict. Code below gives conv1.weights, conv1.bias, conv2.weight, conv2.bias (notice lack of torch.nn.ReLU(), see end of this answer).
import collections

import torch

model = torch.nn.Sequential(
    collections.OrderedDict(
        [
            ("conv1", torch.nn.Conv2d(1, 20, 5)),
            ("relu1", torch.nn.ReLU()),
            ("conv2", torch.nn.Conv2d(20, 64, 5)),
            ("relu2", torch.nn.ReLU()),
        ]
    )
)

for name, param in model.named_parameters():
    print(name)

Dynamic
Use ModuleDict instead of ModuleList:
class MyModule(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.whatever = torch.nn.ModuleDict(
            {f"my_name{i}": torch.nn.Conv2d(10, 10, 3) for i in range(5)}
        )

Will give us whatever.my_name{i}.weight (or bias) for each created module dynamically.
Direct
Just name it however you want and that's how it will be named
self.my_name_or_whatever = nn.Linear(7, 8)

You didn't think about

*

*If you want to plot weights, biases and their gradients you can go along this route

*You can't plot activations this way (or output from activations). Use PyTorch hooks instead (if you want per-layer gradients as they pass through network use this also)

For last task you can use third party library torchfunc (disclaimer: I'm the author) or go directly and write your own hooks.


text:
Q: Maven build on save I just jumped into a webapplication that uses Maven. It's a project that's been around for some months now and a lot have people worked on it and left. So it's a mess and there hasn't been a lot of documenting around it.
So I've been trying to find my way around the project and something I've been running into is that I have to build 2 folders, move a file into the server folder to see the changes I've made. This is a slow and tedious process, so I'm trying to speed it up.
We are all using the Eclipse IDE and after I've done changes in the code I have to right click a the rootfolder > run as > maven build > goals: clean install. This I have to do for two folders.
Then I have to close Wildfly (the server app for the project) and move a .ear file from folder a to b and restard Wildfly to see my changes. As you can see this takes quite some actions so I'm looking for a method to automate this.
Is it possible to configure this in Eclipse or should I look into creating a .bat file that a user can run that performs the actions stated above?

A: Eclipse by default should build each class file as you edit it.
I would suggest running Wildfly within Eclipse.  Take a look at JBoss tools for some better integration in this area. Once you have it configured to run within Eclipse then it should auto reload the files as you edit them - no need to even restart Wildfly.

A: I've created a batch file:
rem run a maven clean install
cd C:\Users\A647450\workspace\****\*****
call mvn clean install
rem run a maven clean install
cd C:\Users\A647450\workspace\*****\****
call mvn clean install
rem copy created EAR file to Wildfly folder
copy C:\Users\A647450\workspace\****\****\target\****-1.2.1-SNAPSHOT.ear C:\wildfly-10.1.0.Final\standalone\deployments\****-1.2.1-SNAPSHOT.ear /y

This does get the job done, but takes a while.


text:
Q: Objects disappearing once constructor finishes I suspect there is a term for this behavior that, if I knew it, I could google it and learn what I need. However, I don't know it.
Here is my constructor:
[Export(typeof(MainWindowViewModel))]
public class MainWindowViewModel : ObservableObject
{
    private readonly IProductService _productService;
    private readonly IProfileService _profileService;
    public IEnumerable<ProductViewModel> Products { get; private set; }
    private ProductViewModel _productSelected;

    [ImportingConstructor]
    public MainWindowViewModel(IProductService productService, IProfileService profileService, ILoggingService logger)
    {
        Products = _productService.InstalledProducts.Select(p => new ProductViewModel(p, _profileService, _logger));
        SelectTheProductInDirectoryRunningFrom();

        _productSelected.Load();
    }

    protected virtual void SelectTheProductInDirectoryRunningFrom()
    {
        string currentDir = Directory.GetCurrentDirectory();

        if (_productSelected != null && _productSelected.InstalledPath != null &&
                !_productSelected.InstalledPath.Contains(currentDir))
        {
            _productSelected =
                Products.Where(p => currentDir.Contains(p.InstalledPath)).Select(p => p).DefaultIfEmpty(
                    _productSelected).SingleOrDefault();
        }
    }

It seems pretty self-explanatory. It builds a collection of ProductViewModels, finds the relevant one, and calls Load() on it. ProductViewModel.Load() contains this code:
public class ProductViewModel : ObservableObject
{
    private readonly IProfileService _profileService;
    private readonly ILoggingService _logger;
    private ObservableCollection<ProfileViewModel> _profiles;
    private ConfigProfile _defaultConfig;
    private ProfileViewModel _currentProfile;
    public ListCollectionView Profiles { get; set; }

public bool Load(string errorMessage, bool critical)
{
    List<ProfileViewModel> profileVms = new List<ProfileViewModel> { _currentProfile };

    profileVms.AddRange(
        _profileService.GetSavedProfiles(_data.ProductType).Select(
            p =>
            {
                p.FilePath = current.FilePath;
                return new ProfileViewModel(p, _defaultConfig, _profileService) { IsChanged = false };
            }));
    _profiles = new ObservableCollection<ProfileViewModel>(profileVms);

    Profiles = new ListCollectionView(_profiles);
    Profiles.SortDescriptions.Add(new SortDescription("ProfileTypeValue", ListSortDirection.Ascending));
    Profiles.SortDescriptions.Add(new SortDescription("ProfileName", ListSortDirection.Ascending));
    Profiles.CurrentChanged += (sender, args) =>
    {
        ((ProfileViewModel)Profiles.CurrentItem).Initialize();
        _currentProfile = Profiles.CurrentItem as ProfileViewModel;
    };

    return true;
}

When I step through this code in the visual studio debugger, everything executes and both _profiles and Profiles are assigned to correctly. However, when execution returns from the MainWindowViewModel constructor, _profiles and Profiles are both null.

I press F11 twice to arrive here:

What could be going wrong? Are my objects somehow passing out of scope? I thought maybe it had something to do with value vs reference but I can't find anything. Thanks!

A: Assigning to an object from a WhereSelectEnumerableIterator creates a new object so the original list wasn't being updated.
_productSelected =
    Products.Where(p => currentDir.Contains(p.InstalledPath)).Select(p => p).DefaultIfEmpty(
        _productSelected).SingleOrDefault();

I added a .ToList() onto this call
Products = _productService.InstalledProducts.Select(p => new ProductViewModel(p, _profileService, _logger));

to force the IEnumerable into a List which does not create a new object and does update the existing one. Thanks @Igor.


text:
Q: Send email with HTML signature, the signature is in html code Referring to this thread I'm able to retrieve my signature from Gmail with the code var signature = Gmail.Users.Settings.SendAs.list("me").sendAs.filter(function(account){if(account.isDefault){return true}})[0].signature;
But if I attach the retrieved HTML to the email body, the recipient see the raw code instead of my signature.
I red many threads with this problem, but I'm unable to understand how fix this, I'm not expert with HTML.
Please could someone help me?

A: GmailApp allows you to parse html using htmlBody:
var signature = Gmail.Users.Settings.SendAs.list("me").sendAs.filter(function(account){if(account.isDefault){return true}})[0].signature;
GmailApp.sendEmail("email@gmaiil.com", "signature test", "test", {htmlBody: signature})

Update:
The signature of GmailApp.sendEmail is:

*

*sendEmail(recipient, subject, body, options)
or:

*sendEmail(recipient, subject, body)
In your case, you need to use option 1.
replyTo is specified using the options object.
So, to summarize, here is your code:
mia_firma = '<p>' + corpo + '</p>' + mia_firma; // concat htmlBody
MailApp.sendEmail(dest, // recipient email - string
                  sogg, // should be subject - string
                  corpo, // mail body - WILL BE IGNORED if you use htmlBody
                  { // options - object
                      htmlBody: mia_firma,
                      replyTo: "reply_to@XYZ.page"
                  }
);

You can see the full documentation here


text:
Q: how to add header and footer in PDF to be generated using iText in JSP only I have gone through many post but I am not getting anything useful, as they are all about adding header and footer to existing PDF. What I want is that i want to create header and footer automatically at runtime when PDF is created.
I don't have much knowledge of java, so these classes and interface are out of my knowledge
what I have tried is
Jsp Page
    <%

Phrase header;
PdfPTable footer;

try{

Document document = new Document(PageSize.A4, 36, 36, 54, 54);
// step 2
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\lata.pdf"));
HeaderFooter event = new HeaderFooter();
writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));
writer.setPageEvent(event);//**problem: The constructor HeaderFooter() is undefined**
// step 3
document.open();
for(int i=0;i<1000;i++){
document.add(new Phrase("lata "));
}
document.close();
}catch(Exception e){
}%>

Is it possible to call that function or create a PDF file with iText just by placing code in the JSP page or any other simple solution? What I want to add image at the end of every pdf page.

A: ANSWER TO: Is it possible to call that function or create a PDF file with iText just by placing code in the JSP page or any other simple solution?
To develop this code, first do it in a simple java application, say inside
public static void main(String[] args) {
    ...
}

That is the hardest part, especially as iText is concerned.
When it works,

*

*port the code to a JSP,

*setting the content type to PDF ("application/x-pdf").

*and making sure there is no additional output between %> and <%,

*output the file data (write to response.getOutputStream()).

or instead of immediately outputting the PDF:

*

*redirect to a written copy of the PDF in the web directory.

Porting to JSP:

*

*The import statements can be placed in the page directive.

*Declarations of global constantsand methods/functions can be placed in <%! ... %>.

*Add the required library jars.

You will need to search examples.

I take it, that this was your source. To create the inner class TableHeader aka HeaderFooter:
<%!
class HeaderFooter extends PdfPageEventHelper {
...
}
%>


text:
Q: JavaScript to generate the questions using random numbers using Select operators randomly(+,*,-) for each equation I want to do this math game that generates numbers and operators randomly.
This is hint - x = Math.floor(Math.random()*101); will generate a random number between 0 and 100. Select operators randomly (+,*,-) for each equation. Please any one can help me.

var arr = []
while(arr.length < 8){
    var r = Math.floor(Math.random()*100) + 1;
    if(arr.indexOf(r) === -1) arr.push(r);
}
document.write(arr);

A: Here's an ES6 implementation of that, I used console.log instead of document.write

let questionsCount = 10;

function generateQuestions() {
    let questions = [];

    for(let i = 0;i < questionsCount;i++) {
      let n1 = Math.floor(Math.random() * 101);
      let n2 = Math.floor(Math.random() * 101);
      let operatorObj = randomOperator(n1,n2)
      questions.push({
         question: `${n1} ${operatorObj.operator} ${n2} ?`,
         answer: operatorObj.answer
      });
    }

    return questions;
}

 function randomOperator(n1,n2) {
    let n = Math.floor(Math.random() * 4);
    switch (n) {
       case 0:
         return {operator: '+', answer: n1 + n2};
       case 1:
         return {operator: '-', answer: n1 - n2}
       case 2:
         return {operator: '*', answer: n1 * n2}
       case 3:
         return {operator: '/', answer: n1 / n2}
    }
 }

let questions = generateQuestions();

let answers = questions.map((question) =>
     prompt(question.question));

answers.forEach((answer,i) => {
    console.log(`${questions[i].question} ${answer} ${(answer ==
       questions[i].answer) ? 'Correct': `Wrong should be
       ${questions[i].answer}`}`)
});

A: You can use switch-case statement to select the operator and use Math.random() to randomize it
var arr = []
while(arr.length < 8){
    var r = Math.floor(Math.random()*100) + 1;
    if(arr.indexOf(r) === -1) arr.push(r);
}

for (var i=0; i<4; i++) {
    operator = Math.floor(Math.random() * 3);
    switch(operator) {
        case 0:
            eval(prompt(arr[i*2] + " + " + arr[i*2+1]));
            break;
        case 1:
            eval(prompt(arr[i*2] + " - " + arr[i*2+1]));
            break;
        case 2:
            eval(prompt(arr[i*2] + " * " + arr[i*2+1]));
            break;
    }
}

A: Better solution: While it doesn't use prompts I'm sure you can figure that part out.
works best on codepen, and not very well inside the awkward snippet
feature that stack-overflow provides (due to the reset button triggering reload)
here's the code in case your interested:

//Solve the equation - math problem game

//change * 4 if you want more operators then add the
//operator as a string inside the operator array...
//you may also add duplicate operators to increase odds
//higher odds of harder operator = harder mode
var a = location;
function start() {
document.body.innerHTML = null;
var operators = ["/", "*", "-", "+"],
  arr = [],
  arrCompiled,
  i = 0, a = location;
while (arr.length < 8) {
  var r = Math.floor(Math.random() * 100) + 1;
  if (arr.indexOf(r) === -1) arr.push(r);
}
while(i < arr.length) {
  var oper = ' '+operators[Math.floor(Math.random() * 4)]+' ';
  if (i === 0) {
    arrCompiled = arr.toString()
.replace(/,/, oper);
  }

  arrCompiled = arrCompiled.replace(/,/, oper);
  i++;
}
document.write('
'+arrCompiled+' = ???
');
document.getElementById("questions").insertAdjacentHTML('afterend', '<button id="solve">Solve</button>');
}
start();

document.getElementById('solve').addEventListener('click', function() {
  if (document.getElementById('solve')) {
  var x = document.getElementById('questions').innerText.replace(/\?/g, "");
  var y = x.replace(/[^0-9*/+-.()]+/g, "");
  var z = Math.round(eval(y) * 100) / 100;
  document.write(x + z + ' - solved <button>New Problem</button>');
  document.getElementById('questions').remove();
  }
});

A:

var arr = []
while(arr.length < 8){
    var r = Math.floor(Math.random()*100) + 1;
    if(arr.indexOf(r) === -1) arr.push(r);
}
document.write(arr);


text:
Q: html code in javascript not getting the id to open to another window I have a html inside a javascript. My problem is I cant call the id in my html code. Can someone help me with this?
My code:

I'm using ttwnotificationmenu.js from www.codebasehero.com.
So my problem is getting the id in the html code hope someone will help me with this.


text:
Q: Alternative for using multiple callouts from Salesforce to external System We retrieve a list of flight passengers from an external system via a callout. The endpoint sends us a passenger list along with arrival and departure airport codes. Our external system has another endpoint that translates airport codes to their names. We would like to retrieve the airport name based on its code in order to send an email with flight information (incl. airport name) to the user.
I am little wary of calling out to the external system every time we need to translate an airport code to its corresponding name.
Assuming the mapping of codes to names won't change that often, how do I avoid multiple callouts?
I was thinking of these options:

*

*Platform Cache. Load all airport codes and city names into cache and then do probably a monthly retrieve

*An external object. Need to check if they have required adapter to connect the database.

*Custom metadata to store code/name mappings.

Just to add: If the external system does not have the endpoint to query all the airport names and only have endpoint where they expect a set of airport codes,how should we go about it then?


text:
Q: Javascript and jquery script only changes class once I'm creating a webpage for school home work and I'm making a dropdown into a nav, to show it I use javascript and jquery but it only works once, I can open the dropdown but I cannot close it.
I've tried bunch of ways to do this like using only javascript, or using toggle class but it didn't work

   Your Name

Action

Another action

Logout

var x = 0;
if (x == 0){
$("#yname").click(function(){
$("#dropdowncontent").removeClass("dropdown-content");
$("#dropdowncontent").addClass("dropdown-content-show");
var x = 1;
});
}

else {
$("#yname").click(function(){
$("#dropdowncontent").removeClass("dropdown-content-show");
$("#dropdowncontent").addClass("dropdown-content");
var x = 0;
});
}

.dropdown-content-show {
    display: block;
}

.dropdown-content {
    display: none;
}

I expected to show dropdown and hide dropdown but it only shows

A: You only ever assign the first click handler.  Consider the logic of these two lines of code:
var x = 0;
if (x == 0){

The variable x will always equal 0 in that condition.  Because it was explicitly set to 0 immediately before checking it.
Put the conditional logic inside the click handler, instead of conditionally creating the handler.  Something like this:
var x = 0;

$("#yname").click(function(){
    if (x == 0) {
        $("#dropdowncontent").removeClass("dropdown-content");
        $("#dropdowncontent").addClass("dropdown-content-show");
        x = 1;
    } else {
        $("#dropdowncontent").removeClass("dropdown-content-show");
        $("#dropdowncontent").addClass("dropdown-content");
        x = 0;
    }
});

(Note also the removal of var when re-assigning the variable.  That was creating a new variable within that scope, which isn't what you want.)
Though logically you should be able to simplify this to something like:
$("#yname").click(function(){
    $("#dropdowncontent").toggleClass("dropdown-content");
    $("#dropdowncontent").toggleClass("dropdown-content-show");
});

A: First of all, dont use X as a conditional like that. Instead of using X and changing its value if the user has clicked, you should make use of the classList.contains()method.
You should also be handling the condition after the event.
Basically, the code should be handled like this:
$("#yname").click(function(){
    if($("#dropdowncontent").classList.contains("dropdown-content")){
        $("#dropdowncontent").classList.remove("dropdown-content")
        $("#dropdowncontent").classList.add("dropdown-content-show")
    } else {
        $("#dropdowncontent").classList.add("dropdown-content")
        $("#dropdowncontent").classList.remove("dropdown-content-show")
    }
}

This is a decent improvement over your code, but still very goofy. If you want to advance in JavaScript, just learn the language. There are no shortcuts like jQUery, just learn JS and then move on to something like React JS

A: Replace
 Your Name

with :
 Your Name

and inside js script add this:
function toggleFunction() {
var element = document.getElementById("dropdowncontent");
element.classList.toggle("dropdown-content");}

Demo:  https://codepen.io/endritspahiu/pen/oNNyaMQ


text:
Q: PBKDF2 in Bouncy Castle C# I've being messing around the C# Bouncy Castle API to find how to do a PBKDF2 key derivation.
I am really clueless right now.
I tried reading through the Pkcs5S2ParametersGenerator.cs and PBKDF2Params.cs files but i really cant figure out how to do it.
According to the research I have done so far, PBKDF2 requires a string (or char[]) which is the password, a salt and an iteration count.
So far the most promising and most obvious i've come so far is the PBKDF2Params and Pkcs5S2ParametersGenerator.
None of these seems to be accepting a string or a char[].
Has anyone done this in C# or have any clue about this? Or perhaps someone who has implemented BouncyCastle in Java and can help?
Thanx a lot in advance :)
UPDATE: I have found how to do this in Bouncy Castle. Look below for answer :)

A: I just had this problem myself, and found a more direct approach.  As of at least Bouncy Castle 1.7 you can do it like this (in VB using Org.BouncyCastle.Crypto):
Dim bcKeyDer As New Generators.Pkcs5S2ParametersGenerator()
bcKeyDer.Init(password, salt, keyIterations)
Dim bcparam As Parameters.KeyParameter = bcKeyDer.GenerateDerivedParameters("aes256", 256)
Dim key1() As Byte = bcparam.GetKey()

I have tested this against .Net's System.Security.Cryptography, and it works!

A: After hours and hours of going through the code, I found that the easiest way to do this is to take a few parts of the code in Pkcs5S2ParametersGenerator.cs and create my own class which of course use other BouncyCastle API's. This works perfectly with the Dot Net Compact Framework (Windows Mobile). This is the equivalent of Rfc2898DeriveBytes class which is not present in the Dot Net Compact Framework 2.0/3.5. Well, maybe not the EXACT equivalent but does the job :)
This is PKCS5/PKCS#5
The PRF (Pseudo Random Function) which is used will be HMAC-SHA1
First things, first. Download the Bouncy Castle compiled assembly from http://www.bouncycastle.org/csharp/, add the BouncyCastle.Crypto.dll as a reference to your project.
After that create new class file with the code below.
using System;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;

namespace PBKDF2_PKCS5
{
    class PBKDF2
    {

        private readonly IMac hMac = new HMac(new Sha1Digest());

        private void F(
            byte[] P,
            byte[] S,
            int c,
            byte[] iBuf,
            byte[] outBytes,
            int outOff)
        {
            byte[] state = new byte[hMac.GetMacSize()];
            ICipherParameters param = new KeyParameter(P);

            hMac.Init(param);

            if (S != null)
            {
                hMac.BlockUpdate(S, 0, S.Length);
            }

            hMac.BlockUpdate(iBuf, 0, iBuf.Length);

            hMac.DoFinal(state, 0);

            Array.Copy(state, 0, outBytes, outOff, state.Length);

            for (int count = 1; count != c; count++)
            {
                hMac.Init(param);
                hMac.BlockUpdate(state, 0, state.Length);
                hMac.DoFinal(state, 0);

                for (int j = 0; j != state.Length; j++)
                {
                    outBytes[outOff + j] ^= state[j];
                }
            }
        }

        private void IntToOctet(
            byte[] Buffer,
            int i)
        {
            Buffer[0] = (byte)((uint)i >> 24);
            Buffer[1] = (byte)((uint)i >> 16);
            Buffer[2] = (byte)((uint)i >> 8);
            Buffer[3] = (byte)i;
        }

        // Use this function to retrieve a derived key.
        // dkLen is in octets, how much bytes you want when the function to return.
        // mPassword is the password converted to bytes.
        // mSalt is the salt converted to bytes
        // mIterationCount is the how much iterations you want to perform.

        public byte[] GenerateDerivedKey(
            int dkLen,
            byte[] mPassword,
            byte[] mSalt,
            int mIterationCount
            )
        {
            int hLen = hMac.GetMacSize();
            int l = (dkLen + hLen - 1) / hLen;
            byte[] iBuf = new byte[4];
            byte[] outBytes = new byte[l * hLen];

            for (int i = 1; i <= l; i++)
            {
                IntToOctet(iBuf, i);

                F(mPassword, mSalt, mIterationCount, iBuf, outBytes, (i - 1) * hLen);
            }

        //By this time outBytes will contain the derived key + more bytes.
       // According to the PKCS #5 v2.0: Password-Based Cryptography Standard (www.truecrypt.org/docs/pkcs5v2-0.pdf)
       // we have to "extract the first dkLen octets to produce a derived key".

       //I am creating a byte array with the size of dkLen and then using
       //Buffer.BlockCopy to copy ONLY the dkLen amount of bytes to it
       // And finally returning it :D

        byte[] output = new byte[dkLen];

        Buffer.BlockCopy(outBytes, 0, output, 0, dkLen);

        return output;
        }

    }
}

So how to use this function? Simple! :)
This is a very simple example where the password and the salt is provided by the user.
private void cmdDeriveKey_Click(object sender, EventArgs e)
        {
            byte[] salt = ASCIIEncoding.UTF8.GetBytes(txtSalt.Text);

            PBKDF2 passwordDerive = new PBKDF2();

      // I want the key to be used for AES-128, thus I want the derived key to be
      // 128 bits. Thus I will be using 128/8 = 16 for dkLen (Derived Key Length) .
      //Similarly if you wanted a 256 bit key, dkLen would be 256/8 = 32.

            byte[] result = passwordDerive.GenerateDerivedKey(16, ASCIIEncoding.UTF8.GetBytes(txtPassword.Text), salt, 1000);

           //result would now contain the derived key. Use it for whatever cryptographic purpose now :)
           //The following code is ONLY to show the derived key in a Textbox.

            string x = "";

            for (int i = 0; i < result.Length; i++)
            {
                x += result[i].ToString("X");
            }

            txtResult.Text = x;

        }

How to check whether this is correct?
There is an online javascript implementation of PBKDF2
http://anandam.name/pbkdf2/
I got consistent results :)
Please report if anyone is getting an incorrect result :)
Hope this helps someone :)
UPDATE: Confirmed working with test vectors provided here
https://datatracker.ietf.org/doc/html/draft-josefsson-pbkdf2-test-vectors-00
UPDATE:
Alternatively, for the salt we can use a RNGCryptoServiceProvider. Make sure to reference the System.Security.Cryptography namespace.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

byte[] salt = new byte[16];

rng.GetBytes(salt);


text:
Q: How to mock "this" keyword in Jest Unit Testing I need to this code using Jest Unit Testing:
componentDidUpdate(prevProps) {
    if (prevProps.socialMediaId !== this.props.socialMediaId) {
      if (typeof this.window.FB !== 'undefined') {
        this.window.FB.XFBML.parse();
      }
    }
  }

using the test case:
it('should test componentDidUpdate', () => {
    props.socialMediaId = '/old_id/';
    const component = mount(<MyComponent {...props} />);
    this.window.FB = {
      XFBML: {
        parse: () => {}
      }
    };
    props.socialMediaId = '/new_id/';
    component.setProps(props);
    expect(this.window.FB.XFBML.parse).toHaveBeenCalled();
  });

But, I'm getting the error:

TypeError: Cannot read property 'window' of undefined

How to fix this issue with "this" keyword in this case?

A: Here this.window is component property that is likely used as an abstraction over window global. this inside componentDidUpdate isn't the same object as this inside a test
It can be mocked on component instance:
const component = mount(<MyComponent {...props} />);
component.instance().window = { FB: {
  XFBML: {
    parse: jest.fn()
  }
} };

As a rule of thumb, all no-op functions should be Jest stubs for testability purposes, so their calls could be asserted later if needed.


text:
Q: Passing Media from one Activity to another So I am trying to create a basic music app on android which displays the songs of the device in a list view and when one taps a particular song the app should play it on a different activity.
So far I've been able to extract the songs from sd card, create the second activity for playing the song (which is provided by a play/pause button and a seekbar).
But how would I pass the song tapped by the user in the list view to the second activity in order to play it.

A: You can use either a singleton in this case so you can create a SongManager which will be your singleton which store your song and playable in the second activity
or you can show the listview in a fragment so your SongManager is NOT a singleton but just a simple object managed by the activity which shows the fragment, when you want to play the song you can open an another fragment which will ask the song to play to the activity.
So
ACTIVITY (create the object `SongManager`)
   FRAGMENT A (ListView)
   FRAGMENT B (Play)

A: I would suggest just passing the filename as a String, i.e.
Intent intent = new Intent(ActivityA.this, ActivityB.class);
intent.putExtra("SongKey", songFileName);
startActivity(intent);

A: you need to parsing mp3 path to new activity, so new activity can play your song
              Intent intent = new Intent(getActivity(),Play.class);
                    intent.putExtra("title", titleX);
                    intent.putExtra("path", mp3path);
                    startActivity(intent);

then in play.class activity
        title = getIntent().getStringExtra("title");
        location = getIntent().getStringExtra("path");
        //other function
        mediaPlayer.setDataSource(location);
        mediaPlayer.prepare();


text:
Q: Ajax PHP wont retrieve address bar variable My current website address reads: www.mysite.com/index.php?user=123
I click a link to active an ajax page to open. The ajax page contains the following:
$usernum = $_GET["user"];
$result = mysql_query("SELECT * FROM Persons WHERE user = $usernum");

This produces an error:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\Program Files (x86)\Ampps\www\social2\profile\indexBasics.php on line 29

No error ocurrs if I hard code in a user number though, it just refuses to get the address bar variable.
Help? Advice?
----- ADDED INFO ------
<script>
window.onload = function () {
    var basics = document.getElementById('basics'),
        favorites = document.getElementById('favorites');

    basics.onclick = function() {
        loadXMLDoc('indexBasics');
        var otherClasses = favorites.className;
        if (otherClasses.contains("Active")) {
            basics.className = 'statusOptionActive';
            favorites.className = 'statusOption';
        }
    }

    favorites.onclick = function() {
        loadXMLDoc('indexFav');
        var otherClasses = basics.className;
        if (otherClasses.contains("Active")) {
            favorites.className = 'statusOptionActive';
            basics.className = 'statusOption';
        }
    }

    function loadXMLDoc(pageName)
    {
        var xmlhttp;
        if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
          }
        else
          {// code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
    xmlhttp.onreadystatechange=function()
          {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
            document.getElementById("centreCont").innerHTML=xmlhttp.responseText;
            }
          }
        xmlhttp.open("GET","../profile/" + pageName + ".php",true);
        xmlhttp.send();
        }
}
</script>

A: So you're saying that you are on www.mysite.com/index.php?user=123 when you click on your button (or whatever fire the AJAX event), you will load a different URL, which can be something like www.mysite.com/myajaxpage.php.
In that case, you may have forget to pass the user parameter to your AJAX request. So you can't access to $_GET['user'] in myajaxpage.php because it isn't defined in your URL.
Code example
If you're using jQuery, you can do this trick:
$.urlParam = function(name){
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    return results[1] || 0;
}

// ....

$.post('myajaxpage.php', {'user': $.urlParam('user')}, function(data) {
   // your stuff
});

EDIT: The author uses Vanilla JS, so this example was just pointless.


text:
Q: SFSafariViewController's navigation bar color is not solid I have a view controller and I am opening SFSafariViewController from one view controller to open a link. I have given a tink color to SFSafariViewController. But tint color which I am giving is not the same color which I have given to it. I have tried to off the translucency but still, that doesn't effect.
Below is the code which I am using to give the tint color to SFSafariViewController:
func loadUrlinWebView(urlString: String?) {
    guard let urlVal = urlString else {
        return
    }
    let url = URL(string: urlVal)
    let controller = SFSafariViewController(url: url!)
    if #available(iOS 10.0, *) {
        controller.preferredBarTintColor = UIColor(red: 234.0 / 255.0, green: 108.0 / 255.0, blue: 19.0 / 255.0, alpha: 1.0)
        controller.preferredControlTintColor = .white
    } else {
        controller.view.tintColor = UIColor(red: 234.0 / 255.0, green: 108.0 / 255.0, blue: 19.0 / 255.0, alpha: 1.0)
    }
    (controller.view.subviews[0].subviews[0] as? UINavigationBar)?.barTintColor = UIColor.tracePrimaryColor
    (controller.view.subviews[0].subviews[0] as? UINavigationBar)?.isTranslucent = false
    (controller.view.subviews[0].subviews[1] as? UIToolbar)?.barTintColor = UIColor.tracePrimaryColor
    (controller.view.subviews[0].subviews[1] as? UIToolbar)?.isTranslucent = false

    self.present(controller, animated: true, completion: nil)
    controller.delegate = self
}

The actual color which I am setting is : UIColor(red: 234.0 / 255.0, green: 108.0 / 255.0, blue: 19.0 / 255.0, alpha: 1.0)
And the color which I can see on SFSafariViewController's navigation bar is UIColor(red: 233.0 / 255.0, green: 116.0 / 255.0, blue: 47.0 / 255.0, alpha: 1.0).
Using above code I have received the actual color ( UIColor(red: 234.0 / 255.0, green: 108.0 / 255.0, blue: 19.0 / 255.0, alpha: 1.0)) on SFSafariViewController's navigation bar for the fraction of seconds then again that color changed to (UIColor(red: 233.0 / 255.0, green: 116.0 / 255.0, blue: 47.0 / 255.0, alpha: 1.0)). I don't know why this is the behaviour.
Please help me in this.


text:
Q: Error:Could not find property 'manifest' on source set 'main'. with experimental gradle plugin 0.6.0 beta5 "Error:Could not find property 'manifest' on source set 'main'" comes to console when I use following build.gradle
Note:experimental gradle plugin with version 0.6.0-beta5
build.gradle:
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle-experimental:0.6.0-beta5'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

gradle/wrapper/gradle-wrapper.properties
#Wed Oct 21 11:34:03 PDT 2015
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

app/build.gradle:
apply plugin: 'com.android.model.application'

model {
    android {
        compileSdkVersion = 23
        buildToolsVersion = "23.0.2"

        defaultConfig.with {
            applicationId = "package.name"
            minSdkVersion.apiLevel = 10
            targetSdkVersion.apiLevel = 23

            multiDexEnabled = true
        }
  }

    android.sources {
        main {
            manifest.source {
                srcDir "."
                include "AndroidManifest.xml"
            }
            java.source.srcDirs += 'src'
            resources.source.srcDirs += 'resources'
            aidl.source.srcDirs += 'aidl'
            res.source.srcDirs += 'res'
            assets.source.srcDirs += 'assets'

            jniLibs.source.srcDirs += 'jniLibs'

            jni.source.srcDirs += 'src/jni'
        }
    }
}


text:
Q: How do you slidetoggle a div while a yes or no radio is selected in javascript/jquery I haven't been able to find something that works or does what I'm looking for. I'm trying to toggle hide/show a div depending on a selected yes or no radio button. I have the following for the html
    <input type="radio" id="yes" name="radio" value="1" /> Yes
    <input type="radio" id="no" name="radio" value="2" /> No

Data

There is a lot more before and after this code in a form tag but this is the focus. The Javascript/jQuery is
$("#yes").click(function(){
    if($("#yes").is(':checked')){
        $("#more_questions").slideToggle();
    }
});

I have also tried checking to see if #yes.checked == true and that hasn't worked. I'm not sure what it is that I'm missing but if anyone could help I would really appreciate it! Thanks in advance!

A: $("input[name=radio]").on('change', function(){
    $("#more_questions")[this.id=='yes'?'slideDown':'slideUp']();
});

FIDDLE

A: Try:
$("input[name=radio]").click(function () {
    if ($("input[name=radio]:checked").val() == '1') {
        $("#more_questions").slideDown();
    } else {
        $("#more_questions").slideUp();
    }
});

jsFiddle example


text:
Q: App ID & bundle identifier: provisioning profile issues I'm working on an Ionic 3 project and just now getting around to setting up and testing notifications. I don't have prior native iOS development experience, so I've been following a few guides on how to get all the proper certificates, provisioning profiles, and other setup done correctly.
I have an Apple Developer account which I've added to Xcode and have so far been letting Xcode (version 8.3.3) handle signing automatically.
I'm implementing notifications as part of Mixpanel integration, so I've been following this guide: https://mixpanel.com/help/reference/ios-push-notifications. This guide is pretty complete- it walks the user through creating an app ID, adding push, creating & signing the required certs, creating a provisioning profile, and finally uploading those to Mixpanel. The entire process went fine.
When I connected my device in order to try and test push notifications, I started having issues building- I hadn't added the push notification Capability in Xcode, so I did that- however, when I did so, I started getting an error in the code signing config that my provsioning profile didn't include that capability. Weird, because in the details of my App ID on the Apple Developer site, I see that push notifications are enabled for development.
Upon closer inspection, I think the issue is that my App ID bundle identifier (on the Apple Dev site) and the bundle identifier in Xcode don't match. My App ID bundle identifier is:
<team_ID>.com.<domain>.app

But my bundle identifier in Xcode is:
com.<domain>.app

At the time I created the App ID, I thought the <team_ID> prefix was required for the bundle identifier in the App ID setup- but I don't think that's right. I see the prefix separately in the App ID info:

Was this the wrong thing to do? The reason I got confused and added the team ID to my App ID bundle identifier was because my bundle identifier from Xcode (com.<domain>.app) wasn't allowed. The error I got when trying to use it while creating an App ID:

To be clear- I have no other App IDs in the Apple Developer profile with this bundle identifier.
I know this identifier should be available because I've been using it in Xcode before today, with the same signing identity. Why wouldn't I be allowed to use it to create an App ID- isn't the point that the bundle ID must be the same both in that and in Xcode?
The final confusing point here (to me) is that I decided to change the bundle identifier in Xcode to match that of my App ID (to confirm that, once they matched, building would work). After I did that, Xcode seemed to accept the new bundle identifier, but I get different build errors- and if I change my signing identity, the errors that show up in the signing config don't make sense- they reference a bundle identifier that isn't the one just above in Xcode:

Specifically, why does the bundle identifier in the error not match what's set in the config at the top of the image? I've tried restarting Xcode and this still happens. At this point, I can't even build with Xcode if I remove the push capability- I get a mysterious Apple Mach-O Linker (ID) error which doesn't turn up much when googling.

A: The provisioning profile you are using is configured for the bundle identifier in the error message you are receiving. To fix this you can either:

*

*Set the bundle identifier of your app to the one you see in the
error message

*Create another provisioning profile with the bundle identifier you
would like to use in your app

You will also need to add Push Notifications to your profile. Here are some instructions on how to do this:

*

*Go to Certificates, Identifiers & Profiles and for Mac apps, choose
OS X from the pop-up menu on the left.

*Under Identifiers, select App IDs.

*Select the explicit App ID that matches the bundle ID.

*A green circle followed by "Enabled" appears in the Push
Notifications row and the Distribution column.

A: The provided answers and comments had good information, however, the only thing that worked for me was creating a new App ID that didn't conflict with the bundle identifier I had set in Xcode. I think the inclusion of my team prefix in my first App ID name played a large part in this usse, as I haven't seen that weird behavior since creating a new App ID with a normal bundle identifier.

A: In addition to the possible solutions above, if these do not work for you or if you are getting a build error that says something like:
'resource fork, Finder information, or similar detritus not allowed'
then here is the solution that worked for me:
A: This is a security hardening change that was introduced with iOS 10, macOS Sierra, watchOS 3, and tvOS 10.
Code signing no longer allows any file in an app bundle to have an extended attribute containing a resource fork or Finder info.
To see which files are causing this error, run this command in Terminal:
$ xattr -lr
replacing  with the path to your actual app bundle.
Here's an example of this command in action:
$ xattr -lr Foo.app
/Applications/Foo.app: com.apple.FinderInfo:
00000000  00 00 00 00 00 00 00 00 00 10 00 00 00 00 00 00  |................|
You can also remove all extended attributes from your app bundle with the xattr command:
$ xattr -cr
Note that browsing files within a bundle with Finder's Show Package Contents command can cause Finder info to be added to those files. Otherwise, audit your build process to see where the extended attributes are being added.
link to the original article in Apple developer library


text:
Q: Rendering an array of html elements I want to render an array of html elements in my component. The reason for storing the data/html in an array is because I want to be able to dynamically load a new element depending on a button-click.
This is how I want to display my array:

       {this.state.steps}

This is how I initiate my component and array:
  componentDidMount() {
        this.createProcessStep().then(step => {
            this.setState({steps: this.state.steps.concat(step)});
        });
    }
  export function createProcessStep() {
    this.setState({processStepCounter: this.state.processStepCounter += 1});
    return this.addStepToArray().then(d => {
        return this.reallyCreateProcessStep()
    });
  }
 addStepToArray = () => {
        const step = {
          ...Some variables...
        };
        return new Promise(resolve => {
            this.setState({
                stepsData: this.state.stepsData.concat(step)
            }, resolve)
        });
    };

"stepsData" is another array that holds data (variables) belonging to each step. "steps" on the other hand, should only hold the html.
This is how one step/element looks like:

 ...Some Content...
 <button label="+" onClick={ () => {
                            this.createProcessStep().then(step => {
                                this.setState({
                                    steps: this.state.steps.concat(step)
                                });
                            })
                        }}/>
 ...other content...

This button within each step is responsible for loading/adding yet another step to the array, which actually works. My component displays each step properly, however react doesn't properly render changes to the element/step, which is
to say that, whenever e.g. I change a value of an input field, react doesn't render those changes. So I can actually click on the "+"-button that will render the new html element but whenever a change to this element occurs,
react simply ignores the phenotype of said change. Keeping in mind that the changeHandlers for those steps/elements still work. I can change inputfields, radioButtons, checkboxes etc. which will do exactly what it's
supposed to, however the "re-rendering" (or whatever it is) doesn't work.
Any ideas of what I'm doing wrong here? Thanks!

A: While you could certainly beat your approach into working, I would advise that you take more common react approach.
You make your components to correctly display themselves from the state . ie as many steps are in the state, your component will display. Than make your add button add necessary information (information, not formated html) to the state.
Here is an example how to use component N times:
const MyRepeatedlyOccuringComponent = (n) => (
There goes Camel {n}
)

const App = () => {
 const camels = [1,22,333,4444,55555]
 const caravan = camels.map((n) => MyRepeatedlyOccuringComponent(n))
 return(
{caravan}

}


text:
Q: DirectX11::HLSL::Как передать данные сразу в пиксельный шейдер? В одном проекте на юнити, заметил, что там данные в шейдер передаются примерно таким образом:
    private void SetShaderParameters()
    {
        RayTracingShader.SetTexture(0, "_SkyboxTexture", SkyboxTexture);
        RayTracingShader.SetMatrix("_CameraToWorld", _camera.cameraToWorldMatrix);
        RayTracingShader.SetMatrix("_CameraInverseProjection", _camera.projectionMatrix.inverse);
        RayTracingShader.SetVector("_PixelOffset", new Vector2(Random.value, Random.value));
        RayTracingShader.SetFloat("_Seed", Random.value);

        Vector3 l = DirectionalLight.transform.forward;
        RayTracingShader.SetVector("_DirectionalLight", new Vector4(l.x, l.y, l.z, DirectionalLight.intensity));

        SetComputeBuffer("_Spheres", _sphereBuffer);
        SetComputeBuffer("_MeshObjects", _meshObjectBuffer);
        SetComputeBuffer("_Vertices", _vertexBuffer);
        SetComputeBuffer("_Indices", _indexBuffer);
    }

А в самом шейдере этими данными заполняются глобальные переменные:
#pragma kernel CSMain

RWTexture2D<float4> Result;

float4x4 _CameraToWorld;
float4x4 _CameraInverseProjection;

float4 _DirectionalLight;

float2 _PixelOffset;

Texture2D<float4> _SkyboxTexture;
SamplerState sampler_SkyboxTexture;

static const float PI = 3.14159265f;
static const float EPSILON = 1e-8;

float2 _Pixel;
float _Seed;

Возможно это работает потому что в том проекте использовался compute шейдер.
Но я думаю это применимо и к пиксельному шейдеры, а вопрос собственно в том, как это провернуть
в DirectX 11, без юнити.


text:
Q: What is the fourier transform of $e^{-\frac{t^2}2}$ What is the fourier transform of $e^{-\frac{t^2}2}$. I need a classical solution, I mean, straight-forward. done by hand, without using tricks and convolutions. Many thanks in advance
First steps, am I on the right way?

A: The solution involves completing the square in the exponent of the integrand, and then performing a $u$ substitution to get a well known integral that evaluates to 1:
$$\begin{align*}\mathscr{F}\left\{e^{-\frac{t^2}{2}}\right\}&= \int_{-\infty}^{\infty}e^{-\frac{t^2}{2}}e^{-2\pi i s t} dt\\
\\
&= \int_{-\infty}^{\infty}e^{-\frac{1}{2}(t^2+4\pi i st)} dt\\
\\
&= \int_{-\infty}^{\infty}e^{-\frac{1}{2}(t^2+4\pi i st-4\pi^2s^2)} e^{-2\pi^2s^2}dt\\
\\
&= \int_{-\infty}^{\infty}e^{-\frac{1}{2}(t+2\pi i s)^2} e^{-2\pi^2s^2}dt\\
\\
&=  e^{-2\pi^2s^2} \int_{-\infty}^{\infty}e^{-\frac{\pi}{2}\left(\frac{t}{\sqrt{\pi}}+2\sqrt{\pi} i s\right)^2}dt\\
\\
&=  e^{-2\pi^2s^2} \int_{-\infty}^{\infty}e^{-\pi\left(\frac{t}{\sqrt{2\pi}}+\sqrt{2\pi} i s\right)^2}dt\\
\\
&=  {\sqrt{2\pi}}{e^{-2\pi^2s^2}} \int_{-\infty}^{\infty}e^{-\pi u^2}du\\
\\\
&=  {\sqrt{2\pi}}{e^{-2\pi^2s^2}}\\
\\
&= {\sqrt{2\pi}} {e^{-\pi\left(\sqrt{2\pi}s\right)^2}}\\
\\
&= \mathscr{F}\left\{e^{-\pi\left(\frac{t}{\sqrt{2\pi}}\right)^2}\right\}
\end{align*}$$


text:
Q: Weird Apple Push Notification behaviour when the receiving iPhone is turned off I'm seeing some very strange behaviour from the Apple Push Notification Servers when the recipient iPhone is off.  Here is my scenario:

-Send push notification A to Apple.  Within a few seconds a push notification popup gets displayed as expected on the iPhone.
  -Send blank notification to Apple to cancel previous one (the previous notification is pointless after about 10 seconds, that's why I want to get rid of it).  Nothing displayed on the iPhone.
  -Turn OFF iPhone completely (not asleep, it is powered down).
  -Send push notification B to Apple.  Wait 10 seconds.
  -Send blank notification to Apple to cancel previous one.  Wait 10 seconds.
  -Send push notification C to Apple.  Wait 10 seconds.
  -Send blank notification to Apple to cancel previous one.  Wait 30 seconds.
  -Turn ON iPhone.
  -After about 60 seconds a push notification popup is displayed for notification B on the iPhone.
  -Notification C never seems to arrive.

This is very strange!  From reading the Apple docs I was expecting only the latest push notification to be sent.  I was hoping my blank notification would be sent, I certainly wasn't expecting the oldest unsent push notification to be sent!
The Apple docs say:

Apple Push Notification Service includes a default Quality of Service (QoS) component that performs a store-and-forward function. If APNS attempts to deliver a notification but the device is offline, the QoS stores the notification. It retains only one notification per application on a device: the last notification received from a provider for that application. When the offline device later reconnects, the QoS forwards the stored notification to the device. The QoS retains a notification for a limited period before deleting it.

Has anybody seen this behaviour?  Am I just hitting some sort of timing window bug?  What should happen?
Updates:
-If I turn the phone off and wait 5 to 15 minutes before sending any push notifications then this problem doesn't occur.  In this case when I turn the phone on I don't see any notification popup, although I'm not sure if this is a result of Apple dropping the notification, or their 'queue' working correctly (i.e. holding the newest blank notification instead of the first one with the popup).
-I will investigate further by putting an APNsLogging.mobileconfig onto the iPhone to see what notifications it got.
-Turning wifi off doesn't seem to change the results.
-I have raised a bug report with Apple for this scenario.

A: You may want to check for this behavior across both the cellular and WiFi networks. There's a lot of strange behavior when the phone is on WiFi, especially if there are multiple NAT router involved, i.e. in a large corporation where there's a main router and per-floor WiFi routers, or in a home where you have multiple routers used to extend the range. But on cell it's been pretty solid.
Also, the 10-second cancellation delay may be cutting it too close. They don't guarantee timely delivery and I've gotten lags of as much as 3 minutes on the production server after queuing off a push request. You may want to plan for system congestion.
Either way, it sounds like it might be worthy of a bugreporter report.

A: For the record, I raised this as bug ID #7349660 with Apple on 29th Oct (https://bugreport.apple.com), then gave them the additional diagnostics they wanted on 30th Oct.
No response from Apple since then, so I am assuming this is probably just low on their priority list, which is fair enough as it is quite a small timing window where the problem can occur (which I didn't realize when I first opened this question).

A: In apple's document it is said that it can cache the push notification up to 30 days.so u may get push once you switch on your iphone (provided you are having interconnection)

A: How soon was C sent after B?  It seems like it may be a bug where there's some kind of timeout server side, and they accidentally keep B if C was sent too soon after...
If you have a good test example (and this seems like a good test) I would file a Radar report on this.


text:
Q: Prove $\nabla \cdot f=0$ knowing $\int_{R^3}f \cdot \nabla \phi\ dxdydz=0$ for $\phi$ with compact support I want to prove that:
If $f$ is continuously differentiable vector field from $\mathbb{R}^3 \to \mathbb{R}^3$, and for any continuously differentiable function $\phi:\mathbb{R}^3 \to \mathbb{R}$ with compact support, we have:
$$
\int_{R^3}f \cdot \nabla \phi\ dxdydz=0
$$
Then $\nabla \cdot f=0$.
Firstly, I want to use the identity that $\nabla \cdot (f\phi) = f \cdot \nabla \phi + \phi \nabla \cdot f$ but I don't know how to proceed.
My second idea is make $\phi$ to be a small ball surrounding a point and using Gauss's theorem. To be specific, let $r$ be a radius and let $\lambda(x,y,z)=\frac{1}{2r}(x^2+y^2+z^2)$, then $\|\nabla\lambda\| = 1$ on the sphere $x^2+y^2+z^2 = r^2$.
Then let $\phi=\lambda$ when $x^2+y^2+z^2 = a^2$ and $a\in(r-\frac{1}{2}\Delta r, r+\frac{1}{2}\Delta r)$ where $\Delta r>0$ is a small number, and $\phi=0$ elsewhere. Here $\phi$ is not differentiable and this is where my concern is. To continue my idea, notice that $\nabla\phi$ is the norm vector over the ball. Then I guess $\frac{\int_{R^3}f \cdot \nabla \phi\ dV}{\Delta r} \approx \int_{R^3}f \cdot \nabla \phi\ dS$. We can use Gauss's theorem:
$$
\int_{R^3}f \cdot \nabla \phi\ dS = \int_{R^3}f \cdot dS = \int_{R^3}\nabla \cdot f\ dV=0
$$
Since $f$ is continuously differentiable, $\nabla \cdot f(0,0,0)$ should be $0$.
This is only my intuitive way and there are many flaws in it. Could anyone help me? Thank you!

A: Let  $\mathbf{x} \in \mathbb{R}^3$ be any point and $B_\delta(\mathbf{x})$ be the open ball of radius $\delta$ centered at $\mathbf{x}$.
Using the identity $\nabla \cdot (\phi \, f) = \phi \, \nabla \cdot f +  f \cdot\nabla\phi $ and applying the divergence theorem, we have
$$\int_{B_\delta(\mathbf{x})} \phi \, \nabla \cdot f \, dV = \int_{B_\delta(\mathbf{x})}  \nabla \cdot (\phi \, f) \, dV - \int_{B_\delta(\mathbf{x})}  f \cdot\nabla\phi \, dV = \int_{\partial {B_\delta(\mathbf{x})} } \phi \cdot \mathbf{n}  \, dS - \int_{B_\delta(\mathbf{x})}  f \cdot\nabla\phi \, dV.$$
If $\phi$ has compact support inside $B_\delta(\mathbf{x})$ then the first integral on the RHS vanishes since $\left.\phi \right|_{\partial B_\delta(\mathbf{x})}=0$ and the second integral vanishes by hypothesis
Thus, for any continuously differentiable function $\phi$ with compact support inside the open ball,
$$\int_{B_\delta(\mathbf{x})} \phi \, \nabla \cdot f \, dV = 0$$
Since $\nabla \cdot f$ is continuous, if $\nabla \cdot f(\mathbf{x}) > 0$ then there exists an open ball $B' \subset B_\delta(\mathbf{x})$ such that $\nabla \cdot f > 0$ throughout $B'$.
We can choose $\phi$ such that $\phi \, \nabla \cdot f (\mathbf{x}) \geqslant  0$ in $B_\delta(\mathbf{x})$ and it follows that
$$0 < \int_{B'} \phi \, \nabla \cdot f \, dV  \leqslant \int_{B_\delta(\mathbf{x})} \phi \, \nabla \cdot f \, dV = 0.$$
a contradiction. A similar argument applies if $\nabla \cdot f (\mathbf{x}) < 0$.
Thus, $\nabla \cdot f = 0$ on $\mathbb{R}^3$.


text:
Q: How to use Search bar with Navigaitonbar I have successfully get UISearchController to work in a new project, but when I am trying to do the same thing in my own project, it behaves differently.
This is what I have done to get it to work.
Storyboard:

This is my code for my view controller:
class ViewController: UIViewController, UISearchControllerDelegate, UISearchResultsUpdating, UISearchBarDelegate {

    var searchController : UISearchController!

    override func viewDidLoad() {
        super.viewDidLoad()

        let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let modalVC =  mainStoryboard.instantiateViewController(withIdentifier: "SearchTableViewController_SBID")
        self.searchController = UISearchController(searchResultsController:  modalVC)

        self.searchController.searchResultsUpdater = self
        self.searchController.delegate = self
        self.searchController.searchBar.delegate = self

        self.searchController.hidesNavigationBarDuringPresentation = false
        self.searchController.dimsBackgroundDuringPresentation = true

        self.navigationItem.titleView = searchController.searchBar

        self.definesPresentationContext = true
    }

    func updateSearchResults(for searchController: UISearchController) {

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

The result I am getting is, when I click on the search bar, the background will be dimmed, and when I started typing, the tableview controller will be visible, will the search bar is still visible in the navigation bar in the tableview controller.
However, when I try to implement the same thing in my project, when I started typing on the search bar, the table view controller will fill the whole screen, and the navigation bar is not visible.
This is the storyboard for my project:

Notice both projects are similar, except for one of them is Navigation Controller -> Tab Bar View Controller, which doesn't show the navigation bar when I type on the searchbar.
How do I get the navigation bar to show in a project Navigation Controller -> Tab Bar View Controller?
This is what it looks like for 2 projects:

A: Storyboard Setup

Coding of both view controller
class ViewController1: UIViewController,UISearchBarDelegate {
    @IBOutlet weak var lbl1: UILabel!
    var searchBar:UISearchBar? = nil
    override func viewDidLoad() {
        super.viewDidLoad()

        //Code to identify the searchbar
        for view in (self.tabBarController?.navigationItem.titleView?.subviews)!
        {
            if view.isKind(of: UISearchBar.self)
            {
                searchBar = (view as! UISearchBar);
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        //Assign Delegate and blank the search bar text
        searchBar?.text = ""
        searchBar?.delegate = self

    }
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        lbl1.text = "Tab 1 : \(searchText)"

    }

}
class ViewController2: UIViewController,UISearchBarDelegate {
    @IBOutlet weak var lbl1: UILabel!
    var searchBar:UISearchBar? = nil
    override func viewDidLoad() {
        super.viewDidLoad()

        //Code to identify the searchbar
        for view in (self.tabBarController?.navigationItem.titleView?.subviews)!
        {
            if view.isKind(of: UISearchBar.self)
            {
                searchBar = (view as! UISearchBar);
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        searchBar?.text = ""
        searchBar?.delegate = self
    }
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        lbl1.text = "Tab 2 : \(searchText)"

    }

}

Result


text:
Q: How to use touchAndHold event for sprite kit xcode 5 I'm trying to make a game with sprite kit and i need the character to move. I want the user to hold down the button for the character to move straight on the x axis. Right now you have to tap it multiple times for him to move.

A: I would recommend setting a x direction velocity on the touchBegan event and on the touchUp event set the velocity to 0.

*

*Touch down on a Node (left or right)

*Check if direction node was touched

*Set speed based on which node was touched (+ value moves right, - value moves left)

*When Touch is released, reset velocity of character to 0

Here is some code I stripped from my game for you:
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

UITouch * touch = [touches anyObject];

CGPoint location = [touch locationInNode:self];

if([self.moveRightNode containsPoint: location]) {
     NSInteger xSpeed = yourSpeed;
     character.physicsBody.velocity = CGVectorMake(yourspeed, 0);
}
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

UITouch * touch = [touches anyObject];
CGPoint location = [touch locationInNode:self];
character.physicsBody.velocity = CGVectorMake(0, 0);

}
When setting the physicsworld up, make gravity 0 or make the character.physicsworld.dynamic=NO.


text:
Q: Change of Variable vs Parametrization I'm considering the problem of computing the volume and surface area of an ellipsoid. We define the ellipsoid by the set of points
$$S=\left\{(\alpha r\cos\theta\sin\phi,\beta r\cos\theta\cos\phi,\gamma r\sin\theta)\,:\,\,0\leq\phi\leq2\pi,0\leq\theta\leq\pi,0\leq r\leq\rho\right\}$$
where, naturally, $\alpha$, $\beta$, $\gamma$, and $\rho$ are positive constants.
If we'd like to compute the volume of the ellipsoid, can first make a change of variable from Cartesian coordinates $(x,y,z)$ to scaled Cartesian coordinates $(u,v,w)$ by a mapping $\Phi_1$:
$$(x,y,z)=\Phi_1(u,v,w)=(\alpha u,\beta v,\gamma w)$$
such that our volume integral is
$$\text{vol}(S)=\int_S\,dx\,dy\,dz=\alpha\beta\gamma\int_S\,du\,dv\,dw$$
We then make a second change of variable from our (scaled) Cartesian coordinates to spherical coordinates, giving
$$\begin{aligned}\text{vol}(S)&= \alpha\beta\gamma\int_{r=0}^{\rho}\int_{\theta=0}^{\pi}\int_{\phi=0}^{2\pi}r^2\sin\theta\,d\phi\,d\theta\,dr\\
&=\frac{4}{3}\pi\,\alpha\beta\gamma\rho^3\end{aligned}$$
which is certainly the correct formula.
I had the (rather reckless) idea of trying a similar thing with the integral for the surface area of the ellipsoid. We define $\Phi_1$ by
$$\Phi_1(u,v,w)=(\alpha u,\beta v,\gamma w)$$
and $\Phi_2$ by
$$\Phi_2(\phi,\theta)= (\cos\theta\sin\phi,\cos\theta\cos\phi,\sin\theta)$$
It's obvious that composing $\Phi_1$ with $\Phi_2$ gives the desired parametrization of the ellipsoid. However, if we try playing the same game is with the volume integral by making two successive changes of variable, we end up with
$$\begin{aligned}\text{area}(S)&=\alpha\beta\gamma\rho^3\int_{\theta=0}^{\pi}\int_{\phi=0}^{2\pi}|\cos\theta|\,d\phi\,d\theta\\
&=4\pi\,\alpha\beta\gamma\rho^2\end{aligned}$$
which is certainly not the correct formula.
My question is regarding what, precisely, went wrong with the surface area computation. My best guess is that the mapping $\Phi_2$ is just a parametrization of the surface, and therefore doesn't have any reason to play nicely with changes of variable. However, I'm a little unclear on the specifics of what's happening. Can anyone offer any insight on the distinction between the bona fide change of variables in the volume integral and the mapping from 2-space to 3-space in the volume integral?


text:
Q: How to download a dynamic file in django? I have created a django application that converts txt to csv files. Now, I want to create a view function to download the newly converted csv files. Any suggestions will be highly appreciated.
How to read the path object in download view?
views.py
def submit(request):
   # this function uploads txt files.
   # this function converts txt to csv files. For example abcd.txt is converted into abcd0000.csv and abcd0000.csv is stored in /main/temp/ folder.
   path = 'main/temp/converted_file.csv' #(Example)This file is dynamic
   # context is also present
   context = {'path':path}
   return render(request,'submit.html',context)

Now I want to create a download function. For example:
def download(request):
   context = {'path': request.GET.get('path')}
   data = open(path,'r').read()
   resp = HttpResponse(data, mimetype='application/x-download')
   resp['Content-Disposition'] = 'attachment;filename=path.csv'
   return resp

submit.html

<title>
</title>

You have successfully converted the file.

Download (Filename)

A: You can write a streamed response like you can see in the django docs
In your case it might do something like this with your file;
import csv

from django.http import StreamingHttpResponse

class Echo:
    """An object that implements just the write method of the file-like
    interface.
    """
    def write(self, value):
        """Write the value by returning it, instead of storing in a buffer."""
        return value

def some_streaming_csv_view(request):
    """ A view that streams a large CSV file. """
    data = open(path,'r').readlines()

    pseudo_buffer = Echo()
    writer = csv.writer(pseudo_buffer)
    response = StreamingHttpResponse(
        (writer.writerow(row) for row in data),
        content_type="text/csv"
    )
    response['Content-Disposition'] = 'attachment; filename="somefilename.csv"'
    return response

Add the GET param to your URL, because you're already adding it to the context and trying to read it back out;

Download (Filename)


text:
Q: HTTPBuilder Retry strategy I have the following method in my Rest requests handler
def get_Game(String gameId){
    def gameInfo
    http.request(Method.GET, ContentType.XML){
        uri.path = gamePath
        uri.query = [id : gameId]
        response.'200' = { resp, reader ->
            gameInfo =  reader.item
        }
        response.'202' = {
            println 'retry'
        }
    }
    return gameInfo
}

The response status for this request is 200 if data is retrieved or 202 when the request is queued and I need to keep retrying until the status is 200.
Is there anyway to retry a request while response code is 202?


text:
Q: newline in multirow environment I have a table with many multirow environment that are each compouned with many lines.
I have seen that it is possible to break lines in multirows by fixing a particular width (with minipage for example) but I would like to decide where to break a line precisely (with a \newline for instance).
Example of current latex document :
\documentclass{article}
\usepackage[frenchb]{babel}
\usepackage[T1]{fontenc}
\usepackage{multirow}

\begin{document}
\begin{table}
\begin{tabular}{|c|c|}\hline
\multirow{5}{*}{Numbers from 1 to 5}&1 \\
&2 \\
&3 \\
&4 \\
&5 \\ \hline
\end{tabular}
\end{table}
\end{document}

The result is

What i would like to get is something like that  :

A: There is several ways to do it. A very simple way is using \shortstack
\documentclass{article}
\usepackage[frenchb]{babel}
\usepackage[T1]{fontenc}
\usepackage{multirow}

\begin{document}
\begin{table}
  \begin{tabular}{|c|c|}\hline
    \multirow{5}{*}{\shortstack[l]{Numbers from\\ 1 to 5}}&1 \\
                                                          &2 \\
                                                          &3 \\
                                                          &4 \\
                                                          &5 \\ \hline
  \end{tabular}
\end{table}

\begin{table}
  \begin{tabular}{|c|c|}\hline
    \multirow{5}{*}{\shortstack{Numbers from\\ 1 to 5}}&1 \\
                                                       &2 \\
                                                       &3 \\
                                                       &4 \\
                                                       &5 \\ \hline
  \end{tabular}
\end{table}

\begin{table}
  \begin{tabular}{|c|c|}\hline
    \multirow{5}{*}{\parbox{3cm}{Numbers from\\ 1 to 5}}&1 \\
                                                        &2 \\
                                                        &3 \\
                                                        &4 \\
                                                        &5 \\ \hline
  \end{tabular}
\end{table}

\end{document}

A: Simple with makecell, which is done for this sort of things: use the \multirowcell command (syntax even simpler than \multirow):
\documentclass{article}
\usepackage[frenchb]{babel}
\usepackage[T1]{fontenc}
\usepackage{multirow, makecell}

\begin{document}

\begin{table}
\begin{tabular}{|c|c|}\hline
\multirowcell{5}{Numbers\\from\\ 1 to 5}&1 \\
&2 \\
&3 \\
&4 \\
&5 \\ \hline
\end{tabular}
\end{table}
\end{document}

A: A simple option is to use the option to put a size to the column. Replace the c by p{5cm} with the size between the brackets.


text:
Q: ImGui multisampling I render my scene to FBO with multisampling. The resulting texture I use as ImGui::Image content. But how can I disable multisampling for gui?
I tried:
glDisable(GL_MULTISAMPLE);
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplSDL2_NewFrame(Game::getWindow());
ImGui::NewFrame();
//...
// Some gui elements
//...
ImGui::Render();
ImGui::UpdatePlatformWindows();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
glEnable(GL_MULTISAMPLE);

But this doesn't work. MSAA actually enabled when the gui drawing(text is blurred).

A: When it comes to window contexts, you can't disable MSAA after the window has been created. You need to recreate your window for it to take effect.
I'm not sure if the same thing is needed for FBOs, however, to my knowledge calling glDisable(GL_MULTISAMPLE) at runtime only cleans up some AA state, and you can't rely on it, since it's intended that you recreate your window to make changes to MSAA, so I'd guess it probably doesn't affect your FBO the way you expect it to either.
There's also an open issue on the ImGui repo about dealing with AA and fonts, though it seems to be "on hold" for now.


text:
Q: How To Insert a Row (not value by value) From Other Database with SQLite Python I know is possible to insert rows (not by every single values) with this definition:
insert into table1 select * from table2

But what if I need to transfer rows from one database_1 table to another database_2 table? (considering that the number of columns will always match)
I would like something like this:
c_database_2.execute('''SELECT * FROM table
                        WHERE date = ?
                        AND timestamp = ?''', (a, b)
row = c_new.fetchone()

c_database_1.execute("INSERT INTO table SELECT * FROM ?", (row))


text:
Q: applying a function recursively to each element (def v [:1 :1 :1  :2 :2 :2 :3 :3])
(defn groupFirstElem [[vec & more :as myList]]
  (split-with (partial = vec) myList)
)
;the (groupFirstElem v) yields [(:1 :1 :1) (:2 :2 :2 :3 :3)]

the idea is to use groupFirstElem function to obtain this
[(:1 :1 :1) (:2 :2 :2) (:3 :3)]

how do i go about recursevely calling groupFirstElem so that it applies to each "group" of v without having to evaluate the first element twice.

A: First of all, your specific problem can be solved using:
(partition-by identity [:1 :1 :1 :2 :2 :2 :3 :3])
;; => ((:1 :1 :1) (:2 :2 :2) (:3 :3))

Back to your question; the following would repeatedly replace the last element of a sq with the (spliced) result of a function:
(defn iterate-last
  [f sq]
  (loop [sq sq]
    (if (empty? (last sq))
      (butlast sq)
      (recur (concat (butlast sq) (f (last sq)))))))

A small caveat, you have to call it like this:
(iterate-last groupFirstElem [v])
;; => ((:1 :1 :1) (:2 :2 :2) (:3 :3))