text:
Q: Bind parameters of two polymer components inside repeat template

I would like to bind attr and attr1 in the following example. These two parameters do not depend on data (other attributes do). When using the binding this way, there is only one shared data object between all 'rows'. I want only the two components of one iteration to be bound together.
<template repeat"{{data in dataList}}">
    <component1 attr="{{binding}}" />
    <component2 attr2="{{binding}}" />
</template>

My first idea was to bind the attributes to an variable of the data object:
<template repeat"{{data in dataList}}">
    <component1 attr="{{data.binding}}" />
    <component2 attr2="{{data.binding}}" />
</template>

This solution on the other hand is really ugly, because the model object get's view-only data attached. Because the model lives normally longer than the components, this could cause a huge overhead. Another problem is serialization, which could fail because of the attached data.
Is there any elegant solution? The only one I imagined so far is to wrap the data objects before iterating over the data set. This approach on the other hand would probably make problems with model updates...
Naive thought: Shouldn't be the scope of a variable that is only used inside of a template restricted to this template? In the special case of the repeat template furthermore to one iteration?

A: You might type-suggest your binding variable being an Object and use it like:
<polymer-element name="my-element" attributes="dataList">
  <template>

      <template repeat="{{d in dataList}}">

          {{d}} ⇒ {{binding[d]}}

      </template>

  </template>

</polymer-element>

Please be aware that the snippet above expects different items in dataList. Live preview: http://plnkr.co/edit/ez36BVUPCKW8xRSkGxOM?p=preview

Naive thought: Shouldn't be the scope of a variable that is only used inside of a template restricted to this template? In the special case of the repeat template furthermore to one iteration?

This sounds impossible for me, because (besides that this will overcomplicate the implementation) sometimes one wants to bind the variable in nested template:
<template repeat="{{a in lst}}">
  {{bound_here}}
  <template id="nested">
    {{bound_here}}
  ...

With what you suggested the binding above becomes impossible.


text:
Q: is there a way to find the oldest file using just the c++ On Linux.
I want to build a buffer of files. A new file is saved every 30 minutes . But the total number of files allowed are 'n'.
so when 'n+1'th file is created, the oldest one has to be deleted.
I found stuff like 'dirent.h' and 'struct stat' that can help access directory, list all files and get its properties.
struct stat does not however the give time of creation, but just - last modified,last accessed, time of last status changed http://pubs.opengroup.org/onlinepubs/7908799/xsh/sysstat.h.html
Please Help.
P.S: boost is not available right now.

A: On Linux there is no such thing as file creation time saved with file in file system(s) metadata. There is something close to it, but not the same: inode modification time (this is the st_ctime member of struct stat). From stat man page:

The field st_ctime is changed by writing or by setting inode
  information (i.e., owner, group group,link count, mode, etc.).

As long as you do not modify these properties and you do not write (more than zero bytes) to a file(s) - the st_ctime is your "file creation time".

A: I needed a function that deletes the oldest file in a given directory. I used system callback functions and wrote the code in C. You can call it from C++.
#include <stdio.h>
#include <dirent.h>
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>

void directoryManager(char *dir, int maxNumberOfFiles){
DIR *dp;
struct dirent *entry, *oldestFile;
struct stat statbuf;
int numberOfEntries=0;
time_t t_oldest;
double sec;

time(&t_oldest);
//printf("now:%s\n", ctime(&t_oldest));
if((dp = opendir(dir)) != NULL) {
   chdir(dir);
   while((entry = readdir(dp)) != NULL) {
      lstat(entry->d_name, &statbuf);
      if(strcmp(".",entry->d_name) == 0 || strcmp("..",entry->d_name) == 0)
         continue;
      printf("%s\t%s", entry->d_name, ctime(&statbuf.st_mtime));
         numberOfEntries++;
      if(difftime(statbuf.st_mtime, t_oldest) < 0){
            t_oldest = statbuf.st_mtime;
         oldestFile = entry;
      }
  }
}

//printf("\n\n\n%s", oldestFile->d_name);
if(numberOfEntries >= maxNumberOfFiles)
   remove(oldestFile->d_name);

//printf("\noldest time:%s", ctime(&t_oldest));
closedir(dp);
}

int main(){
    directoryManager("/home/myFile", 5);
}

A: @Onur A.'s code will run failed when directory have too many files(maybe more than 125?). Since the pointer oldestFile's value will changed on after some loops. The reason I still not found, maybe readdir() reuse that output buffer when input files more than a certain amount?
I prefer use strncpy to store oldest file's path in that code. Here's my code
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <unistd.h>

void directoryManager(char *dir, int maxNumberOfFiles) {
    DIR           *dp;
    struct dirent *entry;
    char oldestFile[128];
    struct stat    statbuf;
    int            numberOfEntries = 0;
    time_t         t_oldest;
    double         sec;

    time(&t_oldest);
    // printf("now:%s\n", ctime(&t_oldest));
    if ((dp = opendir(dir)) != NULL) {
        chdir(dir);
        while ((entry = readdir(dp)) != NULL) {
            lstat(entry->d_name, &statbuf);
            if (strcmp(".", entry->d_name) == 0 || strcmp("..", entry->d_name) == 0) continue;
            printf("%s\t%s", entry->d_name, ctime(&statbuf.st_mtime));
            numberOfEntries++;
            if (difftime(statbuf.st_mtime, t_oldest) < 0) {
                t_oldest   = statbuf.st_mtime;
                strncpy(oldestFile, entry->d_name, sizeof(oldestFile));
            }
        }
    } else {
        printf("open %s failed\n", dir);
        return;
    }

    printf("\n\n\n%s\n", oldestFile);
    if (numberOfEntries >= maxNumberOfFiles) remove(oldestFile);
    closedir(dp);

}

int main() {
    directoryManager("./myFile", 5);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Superscripts after fs - spacing When certain characters in superscripts follow certain letters ("f" at least) they collide. I'm using a numeric superscripted citation style, but the problem is more general that that as the following MWE demonstrates:
\documentclass{article}
\begin{document}
f$^6$ f$^1$ y$^6$

f\,$^6$ f\,$^1$ y\,$^6$
\end{document}

In the first line, all but the first example look right; in the second line even f$^6$ looks rather wide, the other superscripts are floating off into the middle distance. This probably applies to \footnotes (with letters) as well, I just don't happen to have a combination that demonstrates that.
Can it really be right that for certain combinations I have to add a manual correction (\kern0.05em looks about right)? Or is there a more general solution?

A: The font "knows" the adjustment needed here and makes it available as the italic correction \/

\documentclass{article}
\begin{document}
f$^6$ f$^1$ y$^6$

f\textsuperscript6 f\textsuperscript1 y\textsuperscript6

f\/\textsuperscript{6} f\/\textsuperscript{1} y\/\textsuperscript{6}  $\leftarrow$ this one

f\,$^6$ f\,$^1$ y\,$^6$

f\kern0.05em$^6$ f\kern0.05em$^1$ y\kern0.05em$^6$
\end{document}

A: Using f$^6$ is not the best way to cope with this, because it's not math, so
f\textsuperscript{6}

would be a better way. The problem is that the character "f" slightly extends beyond its bounding box. There is a built-in mechanism for coping with this, the italic correction that, despite its name, can come to rescue also for non slanted fonts, which are the ones where the problem presents more often.
Unfortunately, \textsuperscript doesn't add the italic correction, which it should, in my opinion. More unfortunately, patching \textsuperscript is not sufficient for footnotes.
Let's do a test document:
\documentclass{article}

\begin{document}
f\textsuperscript{6} f\textsuperscript{1} y\textsuperscript{6}

f\footnote{A}
f\footnote{B}
f\footnote{C}
f\footnote{D}
f\footnote{E}
f\footnote{F}

\setcounter{footnote}{0}

y\footnote{A}
y\footnote{B}
y\footnote{C}
y\footnote{D}
y\footnote{E}
y\footnote{F}

\end{document}

that outputs

Now we patch \textsuperscript and \footnote; actually a couple of internal macros need to be patched.
\documentclass{article}
\usepackage{etoolbox}

\makeatletter
\pretocmd\@textsuperscript{\/}{}{}
\patchcmd\@footnotemark{\edef}{\/\edef}{}{}
\makeatother

\begin{document}
f\textsuperscript{6} f\textsuperscript{1} y\textsuperscript{6}

f\footnote{A}
f\footnote{B}
f\footnote{C}
f\footnote{D}
f\footnote{E}
f\footnote{F}

\setcounter{footnote}{0}

y\footnote{A}
y\footnote{B}
y\footnote{C}
y\footnote{D}
y\footnote{E}
y\footnote{F}

\end{document}

and we get

You can see that the output with y is unaffected, while it's improved for f, because we essentially add \/ before \textsuperscript and \footnote. If the font is properly designed, the italic correction should compensate the right amount of spacing.
A possible patch for \supercite is
\patchcmd{\mkbibsuperscript}{\unspace}{\unspace\/}{}{}

Example.
\documentclass{article}
\usepackage{biblatex}
\makeatletter
\pretocmd\@textsuperscript{\/}{}{}
\patchcmd\@footnotemark{\edef}{\/\edef}{}{}
\patchcmd{\mkbibsuperscript}{\unspace}{\unspace\/}{}{}
\makeatother

\addbibresource{xampl.bib}

\begin{document}
\nocite{*}

f\supercite{article-full}

\printbibliography
\end{document}


text:
Q: Error:The method is not aplicable for the arguments I get the following error

Error Type:
  The method extractAccelerometer(BluetoothGattCharacteristic) in the type SensorTagData is not applicable for the arguments (BluetoothGattCharacteristic, TextView)

in the file MainActivity.java
  private void updateAccelerometerValue(BluetoothGattCharacteristic characteristic){

        double accelerometer = SensorTagData.extractAccelerometer(characteristic,mAccelerometer);      //ERROR HERE//
        mAccelerometer.setText(String.format("%.4f", accelerometer));
    }
}

and the definition of my class:
public class SensorTagData {

    public static double extractHumAmbientTemperature(BluetoothGattCharacteristic c) {
        int rawT = shortSignedAtOffset(c, 0);

        return -46.85 + 175.72/65536 *(double)rawT;
    }

    public static double extractAccelerometer(BluetoothGattCharacteristic c) {
        Integer x = c.getIntValue(FORMAT_SINT8, 0);
        Integer y = c.getIntValue(FORMAT_SINT8, 1);
        Integer z = c.getIntValue(FORMAT_SINT8, 2) * -1;

        double scaledX = x / 64.0;
        double scaledY = y / 64.0;
        double scaledZ = z / 64.0;

        return (double) scaledX scaledY scaledZ ;
    }
}

What did I do wrong?

A: The error message is pretty clear here :
Error Type: The method extractAccelerometer(BluetoothGattCharacteristic) in the
type SensorTagData is not applicable for the arguments
(BluetoothGattCharacteristic, TextView)

The method signature for extractAccelerometer specifies that the method takes only one parameter.
extractHumAmbientTemperature(BluetoothGattCharacteristic)

However, while making the call to this method, you are passing two arguments. Clearly, there is a mismatch in the number of arguments as is clear from the error message. Any reasonably good IDE should be able to point this out to you.
extractAccelerometer(characteristic,mAccelerometer);
                                    ^^^^^^^^^^^^^^
                                    extra argument

If your method declaration is correct or the way you wish to define it to be, then the simple way to fix this would be to remoe this extra parameter, and call the function like this :
extractAccelerometer(characteristic)

A: You are passing in an extra parameter, mAccelerometer. Remove that.
double accelerometer = SensorTagData.extractAccelerometer(characteristic); // <-- the extra parameter has been removed


text:
Q: Yield return inside usings If I recall correctly that when I used yield inside using SqlConnection blocks I got runtime exceptions.
using (var connection = new SqlConnection(connectionString))
{
    var command = new SqlCommand(queryString, connection);
    connection.Open();

    SqlDataReader reader = command.ExecuteReader();

    // Call Read before accessing data.
    while (reader.Read())
    {
        yield reader[0];
    }

    // Call Close when done reading.
    reader.Close();
}

Those problems were solved when I replaced yield by a List where I added items each iteration.
The same problem didn't happen yet to me when inside using StreamReader blocks
using (var streamReader = new StreamReader(fileName))
{
    string line;
    while ((line = streamReader.ReadLine()) != null)
    {
        yield return line;
    }
}

Is there any explanation why Exceptions happened in the former case and not in the latter? Is this construction advisable?
EDIT To get the error (early disposal) that I did in the past you should call the first method below:
IEnumerable<string> Read(string fileName)
{
    using (var streamReader = new StreamReader(fileName))
    {
        return Read(streamReader);
    } // Dispose will be executed before ReadLine() because of deffered execution
}

IEnumerable<string> Read(StreamReader streamReader)
{
    string line;
    while ((line = streamReader.ReadLine()) != null)
    {
        yield return line;
    }
}

The same error can be achieved with other ways of deferring execution, such as System.Linq.Enumerable.Select()

A: See this post for a good explanation of the issues with using and yield. Because you return in enumerator, the using block will already have destroyed the context before anything is accessed. The answers have good solutions, basically, either make the wrapper method an enumerator, or build a list instead.
Also it's usually more practical to have using around the reader, not the connection, and use CommandBehavior.CloseConnection to ensure resources are released when the reader's done. Though it doesn't really matter in your situation, if you ever return a data reader from a method, this will ensure the connection is closed properly when the reader is disposed.
   using(SqlDataReader reader =
             command.ExecuteReader(CommandBehavior.CloseConnection)) {
        while (reader.Read())
        {
            yield reader[0];
        }
   }

A: The compiler should handle the yield inside the using block correctly in both cases. There's no obvious reason why it should throw an exception.
One thing to be aware of is that the connection will only be disposed once you've completed iterating and/or manually disposed the enumerator object. If you expose this code in a public method then it's possible that stupid or malicious code could keep your connection open for a long time:
 var enumerable = YourMethodThatYieldsFromTheDataReader();
 var enumerator = enumerable.GetEnumerator();
 enumerator.MoveNext();
 Thread.Sleep(forever);    // your connection will never be disposed


text:
Q: I'm getting a process memory usage using PerformanceCounter. How can i display the memory usage in the same units as in task manager? private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            if ((worker.CancellationPending == true))
            {
                e.Cancel = true;
            }
            else
            {
                while (true)
                {
                    Process[] processes = Process.GetProcessesByName("GameCapture");

                    PerformanceCounter performanceCounter = new PerformanceCounter();
                    performanceCounter.CategoryName = "Process";
                    performanceCounter.CounterName = "Working Set";
                    performanceCounter.InstanceName = processes[0].ProcessName;
                    worker.ReportProgress(0, ((uint)performanceCounter.NextValue() / 1024).ToString("N0"));
                }
            }
        }

What i get is in my program 530.7 MB
In task manager same process i see it around 445.3 MB
Why is the big difference between my program and the task manager ?
what should i do if i wanted to display in my program the task manager value ?

A: Working set represents the size of all pages belonging to the process. This variable shrinks and grows when pages are moved to the page file and when they are called back into main memory, respectively. It doesn't refer exclusively to memory your application uses, as such some shared memory might be counted twice in this metric. Look here for more info.
Working set - Private is probably the metric you are looking for. Windows Task manager uses working set private as its memory usage metric. It doesn't concern itself with the page file, so you get an accurate representation of the impact on your physical ram, and it doesn't count shared objects twice.
PerformanceCounter performanceCounter = new PerformanceCounter();

performanceCounter.CategoryName = "Process";
performanceCounter.CounterName = "Working Set - Private";
performanceCounter.InstanceName = processes[0].ProcessName;


text:
Q: short list of recently changed pages in mediawiki I'm using mediawiki to run a wiki for my (relatively small <10 users) team and would like to know if its possible to get a short list of, say, the last 5 changed pages to appear in the side bar.  I know I can go to recent changes page, but my users are used to seeing a list of the most recent changed pages on every page.
Thanks

A: I saw here that you got a hack to put wikitext into the sidebar: http://www.mwusers.com/forums/showthread.php?15842-Show-recent-changes-in-sidebar
Try transcluding the recent changes into a template, then putting that template in the sidebar.


text:
Q: Java: Find the longest substring without any number and at least one upper case character Came across a programming exercise and was stuck. The problem is:

You need to define a valid password for an email but the only
  restrictions are:

*

*The password must contain one uppercase character

*The password should not have numeric digit
Now, given a String, find the length of the longest substring which
  is a valid password.   For e.g Input Str = "a0Ba" , the output should
  be 2 as "Ba" is the valid substring.

I used the concept of longest substring without repeating characters which I already did before but was unable to modify it to find the solution to above problem. My code for longest substring without repeating characters is:
public int lengthOfLongestSubstring(String s) {
    int n = s.length();
    Set<Character> set = new HashSet<>();
    int ans = 0, i = 0, j = 0;
    while (i < n && j < n) {
        // try to extend the range [i, j]
        if (!set.contains(s.charAt(j))){
            set.add(s.charAt(j++));
            ans = Math.max(ans, j - i);
        }
        else {
            set.remove(s.charAt(i++));
        }
    }
    return ans;
}

A: How about
final String input = "a0Ba";

final int answer = Arrays.stream(input.split("[0-9]+"))
    .filter(s -> s.matches("(.+)?[A-Z](.+)?"))
    .sorted((s1, s2) -> s2.length() - s1.length())
    .findFirst()
    .orElse("")
    .length();

out.println(answer);

Arrays.stream(input.split("[0-9]+")) splits the original string into an array of strings. The separator is any sequence of numbers (numbers aren't allowed so they serve as separators). Then, a stream is created so I can apply functional operations and transformations.
.filter(s -> s.matches("(.+)?[A-Z](.+)?")) keeps into the stream only strings that have at least one upper-case letter.
.sorted((s1, s2) -> s2.length() - s1.length()) sorts the stream by length (desc).
.findFirst() tries to get the first string of the stream.
.orElse("") returns an empty string if no string was found.
.length(); gets the length of the string.

A: I suggest that you split your String to have an array of strings without digit:
yourString.split("[0-9]")

Then iterate over this array (says array a) to get the longest string that contains one Upper case character:
a[i].matches("[a-z]*[A-Z]{1}[a-z]*");

A: You can use a simple array. The algorithm to use would be a dynamic sliding window. Here is an example of a static sliding window: What is a Sliding Window
The algorithm should be as follows:
Keep track of 2 indexes of the array of char. These 2 indexes will be referred to as front and back here, representing the front and back of the array.
Have an int (I'll name it up here) to keep track of the number of upper case char.
Set all to 0.
Use a while loop that terminates if front > N where N is the number of char given.
If the next char is not a number, add 1 to front. Then check if that char is upper case. If so, add 1 to up.
If up is at least 1, update the maximum length if necessary.
If the next char is a number, continue checking the following char if they are also numbers. Set front to the first index where the char is not a number and back to front-1.
Output the maximum length.

A: You can use my solution which runs in O(n) time and finds the longest part without any digit and with a capital letter:
    String testString = "skjssldfkjsakdfjlskdssfkjslakdfiop7adfaijsldifjasdjfil8klsasdfŞdijpfjapodifjpoaidjfpoaidjpfi9a";

    int startIndex = 0;
    int longestStartIndex = 0;
    int endIndex = 0;
    int index = 0;
    int longestLength = Integer.MIN_VALUE;
    boolean foundUpperCase = false;

    while(index <= testString.length()) {
        if (index == testString.length() || Character.isDigit(testString.charAt(index))) {
            if (foundUpperCase && index > startIndex && index - startIndex > longestLength) {
                longestLength = index - startIndex;
                endIndex = index;
                longestStartIndex = startIndex;
            }
            startIndex = index + 1;
            foundUpperCase = false;
        } else if (Character.isUpperCase(testString.charAt(index))) {
            foundUpperCase = true;
        }
        index++;
    }

    System.out.println(testString.substring(longestStartIndex, endIndex));

A: I am using modification of Kadane algorithm to search the required password length. You may use isNumeric() and isCaps() function or include inline if statements. I have shown below with functions.
public boolean isNumeric(char x){
    return (x>='0'&&x<='9');
}
public boolean isCaps(char x){
    return (x>='A'&&x<='Z');
}
public int maxValidPassLen(String a)
{
   int max_so_far = 0, max_ending_here = 0;
   boolean cFlag = false;
   int max_len = 0;
   for (int i = 0; i < a.length(); i++)
   {
       max_ending_here = max_ending_here + 1;
       if (isCaps(a.charAt(i))){
           cFlag = true;
       }
       if (isNumeric(a.charAt(i))){
           max_ending_here = 0;
           cFlag = false;
       }
       else if (max_so_far<max_ending_here){
           max_so_far = max_ending_here;
       }
       if(cFlag&&max_len<max_so_far){
           max_len = max_so_far;
       }
   }
   return max_len;
}

Hope this helps.

A: You don't need regular expressions. Just use a few integers to act as index pointers into the string:
int i = 0;
int longestStart = 0;
int longestEnd = 0;
while (i < s.length()) {
  // Skip past all the digits.
  while (i < s.length() && Character.isDigit(s.charAt(i))) {
    ++i;
  }

  // i now points to the start of a substring
  // or one past the end of the string.
  int start = i;

  // Keep a flag to record if there is an uppercase character.
  boolean hasUppercase = false;

  // Increment i until you hit another digit or the end of the string.
  while (i < s.length() && !Character.isDigit(s.charAt(i))) {
    hasUppercase |= Character.isUpperCase(s.charAt(i));
    ++i;
  }

  // Check if this is longer than the longest so far.
  if (hasUppercase && i - start > longestEnd - longestStart) {
    longestEnd = i;
    longestStart = start;
  }
}
String longest = s.substring(longestStart, longestEnd);

Ideone demo
Whilst more verbose than regular expressions, this has the advantage of not creating any unnecessary objects: the only object created is the longest string, right at the end.

A: There are plenty of good answers here but thought it might be of interest to add one that uses Java 8 streams:
IntStream.range(0, s.length()).boxed()
    .flatMap(b -> IntStream.range(b + 1, s.length())
        .mapToObj(e -> s.substring(b, e)))
    .filter(t -> t.codePoints().noneMatch(Character::isDigit))
    .filter(t -> t.codePoints().filter(Character::isUpperCase).count() == 1)
    .mapToInt(String::length).max();

If you wanted the string (rather than just the length), then the last line can be replaced with:
    .max(Comparator.comparingInt(String::length));

Which returns an Optional<String>.

A: I'd use Streams and Optionals:
public static String getBestPassword(String password) throws Exception {
    if (password == null) {
        throw new Exception("Invalid password");
    }
    Optional<String> bestPassword = Stream.of(password.split("[0-9]"))
            .filter(TypeErasure::containsCapital)
            .sorted((o1, o2) -> o1.length() > o2.length() ? 1 : 0)
            .findFirst();

    if (bestPassword.isPresent()) {
        return bestPassword.get();
    } else {
        throw new Exception("No valid password");
    }
}

/**
 * Returns true if word contains capital
 */
private static boolean containsCapital(String word) {
    return word.chars().anyMatch(Character::isUpperCase);
}

Be sure to write some unit tests

A: public String pass(String str){
    int length = 0;
    boolean uppercase = false;
    String s= "";

    String d= "";

    for(int i=0;i<str.length();i++){
        if(Character.isUpperCase(str.charAt(i)) == true){
        uppercase = true;
        s = s+str.charAt(i);

        }else if(Character.isDigit(str.charAt(i)) == true ){
            if(uppercase == true && s.length()>length){
            d = s;
            s = "";
            length = s.length();
            uppercase = false;
            }
        }else if(i==str.length()-1&&Character.isDigit(str.charAt(i))==false){
        s = s + str.charAt(i);
        if(uppercase == true && s.length()>length){
            d = s;
            s = "";
            length = s.length();
           uppercase = false;
        }

        }else{
        s = s+str.charAt(i);
        }
   }
  return d;}

A: Here is a simple solution with Scala
 def solution(str: String): Int = {
      val strNoDigit = str.replaceAll("[0-9]", "-")
      strAlphas = strNoDigit.split("-")

      Try(strAlphas.filter(_.trim.find(_.isUpper).isDefined).maxBy(_.size))
      .toOption
      .map(_.length)
      .getOrElse(-1)
  }

A: Another solution using tail recursion in Scala
    def solution2(str: String): Int = {

    val subSt = new ListBuffer[Char]

       def checker(str: String): Unit = {
          if (str.nonEmpty) {
        val s = str.head
        if (!s.isDigit) {
          subSt += s
        } else {
          subSt += '-'
        }
        checker(str.tail)
      }
    }

    checker(str)

    if (subSt.nonEmpty) {
      val noDigitStr = subSt.mkString.split("-")
      Try(noDigitStr.filter(s => s.nonEmpty && s.find(_.isUpper).isDefined).maxBy(_.size))
        .toOption
        .map(_.length)
        .getOrElse(-1)
    } else {
      -1
    }
  }

A: String[] s = testString.split("[0-9]");
int length = 0;
int index = -1;
for(int i=0; i< s.length; i++){
    if(s[i].matches("[a-z]*.*[A-Z].*[a-z]*")){
        if(length <= s[i].length()){
            length = s[i].length();
            index = i;
        }
    }
}
if(index >= 0){
    System.out.println(s[index]);
}

A: This is a dynamic programming problem. You can solve this yourself using a matrix. It is easy enough. Just give it a try. Take the characters of the password as the rows and columns of the matrix. Add the diagonals if the current character appended to the last character forms a valid password. Start with the smallest valid password as the initial condition.

A: I think this solution takes care of all the possible corner cases. It passed all the test cases in an Online Judge. It is a dynamic sliding window O(n) solution.
public class LongestString {

    public static void main(String[] args) {

        // String testString = "AabcdDefghIjKL0";
        String testString = "a0bb";

        int startIndex = 0, endIndex = 0;
        int previousUpperCaseIndex = -1;
        int maxLen = 0;

        for (; endIndex < testString.length(); endIndex++) {
            if (Character.isUpperCase(testString.charAt(endIndex))) {
                if (previousUpperCaseIndex > -1) {
                    maxLen = Math.max(maxLen, endIndex - startIndex);
                    startIndex = previousUpperCaseIndex + 1;
                }
                previousUpperCaseIndex = endIndex;
            } else if (Character.isDigit(testString.charAt(endIndex))) {
                if (previousUpperCaseIndex > -1) {
                    maxLen = Math.max(maxLen, endIndex - startIndex);
                }
                startIndex = endIndex + 1;
                previousUpperCaseIndex = -1;
            }
        }
        if (previousUpperCaseIndex > -1)
            maxLen = Math.max(maxLen, endIndex - startIndex);
        System.out.println(maxLen);
    }}

A: //easiest way to do it:
String str = "a0Ba12hgKil8oPlk";
        String[] str1 = str.split("[0-9]+");
        List<Integer> in = new ArrayList<Integer>();
        for (int i = 0; i < str1.length; i++) {
            if (str1[i].matches("(.+)?[A-Z](.+)?")) {
                in.add(str1[i].length());
            } else {
                System.out.println(-1);
            }
        }
        Collections.sort(in);
        System.out.println("string : " + in.get(in.size() - 1));

A: This is my solution with c#. I tested a range of strings and it gave me the correct value. Used Split. No Regex or Substrings. Let me know if it works; open to improvements and corrections.
public static int validPassword(string str)
    {
        List<int> strLength = new List<int>();
        if (!(str.All(Char.IsDigit)))
        {
            //string str = "a0Bb";
            string[] splitStrs = str.Split(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' });

            //check if each string contains a upper case
            foreach (string s in splitStrs)
            {
                //Console.WriteLine(s);
                if (s.Any(char.IsUpper) && s.Any(char.IsLower) || s.Any(char.IsUpper))
                {
                    strLength.Add(s.Length);
                }
            }

            if (strLength.Count == 0)
            {
                return -1;
            }

            foreach (int i in strLength)
            {
                //Console.WriteLine(i);

            }
            return strLength.Max();
        }

        else
        {
            return -1;
        }

    }

A: function ValidatePassword(password){
    var doesContainNumber = false;
    var hasUpperCase = false;

    for(var i=0;i<password.length;i++){
        if(!isNaN(password[i]))
            doesContainNumber = true;
        if(password[i] == password[i].toUpperCase())
            hasUpperCase = true;
    }

    if(!doesContainNumber && hasUpperCase)
        return true;
    else
        return false;
}

function GetLongestPassword(inputString){
    var longestPassword = "";
    for(var i=0;i<inputString.length-1;i++)
    {
        for (var j=i+1;j<inputString.length;j++)
        {
            var substring = inputString.substring(i,j+1);
            var isValid = ValidatePassword(substring);
            if(isValid){
                if(substring.length > longestPassword.length)
                {
                    longestPassword = substring;
                }
            }
        }
    }
    if(longestPassword == "")
    {
        return "No Valid Password found";
    }
    else
    {
        return longestPassword;
    }
}


text:
Q: Build C++ XPCOM dependency error I am building my C++ XPCOM for extension with Gecko sdk 24, but I got below error:
Error   15   error LNK2001: unresolved external symbol __imp__NS_CStringContainerInit2   xpcomglue_s_nomozalloc.lib
Error   16   error LNK2001: unresolved external symbol __imp__NS_CStringContainerFinish   xpcomglue_s_nomozalloc.lib
Error   17   error LNK2001: unresolved external symbol __imp__NS_CStringContainerInit   xpcomglue_s_nomozalloc.lib
Error   18   error LNK2001: unresolved external symbol __imp__NS_GetServiceManager   xpcomglue_s_nomozalloc.lib
Error   19   error LNK2001: unresolved external symbol __imp__NS_GetComponentManager   xpcomglue_s_nomozalloc.lib
Error   20   fatal error LNK1120: 5 unresolved externals   ..\..\..\firefoxExtension\xpi\components\gecko24\nsWin32Util.dll

Preprocessor:
MOZ_NO_MOZALLOC
XP_WIN
XP_WIN32
Additional Dependency:
xpcomglue_s_nomozalloc.lib
I used to build XPCOM with Gecko 10 and dependency are
nspr4.lib
xpcom.lib
xpcomglue_s_nomozalloc.lib
But I cannot find nspr4.lib and xpcom.lib in Gecko 24, So what's the correct settings for Gecko 24?

A: Try linking against xul.lib?  Note that this is a temporary workaround, though; upstream is getting pretty downright hostile about binary extensions, and you'll probably have better luck doing things via JS-ctypes where possible.  Haven't tested that against nomozalloc, though; not sure how well that will work.


text:
Q: Spring Data for ElasticSearch save method increments count (incorrect) even for update I'm having an issue in which the count keeps incrementing by 1 whenever I do an update to a document using save and the count's supposed to remain the same. If I create a document with save then the count is incremented by 2. Am I setting something wrong?
This is my settings for the ElasticSearch index:
{
    "aliases": {
      "case": {}
    },
    "mappings": {
      "_doc": {
        "dynamic": false,
        "properties": {
          "created": {
            "index": true,
            "type": "date"
          },
          "modified": {
            "index": true,
            "type": "date"
          },
          "type": {
                "index": true,
                "type": "keyword", "normalizer": "lower_case_normalizer"
          },
          "states": {
            "type": "nested",
            "properties": {
              "from": {
                "index": true,
                "type": "keyword", "normalizer": "lower_case_normalizer"
              },
              "to": {
                "index": true,
                "type": "keyword", "normalizer": "lower_case_normalizer"
              },
              "event": {
                "index": true,
                "type": "keyword", "normalizer": "lower_case_normalizer"
              }
            }
          }
        }
      }
    },
    "settings": {
      "index": {
        "number_of_shards": 3,
        "number_of_replicas": 2
      },
      "analysis": {
        "normalizer": {
          "lower_case_normalizer": {
              "type": "custom",
              "char_filter": [],
              "filter": ["lowercase", "asciifolding"]
          }
        }
      }
    }
  }

This is how I insert a document into ES:
public Case createCase(final Case case) throws UnableToGenerateUUIDException {

    final UUID caseId = uuidService.getNowTimeUUID();
    final Instant now = Instant.now();
    case.setCreated(now);
    case.setModified(now);
    case.setId(caseId.toString());

    return caseRepository.save(case);
}

A: This is the bug from the Chrome extension I used, not from Spring Data. I apologize for the mistake. I have verified that the count() from Spring Data reflects the correct number.


text:
Q: Column ' ' in where clause is ambiguous Error in mysql SELECT tbl_user.userid,
       tbl_user.firstname,
       tbl_user.lastname,
       tbl_user.email,
       tbl_user.created,
       tbl_user.createdby,
       tbl_organisation.organisationname
FROM   tbl_user
       INNER JOIN tbl_organisation
         ON tbl_user.organisationid = tbl_organisation.organisationid
WHERE  organisationid = @OrganisationID;

I am using this statement to do a databind. I am getting a error here.
Column 'OrganisationID' in where clause is ambiguous
What should I do is it wrong to name the OrganisationID in tbl_user same as tbl_organisation.
OrganisationID is a foreign key  from tbl_Organisation

A: Since you have two columns with the same name on two different tables (and that's not a problem, it's even recommended on many cases), you must inform MySQL which one you want to filter by.
Add the table name (or alias, if you were using table aliases) before the column name. In your case, either
WHERE tbl_user.OrganisationID

or
WHERE tbl_Organisation.OrganisationID

should work.

A: You just need to indicate which table you are targeting with that statement, like "tbl_user.OrganisationID".  Otherwise the engine doesn't know which OrganisationID you meant.
It is not wrong the have the same column names in two tables.  In many (even most) cases, it is actually perferred.


text:
Q: I would like to track inventory level in my store based on sell through. I have data in excel format I need help regarding inventory management in my stores. I have 30 stores in the city. I get weekly sales report in excel. I am using excel filters to find the stocks in these 30 stores. Its a hard work for me cos every year no of store getting raised.
Please help me, I have excel sales report. We will calculate based on sell through percentage.
For eg. I sent a 10pcs of Product A to store X. And the weekly report says that 6pcs of Product A sold in store x. So the sell through percentage is 60% and the stock in store X reduced to 4pcs of Product A. So from the warehouse I have to send 6 more pieces to store x immediately. This is for one store is okay. But for 30 stores how many filters i have to use. I used to miss datas many times. Please help me how can i solve this problem?
Thank in advance

A: Nobody is going to give a quick solution to this. But I can give you guidance.
You need to stop doing it this way and come up with a demand planning system. Of course your going to miss things doing it like this.
You need to break the problem into many small steps and have a worksheet for each.
The sheets you should consider are
stores
items
store item listing
sales history
current stock
forecast
analysis
output

Then what you are doing in your head, break down into each sheet using a mix of lookups,simple calculations and pivot tables)
Then the output sheet will have the things your need to order

A: From your description and the growth you allude to it may be that supply chain and inventory specific software is what you need. Eventually you may need to train someone else to do this and when you get there a home brew solution in Excel may not be as easily migrated to a multi user environment.
You really could do a lot of this in Excel, but you might get more bang for your buck looking at something else that can import Excel data and generate the activity analysis you need.


text:
Q: Android Imageview I have kept some .png file in res->drawable-hdpi and now, I want to show it in imageview in android. But when I refer to that image from image view, android says:

Couldn't resolve resource @drawable/my_pic.

I am using the following code :
<ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/my_pic" />

*

*I am using every file name in small letter

*The size of my_pic is 36kb

So how can I load the picture? Is this problem for size or something else. How to fix this problem. Any help ?

A: If you dont save your changes, you get a
"Couldn't resolve resource @drawable/my_pic."

Control+S  ... to save Changes, its all or..
When the R.java have a problem, only needs:
(Project -> Clean from the menus)


text:
Q: Matlab: animation I want to write a program which shows a visual animation of the orbit of satellite in 3D space, with the Earth's rotation.
I can write a code which shows a visualisation of the orbit (simply comet3()). It is possible to rotate the 3D model of the Earth either.
But I can't merge these two programs.
I've seen some Youtube videos like "Satellite Orbit Analysis and Simulation (in MATLAB)". How has he done it?
Is there any special stackexchange site for Matlab questions?

A: You can see a demo how to draw the Earth in 3D or 2D here:
Earth's Topography
To rotate an object like surface you can use function ROTATE. For example:
rotate(hsurf, [0 0 1], 20) #% rotates surface with handle hsurf around z axis by 20 deg

In addition have a look at Orbit Determination Toolbox (ODTBX).
And yeh, the best MATLAB SE site is here at SO. Just add or search for matlab tag.

UPDATE: Another beautiful Earth plot at FileExchange: http://www.mathworks.com/matlabcentral/fileexchange/25048

A: Consider doing the graphical front-end in Java. MATLAB interfaces flawlessly with Java, and it's much easier to do GUI stuff in Java. If you don't know Java and you have time, start learning, it's worth the effort as a general purpose programming language that's everywhere, and it's an invaluable companion to MATLAB.


text:
Q: SQL query takes time HI I have my application running on my production server perfectly, I updated the application some 2 days ago and since  then I experienced some performance related issue. The issue is  when  you click the button the query that runs against that button needs some 1 min or more to pull out the result and my application thus shows time out error but the same application runs fine here in my local.
I don't think its the issue related to query optimization since its  simple select query having joins  b/w 2 tables and its some 40-50 records pulled.
I am using SQL 2012 database, Is there any setting needs to be done on it?

A: Could be anything dude, without having all the information. E.g. recent degraded disk on DB server, fragmented indexes, inefficient joins, inefficient query...
Here are some general tips...

*

*User Performance Monitor (PerfMon) to capture and review any long running queries

*DBCC FREEPROCCACHE
http://msdn.microsoft.com/en-AU/library/ms174283.aspx

*

*DBCC INDEXDEFRAG

http://msdn.microsoft.com/en-au/library/ms177571.aspx

*

*or more intrusive, rebuild indexes DBCC DBREINDEX

http://msdn.microsoft.com/en-us/library/ms181671.aspx

*

*Review the health of the database server, in particular harddrives where data and log files reside. Also, check server CPUs usages.


text:
Q: Authentication flow for temporary credentials in the browser I'm trying to wrap my head around a specific proprietary authentication flow used by one of our customers, and how to implement it in IdentityServer4.
We're developing an SPA with some microservices as backend and do all our authentication/authorization with IdentityServer4. The standard workflow for the SPA is (as expected, I guess) the implicit flow using oidc-client-js (for now).
Now the problem: one of our customers has something like a homebrew SSO solution dating way back. Users basically authenticate at a central portal and get a link to the application with a token attached. This token is valid for a few minutes and contains the temporary user credentials, I need to somehow authenticate at our IdentityServer.
My first attempt was the client credentials flow. Doesn't work, as the client cannot refresh its access token later, once the initial credential token ran out (the client does not and cannot have access to permanent credentials.) My current approach would be to kind of "hijack" the implicit flow, by authenticating with the given temporary credentials and from there on out use the normal refresh cycle without further need for any credentials.
Is this a valid approach or am I completely on the wrong track? If it's valid: how do I get IdentityServer4 to do my bidding? I cannot use IResourceOwnerPasswordValidator, because that would require the client credentials flow (I think?). Is an IExtensionGrantValidator the way to go? (If so: any ideas, how to convince oidc-client-js to use a custom grant?)
Thanks for your help.
Regards,
Markus


text:
Q: Filter a list to new list please anyone can show me how to add an element from a list to another list using filter so as to make sure it is not added more than once to the new list
what i tried:
for living_thing in Animal or Bird:
if living_thing not in Zoo:
if isinstance(living_thing, Animal):
if len(self.__animal_list) < 2:
self.__animal_list.append(living_thing)


text:
Q: Serre Fibration long exact sequence I want to know if there exists something like the long exact sequence
on the following case:
Let $p : E\rightarrow B$ a continuous surjective map such that
there exists an open dense subset $U$ of $B$ such that $p$ its a trivial bundle over $p^{-1}(U)$ (i mean that $p^{-1}(U)\cong U \times T$ for some topological space $T$ and $p$ acts as the projection on the first coordinate) . For some $b\in U$ there exists something like the Serre long exact sequence
associated to the maps $p^{-1} ( b ) \rightarrow E \rightarrow B$.
In particullary interested on the case when $E,B$ and $T$ are algebraic varieties and $P$ is a quotient for the action of a reductive algebraic group on $E$.


text:
Q: Change image within a function onclick I have this function showing an image moving left and right. Is there a way to create a button in the html page that changes one of those images?
For example, if you click on "tell a joke" happy.png changes to laugh.png?
//fish moves on mouse hover
$(document).ready(function() {
    $("#swim").mousemove(function (event) {//defines the swim area
        var fish = $("#fish1");//defines the fish css styles
        var position = fish.position();
        var mousey = event.pageX;

        if (position.left > mousey) {
            $("#fish1").html("");//when swimming left, show left facing fish
        } else {
            $("#fish1").html("");//when swimming right, show right facing fish
        }

        $("#fish1").stop().animate({//animates the two images to show animated swimming
            left: event.pageX,
            top: event.pageY
        }, 300);
    });
});

A: Something like this should work
<button type="button" onclick="$('#fish1').prop('src','images/laugh.png');">tell a joke</button>


text:
Q: How can I quickly dig out 3 chunks for my basement in FTB Infinity Evolved? I'm expanding my 1 chunk house to a 4 chunks house.
I need to excavate an 3 chunk hole for my 3 floors basement (4 chunks total less 1 chunk already built).
My first thought was using a filler from BuildCraft, but that is prohibited in the overworld on the server I'm playing. Same for turtles and the BuildCraft and Extra Utilities Quarrys.
I can use a Tinker's Construct hammer and excavator but that would be slow.
So, how can I clean the area quickly for I build the basement?

A: A Tinkers' construct hammer should be able to knock that out pretty quick. Also using a /dev/null to void the Cobblestone would help with any lag.

A: If it's allowed, the fastest way to do that is to use a bunch of nukes. Then, you can build the walls back using extra utilities's builder wand.

A: A Draconic Staff of Power can mine 9x9x9 at a time.  It also can be used to void particular blocks.  Just make sure you turn it down when you bring it into your base.


text:
Q: Is there a Java equivalent to AttributeUsage(AttributeTargets.Property) from C# I am migrating a C# solution to Java and being a beginner in Java I am having difficulties migrating the below piece of code :
in C#:
[AttributeUsage(AttributeTargets.Property)]
public class DefaultField: Attribute
{
    public DefaultField()
    {
        this.HasDefaultValue = false;
    }

    public DefaultField(object defaultValue)
    {
        this.DefaultValue = defaultValue;
        this.HasDefaultValue = true;
    }

    internal bool HasDefaultValue;
    internal object DefaultValue;
}

with the below usage as example:
[DefaultField(1.0)]
public double WindowSize { get; set; }

[DefaultField("Summary")]
public string WindowTitle { get; set; }

I tried looking at interface and annotations but the only thing I was able to do was to create an interface for a specific Object e.g. Double, Int, String without even being able to check if the default value had been set
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.FIELD)
public @interface DefaultField{
    double value();
}

with the below usage:
@DefaultField(0.0)
public double val;

Any help would be greatly appreciated.

A: (Edited: My original answer was not correct, thus: edited)
Problem with annotations is that they accept only constants values, which are: primitives, String and enums.
Therefore the best solution seems to be using a String that contains serialized value and then during annotation processing parse it differently depending on the actual type of the field.
This means that for each type T you'll have to have a method Function<String,T>. For primitive types you can directly use factory methods from those types:

*

*bool:  Boolean::parseBoolean

*int: Integer::parseInt

*float: Float::parseFloat

*etc

If you want to handle enum, then you can use Enum.valueOf(Class<T> enumType,String name). For other types that are in jdk and they have some sort of factory method, you can still use it, i.e.LocalDateTime::parse).
However, if you want to be able to provide default value to any type, then you'll need to decide how you want to represent its value when it's serialized into String. You could use something generic like JSON and then use Gson library to parse it.
====================== INCORRECT (OLD) ANSWER BELOW =================
If you want to be able to pass various types of values i.e. @DefaultField(0.1) or @DefaultField("string") then you'd have to declare value() as of type Object.
It's the rest of the code that you implement for processing annotation that will have to verify if that matches type of the field (I assume that you'll just want to set to this value in case it's not initialized other way).


text:
Q: Close last div after loop with unknown iteration ( logical question ) if I have loops within an unknown iteration, how would you ensure the last div gets closed after the last run? I am not sure if my logic is right here of if there's just a more effective way.
For example, I need 6 "sub-col" (could be in a different szenario I just need 4 or 3 "sub-col").
Loop can run completely random times.
<?php

$loop_iteration = 0;

while ( have_posts() ) : the_post();

    if ( $loop_iteration % 6 == 0 ) {
        if ( $loop_iteration != 0 ) { echo '
 ';echo '
 '; }

        echo '
';
        echo '
';
    }

    echo '
';

    /* do stuff */

    echo '
';

    $loop_iteration++;

endwhile;

// here I also could make a function, but for demonstration I let it as 'if'
if (
    $loop_iteration % 6 == 1
    ||  $loop_iteration % 6 == 2
    ||  $loop_iteration % 6 == 3
    ||  $loop_iteration % 6 == 4
    ||  $loop_iteration % 6 == 5
) {
    echo '
 ';
    echo '
 ';
}

?>

Same loop, different check
<?php

$loop_iteration = 0;
$div_status     = 'close';

while ( have_posts() ) : the_post();

    if ( $loop_iteration % 6 == 0 ) {
        if ( $loop_iteration != 0 ) { echo '
 ';echo '
 '; }

        echo '
';
        echo '
';
        $div_status = 'open';
    }

    echo '
';

        /* do stuff */

    echo '
';

    $loop_iteration++;

endwhile;

if ( $div_status == 'open' ) {
    echo '
 ';
    echo '
 ';
}

?>

Thank you.

A: Just move open and closed tags outside your loop:
$loop_iteration = 0;

while ( have_posts() ) : the_post();
    if ($loop_iteration !== 0) {
        echo '
 ';
        echo '
 ';
    }
    echo '
';
    echo '
';
    echo '
';

    /* do stuff */

    echo '
';

    $loop_iteration++;

endwhile;

if ($loop_iteration > 0) {
    echo '
 ';
    echo '
 ';
}


text:
Q: Joomla! URL Rewrite creates 404 error I have a problem with my joomla and the URL Rewrite function.
I have activated this function in backend and renamed the htaccess.txt to .htaccess.
But now I get a 404 error on every menu link.
You can find the site here: (removed after solution found)
I used the standard htaccess file.
I already checked - mo_rewrite is active.
I also have added a image where you can see the system information.

Can you help?

A: You have a problem with RewriteRule settings in .htaccess. It setup to use root of server path, but your site is in directory.
For example:
http://www.skripten.at/joom25/index.php/studium-sp-481533707/finanzen-soziales
this URL works.
Try to change in .htaccess the line above or copy your site to the DocumentRoot without subfolder:
RewriteBase /joom25/

and in Joomla config find and change:
var $live_site = 'http://www.skripten.at/joom25/';

May be you need some more changes, it's what about i think in a first step.

A: It might be even more simple, at least for me it was :D
I took a look at the following article Friendly Urls and since I am on a hosted server I was almost sure that mod_rewrite was ok, so I just renamed the htaccess.txt to .htaccess, then went to the global configuration (in site) turned on the friendly url and everything worked fine.

A: i had same problem too. But the solution is not too far. Just go to you file manager and rename your htaccess.txt to  .htaccess    Remember! dont forget to put dot (.) in front of htaccess   like this ( .htaccess)   that is all you need.


text:
Q: The derived group of a reductive connected group is semisimple I am actually having some trouble in demonstrating the following result in the book Lie algebras and Algebraic groups of P. Tauvel and R. W. T. Yu:

Let $G$ be a connected reductive algebraic group. Then the derived group $\mathcal{D}(G)$ is semi-simple.

Actually, it is a direct consequence of the corollary 20.5.5 in the same book. This corollary states thant a Lie algebra is reductive if, and only if its derived algbra is semisimple.
However, I am thinking of a demonstration that does not use Lie algebras. So this is how I started:
Let $H$ is the greatest solvable, connected, normal, closed subgroup of $\mathcal{D}(G)$.
Since $\mathcal{D}(G)$ is connected, normal, closed in $G$, so is $H$ in $G$. So there is only left to use the fact that H is solvable in order to show that H is trivial. I though of showing that the radical of $\mathcal{D}(G)$ is equal to the unipotent radical of $G$ in order to use the fact that $G$ is reductive, but I did not managed to.
I am a beginner in the field of Algbraic groups so any help would be great.
Thanks a lot.
K. Y.

A: $[H,H]$ is unipotent since $G$ is reductive, $[H,H]=1$, $H=1$ since a commutative connected group is unipotent.


text:
Q: React Native - Cut-off texts
As you can see on the attached image, some texts are getting cut-off. Those marked with red-colored question mark, there's supposed to be a letter or a word, but someshow its missing. So far this issue happens in some LG in Oppo phone models, haven't seen this issue in Samsung and iPhones.
I'm using a react native boiler plate called "ignite".
Thanks in advance and more power
PS: the screenshot is taken from an LG phone, this means that it happens in production also, i can't reproduce this on development using genymotion because i can't find an LG or Oppo emulator.

A: In my experiences, this has been caused by a setting that exists on the phone that has a system-wide specific font that doesn't correlate with the default font of your app.
In order to mitigate this issue, let's say for instance your default app font is 'Lucida Grand' yet your system-wide font set in the settings of your phone is 'Roboto', you can ship your app with a TTF file of 'Lucida Grand' and set the default font of your app to 'Lucida Grand' so it avoids defaulting to the system-wide font on the phone.
See this issue reported that shows a similar situation.


text:
Q: NHibernate Futures vs CreateMultiCriteria I have used both NHibernate Futures and NHibernate CreateMultiCriteria in the past to batch sql queries.  Are there any reasons why I would want to use one or the other.  Are both of those methods equivalent or is it a matter of preference?

A: From my understanding, CreateMultiCriteria isn't supported by some databases.  I've only tried it on MySQL and SQL Server.  Check your provider's SupportsMultipleQueries property.  Futures fall back to single requests or batches if the provider supports it.


text:
Q: Qué códigos de color en CSS cargan más rápido En los archivos CSS, ¿es mejor poner el código del color o poner su nombre en letras? Me refiero a nivel de carga de los estilos.
Por ejemplo, ¿da lo mismo poner color: white; que color: #fff;?
¿Cuál de ellos cargaría más rápido?

A: Según he leído por Internet, la mejor práctica es usar código hexadecimal de 6 dígitos (no se distinguen mayúsculas de minúsculas).
Si usas colores no primarios, puede ser que depende el navegador que uses, tengan diferentes colores definidos.
Por otro lado, si deseas añadir pequeñas modificaciones a los colores, también se usan los colores rgba: rgba(255,255,255,0.8); Ese 0.8 al final es un parámetro alpha para darle más o menos opacidad al color.

A: Considero que tanto con un formato como con otro el sistema funciona correctamente, no obstante poner el código exadecimal ( #fff ) quizá sea un pelín más rápido.
Un saludo

A: No hay respuesta mejor o peor. Simplemente acuerda con tu equipo un estándard y síguelo.
O simplemente cuando empieces en un proyecto existente probablemente se usará alguno de estos estándares y tendrás que seguirlo.
Comentar que los nombres para colores se ampliaron con la especificación CSS3. Aquí puedes ver una lista completa.
Particularmente me parece una cantidad de nombres más que suficiente para cualquier proyecto. Así que trabajar únicamente con nombres de colores me parece una opción perfectamente válida.
Lo que a veces pasa es que el diseño no depende de ti, y muchas veces tienes que implementar algo que te ha pedido un maquetador, usando unos colores concretos que no puedes/debes cambiar. Y si ese color no tiene nombre dentro del estándard CSS3, deberás usar rgb/rgba/hex.


text:
Q: Invalid object name when inputting data from .aspx into sql server This is my error
Invalid object name 'userdatabase'

This is the code for the source error
enter code here
Line 27:
Line 28:             User.Open();
Line 29:             xp.ExecuteNonQuery();
Line 30:             User.Close();
Line 31:

this is the stack trace
[SqlException (0x80131904): Invalid object name 'userdatabase'.]

System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean       breakConnection, Action`1 wrapCloseInAction) +1789270

System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +5340622

System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +244

System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) +1691

System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +275

System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite, SqlDataReader ds) +1421

System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite) +177

System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +208

System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +163
   Default2.Button1_Click(Object sender, EventArgs e) in c:\Users\Calum Barnett\Documents\Visual Studio 2013\WebSites\WebSite3\Default2.aspx.cs:29

System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9614758

System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10

System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13

System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35

System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724
`

And this is the cs code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Page.IsPostBack == true)
        {
            Label1.Text = ("**Registration Succesful");
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection User = new SqlConnection("Data Source=TOSHIBA0007\\TESTSERVER;Integrated Security=True");
        {
            SqlCommand xp = new SqlCommand("Insert into userdatabase(Username, Email,  Password)Values(@Username, @Email, @Password)", User);
            xp.Parameters.AddWithValue("@Username", InputUsername.Text);
            xp.Parameters.AddWithValue("@Email", InputEmail.Text);
            xp.Parameters.AddWithValue("@Password", InputPassword.Text);

            User.Open();
            xp.ExecuteNonQuery();
            User.Close();

            if (IsPostBack)
            {
                InputUsername.Text = "";
                InputPassword.Text = "";
                InputEmail.Text = "";
                VerifyPassword.Text = "";

            }
        }
        }
    }

Any help is appreciated as i am a beginner to these kinds of errors.

A: seems to be wrong table name userdatabase or mismatch in table name...
SqlCommand xp = new SqlCommand("Insert into userdatabase(Username, Email,
    Password)Values(@Username, @Email, @Password)", User);
                xp.Parameters.AddWithValue("@Username", InputUsername.Text);
                xp.Parameters.AddWithValue("@Email", InputEmail.Text);
                xp.Parameters.AddWithValue("@Password", InputPassword.Text);


text:
Q: A fake proof of pull-back of an ample divisor is ample Let $\pi: X \to Y$ be a morphism between projective varieties and $H$ be an ample divisor on $Y$. I want to "show" $\pi^*H$ is ample on $X$ by the following argument:
Let $N_1(X)_\mathbb{R},N_1(Y)_\mathbb{R}$ be vector spaces of 1-cycles module numerical equivalence, and let $NE(X),NE(Y)$ be the cones of effective 1-cycles in $N_1(X)_\mathbb{R},N_1(Y)_\mathbb{R}$ with $\overline{NE(X)},\overline{NE(Y)}$ being their closures.
Then we have a continuous map

$\pi_*:  N_1(X)_\mathbb{R} \to N_1(Y)_\mathbb{R}$
  defined by $[C] \mapsto [\pi_* C]$.

Where if $C$ is an irreducible curve, then $\pi_* C$ is defined to be $\deg(\pi)\pi(C)$ when $\pi$ does not contract $C$, and $0$ otherwise.
$\pi_*$ induces a continuous map

$\pi_*: \overline{NE(X)} \to \overline{NE(Y)}$.

Kleiman's criterion shows: $H $ is ample $\iff$ $\forall ~C' \in \overline{NE(Y)}, H\cdot C'>0$ .
Let $C \in \overline{NE(X)}$, and $C_i \to C$. Then by projection formula, we have

$\pi^* H \cdot C_i = H \cdot \pi_* C_i > 0$, and hence $\pi^* H \cdot C>0$.

By  Kleiman's criterion again, $\pi^*H$ is an ample divisor.
I know ampleness does not behave quite well under pull back, one need some extra condition (e.g. finite morphism) to make sure $\pi^*H$ preserve ampleness. There must be something wrong in the above argument, and I will be very appreciated if someone can point it to me!!


text:
Q: Socket connected via the Internet but BufferedReader is not recieving any lines I tried to make a basic Socket communication using BufferedReader and BufferedWriter which works without any problems using "localhost" or connecting in a local network with 2 PCs using the same router. The step that's making me trouble is the connection via the Internet. I have set up a free domain at selfhost, and also added that domain to my router's dynamic dns settings and added an NAT for the used port.
After that I was able to make the ServerSocket accept the request via that domain, and were able to use the write(string + "\n") and flush() methods of the Sockets on both sides, but the BufferedReader didn't recieve any of these messages and throws an Exception because "null" is returned after a few seconds. The same occured when using the global ip, only the local and hamachii ips have worked yet.
I already opened the port in my firewall for any TCP-usage and deactivated any Anti-Virus software on my computer that could block it for a while, but nothing changed.
Both Sockets return true for the isConnected() method but the when I use the global ip / domain the ready() method return false the whole time. I have really no idea what i causing the problem but i don't think that it has something to do with my firewall because else i guess i wouldn't even be able to connect, or there would be at least a one-way communication possible. Is it a special thing with java, that there is a different communication protocol when using global IPs? What is keeping the reader busy the whole time?
I would really appreciate if anyone has a constructive idea or someone has the same problem.
Basic Example:
When using ip = "globalhost" the console outputs "message"
When using ip = global-ip or selfhost-domain the Server sends the line and closes but the Client doesn't recieve anything.
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class Client {
  public static void main(String[] args) {
    try {
      Socket client = new Socket (ip, 1034);
      InputStream in = client.getInputStream();
      BufferedReader reader = new BufferedReader(new InputStreamReader(in));
      System.out.println(reader.readLine());
      client.close();
    } catch (Exception e) {
    }
  }
}

import java.io.BufferedWriter;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    public static void main(String[] args) {
    try {
      ServerSocket server = new ServerSocket(1034);
      Socket socket = server.accept();
      OutputStream out = socket.getOutputStream();
      BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out));
      writer.write("message\n");
      writer.flush();
      server.close();
    } catch (Exception e) {
    }
  }
}

A: Try
  writer.write("message\r\n");


text:
Q: progressive (continuous) I'm reviewing a paper about pain, the author writes: "chronic pain is developed in many patients"; what they mean is "chronic pain develops in many patients."
What is a proper grammatical explanation of this correction?

A: They are two different syntactic constructions, and they mean different things in medicine. Develops is the active voice, present tense, third person singular of the verb to develop, and it's used for the progression of a disease or symptoms:
For instance, from a book on rehab medicine:

The amount of anxiety generated and possibly pain seems to be more influenced by the setting in which the pain develops rather than personality variables

They're talking about the influence of the physical environment on the growth or course of a patient's pain.
Developed, on the other hand, is the past participle of the same verb, and it shows up as a predicative adjectival complement, describing the subject of a sentence, as in this example from the journal Pain:

The increase of GH [growth hormone] secretion, at a stage of the illness when chronic pain is well developed, raises ... questions....

The meaning here is "is present or made manifest". (Ironically, well in this instance means well-along or acute.)


text:
Q: wicket: how to update a component after AjaxLazyLoadPanel? I have a page that has a status text label and a panel doing some DB query. since the query can take some time I am loading it using
add(new AjaxLazyLoadPanel("resultPanel")
{
    @Override
public Component getLazyLoadComponent(String id) {
        return new SearchResultPanel(id);
    }
};

which works very well.
My question is how to update the status label which is outside of the resultPanel, to show the number of search results?
I was thinking along the lines of addComonent(target) but I don't have a target? am i off the track?

A: Well the SearchResultPanel might look like this:
public class SearchResultPanel extends Panel implements IHeaderContributor{
   public SearchResultPanel(String id){
      super(id);
      ....
   }
   public void renderHead(IHeaderResponse response){
      response.renderOnDomReadyJavascript("alert('hello');");
   }
}

Now when it is loaded it should throw out that javascript. Another way answered on stackoverflow previously (though I do not like it) is to use an AjaxSelfUpdatingTimerBehavior, which unless the javascript should be ran more then once I do not like, and still it is less elegant in my opinion.
Look here for their answer: Wicket: reload AjaxLazyLoadPanel automatically

A: You can always obtain the current request target using RequestCycle.get().getRequestTarget(), provided that there is an active request cycle, so in theory you could do that from your lazy-loaded component constructor, check if it is an Ajax target, and add the component if it is.
Another solution is to look at the source code of AjaxLazyLoadPanel and create your own component based on it. (It's really simple but as you can see if you look at the code, there's no way you can make it expose the request target. This isn't a very OO thing to do, but as all the important functionality is wrapped in the constructor, you have very little choice..
I would avoid having to tamper with Javascript, unless there's really no other way.

A: Happened to come across this post and I have something to add as well.
The AjaxLazyLoadPanel now has an overridable method called onComponentLoaded(Component, AjaxRequestTarget) which could also solve your problem.


text:
Q: Copying a number from one workbook to another and then coverting that number to a % format is adding two extra places For example, I copy these 4 items from workbook 1 to workbook 2.
73.05
73.78
70.66
66.75
and then after pasting them and changing the formatting to percent, it turns into:
7305%
7378%
7066%
6675%
That's not what I want. I want :
73.05%
73.78%
70.66%
66.75%

A: Formatting as percent multiplicitets the value automatically by 100, because '%' means per hundred '/100', so if you want the values to look the same, you must divide them by 100.


text:
Q: Is it possible in Android to implement a recursive alarm or an alarm that overwrites itself? I'm thinking of broadcasting an Intent from my MainActivity to be received by SomeReceiver, then register a new alarm somewhere in onReceive() which fires an Intent that SomeReceiver will again catch. Is that possible? How do I overwrite the old alarm with the new one and make sure the old one is killed or unregistered?
UPDATE: The MainActivity will not be open at all times and the Alarm will need to keep being fired nonetheless.

A: First call of alarm is depends on your logic. For next alarm you should reschedule alarm in onreceive of receiver. You are right you need to call set(). Repeating time in not fixed? If yes then go ahead. U r on right track. But if repeating time is fixed, then you should use setRepeating().


text:
Q: Adding markers to google api I have followed some online tutorials for adding markers to the google maps api in android. There code is structured differently from mine but in general I saw them do it in the onCreate method. Below I have a really basic code to try and get a marker in the middle of the map, however, I get a null pointer exception. Does anyone know of a simple fix to this?
Here is the error in detail and below is my method. I have map declared as a global variable.

java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.android.gms.maps.model.Marker com.google.android.gms.maps.GoogleMap.addMarker(com.google.android.gms.maps.model.MarkerOptions)' on a null object reference

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    serviceManager = ServiceManager.getInstance(getActivity());
    userID = getString(R.string.mobile_health_client_user_id);
    client = MobileIOClient.getInstance(getContext(), userID);
    //client = MobileIOClient.getInstance(userID);
    map.addMarker(new MarkerOptions()
            .position(new LatLng(0, 0))
            .title("Hello world"));
}

I have also ran through the google tutorial which overrides onMapReady() but that method did not work for me either. I am not sure how to get it working in my code and can't find adequate resource online to assist me. Any help would be appreciated.
Thanks

A: Here is the code I use:
public class Map extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, LocationListener {

private GoogleMap mMap;
public GoogleApiClient mGoogleApiClient;
public static final String TAG = Map.class.getSimpleName();
public LocationRequest mLocationRequest;
double latitude;
double longitude;

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

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();

    // Create the LocationRequest object
    mLocationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
            .setInterval(10 * 1000)        // 10 seconds, in milliseconds
            .setFastestInterval(1 * 1000); // 1 second, in milliseconds

}

/**
 * Manipulates the map once available.
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    LatLng here = new LatLng(latitude,longitude);
    mMap.addMarker(new MarkerOptions().position(here).title("Here!"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(here));
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    Log.i(TAG, "Location services connected.");
    Location location = null;
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    }

    if (location == null) {
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }
    else {
        handleNewLocation(location);
    };
}

@Override
public void onConnectionSuspended(int i) {
    Log.i(TAG, "Location services suspended. Please reconnect.");
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
protected void onResume(){
    super.onResume();
    //setUpMapIfNeeded();
    mGoogleApiClient.connect();
}

@Override
protected void onPause() {
    super.onPause();
    if (mGoogleApiClient.isConnected()) {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        mGoogleApiClient.disconnect();
    }
}

private void handleNewLocation(Location location) {
    Log.d(TAG, location.toString());
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    LatLng latLng = new LatLng(latitude,longitude);

    MarkerOptions options = new MarkerOptions()
            .position(latLng)
            .title("I am here!");
    mMap.addMarker(options);
    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
}

@Override
public void onLocationChanged(Location location) {
    handleNewLocation(location);
    }
}

A: You should not be interacting with the map object in your activity or fragment's onCreate() method. The simple reasoning being that the map probably isn't ready yet. The proper way to handle this is to implement the OnMapReadyCallback interface and add you marker in your implementation of the onMapReady(GoogleMap googleMap) function.
Your solution will need to be slightly different if you are using a MapFragment vs a MapView, but the general idea remains the same.
Example:
public class MyActivity extends Activity implements OnMapReadyCallback {
    .
    .
    @Override
    public void onMapReady(GoogleMap googleMap) {
        map = googleMap; // Set your local instance of GoogleMap for future use
        map.addMarker(new MarkerOptions()
            .position(new LatLng(0, 0))
            .title("Hello world"));
    }
    .
    .
}

If you are using a MapView, you will need to get a handle to your view in your layout and explicitly call map.getMapAsync(this) in order to attach the onMapReady() listener.
I hope this helps!

A: Write simply in onMapReadygoogleMap.addMarker(new MarkerOptions().position(new LatLng(0, 0));


text:
Q: Delaying progress indicator I have the following code in my layout page so whenever an Ajax request is sent, it'll show a progress-please-wait panel.
but I'm not sure how to put a delay to it.
$(document).ajaxStart(function (event, XMLHttpRequest, ajaxOptions) {
    $('#wait').modal('show');
});

$(document).ajaxComplete(function (event, jqXHR, ajaxOptions) {
    $('#wait').modal('hide');
});

I tried:
$(document).ajaxStart(function (event, XMLHttpRequest, ajaxOptions) {
    setTimeout("$('#wait').modal('show')", 3000);
});

But if a request takes less than 3000 ms, the in progress indicator shows up and never goes away becaue ajaxComplete is already done by then.
So I guess in the setTimeout, I have to check if the current ajax is already done, if it is, then do not bother to show the panel, else, show it and ajaxComplete will hide it later. However, I do not know how to check for its current status in ajaxStart.

A:
So I guess in the setTimeout, I have to check if the current ajax is already done, if it is, then do not bother to show the panel, else, show it and ajaxComplete will hide it later. However, I do not know how to check for its current status in ajaxStart.

Make a simple boolean flag for it.
var isLoading = false;
$(document).ajaxStart(function (event, XMLHttpRequest, ajaxOptions) {
    isLoading = true;
    setTimeout(function() {
        if (isLoading)
            $('#wait').modal('show');
    }, 3000);
});
$(document).ajaxComplete(function (event, jqXHR, ajaxOptions) {
    isLoading = false;
    $('#wait').modal('hide'); // won't do any harm if already hidden
});

Alternatively, you could save the timeout id in a variable and clear it when the ajax completes before the modal is shown:
var timer = null;
$(document).ajaxStart(function (event, XMLHttpRequest, ajaxOptions) {
    if (timer)
        return; // when multiple requests are sent at same time
    timer = setTimeout(function() {
        timer = null;
        $('#wait').modal('show');
    }, 3000);
});
$(document).ajaxComplete(function (event, jqXHR, ajaxOptions) {
    if (timer)
        clearTimeout(timer);
    else
        $('#wait').modal('hide');
    timer = null;
});

Btw, 3s seem very long to me. An UI that doesn't react after ~200ms does feel unresponsive, so I'd suggest showing the modal much earlier.


text:
Q: change background-color of navbar when scroll event with vuejs how can I change background-color of navbar when scrolling event with Vuejs. I tried V-scroll event by using this answer How to change css while scrolling in Vue
 this is the code but it does not work?

          <button id="mobBtn" @click="displayList">

          </button>

            Home

            About

            Blog

            Contact

A: Add event listener to your window and assign new data to your data model and update it's value when scroll event is started. see code below
date model
data: {
    scrollPosition: null
},

methods
methods: {
    updateScroll() {
       this.scrollPosition = window.scrollY
    }
}

mounted hook
mounted() {
    window.addEventListener('scroll', this.updateScroll);
}

Now in your case, put this in your navbar
 50}">
      ...
      ...

and put css to your change_color class


text:
Q: Nginx git server returns error 500 I'm trying to set up an nginx remote server (with ssl) for a bare git repository, but getting error 500 when trying git clone https://my.domain.com/repo.git from git bash (windows 7 machine).
My current configuration looks like this.
Nginx server config:
server {
  listen: 80;
  server_name my.domain.com;
  # Redirect all non-HTTPS traffic to the HTTPS version
  return 301 https://my.domain.com;
}

server {
  listen 443 ssl;
  server_name my.domain.com;
  root /var/www/git;
  index index.html;

  ssl_certificate /etc/nginx/ssl/nxing.crt;
  ssl_certificate_key /etc/nginx/ssl/nginx.key;

  access_log /var/www/git/git.access.log;
  error_log /var/www/git/git.error.log;

  auth_basic "Git authentication required";
  auth_basic_user_file /etc/nginx/users_git;

  location / {
    client_max_body_size 0;

    include /etc/nginx/fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /usr/libexec/git-core/git-http-backend;
    fastcgi_param GIT_HTTP_EXPORT_ALL "";
    fastcgi_param GIT_PROJECT_ROOT /repo.git;
    fastcgi_param PATH_INFO $1;
    fastcgi_param REMOTE_USER $remote_user;

    fastcgi_pass unix:/var/run/fcgiwrap.socket;
  }
}

I've consulted this source for help with setting up the fcgiwrap: http://knowledgebase.cc/en/software-en/linux-en/how-to-install-fcgiwrap-to-serving-cgiperl-scripts-in-nginx/
The exact error I receive upon running git clone http://my.domain.com/repo.git:

Cloning into 'repo'... fatal: unable to access 'http://my.domain.com/repo.git': The requested URL returned error:
  500

This is the extract from the URL's access log:

1xx.xxx.xxx.xx - - [06/May/2015:17:29:02 +0200] "GET / HTTP/1.1" 500 5 "-" "git/1.9.5.msysgit.1"

The URL's error log is empty.
I've already gone through every step and detail another person described in this post: https://superuser.com/questions/719949/centos-5-nginx-git-http-backend
but I had no success so far.
UPDATE #1
I've tried commenting out the fastgci parameters in the nginx server config's location setting and specifying the location url itself, resulting in this
location /repo.git {
  client_max_body_size 0;

  [...] commented fastcgi params [...]
}

The result is now that when I try git clone http://my.domain.com/repo.git I get the following output in git bash:

Cloning into 'repo'...
  Username for 'http://my.domain.com': git
  Password for 'http://git@my.domain.com': ...
  fatal: http://my.domain.com/repo.git/info/refs not valid: is this a git repository?

But I can reach both http://my.domain.com and http://my.domain.com/repo.git in the browser
Update #2
I had a loot at this website: http://weininger.net/configuration-of-nginx-for-gitweb-and-git-http-backend.html, which helped me solve my issue, somehow.
My final Nginx server configuration now looks like this:
server {
  listen 80;
  server_name my.domain.com;
  # Redirect all non-HTTPS traffic to the HTTPS version
  rewrite ^ https://$server_name$request_uri? permanent;
}

server {
  listen 443 ssl;
  server_name my.domain.com;
  root /var/www/git;
  index index.html;

  ssl_certificate /etc/nginx/ssl/nginx.crt;
  ssl_certificate_key /etc/nginx/ssl/nginx.key;

  access_log /var/www/git/git.access.log;
  error_log /var/www/git/git.error.log;

  auth_basic "Git authentication required";
  auth_basic_user_file /etc/nginx/users_git;

  location ~ ^.*\.git/(HEAD|info/refs|objects/info/.*|git-(upload|receive)-pack)$ {

    include /etc/nginx/fastcgi_params;
    fastcgi_param SCRIPT_FILENAME /usr/libexec/git-core/git-http-backend;
    fastcgi_param GIT_HTTP_EXPORT_ALL "";
    fastcgi_param GIT_PROJECT_ROOT /var/www/git;
    fastcgi_param PATH_INFO $uri;
    fastcgi_param REMOTE_USER $remote_user;

    fastcgi_pass unix:/var/run/fcgiwrap.socket;
  }
}

This allowed me to properly do a git clone and git pull without any errors, but git push would give me the following error

Counting objects: 4, done.
  Delta compression using up to 4 threads.
  Compressing objects: 100% (2/2), done.
  Writing objects: 100% (3/3), 312 bytes | 0 bytes/s, done.
  Total 3 (delta 0), reused 0 (delta 0)
  error: unpack failed: unpack-objects abnormal exit
  To http://my.domain.com/repo.git
   ! [remote rejected] master -> master (n/a (unpacker error))
  error: failed to push some refs to 'http://my.domain.com/repo'

Update #3
Seems the unpack failed error was due to a permission problem. Even though I did chown -R git:git repo.git I could not push to the repository. But doing chown -R git:nginx repo.git solved it. Which I partially understand, considering that it's the fastcgi script doing the writing (I suppose?), which in turn is spawned by Nginx.
Some clarification or deeper explanation of why these settings work the way they do would be great though, in order to learn and understand things better, if anybody can.

A: Solved my issues through a lot of (re)search and trial/error. The steps I've taken are written down in detail in the question's updates.


text:
Q: Replace operation does not function correctly I am trying to replace '/' character with '%252F' in Brackets. However it returns me '%2F'. Although '%2F' might mean something similar, I need particularly '%252F'. I am wondering how to solve this issue. Below you can see how I am trying to do that.
label = '146621/0';
label.replace("/","%252F");


text:
Q: Call MS Studio C dll from Java JNA - error msg My hello.c file in MS Studio 2015 Win 10:
#include <stdio.h>

extern void hello();

void hello()
{
    printf("Hello from C");
}

My Java file in eclipse:
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;

public class PaMMTE {

       public interface CPaMMTE_testDLL extends Library {
           public void welcome();
       }

       public static void main(String[] args) {
           CPaMMTE_testDLL lib = (CPaMMTE_testDLL) Native.loadLibrary("TestCallingFromJava", CPaMMTE_testDLL.class);
           lib.welcome();
           System.out.println("Hello, World");
       }
}

(The name of the dll is CPaMMTE_testDLL.)
Anyway, I've got the following error message:
> Exception in thread "main" java.lang.UnsatisfiedLinkError: %1 is not a
> valid Win32 application.
>
>   at com.sun.jna.Native.open(Native Method)   at
> com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:288)     at
> com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:427)     at
> com.sun.jna.Library$Handler.<init>(Library.java:179)  at
> com.sun.jna.Native.loadLibrary(Native.java:569)   at
> com.sun.jna.Native.loadLibrary(Native.java:544)   at
> PaMMTE.main(PaMMTE.java:18)

I'm pretty sure that the configuration is wrong in MS Studio project.
I've tried several different configurations without any good result.
I've changed on the MS Studio Win 10 configuration:
> Exception in thread "main" java.lang.UnsatisfiedLinkError: Error
> looking up function 'hello': The specified procedure could not be
> found.
>
>   at com.sun.jna.Function.<init>(Function.java:245)   at
> com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:566)     at
> com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:542)     at
> com.sun.jna.NativeLibrary.getFunction(NativeLibrary.java:528)     at
> com.sun.jna.Library$Handler.invoke(Library.java:228)  at
> com.sun.proxy.$Proxy0.hello(Unknown Source)   at
> PaMMTE.main(PaMMTE.java:14)

The second one looks better. :-)
My first problem was that I used 32-bit compile instead of 64 bit. But I still don't find the right MS config.
Thanks for your help!
EDIT:
Old pictures about the configuration are removed (I can add only two pic links).
The working MS Studio C configuration is:
Create working MS Studio C dll
As I promised, I put here a working version (still not really understand why it is working).
Java is the same!
C code:
include
__declspec(dllexport) void hello()
{
    printf("Hello from C");
}

Should I use extern? Or it is only relevant in case of c++ wrapping?


text:
Q: Error in windows docker desktop kubernetes In kubernetes on windows docker desktop when I try to mount an empty directory I get the following error:
error: error when retrieving current configuration of:
Resource: "/v1, Resource=pods", GroupVersionKind: "/v1, Kind=Pod"
Name: "", Namespace: "default"
Object: &{map["apiVersion":"v1" "kind":"Pod" "metadata":map["annotations":map["kubectl.kubernetes.io/last-applied-configuration":""] "namespace":"default"] "spec":map["containers":[map["image":"nginx:alpine" "name":"nginx" "volumeMounts":[map["mountPath":"/usr/share/nginx/html" "name":"html" "readOnly":%!q(bool=true)]]] map["args":["while true; do date >> /html/index.html; sleep 10; done"] "command":["/bin/sh" "-c"] "image":"alpine" "name":"html-updater" "volumeMounts":[map["mountPath":"/html" "name":"html"]]]] "volumes":[map["emptyDir":map[] "name":"html"]]]]}
from server for: "nginx-alpine-emptyDir.pod.yml": resource name may not be empty

The error message seems a bit unclear and I cannot find what's going on.
My yaml configuration is the following:
apiVersion: v1
kind: Pod
spec:
  volumes:
    - name: html
      emptyDir: {}
  containers:
    - name: nginx
      image: nginx:alpine
      volumeMounts:
        - name: html
          mountPath: /usr/share/nginx/html
          readOnly: true
    - name: html-updater
      image: alpine
      command: ["/bin/sh", "-c"]
      args:
        - while true; do date >> /html/index.html; sleep 10; done
      volumeMounts:
        - name: html
          mountPath: /html

A: Forgot to add metadata name
metadata:
  name: empty-dir-test

Code after change is:
apiVersion: v1
kind: Pod
metadata:
  name: empty-dir-test
spec:
  volumes:
    - name: html
      emptyDir: {}
  containers:
    - name: nginx
      image: nginx:alpine
      volumeMounts:
        - name: html
          mountPath: /usr/share/nginx/html
          readOnly: true
    - name: html-updater
      image: alpine
      command: ["/bin/sh", "-c"]
      args:
        - while true; do date >> /html/index.html; sleep 10; done
      volumeMounts:
        - name: html
          mountPath: /html


text:
Q: lateinit property vkUserRepository has not been initialized. Why? I try "kotlin - spring boot 2 - jpa".I just started to study spring-boot.
I have model, repository and app files. I`m use start.spring.io for starting.I've seen examples with web, but I don't need a web.
I have error during compilation. Why ?
How can I fix this error?
2018-12-21 13:26:02.732  INFO 28188 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL95Dialect
2018-12-21 13:26:02.923  INFO 28188 --- [           main] o.h.e.j.e.i.LobCreatorBuilderImpl        : HHH000421: Disabling contextual LOB creation as hibernate.jdbc.lob.non_contextual_creation is true
2018-12-21 13:26:02.929  INFO 28188 --- [           main] org.hibernate.type.BasicTypeRegistry     : HHH000270: Type registration [java.util.UUID] overrides previous :         org.hibernate.type.UUIDBinaryType@396ef8b2
2018-12-21 13:26:03.335  INFO 28188 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-12-21 13:26:04.150  INFO 28188 --- [           main] r.k.v.VkUsersSkillApplicationKt          : Started VkUsersSkillApplicationKt in 4.348 seconds (JVM running for 4.905)
Exception in thread "main" kotlin.UninitializedPropertyAccessException: lateinit property vkUserRepository has not been initialized
  at     ru.program.vkUsersSkill.VkUsersSkillApplicationKt.main(VkUsersSkillApplication.kt:17)

My program:
VkUser.kt
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.Id
import javax.persistence.Table

@Entity
@Table (name = "vk_users")
data class VkUser(
    @Id
    @Column(name = "user_id")
    var userId: Long = 0L,

    @Column(name = "access_token")
    var accessToken: String = "",

    @Column(name = "alias")
    var alias: String = "",

    @Column(name = "login")
    var login: String = "",

    @Column(name = "password")
    var password: String = ""
)

VkUserRepository.kt
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
import ru.program.vkUsersSkill.models.VkUser

@Repository
interface VkUserRepository: JpaRepository<VkUser, Long>

VkUsersSkillApplication.kt
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import ru.program.vkUsersSkill.repositories.VkUserRepository

@Autowired
lateinit var vkUserRepository: VkUserRepository

@SpringBootApplication
class VkUsersSkillApplication

fun main(args: Array<String>) {
  runApplication<VkUsersSkillApplication>(*args)
  vkUserRepository.findAll()
}

application.properties
spring.jpa.database-platform =org.hibernate.dialect.PostgreSQL95Dialect
spring.datasource.url=jdbc:postgresql://localhost:5432/vkadmin
spring.datasource.username=vkadmin
spring.datasource.password=pass
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true

A: We can create start class-bean
@Component
class StartHere {
@Autowired
lateinit var vkUserRepository: VkUserRepository
fun runHere() {
    var users = vkUserRepository.findAll()
    println(users)
}

//TODO all other program code here
}

Then in MAIN function we get 'application context' and run our bean-starter
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import ru.program.vkUsersSkill.init.StartHere

@SpringBootApplication
class VkUsersSkillApplication

fun main(args: Array<String>) {
val context = runApplication<VkUsersSkillApplication>(*args)
val start = context.getBean(StartHere::class.java)
start.runHere()
}

All is done.
Thanks to @Jonathan Johx.


text:
Q: Using node as api and static I'm extremely new to web development. I've bought a domain name (let say 'domain.com' and what I want is to have two links: one 'api.domain.com' with MySql database and Node server for API; and second is: 'domain.com' with some client-side app which will call to 'api.domain.com' for data. Same for native mobile apps which will call 'api.domain.com'.
What NodeJS frameworks will you suggest to best serve this needs. And how are those "domain tricks" called, so I can read about how to organise it.

A: *

*For bare web framework and middleware abstraction, please see express

*For Extensive API development and integration, please see loopback

*For enterprise features to manage your deployments, please see strongloop


text:
Q: Can we use single thread to consume multiple disruptor? I have different data coming from different source (multicast, tcp).
I'm intending to use different Disruptor to manage each type of data individually while I would like to consume all these data by a single thread.
Is such model Disruptor designed for?
If so, the Disruptor constructor comes with Executor / ThreadFactory which implies the data inside should be managed by thread pool. How can we share the same thread to multiple disruptor?

A: The disruptor library probably won't do that without your effort; I'm not sure what the entire API looks like. There is an api on the ring buffer to get(sequence) and get cursor, at the very least.
But if you understood the pattern, obviously the consumer thread isn't blocked in any API, so a custom implementation could easily poll various ring buffers, especially instead of spinning a busy-wait loop.
However, you might loose some of the cpu cache locality by jumping from one task+memory to another.


text:
Q: Поиск диапазона чисел в mongodb Есть таблица в mongodb, следующего формата
{
    "_id" : "14",
    "Command" : "some text",
    "Content" : "some text"
}

Поле _id формата String. Как осуществлять поиск диапазона чисел в такой таблице с помощью C# (да и в самом mongo тоже не получается)?
Вот как я пытаюсь искать
var filter = Query.And(Query<FT.MogoBase.Commands>.GTE(l => l._id, from),
            Query<FT.MogoBase.Commands>.LT(l => l._id, to));
var ret = collectionCommands.Find(filter).ToList();

_id в базе String формата, а мне надо искать как int.
В mongodb выходит следующий вид
{ "_id" : { "$gte" : 2, "$lt" : 5475 } }

Но естественно так ничего не находит.

A: В mongoshell вы можете отобрать следующей инструкцией:
db.test.find("this._id > 2 && this._id < 5475")

или
db.test.find( { $where: function() { return (parseInt(this._id) > 2 && parseInt(this._id) < 5475) } } );

В этом запросе поле будет автоматически преобразовано в число. Это повлияет на производительность выполнения каждого запроса. Также при таком запросе не будут использоваться индексы.
Но лучше всего преобразовать поле _id в число. Вы же по нему ищите как по числу. Сравнение строкового типа выполняется по другим правилам.
Преобразовать можно следующим скриптом в основной таблице:
db.test.find().snapshot().forEach(function(doc) {
    var id = doc._id;
    doc._id = new NumberInt(id);
    db.test.insert(doc);
    db.test.remove({_id : id});
})

и в ссылающейся на нее:
db.test2.find().forEach(function(doc) {
    var intVal = new NumberInt(doc.extid);
    db.test2.update(
        {_id: doc._id},
        {$set: {extid: intVal}}
    );
})

A: Как говорилось в предыдущем ответе Лушее вариант преобразовать поле _id в число. Лучший способ сделать это; это с помощью "Bulk" API для максимальной эффективности.
var bulk = db.test.initializeOrderedBulkOp();
var count = 0;
db.test.find().forEach(function(doc) {
    bulk.find({ "_id" : doc._id }).removeOne();
    doc._id = parseInt(doc._id);
    bulk.insert(doc);
    count++;
    if(count % 100 == 0) {
        // выполнить каждые 100 операций и повторного инициализации
        bulk.execute();
        bulk = db.test.initializeOrderedBulkOp();
    }
} )

if(count > 0) {
    // очистить очереди
    bulk.execute();
}

Теперь можно писать запрос:
db.test({ "_id" : { "$gte" : 2, "$lt" : 5475 } })