text:
Q: Java string intern and literal Are the below two pieces of code the same?
String foo = "foo";
String foo = new String("foo").intern();

A: public String intern()

It follows that for any two strings s
  and t, s.intern() == t.intern() is
  true if and only if s.equals(t) is
  true.

So I believe the answer is yes, although the second method will have to search through the pool.
EDIT
As sugegsted by T.J. Crowder

When the intern method is invoked, if
  the pool already contains a string
  equal to this String object as
  determined by the equals(Object)
  method, then the string from the pool
  is returned. Otherwise, this String
  object is added to the pool and a
  reference to this String object is
  returned.
All literal strings and string-valued
  constant expressions are interned.

A: The first one i.e.
    String foo = "foo";

in this line, we are creating a String using String literals. That means the string is automatically saved in String Constant pool.
In the 2nd one , i.e. -
    String foo = new String("foo").intern();

Here we are creating a String using new String() & then manually saving it to the String constant pool. If we didn't have mentiones intern() , it would not have saved in the String constant pool.
For more clarification, please refer to this link -
http://javacodingtutorial.blogspot.com/2013/12/comparing-string-objects-intern-other.html

A: They have the same end result, but they are not the same (they'll produce different bytecode; the new String("foo").intern() version actually goes through those steps, producing a new string object, then interning it).
Two relevant quotes from String#intern:

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
All literal strings and string-valued constant expressions are interned.

So the end result is the same: A variable referencing the interned string "foo".

A: Yes, they are same. Basically intern() returns a representation of a string that is unique across the VM. This means you can use == instead of .equals() to compare the strings, saving on performance.

A:
Explicitly constructing a new String
  object initialized to a literal
  produces a non-interned
  String. (Invoking intern() on this
  String would return a reference to the
  String from the intern table.)

Taken from : http://javatechniques.com/public/java/docs/basics/string-equality.html


text:
Q: How can i get executed query in cakephp3 in case of save & delete. My requirement is to save query in database Please help me to solve below queries on cakephp3
1. How can i get executed query in cakephp3 in case of save & delete. My requirement is to save query in database.
2. Is it possible to get the query inside any of callback function like eg. BeforeSave, AfterSave, AfterSaveCommit, BeforeDelete .. etc.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Optional HTTP Post parameters JavaScript I have a filtration function, a lot of checkboxes and dropdowns. When user selects multiple check boxes and selects the dropdown values they click on the "Filter Now" button.
That button then carries out a POST request to my API and pass along the filtration options as the parameters and return the data from MongoDB.
Heres my code:
factory.getFilteredProjects = function(regions, services, sector){

  return $http.post('/user/test',{
      region: regions,
      sol: services,
      sec: sector
  }).
    success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available

        console.log("this is the response data " + data);
    }).
    error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
    });

  };
     return factory;
 });

In the above code you can see I have 3 parameters (regions, services, sector)
Now the user only might want to filter the data by:

*

*Regions or Sector

*Just Regions

*Just Services

*Services and Regions

And So On!
My question:
How can I pass options parameters with my POST regions. At the moment I have to send all 3 parameters to get data back. If I don't send all 3 then I don't get any data back. Only the ones the user actually interacted with so basically something like:
// This is just to get my point across.
function(a || b || c){
}

UPDATE:
Testing my API through POSTMan. As you can see I only sent 2 parameters and got a 200 status back and i am also getting the correct data back.

Thanks.

A: You can just give an object in parameter instead of three string. Like this you can control the number of POST parameters instead of have some of them undefined.
EDIT : I suggest to do the filtering in your service. Like this, you don't have to complexify your code on each controller :
factory.getFilteredProjects = function(params){

  // remove empty value or empty array
  angular.forEach(params, function(value, key) {
    if( ! value || value.length === 0 ) {
      delete params[key];
    }
  })

  return $http.post('/user/test', params).
    success(function(data, status, headers, config) {
        // this callback will be called asynchronously
        // when the response is available

        console.log("this is the response data " + data);
    }).
    error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
    });

  };
     return factory;
 });

getFilteredProjects({ region: 'test', sec: 'sector' })

A: so after doing some research, a few cups of coffee and couple of swear words later I got this working.
But heres a note:
First thanks to Yoann Prot your suggestion was a huge help!
This is my initial solution, I will NOT be accepting my own answer. Because there might be a better solution to this and I would like someone to post an answer/comment if they think it can be improved
So my if you read the comments above you know my API was able to handle multiple or flexible number parameters. The issue was my HTTP Post function required all parameters to be present.
As Alex Blex suggested in the comments that:

Then you just need to detect which ones the user actually interacted, and send only them

And thats exactly what I did.
I created a filter object to which I added key/value pairs of only the options that the user interacted with and passed that whole filter object as the parameter. This made my parameters for the HTTP Post request much more flexible.
Heres the code:
 var filterObj = {};

    var form = document.getElementById("regionPicker");
    var servicesForm = document.getElementById("servicesPicker");

    var inputs = form.getElementsByTagName("input");
    var arr = [];

    var servicesInput = servicesForm.getElementsByTagName("input");
    var servicesArr = [];

    for (var i = 0;  i < inputs.length; i += 1) {
         // Take only those inputs which are checkbox
        if (inputs[i].type === "checkbox" && inputs[i].checked) {
                 arr.push(inputs[i].value);
         }
     }

    for (var i = 0;  i < servicesInput.length; i += 1) {
         // Take only those inputs which are checkbox
        if (servicesInput[i].type === "checkbox" && servicesInput[i].checked) {
                 servicesArr.push(servicesInput[i].value);
          }
       }

 // here arr contains an array of filter options selected by user
 filterObj.region = (arr.length > 0) ? arr:"";

 // here serviceArr contains an array of another filter options selected by user
 filterObj.sol = (servicesArr.length > 0) ? servicesArr:"";

And finally pass the filterObj as the parameter:
factory.getFilteredProjects = function(filterObj){

  return $http.post('/user/test',filterObj)
  .success(function(data, status, headers, config) {
       console.log("this is the response data " + data.length);
    })
  .error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
    });
  };

So far all the tests have been successful. But I repeat if you know a better solution please let me know or if you think this solution has drawbacks or issues or is just bad practice please let me know.
Thanks!


text:
Q: Get slicer value in Apps Script I recently started using slicers in Google Sheets and I would like to find a solution (probably with Apps Script) to access the current value selected in a slicer of my Spreadsheet.
Do you have any leads to solve this problem?


text: Q: gulp concat js files into two min.js, lost library definition I'm using gulp to concat all js library to lib.js, and concat all self-writing js files to app.js, then I use gulp-inject to inject into my index.html, but chrome console shows the error jQuery is not defined


text:
Q: Accessing real-time user location via last post or mobile location I've built an app utilizing user's straight location; but I'd like access to the user's latest  location i.e. when a user posts from a mobile device they include an approx. location; how can we access that?  This would open a door to a huge "real-time" market.

A: This is not exposed via the Graph API.
I can't be 100% sure, but I posted a status update via the mobile app, verified it had the location "Brooklyn" on it.  Then I used the API Explorer to drill down and look at that status update: http://developers.facebook.com/tools/explorer/?method=GET&path=781062048236 and there is no location information available.
You can also verify by looking at the docs that they just don't make it available.


text:
Q: javac source and target options I have seen the compile options like discussed in Which JDK's distributions can run `javac -source 1.6 -target 1.5`?. I understand the individual options for source and target. I don't  understand why source version is higher that the target version. Compiling the code for older targets makes sense. But in that case, why dont we just use -source of the oldest target we want to be able to run on

A: *

*source: The version that your source code requires to compile.

*target: The oldest JRE version you want to support.

Be sure to also set bootclasspath to ensure your program will work on older VMs.

From the javac documentation:

Cross-Compilation Example
The following example uses javac to compile code that will run on a 1.6 VM.
C\:>javac -source 1.6 -target 1.6 -bootclasspath C:\jdk1.6.0\lib\rt.jar -extdirs "" OldCode.java

The -source 1.6 option specifies that version 1.6 (or 6) of the Java programming language be used to compile OldCode.java. The option -target 1.6 option ensures that the generated class files will be compatible with 1.6 VMs. Note that in most cases, the value of the -target option is the value of the -source option; in this example, you can omit the -target option.
You must specify the -bootclasspath option to specify the correct version of the bootstrap classes (the rt.jar library). If not, the compiler generates the following warning:
C:\>javac -source 1.6 OldCode.java
warning: [options] bootstrap class path not set in conjunction with -source 1.6

If you do not specify the correct version of bootstrap classes, the compiler will use the old language rules (in this example, it will use version 1.6 of the Java programming language) combined with the new bootstrap classes, which can result in class files that do not work on the older platform (in this case, Java SE 6) because reference to non-existent methods can get included.

A: Peter Tseng does mention a lot of key points to remember during compilation. As a matter of fact even I faced a similar issue sometime back and want to share the root causes of many issues.
I had a source code which had to compiled & make it compatible (-source & -target) Java '1.8'. The code itself had

*

*Lot of Trademark symbol hence I ended up in unrecognized characters(I had to tweak the IntelliJ Idea's encoding settings)

*Lot of changes to java.sql.* package

*Usage of lot of third-party libraries. Spare me the horror of explaining the difficulty debugging there and blah blah blah.

After certain changes I ended up with a code which had equal amount of JUnit test cases to run. Eventually I bumped into a java.lang.VerifyError. I was shocked when I understood that such error happens when I compile and run the code in the different libraries/environment(Which was not the case).
What I almost missed was that, for honoring the fact that the tests had to run in an isolated environment, the Junit & its test cases where executed in a seperate forked VM
<target name="runJunit">
    <junit printonsummary="on"
           haltonfailure="off"
           fork="true"
           forkmode="once">
        <formatter />
        <batchtest />
        <classpath />
    </junit>
</target>

This obviously will be spanned as a separate process and act as a standalone application in execution. Even though the IDE spans both processes synchronously, the JVM's are pretty much isolated.
After Java 1.7, Oracle has introduced a stricter verification and changed the class format a bit -- to contain a stack map, used to verify that code is correct. The exception I had seen was because some method doesn't have a valid stack map. I eventually tried including lot of JVM options to tweak the setting, but in vain.
<jvmarg value="bootclasspath:{env.JAVA_HOME}\jre\bin\rt.jar" prefix="-X"/>

nothing worked. The only work around was to include
<jvmarg value=":UseSplitVerifier" prefix="-XX"/>

In Java 1.7 to allow only nominal byte code verification. Since this was taken off in Java 1.8, the only option was to use
<jvmarg value="-noverify"/>

A: Java is backwards compatible. You use the -source option to specify the java version used for compilation and you use the -target option to specify the lowest java version to support. eg. If I specify a target of 1.4, then my program will not be able to run on java 1.3 or lower. see the following javac documentation for more info. especially the section on Cross-Compilation Options

A: JDK1.8 will no longer support -source and -target less than 1.6
"c:\Program Files\Java\jdk1.8.0_121\bin\javac.exe" -source 1.3 HelloWorld.java
warning: [options] bootstrap class path not set in conjunction with -source 1.3
warning: [options] source value 1.3 is obsolete and will be removed in a future release
warning: [options] target value 1.4 is obsolete and will be removed in a future release
warning: [options] To suppress warnings about obsolete options, use -Xlint:-options.
4 warnings


text:
Q: user authentication failed for MasterCard type in PayPal PayFlow link Test Transaction I got the below message after transaction failed,
RESULT=1 RESPMSG=User+authentication+failed.
Used MasterCard test Credit Card Number. I searched and tried to find a solution.But couldn't
Please help me to find a solution,
Thanks in advance...

A: This typically means that you are not passing across the correct credentials.  You would need to double check these and make sure they are correct.  If you see this transaction show up in your Payflow account and it says user authentication, then this usually means that you do not have your processor information set up on the account correctly, and you may need to double check the processor information.  However, this shouldn't be an issue if this is a test being ran again the test server.


text:
Q: Multiline textview in table row not wrapping properly I'm trying to get my text of my text view within the table row to appear on more than one line, but for some reason it doesn't wrap properly and I end up with this (see screenshot). I know the text view has something to do this it but I don't know what I causing this problem to occur. What can be done to resolve this issue?
Screenshot

List item XML
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TableRow>
        <ImageView
            android:id="@+id/img"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_gravity="center_vertical" />

        <TextView
            android:id="@+id/txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginStart="15dp"
            android:layout_marginEnd="15dp"
            android:singleLine="false"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </TableRow>
</TableLayout>

A: You need specify android:layout_weight="1".

This value is telling to TableRow that the TextView is need to be equivalent to match_parent

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:layout_width="match_parent"
             android:layout_height="match_parent">
    <TableRow
            >
        <ImageView
                android:id="@+id/img"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_gravity="center_vertical"/>

        <TextView
                android:id="@+id/txt"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center_vertical"
                android:layout_marginStart="15dp"
                android:layout_marginEnd="15dp"
                android:layout_weight="1"
                android:text="This is a long long long long text fodshfkjsdkjfjsh js hdfjksh kjdhf kjshdkjf"
                android:textAppearance="?android:attr/textAppearanceLarge"/>
    </TableRow>
</TableLayout>

A: give <TableRow> attributes
   <TableRow
       android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <ImageView
            android:id="@+id/img"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_gravity="center_vertical" />

        <TextView
            android:id="@+id/txt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:layout_marginStart="15dp"
            android:layout_marginEnd="15dp"
            android:singleLine="false"
            android:paddingRight="10dip"
            android:textAppearance="?android:attr/textAppearanceLarge" />
    </TableRow>

A: Try below code may help
<com.project_name.JustifiedTextView.JustifiedTextView
                    android:id="@+id/txtHide"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="right"
                    android:padding="25dp"
                    xmlns:noghteh="http://noghteh.ir"
                    android:text=""
                    android:textColor="@color/BlueText"
                    android:textSize="@dimen/text_size" />

Link:
https://github.com/navabi/JustifiedTextView

A: Simple fix would be to increase margin end,
try :
<TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_marginStart="15dp"
        android:layout_marginEnd="30dp"
        android:singleLine="false"
        android:textAppearance="?android:attr/textAppearanceLarge" />


text:
Q: Компилятор останавливается на пробеле #include<iostream.h>
#include<string.h>
#include<stdio.h>

void main() {
    int m=0;
    char s[100];
    cin>>s;
    for ( int i=0; i < strlen(s)-2; i++) {
        if((s[i]=='a')&&(s[i+1]=='b')&&(s[i+2]=='c'))
            m++;
    }
    cout<<m<<endl;
}

A: код видимо  написан под какой то очень старый компилятор. Как минимум его нужно переписать так
#include<iostream> // с .h нет такого файла
#include<cstring>
#include<cstdio>

int main() { // void тип не принято писать.
  int m=0;
  std::string s;
  std::getline(std::cin,s); // здесь может быть и std::cin >> s; но тогда будет только до первого пробела.
  for ( size_t i=0; i < s.length() - 2 ; i++) { // здесь нужен - 2, что бы не выйти за пределы.
    if((s[i]=='a')&&(s[i+1]=='b')&&(s[i+2]=='c')) // здесь можно  было бы и красивее написать, но я уже так оставил
      m++;
  }
  std::cout << m << std::endl;
  return 0; // очень желательно в конец добавить
}


text:
Q: Best pratice for having a daily updated cache for multithreading application in Java In my application, I'd like to have a cache that will be updated daily by an expensive operation (for example, fetching from remote and computing locally). The idea is every day, it will fetch and compute the latest cache for today. And at any time of today, any thread should be able to read from/write to the daily cache. And it's fine to serve the old data when the expensive operation is running daily and should not block any requests at any time.
I have written a simple code to illustrate the idea but not sure if it's the best practice or even correct in terms of multithreading.
For example,

*

*is volatile required?

*What will happen if there is a cache reassignment finished in the middle of a get or put.

Any suggestion will be much appreciated!
public class DailyCache {
    private volatile ConcurrentHashMap<String, String> cache;

    public DailyCache() {
        cache = expensiveCalculation();
        Executors.newScheduledThreadPool(1)
                 .scheduleAtFixedRate(() -> cache = expensiveCalculation(), 1, 1, TimeUnit.DAYS);
    }

    public String get(String key) {
        return cache.get(key);
    }

    public void put(String key, String value) {
        cache.put(key, value);
    }

    public ConcurrentHashMap<String, String> expensiveCalculation() {
        // an expensive operation to fetch the cache for today
    }
}

A: Executor service
First of all, you need to capture the reference returned from the call Executors.newScheduledThreadPool(1). You must store that reference somewhere in your app for eventual shutdown. If you neglect to shut down an executor service, it's backing pool of threads may continue to run after your app exits, like a zombie ♂.
And, by the way, for a single-threaded executor service, call the convenience method Executors.newSingleThreadExecutor.
Replace entries
If you are using a thread-safe collection, then I would replace individual elements during your update. Do you have a need to replace all the map entries simultaneously? If so, say so in your Question.
If you do not have a reason to replace the entire map, change your code to mark your cache as final. If you establish the map's existence well before the first attempt to access it, and you never replace it, then no need to mark it as volatile.
Another thing: It's generally best to make your fields the most general type that fits. So in this case, ConcurrentMap rather than locking yourself into ConcurrentHashMap.
public class DailyCache {
    private final ConcurrentMap< String, String > cache;
    private final ScheduledExecutorService ses;

    public DailyCache() {
        this.cache = new ConcurrentHashMap<>() ;
        this.expensiveCalculation();
        this.ses = Executors.newSingleThreadExecutor() ;
        this.ses.scheduleAtFixedRate(() -> cache = expensiveCalculation(), 1, 1, TimeUnit.DAYS );
    }

    public String get( String key ) {
        return this.cache.get( key );
    }

    public void put( String key, String value) {
        this.cache.put( key, value );
    }

    public void expensiveCalculation() {
        // A series of expensive operations to replace each element/entry of the `Map` cache.
    }

    public void shutdown() {
        // Gracefully shut down the scheduled executor service held in var `ses`.
        …
    }
}

One advantage to this entry-replacement approach is that fresh data arrives to the user faster, with the early replacements being made available to the calling code while later replacements have yet to be made.
Replace map
volatile
If you have a reason to replace the entire map all at once, rather than replacing individual entries, then you should make the cache declaration non-final, and volatile.
public class DailyCache {
    private volatile ConcurrentMap< String, String > cache;
…

But I prefer a different approach. Due to the change in its definition specifically, and the complexity of concurrency in general, I expect the volatile keyword is not clearly understood by all programmers.
AtomicReference
So I would use an AtomicReference object instead, to hold a reference to your current map object. Seeing that AtomicReference declaration should make your intentions obvious to another programmer.
An AtomicReference is a thread-safe holder for a reference to an object.

*

*var ➤ reference ➤ objectWith a conventional reference, such as the cache variable seen above, we are one step away from the map object: The cache variable holds a reference which at runtime takes us to the ConcurrentMap object floating within the heap somewhere.

*var ➤ reference ➤ object ➤ reference ➤ objectWith an AtomicReference, we are two steps away from the desired object. The cache variable seen below is a reference to an object whose content is the reference to yet another object.

An AtomicReference is a little weird to think about at first, because in Java we think of a variable like cache above being the object, even though we know it is one step away from an object. In contrast, an AtomicReference makes us quite conscious of the fact that we are manipulating a reference to an object containing a reference to an object. For example, notice the .get().get(…) and .get().put(…) calls below.
public class DailyCache {
    private final AtomicReference < ConcurrentMap< String, String > > cache;
…

Here is the complete class, revised for an AtomicReference.
public class DailyCache {
    private final AtomicReference < ConcurrentMap< String, String > > cache;
    private final ScheduledExecutorService ses;

    public DailyCache() {
        this.cache = new AtomicReference<>( new ConcurrentHashMap< String, String > () ) ;
        this.expensiveCalculation() ;
        this.ses = Executors.newSingleThreadExecutor() ;
        this.ses.scheduleAtFixedRate(() -> cache = expensiveCalculation(), 1, 1, TimeUnit.DAYS );
    }

    public String get( String key ) {
        return this.cache.get().get( key );
    }

    public void put( String key, String value) {
        this.cache.get().put( key, value );
    }

    public void expensiveCalculation() {
        ConcurrentMap< String, String > concurrentMap = … // An expensive operation to produce a new `ConcurrentMap`.
        this.cache.set( concurrentMap ) ;
    }

    public void shutdown() {
        // Gracefully shut down the scheduled executor service held in var `ses`.
        …
    }
}

A: To answer your questions:

Q: is it "the best practice"

There are No Best Practices.  If you haven't done so already, take the time to read that.
This question is unanswerable ... and not even meaningful.
Hint: it is time to remove "best practice" from your vocabulary ... and start questioning the wisdom of people who tell you that something is "best practice".

Q: is volatile required?

Maybe.  It depends on whether it is possible for the reference in cache to change.

*

*If it is possible, then the volatile is required.

*If it is not possible, then the volatile may not be required.  But in that case you should declare the variable as final.  If you do that, then the JLS guarantees that all threads will see the correct value for variable.

In your code, it looks like you are periodically assigning a new value to cache.  If so, then it needs to be volatile, or you need some other way to ensure that all worker threads see the updated cache value.  (There are other ways ... but this is starting to smell of premature optimization.)

Q: What will happen if there is a cache reassignment finished in the middle of a get or put.

If the get or put call starts before the assignment, then they will definitely operate on the old cache.  If not, it is not it will depend on whether the fetch of the cache occurs before or after the assignment.  That is unpredictable.

There is one other thing that you don't seem to have considered.  You say:

And it's fine to serve the old data when the expensive operation is running daily and should not block any requests at any time.

But you have not said if it is OK (or not) for the old cache to be updated while the new cache is being built.  For example, consider this sequence of events:

*

*Start rebuilding cache

*Cache rebuilder updates key1 -> value1 in the new cache

*The main application reads and updates key1 -> value2 in the old cache

*The cache is replaced.

Now we have the application running with the new cache, but the new cache contains a value1 for key1 that is older than the most recently used value (value2).
If that breaks your application, then you need a way to solve it.  There will be ways ... but it will depend on aspects of your application logic that you haven't mentioned.   For example, the scenarios in which regular application threads will do cache put operations.


text:
Q: Is the solution to this recurrence correct? I'm working on a problem that resulted in the following recurrence (which I think is wrong, but that's not the question here):
$$
(n-i)*2i*Z_i = n(n-1) + (n-i)(i+1)Z_{i+1} + (n-i)(i-1)Z_{i-1}
$$
Subject to $Z_n = 0$.
The solution for $i=1$ to the above recurrence is said to be
$$
Z_1=(n-1)^2
$$
Is there a quick way I can find if this solution is indeed correct?

A: This is a second order recurrence. With a single final condition, the solution is indeterminate.

Assuming you fix this, a possible check is to solve the recurrence explicitly with small $n$, say $3,4,5$, and check if the solutions match $(n-1)^2$.


text:
Q: Generate auto-increment int column in MariaDB with EFCore The Problem:
I'm trying to create a table with efcore in .netcore 2.2 using codefirst having an auto-increment integer primary key starting at 0. All solutions i found result in either an error on adding migration or the auto-incrementing works but start at int.MinValue.
All the following solutions have been tried seperated, not combined:

Solution 1:
Do nothing. Just let efcore do its default thing.
-> The column auto-increments but starts at int.MinValue

Solution 2:
setting annotation "[DatabaseGenerated(DatabaseGeneratedOption.Identity)]" on primary key.
-> The column auto-increments but starts at int.MinValue

Solution 3:
modelBuilder.Entity<User>()
    .Property(u => u.Id)
    .ValueGeneratedOnAdd();

-> The column auto-increments but starts at int.MinValue

Solution 4:
modelBuilder.HasSequence<int>("User_seq")
    .StartsAt(0)
    .IncrementsBy(1);

modelBuilder.Entity<User>()
    .Property(u => u.Id)
    .HasDefaultValueSql("NEXT VALUE FOR User_seq");

-> Adding a migration fails with an error:
    "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SEQUENCE User_seq START WITH 0 INCREMENT BY 1' at line 1"

Solution 5:
changing the datatype of Id to uint.
-> The column auto-increments but starts at int.MaxValue

My User entity:

    public class User
    {
        public int Id { get; set; }
        public string FirstName{ get; set; }
        public string LastName { get; set; }
    }

Provider used: Pomelo.EntityFrameworkCore.MySql

To clarify my question: How do I create an auto-incrementing integer primary key column starting at 0 incrementing by 1 in MariaDB using efcore codefirst?

A: You cannot.
MariaDB (MySQL) treats 0 as meaning to create a new AUTO_INCREMENT value.
Do not assume properties of AUTO_INCREMENT that it does not provide.  It only says that each new value will be different than the existing values.
Probably int.MinValue is some big negative value (-2^31).


text:
Q: UnexpectedValueException in Response.php line 403 - Laravel 5.3 I am new to Laravel and am building a small project as my schooling. I have struck the above error and I cannot seem to fix it. Any help is appreciated.
I am using sentinel package for authentication.
Web.php
Route::post('/login' , 'LoginController@login');

LoginController.php
public function login(Request $request){
       Sentinel::authenticate($request->all());
       return Sentinel::check();

}

When I click on submit button then this error showing:

UnexpectedValueException in Response.php line 403:
  The Response content must be a string or object implementing __toString(), "boolean" given.

A: Finally i solved the problem .
Actually i forget to replace email to username in EloquentUser.php because i am using username unique rather than email .
 protected $loginNames = ['email']; ->  protected $loginNames = ['username'];


text:
Q: unable to install material-ui/core in reactjs project? I try to install material-UI on my new project but got an error.
I tried with --force tag but it didn't work.

A: As mentioned in the links in the comments, it's a DNS issue.  You can troubleshoot it by:

*

*Open a command prompt (windows) or terminal (mac/linux)

*Type nslookup

*Next type registry.npmjs.org

*If it doesn't respond with an IP address and says, non-existent domain type server 8.8.8.8 (this is google's public dns server)

*Type registry.npmjs.org and it should return the IP.  This confirms it's an issue with the dns server you're using.

If that's the case, you can try setting your machine's DNS server to use 8.8.8.8 and run the install.

A: Check if you have any proxy set, if yes remove them
to check if you have proxy,
npm config list

to remove proxy,
npm config rm proxy
npm config rm https-proxy

Another silly thing to try would be to disconnect from your network/wireless and connect through mobile hotspot and check.


text:
Q: Why are there different types of bond configuration policies in linux, instead of one that can give a combined throughput and fail-over configuration? I am confused and not able to understand exactly the actual concept behind it. At switch level, what happens that prevents to use one globally accepted bond configuration policy?
And I don't understand why do we use specifically active-backup policy in our environment, instead of going for a better one that gives combined throughput, but not just fail-over configuration.
This website seems to have a good explanation: http://www.enterprisenetworkingplanet.com/linux_unix/article.php/3850636/Understanding-NIC-Bonding-with-Linux.htm
but I am unable to follow exactly. So, can someone explain it more clearer and try to explain in as much detail as possible what's happening at switch end and with the mac addresses?
Thanks.
Or you can also suggest a good book, where I can read everything about it and learn from scratch.


text:
Q: How can I make a copy of a table from information_schema? I would like to extract meta information from information_schema like count of rows in a table and store the result table into "meta" database. However, while I can query tables in information_schema, I can't store the result into a table. Following query always returns "ok", but it doesn't produce the table (I can rerun the query and MariaDB still returns "ok"):
create table meta.copy as
select *
from information_schema.`TABLES`

What is more interesting is that if I thoroughly avoid databases (TABLE_SCHEMAs) with a view, I can save the partial copy of information_schema.TABLES. For example, following query works:
create table meta.copy as
select *
from information_schema.`TABLES`
where TABLE_SCHEMA = 'performance_schema'

Is this a quirk of MariaDB 10.0.15? Or is there some rationale behind this behavior? And is there a query that can make complete copies of tables from information_schema?
PS: I know I can extract count of rows other ways but I also want to extract other information from information_schema than count of rows.


text:
Q: Windows 7 blocking java.io.File methods? Here's a program that takes all PDF files in a given folder, then adds a date prefix and filters out all umlauts. This worked on my Win XP install but not on a fresh Win7 one, where the exact same code terminates because of a nullPointerException in replaceSymbolsInDir(String)'s line 4, that's the empty line right before the for-loop.
I triggered the process by compiling it in Eclipse:
import java.io.File;

public class loadFile {

public static String dir = "C:\\Users\\UserName\\Desktop\\PdfDirectory\\";
public static String date = "130406";

public static void main(String args[]) {

        replaceSymbolsInDir(dir);
        addPrefix(dir, date + "-");
}

public static void replaceSymbolsInDir(String path){

    File folder = new File(path);
    File[] fileArray = folder.listFiles();

    for(int i = 0; i<fileArray.length; i++) {
        File currentFile = fileArray[i];
        if(currentFile.getName().toLowerCase().endsWith(".pdf")) {
            currentFile.renameTo(new File(path, replaceSymbolsInString(currentFile.getName())));
        }
    }
}

public static String replaceSymbolsInString(String s) {
    //figure out regex
    String result = s.replace('ä','a');
    result = result.replace('ö','o');
    result = result.replace('ü','u');
    result = result.replace('ß','s');
    result = result.replace(' ','-');
    return result;
}

public static void addPrefix(String path, String prefix) {

    File folder = new File(path);
    File fileArray[] = folder.listFiles();

    for(int i = 0; i<fileArray.length; i++) {

        File currentFile = fileArray[i];
        if(!currentFile.getName().startsWith(prefix) && currentFile.getName().toLowerCase().endsWith(".pdf")) {
            String newName = prefix + "" + currentFile.getName();
            currentFile.renameTo(new File(path, newName));
        }
    }
}
}

Is win7 blocking methods that try to find information about files and folders? It seems like
folder.listFiles();

is coming up null and that that's the issue.
Any ideas besides the path being wrong? Because that's ctrl+c/v out of the explorer window plus escapes and should therefore be correct.
Edit: I'm running the program on the only existing user account, the account management window labels it "admin". Running from cmd after opening cmd as admin also produces a NPE.
Edit2: As was said, the folder defaults to being write protected and can't be changed, that's what seems to be the root cause. I'll look into it...

A: Windows 7 doesn't allow one user to read files or folders in another user's directory by default, whereas Windows XP does.  You'll need to do one of two things:

*

*Get the user whose folder this is to grant the 'read' permission to the user who is running the code, or

*Run the code with elevated permissions (e.g. from an elevated command prompt) using UAC.


text:
Q: Can I do this kind of change of variables? What would be the functional determinant? Let's say I need to solve this functional integral:
$$
Z=\int \mathcal{D}x(\lambda)F[x(\lambda)]
$$
Then, I want to change the integration to $\mathcal{D}v(\lambda) $. Where $v$ is a shorthand for $v^\mu =\frac{dx^\mu}{d\lambda}$. The reason for this could be, for example, that in the functional $F$ there is no $x$ (just derivatives of $x$) and (for example) integrals of the form:
$$\int_{\lambda_i}^{\lambda_f}\frac{dx^\mu}{d\lambda}\frac{dx_\mu}{d\lambda} d\lambda$$
So my guess is that
$$Z=\int \mathcal{D}v(\lambda) \det(\frac{\delta x(\lambda)}{\delta v(\lambda)}) G[v(\lambda)]$$
where
$$G[v(\lambda)]=F[x(\lambda)]|_{\frac{dx^\mu}{d\lambda}=v^\mu(\lambda)}$$
I wonder if the jacobian would be something relevant, or perhaps something kind of trivial, that I can take out in a constant N
$$Z=N\int \mathcal{D}v(\lambda)  G[v(\lambda)]$$
Are my steps correct? What would be the functional determinant?


text:
Q: Update Datatable with another I have 2 C# datatables, the master(datatable1) that I want too update has many rows but the second contains only a few unique rows. Below is what I am trying to achieve.
I have searched to find a way to do this with loops and LINQ but none seem to  update the ECAD column.
I tried this.
foreach (DataRow row in dtARIAA.Rows)
{
      foreach (DataRow row1 in dtReport.Rows)
      {
            if (row["Ser"] == row1["Ser"] )
            {
                row1["ECAD"] = row["Date"];
            }
      }
}
dtReport.AcceptChanges();

A: As far as I can tell from your schema above you just need to write and execute this SQL.
Table1 is you table with dates to update, Table2 is your second table with dates
update t1 set t1.ECAD  = [t2].[Date] from Table1 t1
                         inner join Table2 t2  ON t2.Ser = t1.Ser

But if you want to work with two DataTables already in memory then you could use
// Loop over the table with the unique Ser value and with the date to transfer
foreach (DataRow r in dtARIAA.Rows)
{
      // Get the rows in the destination table with the same "Ser" value
      DataRow[] destRows = dtReport.Select("Ser = " + r["Ser"]);

      // Now update the destination table rows with the Date value
      foreach (DataRow row1 in destRows)
          row1["ECAD"] = r["Date"];
}
dtReport.AcceptChanges();


text:
Q: s/mime v3 with M2Crypto I would like to send a mail with a s/mime v3 attachment through SMTP.
The excellent HOWTO below describes the procedure in detail for s/mime v2.
http://sandbox.rulemaker.net/ngps/m2/howto.smime.html
I would greatly appreciate any help in doing the same for s/mime v3.
Arye.

A: I don't know about v3, but some updated info...
The new location for that howto is at http://svn.osafoundation.org/m2crypto/trunk/doc/howto.smime.html. Note that it is still for v2. There are also some smime tests at http://svn.osafoundation.org/m2crypto/trunk/tests/test_smime.py


text:
Q: java, Calculating mongodb query execution time I want to log my query times for each time when a query made.
I'm using mongodb on playframework. Simply I'm thinkinig to substract start and end time.For ex:
a=currenttime();
madequert();
querytime=currenttime()-a;

Is there any better way?

A: You probably want to use Mongo's DB profiler. That way you'll keep that of your code (less work to maintain it) and it will give you more options to check Mongo behaviour.


text:
Q: Move elements in an object array in front of a different element [Java] I'm doing an assignment and I was wondering if there was an easy to move elements in an array around. I'm trying to sort a list of authors alphabetically, so I'd like to compare array[1] to array[2] and if 2 belongs in front of 1 I'd simply like to move it there. I figured the best way to do this would be by using two for loops. Here's basically what I have. Is there any easy way to move k in front of j in the array?
for(int j = 0; i > j; j++) {
            for(int k = 0; k > i; k++) {
                if(array[j].getAuthor.compareTo(array[k]) == -1) {
                    //move k in front of j
                } else {
                                  //do nothing
                }
            }

        }

A: you use java, so the jdk provides a method for you.
Arrays.sort(array,new Comparator<Object> {
      @Override
      public int compare(final Object pre, final Object next){
        //return 0, 1 ,-1
}
)

A: There is no primitive "move in front of" operation on Java arrays.
What you need to do is to rethink your algorithm so that it works using the primitive operations that ARE available to you.  These are* getting and setting the element at a particular offset (using array[i]), and getting the length of the array (using array.length).
So if you want to put array[i] in front of array[j] you need to move all of the elements between i and j to the left or right using a loop and assignments.  I'll leave you to work out the details ... 'cos that is obviously what the person who set your homework expects you to do.

* - actually, there are a couple of library methods for bulk copying array elements; e.g. System.arraycopy.  However, I recommend that you implement it with loops so that you can get a better understanding of what is involved.


text:
Q: The getter 'length' was called on null. Receiver: null Tried calling: length FutureBuilder with List I keep getting the error mentioned above during runtime of my flutter app. Basically what I am trying to achieve is to fetch data from an api and display it in a form of a SliverList by using a FutureBuilder.
This was working perfectly fine until I changed my code for the list from FutureBuilder<List> to FutureBuilder<List> to make use of the class EntertainerEvent which has all the fields I need for display from the json file.
How can I resolve this because it seems like the contructor or the application itslef is not picking up the data when I make use of a custom class.
This is the code for the EntertainerEvent class:
    class EntertainerEvent {
      final int eventId;
      final int entertainerId;
      final int eventTypeId;
      final int categoryId;
      final String eventName;
      final String description;
      final String imagePoster;
      final String location;
      final DateTime startDate;
      final DateTime endDate;
      final double entreeFee;

      const EntertainerEvent({required this.eventId, required this.entertainerId, required this.eventTypeId,
        required this.categoryId, required this.eventName, required this.description, required this.imagePoster,
        required this.location, required this.startDate, required this.endDate, required this.entreeFee});

      factory EntertainerEvent.fromJson(Map<String, dynamic> event) {
        return EntertainerEvent(
          eventId: event['EventID'],
          entertainerId: event['EntertainerID'],
          eventTypeId: event['EventTypeID'],
          categoryId: event['CategoryID'],
          eventName: event['EventName'],
          description: event['Description'],
          imagePoster: event['ImagePoster'],
          location: event['Location'],
          startDate: event['StartDate'],
          endDate: event['EndDate'],
          entreeFee: event['EntryFee'],
        );
      }
    }

Below is the code for fetching data from the api:

Future<List<EntertainerEvent>> fetchEvents() async {
    var result = await http.get(Uri.parse(apiUrl));

    if (result.statusCode == 200) {
      var content = result.body;
      var arr = json.decode(content) as List;

      return arr.map((eve) => new EntertainerEvent.fromJson(eve)).toList();
    } else {
      print('Not loaded');
      throw Exception('Unable to fetch data from the Rest API');
    }
  }

  late Future<List<EntertainerEvent>> _fetchEvents;

  @override
  void initState() {
    _fetchEvents = fetchEvents();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<List<EntertainerEvent>>(
        future: _fetchEvents,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          var childCount = 0;
          if (snapshot.connectionState != ConnectionState.done) {
            childCount = 1;
          } else {
            childCount = snapshot.data.length;
          }
          return SliverList(
            delegate: SliverChildBuilderDelegate((context, index) {
              if (snapshot.hasData) {
                List<EntertainerEvent> someData = snapshot.data;
                print('data here');

                //Do some stuff

               }
              },  childCount: childCount),
           );
       });
  }

I do not know what exactly is it that I am missing because this code works if I use the type dynamic instead of the custom class EntertainerEvent.
Thank you all in advance!

A: Wrap it with hasData:
if(snapshot.hasData){
return SliverList(
            delegate: SliverChildBuilderDelegate((context, index) {

                List<EntertainerEvent> someData = snapshot.data;
                print('data here');

                //Do some stuff

              },  childCount: childCount),
           );}
    return CircularProgressIndicator();


text:
Q: Do HTTP responses have HTTP methods? I am learning HTTP and I have a basic question:

Do HTTP responses have HTTP methods like in the HTTP requests (GET,
POST, PUT, DELETE, etc.)?

If so, I have another question:

Does the HTTP method of an HTTP response always is POST to allow
having a body in HTML, SOAP or JSON?


text:
Q: Changing Rails Query to Pure SQL I'm looking to move the following code away from ActiveRecord to pure SQL for a performance increase.  What would be the best way to write this query in pure SQL (MySQL DB)?
User.count(:conditions => ["email = ?",params[:email]]) > 0

Thanks

A: Analogously to find_by_sql you can use count_by_sql:
User.count_by_sql(["SELECT COUNT(*) FROM users u WHERE u.email = ?", params[:email]]) > 0

Remember also to use the syntax ["... ? ...", var] here to protect against SQL injection.
However, I doubt that you can achieve a significant performance improvement by that. Test it. If it's not faster, stay with the ActiveRecord version or try to find a more nifty solution to your problem.
Edit:
If you just want to test whether an given email is already contained in the table you could also test the performance of User.find_by_email(params[:email]).present?


text:
Q: standalone value does not appear in xml generated by moxy - jaxb I have a xml file generated using moxy implementation of jaxb. However standalone value does not appear in the xml document.

A: Note:  I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.
The standalone attribute is seldom used, and is only relevant if you are using a DTD.  Since JAXB (JSR-222) is primarily used with XML Schema it doesn't apply.  We chose not to output that attribute in the MOXy implemenation of JAXB (JSR-222).
Other XML technologies chose not to support the standalone attribute as well.  For example I am not aware of a way to output a standalone value using a StAX parser.
For More Information

*

*http://www.xmlplease.com/xml/xmlquotations/standalone


text:
Q: Controller doesn't return html file So I got this simple code I'd like to test but somehow it doesn't return the dataBaseEntity.html.
@Controller
public class DataBaseMicroserviceRestConnectorProvider {

    @Autowired
    private DataBaseSpringDataConnectorRequester dataBaseSpringDataConnectorRequester;

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String addNewDataBaseEntityForm(Model model) {
        model.addAttribute("dataBaseEntity", new DataBaseEntity());
        return "dataBaseEntity";
    }

The html file is allocated in src/main/resources/templates/dataBaseEntity.html
<!DOCTYPE HTML>

    <title>Getting Started: Handling Form Submission</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

Form

    <form action="#" th:action="@{/dataBaseEntity}" th:object="${dataBaseEntity}" method="post">

Id: <input type="text" th:field="*{id}" />

Name: <input type="text" th:field="*{name}" />

<input type="submit" value="Submit" /> <input type="reset" value="Reset" />

    </form>

pom.xml
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

And I got a second question: is there a way to do this with @RestController instead of @Controller?

A: handle form submission in spring boot
go to this link, it will help to solve your problem.
there can be many things you may be missing in your example,
like :- I can't see your dataBaseEntity request in your controller , may be there you are missing something.
@RestController

we usually use for our rest end point not for jsp request.
hope by this link you will get your solution.

A: You may have a wrong configuration, please make sure you have set the right suffix and prefix for your templates:
@Bean
public SpringResourceTemplateResolver templateResolver(){
    SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
    templateResolver.setApplicationContext(this.applicationContext);
    templateResolver.setPrefix("classpath:/templates/");
    templateResolver.setSuffix(".html");
    templateResolver.setTemplateMode(TemplateMode.HTML);
    templateResolver.setCacheable(true);
    return templateResolver;
}

If you don't have a config right now, this might be your problem, please refer to: https://www.thymeleaf.org/doc/tutorials/3.0/thymeleafspring.html
For your second question about the @RestController annotation. This is basically the same as writing: @Controller and @ResponseBody
See:
Difference between spring @Controller and @RestController annotation


text:
Q: MFC application Assertion failed when linking with a regular DLL that uses MFC I'm migrating an old OWL application to MFC. there were a main library that has the main dialogs and controls , I started writing an alternative classes of MFC to the old OWL like TDialog[inherits from CDialogEx], TEdit..... I added all the needed classes from the OWL now my library build successfully.
I created a new MFC Application [to test the library], i exported a function [SowDialogue] from the dll to be used in the Application , I added the .lib of dll to the MFC application, I called the function to show a simple dialog , the build go successfully, but at the first start the application fail with the following message

I clicked retry and the break to get the line that caused the assertion it was that one

So the problem is with the resources. when i link with the library the MFC can't get the right resources module.
I thought it was because i use a regular dll that uses MFC and shares MFC objects, if i must use an MFC extension library. how can i convert regular library to MFC extension library.
Or any solution to this disaster after a long work
EDIT

this is the call stack, there are no exported functions in this, its all in the application the error come before calling anything from the dll

Solution

the problem was solved when i converted the dll to an MFC extension library, really i created a new mfc extension dll and cheated it's properties, the dll main, the stafx includes and preprocessors definisions
static AFX_EXTENSION_MODULE MFCExtensionDLL = { NULL, NULL };

extern "C" int APIENTRY DllMain( HINSTANCE hInst, DWORD fdwReason, LPVOID)
{
    if (fdwReason == DLL_PROCESS_ATTACH)
    {
        TRACE0("MFCExtension.DLL Initializing!\n");

        // Extension DLL one-time initialization
        if (!AfxInitExtensionModule(MFCExtensionDLL, hInst))
            return 0;

        new CDynLinkLibrary(MFCExtensionDLL);

        //My initialization code

        return 1;
    }
    else if (fdwReason == DLL_PROCESS_DETACH)
    {
        // Terminate the library before destructors are called
        AfxTermExtensionModule(MFCExtensionDLL);
        // my finalization code
        return 1;
    }
}

the properties
in the properties of project->configuration properties->general Use of MFC = Use MFC in a Shared DLL

,
in the properties of project->configuration properties->C/C++->Preprocessor->Preprocessor Definitions->add _AFXEXT , make sure to delete _USERDLL if it exists

A: When using MFC in a .dll, you have to make sure that the .dll can find resource handles for things like strings and bitmaps in the .rc file.  MFC maintains an internal state for each .dll that points to the resources for that .dll.  When calling into that .dll from an application (or another .dll) you have to 'help' MFC get the internal state right or it will not be able to find your resource and will ASSERT.
I can't see the function immediately below the one in the call stack in your example, but if it is an exported function, the MFC state problem is likely what is going on.
Make sure you have put the AFX_MANAGE_STATE macro at the top of any functions accessible from outside (exported functions).  That will go a long way to solving your problems.
Microsoft reference:  http://msdn.microsoft.com/en-us/library/ba9d5yh5(v=vs.80).aspx

A: If you use resources or windows from a dll file, you can try this way.  This code can be in the dll itself.  Whenever the resource is created the current resource handle of the main process will be set as the dll's resource handle and use the handle.
After any window creation or resource change revert it back to the old value.
hdllresource = ::LoadLibrary(<dllfile containing the resource>);
hcurrentInst = AfxGetResourceHandle();
AfxSetResourceHandle(hdllresource );

//do your window creation or resource loading stuff

AfxSetResourceHandle(hdllresource);


text:
Q: Вывести по номеру комбинацию факториала(перестановка) Здравствуйте.
Пользователь вводит N!
С этим числом работает метод перестановки. Который в свою очередь выполняется по формуле из комбинаторики(перестановка). Нужно вывести на экран по определенному номеру комбинацию которая соответствует ему.
Проблема в том, что это нужно реализовать без использования массива, коллекций.
Буду очень благодарен любому ответу.
Кто может, предоставьте пожалуйста пример на языке C#.
Пример
-----------------
4!
----------------
1 - 1234
2 - 1243
3 - 1342
4 - 1324
5 - 1423
6 - 1432
----------------
7 - 2341
8 - 2314
9 - 2413
10 - 2431
11 - 2413
12 - 2431
----------------
13 - 3412
14 - 3421
15 - 3124
16 - 3142
17 - 3241
18 - 3214
----------------
19 - 4123
20 - 4132
21 - 4231
22 - 4213
23 - 4312
24 - 4321
----------------

//По перестановке вычислить порядковый номер и по номеру саму перестановку.


text:
Q: Struggling to get the cell index path at the centre of collectionview I'm trying to get the indexpath of the cell in the collectionview like so using an extension
Code in extension
extension InfiniteCollectionView
{

    var centerPoint : CGPoint {
        get {
            return CGPoint(x: self.contentOffset.x + (CGRectGetWidth(self.bounds) * 0.5) , y: self.contentOffset.y + (CGRectGetWidth(self.bounds) * 0.5))
        }
    }

    var centerCellIndexPath: NSIndexPath?{

            return self.indexPathForItemAtPoint(self.centerPoint)
    }
}

So i can get the center indexpath like so
print(collectionVw.centerCellIndexPath)

But this keeps on returning nil which i can't seem to figure out why, it's worth noting that the extension is in a class called InfiniteCollectionView which is set as the custom class on a collectionview rather than a view controller.

A: "indexPathForItemAtPoint will return nil if no item was found at the specified point", your calculation for center point can return a point in space, so use indexPathsForVisibleItems.
The documentation also suggests to use layoutAttributesForItemAtIndexPath:
"Use this method to retrieve the layout information for a particular item. You should always use this method instead of querying the layout object directly."


text:
Q: Crackling, poor and low sound on HP Envy x360 AMD (Bang&Olufsen) and Ubuntu 20.04 I have a problem with my HP Envy x360 and Ryzen 5. It has Bang & Olufsen speakers. I also tried connecting Bluetooth Headphones (Niceboy Hive 2). Status:

*

*sound works

*sound is very low, and low in quality (very flat sounding)

*mic seems to work as per test in the settings

*when using overamplification, the anyway poor sound just starts crackling and is distorted

Did anyone get this to work, or is it a nyet? :)
Thanks

A: Nothing to do anymore. Point release fixed it last fall.


text:
Q: How to prove a vanishing set is a subset of $\mathbb{C}P^1 \times \mathbb{C}P^1$ I've been dabbling in algebraic geometry lately and studying some of the basic concepts. I understand that, if I have a homogeneous polynomial
$$
F \in \mathbb{C}[X_0,X_1,\dots, X_{n}]
$$
then the vanishing set $V(F)$ is a subset of $\mathbb{C}P^n$. However, I've also found other kind of polynomials such as this one:
$$
F = X_0^2 Y_0^3 + X_1^2 Y_1^3 + X_0 X_1 (Y_0^3 - Y_1^3) \in \mathbb{C}[X_0,X_1,Y_0,Y_1].
$$
This polynomial is a degree $5$ homogeneous polynomial in four variables, and so should be a hypersurface in $\mathbb{C}P^3$. In addition, it is a bihomogeneous polynomial of degree $2$ in $(X_0,X_1)$ and degree $3$ in $(Y_0,Y_1)$. I've been told that vanishing sets of polynomials of this form are also subsets of $\mathbb{C}P^1 \times \mathbb{C}P^1$ of dimension $1$. However, I fail to see how that is the case. I can't express $F$ as a product of a polynomial in $\mathbb{C}[X_0,X_1]$ and another one in  $\mathbb{C}[Y_0,Y_1]$, and I fail to see another way to prove this.
Thanks for any help in advance.

A: There are two different vanishing sets. One is a subset of $\mathbb{CP}^3$, and the other is a subset of $\mathbb{CP}^1\times\mathbb{CP}^1$:
$$\{[X_0, X_1, Y_0, Y_1] \in \mathbb{CP}^3 \mid F(X_0, X_1, Y_0, Y_1) = 0\} \subset \mathbb{CP}^3$$
$$\{([X_0, X_1], [Y_0, Y_1]) \in \mathbb{CP}^1\times\mathbb{CP}^1 \mid F(X_0, X_1, Y_0, Y_1) = 0\} \subset \mathbb{CP}^1\times\mathbb{CP}^1.$$
In general, a homogeneous polynomial has a well-defined vanishing set in projective space, and a multi-homogeneous polynomial has a well-defined vanishing set in a product of projective spaces. Every multi-homogeneous polynomial is homogeneous, so you always get two vanishing sets.


text:
Q: How to check updated file? I have following task:
I need to connect to FTP server and download data from it. Then connect to same server and check files for updates.
I can't check it by content, because file is too big. How can I do it? I use apache.commons library, FTPClient class.

A: You can call FTPClient.listFiles(String pathName) which gets you an array of FTPFile objects. These contain the timestamp.


text:
Q: How to create a view that would change the interface? Currently, I am making a contacts application. There is a feature that I would like to add in.

As you can see, there are 3 buttons at the bottom of the screen: Contacts, Phone, Groups. By clicking any one of these three buttons, I would be directed to another screen. This is the feature that I would like to add. How to make it? Any help would be very much appreciated.

A: you can start a new activity . and if you want to stay in the same activity you can use setContentView(layout) to set new layout for a screen.


text:
Q: Post Apocalyptic story involving illusions I am looking for a title of a short story based in a post-apocalyptic world, where an alien race has created an illusion for the last man on Earth.
In this illusion, a girl is present but the protagonist is able to identify her as an alien because she moves her ears towards where a sound comes from, in order to hear it better.

A: So, the title of this short story is Precious Artifact by Philip K. Dick.

"Precious Artifact" tells the tale of Milt Biskle, a terraforming
  engineer who has just turned his section of Mars into habitable land
  for human occupation. But something is nagging him in the back of his
  mind and he has doubts about the recent war in which Terra defeated
  the invading Proxmen. On his return to Earth his doubts are confirmed
  and he finds that beneath the surface of the seemingly normal world
  there is complete destruction. The Proxmen won the war, not the
  Terrans. Despite the presence of the nubile Mary Ableseth – a Proxman
  in disguise – Milt wishes to return to Mars for a rest before taking
  on the job of terraforming Earth to the Proxmen's designs. His one
  wish is that he be allowed to take a kitten back with him. This is
  granted and with the hope that he may talk the Proxmen into letting
  cats exist in the future he returns to his (fake) wife and children on
  Mars. But in the Proxmen's worlds there isn't much room for anything
  but Proxmen…"


text:
Q: Error connecting to MySQL server using C# I get a Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll error when trying to connect to my server in C#.
I've made a MySQL server using gearhost. Now I'm trying to test my connection using C# in WindowsForms. Here's my code:
    private void button1_Click(object sender, EventArgs e)
    {
        SqlConnection myConnection = new SqlConnection("Server=den1.mysql6.gear.host;" +
            "Database=databasetestroy;" +
            "Uid=databasetestroy;" +
            "Pwd=myPassHere");

        try
        {
            myConnection.Open();
            Console.WriteLine("Connected!");
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }

Here's a screenshot of my server/account details that I use to login.
I've succesfully logged in on the server from MySQL workbench.
Why do I get an error when trying to login?
I didn't add the details because they were in Dutch, I need to fix that so I can get the errors in English.
The solution of Tim Jarvis solved everything, I didn't know that the 'standard' SQL class was only meant for Microsoft. Thanks for the help.

A: It looks like you are trying to connect using the MSSQLServer database client, to connect to MySql you will need to use the MySql Client
using MySql.Data;
using MySql.Data.MySqlClient
....
var myConnection = new MySqlConnection(..etc..)

You can get the client via Nuget (supplied by Oracle)


text:
Q: Is it possible to define the version of a package in R install.packages? I know that you can download old packages and install them with
R CMD INSTALL package-version.tar.gz

I wonder if you can tell install.packages() to install a specific version from a repository, saving you from having to locate the tar.gz first. I have neither found this option in the help entry for install.packages nor googling for it. If this option does not exist, is there any reason for that?. I can only think that not all repos have all versions so you are forced to find the version first and download it.
There is an equivalent question already in SO but the problem and answer is more about repository problems, so at the end they never answered this question directly.

A: install.packages() does not, but there is a function install_version() in the devtools package which can install a version other than the most recent one from a CRAN repository.

A: remotes::install_version(package, version= version number, lib =location) and versions::install.dates(pkgs, dates, lib) are two other options. Also, checkpoint will fix the R version too.
library(checkpoint)
checkpoint("2020-01-01", r_version="3.6.2")


text:
Q: Place Bullets in Text Box Powerpoint C++/CLI I am placing a text box on a slide with my program, but I want to have bullets in the text box. I cannot seem to find how to do this? Say I have the text in a string:
Hey \rIt is cold

How do I turn that into bullets like:
 - Hey
 - It is cold

I have found:
NewSlide->Shapes[1]->TextFrame->TextRange->ParagraphFormat->Bullet->Character = 8226;

But now the issue is how do I change the indentation of the second line I have tried
txtRange->Paragraphs(1,1)->IndentLevel = 2;
txtRange->Paragraphs(2,1)->IndentLevel = 3;

But it does not change the indentation at all when my PPT shows up, but in my code when I debug it says there is a different indentation? How do I use the Paragraphs method to change the indentation?

A: The ParagraphFormat.Bullet property is read-only, however it is still a full-fledged object that has access to other objects such as Character. You can insert a bullet character using NewSlide->Shapes[1]->TextFrame->TextRange->Paragraphs[1]->ParagraphFormat->Bullet->Character = 8226. (8226 is the Unicode character value). There is also the Bullet.Type property where you can set an enumeration for example: Bullet.Type = ppBulletUnnumbered
You can set the IndentLevel of the bulleted paragraph with NewSlide->Shapes[1]->TextFrame->TextRange->Paragraphs[1]->IndentLevel = {yourInteger1through5}
Side note: In my experience, if you have a lot of work to do with programming Office documents, instead of fighting with its object model, it is best to ditch Interop and use OpenXML.


text:
Q: Inline If-Else Throws System.ArgumentException: Argument types do not match I have the following snippet:
var a = dbContext.Employees.AsQueryable();
var b = dbContext.Employees.Where(x => x.IsManager == 1);
var results = dbContext.Companies
                       .SelectMany(x => x.IsActive == 1 ? a : b)
                       .Select(x => x.Id);

I thought it's going to execute without any issues, but interestingly I got this error:

fail: Microsoft.AspNetCore.Server.Kestrel[13]
            Connection id "0HLQ6AD1S5ITB", Request id "0HLQ6AD1S5ITB:00000001": An unhandled exception was thrown by the application.
      System.ArgumentException: Argument types do not match
         at System.Linq.Expressions.Expression.Condition(Expression test, Expression ifTrue, Expression ifFalse, Type type)
         at System.Linq.Expressions.ConditionalExpression.Update(Expression test, Expression ifTrue, Expression ifFalse)
         at System.Linq.Expressions.ExpressionVisitor.VisitConditional(ConditionalExpression node)
         at System.Linq.Expressions.ConditionalExpression.Accept(ExpressionVisitor visitor)
         at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
         at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.ReplaceClauseReferences(Expression expression, IQuerySource querySource, Boolean inProjection)
         at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.CompileAdditionalFromClauseExpression(AdditionalFromClause additionalFromClause, QueryModel queryModel)
         at Microsoft.EntityFrameworkCore.Query.RelationalQueryModelVisitor.CompileAdditionalFromClauseExpression(AdditionalFromClause additionalFromClause, QueryModel queryModel)
         at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.VisitAdditionalFromClause(AdditionalFromClause fromClause, QueryModel queryModel, Int32 index)
         at Microsoft.EntityFrameworkCore.Query.RelationalQueryModelVisitor.VisitAdditionalFromClause(AdditionalFromClause fromClause, QueryModel queryModel, Int32 index)
         at Remotion.Linq.Clauses.AdditionalFromClause.Accept(IQueryModelVisitor visitor, QueryModel queryModel, Int32 index)
         at Remotion.Linq.QueryModelVisitorBase.VisitBodyClauses(ObservableCollection`1 bodyClauses, QueryModel queryModel)
         at Remotion.Linq.QueryModelVisitorBase.VisitQueryModel(QueryModel queryModel)
         at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.VisitQueryModel(QueryModel queryModel)
         at Microsoft.EntityFrameworkCore.Query.RelationalQueryModelVisitor.VisitQueryModel(QueryModel queryModel)
         at Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor.CreateQueryExecutor[TResult](QueryModel queryModel)
         at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](QueryModel queryModel)

I'm not sure what's wrong here, especially that this snippet works just fine with the correct results:
var a = dbContext.Employees.AsQueryable();
var results = dbContext.Companies
                       .SelectMany(x => a)
                       .Select(x => x.Id);

and this snipped alone works fine as well:
var b = dbContext.Employees.Where(x => x.IsManager == 1);
var results = dbContext.Companies
                       .SelectMany(x => b)
                       .Select(x => x.Id);

P.S. I'm using EF Core 2.2

UPDATE 1
Okay I was trying to simplify my problem with the above example but I think that wasn't a good idea.
So here is what I actually have: I have three main entities: Post, Employee, and, WorkGroup and three mapping entities: EmployeeWorkGroup, PostEmployee, and PostWorkGroup. The six entities have the following implementation:
class Post {
    public Guid Id { get; set; }
    public int IsGlobal { get; set; }
    public virtual ICollection<PostEmployee> Employees { get; set; }
    public virtual ICollection<PostWorkGroup> WorkGroups { get; set; }
}

class Employee {
    public Guid Id { get; set; }
}

class WorkGroup {
    public Guid Id { get; set; }
    public Guid? ParentId { get; set; }
    public string Prefix { get; set; }
}

class EmployeeWorkGroup {
    public Guid EmployeeId { get; set; }
    public Guid WorkGroupId { get; set; }
    public virtual Employee Employee { get; set }
    public virtual WorkGroup WorkGroup { get; set; }
}

class PostEmployee {
    public Guid EmployeeId { get; set; }
    public Guid PostId { get; set; }
    public virtual Employee Employee { get; set }
    public virtual Post Post { get; set; }
}

class PostWorkGroup {
    public Guid WorkGroupId { get; set; }
    public Guid PostId { get; set; }
    public virtual WorkGroup WorkGroup { get; set; }
    public virtual Post Post { get; set; }
}

Put simply, the main purpose is to send posts to employees either directly to them (using PostEmployee entity), by work groups: (using EmployeeWorkGroup and PostWorkGroup), or to all employees (by setting IsGlobal of Post to 1).
I managed to do the above, now I want to fetch the employees of a given post. The challenge is that I need to collect them from the post's designated work groups (which is hierarchical) (using EmployeeWorkGroup and PostWorkGroup) and from the post's employees (using PostEmployee entity). If the post was sent to every one (i.e., IsGlobal is 1), I need to return all employees.
This is my current attempt:
// get all employee ids from the posts work groups
Expression<Func<Post, IEnumerable<Guid>>> postEmployeesFromWorkGroups = post =>
    allWorkGroups
        .Where(workGroup => post.WorkGroups
            .Any(postWorkGroup => workGroup.Prefix.StartsWith(postWorkGroup.WorkGroup.Prefix)))
        .SelectMany(y => y.Employees
            .Where(z => !post.Employees.Any(b => b.EmployeeId.Equals(z.EmployeeId))))
        .Select(y => y.EmployeeId)
        .Distinct();

// get all employee ids from posts' immediate employees list
Expression<Func<Post, IEnumerable<Guid>>> postEmployees = post => post.Employees.Select(x => x.EmployeeId);

// return the results
public static Expression<Func<Post, IEnumerable<Employee>>> var predicate = post => post.IsGlobal == 1
    ? allEmployees
    : allEmployees.Where(x =>
        postEmployeesFromWorkGroups.Invoke(post).Contains(x.Id) ||
        postEmployees.Invoke(post).Contains(x.Id));

db.Posts.AsExpandable().Where(x=>x.Id.Equals("some-id")).Select(predicate);

With out the condition, I can execute either side of the if-else flawlessly.
P.S. I'm using LinqKit.

UPDATE 2
This is the query that I get by executing the code above (I removed one side of the if else to make it work):
SELECT [x0].[id]
FROM [posts] AS [x]
CROSS JOIN [employees] AS [x0]
WHERE (([x].[is_deleted] <> 1) AND ([x0].[is_deleted] <> 1)) AND ([x0].[id] IN (
  SELECT DISTINCT [workGroup.Employees].[employee_id]
  FROM [work_groups] AS [x1]
  INNER JOIN [employees_work_groups] AS [workGroup.Employees] ON [x1].[id] = [workGroup.Employees].[work_group_id]
  WHERE (([x1].[is_deleted] <> 1) AND EXISTS (
      SELECT 1
      FROM [work_groups_posts] AS [postWorkGroup]
      INNER JOIN (
          SELECT [x2].*
          FROM [work_groups] AS [x2]
          WHERE [x2].[is_deleted] <> 1
      ) AS [t] ON [postWorkGroup].[work_group_id] = [t].[id]
      WHERE (([x1].[prefix] LIKE [t].[prefix] + N'%' AND (LEFT([x1].[prefix], LEN([t].[prefix])) = [t].[prefix])) OR ([t].[prefix] = N'')) AND ([x].[id] = [postWorkGroup].[post_id]))) AND NOT EXISTS (
      SELECT 1
      FROM [employees_posts] AS [b]
      WHERE ([b].[employee_id] = [workGroup.Employees].[employee_id]) AND ([x].[id] = [b].[post_id]))
) OR [x0].[id] IN (
  SELECT [x3].[employee_id]
  FROM [employees_posts] AS [x3]
  WHERE [x].[id] = [x3].[post_id]
))


text:
Q: Why i can not access file second time NSData Swift I need to attach file to my email.
I created mail controller:
let mail = MFMailComposeViewController()
Then i use FileManager to get a path to my PDF file:
let filemgr = FileManager.default
let dirPaths = filemgr.urls(for: .documentDirectory, in: .userDomainMask)
let docsURL = dirPaths[0]
let newDir = docsURL.appendingPathComponent("folder").path

After that i get the file with NSData and attach it:
if let fileData = NSData(contentsOfFile: newDir+"/file.pdf") {
    mail.addAttachmentData(fileData as Data, mimeType: "application/pdf", fileName: "file.pdf")
}

And then using "present" i sent it to email form:
present(mail, animated: true)

It's ok. File has been attached. But if i cancel sending the email and try to attach it again i dont see my file. After rebuild application i can attach file once again. What is wrong?


text:
Q: Haskell compilation problem I have a problem compiling Haskell programs, that import the Text.Regex.Posix module. I have tried to isolate the problem in a small test program:
module Main () where

import Text.Regex.Posix ((=~))

main = return ()

Running the interpreter works fine:
/regex-test$ runghc Main.hs
/regex-test$

However, compiling this program with ghc yields:
/regex-test$ ghc -o tester Main.hs
Main.o: In function `rmS_info':
(.text+0xf3): undefined reference to `__stginit_regexzmposixzm0zi72zi0zi3_TextziRegexziPosix_'
collect2: ld returned 1 exit status

After this, the interpreter also stops working:
/regex-test$ runghc Main.hs

<interactive>:1:32: Not in scope: `main'
/projects/regex-test$

I can get it to work again by saving the file again without making any changes.
Does anyone have an idea how to solve this?
Some info on my system:
/regex-test$ uname -a
Linux Hello-Ubuntu 2.6.28-15-generic #52-Ubuntu SMP Wed Sep 9 10:49:34 UTC 2009 i686 GNU/Linux

and
/regex-test$ ghc-pkg list
/usr/local/lib/ghc-6.10.3/./package.conf:
Cabal-1.6.0.3, HUnit-1.2.0.3, QuickCheck-1.2.0.0, array-0.2.0.0,
base-3.0.3.1, base-4.1.0.0, bytestring-0.9.1.4, containers-0.2.0.1,
directory-1.0.0.3, (dph-base-0.3), (dph-par-0.3),
(dph-prim-interface-0.3), (dph-prim-par-0.3), (dph-prim-seq-0.3),
(dph-seq-0.3), extensible-exceptions-0.1.1.0, filepath-1.1.0.2,
(ghc-6.10.3), ghc-prim-0.1.0.0, haddock-2.4.2, haskell-src-1.0.1.3,
haskell98-1.0.1.0, hpc-0.5.0.3, html-1.0.1.2, integer-0.1.0.1,
mtl-1.1.0.2, network-2.2.1, old-locale-1.0.0.1, old-time-1.0.0.2,
packedstring-0.1.0.1, parallel-1.1.0.1, parsec-2.1.0.1,
pretty-1.0.1.0, process-1.0.1.1, random-1.0.0.1,
regex-base-0.72.0.2, regex-base-0.93.1, regex-compat-0.71.0.1,
regex-posix-0.72.0.3, regex-tdfa-1.1.2, rts-1.0, stm-2.1.1.2,
syb-0.1.0.1, template-haskell-2.3.0.1, time-1.1.3, unix-2.3.2.0,
xhtml-3000.2.0.1
~/.ghc/i386-linux-6.10.3/package.conf:
HTTP-4000.0.4, zlib-0.5.0.0

A: I'd expect at least main to be exported... i.e.
module Main (main) where

but that's not the problem here.

$ ghc -o tester -package regex-posix Main.o

Linking like this works perfectly fine.
You should either use cabal as your buildsystem, compile and link with ghc --make, or take care to expose all requisite packages manually.

A: Do exactly what you did but pass --make to ghc as well.

A: You're missing --make flag, which has GHC solve the missing library dependencies for you.


text:
Q: Use #define from macro I have #defined a preprocessor constant called CurrentClass.
The macro Method reads this constant to build a method declaration for the current class.
#define CurrentClass Foo
#define Method(x) \
    CurrentClass ## _ ## x

void Method(bar)() {

}

The preprocessor produces the following result:
void CurrentClass_bar() {

}

Obviously, CurrentClass_bar here should be Foo_bar.
The following on the other hand produces the correct result.
#define Method(class, x) \
    class ## _ ## x

void Method(Foo, bar)() {

}

For some reason, Method can't concatenate the constant CurrentClass with something else. CurrentClass alone produces the desired Foo string.
Any idea what is happening here?

A: You have to expand it twice
#define xx(x0,x1) x0 ## _ ## x1
#define x(x0,x1) xx(x0,x1)
#define Method(y) \
    x(CurrentClass,y)


text:
Q: how to get connection string from app config in c# My app.config file:
<configuration>
    <connectionStrings>
        <add name="MegaPixelBizConn"
            connectionString="Data Source=PSHERATH-PC;Initial Catalog=MegaPixelBiz;Integrated Security=True"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
</configuration>

Then I created DBConnection file:
class DBConnection
    {
        #region Database connection method
        public SqlConnection Connect()
        {
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["MegaPixelBizConn"].ToString();

            try
            {
                conn.Open();
            }
            catch
            {
            }
            return conn;
        }
        #endregion
    }

this is my login form:
SqlCommand cmd;
        DataSet ds = new DataSet();
        DBConnection db = new DBConnection();

        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtUserName.Text == "" || txtPassword.Text == "")
                {
                    lblError.Visible = true;
                    lblError.Text = "*Enter UserName and Password";
                    //MessageBox.Show(" Enter UserName and Password .");
                    return;
                }
                else
                {
                    string sql = "SELECT * FROM login_info WHERE userName = '" + txtUserName.Text + "' and password = '" + txtPassword.Text + "'";
                    cmd = new SqlCommand(sql, db.Connect());
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(ds);
                    int i = ds.Tables[0].Rows.Count;
                    if (i == 1)
                    {
                        this.Hide();
                        Home hm = new Home();
                        hm.Show();
                        ds.Clear();

                    }
                    else
                    {
                        lblError.Text = "*Not Registered User or Invalid Name/Password";
                        //MessageBox.Show("Not Registered User or Invalid Name/Password");
                        txtPassword.Text = "";
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

But when my project run, this error come:
"Object reference not set to an instance of an object."
please give me a solution. I use all suitable references

A: Basing my answer on this solution, try:
conn.ConnectionString = ConfigurationManager.ConnectionStrings["MegaPixelBizConn"].ConnectionString;

Make sure you have a reference to System.Configuration as well.
Also remember to close your connection.
EDIT
Based on your new edit, try this for your code (Note I unfortunately can't test if this works due to my PC being broken).
private void btnLogin_Click(object sender, EventArgs e)
    {
        try
        {
            if (txtUserName.Text == "" || txtPassword.Text == "")
            {
                lblError.Visible = true;
                lblError.Text = "*Enter UserName and Password";
                //MessageBox.Show(" Enter UserName and Password .");
                return;
            }
            else
            {

                using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MegaPixelBizConn"].ConnectionString))
                {

                    con.Open();

                    using (SqlCommand cmd = new SqlCommand("SELECT * FROM login_info WHERE userName = @Username AND password = @Password", con))
                    {
                        // If these two lines don't work, replace "Username" and "Password" with "@Username"/"@Password"
                        cmd.Parameters.Add(new SqlParameter("Username", txtUserName.Text);
                        cmd.Parameters.Add(new SqlParameter("Password", txtPassword.Text);
                        SqlDataReader r = cmd.ExecuteReader();
                        if(r.HasRows())
                        {
                            // this assumes that there is only one user/password and no two users with same UID and PWORD
                            this.Hide();
                            Home hm = new Home();
                            hm.Show();
                        }

                        else
                        {
                            lblError.Text = "*Not Registered User or Invalid Name/Password";
                            //MessageBox.Show("Not Registered User or Invalid Name/Password");
                            txtPassword.Text = "";
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

This will help prevent against SqlInjections as well.

A: try
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionStringNameFromWebConfig"].ConnectionString);

It should work


text:
Q: Retrieving database data - General retrieve method? My data access classes often have a method called loadDataToEntity or something similar. This method takes a resultset for instance and populates an entity class which is passed on to be used by the client.
This is nice because all methods which use a stored procedure to retrieve data can just pass the resultset to the loadDataToEntity method and get back an entity.
So it's a good way to reduce code but I often hear that you should retrieve as few columns as possible. To use my general method all stored procedures needs to fetch all columns needed for loadDataToEntity(). Also, when a column is added to the table and is retrieved by a stored procedure all other stored procedures needs to be altered and also retrieve that column.
I'm wondering if there's a better way to both achieve a general method and also retrieve different number of columns sometimes depending on the stored procedure?

public Entity getById(int id)
{
    ResultSet rs;
    //call stored procedure A and stuff
    return loadDataToEntity(rs);
}
public Entity getByName(String name)
{
    ResultSet rs;
    //call stored procedure B and stuff
    return loadDataToEntity(rs);
}
public Entity loadDataToEntity(ResultSet rs)
{
    // fill and return entity here
}

A: It really depends on how you've organised the different categories of entity within your database and how you're retrieving them.  For example, if you have one large denormalised table that can contain many entity types with each type requiring a different combination of columns being populated then you will have to retrieve all columns if you wish to retrieve all entity types in a single query.
Conversely if you've organised your database schema in a normalised form you might well have a parent entity table (which might simply contain entity ID) and multiple sub-tables, one per entity type.  In this case you could run multiple bespoke queries to retrieve the various entity types; e.g.
select E.EntityId, S.EntityName, S.EntityAge
from Entity E
inner join SubEntity S on E.EntityId = S.EntityId

or
select E.EntityId, A.EntityAddress, A.EntityGender
from Entity E
inner join AnotherSubEntity A on E.EntityId = S.EntityId

The trade-off with this second approach is the need to run multiple queries, which could in fact be slower.  However, I've resolved this in my application by running the queries in parallel and multiplexing the results together within the application.


text:
Q: How to test back end from front end? Recently I've been asked this type of questions for several times.
It is like "If you can't access the back end, how do you know if a problem is from front end or back end?", or "If you can't access the database, how do you know the performance issue in the website is from the front end or back end?", or "In front end, how can you differentiate if a problem is from front end or from back end?"
I really don't have any clue how to answer this kind of questions. Can someone help me? Thanks in advance.

A: I think that alla the 4 questions could have a great number of answers,all of them depending from the context. Backend and frontend when using ajax requests get mixer a lot.
Let's say we're talking about performance problems in a website and we don't know anything about the architecture behind.
In this case I would take a look into network stats and timelines from firebug or similar. If some sort of request to our application server is taking to much time it could be the backend. But how to be sure? maybe the frontend is asking with an ajax call for al the database entries while the pace only needs are to display just one entry.
Maybe the only good answer for all the questions would be "I would start to look for performance bottlenecks and understand their nature "


text:
Q: Estimating error from a 1% sample Say we decide to take a 1% random sample (without replacement) of a population to estimate how many individuals have some condition.
We then observe that X individuals in the sample have this condition (e.g. 800).
That's all we know. We don't know the size of the sample, the population, nor anything else.
What can we say about:

*

*The number of individuals in the population that have this condition?

*The error in the estimation?

A: Clearly a good (unbiased) estimate of the number of people in the population with the condition is $X/(1\%)=100X$.
$X$ has a Binomial distribution--but we don't know its parameters, because we lack information on the population size (except to know it is at least $800/(1\%)=800\times100=80000$). If we assume the proportion of people in the population with the condition is small, then to an excellent approximation $X$ has a Poisson distribution.  A good estimate of the sampling standard deviation of $X$ is its square root.  If that unknown proportion is large, then the sampling standard deviation of $X$ will be smaller than its square root: so let's conservatively use that square root to make sure we produce a confidence interval that isn't overly narrow.
Again because $X$ is large, its sampling distribution will also be approximately Normal.  Thus, to find a two-sided confidence interval of confidence $100-100\alpha\%$, find the upper $100-100\alpha\%$ percentile of a standard normal distribution as $Z_{1-\alpha/2}$ and form the interval
$$CI = [100(X -Z_{1-\alpha/2}\sqrt{X}), 100(X + Z_{1-\alpha/2}\sqrt{X})].$$
This has at least a $100-100\alpha\%$ chance of covering the true value.
With $X=800$ and $\alpha=0.05$ (for a $95\%$ confidence interval), $Z_{1-\alpha/2} = 1.96$ and the interval is
$$CI = [74456, 85544].$$
For a little more insight into this result, we might ask the computer to plot the limits of the CI (using a Normal approximation to a Binomial distribution) as a function of the population size.  The smallest possible size is $80000$, so let's indicate any potential population size as a multiple of this minimum.

The conservative 95% limits are plotted as horizontal gray lines while the Binomial limits are plotted as red curves.  You can see that the Binomial intervals approach the limits quickly: unless most people in the population have the condition, the conservative interval will not be too wide.
A similar plot could be produced for sampling without replacement: the intervals would be narrower at the left, but by the time the multiple reached $10$ or larger, there would be little difference between the two plots.

A: Suppose we have a population of $N$ Bernoulli trials, but $N$ is unknown. Suppose $α ∈ [0, 1]$ (.01 in the example) is known and we draw a simple random sample of size $αN$ (unknown). We observe $X$ successes (known) in the $αN$ trials. We want to estimate $K$, the number of successes among the $N$ trials in the population.
Since the sampling is without replacement, $X$ follows a hypergeometric distribution with population size $N$, sample size $αN$, and number of successes $K$. You could estimate $K$ in a Bayesian fashion, putting priors on $N$ and $K$, or you could find the maximum likelihood estimate of $K$ (which will probably be $X/α$, as you'd expect).
Of course, there's no way to compute the error between the estimate and the true value without knowing the true value. You could get a sense of the uncertainity in the estimate using a credible interval (in the Bayesian case) or a bootstrapped confidence interval (in the MLE case).


text:
Q: Get counts for every factor in one column of data.table broken out by two other columns I have a data.table containing a column, DT$Locale
that has the following entries:
DT[,unique(Locale)]

downstream                upstream                  intergenic                intron                    intron,nc                 regulatory                synonymous
non_coding_exon,nc        5_prime_UTR               splice,5_prime_UTR        splice,intron             missense                  3_prime_UTR               splice,intron,nc
splice,synonymous         splice_donor              synonymous,NMD            mature_miRNA              splice_donor,nc           splice_acceptor           3_prime_UTR,NMD
stop_gained               missense,NMD              5_prime_UTR,NMD           intron,NMD                splice,intron,NMD         splice,non_coding_exon,nc missense,splice
splice_acceptor,nc        coding_sequence,NMD       missense,splice,NMD       stop_lost                 initiator_codon           splice_acceptor,NMD

I have two other columns as well, having the following formats:
DT[,unique(Cohort)]
[1] CEU   Lupus RA    YRI  RALoci

DT[,unique(Locus)]

 [1] 1.110927656.111927656  1.194335780.195335780  1.217775877.218775877  1.236880267.237880267  1.85471701.86471701    10.52963302.53963302   10.6118896.7118896
 [8] 10.74879027.75879027   11.20046869.21046869   12.37676238.38676238   12.38077040.39077040   13.92438484.93438484   14.47539055.48539055   14.89244697.90244697
[15] 14.98090299.99090299   14.98556636.99556636   15.101213744.102213744 15.47426024.48426024   16.13885034.14885034   16.27399400.28399400   16.48056833.49056833
[22] 16.5898498.6898498     16.63172805.64172805   16.76469520.77469520   16.86513832.87513832   17.4148334.5148334     18.4824309.5824309     18.54958827.55958827
[29] 2.146859650.147859650  2.229978358.230978358  2.86605444.87605444    20.19570642.20570642   22.39592645.40592645   3.41789975.42789975    3.7782962.8782962
[36] 3.85190848.86190848    4.141037599.142037599  4.29959034.30959034    5.128060465.129060465  5.65898794.66898794    5.7513893.8513893      6.56405042.57405042
[43] 7.124946062.125946062  8.18012618.19012618    9.28933416.29933416    9.87628311.88628311

I wish to get a count of the type of each entry in DT$Locale for each combination of DT$Cohort and DT$Locus.
It seemed to me the that libary data.table represented an effective way to do this, so I tried things like:
DT[,sum(unique(Locale)),by="Locus,Cohort"], but this of returns an error - it seems to me there is likely an easy way to do this using lapply, but I have not hit on the correct syntax yet, can anyone offer a solution?
Note: in response to posts:
RALociDT[,list(count=length(unique(Locale3))),by="Locus,Cohort"]
                     Locus Cohort count
  1: 1.110927656.111927656    CEU    14
  2: 1.110927656.111927656  Lupus    15
  3: 1.110927656.111927656     RA    14
  4: 1.110927656.111927656    YRI    13
  5: 1.194335780.195335780    CEU     4
 ---
180:   9.28933416.29933416    YRI     4
181:   9.87628311.88628311    CEU    11
182:   9.87628311.88628311  Lupus    10
183:   9.87628311.88628311     RA     9
184:   9.87628311.88628311    YRI    11

Returns the number of items in the list that appear, not the count of how many times each one that does appear occurs (by Locus and Cohort).

A: Try DT[,list(count=length(unique(Locale))),by=c("Locus","Cohort")]
Trying to sum the unique values of Locale when you want the length of the vector of unique values.

A: You've confused people by not making clear the difference between "number of times each appears" and "how many of them appear". To most of us that sounds like the same thing. Perhaps you simply want to add Locale to the grouping vector:
 DT[, table(Locale, Locus, Cohort)]

So that would count the number of times each Locale-type appears within each Locus and Cohort that has any representative.


text:
Q: JSON inside XML I want to know about standard and best practice in :
Case Scenario :
If a xml standard exist by "XYZ SPECIFICATION" (ex : BPMN Specification) like :
<home>
<person name="ZEN" />
<person name="PAUL" />
<animal name="DOG" />
<animal name="CAT" />
</home>

and  "XYZ SPECIFICATION" also provide extension element to define your own tag like :
   <home>
    <person name="ZEN" />
    <person name="PAUL" />
    <animal name="DOG" />
    <animal name="CAT" />
    <extension>
    <instrument-list>
    <type name="acoustic">
      <instrument name="GUITAR" />
      <instrument name="VIOLIN"  />
    </type>
    <type name="electronic">
      <instrument name="GUITAR" />
      <instrument name="VIOLIN"/>
    </type>
    </instrument-list>
    </extension>
    </home>

Tag defined by standard are used by other client parser , they don't need to parse extension tag so i was thinking that it would be better to compress extension element using json (because json takes less space in compare to xml) :
  <home>
    <person name="ZEN" />
    <person name="PAUL" />
    <animal name="DOG" />
    <animal name="CAT" />
    <extension>
    <instrument-list>{"type":[{"name":"acoustic","instrument":[{"name":"GUITAR"},{"name":"VIOLIN"}]},{"name":"electronic","instrument":[{"name":"GUITAR"},{"name":"VIOLIN"}]}]}</instrument-list>
    </extension>
    </home>

or
<home>
    <person name="ZEN" />
    <person name="PAUL" />
    <animal name="DOG" />
    <animal name="CAT" />
    <extension>
    <instrument-list><![CDATA[ {"type":[{"name":"acoustic","instrument":[{"name":"GUITAR"},{"name":"VIOLIN"}]},{"name":"electronic","instrument":[{"name":"GUITAR"},{"name":"VIOLIN"}]}]} ]]></instrument-list>
    </extension>
    </home>

Is it violates standard and best practices ?

A: There is no "XYZ specification" per say. Though I would recommend reading up on XML and its specification because you will need to take into consideration of escaping the following characters inside your JSON for things to work nicely with XML parsers.
XML escape characters.
"   "
'   '
<   <
>   >
&   &

or use

<![CDATA[ ]]>