text:
Q: My app won't show the ActionBar I'm trying to show an ActionBar onto one of my Activities, but I can't seem to work out why it won't show.
Can someone help, please?
Activity:
public class Login extends Activity {
    public static final String TAG = "MainActivity";
    public static final String DEFAULT_CHAT_NAME = "";
    private WifiP2pManager mManager;
    private Channel mChannel;
    private WifiDirectBroadcastReceiver mReceiver;
    private IntentFilter mIntentFilter;
    private com.ajapps.app.floatingactionbutton.AddFloatingActionButton goToChat;
    private ImageView goToSettings;
    private TextView goToSettingsText;
    private TextView setChatNameLabel;
    private EditText setChatName;
    private ImageView disconnect;
    public static String chatName;
    public static ServerInit server;

    //Getters and Setters
    public WifiP2pManager getmManager() { return mManager; }
    public Channel getmChannel() { return mChannel; }
    public WifiDirectBroadcastReceiver getmReceiver() { return mReceiver; }
    public IntentFilter getmIntentFilter() { return mIntentFilter; }
    public com.ajapps.app.floatingactionbutton.AddFloatingActionButton getGoToChat(){ return goToChat; }
    public TextView getSetChatNameLabel() { return setChatNameLabel; }
    public ImageView getGoToSettings() { return goToSettings; }
    public EditText getSetChatName() { return setChatName; }
    public TextView getGoToSettingsText() { return goToSettingsText; }
    public ImageView getDisconnect() { return disconnect; }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        //Init the Channel, Intent filter and Broadcast receiver
        init();

        //Button Go to Settings
        goToSettings = (ImageView) findViewById(R.id.goToSettings);
        goToSettings();

        //Go to Settings text
        goToSettingsText = (TextView) findViewById(R.id.textGoToSettings);

        //Button Go to Chat
        goToChat = (com.ajapps.app.floatingactionbutton.AddFloatingActionButton) findViewById(R.id.goToChat);
        goToChat();

        //Set the chat name
        setChatName = (EditText) findViewById(R.id.setChatName);
        setChatNameLabel = (TextView) findViewById(R.id.setChatNameLabel);
        setChatName.setText(loadChatName(this));

        //Button Disconnect
        disconnect = (ImageView) findViewById(R.id.disconnect);
        disconnect();
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
        registerReceiver(mReceiver, mIntentFilter);

        mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {

            @Override
            public void onSuccess() {
                Log.v(TAG, "Discovery process succeeded");
            }

            @Override
            public void onFailure(int reason) {
                Log.v(TAG, "Discovery process failed");
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
//        int idItem = item.getItemId();
        return super.onOptionsItemSelected(item);
    }

    public void init(){
        mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
        mChannel = mManager.initialize(this, getMainLooper(), null);
        mReceiver = WifiDirectBroadcastReceiver.createInstance();
        mReceiver.setmManager(mManager);
        mReceiver.setmChannel(mChannel);
        mReceiver.setmActivity(this);

        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
        mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
    }

    public void goToChat(){
        goToChat.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if(!setChatName.getText().toString().equals("")){
                    //Set the chat name
                    saveChatName(Login.this, setChatName.getText().toString());
                    chatName = loadChatName(Login.this);

                    //Start the init process
                    if(mReceiver.isGroupeOwner() ==  WifiDirectBroadcastReceiver.IS_OWNER){
                        Toast.makeText(Login.this, "I'm the group owner  " + mReceiver.getOwnerAddr().getHostAddress(), Toast.LENGTH_SHORT).show();
                        server = new ServerInit();
                        server.start();
                    }
                    else if(mReceiver.isGroupeOwner() ==  WifiDirectBroadcastReceiver.IS_CLIENT){
                        Toast.makeText(Login.this, "I'm the client", Toast.LENGTH_SHORT).show();
                        ClientInit client = new ClientInit(mReceiver.getOwnerAddr());
                        client.start();
                    }

                    //Open the ChatActivity
                    Intent intent = new Intent(getApplicationContext(), ChatActivity.class);
                    startActivity(intent);
                }
                else{
                    Toast.makeText(Login.this, "Please enter a chat name", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void disconnect(){
        disconnect.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mManager.removeGroup(mChannel, null);
                finish();
            }
        });
    }

    public void goToSettings(){
        goToSettings.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                //Open Wifi settings
                startActivityForResult(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS), 0);
            }
        });
    }

    //Save the chat name to SharedPreferences
    public void saveChatName(Context context, String chatName) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        Editor edit = prefs.edit();
        edit.putString("chatName", chatName);
        edit.commit();
    }

    //Retrieve the chat name from SharedPreferences
    public String loadChatName(Context context) {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        return prefs.getString("chatName", DEFAULT_CHAT_NAME);
    }
}

And my xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:fab="http://schemas.android.com/apk/res-auto"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ajapps.wifichat.MainActivity">

    <!-- Go to Settings screen -->

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:id="@+id/linearLayout"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true">

        <ImageView
            android:id="@+id/goToSettings"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/go_to_settings_button"
            android:src="@drawable/wifi_icon"
            android:layout_gravity="center" />

        <TextView
            android:id="@+id/textGoToSettings"
            android:layout_width="200dp"
            android:layout_height="wrap_content"
            android:text="@string/go_to_settings_text"
            android:textSize="16sp"
            android:textColor="@color/red"
            android:gravity="center"
            android:layout_gravity="center_vertical"/>

    </LinearLayout>

    <!-- Go to Chat screen -->

    <ImageView
        android:id="@+id/disconnect"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/setChatNameLabel"
        android:contentDescription="@string/disconnect"
        android:src="@drawable/disconnect"
        android:layout_marginBottom="15dp"
        android:visibility="gone"
        android:layout_centerHorizontal="true"/>

    <TextView
        android:id="@id/setChatNameLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/setChatName"
        android:text="@string/set_chat_name"
        android:layout_centerHorizontal="true"
        android:textSize="18sp"
        android:textColor="@color/app_text"
        android:visibility="gone" />

    <com.ajapps.app.floatingactionbutton.AddFloatingActionButton
        android:id="@+id/goToChat"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        fab:fab_icon="@drawable/send"
        android:background="@drawable/button_pressed2"
        fab:fab_plusIconColor="@color/half_black"
        fab:fab_colorNormal="@color/red"
        fab:fab_colorPressed="@color/red_pressed"
        android:layout_centerVertical="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:visibility="gone" />

    <EditText
        android:id="@+id/setChatName"
        android:inputType="textCapWords"
        android:lines="1"
        android:maxLength="20"
        android:layout_width="160dp"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/edit_text"
        android:layout_marginTop="15dp"
        android:visibility="gone" />

</RelativeLayout>

I've looked into my style.xml and can't see anything that would affect it.
This is my theme:
<resources>

    <style name="AppTheme"
        parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/ColorPrimary</item>
        <item name="colorPrimaryDark">@color/ColorPrimaryDark</item>
        <item name="android:icon">@android:color/transparent</item>
        <item name="windowActionBar">true</item>
        <item name="android:textColorPrimary">#000000</item>
    </style>

    <style name="Match">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">match_parent</item>
    </style>

    <style name="Wrap">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
    </style>

    <style name="MatchWidth" parent="Match">
        <item name="android:layout_height">wrap_content</item>
    </style>

    <style name="ScrollView" parent="Match">
        <item name="android:fillViewport">true</item>
    </style>

    <style name="LinearLayout" parent="Match">
        <item name="android:orientation">vertical</item>
    </style>

    <style name="RobotoTextView" parent="Wrap">
        <item name="android:textColor">@color/green_light</item>
        <item name="android:layout_gravity">center</item>
    </style>

    <style name="RobotoTextView.Number">
        <item name="android:textSize">@dimen/text_size_fragment_number</item>
    </style>

    <style name="RobotoTextView.Fragment">
        <item name="android:textSize">@dimen/text_size_xlarge</item>
    </style>

    <style name="menu_labels_style">
        <item name="android:background">@drawable/fab_label_background</item>
        <item name="android:textColor">@color/white</item>
        <item name="android:colorPrimaryDark">@color/orange</item>
    </style>

</resources>

A: just change
   public class Login extends Activity {

   }
   public class Login extends AppCompatActivity {
   }

A: Here's why: public class Login extends Activity {
You have to extend from AppCompatActivity.
Not ActionBarActivity, since it is deprecated.


text:
Q: Как сделать добавление, удаление, редактирование? ребята, подскажите пожалуйста как исправить код чтобы работало добавление, удаление, редактирование , у меня когда на кнопку нажимаю все исчезает. Мой код вложение, также sandbox https://codesandbox.io/s/intelligent-mopsa-ttk8sm?file=/src/App.js
App.js
import React, { useState } from "react";

function App() {
  const [arr, setArr] = useState([]);
  const [value, setValue] = useState("");

  const result = arr.map((element, index) => {
    return (

 remove(index)}>
        {element} +"X"

    );
  });

  function remove(index) {
    setArr([...arr.slice(0, index), ...arr.slice(index + 1)]);
  }

  function add() {
    // добавление элемента
    setArr([...arr, value]);
  }

  function changeValue(event) {
    // изменение содержания поля input
    setValue(event.target.value);
  }

  return (

      {result}
      <form>
        <input type="text" placeholder="" />
        <input onClick={changeValue} />
        <button onClick={add}>Добавить</button>
      </form>

  );
}

export default App;

index.js
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";

import App from "./App";

const rootElement = document.getElementById("root");
const root = createRoot(rootElement);

root.render(
  <StrictMode>
    <App />
  </StrictMode>
);

A: Исправь
<button onClick={add}>Добавить</button>

на
<button type="button" onClick={add}>Добавить</button>

иначе кнопка воспринимается как type="submit" и нажатие вызывает отправку формы и перезагрузку страницы
Или убери теги <form> вообще. Чтобы не вызывать случайно submit, нажатием ентера в input

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting a Index & Match & Offset function to work with userform I have a working VBA code here:
Evaluate("INDEX(A$6:A$72,MATCH(J5,B$6:B$72,0))") = Change_Pool.Value

What it does, is takes a index and matches it with a userform linked cell (J5).

What I want it to do is:
1. Make the VBA code use the combobox on the userform (Edit_pool.Change_Pool) instead of the linked cell. ie:
Evaluate("INDEX(A$6:A$72,MATCH(  *Edit_pool.Change_Pool.value*  ,B$6:B$72,0))")

*Then I want it to offset the result down a cell.
So It would look like
Offset ("INDEX(A$6:A$72,MATCH(  Edit_pool.Change_Pool.value  ,B$6:B$72,0))") 1
or something ^^

A: You can do this:
Evaluate("INDEX(A$6:A$72,MATCH(" & Edit_pool.Change_Pool.value & ",B$6:B$72,0))")

Note if your value is not numeric you'll need to add quotes around it:
Evaluate("INDEX(A$6:A$72,MATCH(""" & Edit_pool.Change_Pool.value & """,B$6:B$72,0))")

A: To match text values, try...
Evaluate("OFFSET(INDEX(A$6:A$72,MATCH(""" & Edit_pool.Change_Pool.value & """,B$6:B$72,0)),1,0)") = Change_Pool.Value

To match numerical values, try...
Evaluate("OFFSET(INDEX(A$6:A$72,MATCH(" & Edit_pool.Change_Pool.value & ",B$6:B$72,0)),1,0)") = Change_Pool.Value


text:
Q: Algorithm to generate all possible permutations of a list? Say I have a list of n elements, I know there are n! possible ways to order these elements. What is an algorithm to generate all possible orderings of this list? Example, I have list [a, b, c]. The algorithm would return [[a, b, c], [a, c, b,], [b, a, c], [b, c, a], [c, a, b], [c, b, a]].
I'm reading this here
http://en.wikipedia.org/wiki/Permutation#Algorithms_to_generate_permutations
But Wikipedia has never been good at explaining. I don't understand much of it.

A: As WhirlWind said, you start at the beginning.
You swap cursor with each remaining value, including cursor itself, these are all new instances (I used an int[] and array.clone() in the example).
Then perform permutations on all these different lists, making sure the cursor is one to the right.
When there are no more remaining values (cursor is at the end), print the list. This is the stop condition.
public void permutate(int[] list, int pointer) {
    if (pointer == list.length) {
        //stop-condition: print or process number
        return;
    }
    for (int i = pointer; i < list.length; i++) {
        int[] permutation = (int[])list.clone();.
        permutation[pointer] = list[i];
        permutation[i] = list[pointer];
        permutate(permutation, pointer + 1);
    }
}

A: Recursive always takes some mental effort to maintain. And for big numbers, factorial is easily huge and stack overflow will easily be a problem.
For small numbers (3 or 4, which is mostly encountered), multiple loops are quite simple and straight forward. It is unfortunate answers with loops didn't get voted up.
Let's start with enumeration (rather than permutation). Simply read the code as pseudo perl code.
$foreach $i1 in @list
    $foreach $i2 in @list
        $foreach $i3 in @list
            print "$i1, $i2, $i3\n"

Enumeration is more often encountered than permutation, but if permutation is needed, just add the conditions:
$foreach $i1 in @list
    $foreach $i2 in @list
        $if $i2==$i1
            next
        $foreach $i3 in @list
            $if $i3==$i1 or $i3==$i2
                next
            print "$i1, $i2, $i3\n"

Now if you really need general method potentially for big lists, we can use radix method. First, consider the enumeration problem:
$n=@list
my @radix
$for $i=0:$n
    $radix[$i]=0
$while 1
    my @temp
    $for $i=0:$n
        push @temp, $list[$radix[$i]]
    print join(", ", @temp), "\n"
    $call radix_increment

subcode: radix_increment
    $i=0
    $while 1
        $radix[$i]++
        $if $radix[$i]==$n
            $radix[$i]=0
            $i++
        $else
            last
    $if $i>=$n
        last

Radix increment is essentially number counting (in the base of number of list elements).
Now if you need permutaion, just add the checks inside the loop:
subcode: check_permutation
    my @check
    my $flag_dup=0
    $for $i=0:$n
        $check[$radix[$i]]++
        $if $check[$radix[$i]]>1
            $flag_dup=1
            last
    $if $flag_dup
        next

Edit: The above code should work, but for permutation, radix_increment could be wasteful. So if time is a practical concern, we have to change radix_increment into permute_inc:
subcode: permute_init
    $for $i=0:$n
        $radix[$i]=$i

subcode: permute_inc
    $max=-1
    $for $i=$n:0
        $if $max<$radix[$i]
            $max=$radix[$i]
        $else
            $for $j=$n:0
                $if $radix[$j]>$radix[$i]
                    $call swap, $radix[$i], $radix[$j]
                    break
            $j=$i+1
            $k=$n-1
            $while $j<$k
                $call swap, $radix[$j], $radix[$k]
                $j++
                $k--
            break
    $if $i<0
        break

Of course now this code is logically more complex, I'll leave for reader's exercise.

A: If anyone wonders how to be done in permutation in javascript.
Idea/pseudocode

*

*pick one element at a time

*permute rest of the element and then add the picked element to the all of the permutation

for example. 'a'+ permute(bc). permute of bc would be bc & cb. Now add these two will give abc, acb. similarly, pick b + permute (ac) will provice bac, bca...and keep going.
now look at the code
function permutations(arr){

   var len = arr.length,
       perms = [],
       rest,
       picked,
       restPerms,
       next;

    //for one or less item there is only one permutation
    if (len <= 1)
        return [arr];

    for (var i=0; i<len; i++)
    {
        //copy original array to avoid changing it while picking elements
        rest = Object.create(arr);

        //splice removed element change array original array(copied array)
        //[1,2,3,4].splice(2,1) will return [3] and remaining array = [1,2,4]
        picked = rest.splice(i, 1);

        //get the permutation of the rest of the elements
        restPerms = permutations(rest);

       // Now concat like a+permute(bc) for each
       for (var j=0; j<restPerms.length; j++)
       {
           next = picked.concat(restPerms[j]);
           perms.push(next);
       }
    }

   return perms;
}

Take your time to understand this. I got this code from (pertumation in JavaScript)

A: I have written this recursive solution in ANSI C. Each execution of the Permutate function provides one different permutation until all are completed. Global variables can also be used for variables fact and count.
#include <stdio.h>
#define SIZE 4

void Rotate(int vec[], int size)
{
    int i, j, first;

    first = vec[0];
    for(j = 0, i = 1; i < size; i++, j++)
    {
        vec[j] = vec[i];
    }
    vec[j] = first;
}

int Permutate(int *start, int size, int *count)
{
    static int fact;

    if(size > 1)
    {
        if(Permutate(start + 1, size - 1, count))
        {
            Rotate(start, size);
        }
        fact *= size;
    }
    else
    {
        (*count)++;
        fact = 1;
    }

    return !(*count % fact);
}

void Show(int vec[], int size)
{
    int i;

    printf("%d", vec[0]);
    for(i = 1; i < size; i++)
    {
        printf(" %d", vec[i]);
    }
    putchar('\n');
}

int main()
{
    int vec[] = { 1, 2, 3, 4, 5, 6 }; /* Only the first SIZE items will be permutated */
    int count = 0;

    do
    {
        Show(vec, SIZE);
    } while(!Permutate(vec, SIZE, &count));

    putchar('\n');
    Show(vec, SIZE);
    printf("\nCount: %d\n\n", count);

    return 0;
}

A: Another one in Python, it's not in place as @cdiggins's, but I think it's easier to understand
def permute(num):
    if len(num) == 2:
        # get the permutations of the last 2 numbers by swapping them
        yield num
        num[0], num[1] = num[1], num[0]
        yield num
    else:
        for i in range(0, len(num)):
            # fix the first number and get the permutations of the rest of numbers
            for perm in permute(num[0:i] + num[i+1:len(num)]):
                yield [num[i]] + perm

for p in permute([1, 2, 3, 4]):
    print p

A: I was thinking of writing a code for getting the permutations of any given integer of any size, i.e., providing a number 4567 we get all possible permutations till 7654...So i worked on it and found an algorithm and finally implemented it, Here is the code written in "c".
You can simply copy it and run on any open source compilers. But some flaws are waiting to be debugged. Please appreciate.
Code:
#include <stdio.h>
#include <conio.h>
#include <malloc.h>

                //PROTOTYPES

int fact(int);                  //For finding the factorial
void swap(int*,int*);           //Swapping 2 given numbers
void sort(int*,int);            //Sorting the list from the specified path
int imax(int*,int,int);         //Finding the value of imax
int jsmall(int*,int);           //Gives position of element greater than ith but smaller than rest (ahead of imax)
void perm();                    //All the important tasks are done in this function

int n;                         //Global variable for input OR number of digits

void main()
{
int c=0;

printf("Enter the number : ");
scanf("%d",&c);
perm(c);
getch();
}

void perm(int c){
int *p;                     //Pointer for allocating separate memory to every single entered digit like arrays
int i, d;
int sum=0;
int j, k;
long f;

n = 0;

while(c != 0)               //this one is for calculating the number of digits in the entered number
{
    sum = (sum * 10) + (c % 10);
    n++;                            //as i told at the start of loop
    c = c / 10;
}

f = fact(n);                        //It gives the factorial value of any number

p = (int*) malloc(n*sizeof(int));                //Dynamically allocation of array of n elements

for(i=0; sum != 0 ; i++)
{
    *(p+i) = sum % 10;                               //Giving values in dynamic array like 1234....n separately
    sum = sum / 10;
}

sort(p,-1);                                         //For sorting the dynamic array "p"

for(c=0 ; c<f/2 ; c++) {                        //Most important loop which prints 2 numbers per loop, so it goes upto 1/2 of fact(n)

    for(k=0 ; k<n ; k++)
        printf("%d",p[k]);                       //Loop for printing one of permutations
    printf("\n");

    i = d = 0;
    i = imax(p,i,d);                            //provides the max i as per algo (i am restricted to this only)
    j = i;
    j = jsmall(p,j);                            //provides smallest i val as per algo
    swap(&p[i],&p[j]);

    for(k=0 ; k<n ; k++)
        printf("%d",p[k]);
    printf("\n");

    i = d = 0;
    i = imax(p,i,d);
    j = i;
    j = jsmall(p,j);
    swap(&p[i],&p[j]);

    sort(p,i);
}
free(p);                                        //Deallocating memory
}

int fact (int a)
{
long f=1;
while(a!=0)
{
    f = f*a;
    a--;
}
return f;
}

void swap(int *p1,int *p2)
{
int temp;
temp = *p1;
*p1 = *p2;
*p2 = temp;
return;
}

void sort(int*p,int t)
{
int i,temp,j;
for(i=t+1 ; i<n-1 ; i++)
{
    for(j=i+1 ; j<n ; j++)
    {
        if(*(p+i) > *(p+j))
        {
            temp = *(p+i);
            *(p+i) = *(p+j);
            *(p+j) = temp;
        }
    }
}
}

int imax(int *p, int i , int d)
{
    while(i<n-1 && d<n-1)
{
    if(*(p+d) < *(p+d+1))
    {
        i = d;
        d++;
    }
    else
        d++;
}
return i;
}

int jsmall(int *p, int j)
{
int i,small = 32767,k = j;
for (i=j+1 ; i<n ; i++)
{
    if (p[i]<small && p[i]>p[k])
    {
       small = p[i];
       j = i;
    }
}
return j;
}

A: void permutate(char[] x, int i, int n){
    x=x.clone();
    if (i==n){
        System.out.print(x);
        System.out.print(" ");
        counter++;}
    else
    {
        for (int j=i; j<=n;j++){
     //   System.out.print(temp); System.out.print(" ");    //Debugger
        swap (x,i,j);
      //  System.out.print(temp); System.out.print(" "+"i="+i+" j="+j+"\n");// Debugger
        permutate(x,i+1,n);
    //    swap (temp,i,j);
    }
    }
}

void swap (char[] x, int a, int b){
char temp = x[a];
x[a]=x[b];
x[b]=temp;
}

I created this one. based on research too
permutate(qwe, 0, qwe.length-1);
Just so you know, you can do it with or without backtrack

A: Here's a toy Ruby method that works like #permutation.to_a that might be more legible to crazy people. It's hella slow, but also 5 lines.
def permute(ary)
  return [ary] if ary.size <= 1
  ary.collect_concat.with_index do |e, i|
    rest = ary.dup.tap {|a| a.delete_at(i) }
    permute(rest).collect {|a| a.unshift(e) }
  end
end

A: Here is the code in Python to print all possible permutations of a list:
def next_perm(arr):
    # Find non-increasing suffix
    i = len(arr) - 1
    while i > 0 and arr[i - 1] >= arr[i]:
        i -= 1
    if i <= 0:
        return False

    # Find successor to pivot
    j = len(arr) - 1
    while arr[j] <= arr[i - 1]:
        j -= 1
    arr[i - 1], arr[j] = arr[j], arr[i - 1]

    # Reverse suffix
    arr[i : ] = arr[len(arr) - 1 : i - 1 : -1]
    print arr
    return True

def all_perm(arr):
    a = next_perm(arr)
    while a:
        a = next_perm(arr)
    arr = raw_input()
    arr.split(' ')
    arr = map(int, arr)
    arr.sort()
    print arr
    all_perm(arr)

I have used a lexicographic order algorithm to get all possible permutations, but a recursive algorithm is more efficient. You can find the code for recursive algorithm here:
Python recursion permutations

A: Java version
/**
 * @param uniqueList
 * @param permutationSize
 * @param permutation
 * @param only            Only show the permutation of permutationSize,
 *                        else show all permutation of less than or equal to permutationSize.
 */
public static void my_permutationOf(List<Integer> uniqueList, int permutationSize, List<Integer> permutation, boolean only) {
    if (permutation == null) {
        assert 0 < permutationSize && permutationSize <= uniqueList.size();
        permutation = new ArrayList<>(permutationSize);
        if (!only) {
            System.out.println(Arrays.toString(permutation.toArray()));
        }
    }
    for (int i : uniqueList) {
        if (permutation.contains(i)) {
            continue;
        }
        permutation.add(i);
        if (!only) {
            System.out.println(Arrays.toString(permutation.toArray()));
        } else if (permutation.size() == permutationSize) {
            System.out.println(Arrays.toString(permutation.toArray()));
        }
        if (permutation.size() < permutationSize) {
            my_permutationOf(uniqueList, permutationSize, permutation, only);
        }
        permutation.remove(permutation.size() - 1);
    }
}

E.g.
public static void main(String[] args) throws Exception {
    my_permutationOf(new ArrayList<Integer>() {
        {
            add(1);
            add(2);
            add(3);

        }
    }, 3, null, true);
}

output:
  [1, 2, 3]
  [1, 3, 2]
  [2, 1, 3]
  [2, 3, 1]
  [3, 1, 2]
  [3, 2, 1]

A: in PHP
$set=array('A','B','C','D');

function permutate($set) {
    $b=array();
    foreach($set as $key=>$value) {
        if(count($set)==1) {
            $b[]=$set[$key];
        }
        else {
            $subset=$set;
            unset($subset[$key]);
            $x=permutate($subset);
            foreach($x as $key1=>$value1) {
                $b[]=$value.' '.$value1;
            }
        }
    }
    return $b;
}

$x=permutate($set);
var_export($x);

A: this is a java version for permutation
public class Permutation {

    static void permute(String str) {
        permute(str.toCharArray(), 0, str.length());
    }

    static void permute(char [] str, int low, int high) {
        if (low == high) {
            System.out.println(str);
            return;
        }

        for (int i=low; i<high; i++) {
            swap(str, i, low);
            permute(str, low+1, high);
            swap(str, low, i);
        }

    }

    static void swap(char [] array, int i, int j) {
        char t = array[i];
        array[i] = array[j];
        array[j] = t;
    }
}

A: public class PermutationGenerator
{
    private LinkedList<List<int>> _permutationsList;
    public void FindPermutations(List<int> list, int permutationLength)
    {
        _permutationsList = new LinkedList<List<int>>();
        foreach(var value in list)
        {
            CreatePermutations(value, permutationLength);
        }
    }

    private void CreatePermutations(int value, int permutationLength)
    {
        var node = _permutationsList.First;
        var last = _permutationsList.Last;
        while (node != null)
        {
            if (node.Value.Count < permutationLength)
            {
                GeneratePermutations(node.Value, value, permutationLength);
            }
            if (node == last)
            {
                break;
            }
            node = node.Next;
        }

        List<int> permutation = new List<int>();
        permutation.Add(value);
        _permutationsList.AddLast(permutation);
    }

    private void GeneratePermutations(List<int> permutation, int value, int permutationLength)
    {
       if (permutation.Count < permutationLength)
        {
            List<int> copyOfInitialPermutation = new List<int>(permutation);
            copyOfInitialPermutation.Add(value);
            _permutationsList.AddLast(copyOfInitialPermutation);
            List<int> copyOfPermutation = new List<int>();
            copyOfPermutation.AddRange(copyOfInitialPermutation);
            int lastIndex = copyOfInitialPermutation.Count - 1;
            for (int i = lastIndex;i > 0;i--)
            {
                int temp = copyOfPermutation[i - 1];
                copyOfPermutation[i - 1] = copyOfPermutation[i];
                copyOfPermutation[i] = temp;

                List<int> perm = new List<int>();
                perm.AddRange(copyOfPermutation);
                _permutationsList.AddLast(perm);
            }
        }
    }

    public void PrintPermutations(int permutationLength)
    {
        int count = _permutationsList.Where(perm => perm.Count() == permutationLength).Count();
        Console.WriteLine("The number of permutations is " + count);
    }
}

A: Here is an algorithm in Python that works by in place on an array:
def permute(xs, low=0):
    if low + 1 >= len(xs):
        yield xs
    else:
        for p in permute(xs, low + 1):
            yield p
        for i in range(low + 1, len(xs)):
            xs[low], xs[i] = xs[i], xs[low]
            for p in permute(xs, low + 1):
                yield p
            xs[low], xs[i] = xs[i], xs[low]

for p in permute([1, 2, 3, 4]):
    print p

You can try the code out for yourself here: http://repl.it/J9v

A: In Scala
    def permutazione(n: List[Int]): List[List[Int]] = permutationeAcc(n, Nil)

def permutationeAcc(n: List[Int], acc: List[Int]): List[List[Int]] = {

    var result: List[List[Int]] = Nil
    for (i ← n if (!(acc contains (i))))
        if (acc.size == n.size-1)
            result = (i :: acc) :: result
        else
            result = result ::: permutationeAcc(n, i :: acc)
    result
}

A: Here's an implementation for ColdFusion (requires CF10 because of the merge argument to ArrayAppend() ):
public array function permutateArray(arr){

    if (not isArray(arguments.arr) ) {
        return ['The ARR argument passed to the permutateArray function is not of type array.'];
    }

    var len = arrayLen(arguments.arr);
    var perms = [];
    var rest = [];
    var restPerms = [];
    var rpLen = 0;
    var next = [];

    //for one or less item there is only one permutation
    if (len <= 1) {
        return arguments.arr;
    }

    for (var i=1; i <= len; i++) {
        // copy the original array so as not to change it and then remove the picked (current) element
        rest = arraySlice(arguments.arr, 1);
        arrayDeleteAt(rest, i);

         // recursively get the permutation of the rest of the elements
         restPerms = permutateArray(rest);
         rpLen = arrayLen(restPerms);

        // Now concat each permutation to the current (picked) array, and append the concatenated array to the end result
        for (var j=1; j <= rpLen; j++) {
            // for each array returned, we need to make a fresh copy of the picked(current) element array so as to not change the original array
            next = arraySlice(arguments.arr, i, 1);
            arrayAppend(next, restPerms[j], true);
            arrayAppend(perms, next);
        }
     }

    return perms;
}

Based on KhanSharp's js solution above.

A: There is already plenty of good solutions here, but I would like to share how I solved this problem on my own and hope that this might be helpful for somebody who would also like to derive his own solution.
After some pondering about the problem I have come up with two following conclusions:

*

*For the list L of size n there will be equal number of solutions starting with L1, L2 ... Ln elements of the list. Since in total there are n! permutations of the list of size n, we get n! / n = (n-1)! permutations in each group.

*The list of 2 elements has only 2 permutations => [a,b] and [b,a].

Using these two simple ideas I have derived the following algorithm:
permute array
    if array is of size 2
       return first and second element as new array
       return second and first element as new array
    else
        for each element in array
            new subarray = array with excluded element
            return element + permute subarray

Here is how I implemented this in C#:
public IEnumerable<List<T>> Permutate<T>(List<T> input)
{
    if (input.Count == 2) // this are permutations of array of size 2
    {
        yield return new List<T>(input);
        yield return new List<T> {input[1], input[0]};
    }
    else
    {
        foreach(T elem in input) // going through array
        {
            var rlist = new List<T>(input); // creating subarray = array
            rlist.Remove(elem); // removing element
            foreach(List<T> retlist in Permutate(rlist))
            {
                retlist.Insert(0,elem); // inserting the element at pos 0
                yield return retlist;
            }

        }
    }
}

A: Wikipedia's answer for "lexicographic order" seems perfectly explicit in cookbook style to me. It cites a 14th century origin for the algorithm!
I've just written a quick implementation in Java of Wikipedia's algorithm as a check and it was no trouble. But what you have in your Q as an example is NOT "list all permutations", but "a LIST of all permutations", so wikipedia won't be a lot of help to you. You need a language in which lists of permutations are feasibly constructed. And believe me, lists a few billion long are not usually handled in imperative languages. You really want a non-strict functional programming language, in which lists are a first-class object, to get out stuff while not bringing the machine close to heat death of the Universe.
That's easy. In standard Haskell or any modern FP language:
-- perms of a list
perms :: [a] -> [ [a] ]
perms (a:as) = [bs ++ a:cs | perm <- perms as, (bs,cs) <- splits perm]
perms []     = [ [] ]

and
-- ways of splitting a list into two parts
splits :: [a] -> [ ([a],[a]) ]
splits []     = [ ([],[]) ]
splits (a:as) = ([],a:as) : [(a:bs,cs) | (bs,cs) <- splits as]

A: Basically, for each item from left to right, all the permutations of the remaining items are generated (and each one is added with the current elements). This can be done recursively (or iteratively if you like pain) until the last item is reached at which point there is only one possible order.
So with the list [1,2,3,4] all the permutations that start with 1 are generated, then all the permutations that start with 2, then 3 then 4.
This effectively reduces the problem from one of finding permutations of a list of four items to a list of three items. After reducing to 2 and then 1 item lists, all of them will be found.
Example showing process permutations using 3 coloured balls:
 (from https://en.wikipedia.org/wiki/Permutation#/media/File:Permutations_RGB.svg - https://commons.wikimedia.org/wiki/File:Permutations_RGB.svg)

A: In the following Java solution we take advantage over the fact that Strings are immutable in order to avoid cloning the result-set upon every iteration.
The input will be a String, say "abc", and the output will be all the possible permutations:
abc
acb
bac
bca
cba
cab

Code:
public static void permute(String s) {
    permute(s, 0);
}

private static void permute(String str, int left){
    if(left == str.length()-1) {
        System.out.println(str);
    } else {
        for(int i = left; i < str.length(); i++) {
            String s = swap(str, left, i);
            permute(s, left+1);
        }
    }
}

private static String swap(String s, int left, int right) {
    if (left == right)
        return s;

    String result = s.substring(0, left);
    result += s.substring(right, right+1);
    result += s.substring(left+1, right);
    result += s.substring(left, left+1);
    result += s.substring(right+1);
    return result;
}

Same approach can be applied to arrays (instead of a string):
public static void main(String[] args) {
    int[] abc = {1,2,3};
    permute(abc, 0);
}
public static void permute(int[] arr, int index) {
    if (index == arr.length) {
        System.out.println(Arrays.toString(arr));
    } else {
        for (int i = index; i < arr.length; i++) {
            int[] permutation = arr.clone();
            permutation[index] = arr[i];
            permutation[i] = arr[index];
            permute(permutation, index + 1);
        }
    }
}

A: I know this a very very old and even off-topic in today's stackoverflow but I still wanted to contribute a friendly javascript answer for the simple reason that it runs in your browser.
I've also added the debugger directive breakpoint so you can step through the code (chrome required) to see how this algorithm works. Open up your dev console in chrome (F12 in windows or CMD + OPTION + I on mac) and then click "Run code snippet". This implements the same exact algorithm that @WhirlWind presented in his answer.
Your browser should pause execution at the debugger directive. Use F8 to continue code execution.
Step through the code and see how it works!

function permute(rest, prefix = []) {
  if (rest.length === 0) {
    return [prefix];
  }
  return (rest
    .map((x, index) => {
      const oldRest = rest;
      const oldPrefix = prefix;
      // the `...` destructures the array into single values flattening it
      const newRest = [...rest.slice(0, index), ...rest.slice(index + 1)];
      const newPrefix = [...prefix, x];
      debugger;

      const result = permute(newRest, newPrefix);
      return result;
    })
    // this step flattens the array of arrays returned by calling permute
    .reduce((flattened, arr) => [...flattened, ...arr], [])
  );
}
console.log(permute([1, 2, 3]));

A: It's my solution on Java:
public class CombinatorialUtils {

    public static void main(String[] args) {
        List<String> alphabet = new ArrayList<>();
        alphabet.add("1");
        alphabet.add("2");
        alphabet.add("3");
        alphabet.add("4");

        for (List<String> strings : permutations(alphabet)) {
            System.out.println(strings);
        }
        System.out.println("-----------");
        for (List<String> strings : combinations(alphabet)) {
            System.out.println(strings);
        }
    }

    public static List<List<String>> combinations(List<String> alphabet) {
        List<List<String>> permutations = permutations(alphabet);
        List<List<String>> combinations = new ArrayList<>(permutations);

        for (int i = alphabet.size(); i > 0; i--) {
            final int n = i;
            combinations.addAll(permutations.stream().map(strings -> strings.subList(0, n)).distinct().collect(Collectors.toList()));
        }
        return combinations;
    }

    public static <T> List<List<T>> permutations(List<T> alphabet) {
        ArrayList<List<T>> permutations = new ArrayList<>();
        if (alphabet.size() == 1) {
            permutations.add(alphabet);
            return permutations;
        } else {
            List<List<T>> subPerm = permutations(alphabet.subList(1, alphabet.size()));
            T addedElem = alphabet.get(0);
            for (int i = 0; i < alphabet.size(); i++) {
                for (List<T> permutation : subPerm) {
                    int index = i;
                    permutations.add(new ArrayList<T>(permutation) {{
                        add(index, addedElem);
                    }});
                }
            }
        }
        return permutations;
    }
}

A: You can't really talk about solving a permultation problem in recursion without posting an implementation in a (dialect of) language that pioneered the idea. So, for the sake of completeness, here is one of the ways that can be done in Scheme.
(define (permof wd)
  (cond ((null? wd) '())
        ((null? (cdr wd)) (list wd))
        (else
         (let splice ([l '()] [m (car wd)] [r (cdr wd)])
           (append
            (map (lambda (x) (cons m x)) (permof (append l r)))
            (if (null? r)
                '()
                (splice (cons m l) (car r) (cdr r))))))))

calling (permof (list "foo" "bar" "baz")) we'll get:
'(("foo" "bar" "baz")
  ("foo" "baz" "bar")
  ("bar" "foo" "baz")
  ("bar" "baz" "foo")
  ("baz" "bar" "foo")
  ("baz" "foo" "bar"))

I won't go into the algorithm details because it's been explained enough in other posts. The idea is the same.
However, recursive problems tend to be much harder to model and think about in destructive medium like Python, C, and Java, while in Lisp or ML it can be concisely expressed.

A: I came up with these algorithms (one recursive and the other iterative) when I was in my first year of engineering and implemented them in python (I apologize for the random naming scheme):
def permute(x):
    m = [ord(i) for i in x]
    m.sort()
    count = 1
    print(count,''.join([chr(i) for i in m]))
    while (True):
        l = -1
        lgth = len(m)
        while (m[l] <= m[l-1]):
            l -= 1
            if l == -lgth:
                break
        if l == -lgth:
            break
        z = sorted(m[l-1:])
        k = m[l-1]
        z2 = z[:]
        z.reverse()
        b = z[z.index(k)-1]
        z2.remove(b)
        v = [b] + z2
        m[l-1:] = v
        count += 1
        print(count, ''.join([chr(i) for i in m]))

"""A Less-powerful solution: """

def permute_recursively(inp_list):
    if (len(inp_list) == 1):
        return [inp_list]
    else:
        x = permute_recursively(inp_list[1:])
        a = inp_list[0]
        z = []
        for i in x:
            for k in range(len(i) + 1):
                z.append(i[:k] + [a] + i[k:])
        return(z)

""" main section """

x = input("Enter the string: ")

#call to permute
permute(x)
print("****** End of permute ******\n")

#call to permute_recursively
count = 1
for i in permute_recursively(sorted(list(x))):
    print(count, ''.join(i))
    count += 1

Characteristics of the first algorithm:

*

*More efficient.

*Usable for inputs of literally any length (if you have enough time
and computing resources).

*Generates permutations in lexicographical order according to the
ASCII values. of the characters.

*Uses virtually no memory at all

*Skips generating any duplicates.

*Generates exactly https://i.stack.imgur.com/NZ2vt.jpg permutations,
where n is the number of characters in the input, i is the index of
any character that is repeated, and m is the number of repetitions of
the character with index i.

The second algorithm is recursive:

*

*It is less efficient.

*Cannot be used for inputs of lengths beyond a certain limit because
the recursion depth allowed is finite.

*Doesn't generate permutations in lexicographical order.

*Uses a lot of memory as it needs to store each permutation it generates

*Generates duplicates.

*Generates exactly n! outputs

A: Here is a recursive solution in PHP. WhirlWind's post accurately describes the logic. It's worth mentioning that generating all permutations runs in factorial time, so it might be a good idea to use an iterative approach instead.
public function permute($sofar, $input){
  for($i=0; $i < strlen($input); $i++){
    $diff = strDiff($input,$input[$i]);
    $next = $sofar.$input[$i]; //next contains a permutation, save it
    $this->permute($next, $diff);
  }
}

The strDiff function takes two strings, s1 and s2, and returns a new string with everything in s1 without elements in s2 (duplicates matter). So, strDiff('finish','i') => 'fnish' (the second 'i' is not removed).

A: Here is an algorithm in R, in case anyone needs to avoid loading additional libraries like I had to.
permutations <- function(n){
    if(n==1){
        return(matrix(1))
    } else {
        sp <- permutations(n-1)
        p <- nrow(sp)
        A <- matrix(nrow=n*p,ncol=n)
        for(i in 1:n){
            A[(i-1)*p+1:p,] <- cbind(i,sp+(sp>=i))
        }
        return(A)
    }
}

Example usage:
> matrix(letters[permutations(3)],ncol=3)
     [,1] [,2] [,3]
[1,] "a"  "b"  "c"
[2,] "a"  "c"  "b"
[3,] "b"  "a"  "c"
[4,] "b"  "c"  "a"
[5,] "c"  "a"  "b"
[6,] "c"  "b"  "a"

A: #!/usr/bin/env python
import time

def permutations(sequence):
  # print sequence
  unit = [1, 2, 1, 2, 1]

  if len(sequence) >= 4:
    for i in range(4, (len(sequence) + 1)):
      unit = ((unit + [i - 1]) * i)[:-1]
      # print unit
    for j in unit:
      temp = sequence[j]
      sequence[j] = sequence[0]
      sequence[0] = temp
      yield sequence
  else:
    print 'You can use PEN and PAPER'

# s = [1,2,3,4,5,6,7,8,9,10]
s = [x for x in 'PYTHON']

print s

z = permutations(s)
try:
  while True:
    # time.sleep(0.0001)
    print next(z)
except StopIteration:
    print 'Done'

['P', 'Y', 'T', 'H', 'O', 'N']
['Y', 'P', 'T', 'H', 'O', 'N']
['T', 'P', 'Y', 'H', 'O', 'N']
['P', 'T', 'Y', 'H', 'O', 'N']
['Y', 'T', 'P', 'H', 'O', 'N']
['T', 'Y', 'P', 'H', 'O', 'N']
['H', 'Y', 'P', 'T', 'O', 'N']
['Y', 'H', 'P', 'T', 'O', 'N']
['P', 'H', 'Y', 'T', 'O', 'N']
['H', 'P', 'Y', 'T', 'O', 'N']
['Y', 'P', 'H', 'T', 'O', 'N']
['P', 'Y', 'H', 'T', 'O', 'N']
['T', 'Y', 'H', 'P', 'O', 'N']
['Y', 'T', 'H', 'P', 'O', 'N']
['H', 'T', 'Y', 'P', 'O', 'N']
['T', 'H', 'Y', 'P', 'O', 'N']
['Y', 'H', 'T', 'P', 'O', 'N']
['H', 'Y', 'T', 'P', 'O', 'N']
['P', 'Y', 'T', 'H', 'O', 'N']
.
.
.
['Y', 'T', 'N', 'H', 'O', 'P']
['N', 'T', 'Y', 'H', 'O', 'P']
['T', 'N', 'Y', 'H', 'O', 'P']
['Y', 'N', 'T', 'H', 'O', 'P']
['N', 'Y', 'T', 'H', 'O', 'P']

A: Just to be complete, C++
#include <iostream>
#include <algorithm>
#include <string>

std::string theSeq = "abc";
do
{
  std::cout << theSeq << endl;
}
while (std::next_permutation(theSeq.begin(), theSeq.end()));

...
abc
acb
bac
bca
cab
cba

A: Here is a non-recursive solution in C++ that provides the next permutation in ascending order, similarly to the functionality provided by std::next_permutation:
void permute_next(vector<int>& v)
{
  if (v.size() < 2)
    return;

  if (v.size() == 2)
  {
    int tmp = v[0];
    v[0] = v[1];
    v[1] = tmp;
    return;
  }

  // Step 1: find first ascending-ordered pair from right to left
  int i = v.size()-2;
  while(i>=0)
  {
    if (v[i] < v[i+1])
      break;
    i--;
  }
  if (i<0) // vector fully sorted in descending order (last permutation)
  {
    //resort in ascending order and return
    sort(v.begin(), v.end());
    return;
  }

  // Step 2: swap v[i] with next higher element of remaining elements
  int pos = i+1;
  int val = v[pos];
  for(int k=i+2; k<v.size(); k++)
    if(v[k] < val && v[k] > v[i])
    {
      pos = k;
      val = v[k];
    }
  v[pos] = v[i];
  v[i] = val;

  // Step 3: sort remaining elements from i+1 ... end
  sort(v.begin()+i+1, v.end());
}

A: In C, create a single matrix (unsigned char) to quickly and easily access all permutations from 1 to 6. Based on code from https://www.geeksforgeeks.org/heaps-algorithm-for-generating-permutations/.
void swap(unsigned char* a, unsigned char* b)
{
    unsigned char t;

    t = *b;
    *b = *a;
    *a = t;
}

void print_permutations(unsigned char a[], unsigned char n)
{
    // can't rely on sizeof(a[6]) == 6, such as with MSVC 2019
    for (int i = 0; i < n; i++)
    {
        assert(a[i] < n);
        printf("%d ", a[i]);
    }
    printf("\n");
}

// Generating permutation using Heap Algorithm
void generate_permutations(unsigned char (**permutations)[6], unsigned char a[], int size, int n)
{
    // can't rely on sizeof(a[6]) == 6, such as with MSVC 2019
    // if size becomes 1 then prints the obtained permutation
    if (size == 1)
    {
        memcpy(*permutations, a, n);
        *permutations += 1;
    }
    else
    {
        for (int i = 0; i < size; i++)
        {
            generate_permutations(permutations, a, size - 1, n);

            // if size is odd, swap first and last element
            if (size & 1)
                swap(a, a + size - 1);

            // If size is even, swap ith and last element
            else
                swap(a + i, a + size - 1);
        }
    }
}

int main()
{
    unsigned char permutations[720][6]; // easily access all permutations from 1 to 6
    unsigned char suit_length_indexes[] = { 0, 1, 2, 3, 4, 5 };
    assert(sizeof(suit_length_indexes) == sizeof(permutations[0]));
    unsigned char(*p)[sizeof(suit_length_indexes)] = permutations;
    generate_permutations(&p, suit_length_indexes, sizeof(suit_length_indexes), sizeof(suit_length_indexes));
    for (int i = 0; i < sizeof(permutations) / sizeof(permutations[0]); i++)
        print_permutations(permutations[i], sizeof(suit_length_indexes));
    return 0;
}

A: Below are two classic kotlin implementations of recursive and non recursive Heap algorithm implementations:
Non recursive:
fun <T> permutationsHeapNonRecursive(list: List<T>): List<List<T>> {
    val result = mutableListOf<List<T>>()
    val c = Array(list.size) {0}
    result.add(list.toList())

    val tempList = list.toMutableList()
    var i = 1
    while (i < list.size) {
        if (c[i] < i) {
            if (i % 2 == 0)
                tempList[0] = tempList[i].also { tempList[i] = tempList[0] }
            else
                tempList[c[i]] = tempList[i].also { tempList[i] = tempList[c[i]] }
            result.add(tempList.toList())
            c[i] += 1
            i = 1
        }
        else {
            c[i] = 0
            i += 1
        }
    }
    return result
}

and, recursive:
private fun <T> permutationsHeapRecursiveInternal(k: Int, list: MutableList<T>, outList: MutableList<List<T>>) {
    if (k == 1) {
        outList.add(List<T>(list.size) {list[it]})
    }
    else {
        permutationsHeapRecursiveInternal(k - 1, list, outList)
        for (i in 0 until k-1) {
            if (k % 2 == 0)
                list[i] = list[k-1].also{ list[k-1] = list[i] }
            else
                list[0] = list[k-1].also{ list[k-1] = list[0] }
            permutationsHeapRecursiveInternal(k - 1, list, outList)
        }
    }
}

fun <T> permutationsHeapRecursive(list: List<T>): List<List<T>> {
    val result = mutableListOf<List<T>>()
    if (list.isNotEmpty()) {
        val tempList = MutableList<T>(list.size) { i -> list[i] }
        permutationsHeapRecursiveInternal(tempList.size, tempList, result)
    }
    return result
}

I have profiled non recursive version and after some tweaking with limiting memory allocations it is faster than recursive one.

A: As a C# Extension Method:

*

*Avoids inserting at position zero into List() (assumed backed by Array).

*Replaces the list.Count == 2 with a simpler list.Count == 0 check.

*Disadvantage, uses an extra arg during recursion.

Usage:
List<List<string>> permutations = new List<string> { "A", "BB", "CCC" }.Permutations();

Debug.WriteLine(String.Join("; ", permutations.Select(p => string.Join(", ", p))));

Output:

A, BB, CCC; A, CCC, BB; BB, A, CCC; BB, CCC, A; CCC, A, BB; CCC, BB, A

Method:
static public List<List<T>> Permutations<T>(this List<T> list, List<T> prefillOpt = null)
{
    List<List<T>> result = new List<List<T>>();

    if (list.Count == 0)
    {
        if (prefillOpt?.Any() == true)
            result.Add(prefillOpt.ToList()); // make a copy, owned by caller
    }
    else
    {
        prefillOpt = prefillOpt ?? new List<T>();

        for (int i = 0; i < list.Count; i++)
        {
            prefillOpt.Add(list[i]);

            int j = 0;
            result.AddRange(Permutations(list.Where(moot => j++ != i).ToList(), prefillOpt));

            prefillOpt.RemoveAt(prefillOpt.Count - 1);
        }
    }
    return result;
}

A: The following is the generic implementation of Heap's algorithm (works with int, char, etc):
void generate<T>(int k, List<T> A, List<List<T>> result)
{
    if (k == 1)
    {
        result.Add(new List<T>(A));
        return;
    }
    for (int i = 0; i < k; i++)
    {
        generate(k - 1, A, result);
        if (k % 2 == 0)
            (A[i], A[k - 1]) = (A[k - 1], A[i]);
        else
            (A[0], A[k - 1]) = (A[k - 1], A[0]);
    }
}

To use it:
var permutations = new List<List<char>>();
List<char> A = new List<char>() { 'a', 'b', 'c', 'd'};
generate<char>(A.Count, A, permutations);
// The output is in permutations
int c = 0;
foreach (var item in permutations)
{
    c++;
    Console.Write(c + ". ");
    foreach (var element in item)
    {
        Console.Write(element);
    }
    Console.WriteLine();

}

A: the simplest way I can think to explain this is by using some pseudo code
so
list of 1, 2 ,3
for each item in list
    templist.Add(item)
    for each item2 in list
        if item2 is Not item
            templist.add(item)
               for each item3 in list
                   if item2 is Not item
                      templist.add(item)

                   end if
               Next
            end if

    Next
    permanentListofPermutaitons,add(templist)
    tempList.Clear()
Next

Now obviously this is not the most flexible way to do this, and doing it recursively would be a lot more functional by my tired sunday night brain doesn't want to think about that at this moment. If no ones put up a recursive version by the morning I'll do one.

A: Bourne shell solution - in a total of four lines (without test for no param case):
test $# -eq 1 && echo "$1" && exit
for i in $*; do
  $0 `echo "$*" | sed -e "s/$i//"` | sed -e "s/^/$i /"
done

A: This produces them one-at-time without making a list - the same end result as Marios Choudary's answer (or simply calling C++'s nextPermute, as Anders answer notes). But this is Heap's algorithm (the non-recursive version) re-arranged and a class to save context. Used as:
P5=new genPermutes_t(5); // P5.P is now [0,1,2,3,4]
while(!P5.isDone()) {
  // use P5.P here
  P5.next();
}

Code is in C# without being an endorsement. Variables are as-is from Heap's pseudocode, to which the comments also refer:
public class genPermutes_t {
  public int[] P; // the current permuation

  private int n, i; // vars from the original algorithm
  private int[] c; // ditto

  public genPermutes_t(int count) {
    // init algorithm:
    n=count;
    i=0;
    c=new int[n];
    for(int j=0;j<n;j++) c[j]=0;

    // start current permutation as 0,1 ... n-1:
    P=new int[n];
    for(int j=0;j<n;j++) P[j]=j;
  }

  public bool isDone() {
    return i>=n; // condition on the original while loop
  }

  public void next() {
    // the part of the loop that spins until done or ready for next permute:
    while(i<n && c[i]>=i) {
      c[i]=0;
      i++;
    }
    // pulled from inside loop -- the part that makes next permute:
    if(i<n) { // if not done
      if(i%2==0) swap(0,i);
      else swap(c[i], i);
      // "print P" removed. User will simply examine it
      c[i]+=1;
      i=0;
    }
  }

  private void swap(int i1, int i2) {int tmp=P[i1]; P[i1]=P[i2]; P[i2]=tmp;}
}


text:
Q: OutOfMemoryError in test with jUnit When i Test my programe with jUnit, i have errors of

java.lang.OutOfMemoryError

. How can i manage the memory size for testing?

A: One possible reason for this is keeping lots of data in instance fields of the test classes.
You have to understand that JUnit will create a new object of the test class for each test method in the class (in order to avoid having the tests influence each other), and will keep references to all those objects.
Therefore instance fields in test classes should not refer to large amounts of data or, if that is really necessary, theyy have to be set to null in a teardown method.
Update: The problem described above was apparently only present in older versions of JUnit.

A: If you are using Eclipse IDE; click on run from the menu on top and select run configurations. A dialog box will appear. Select the test that you are running and click on the arguments tab. type: -Xmx1024m and click apply. Run it again and see if it throws the same exception. If it does, the method under test is probably causing the problem. That happens when you have recursive calls in a cycle. Hope that helps.


text:
Q: Shutdown mac with keyboard only? Can I shut down my mac with the keyboard only?
I dont want to force shut down (like holding the power key), I want to shut it down normally.

A: Well, while it's not "keyboard only" per se, you can open up a terminal and type in sudo shutdown -h now, which will send a signal to the kernel to shutdown the computer.
I'm not sure if that was exactly what you were looking for, but it should be a viable solution.
Apparently, another option is to use Command-Option-Control-Media Eject key, which will quit all applications and let you save documents/work and then shuts down the mac.

A: If you have a keyboard with an eject key, you can use ⌃⌥⌘⏏ (control-option-command-eject).
If you have a laptop with a power key in place of an eject key, the power key can be substituted for eject in 10.8 and newer versions of OS X.
Other keyboard shorcuts:

*

*⌃⌘⏏ restarts the computer

*⌥⌘⏏ puts the computer to sleep

*⌃⇧⏏ puts displays to sleep

*⌃⏏ opens the dialog shown when pressing a power button or power key

*⇧⌘Q logs out after showing a confirmation dialog

*⌥⇧⌘Q logs out without showing a confirmation dialog

My keyboard doesn't have an eject or power key, so I normally use Alfred:

You could also assign a keyboard shortcut to a script like this:
tell app "System Events" to shut down

The shut down command sends loginwindow a kAEShutDown Apple event, which starts a normal shut down sequence as described in the Daemons and Services Programming Guide. sudo shutdown -h now does not for example allow graphical applications to ask for confirmation if there are unsaved changes.

A: Open Keyboard Shortcuts in System Preferences. Click on Applications Shortcuts in the list at left.
Click on the "plus" sign and choose "All Applications" in the pulldown menu. Type in "Shut Down" (WITHOUT the ellipses you'd find after this command in the Apple Menu) and choose whatever keyboard shortcut you want.
(I typically put SHIFT-OPT-COMMAND in front of all of my shortcuts so it's harder to hit them by accident.)a
Restart your Mac and your new command should show up in the Apple Menu below the normal "Shut Down…" command, along with its new keyboard shortcut.
p.s. you can use this for Sleep and Restart, too.

A: *

*Press CtrlF2 to keyboard-focus the menu bar

*Press Return to open the  menu

*Press ↑ twice to navigate to the Shutdown… item

*Press OptionReturn to shutdown without additional confirmation dialog

This will work unless you changed the keyboard shortcut to access the menu bar in System Preferences » Keyboard » Keyboard Shortcuts » Keyboard & Text Input.


text:
Q: Computing preference values in Apache Mahout I am trying to learn Apache mahout, very new to this topic. I want to implement user-based recommender. For this, after exploring on the internet I have found some samples like below,
public static void main(String[] args) {
        try {
            int userId = 2;

            DataModel model = new FileDataModel(new File("data/mydataset.csv"), ";");
            UserSimilarity similarity = new PearsonCorrelationSimilarity(model);
            UserNeighborhood neighborhood = new NearestNUserNeighborhood(2, similarity, model);
            UserBasedRecommender recommender = new GenericUserBasedRecommender(model, neighborhood, similarity);

            List<RecommendedItem> recommendations = recommender.recommend(userId, 3);
            for (RecommendedItem recommendation : recommendations) {
                logger.log(Level.INFO, "Item Id recommended : " + recommendation.getItemID() + " Ratings : "
                        + recommendation.getValue() + " For UserId : " + userId);
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "Exception in main() ::", e);
        }

I am using following dataset which contains userid, itemid, preference value respectively,
1,10,1.0
1,11,2.0
1,12,5.0
1,13,5.0
1,14,5.0
1,15,4.0
1,16,5.0
1,17,1.0
1,18,5.0
2,10,1.0
2,11,2.0
2,15,5.0
2,16,4.5
2,17,1.0
2,18,5.0
3,11,2.5
3,12,4.5
3,13,4.0
3,14,3.0
3,15,3.5
3,16,4.5
3,17,4.0
3,18,5.0
4,10,5.0
4,11,5.0
4,12,5.0
4,13,0.0
4,14,2.0
4,15,3.0
4,16,1.0
4,17,4.0
4,18,1.0

In this case, it works fine, but my main question is I have the different set of data which don't have preference values, which contains some data based on that I am thinking to compute preference values. Following is my new dataset,
userid  itemid  likes   shares  comments
1        4       1      20      3
2        6       18     20      12
3        12      10     2       20
4        7       0      20      13
5        9       0      2       1
6        5       5      3       2
7        3       9      7       0
8        1       15     0       0

My question is how can I compute preference value for a particular record based on some other columns such as likes, shares, comments etc. Is there anyway to compute this in mahout?

A: Yes- I think your snippet is from an older version of Mahout, but what you want to use is the Correlated Co Occurrence recommender. The CCO Recommender is multi-modal (allows user to have various inputs).
There are CLI Drivers, but I'm guessing you want to code, there is a Scala tutorial here
In the tutorial I think it recommends 'friends' based on genres tagged and artists 'liked', as well as your current friends.

A: As @rawkintrevo says, Mahout has moved on from the older "taste" recommenders and they will be deprecated from Mahout soon.
You can build you own system from the CCO algorithm in Mahout here. It allows you to use data from different user behavior like "likes, shares, comments". So we call it multi-modal.
Or in another project we have created a full featured recommendation server based on Mahout, called the Universal Recommender. It is build on Apache PredicitonIO where the UR is a plugin called a Template. Together they deliver a nearly turnkey server that takes input and responds to queries. To get started easily try the AWS AMI that has the whole system working. Some other methods to install are shown here.
This is all Apache licensed OSS, but Mahout no longer can really provide a production ready environment, Mahout does algorithms but you need a system around it. Build your own or try the PredictionIO based one. Since everything is OSS you can tweak things if needed.


text:
Q: How to find all subgroups of $(\mathbb{Q},+)$ Exercise 1.6.13 from Scott's book  Group Theory.

(Hard) Find all subgroups of $(\mathbb{Q},+)$. Hint: It is slightly
  easier to find those subgroups $H$ such that $1\in H.$

I've found some of those subgroups: $\mathbb{Z}$, $\mathbb{Q}$, $\langle 1,\frac{1}{2}\rangle$, $\langle 1,\frac{1}{2},\frac{1}{3}\rangle$, $\cdots $. But can't I find all of them. How to find them?

A: Let $A$ be an additive subgroup of $\mathbb Q$. Let $D$ be the set of denominators occurring in $A$ when you consider reduced fractions only. Then the following are easy to prove:

*

*$b\in D, u \mid b \implies u\in D$

*$u,v \in D, (u,v)=1 \implies uv \in D$

The first property means that you cannot increase the power of a prime in $D$. The second property means that you can combine powers of different primes. That should give you a description of $D$.
$A \cap \mathbb Z$ is an additive subgroup of $\mathbb Z$ and these are easy to characterize. That should give you a description of the set $N$ of numerators in $A$.
For a complete solution, see the paper

Ross A. Beaumont and H. S. Zuckerman, A characterization of the subgroups of the additive rationals, Pacific J. Math. Volume 1, Number 2 (1951), 169-177. MR0044522


text:
Q: Changing Views but let the background stay in place Is it possible to let the Background stay in place and only move the Objects in the View with a push effect?
I know that I could let the objects move from out of the view into the view and so on but that isn't really what I was looking for.
Like the effect on the Homescreen with the App-Icons

A: Try a transparent UIScrollView, have a background behind it. As the subviews of the scroll view scroll, the background won't move.


text:
Q: use 'Collections.frequency' to get a count of instances given one value To simplify what I'm doing, let's use the example from learnfromexamples.com that I modified a few bits.
package test;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

class Employee {
        private String empno;
        private String empName;

        public Employee(String empno, String empName ) {
            this.empno = empno;
            this.empName = empName;
        }

        public String getEmpno() {
            return empno;
        }

        public void setEmpno(String empno) {
            this.empno = empno;
        }

        public String getEmpName() {
            return empName;
        }

        public void setEmpName(String empName) {
            this.empName = empName;
        }
        @Override
        public String toString() {
            return "Empno is "+ empno + " Empname is " + empName;
        }
        public Employee() {
            // TODO Auto-generated constructor stub
        }

        @Override
        public boolean equals(Object arg0) {
            // TODO Auto-generated method stub
            boolean flag = false;
            Employee employee = (Employee) arg0;
            if(null!= employee && employee.getEmpName().equalsIgnoreCase(empName) && employee.getEmpno().equalsIgnoreCase(empno)){
                flag = true;
            }
            return flag;
        }

    }

public class Test  {
    public static void main(String[] args) {

        List<Employee> empList = new ArrayList<Employee>();
        empList.add(new Employee("001", "Shidhar"));
        empList.add(new Employee("002", "Pathy"));
        empList.add(new Employee("003", "Sahana"));
        empList.add(new Employee("003", "Sahana"));
        empList.add(new Employee("004", "Sahana"));
        empList.add(new Employee("003", "Sahana"));

        //Get the occurrence of "new Employee("003", "Sahana")" from empLists
        //int sahanaCount = Collections.frequency(empList, new Employee("003"));
        //System.out.println("Count of sahana is : " +sahanaCount);

        Set<Employee> uniqueId = new HashSet<Employee>(empList);
        for (Employee emId : uniqueId) {
            System.out.println("The emp with id "+emId.getEmpno()+" was repeated: "
                    + Collections.frequency(empList, emId.getEmpName()));
        }

    }
}

Is it possible to use Collections.frequency to find frequency given one variable e.g. Collections.frequency(empList,"Sahana"); that yields 4.
Another alternative is I can use HashMap to keep the count but let's say I'm impressed with Collections.frequency and try to use it.

A: No, it's impossible given your implementation of equals. In Java-8 instead of Collections.frequency you can use Stream API instead:
empList.stream().map(Employee::getEmpName).filter(emId.getEmpName()::equals).count();

A: Sets are not suitable to store an object multiple times. Sets remove duplicates from it. You need to have several changes in your code to make this work out

*

*Use ArrayList or any other list implementation instead of HashSet

*In your equals() method, the equality of the object is done comparing both empno and empName.so, you should use the same empno value while creating the Employee object when adding to the collection to pass the equality comparison. Otherwise, the equal() method need to be modified.

The code change would be "003" instead of "004"
empList.add(new Employee("003", "Sahana"));
empList.add(new Employee("003", "Sahana"));
empList.add(new Employee("003", "Sahana"));
empList.add(new Employee("003", "Sahana"));

and remove the below line
Set<Employee> uniqueId = new HashSet<Employee>(empList);

where HashSet takes the list as the argument. Now, Iterate the list directly
for (Employee employee : empList) {
            System.out.println("The emp with id "+employee.getEmpno()+" was repeated: "
                    + Collections.frequency(empList, employee);
        }

and finally pass the employee instance instead of passing empName of the employee instance. This should print the number of duplicate objects present in the list. This is what Collections.frequency method is intended for.
To get the count based on 'empName', you should go for a custom implementation like
private int getCount(String empName){
    int count = 0;
    for (Employee employee : empList) {
        if(employee.getEmpName() != null && employee.getEmpName().equals(empName)){
count++;
}
            }
return count;
}

A: From the JavaDoc itself

Returns the number of elements in the specified collection equal to
  the specified object. More formally, returns the number of elements e
  in the collection such that (o == null ? e == null : o.equals(e)).

So yes you could use Collections.frequency. But you got to be careful with equals method and override it according to your implementation, which will identify equal objects for the Collections.frequency method


text:
Q: select from missing table error in subquery (after WHEN EXISTS in CASE) ** edited to invert logic in EXISTS test
I need to select a field from a table that may not exist. I also need to do this in a sub query.
There is a code release coming from engineering that will add a table to a database I scrape for reporting. If the table exists, select the field. If it does not, give a generic failure.
** Yes, there are tons of examples on how to use EXISTS. This goes outside of those as it deals with something that may not exist.
The new code release will rollout to several sites, some may not have the table immediately where others will. My stuff has to ready for Day Zero - aka: rolled out before hand (day -1?).
Here is my code (tables and columns renamed) that I am trying to make work in SQL Server Management Studio (SQL 2016) (SSMS 17.4)
select 'Cern' as  SiteName,
(
select
case when exists (select 1 from sys.tables where name like 'ProtonAcceleratorSecurity')
 then
   (select top 1 isnull(SecurityID,'Not on file') from [ProtonAcceleratorSecurity] with (nolock) )
 else
   (select 'No Security Table Found')
end
 as SecurityID

It looks contrived, but it is very near what I am trying to do, using that exact query (but nothing to do with security...)
The goal is to get back the site name, and the first security ID (at random - doesn't matter - no consistency required) - but only if the table actually exists.
The problem is that SSMS throws an error telling me that the table is an invalid object which I already know.
"Invalid object name 'ProtonAcceleratorSecurity' "
Final answer from @TabAlleman, with a minor correction:

SET @sql = '
select ''Cern'' as  SiteName, ' +
( select
    case when exists (select 1 from sys.tables where name like 'ProtonAcceleratorSecurity')
 then
   '(select top 1 isnull(SecurityID,''Not on file'') from [ProtonAcceleratorSecurity] with (nolock) )'
 else
   '''No Security Table Found'''
end  )
+ ' as SecurityID ';

EXEC (@sql); ```

A: The reason for your error is that SQL Server will parse and compile your entire statement before it executes it.  So your query cannot contain references to invalid objects, even though the query itself checks to make sure the object is valid before referencing it.   The parser isn't smart enough to know that the subquery will not be called if the object doesn't exist, so it will prevent you from running the query at all.
One way you can trick the parser is through dynamic sql, which doesn't get pre-parsed:
DECLARE @sql varchar(max);

SET @sql = '
select ''Cern'' as  SiteName, '

+
select
case when exists (select 1 from sys.tables where name like 'ProtonAcceleratorSecurity')
 then
   '(select top 1 isnull(SecurityID,''Not on file'') from [ProtonAcceleratorSecurity] with (nolock) )'
 else
   '''No Security Table Found'''
end
+

' as SecurityID
';

EXEC (@sql);

EDIT because I'm not testing as I go, but just to make the idea clear:
You need to check for the existence of the table in the outer query, but then only construct a dynamic query that uses the table if it exists. To make it really simple, ignoring your original CASE structure, you want to logically do this:
IF EXISTS({SELECT query to test for MyTable})
  @SQL = 'query that references MyTable';
ELSE
  @SQL = 'query that doesn't reference MyTable';

EXECUTE (@SQL);

PS:  I think I just fixed the syntax in my first example.

A: I don't think there is any way to do this in a single query.  One suggestion is to hide this in a view:
IF OBJECT_ID('ProtonAcceleratorSecurity') IS NULL
BEGIN
    CREATE VIEW ProtonAcceleratorSecurity
        SELECT 'Not on file' as SecurityID
END;

Then your query can work simply as:
select 'Cern' as SiteName,
       (select top 1 coalesce(SecurityID, 'Not on file')
        from ProtonAcceleratorSecurity
       ) as SecurityID

A: You are getting the problem because the table must exist when the statement is executed.
If you divide it into two statements then there is no problem. The one referencing the non existent table is marked for deferred compilation and as it is never executed the full compilation is never needed and no error.
IF OBJECT_ID('ProtonAcceleratorSecurity', 'U') IS NULL
  SELECT 'Cern'                    AS SiteName,
         'No Security Table Found' AS SecurityID
ELSE
  SELECT TOP 1 'Cern' AS SiteName,
               isnull(SecurityID, 'Not on file') AS SecurityID
  FROM   [ProtonAcceleratorSecurity] WITH (nolock)
  ORDER BY ....


text:
Q: Adding start delay  function moveto(coordinates) {
  step1 = coordinates[0];
  step2 = coordinates[1];
        var w = $(document).width();
        var h = $(document).height();

   $( "#full" )
   .animate({left: -(step1 * w)}, 2000 )
   .animate({top: -(step2 * h) }, 500 );
   }
   var randomNum = randomNumbers();
   moveto(randomNum);

I need to add start delay of this function and to replay after a certain time

A: Change this:
var randomNum = randomNumbers();
moveto(randomNum);

To:
function doRandomMove(){
    var randomNum = randomNumbers();
    moveto(randomNum);
}
setTimeout(function(){
    doRandomMove()
    setInterval(doRandomMove, 10 * 1000);
}, 1000);

This will first call the change at 1 second, and keeps repeating after 10 seconds after first call.

A: Try this window.setTimeout("moveto(1,2)", 1000);.
Your function will be called with a delay of 1000ms.


text:
Q: Undetermined PDE Error I'm trying to solve the Fokker-Planck equation
$$\frac{\partial p}{\partial L}(L, \eta)= \frac{\partial}{\partial \eta}\left[\left(\eta^{2}-1\right) \frac{\partial p}{\partial \eta}(L, \eta)\right] = (\eta^2-1)\frac{\partial^2p}{\partial\eta^2}(L,\eta)+2\eta\frac{\partial p}{\partial\eta}(L,\eta), \quad \eta>1$$
with initial condition
$$p(L=0, \eta)=\delta(\eta-1).$$
Ignoring the initial condition my code is
FPE = D[P[L, eta],
   L] == (1/Lloc)*((eta^2 - 1)*D[P[L, eta], {eta, 2}] +
     2*eta*D[P[L, eta], eta])

s = NDSolve[{FPE, P[0, eta] == DiracDelta[eta-1]}, P, {L, 0, 30}, {eta, 1, 30}]

to which I get the error "Encountered non-numerical value for a derivative at L == 0." Is there something I have done wrong? I know this FPE has an analytical solution in terms of Legendre polynomials. Any help would be much appreciated. Thanks.

A: Try
n = 20;
FPE = D[P[L, eta], L] - D[(eta^2 - 1) D[P[L, eta], eta], eta]
s = Quiet @ NDSolve[{FPE == 0, P[0, eta] == D[Tanh[n (eta - 1)], eta]}, P, {L, 0, 30}, {eta, 1, 30}][[1]]
Plot3D[Evaluate[P[L, eta] /. s], {L, 0, 30}, {eta, 1, 30}]

Here the problem is with DiracDelta[]. Use instead an approximation as
DiracDelta[eta] ~ D[Tanh[n eta], eta]

for $n \gg 1$ and $\eta \ge 0$


text: Q: Prevent ondestroyview to be called for Fragment I have a scenerio in which I am using Fragment with viewpager. The viewpager is having nested fragments with each fragment having a listview. I am using FragmentStatePagerAdapter and have given setOffscreenPageLimit as the size of arraylist. Now when i switch from this fragment to another fragment, all the fragments of viewpager are destroyed. Is there any way to prevent the fragments to be destroyed.


text:
Q: What are the relations between deploy-mode client and master yarn-client I use spark-submit to ran my spark program and I use --deploy-mode client and --master yarn-client to set parameter.My question are:
Q1: Does it means the use of --deploy-mode client and the use of --master yarn-client is same,both of them denote that the driver program are running on the client? Is there any difference between them?
Q2: Does --deploy-mode client  means that my program ran on only a single machine but not on the cluster because I found the follow information in log:all my task finished on localhost.
15/12/29 10:27:28 INFO scheduler.TaskSetManager: Finished task 5.0 in stage 0.0 (TID 5) in 726 ms on localhost (1/8)
15/12/29 10:27:28 INFO scheduler.TaskSetManager: Finished task 6.0 in stage 0.0 (TID 6) in 727 ms on localhost (2/8)
15/12/29 10:27:28 INFO scheduler.TaskSetManager: Finished task 3.0 in stage 0.0 (TID 3) in 730 ms on localhost (3/8)
15/12/29 10:27:28 INFO scheduler.TaskSetManager: Finished task 1.0 in stage 0.0 (TID 1) in 737 ms on localhost (4/8)
15/12/29 10:27:28 INFO scheduler.TaskSetManager: Finished task 4.0 in stage 0.0 (TID 4) in 739 ms on localhost (5/8)
15/12/29 10:27:28 INFO scheduler.TaskSetManager: Finished task 0.0 in stage 0.0 (TID 0) in 749 ms on localhost (6/8)
15/12/29 10:27:28 INFO scheduler.TaskSetManager: Finished task 2.0 in stage 0.0 (TID 2) in 744 ms on localhost (7/8)
15/12/29 10:27:28 INFO scheduler.TaskSetManager: Finished task 7.0 in stage 0.0 (TID 7) in 741 ms on localhost (8/8)

A: You are correct that the yarn-client and deploy-mode client (with master set to yarn I assume) both run the driver on the client. There is no difference between the two.
As to your second question, deploy-mode client only acts as a signal to run the driver on the client. The tasks will be distributed based on your other settings. So, you need to either set --master yarn or set the environment to be yarn export SPARK_YARN_MODE=true. Otherwise it'll default to localhost

A: Deploy mode distinguish where driver process runs.
There are two deploy modes that can be used to launch Spark applications on YARN.
In yarn-cluster mode, the Spark driver runs inside an application master process which is managed by YARN on the cluster, and the client can go away after initiating the application.
In yarn-client mode, the driver runs in the client process, and the application master is only used for requesting resources from YARN
EDIT:
Have a look at :
http://spark.apache.org/docs/latest/running-on-yarn.html

Have a look at this cloudera article for better understanding of two different yarn modes :YARN Cluster and YARN Client.
Coming back to your queries:

*

*Your assumption  is correct.

*It should run on cluster. Is your data set big enough to run on multiple executors of different nodes in your cluster?
Except where the driver should run, your job should run in multiple executors on different nodes of  your cluster.

A: The best source of information on this kind of thing is the Submitting Applications page on the Spark website.
Deploy mode controls where the Spark driver sits, either on the client which runs spark-submit (or spark-shell, etc), or on one of the worker machines. It does not control where the actual task is executed, just where the driver sits. "client" mode is the default by the way.
For "deploy-mode", the Spark deployment documentation says

A common deployment strategy is to submit your application from a
  gateway machine that is physically co-located with your worker
  machines (e.g. Master node in a standalone EC2 cluster). In this
  setup, client mode is appropriate. In client mode, the driver is
  launched directly within the spark-submit process which acts as a
  client to the cluster. The input and output of the application is
  attached to the console.
[snipped]
Alternatively, if your application is submitted from a machine far
  from the worker machines (e.g. locally on your laptop), it is common
  to use cluster mode to minimize network latency between the drivers
  and the executors.

The --master yarn-client parameter has a similar effect, but with some YARN specifics (other than telling Spark to run on the YARN cluster), mostly around configuration settings like spark.local.dir vs the YARN equivalents.
If you're running YARN, you can skip setting the --driver client parameter, and use --master yarn-client or --master yarn-cluster


text:
Q: Plotting multiple spectra on ggplot gives a strange plot with vertical lines joining y-values to each x-value instead of single y-values per x-value I am trying to plot multiple spectra on ggplot. Each spectra should be a separate line, but it is doing something strange and joining y-values at each x-value instead of joining across x-values.
My data is in long format;

     V1       Sample_ID wavenumber transmittance
  1 Crete         1       1328       1180708
  2 Crete         1       1330       1180866
  3 Crete         1       1332       1181083
  4 Crete         1       1334       1181379

and I used the below code to plot the spectra:
ggplot(data = data, aes(x = wavenumber, y = transmittance, color = Sample_ID)) + geom_line()

The plot should be lots of lines (Each Sample_ID) stacked on top of eachother...


text:
Q: Asp.net identity What linq query can I write to return all users with their roles including users without role? I want to get all users with their roles grouped by their name, and also include users that don't  have any role.
I am using asp.net identity 2 so far i have tried
from user in users
from identityUserRole in user.Roles
join identityRole in identityRole on identityUserRole.RoleId equals identityRole.Id into r
from roles in r
group roles.Name by user.UserName into g
select new
{
    UserName = g.Key,
    Roles = g.ToList()
};

But this return only users that have role..

A: I prefer to use a model to map data:
public class UserDto
{
    public string UserName { set; get; }
    public List<string> Roles { set; get; }
}

and then get all users and their roleNames like this:
var users = (from u in db.Users
             let query = (from ur in db.Set<IdentityUserRole>()
                          where ur.UserId.Equals(u.Id)
                          join r in db.Roles on ur.RoleId equals r.Id
                          select r.Name)
             select new UserDto { UserName = u.UserName, Roles = query.ToList() })
             .ToList();

A: To perform a "left join" with empty role lists, try:
from roles in r.DefaultIfEmpty()

A: You could also simplify your query to this.
var userAndRoles = users.Select(user => new
{
    UserName = user.UserName,
    Roles = roles.Where(role => user.Roles.Any(userRole => userRole.UserId == user.UserId && userRole.RoleId == role.RoleId))
});


text:
Q: Conditional probability involving combinations A committee consists of 5 members.The 5 members are chosen from 9 men and 6 women.
Find the probability that 3 men and 2 women are chosen given that that there must be at least 2 women and 2 men in the committee.
Is the answer 9C3 × 6C2/(9C3×6C2 + 6C3 × 9C2)?

A: Comment. Two exact computations and a simulation in R statistical software:
Sometimes one gains confidence in an answer by looking at the problem in several different ways.
(1) Numerical computation of your result:
choose(9,3)*choose(6,2)/(choose(9,3)*choose(6,2)+choose(9,2)*choose(6,3))
## 0.6363636

(2) Let $W$ be the hypergeometric random variable that counts the number
of women selected in this experiment. You want
$$P(W = 2 | W =2\; or\; 3) = P(W=2)/[P(W = 2) + P(W=3)].$$
dhyper(2, 6, 9, 5)/sum(dhyper(2:3, 6, 9, 5))
## 0.6363636

(3) Simulate the experiment a million times and count the proportion of instances of $\{W=2\}$ among instances of $\{W=2\} \cup \{W = 3\}.$
Approximation with about three place accuracy. (In R, | signifies $\cup$,
and the mean of a logical vector of TRUEs and FALSEs is its
proportion of TRUEs.)
m = 10^6;  w = numeric(m)
pop = c(rep(1, 6), rep(0,9))  # six women (1's) and nine men
for (i in 1:m) {  w[i] = sum(sample(pop, 5))  }
mean(w[w==2|w==3]==2)
## 0.6358527


text:
Q: Akkoy solver - prolog i'm new to prolog and I want to solve the puzzle Akkoy with restrictions.
So far, i've been able to implement wich cells can be painted but i don't know how to force the white areas to have all the same area.
For now when solving the problem, prolog gives two answers, but I want only the first one.
Right Answer
Wrong Answer
akkoy_solver(Rows, Cols) :-
    length(Rows, X),
    length(Cols, Y),
    make_grid(Grid, X, Y, Vars),
    reset_timer,
    solver(Rows, Cols, Grid),
    label(Vars),
    printAkkoy(Grid, Rows, Cols),
    print_time,
    statistics, nl.


text:
Q: How to load a part of an webpage in android webview? I would like to make an app, that shows a part of the site.
Lets say that i have this site:
I only want to show this:
https://mail.google.com/mail/?ui=2&ik=d5146163e8&view=att&th=132496ec47863fea&attid=0.1&disp=inline&realattid=f_gsbtyog80&zw
Is there anyway to do this?
I hope some of you could help me.
Gaauwe

A: You could load the url to a WebView and then set the WebView's scroll position and zoom level to display only a specific part of the web page. If you don't want to change zoom level you could initially scroll the WebView to the required location and then override the WebView's onTouch method so that it will only scroll upto the required cordinates.
public class MyWebViewActivity extends Activity implements PictureListener{

private WebView webView;

@Override
public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);

        webView = (WebView)findViewById(R.id.webView1);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new MyWebViewClient());
        webView.setPictureListener(this);
        // disable scroll on touch
        webView.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {
                return (event.getAction() == MotionEvent.ACTION_MOVE);
            }

        });
        webView.loadUrl(url);

    }

@Override
public void onNewPicture(WebView view, Picture picture) {
    // TODO Auto-generated method stub

    webView.scrollTo(x, y);
}
}

A: One of the way is to use PHP on your own server and CURL the webpage into it and strip out all the unnecessary things .
After that you only load it into your webview.
*This is one of the method,  there are others method better then this. *
Another way is coldfusion cfhttp .. not sure,about this http://www.quackit.com/coldfusion/tutorial/coldfusion_http.cfm


text:
Q: formatting text using awk Hi  I have the following text and I need to use awk or sed to print 3 separate columns
11/13/14    101 HUDSON AUBONPAINJERSEY CITY NJ      $4.15
11/22/14    MTAMVM*110TH ST/CATNEW YORK NY          $19.05
11/22/14    DUANE READE #14226 0NEW YORK NY         $1.26

So I like to produce a file containing all the dates. Another file containing all the description and third file containing all the numbers
I can use an awk to print the first column printy $1 and then use -F [$] option to print last column but I'm not able to just print the middle column as there are spaces etc. Can I ignore the spaces?  or is there a better way of doing this?
Thaking you in advance

A: Try doing this :
 $ awk '
     {
         print $1 > "dates"; $1=""
         print $NF > "prices"; $NF=""
         print $0 > "desc"
     }
' file

or :
awk -F'  +' '
    {
        print $1 > "dates"
        print $2 > "desc"
        print $3 > "prices"
    }
' file

Then :
$ cat dates
$ cat desc
$ cat prices

A: Wasn't fast enough to be the first to give an awk solution, so here's one with grep and sed...
grep -o '^.*/.*/1.' file   #first col
sed 's/^.*\/.*\/1.//;s/\$.*//' file   #middle col
grep -o '\$.*$' file    #last col


text:
Q: What is the radius of convergence of the Taylor series of $\frac{2\tan x}{1+4x^2}$ around $x=0?$ What is the radius of convergence of the Taylor series of $\frac{2\tan x}{1+4x^2}$ around $x=0?$
I have to find out $a_n=\frac {f^{(n)}(0)}{n!}$, but the $n-$th  derivative of the given function is not easy to handle. Please help. Thanks,

A: If Complex Analysis is allowed: Let $P:=\{(2k+1) \frac{\pi}{2}:k \in \mathbb Z\} \cup \{\frac{i}{2},-\frac{i}{2}\}$ and $f(z):=\frac{2 \tan(z)}{1+4z^2}$.
Then $f$ is holomorphic on $ \mathbb C \setminus P$.
Hence the radius of convergence in question is given by
$$ \min \{|0-p|: p \in P\}=\frac{1}{2}.$$

A: Hint. The function $f(x):=\frac{2\tan x}{1+4x^2}$ is odd and the coefficient of $x^{2n+1}$  of its Taylor expansion at $0$  is equal to
$$b_{2n+1}=2[x^{2n+1}]\sum_{k=0}^{\infty}a_{2k+1} x^{2k+1}\cdot \sum_{k=0}^{\infty}(-4x^2)^{k}\\=2(a_{2n+1}-4a_{2n-1}+4^2a_{2n-3}+\dots +(-4)^na_1)$$
where $\sum_{k=0}^{\infty}a_{2k+1} x^{2k+1}$ is the Taylor's series at $0$ of $\tan(x)$.
Notice that $a_{2n+1}\sim \frac{C}{(\pi/2)^{2n+1}}$ (see for example Calculate and justify why one has this asymptotic for the nth odd coefficient of the tangent function).
Show that
$$\lim_{n\to +\infty}\sqrt[2n+1]{|b_{2n+1}|}=2$$
and therefore the radius of convergence is $1/2$.


text:
Q: Adding bold tag to a string in pdf How can I able add bold font style to a specific string in a PDF. I tried to read the PDF using TIKA. Now I have to search for a specific string and display it as bold string. How it can be done in python?
ot = welcome to python programming
regex=r"python"
print(ot.replace(regex,"<b>"+regex+"</b>"))

Since I read the pdf using TIKA, the matched word is printed along bold tags.


text:
Q: Why does npm install local packages in my home directory? Node.js newbie here, Windows 10. I npm install-ed some packages (without -g) while inside a directory that didn't have package.json. npm placed the packages in C:\Users\{MyName}\node_modules\.
Now I'm seeing some weird behavior:

*

*When I'm in my project directory (has package.json but no node_modules/ yet), npm list and npm list -g both show an empty list

*When I'm in a non-project directory (no package.json)...

*

*npm list -g still shows an empty list

*However, npm list shows everything in C:\Users\{MyName}\node_modules\
Question 1. What is going on here? Apparently, npm's default global path should be C:\Users\{MyName}\AppData\Roaming\npm\. If so, why is it using C:\Users\{MyName}\node_modules\?
Question 2. How do I get out of this mess? Node.js has no problem importing packages from C:\Users\{MyName}\node_modules\, but I want npm to list them properly. How can I delete the semi-global packages, reinstall them correctly, and ensure that this doesn't happen again?

A: Not sure why it's doing it, but the way to avoid it is to initialize your project directory using:
npm init

or if you don't want to answer the questions:
npm init -y

That will setup the directory with the package.json and node_modules will be put there.

A: Welp, turns out I've been mistakenly npm install-ing packages without package.json. The first time I did this, I was in my home directory(C:\Users\{MyName}\). This caused npm to create node_modules/ and package-lock.json in the home directory. Further (mistaken) attempts to install packages in my projects--which were still missing package.json--caused npm to traverse upwards, until it found the initial node_modules/ dir, and install everything there. Because my home directory is among the places Node.js looks for modules, I didn't notice my mistake until now. :P

A: Ok, a couple of tips then...
when you install a package that you are going to use in production then add --save, e.g.
npm install --save some-package
this will automatically add the dependency to your package.json. If you are installing a package for use purely in development, e.g. chai, then use--save-devand it will add it to the development dependencies.

Also, git is your friend, even if you are only messing :)
Happy noding :)

A: For me the solution here was:

*

*Go to c:\users[me]\AppData\Roaming\npm and delete the node_modules folder completely

*Make sure I had the package.json file for the project

*Delete the project package-lock.json file

*Run npm init

*Run npm install

Project then worked, not sure why the node_modules got to be in the folder above, ain't got time to find out.


text:
Q: How can i optimise this function (beginner ) JAVA I have this function and I need to optimise it so that it takes less time running:
public static int recherche(int cherche, int[] t) {
    int srch = 0;
    int tmp=0;
    boolean result = false;
    for (int i=0; i<t.length ; i++) {
        if (t[i]== cherche && result == false) {
            tmp++;
            srch = i;
            result=true;
        }
    }
    if (tmp!=0) {
        return srch ;
    }
    else {
        return -1;
    }
}

Also I can't use any library tools.

A: If I understand your method correctly you are searching for the index of the first occurrence of cherche in your array t, or -1 if not found.
The problem with your code is, that you keep looping even if you already found the entry. It is better to break the loop immediately. You also do not need the extra variables.
public static int recherche(int cherche, int[] t) {
    int srch = -1;
    for (int i = 0; i < t.length; i++) {
        if (t[i] == cherche) {
            srch = i;
            break;
        }
    }
    return srch;
}

If this is still too slow, you could try to store the data sorted or create some kind of index.
If you had a List instead of an Array, you could use the indexOf method, but I do not think it can be any faster for unsorted data.
It will be always O(n), because you have to check all array values in the worst case.
P.S: Please consider to use better variable names. I have no idea what t and cherche are.

A: There is no real optimization that can be done with this function in Java. If you know that the array t is sorted, you could use binary sort.
I cleaned your code up a bit though
public static int recherche(int cherche, int[] t) {
    for (int i = 0; i < t.length; i++) {
        if (t[i] == cherche) {
            return i;
        }
    }

    return -1;
}

A: The optimizations you can do are returning the result right after you found it and removing redundant variables.
public static int research(int searched, int[] t) {
    for (int i=0; i < t.length ; i++) {
        if (t[i] == searched) {
            return i;
        }
    }
    return -1;
}


text:
Q: Why is :last-child not giving me the results I expect? jsFiddle here: http://jsfiddle.net/_mtr/uqMZJ/
Basically, a table with rows, only 10 or so are not hidden when the document is ready. I want the index of the last non-hidden row, but my jQuery selectors are letting me down.

A: You're misusing the :last-child selector, which matches elements that are the last child of their parent. You actually want the last element in the matched set, so you should use the :last selector instead:
i2 = $('table .visible:last').index();

You will find an updated fiddle here.

A: Because there is nothing (neither <tbody>nor <tr> nor <td>with the class visible that at the same time is the table's last child.
You should use :last instead, which selects the last matching element in a jquery collection.

A: You' better use class selector at the end:
var i2 = $('table :last-child .visible').index();

Because :last-child applies to table.

A: Last-child simply tells you that the element is the last child of the parent, not the last of the group matched by the preceding selector. None of the tr.visibles is the last child of the table tag. To get the last visible tr, try this instead:
$('tr.visible').last ();

That's what the "last" method is for :)