text:
Q: error in Expandable List View in android I'm new in android
and i want to make an expandable list according to this code:
public class ListexpActivity extends ExpandableListActivity {

    ExpandableListView  epView;

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

        ExpandableListAdapter mAdapter;
        epView = (ExpandableListView) findViewById(R.id.expandablelistview01);
        mAdapter = new MyExpandableListAdapter();
        epView.setAdapter(mAdapter);
        epView.setOnGroupClickListener(new OnGroupClickListener() {
            @Override
            public boolean onGroupClick( ExpandableListView arg0, View arg1, int groupPosition, long arg3 ) {
                if (groupPosition == 5) {
                }
                return false;
            }
        });

        epView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick( ExpandableListView parent, View v, int groupPosition, int childPosition, long id ) {
                if (groupPosition == 0 && childPosition == 0) {
                }
                return false;
            }
        });

    }

    class MyExpandableListAdapter extends BaseExpandableListAdapter {
        // Sample data set. children[i] contains the children (String[]) for
        // groups[i].
        private String[]    groups      = { "Parent1", "Parent2", "Parent3" };
        private String[][]  children    = { { "Child1" }, { "Child2" }, { "Child3" }, { "Child4" }, { "Child5" } };

        public Object getChild( int groupPosition, int childPosition ) {
            return children[groupPosition][childPosition];
        }

        public long getChildId( int groupPosition, int childPosition ) {
            return childPosition;
        }

        public int getChildrenCount( int groupPosition ) {
            int i = 0;
            try {
                i = children[groupPosition].length;

            } catch (Exception e) {
            }

            return i;
        }

        public TextView getGenericView() {
            // Layout parameters for the ExpandableListView
            AbsListView.LayoutParams lp = new AbsListView.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, 64);

            TextView textView = new TextView(ListexpActivity.this);
            textView.setLayoutParams(lp);
            // Center the text vertically
            textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
            // textView.setTextColor(R.color.marcyred);
            // Set the text starting position
            textView.setPadding(36, 0, 0, 0);
            return textView;
        }

        public View getChildView( int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent ) {
            TextView textView = getGenericView();
            textView.setText(getChild(groupPosition, childPosition).toString());
            return textView;
        }

        public Object getGroup( int groupPosition ) {
            return groups[groupPosition];
        }

        public int getGroupCount() {
            return groups.length;
        }

        public long getGroupId( int groupPosition ) {
            return groupPosition;
        }

        public View getGroupView( int groupPosition, boolean isExpanded, View convertView, ViewGroup parent ) {
            TextView textView = getGenericView();
            textView.setText(getGroup(groupPosition).toString());
            return textView;
        }

        public boolean isChildSelectable( int groupPosition, int childPosition ) {

            return true;
        }

        public boolean hasStableIds() {
            return true;
        }
    }
}

and in xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <ExpandableListView
        android:id="@+id/expandablelistview01"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ExpandableListView>

</LinearLayout>

but when implement the program in emulator the error is
    05-11 14:38:24.507: E/AndroidRuntime(332): FATAL EXCEPTION: main
    05-11 14:38:24.507: E/AndroidRuntime(332): java.lang.RuntimeException: Unable to start activity ComponentInfo{ola.listexp.Main/ola.listexp.Main.ListexpActivity}: java.lang.RuntimeException: Your content must have a ExpandableListView whose id attribute is 'android.R.id.list'
    05-11 14:38:24.507: E/AndroidRuntime(332):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
    05-11 14:38:24.507: E/AndroidRuntime(332):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
    05-11 14:38:24.507: E/AndroidRuntime(332):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
    05-11 14:38:24.507: E/AndroidRuntime(332):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
    05-11 14:38:24.507: E/AndroidRuntime(332):  at android.os.Handler.dispatchMessage(Handler.java:99)
    05-11 14:38:24.507: E/AndroidRuntime(332):  at android.os.Looper.loop(Looper.java:123)
    05-11 14:38:24.507: E/AndroidRuntime(332):  at android.app.ActivityThread.main(ActivityThread.java:4627)
    05-11 14:38:24.507: E/AndroidRuntime(332):  at java.lang.reflect.Method.invokeNative(Native Method)
    05-11 14:38:24.507: E/AndroidRuntime(332):  at java.lang.reflect.Method.invoke(Method.java:521)
    05-11 14:38:24.507: E/AndroidRuntime(332):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
    05-11 14:38:24.507: E/AndroidRuntime(332):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
    05-11 14:38:24.507: E/AndroidRuntime(332):  at dalvik.system.NativeStart.main(Native Method)
    05-11 14:38:24.507: E/AndroidRuntime(332): Caused by: java.lang.RuntimeException: Your content must have a ExpandableListView whose id attribute is 'android.R.id.list'
    05-11 14:38:24.507: E/AndroidRuntime(332):  at android.app.ExpandableListActivity.onContentChanged(ExpandableListActivity.java:222)
    05-11 14:38:24.507: E/AndroidRuntime(332):  at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:201)
    05-11 14:38:24.507: E/AndroidRuntime(332):  at android.app.Activity.setContentView(Activity.java:1647)
    05-11 14:38:24.507: E/AndroidRuntime(332):  at ola.listexp.Main.ListexpActivity.onCreate(ListexpActivity.java:31)
    05-11 14:38:24.507: E/AndroidRuntime(332):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    05-11 14:38:24.507: E/AndroidRuntime(332):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

i so from the internet that i should change @+id/expandablelistview01 to @android/idexpandablelistview01
but i have another error in

    NOTE: This project contains resource errors, so aapt did not succeed, which can cause rendering failures. Fix resource problems first.

Unable to resolve id "@andriod:id/expandablelistview01" for attribute "id"`

so help me !

A: There error is indeed related to the id of your expandedlist. From your error code there is the following line:
Caused by: java.lang.RuntimeException: Your content must have a ExpandableListView whose id attribute is 'android.R.id.list'

What it is telling you is that in your XML file the ID associated with the list MUST be @android:id/list
That should clear things up :)


text:
Q: In my Android project using Firebase I get this warning: W / System: Ignoring header X-Firebase-Locale because its value was null I am doing a project with Java in Android Studio. I made a user login page. I want it to redirect to the home page after the user name is entered, but I get a warning like W / System: Ignoring header X-Firebase-Locale because its value was null. The emulator's WiFi is also on.
In the Firebase Authentication section, users are authorized to register with email and password.
Code:
    public MainActivity() {
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btngiris=(Button)findViewById(R.id.button);
        Button btnkayit=(Button)findViewById(R.id.kayit);
        girisyetkisi=FirebaseAuth.getInstance();
        txtadi=findViewById(R.id.txtadi);
        txtemaili=findViewById(R.id.txtemaili);
        txtsifresi=findViewById(R.id.txtsifresi);

        btnkayit.setOnClickListener(v -> {
            Intent intent= new Intent(MainActivity.this,kayitol.class);
            startActivity(intent);
            finish();

        });

        btngiris.setOnClickListener( v -> {
            String str_ad = txtadi.getText().toString();
            String str_email=txtemaili.getText().toString();
            String str_sifre=txtsifresi.getText().toString();

                if(TextUtils.isEmpty(str_ad  )){
                    Toast.makeText(MainActivity.this,"İsim girilmesi gerekir",Toast.LENGTH_LONG).show();
                }
                else if(TextUtils.isEmpty(str_email)) {
                    Toast.makeText(MainActivity.this, "Email girilmesi gerekir", Toast.LENGTH_LONG).show();
                }
                else if (TextUtils.isEmpty(str_sifre)){

                    Toast.makeText(MainActivity.this,"Şifre  girilmesi gerekir",Toast.LENGTH_LONG).show();
                }

            else{
                girisyetkisi.signInWithEmailAndPassword(str_email,str_sifre).addOnCompleteListener(MainActivity.this, task -> {
                    if(task.isSuccessful()){
                        DatabaseReference yolGiris= FirebaseDatabase.getInstance().getReference().child("Kullanıcılar").child(girisyetkisi.getCurrentUser().getUid());
                        yolGiris.addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                                Intent intent=new Intent(MainActivity.this,MenusayfasiActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intent);
                                finish();
                            }

                            @Override
                            public void onCancelled(@NonNull DatabaseError databaseError) {

                            }
                        });
                    }
                    else{
                        Toast.makeText(MainActivity.this,"Giriş başarısız",Toast.LENGTH_LONG).show();
                    }
                });
            }
    });
}

A: dependencies {
implementation platform('com.google.firebase:firebase-bom:25.12.0')

redpajama_set_name: RedPajamaStackExchange


text:
Q: Warning: dereferencing 'void *' pointer error - C With a C program written for solving a heat problem I am getting following error:

saying
In function 'main':
       warning: dereferencing 'void *' pointer [enabled by default]
          if (!fp) *NULL;

The program was meant for this:

Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <unistd.h>
#include <mpi.h>

#define COLS 1000
#define ROWS 1000

#define WHITE    "15 15 15 "
#define RED      "15 00 00 "
#define ORANGE   "15 05 00 "
#define YELLOW   "15 10 00 "
#define LTGREEN  "00 13 00 "
#define GREEN    "05 10 00 "
#define LTBLUE   "00 05 10 "
#define BLUE     "00 00 10 "
#define DARKTEAL "00 05 05 "
#define BROWN    "03 03 00 "
#define BLACK    "00 00 00 "

void copyNewToOld(float grid_a[ROWS][COLS], float grid_b[ROWS][COLS], int x_lower, int x_upper) {
  int x, y;
  for (x = x_lower; x < x_upper; ++x) {
    for (y = 0; y < COLS; ++y) {
      grid_b[x][y] = grid_a[x][y];
    }
  }
}

void calculateNew(
  float grid_a[ROWS][COLS],
  float grid_b[ROWS][COLS],
  int x_lower,
  int x_upper
) {
  // Adjust bounds
  if (x_lower == 0) x_lower = 1;
  if (x_upper == ROWS) x_upper = ROWS - 1;
  int x, y;
  for (x = x_lower; x < x_upper - 1; ++x) {
    for (y = 1; y < COLS - 1; ++y) {
      grid_a[x][y] = 0.25 * (grid_b[x-1][y] + grid_b[x+1][y] + grid_b[x][y-1] + grid_b[x][y+1]);
    }
  }
}

void printGridtoFile(FILE* fp, float grid[ROWS][COLS], int x_lower, int x_upper) {
  int x, y;
  for (x = x_lower; x < x_upper; ++x) {
    for (y = 0; y < COLS; ++y) {
      if (grid[x][y] > 250) {
        fprintf(fp, "%s ", RED );
      } else if (grid[x][y] > 180) {
        fprintf(fp, "%s ", ORANGE );
      } else if (grid[x][y] > 120) {
        fprintf(fp, "%s ", YELLOW );
      } else if (grid[x][y] > 80) {
        fprintf(fp, "%s ", LTGREEN );
      } else if (grid[x][y] > 60) {
        fprintf(fp, "%s ", GREEN );
      } else if (grid[x][y] > 50) {
        fprintf(fp, "%s ", LTBLUE );
      } else if (grid[x][y] > 40) {
        fprintf(fp, "%s ", BLUE );
      } else if (grid[x][y] > 30) {
        fprintf(fp, "%s ", DARKTEAL );
      } else if (grid[x][y] > 20) {
        fprintf(fp, "%s ", BROWN );
      } else {
        fprintf(fp, "%s ", BLACK );
      }
    }
    fprintf(fp, "\n");
  }
}

int main(int argc, char **argv) {
  int h, w, cycles, heat;
  float grid_a[ROWS][COLS];
  float grid_b[ROWS][COLS];

  if (argc != 2) {
    printf("Usage: ./program <number of timestamps>\n");
    exit(0);
  }
  cycles = atoi(argv[1]);

  MPI_Init(NULL, NULL);

  int mpi_size;
  MPI_Comm_size(MPI_COMM_WORLD, &mpi_size);

  int mpi_rank;
  MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);

  int x_lower =  mpi_rank    * ROWS / mpi_size;
  int x_upper = (mpi_rank+1) * ROWS / mpi_size;

  /*fprintf(stderr, "CPU=%d/%d x_lower=%d x_upper=%d\n", mpi_rank, mpi_size, x_lower, x_upper);*/

  for (h = x_lower; h < x_upper; ++h) {
    for (w = 0; w < COLS; ++w) {
      grid_a[w][h] = 20;
    }
  }

  for (heat = 299; heat < 700; ++heat) {
    grid_a[0][heat] = 300;
  }

  for (cycles; cycles > 0; --cycles) {
    /*fprintf(stderr, "[%d] Cycle=%d\n", mpi_rank, cycles);*/
    copyNewToOld(grid_a, grid_b, x_lower, x_upper);
    if (mpi_rank != 0) MPI_Sendrecv(
      grid_a[x_lower-1],  // sendbuf
      COLS,               // sendcount
      MPI_FLOAT,          // sendtype
      mpi_rank-1,         // dest
      0,                  // sendtag

      grid_b[x_lower-1],  // recvbuf
      COLS,               // recvcount
      MPI_FLOAT,          // recvtype
      mpi_rank-1,         // source
      0,                  // recvtag

      MPI_COMM_WORLD,     // communicator
      MPI_STATUS_IGNORE   // status
    );

    if (mpi_rank+1 != mpi_size) MPI_Sendrecv(
      grid_a[x_upper+1],  // sendbuf
      COLS,               // sendcount
      MPI_FLOAT,          // sendtype
      mpi_rank+1,         // dest
      0,                  // sendtag

      grid_b[x_upper+1],  // recvbuf
      COLS,               // recvcount
      MPI_FLOAT,          // recvtype
      mpi_rank+1,         // source
      0,                  // recvtag

      MPI_COMM_WORLD,     // communicator
      MPI_STATUS_IGNORE   // status
    );

    calculateNew(grid_a, grid_b, x_lower, x_upper);
  }

  FILE* fp;
  if (mpi_rank == 0) {
    fp = fopen("c.pnm", "w");
    fprintf(fp, "P3\n%d %d\n15\n", COLS, ROWS);
    fclose(fp);
  }

  char dummy = 1;
  if (mpi_rank != 0) MPI_Recv(
    &dummy,             // buf
    1,                  // count
    MPI_BYTE,           // type
    mpi_rank-1,         // source
    0,                  // tag
    MPI_COMM_WORLD,     // communicator
    MPI_STATUS_IGNORE   // status
  );

  /*fprintf(stderr, "[%d] Open file\n", mpi_rank);*/
  fp = fopen("c.pnm", "a");
  if (!fp) *NULL;
  /*fprintf(stderr, "[%d] Start printing\n", mpi_rank);*/
  printGridtoFile(fp, grid_a, x_lower, x_upper);

  /*fprintf(stderr, "[%d] Done printing\n", mpi_rank);*/
  fclose(fp);

  if (1) MPI_Send(
    &dummy,                   // buf
    1,                        // count
    MPI_BYTE,                 // type
    (mpi_rank+1) % mpi_size,  // source
    0,                        // tag
    MPI_COMM_WORLD            // communicator
  );

  if (mpi_rank == 0) {
    MPI_Recv(
      &fp,                // buf
      1,                  // count
      MPI_UNSIGNED_LONG,  // type
      mpi_size-1,         // source
      0,                  // tag
      MPI_COMM_WORLD,     // communicator
      MPI_STATUS_IGNORE   // status
    );
    system("convert c.pnm c.png");
  }

  MPI_Finalize();

  return 0;
}

Any help with this issue would be great I'm fairly new to C. Hoping to use this code and for mpirun on Bridges supercomputer with multiple varied processes.

A: The problem is this piece of code:
  /*fprintf(stderr, "[%d] Open file\n", mpi_rank);*/
  fp = fopen("c.pnm", "a");
  if (!fp) *NULL;
  /*fprintf(stderr, "[%d] Start printing\n", mpi_rank);*/
  printGridtoFile(fp, grid_a, x_lower, x_upper);

  /*fprintf(stderr, "[%d] Done printing\n", mpi_rank);*/
  fclose(fp);

You are trying to dereference NULL, which according to the C standard results in undefined behaviour. In your case this will most likely not cause any ill effects, as this expression has no side-effects and the compiler is likely to optimize it away. The compiler you are using is clever enough to spot this potential issue and is warning you in case you made a mistake.
In your case I guess you simply want to handle failures when opening a file. This is how you'd do it in a better way:
  #include <errno.h>

...

  /*fprintf(stderr, "[%d] Open file\n", mpi_rank);*/
  errno = 0;
  fp = fopen("c.pnm", "a");
  if (NULL == fp)
  {
    fprintf(stderr, "Failed to open file due to %d\n", errno);
    exit(errno);
  }

  /*fprintf(stderr, "[%d] Start printing\n", mpi_rank);*/
  printGridtoFile(fp, grid_a, x_lower, x_upper);

  /*fprintf(stderr, "[%d] Done printing\n", mpi_rank);*/
  fclose(fp);


text:
Q: RStudio - ggplot not saving first plot when printing and saving multiple plots in a script Here is the code to reproduce my problem:
library(ggplot2)

data <- data.frame(randomnums <- rnorm(50,100,200))

plot1 <- ggplot(data, aes(randomnums)) + geom_histogram()
print(plot1)
ggsave(plot1, filename="figures/plot1.pdf", width=5, height=3)

plot2 <- ggplot(data, aes(randomnums)) + geom_histogram()
print(plot2)
ggsave(plot2, filename="figures/plot2.pdf", width=5, height=3)

plot3 <- ggplot(data, aes(randomnums)) + geom_histogram()
print(plot3)
ggsave(plot3, filename="figures/plot3.pdf", width=5, height=3)

If each line of the above code is run line by line and waiting for each command to complete, then everything works fine. However, if I select all and run, things break down:

*

*the first pdf file (plot1.pdf) that is saved will have a file size of 0k, and cannot be opened until I close my rsession (via rstudio)

*My plots are not printed onto the screen. In RStudio, I there are no plots in the "plots" tab.

If I restart rstudio, everything will work fine again if I run the code line by line. Am I missing a command to make sure the code can be run as an entire selection?
EDIT: As requested - my session info.
> sessionInfo()
R version 2.15.2 (2012-10-26)
Platform: x86_64-w64-mingw32/x64 (64-bit)

locale:
[1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United States.1252    LC_MONETARY=English_United States.1252
[4] LC_NUMERIC=C                           LC_TIME=English_United States.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] ggplot2_0.9.3.1

loaded via a namespace (and not attached):
 [1] colorspace_1.2-1   dichromat_2.0-0    digest_0.6.3       grid_2.15.2        gtable_0.1.2       labeling_0.1
 [7] lavaan_0.5-12      MASS_7.3-23        munsell_0.4        plyr_1.8           proto_0.3-10       RColorBrewer_1.0-5
[13] reshape2_1.2.2     scales_0.2.3       stats4_2.15.2      stringr_0.6.2      tools_2.15.2

EDIT: It was discovered that this only breaks in RStudio. It works fine in RGui.


text:
Q: What types of objects should the ViewModel reference in the MVVM pattern? I've seen quite a few examples of MVVM. I can see that the View should reference the ViewModel. I've seen recently an example of a ViewModel referencing a View, which seems wrong to me, as it would result in tighter coupling. Given that ViewModel is often described as an intermediary between the View and the Model, is there more to the ViewModel than a facade to domain objects? I hope I used the term "facade" correctly here.

A: Your intuition is right; the ViewModel should not reference the View.
Note that this is a "should". Purists say that the ViewModel should not even reference WPF stuff such as the Visibility enumeration, but I disagree. Among other things, a ViewModel is supposed to help you separate concerns and improve the readability of your code. If you have to jump through hoops to avoid referencing something that belongs to the View, that's a sign that you might be overdoing it.

A: Technically, the view-model should reference the model, but never the view. The view should bind to the view-model, and the view-model should expose convenient properties for binding using data from the model.
Obviously, the complexity of the view-model depends on the application and the data in the model. But to think of it as a "facade" is not terribly harmful (though not exactly correct in developer lingo).


text:
Q: Socket.io Check connection I want to check if the client is connected to socket server.
I don't mean the disconnect event.
Just wanted to check if it is connected to socket server on the client side.
When it is disconnected, I can find bellow image.

I think this means it check connection with specific time interval.
I can't find this function.
How can I check connection?

A: For checking the connection you want to do something like this from the client:
io.on('connect', (e) => { console.log('connected!'); }

That is the event that happens when the client connects to the server. Based on your screenshot I think you may have a larger issue as that error means the connection can't even be created.
Based on the comment you might want something like this:
const socket = io(server_ip+':3000/');
var isSocketConnected = false;
socket.on('connect', () => { isSocketConnected = true; socketEvent(); });
socket.on('reconnect', () => { isSocketConnected  = true; socketEvent(); });
socket.on('disconnect', () => { isSocketConnected  = false; socketEvent(); });

const socketEvent = (event) => {
    console.log(isSocketConnected);
}


text:
Q: Uncaught SyntaxError: Unexpected identifier error within for loop I am trying to write code in which multiple searches and iframes work together to achieve specified results. I am building this site in business catalyst, so it uses WebApps.
Currently I am trying to submit a search into an iframe and then return a dynamic value to the parent window via form fields. I have been receiving the Uncaught SyntaxError: Unexpected identifier error in response to my code. If anyone could help me by taking a look at my code I would be very appreciative. Thank you!
NOTE: The {module_webappresults} tag is part of business catalyst. When this is rendered on the page a series of divs with values is output to the DOM, several of these items will change the value of the variables.
var chapNum = null;
var chapter1ID = 0;
var chapter2ID = 0;
var chapter3ID = 0;
var chapter4ID = 0;
var chapter5ID = 0;
var chapter1 = false;
var chapter2 = false;
var chapter3 = false;
var chapter4 = false;
var chapter5 = false;
</script>

{module_webappsresults,,_self,true,-1,,1}

    <form name="chapter-ids" id="chapter-ids" action="" method="post">
            <input type="text" maxlength="255" name="chap-id-1" id="chap-id-1" class="cat_textbox" value=""/>
            <input type="text" maxlength="255" name="chap-id-2" id="chap-id-2" class="cat_textbox" value=""/>
            <input type="text" maxlength="255" name="chap-id-3" id="chap-id-3" class="cat_textbox" value=""/>
            <input type="text" maxlength="255" name="chap-id-4" id="chap-id-4" class="cat_textbox" value=""/>
            <input type="text" maxlength="255" name="chap-id-5" id="chap-id-5" class="cat_textbox" value=""/>
            <input type="text" maxlength="255" name="total-chapters" id="total-chapters" class="cat_textbox" value=""/>

    </form>


text:
Q: Should I install Python packages as non root user or set up a virtual environment to install them inside a Docker container? When installing Python package through pip in a Dockerfile, such as:
pip install --trusted-host pypi.python.org -r requirements.txt

with requirements.txt, e.g. as:
python-dotenv>=0.15.0
psycopg2>=2.8.6
sqlalchemy>=1.3.22
numpy>=1.19.0
rasterio>=1.1.8
pandas>=1.1.5
geopandas>=0.8.1
matplotlib>=3.3.0
seaborn>=0.11.0

I recently seen this warning:
WARNING: Running pip as the 'root' user can result in broken permissions
and conflicting behavior with the system package manager.
It is recommended to use a virtual environment
instead: https://pip.pypa.io/warnings/venv

Hence my 'naive' question:
would that make sense to set up a virtual environment / or installing Python packages as the non root user (which is the default in Docker), as one would normally do on his/her local computer?
For the moment I never cared about that, because I'm inside a Docker container which by definition hosts a single application, so I think it's perfectly OK that these packages are installed globally. Hopefully I cannot break anything on my local machine.

A: Honestly? It doesn't much matter.
Using the root user during the build of your container is generally necessary and expected. The warning from pip is "running pip as root could screw up the packages your OS programs depend on" - but there's no OS in your container.
If you drop to a less privileged user at the end of your build or during your docker run, installing the packages as root won't have hurt you any. Practically a container is a single process (your python application) that has a view of the filesystem different from the root system- very much like a virtualenv would try to accomplish.

A: As @Paul Becotte said in his answer, there is no risk in installing your packages globally in your container, but you are seeing this warning because pip doesn't care you are running inside a container or not.
The general python good practice is to create a virtual env as an unprivileged user : $ python -m venv .venv
Then activate it : $ source .venv/bin/activate
And then install your packages with your $ pip install -r requirements.txt command.
You can totally adapt that to the docker build syntax :
RUN python -m venv /abolute/path/to/venv
RUN source /absolute/path/to/venv/bin/activate && pip install -r requirements.txt
CMD source /absolute/path/to/venv/bin/activate && python /path/to/your/app.py

However, the General docker good practice is to run with an unprivileged user. So you have multiple choice here :

*

*Live with the warning, install your python packages globally without venv, drop the privileges and run your container with a normal user

*create venv to get rid of the warning, install your packages in it, run you container as root (not a good practice, but maybe remapping root user can be ok)

*create a venv, install the packages, run the container as a normal user, which is probably the best option if your application doesn't need to be run as root in your container.

A: It's not the best practice to run pip as a root user or to install packages globally. The best practice is to create virtual environment within the project and install every packages there.
If you install globally, it will actually affect other projects because you might not need the packages you installed for project A in the project B that you are about to start and if you remove all the packages, there will be a break in project A as it cannot access the packages again.
Have virtual environment for all your projects and with that, you will be rest assured that all projects will not affect each other.


text:
Q: Invoke VmWare PowerCLI from C# Is there a way to execute the PowerCLI cmdlets from within C#? Basically we have a workflow written using Windows Workflow. At certain stages in the execution of this workflow we need to interact with certain virtual machines and turn them on/off or toggle the persistent mode of the disks etc.
While we can use the .NET toolkit and achieve what we need, it makes sense to explore the possibility of achieving this via PowerCLI cmdlets because pretty much all that we need to do can be very easily done via PowerCLI cmdlets.

A: PowerCLI is a PowerShell-based wrapper for the VIX API.
If you want to develop a script in pure PowerShell Syntax because it makes life easier for you, you should launch a PowerShell process and just run the PowerCLI code.
If you want to automate VMware tasks through C#, you should look up the vSphere API. It has bindings for the dot.net framework.


text:
Q: How to convert my date and time into a datetime object? If I have a date, say 11/05/2011, and a time, 5:30PM, is there an easy way to convert this to a datetime object to put in a datetime database column? Or should I store it completely differently?

A: > rails g model A a:datetime
  invoke  active_record
  create    db/migrate/20111112023850_create_as.rb
  create    app/models/a.rb
  invoke    test_unit
  create      test/unit/a_test.rb
  create      test/fixtures/as.yml

> rake db:migrate
==  CreateAs: migrating =======================================================
-- create_table(:as)
   -> 0.0011s
==  CreateAs: migrated (0.0012s) ==============================================

> rails c
Loading development environment (Rails 3.1.0)
ruby-1.8.7-p299 :001 > rec = A.new
 => #<A id: nil, a: nil, created_at: nil, updated_at: nil>
ruby-1.8.7-p299 :002 > a = "11/05/2011"
 => "11/05/2011"
ruby-1.8.7-p299 :003 > b = "5:30PM"
 => "5:30PM"
ruby-1.8.7-p299 :012 > rec.a = DateTime.parse( "#{a} #{b}" )
 => Sat, 05 Nov 2011 17:30:00 +0000

ruby-1.8.7-p299 :013 > rec.save
  SQL (32.2ms)  INSERT INTO "as" ("a", "created_at", "updated_at") VALUES (?, ?, ?)  [["a", Sat, 05 Nov 2011 17:30:00 UTC +00:00], ["created_at", Sat, 12 Nov 2011 02:43:05 UTC +00:00], ["updated_at", Sat, 12 Nov 2011 02:43:05 UTC +00:00]]
 => true

note: the date was parsed as UTC without a timezone offset

A: Something like this would work.
datetime = DateTime.new(2011,11,05,17,30);
datetime.to_s(:db)

I don't know exactly if you meant the date and time were two separate strings


text:
Q: jQuery insertBefore, Apend for dynamically created elements Please take a look at code, it is working, it should add just one p tag, but for some reason it is inserting several p tags. P tags are not dynamically created, but some of the content in the p tag is created dynamically(just for info, if it is important).
 jQuery("div.content").on("click", ".add", function (e) {

        var ptag = jQuery('p.test-me');
        ptag.insertBefore('.main-content');

        return false;
    });

I would just like to insert one p tag(not several) on click before other p tag with class .main-content.
Thank you in advance.

A: You can try this:
var ptag = jQuery('p.test-me').eq(0);
ptag.insertBefore('.main-content');

A: In your code as you are referring p elements with class name .test-me there might be possibility of retrieving multiple elements if you have p more than one p elements with that class name. As you said it is appending multiple p elements, it is confirmed that there are multiple elements with the class name .test-me. If you do not want more than one element to be appended, and very sure about what element to be append just use id instead of class name, else just get first element of element list.
    // with id

    var ptag = jQuery('#id-of-p').clone().attr('id','');

    //  with className but first element

    var ptag = jQuery('.test-me').first(); or .eq(0);

    // with id, but should have .test-me class name, then only append?

    var ptag = jQuery('#id-of-p.test-me').clone().attr('id','');


text:
Q: %timeit and re-assignment of variable Surprising ipython magic %timeit error:
In[1]: a = 2

In[2]: %timeit a = 2 * a

Traceback (most recent call last):
  File "...\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-97-6f70919654d1>", line 1, in <module>
    get_ipython().run_line_magic('timeit', 'a = 2 * a')
  File "...\site-packages\IPython\core\interactiveshell.py", line 2314, in run_line_magic
    result = fn(*args, **kwargs)
  File "<...\site-packages\decorator.py:decorator-gen-61>", line 2, in timeit
  File "...\site-packages\IPython\core\magic.py", line 187, in <lambda>
    call = lambda f, *a, **k: f(*a, **k)
  File "...\site-packages\IPython\core\magics\execution.py", line 1158, in timeit
    time_number = timer.timeit(number)
  File "...\site-packages\IPython\core\magics\execution.py", line 169, in timeit
    timing = self.inner(it, self.timer)
  File "<magic-timeit>", line 1, in inner
UnboundLocalError: local variable 'a' referenced before assignment

So %timeit doesn't like self re-assignment. Why? Anyway to overcome this?

A: As with the underlying timeit module, the timed statement is integrated into a generated function that performs the timing. The assignment to a causes the function to have an a local variable, hiding the global. It's the same issue as if you had done
a = 2

def f():
    a = 2 * a

f()

although the generated function has more code than that.

A: The cell timeit with initialization works:
In [142]: %%timeit a=2
     ...: a = 2*a
     ...:
     ...:
2.68 µs ± 66.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

A: You could use some %% magic instead to avoid the assignment error:
%%timeit
a = 2
a = a*2


text:
Q: Bash or python scripting of iperf for different ip addresses How can I achieve the following using python or bash?

*

*iperf -s -B 234.5.6.7 -u -f m -i 1

*

*let the above command run for 5 seconds

*kill the above process (e.g. killall iperf)

*iperf -s -B 234.5.6.8 -u -f m -i 1

*

*let the above command run for 5 seconds

*kill the above process (eg killall iperf)

*and so on...

A: $! in bash will give you the pid of the last background process. So you could do something quick and dirty like this in bash
#!/bin/bash

iperf -s -B 234.5.6.7 -u -f m -I 1 &
FOO = $!
sleep 5
kill $FOO
iperf -s -B 234.5.6.8 -u -f m -I 1 &
FOO = $!
sleep 5
kill $FOO

Lather rinse repeat...
We can then refactor this to a for loop
#!/bin/bash

for IP in 234.5.6.7 234.5.6.8
do
  iperf -s -B $IP -u -f m -I 1 &
  FOO = $!
  sleep 5
  kill $FOO
done


text:
Q: rewrite rule wordpress not working This quetsion has been ask al lot, but however I tried I get always a 404 page in WP
I have a templatepage (wp-content/themes/responsivewizzard.php cals: wizzard. ->
I Added a page in the admin sector. The name of the page = "tespage". The template I choose is "wizzard"
When in try example.com/wp/testpage -> I get my wizzard page. No worries.. but..
I like to add a subpage to my wizzardpage. For example:
example.com/wp/testpage/nice
When i try this I get a 404 page from WP
I added this code to my function.php file. This file is in wp-content/themes/responsive directory -> my default theme
function members_rewrite_rules()
{
  add_rewrite_rule('testpage /(.+)/?$', 'index.php?pagename=testpage &subpage=$matches[1]', 'top');
}
add_action( 'init', 'members_rewrite_rules' );

function members_query_vars($query_vars)
{
  $query_vars[] = 'subpage';
  return $query_vars;
}
add_filter('query_vars', 'members_query_vars');

Please help me

A: I found out the soulution. You need to reset the permalinks in the setting menu..


text:
Q: Securing a AJAX->PHP web service call I'm trying to figure a method of securing a web service call with AJAX. The web service processes a contact form and calls the PHP which uses the mail function to send an email without a HTTP request.
I've posted some of my code below so you get a better idea of what I'm asking. I'm attempting to block a direct call to the service through a HTTP request causing my mail server to work everytime the page is requested.
// Data is compiled into datastr...
var datastr =
'input_name=' + encodeURI(input_name) +
'&input_email=' + encodeURI(input_email) +
'&input_organization=' + encodeURI(input_organization) +
'&input_title=' + encodeURI(input_title) +
'&input_phone=' + encodeURI(input_phone) +
'&input_comments=' + encodeURI(input_comments);

 // AJAX is called with datastr param...
 $.ajax({
     type: "POST",
     url: "../common/contact-form-logic.php",
     data: datastr,
     cache: false,
     success: function(resp) {.... etc

Here's the PHP file service.
$input_name = urldecode($_REQUEST['input_name']);
$input_email = urldecode($_REQUEST['input_email']);
$input_organization = urldecode($_REQUEST['input_organization']);
$input_title = urldecode($_REQUEST['input_title']);
$input_phone = urldecode($_REQUEST['input_phone']);
$input_comments = urldecode($_REQUEST['input_comments']);

$to = "xxxxxxxxxxxxxxxxx";

$subject = "Contact form entry from xxxxxxxxxx.com";
$message = $input_name."\n".$input_email."\n".$input_organization."\n".$input_title."\n".$input_phone."\n".$input_comments;

if(mail($to, $subject,$message)){
    echo "1";
}

A: I'm teaching myself security and found myself in a similar situation, here's what I did:
*Disclaimer I'm no security pro but I felt this was better than nothing..

*

*Make sure there's a post

*Check for the xmlhttprequest header

*I then validated the HTTP_REFERER

*I then checked the token I generated a part of their session (example below)
session_start();
$token = md5(uniqid(rand(), TRUE));
$_SESSION['token'] = $token;

if (isset($_SESSION['token']) && $_POST['token'] == $_SESSION['token'])
{
    /* Valid Token */
}

*I checked the $_POST keys against a whitelist to make sure I had everything I needed
Here's an example
// No post no dice!
if( empty($_POST) )
    die('error no post');

// Check for xmlhttprequest header
// I want to make sure this post came from an ajax call.
if( empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')
    die('error invalid ajax request');

// Check to make sure the ajax request came from yourdomainhere.com
if( strpos($_SERVER['HTTP_REFERER'], 'yourdomainhere') === FALSE )
    die('error invalid http ref');

// DIE, if no token is present or token isn't equal to $_SESSION token.
if (!isset($_POST['token']) || $_POST['token'] != $_SESSION['token'])
    die('error invalid token');

// Check to make sure all POST array keys I need exist for my script
$vars_needed = array("input_name", "input_email", "input_organization", "input_title", "input_phone", "input_comments");
foreach($vars_needed as $need) {
    if(!array_key_exists($need, $_POST))
        die('error invalid post');
}

A: What are you trying to secure?  The contents of the message or access to the mail functionality?
For the former, you'll need to use HTTPS.


text:
Q: Getting a cell value from a column based on cell value from another column I have this dataframe
d = {'Number': [1, 2,3,4,5,6,7], 'Letters': ["a", "d","z","f","u","p","g"]}
df = pd.DataFrame(data=d)

    Number Letters
0       1       a
1       2       d
2       3       z
3       4       f
4       5       u
5       6       p
6       7       g

And i want to get a value from Letters column based on the Number column
Lets say i want to get the letter where the number is 3
What I did was
letter = df.loc[df['Number'] == 3]
dfletter = pd.DataFrame(data=letter.values, columns = ['Number', 'Letter'])
dfletter = dfletter.drop(columns = 'Number')

which gives me what i want
    Letter
0      z

But this seems like a dumb workaround, so I am looking for a better solution

A: output = df.loc[df['Number'] == 3, 'Letters']

A: >>> df[df.Number == 3].Letters
2    z
Name: Letters, dtype: object

Or, if you really need a scalar value:
>>> df[df.Number == 3].Letters.values[0]
'z'


text:
Q: mysqli: Returning the same connection when calling constructor twice like $new_link=false; I'm using mysqli to create a connection to the database, using the OOP approach. Is there a way to make it behave like mysql_connect which got a $new_link=false, making it return the same connection for everyone in this script even if they created a new instance?
This is an example of how I'm connecting:
     class DB extends mysqli {

                public function __construct() {
                    $server_params =    $this->server_params;
                    if (!$server_params) {
                        throw Exception('No server params for server: '.$server);
                    }
                    @parent::__construct($server_params['host'], $server_params['user'], $server_params['pass'], $server_params['db'], $port, $socket);
                    if ($this->connect_errno != 0){
                        throw new Exception($this->connect_error, $this->connect_errno);
                    }
              }
     }

And making two instance is just calling
$db = new DB;

Twice from different namespaces in the same script.
I'm aware I can create a singelton and/or use dependency injection, but was wondering if this can be done in the connection request directly.

A: It's normally not a good idea to have two different objects embody the same SQL database connection.  If you start a transaction in one instance what happens if you commit in the other?  If they represent different sessions on the same database that's fine, because sessions are isolated from each other (each session can start its own transaction without risking the other session getting into a nonsensical state).  In that case you'd just create new instances for each connection you want open.
$db1 = new mysqli("example.com", "user", "password", "database");
$db2 = new mysqli("example.com", "user", "password", "database");

If you need multiple references to the same connection and session, then all you need to do is this:
$db1 = new mysqli("example.com", "user", "password", "database");
$db2 = $db1;

Both $db1 and $db2 will refer to the same object and therefore the same connection.

A: From (http://php.net/manual/en/mysqli.construct.php)

Prepending host by p: opens a persistent connection. mysqli_change_user() is automatically called on connections opened from the connection pool.

A:
I was wondering if this can be done in the connection request directly.

Nope, that's impossible.
I see not a much problem with it though.


text:
Q: Question about conditionals I want to know if the following sentences are correct or not.

If you went to the party tomorrow, would you go with me?
If you went to the party yesterday, why didn't you go with me?
If you go to the party tomorrow, will you go with me?

Here's what I think the sentences mean:
The first one: "If you had the possibility to go to the party tomorrow, would you go with me?"
       Or maybe

"If you were to go to the party tomorrow, would you be willing to go with me?"
The second one: "If you did go to the party yesterday, why didn't you go with me?"
         Or maybe

"If you were at the party yesterday, why didn't we go together?"
The third one: "If you for any chance go to the party tomorrow, will you be willing to go with me?"
            Or maybe

"If you are going to the party tomorrow, would you like to go with me?"
I hope I got them right, please comment and let me know if I'm correct or not.

A: The first sentence is incorrect.  "If you went to the party tomorrow, would you go with me?"  The problem is that the sentence uses past tense, to refer to an event in the future.  The sentence could be corrected by bringing "went to" from past tense, to future tense, with "were to go".  Now it would read, "If you were to go to the party tomorrow, would you go with me?"
The second and third sentences are in correct form.


text:
Q: Create a range from multiple cells I want to create a range from multiple cells. Something like this:
I would like to have the following 4 cells:

*

*Cells(4, 7)

*Cells(4, 8)

*Cells(8, 7)

*Cells(8, 8)
to be extracted from a file and then saved to another file as its first row.
I wrote something like this:
With mybook.Worksheets(5)
    Set sourceRange = .Range(Cells(4, 7), Cells(4, 8),
                             Cells(8, 7), Cells(8, 8))
End With

The problem I face is that only the Cells (4,7) and Cells (4,8) appear in the summary sheet.
Can anyone help me out please?

A: Very rudimentary approach.
Sub Transfer4Cells()
    Dim sSht As Worksheet, tSht As Worksheet
    Dim sRng As Range, tRng As Range
    Dim Rng As Range
    Set sSht = ThisWorkbook.Sheets("Sheet1") 'Change as needed.
    Set tSht = ThisWorkbook.Sheets("Sheet2") 'Change as needed.
    Set sRng = sSht.Range("G4,H4,G8,H8") 'You can add more cells here.
    Pos = 1
    For Each Rng In sRng
        tSht.Cells(1, Pos).Value = Rng.Value
        Pos = Pos + 1
    Next Rng
End Sub

While not the perfect solution, the approach is very flexible if you only need it to extract only those 4 cells, or maybe even more.
Hope this helps.


text:
Q: how can i call a method of another class when one delegate is triggerred? i have a mainViewController class and a wifi connection class in my project.
Main view controller class will initialize the wifi connection class(all network delegates and events).there is a delegate in wifi connection class which will work when a stream is came to our device.i need to call a mainViewController method named as "welcomeMessage" when my wifi class delegate is triggered.
can any one help me to do it or provide me some good way to do it...


text:
Q: C++ GetDC All Monitors Basically, I'm making something that imitates a screen melting effect, but I can only get it working on my primary monitor. I've looked up as much as I could and there was only one forum on GetDC for all monitors but it was to no use, all it done was make a rectangle from my primary monitor to my secondary monitor with the effect still only working on my primary monitor. This is the thread I read: GetDC(NULL) gets primary monitor or virtual screen?
LRESULT CALLBACK Melter(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) {
    switch (Message) {
        case WM_CREATE: {
            HDC Desktop = GetDC(HWND_DESKTOP);
            HDC Window = GetDC(hWnd);

            BitBlt(Window, 0, 0, ScreenWidth, ScreenHeight, Desktop, 0, 0, SRCCOPY);
            ReleaseDC(hWnd, Window);
            ReleaseDC(HWND_DESKTOP, Desktop);

            SetTimer(hWnd, 0, Interval, 0);
            ShowWindow(hWnd, SW_SHOW);

            break;
        }
        case WM_PAINT: {
            ValidateRect(hWnd, 0);
            break;
        }
        case WM_TIMER: {
            HDC Window = GetDC(hWnd);
            int uX = (rand() % ScreenWidth) - (150 / 2), uY = (rand() % 15), Width = (rand() % 150);

            BitBlt(Window, uX, uY, Width, ScreenHeight, Window, uX, 0, SRCCOPY);
            ReleaseDC(hWnd, Window);

            break;
        }
        case WM_DESTROY: {
            KillTimer(hWnd, 0);
            PostQuitMessage(EXIT_SUCCESS);
            break;
        }
        return EXIT_SUCCESS;
    }

    return DefWindowProc(hWnd, Message, wParam, lParam);
}

The line I changed was HDC Window = GetDC(Window) to HDC Window = GetDC(NULL) and then some other stuff like the RECT. It'd be great if someone could help me, thanks :)
PS, ScreenWidth = 3600, ScreenHeight = 1080 whilst PMScreenWidth = 1920, PMScreenHeight = 1080. PM as in Primary Monitor, so I've got all the stuff in that function set to ScreenWidth/ScreenHeight so it's the width/height of all monitors. Still doesn't work though.

A: GetDC(HWND_DESKTOP) (same as GetDC(0)) already returns the DC for all monitors. The problem with above code is mainly with the usage of BitBlt and choosing the coordinates. See the MCVE below that addresses the question.
Don't draw in response to WM_CREATE, it's just going to get erased in WM_PAINT or when background is erased.
Don't call ValidateRect in response to WM_PAINT. If you want to erase the window then just use FillRect, or force repaint from a command or another route.
Use GetSystemMetrics(SM_CXVIRTUALSCREEN) and GetSystemMetrics(SM_CYVIRTUALSCREEN) to return width and height for the virtual monitor.
Also be sure the process is DPI aware. For testing you can call SetProcessDPIAware(); at the start of the program. Ideally DPI awareness should be set in manifest file.

int uX = (rand() % ScreenWidth) - (150 / 2);
int uY = (rand() % 15);
int Width = (rand() % 150);
BitBlt(Window, uX, uY, Width, ScreenHeight, Window, uX, 0, SRCCOPY);

Above code is copying bits from client DC the the same client DC, it's not going to do anything. Presumably you want to copy from desktop DC to client DC.
Moreover, the coordinates are basically picked at random. It assumes the primary monitor is on top-left. If uX is greater than window's own width, it will not get copied, unless the window stretches the whole virtual monitor.
LRESULT CALLBACK Melter(HWND hWnd, UINT Message, WPARAM wParam, LPARAM lParam) {

    switch(Message)
    {
    case WM_PAINT:
    {
        PAINTSTRUCT ps;
        auto hdc = BeginPaint(hWnd, &ps);
        RECT rc;
        GetClientRect(hWnd, &rc);

        HDC hdesktop = GetDC(0);

        int screenx = GetSystemMetrics(SM_XVIRTUALSCREEN);
        int screeny = GetSystemMetrics(SM_YVIRTUALSCREEN);
        int screenw = GetSystemMetrics(SM_CXVIRTUALSCREEN);
        int screenh = GetSystemMetrics(SM_CYVIRTUALSCREEN);

        StretchBlt(hdc, 0, 0, rc.right, rc.bottom,
            hdesktop, screenx, screeny, screenw, screenh, SRCCOPY);

        ReleaseDC(0, hdesktop);

        EndPaint(hWnd, &ps);
        break;
    }

    case WM_DESTROY:
        PostQuitMessage(0);
        break;
    }

    return DefWindowProc(hWnd, Message, wParam, lParam);
}

A: You can use
HDC dc = CreateDC(("DISPLAY"), NULL, NULL, NULL);

Check below links:

*

*Using Multiple Monitors as Independent Displays

*CreateDCA function

*Multiple Display Monitors Functions


text:
Q: Return from redirect How can i redirect user in filter to another action and remember action which he wanted to do before redirect and repeat it after he do any action on that redirected page?

A: In the filter:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var dictionary = new RouteValueDictionary();
    dictionary["action"] = "newaction";
    dictionary["controller"] = "home";
    dictionary["returnUrl"] = filterContext.RequestContext.HttpContext.Request.Url.AbsoluteUri;
    filterContext.Result = new RedirectToRouteResult(dictionary);
}

And then use the returnUrl parameter in the new action.


text:
Q: Why can't I destroy blocks or hit people in multiplayer and in single player on diamond dimensions? I am on Diamond Dimensions and I can right click a door or chest to open it, but I can destroy any blocks. I have tried everything, including re-downloading Technic launcher, but I still can't destroy blocks. I was on my friends world so I went to my world and it still didn't work. I made sure my control was on button 1 for attack, I made sure I was on survival mode and not adventure mode, and even tried dying to see if it works. It didn't. I can't even hit someone!! When a monster came near me I couldn't even hit him, I had to run away!! What else can I do?

A: It's just your game lagging, so if you wait a while you will see that the actions you have attempted to make will happen, but if you for example: break a block and it reappears, then you break a different block, only the first block will be broken. The only recommendation I have to fix this lag spike is to get rid of big mods, and get rid of mods you don't want. Doing either of these reduces the strain you're putting on your computer and reduces the lag.


text:
Q: Regular expression matching c# without some tags I want to match exact and prefix wildcard match but there's one condition that It should not be surrounded by a particular tag.
For example: if the word to match is test, the regular expression should match
test, testing,tester ,testing.aspx but it should not match test</x> and testing</x>, tester</x> and other words with prefix test
I came up with a regex which is matching test</x> too.
string regex = string.Format("\\b{0}(\\S)*(?!</x>)", "test");

Can somebody help me in correcting my regex?

A: The \btest(\S)*(?!</x>) pattern matches test</x> because \btest finds a word starting with test, then matches and repeatedly captures any 0+ non-whitespace chars, and then checks if there is no </x> immediately to the right of the current location. Since (\S)* matches the whole </x> at once the negative lookahead checks for </x> when the regex index is already placed after this </x> - and thus it returns true and the match is a success.
Yo may use
string regex = string.Format(@"(?>\b{0}[^<\s]*)(?!</x>)", "test");
// or, beginning with C#6
// var regex = $@"(?>\b{SearchWord}[^<\s]*)(?!</x>)";

See the regex demo
Now, it will match like this:

*

*(?>\btest[^<\s]*) - an atomic group matching

*

*\b - a word boundary

*test - search term

*[^<\s]* - 0+ chars other than < and whitespace

*(?!</x>) - a negative lookahead that fails the match if there is a </x> char sequence immediately to the right of the current location


text:
Q: Deleting multiple files from git Other than individually deleting each file (i.e. git rm src/classes/Config.php, git rm src/public/ajax.php, etc, etc), how can all these files be deleted from git?
[Michael@devserver main]$ git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
# Changed but not updated:
#   (use "git add/rm <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#       deleted:    src/classes/Config.php
#       deleted:    src/public/ajax.php
#       deleted:    src/public/fileuploader.php
#       deleted:    src/public/index2.php
#       deleted:    src/public/json_encode.php
#       deleted:    src/public/petstore.json
#       deleted:    src/public/resources/index.php
#       deleted:    src/public/slimttest.php
#       deleted:    src/public/temp.php
#       deleted:    src/public/test.php
#       deleted:    src/public/test/bla.php
#       deleted:    src/public/test/file1.php
#       deleted:    src/public/test/file2.php
#       deleted:    src/public/test2.php
#       deleted:    src/public/testAPI.php
#       deleted:    src/public/testAPI2.php
#       deleted:    src/public/test_original.php
#       deleted:    src/public/testfile.php
#       deleted:    temporary.txt
#
no changes added to commit (use "git add" and/or "git commit -a")
[Michael@devserver main]$

A: You're looking for git add -u (or --update). From man git add:

This removes as well as modifies index entries to match
  the working tree, but adds no new files.

A: You can use git add --update or git add -u in short to stage all changes that are displayed in the "Changed but not updated" section in git status.
Using this option on git add will not stage untracked files, so it's safe to use even when you have lots of other changes (unlike git add -A).
This is especially helpful for situations like yours where you have lots of removed files. If you have some changes you do not want to stage, you can afterwards use git reset <path> to unstage the change (without undoing that change of course).


text:
Q: Macro to copy chart Excel-Word changes chart appearance I copy-paste charts from Excel (2010) as images in Word. The copy-paste works but the final chart in Word is different than the original and what I copy-paste manually (Paste special - Picture).
I have tried to change the DataType in the Paste and the Format in the copy but the result is always the same. Any other option?
Sub ChartsToWord()

Dim WDApp As Word.Application
Dim WDDoc As Word.Document
Dim iCht As Integer
Dim Msg As String

Set WDApp = CreateObject("Word.Application")
Set WDDoc = WDApp.Documents.Add

For iCht = 1 To ActiveSheet.ChartObjects.Count
   ' copy chart as a picture
    ActiveSheet.ChartObjects(iCht).Chart.CopyPicture _
    Appearance:=xlScreen, Size:=xlScreen, Format:=xlBitmap

    WDApp.Selection.Range.PasteSpecial Link:=False, DataType:=wdPasteEnhancedMetafile, _
    Placement:=wdInLine, DisplayAsIcon:=False

   WDApp.Selection.MoveEnd wdStory
   WDApp.Selection.Move
Next
WDDoc.SaveAs ("C:\Temp\charts.docx")
WDDoc.Close ' close the document

' Clean up
Set WDDoc = Nothing
Set WDApp = Nothing

End Sub

A: Try copying the ChartObject with the Copy Method
ActiveSheet.ChartObjects(iCht).Copy

And try pasting as a Bitmap or PNG:
WDApp.Selection.Range.PasteSpecial Link:=False, DataType:=wdPasteBitmap, _
Placement:=wdInLine, DisplayAsIcon:=False

WDApp.Selection.range.PasteSpecial Link:=False, DataType:=14, Placement:=wdInLine, _
DisplayAsIcon:=False


text:
Q: ByteCode manipulation with ASM on .NET & C# After using ASM on Java language, is there a faint way to use our byteCode manipulation module (insert some custom code) on .NET and C # platforms, through some sort of workaround? Anyway, we would choose Mono.Cecil, but we really fell in love with ASM. The obvious answer is no - for sure, but maybe there is some exciting solution?
All your answers are highly appreciated


text:
Q: Switch CSS class everytime user clicks - Jquery I have 2 links with different CSS classes.
How can I switch between the two everytime a the user clicks?
Class1
Class2

It's just work one time, but when I click a second time, it doesn't work:
$("#class1").click(function(){
    $("#class1").removeClass().addClass("class2");
    $("#class2").removeClass().addClass("class1");
})

$("#class2").click(function(){
    $("#class1").removeClass().addClass("class2");
    $("#class2").removeClass().addClass("class1");
})

The CSS is to change the color

A: You can use toggleClass to switch multiple classes..

$('.red,.blue').click(function() {
  $(this).toggleClass('red blue');
});
.red { background-color:red }
.blue { background-color:blue }

One

Blue

A: The methods are doing the same thing. You set the same class to each tag in both thats why it only works the first time. The second time it just resetting the current class.
Shouldn't they be like this instead?
$("#class1").click(function(){
    $("#class1").removeClass().addClass("class2");
    $("#class2").removeClass().addClass("class1");
})

$("#class2").click(function(){
    $("#class1").removeClass().addClass("class1");
    $("#class2").removeClass().addClass("class2");
})

A: You can use selector "[class^=class]" to select elements where Element.className begins with "class"; use .slice() with parameters 0, -1 to select characters in string up to last character; check if last character is 1 or 2 using == equal operator; set the opposite last character for matches 1: "2", 2: "1" at last character of Element.className

$("[class^=class]").click(function() {
  var c = this.className;
  this.className = c.slice(0, -1) + (c[c.length - 1] == 1 ? 2 : 1);
});
.class1 {
  color: blue;
}

.class2 {
  color: green;
}

Class1
 Class2

A: Done using toggleClass JSFIDDLE:https://jsfiddle.net/kameeshwaran/5puecqeq/
HTML:
Class1
Class2

JS
 $(document).ready(function(){
    $(".class1").click(function(e){
      e.preventDefault();
        $(this).toggleClass("class2")
    });
 });

CSS:
.class1{
  background-color:green;
}
.class2{
  background-color:red;
}

A: When you click class1 once, it removes the class class1 from class1, and puts class2 on.
However, when you click it again, because class1 is set to the class class2, it won't change.
You should probably do something like this:
var class1check = 0;
$("#class1").click(function() {
    if (class1check === 0) {
        var addclass1 = "class2";
        var addclass2 = "class1";
    }
    else {
        var addclass1 = "class1";
        var addclass2 = "class2";
        class1check = 0;
    }
    $("#class1").removeClass().addClass(addclass1);
    $("#class2").removeClass().addClass(addclass2);
});


text:
Q: How to use YouTube Analytics API in Android I need to get some statistics about a certain youtube channel searched by user, and YouTube Data API doesn't provide me enough data. So how can I use YouTube Analytics API to get more data abou an youtube channel?
I can't use their lib:
compile 'com.google.apis:google-api-services-youtubeAnalytics:v1-rev73-1.22.0'
because it gives me error, and I don't want to enable multidex:

Error:Execution failed for task
  ':app:transformClassesWithDexForDebug'.
  com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException:
  java.util.concurrent.ExecutionException:
  com.android.dex.DexIndexOverflowException: method ID not in [0,
  0xffff]: 65536

all my dependences are:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.0.1'
compile 'com.android.support:design:25.0.1'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.3.+'
compile 'io.reactivex:rxandroid:1.0.1'
compile 'com.google.android.gms:play-services-ads:10.0.1'
compile "com.google.android.gms:play-services-gcm:10.0.1"
compile ('com.google.apis:google-api-services-youtubeAnalytics:v1-rev73-1.22.0'){
        exclude module: 'httpclient' //by artifact name
        exclude group: 'org.apache.httpcomponents' //by group
        exclude group: 'org.apache.httpcomponents', module: 'httpclient' //by both name and group
    }}

A: Check this documentation for the different types of reports you can retrieve using the API. Most of the workarounds I have read is to add multiDexEnabled true to your app build.gradle file.

*

*com.android.build.transform.api.TransformException

*Android Studio TransformException : Error:Execution failed for task ':app:transformClassesWithDexForDebug'
Since you don't want to enable it, I can suggest to remove unused code with ProGuard. You should enable code shrinking to run ProGuard for your release builds. Enabling shrinking ensures you are not shipping unused code with your APKs.
You can refer with this another SO answer on how to get both statistics and snippet printed to the console with single api call.


text:
Q: Verify the receipt using curl, but the response is null I verify the receipt using curl, but the response is null. I write the code according this blog. How to fix it?
<?php

$receipt="<7b0a0922 7369676e 61747572 6522203d 20224167 42423765 756e316d 79366745 64755561 4d7a4841 53664363 33315874 6c674439 52316b6d 4c454d35 54436654 67513578 6e576a57 2b395636 2f634141 2f454b37 66624956 524f6454 54613736 6a332f72 544b364d 632f4f74 464b6b43 71615543 5046385a 38334349 47554274 6e564c37 4b4b3679 47494d6b 59705158 46727948 42473346 762b584f 36614747 76396178 794a4359 716b312f 56737047 36586b44 68786a59 7359445a 717a4141 4144567a 43434131 4d776767 49376f41 4d434151 49434347 55556b55 335a5741 53314d41 30474353 71475349 62334451 45424251 55414d48 3878437a 414a4267 4e564241 5954416c 56544d52 4d774551 59445651 514b4441 70426348 42735a53 424a626d 4d754d53 59774a41 59445651 514c4442 31426348 42735a53 42445a58 4a306157 5a705932 46306157 39754945 46316447 6876636d 6c306554 457a4d44 45474131 55454177 77715158 42776247 55676156 5231626d 567a4946 4e306233 4a6c4945 4e6c636e 52705a6d 6c6a5958 52706232 34675158 56306147 39796158 52354d42 34584454 41354d44 59784e54 49794d44 55314e6c 6f584454 45304d44 59784e44 49794d44 55314e6c 6f775a44 456a4d43 45474131 55454177 77615548 56795932 68686332 56535a57 4e6c6158 42305132 56796447 6c6d6157 4e686447 5578477a 415a4267 4e564241 734d456b 46776347 786c4947 6c556457 356c6379 42546447 39795a54 45544d42 45474131 55454367 774b5158 42776247 55675357 356a4c6a 454c4d41 6b474131 55454268 4d435656 4d77675a 38774451 594a4b6f 5a496876 634e4151 45424251 41446759 30414d49 474a416f 4742414d 72526a46 32637434 49725364 69544368 61493067 38707776 2f636d48 7338702f 5277562f 72742f39 31584b56 684e6c34 58494269 6d4b6a51 514e6667 48734473 36796a75 2b2b4472 4b4a4537 754b7370 684d6464 4b596646 45357247 58734164 42456a42 77524978 65785465 76783348 4c454647 4174316d 6f4b7835 30396468 78746949 6444674a 76325961 56733439 4230754a 764e6479 36534d71 4e4e4c48 73444c7a 4453396f 5a484167 4d424141 476a636a 42774d41 77474131 55644577 45422f77 51434d41 41774877 59445652 306a4242 6777466f 41554e68 336f3470 32433067 45597454 4a724474 64444335 4659517a 6f774467 59445652 30504151 482f4241 51444167 65414d42 30474131 55644467 51574242 53706734 50794755 6a465068 4a584342 544d7a61 4e2b6d56 386b3954 41514267 6f71686b 69473932 4e6b4267 55424241 49464144 414e4267 6b71686b 69473977 30424151 55464141 4f434151 45414561 5362506a 746d4e34 432f4942 33514570 4b333252 78616343 44586456 58416556 52655335 46615a78 632b7438 38705150 39334269 41787664 572f3365 54534d47 59354662 6541594c 33657471 5035676d 38777246 6f6a5830 696b7956 52537451 2b2f4151 304b456a 74714230 376b4c73 39515565 38637a52 38554766 644d3145 756d562f 55677644 64344e77 4e59784c 514d6734 57545166 676b5151 56793847 585a7756 48676245 2f554336 59373035 33704758 426b3531 4e504d33 776f7868 64336753 524c7658 6a2b6c6f 48735374 63544571 65397042 44706d47 352b736b 3474772b 474b3347 4d65454e 352f2b65 31515439 6e702f4b 6c316e6a 2b614277 37433078 73793062 466e6141 64316353 53367864 6f72792f 4355764d 3667744b 736d6e4f 4f647154 65736270 30627338 736e3657 71733043 39646763 78524875 4f4d5a32 746d386e 704c556d 37617267 4f537a51 3d3d223b 0a092270 75726368 6173652d 696e666f 22203d20 2265776f 4a496d39 79615764 70626d46 734c5842 31636d4e 6f59584e 6c4c5752 68644755 7463484e 30496941 39494349 794d4445 794c5445 794c5445 77494441 304f6a45 304f6a4d 32494546 745a584a 70593245 76544739 7a583046 755a3256 735a584d 694f776f 4a496e42 31636d4e 6f59584e 6c4c5752 68644755 7462584d 69494430 67496a45 7a4e5459 7a4f5463 324d7a4d 324d7a49 694f776f 4a496e56 75615846 315a5331 705a4756 7564476c 6d615756 79496941 39494349 774d4441 77596a41 794f5745 344d5467 694f776f 4a496d39 79615764 70626d46 734c5852 79595735 7a59574e 30615739 754c576c 6b496941 39494349 784d4441 774d4441 774d4459 774d5463 314d7a67 7a496a73 4b43534a 6c654842 70636d56 7a4c5752 68644755 69494430 67496a45 7a4e5459 7a4f5463 344d544d 324d7a49 694f776f 4a496e52 79595735 7a59574e 30615739 754c576c 6b496941 39494349 784d4441 774d4441 774d4459 774f5445 774e5463 7a496a73 4b43534a 76636d6c 6e615735 68624331 7764584a 6a614746 7a5a5331 6b595852 6c4c5731 7a496941 39494349 784d7a55 314d5451 784e6a63 324d4441 77496a73 4b43534a 335a5749 7462334a 6b5a5849 7462476c 755a5331 70644756 744c576c 6b496941 39494349 784d4441 774d4441 774d4449 324e446b 334f4451 7a496a73 4b43534a 69646e4a 7a496941 39494349 784c6a41 694f776f 4a496d56 3463476c 795a584d 745a4746 305a5331 6d62334a 74595852 305a5751 7463484e 30496941 39494349 794d4445 794c5445 794c5449 30494445 334f6a45 774f6a45 7a494546 745a584a 70593245 76544739 7a583046 755a3256 735a584d 694f776f 4a496d6c 305a5730 74615751 69494430 67496a55 344e6a45 324d7a4d 774e4349 3743676b 695a5868 7761584a 6c637931 6b595852 6c4c575a 76636d31 68644852 6c5a4349 67505341 694d6a41 784d6930 784d6930 794e5341 774d546f 784d446f 784d7942 4664474d 76523031 55496a73 4b43534a 77636d39 6b64574e 304c576c 6b496941 3949434a 6a623230 75615746 75597935 68634842 7764584a 6a614746 7a5a5335 7a5a585a 6c626d52 6865584d 694f776f 4a496e42 31636d4e 6f59584e 6c4c5752 68644755 69494430 67496a49 774d5449 744d5449 744d6a55 674d4445 364d4463 364d544d 67525852 6a4c3064 4e564349 3743676b 6962334a 705a326c 75595777 74634856 79593268 68633255 745a4746 305a5349 67505341 694d6a41 784d6930 784d6930 784d4341 784d6a6f 784e446f 7a4e6942 4664474d 76523031 55496a73 4b43534a 69615751 69494430 67496d4e 76625335 70595735 6a4c6d46 7763484e 31596e4e 6a636d6c 7764476c 76626e4d 694f776f 4a496e42 31636d4e 6f59584e 6c4c5752 68644755 7463484e 30496941 39494349 794d4445 794c5445 794c5449 30494445 334f6a41 334f6a45 7a494546 745a584a 70593245 76544739 7a583046 755a3256 735a584d 694f776f 4a496e46 31595735 30615852 35496941 39494349 78496a73 4b66513d 3d223b0a 0922656e 7669726f 6e6d656e 7422203d 20225361 6e64626f 78223b0a 0922706f 6422203d 20223130 30223b0a 09227369 676e696e 672d7374 61747573 22203d20 2230223b 0a7d>";
$data= array("receipt-data"=>$receipt,"password"=>"12345678");
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,"https://sandbox.itunes.apple.com/verifyReceipt");
curl_setopt($ch,CURLOPT_POST,1);
//curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);

curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
$response = curl_exec($ch);
$errno    = curl_errno($ch);
$errmsg   = curl_error($ch);
echo "response: ".$response;
echo "
";
//$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
 $result = json_decode($response);
echo "errno: ".$errno;
echo "
";
echo "errmsg: ".$errmsg;
echo "
";
//echo "code:".$httpCode;
echo "result: ".$result;
curl_close($ch);

?>
The result is:
response:
errno: 0
errmsg:
result:

A: I have test your code, it work well, so i think you should check your server environment!


text:
Q: How to get URLs sorted by most Facebook Likes based on my appId? Just as the question says, is there a way to get an array of URLs on my domain sorted by most Facebook Likes? I have a Facebook appId if that helps.
Thanks!

A: You can use FQL, like this:
SELECT url, like_count FROM link_stat WHERE url IN ('http://www.url1.com', 'http://www.url2.com')

You can't get it sorted from facebook, you must do that manually later.
Here are some useful links, hope it helps:
http://sudocode.net/article/368/how-to-get-the-access-token-for-a-facebook-application-in-php/
http://developers.facebook.com/docs/reference/fql/


text:
Q: Random click to div with javascript I have 2 divs with 2 different class:

*

*div class name is: good

*div class name is: bad
I would like to click with javascript (user script) randomly for this divs. I never coded in javascript i just found this code in internet.
I have this code:
function addJQuery(callback) {
  var script = document.createElement("script");
  script.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");
  script.addEventListener('load', function() {
    var script = document.createElement("script");
    script.textContent = "(" + callback.toString() + ")();";
    document.body.appendChild(script);
  }, false);
  document.body.appendChild(script);
}

function main() {
setInterval(function(){
$('div.good').click();
$('div.bad').click();
}, 5000);

}
addJQuery(main);

A: It seems like what you are looking to do is perform an action with one of these two divs. It doesn't really make sense to fake a click, because all that does is run code, which could just as easily be executed in another, far more convenient manner. What do you want to happen when the div is clicked?

A: First, 2 questions:

*

*What are you trying to accomplish? The task you present is rather strange and I can't think of any applications that can't be done another way.

*Is there a reason you are appending jQuery asynchronously?

Nevertheless, the following code will dispatch click events to one of two divs, chosen randomly, 30 seconds after page load.
function main() {
    setTimeout(function() {
        if (Math.random() < 0.5)
            $('div.good').click();
        else
            $('div.bad').click();
    }, 30*1000);
}

A more generic solution would be to write a random choice function, which chooses randomly from a set of N items.
Math.randomChoice = function(collection) {
    return collection[Math.floor(Math.random() * collection.length)];
};

function main() {
    setTimeout(function() {
        var elem = Math.randomChoice(['good', 'bad']);
        $('div.' + elem).click();
    }, 30*1000);
}


text:
Q: Aligning ggplot facets in a patchworked graph I have graph consisting of several ggplots combined using patchwork. I have made a ggplot only consisting of the y-axis. This works fine, but the facets are not aligned above each. Any ideas as how to make the facets have the same size and be above each other?

Here's the patchwork code:
y_axis + decreasers_p+late_bloomers_p + o2_lovers_p + solo_riders_p + plot_layout(widths = c(1, 10),
                                                                        guides = "collect",
                                                                        design =
                                                                        "12
                                                                         13
                                                                         14
                                                                         15")

And here's some of the ggplot code:
solo_riders_p <- ggplot(solo_riders, aes(x=days_incubated, y=emission))+
  geom_point(aes(shape=compound, size=compound, fill=compound)) +
  scale_shape_manual(values=c(21, 25))+
  scale_size_manual(values=c(2.8, 2.5))+
  scale_fill_manual(values=c("black", "grey"))+
  labs(fill = "Compound", shape = "Compound", size = "Compound",
       x = "Incubation time (days)",
       y = "BVOC emission (nmol g-1 loi soil h-1)",
       title = "solo_riders") +
  theme_bw() +
  facet_wrap(vars(jar), scales = "free_y")

y_axis <- ggplot(data.frame(l = decreasers_p$labels$y, x = 1, y = 1)) +
  geom_text(aes(x, y, label = l), angle = 90) +
  theme_void() +
  coord_cartesian(clip = "off")

Here's an example of how I would like it to be (but without the titles above each row):


text:
Q: SignalR doesn't fire client's function I am trying to call from a server to a client and pass a string to the client's function or to add text to a client textbox - nothing works, the code is running but nothing happens (the client connect to the server with no problems) what is the problem ? thanks.
//Server
class Hub:hub
{
        public void sendClientIdToServer()
        {
            Clients.Caller.getFeedBack("hey");
        }
}

//Client
 private async void connectToServer()
        {
            Connection = new HubConnection(LocalClient);
            HubProxy = Connection.CreateHubProxy("ConnectByHub");
            //try to call another function and pass to the function a string.
            HubProxy.On("getFeedBack", (msg) => Invoke((Action)(() => { getFeedBack(msg); })));
            // try to add text to richTextBox
            HubProxy.On<string>("getFeedBack", (msg) => Invoke((Action)(() => { MsgTxtBox.Text = msg;    })));
            try
            {
                await Connection.Start();
            }
            catch (Exception ex)
            {
                Invoke((Action)(() => { connectStat.Text = "Error Not connected"; }));
                return;
            }
            Invoke((Action)(() => { connectStat.Text = "connected ClientA"; }));
        }

  //function

public void getFeedBack(string message){

            string test = message;

        }

A: It simple.
The client's "method" is not defined like a normal method.
Have a look here
Scroll to the bottom. Check out how they defined the Client's method.
Example for WPF client code for a method called from server with a parameter (quoted directly from the link)
stockTickerHubProxy.On<Stock>("UpdateStockPrice", stock =>
    Dispatcher.InvokeAsync(() =>
        {
            textBox.Text += string.Format("Stock update for {0} new price {1}\n", stock.Symbol, stock.Price);
        })
);

Well, if you are using WinForms, the codes will be a bit different but very similar too :)

*edit
try this:
Change
HubProxy.On<string>("getFeedBack", (msg) => Invoke((Action)(() => { MsgTxtBox.Text = msg;    })));

to
HubProxy.On<string>("getFeedBack", (msg) =>
    this.Invoke(new MethodInvoker(delegate
    {
        MsgTxtBox.Text = msg;
    }));
});

A: In your Hub, you write:
HubProxy.On("getFeedBack", (msg) => Invoke((Action)(() => { getFeedBack(msg); })));

"getFeedBack" here is method that Server calls to Client.
You should change in your code:
Server:
class Hub:hub
{
    public void sendClientIdToServer()
    {
        Clients.Client(Context.ConnectionId).getFeedBack("hey");
    }
}

Client:
HubProxy.On("getFeedBack");

You also subscribe from Server:
HubProxy.On<string>("getFeedBack", (msg) =>
this.Invoke(new MethodInvoker(delegate
{
    MsgTxtBox.Text = msg;
}));
});


text:
Q: What is the best book or site to understand how to construct Periodic Table, theoretically? I want to understand how Periodic table is constructed theoretically and mathematically.
But I can't find self-contained book or site about it by myself since I'm a computer science guy and lack of knowledge about chemistry and physics.
What is the best self-contained, concise book or site to understand how to construct the Periodic Table, theoretically?
I looked at some chemistry book, but it introduces many concepts (e.g., s-orbit) without definition and I can't understand the theory.
I don't care about the requirements of mathematics and physics knowledge for reading the book, but I want a self-contained book which includes developing theory and mathematics for the Periodic table (e.g., Schrodinger equation).


text:
Q: extract verbatim p-value from cor.test I ran a correlation analysis between two vectors and I need to plot the -log10(pvalue)...when the correlation runs, I have the following results:
data <- read.table("test-data.txt")
a <- data[,1]
b <- data[,2]
test <- cor.test(a, b)
test

    Pearson's product-moment correlation

data:  a and b
t = 8.3704, df = 10352, p-value < 2.2e-16
alternative hypothesis: true correlation is not equal to 0
95 percent confidence interval:
 0.06282908 0.10109436
sample estimates:
       cor
0.08199194

but when I extract the p-value as test$p.value it comes out as zero..this means that when I calculate the -log10(pv) i get Inf as results...which I cannot plot.
however, -log(2.2e-16, base=10) is 15.65758 which is what I want
so my question is: how would you maintain the exponential number?
also, this is a sample of a series of 81 correlations I'm running that have to be plotted all together, I have this very same problem for 30 out of 81

A: Your p-value is not 2.2e-16, its less than that.  That means its computationally zero.  You can skip the zeros, or set zero to the arbitrarily small 2.2e-16.
ifelse(pv==0,-log(2.2e-16,base=10),-log(pv,base=10))

Of course, 30 out of 81 times you do not know what the p-value is, just that it is very small.


text:
Q: Copy paste on summer-note editor from word doc with bullets and number does not show bullets and number - IE and Mozila When i copy and paste content from word document to even online summer note editor it does not display bullets and numbers in any browser. It is actually outdent content and manually i have to indent it to view bullets.
But it also work in chrome only.
To workaround it, i have added onPaste event on summer-note editor and prevent default paste event, take copied content and in form of html i just paste in summer-note but it only resolved in chrome for other browser it is not working.
IE version : 11.0.9600 (First bullet displayed small)
Firefox version : 59.0.1-32 bit.
Online Summer-note editor link :
https://summernote.org/
Sample code of on paste function which only works on chrome but in IE there is no way to get html content from clipboard:
$scope.pasteData = function(e) {

var ua = window.navigator.userAgent;

var msie = ua.indexOf("MSIE ");
msie = msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./);

var ffox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
var htmlContent;

if(msie){

    if( e.clipboardData ){

        htmlContent = e.clipboardData.getData('text/html');
        document.execCommand('insertHTML', false, htmlContent);
        e.preventDefault();

    }
    else if( window.clipboardData ){

        // In case of IE e.clipboardData.getData('text/html'); is not work

    }

}
else{

    htmlContent = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('text/html');

    document.execCommand('insertHTML', false, htmlContent);

    e.preventDefault();

}
}


text:
Q: Stop at first match in a sqlite query I have a sqlite3 database worth 4GB and 400k rows. The id column is a consecutive number starting at 1. If I query the following
select * from game where id = 1

After printing the first match the query continues until it reach the 400k row, thus taking a few seconds to finish the query.
How do I make the query stop at the first match?
Or how do I go directly to specific row since id and rowcount are the same?

A: Just add a LIMIT 1 to your query:
SELECT * FROM game WHERE id = 1 LIMIT 1;


text:
Q: Code indentation converted from tabs to spaces: is it trackable in git? I'm initially trying to adapt soft tabs in my projects but some testing with a python project tracked by git is showing issues; naturally git thinks everything has changed, and that is not what I'd prefer.
While git diff understands to drop whitespace from comparison with -w switch, there's no such switch for git commit.
Is the transition impossible to do nicely or is there a way to achieve git to ignore the sudden change?

A: Can git automatically switch between spaces and tabs?


text:
Q: One liner to restructure/nest a dictionary I'm wondering if in Python3 there is a one liner that can turn:
in_dict = {
    ("ID1", "TEXT_A"): "TIMESTAMP_X",
    ("ID1", "TEXT_B"): "TIMESTAMP_Y",
    ("ID2", "TEXT_C"): "TIMESTAMP_X",
    ("ID3", "TEXT_E"): "TIMESTAMP_Y",
}

into
out_dict = {
    "ID1": [
        {"TEXT_A": "TIMESTAMP_X"},
        {"TEXT_B": "TIMESTAMP_Y"}
    ],
    "ID2": [{"TEXT_C": "TIMESTAMP_X"}],
    "ID3": [{"TEXT_E": "TIMESTAMP_Y"}],
}

I know I can easily do this in a for loop but I was wondering if there is a super fancy way.

A: One way of doing this is using groupby if keys of dictionary are in sorted manner as in your case
from itertools import groupby
in_dict = {
    ("ID1", "TEXT_A"): "TIMESTAMP_X",
    ("ID1", "TEXT_B"): "TIMESTAMP_Y",
    ("ID2", "TEXT_C"): "TIMESTAMP_X",
    ("ID3", "TEXT_E"): "TIMESTAMP_Y",
}
print({k : [{y[1]: in_dict[y]} for y in v]  for k,v in groupby(in_dict, key=lambda x: x[0])})
 # output
 {'ID1': [{'TEXT_A': 'TIMESTAMP_X'}, {'TEXT_B': 'TIMESTAMP_Y'}],
 'ID2': [{'TEXT_C': 'TIMESTAMP_X'}],
 'ID3': [{'TEXT_E': 'TIMESTAMP_Y'}]}

A: This way,
{ uniq_k : [ {k[1] : v } for k, v in in_dict.items() if uniq_k in k ] for uniq_k in {k[0] for k in in_dict} }

A: For abusing Python, functools.reduce() is often more helpful than mere loops.
Like when mentioning a for loop, you may mean something like
out_dict={}
for k in in_dict:
  if k[0] not in out_dict:
    out_dict[k[0]]=[]
  out_dict[k[0]].append({k[1]:in_dict[k]})

which could be rewritten as
from functools import reduce
def rf(acc,k):
  if k[0] not in acc:
    acc[k[0]]=[]
  acc[k[0]].append({k[1]:in_dict[k]})
  return acc
out_dict=reduce(rf,in_dict,{})

and then rf() can be tricked into a lambda:
from functools import reduce
out_dict=reduce(lambda acc,k:[acc.update({k[0]:[]}) if k[0] not in acc else None,acc[k[0]].append({k[1]:in_dict[k]}),acc][2],in_dict,{})

while the else None is particularly repelling, replacing it with something meaningful actually makes the thing longer, even after swapping order to get rid of the not:
out_dict=reduce(lambda acc,k:[acc[k[0]].append({k[1]:in_dict[k]}) if k[0] in acc else acc.update({k[0]:[{k[1]:in_dict[k]}]}),acc][1],in_dict,{})