Gnuplot linear fit with f(x) = a*x

Question: I have a following dataset:
0 6
25 27
91 25
160 21
190 32
335 28

How to plot a linear regression in form y=ax + 6 so that the line would contain point (0,6)? I tried the following code:
f(x) = a*x +6
fit f(x) "data.txt" u 1:2 via a
plot "data.txt" u 1:2 w p pt 7, f(x) w l

Sum of distances of upper points is larger than distances of lower points (in fact we see only one lower point: (335,28) ). How to fit f(x) so that the sum of distances would be equal?
Comment: Maybe I do not fully understand your problem. You have a few of points and want to have linear regression but point `(0,6)` must be exactly on the line? What do you mean with "inaccurate result"? What would be an "accurate" result? Can you please show your graph and explain what you think is not correct?
Comment: Thank you very much for reply. I added some details to my post.
Answer: Fitting with gnuplot is a least-square fit, i.e. the algorithm minimizes the sum of the squares of the differences between the data points and f(x) (check help fit).
In contrast, apparently you are looking for summing up the differences between data points and f(x) and trying to make the sum zero. That's not the same.
As long as your function is as simple as a*x+b you can use stats to calculate the slope of your line as you expected.
Code:
### different ways of "fitting"
reset session

$Data <<EOD
0 6
25 27
91 25
160 21
190 32
335 28
EOD

b = 6
f(x) = a0*x + b

# least square fit
set fit nolog quiet
fit f(x) $Data u 1:2 via a0

# make sum of difference to h(x) to zero
stats $Data u 1:2 nooutput
h(x) = a1*x + b
a1 = (STATS_sum_y - STATS_records*b)/STATS_sum_x

set key top left

plot $Data u 1:2 w p pt 7, \
     f(x) w l ti sprintf("Least square fit: f(x)=a0*x+b, a0=%g",a0), \
     h(x) w l ti sprintf("Sum of differences to zero: h(x)=a1*x+b, a1=%g",a1), \
     $Data u 1:2:(0):(h($1)-$2) w vectors lc "red" nohead ti "Differences to h(x)"
### end of code

Result:
Comment: Thank you very much! It is just what I was looking for!

Gnuplot linear fit with f(x) = a*x


how to filter firestore data on client side in react

Question: I get data from firestore like this
  const [projects, setProjects] = useState([]);

  const getProjects = (sortBy = "NAME_ASC") => {
    const unsubscribe = firebase
      .firestore()
      .collection("projects")
      .orderBy(SORT_OPTIONS[sortBy].column, SORT_OPTIONS[sortBy].direction)
      .onSnapshot((snapshot) => {
        const newProjects = snapshot.docs.map((doc) => ({
          id: doc.id,
          ...doc.data(),
        }));

        setProjects(newProjects);
      });
    return () => unsubscribe();
  };

I have a from to apply a filter agains the name key ob the data object like this:
<form>
    <input
       type="text"
       value={filter}
       onChange={(e) => applyFilter(e.currentTarget.value)}
    />
</form>

and here is my filter function:
  const applyFilter = (filter) => {
    setFilter(filter);
    const filtered = projects.filter((e) => e.name.includes(filter));
    setProjects(filtered);
  };

The filter works fine, but once my data is filtered, I can't undo the filter or filter something complely different because with setProjects(filtered) I overwrite the entire data fetched from firestore.
How can I accomplish that?
Comment: you should be doing that on the view otherwise you need a copy which you ll always filter against
Comment: What means "on the view"?
Answer: When you setProjects in your filter, its overwriting the data which is held within projects. This is obviously bad, as you are losing your list of data while you are filtering.
Its best to keep your original data, projects and then also keep state for filter results, filteredProjects and conditionally choose which to use as the data source, depending on if you have a filter.
  const [projects, setProjects] = useState([]); //Original data, dont mutate
  const [filteredProjects, setFilteredProjects] = useState([]); //holds filter results
  const [filter, setFilter] = useState(""); //filter string (not sure where you keep this)

  const getProjects = (sortBy = "NAME_ASC") => {
    const unsubscribe = firebase
      .firestore()
      .collection("projects")
      .orderBy(SORT_OPTIONS[sortBy].column, SORT_OPTIONS[sortBy].direction)
      .onSnapshot((snapshot) => {
        const newProjects = snapshot.docs.map((doc) => ({
          id: doc.id,
          ...doc.data(),
        }));

        setProjects(newProjects);
      });
    return () => unsubscribe();
  };

Your filter function will now update the filteredProjects state (so it does not overwrite your projects state
  const applyFilter = (filter) => {
    setFilter(filter);
    const filtered = projects.filter((e) => e.name.includes(filter));
    setFilteredProjects(filtered);
  };

now you can conditionally choose which set of data to provide to your view, depending if you have a filter value or not. I do not know what your return method looks like or where you are using it.. but here I have mocked a component called "ProjectsView" which displayed the projects based on the filter.
<form>
    <input
       type="text"
       value={filter}
       onChange={(e) => applyFilter(e.currentTarget.value)}
    />
</form>
<ProjectsView
   projectData={filter.length > 0 ? filteredProjects : projects} //choose the filteredProjects if there is a filter string length is greater than 0, otherwise the original list
/>


How to correctly apply a CSS style to all the images in a div having a specific class?

Question: I have the following HTML:

I am trying to set the CSS property of the img tag inside the div having class="group-item" in this way:
.groups-item img {
    float: left;
    margin-right: 15px;
    width: 80px;
}

but it does not work and it is not applied to the previous img tag (I used FireBug and I can see that the style is not applied)
Why? What am I missing? How can I correctly apply the style to all the img tags inside the div having class="group-item"?
Comment: You have `.groups-item` but use `group-item`.
Answer: .group-item img {
    float: left;
    margin-right: 15px;
    width: 80px;
}

should work, I removed the s from groups- in the css declaration
Comment: Seriously not worth an answer
Comment: @mplungjan - fair enough, still, you have 50k points, I have 1.5k, I'm just trying to pull myself up a bit being new to the site, so I'll take some low hanging fruit here and there
Comment: Because I edited it before I tested to see what was wrong. Then I commented that it was a spelling mistake instead of answering it was a spelling mistake
Answer: Problem is in your Class Define
You gave Class name group-item in HTML where as You use .groups-item in CSS.
Use it like
.group-item a img {
    float: left;
    margin-right: 15px;
    width: 80px;
}


How to create a field that shows a number in an app and can be changed by admin

Question: First of all thanks for thinking with me!
I am new in making apps and need to make an one page mobile app. The app needs a field in the middle with a number, the number in that field needs to be changed by an admin so visitors can see the status (the number represents the status). Anyone an idea to fix this?
Comment: "Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question."
Answer: You will have to use a web service which will be fetching that number from server,
also you have to setup a mechanism through which admin can set the number for app users.
Comment: Yes, thats what I meant. Any suggestions in how to set up the mechanism to set the number?
Comment: No I have nothing build yet.
Comment: You need a back-end for your app to store data which can be shared among your user and admin apps. Depending upon the current and future requirements you may choose among many options available i.e. develop a custom backend for your app in PHP or .net or any other. or there are https://aws.amazon.com/mobile/ and other similar services known as mobile backend as a service.


Will a backdraft damper in a air return duct cause issues with the gas furnace?

Question: In our attic is a gas furnace for the 2nd floor. The attic is not insulated (except for the attic floor which is the 2nd floor ceiling). The air return for this furnance is in the 2nd floor ceiling on the hallway (looks like a rectangle, approx. 20ish inches in diameter). Cold air is leaking out of this air return vent. I assume it's not attic air that leaks into the 2nd floor through this return duct, but the hot air rises into this duct, cools down and then sinks into the 2nd floor. I insulated the return duct in the attic with HVAC insulation which made things better. Now I am wondering if a backdraft damper would improve the situation. The flexible hose from the damper has 13 inch diameter and I bought a fitting backdraft damper. It opens easily and shouldn't put too much pressure on the system. Could this damper cause any other issues than putting more load on the fan? The gas heater is 3 years old and a high efficency unit.
Edit - some more information:
The cold air from the return duct is more than 10 degrees cooler than the 2nd floor temperature. Right now it's around 40 degrees in the attic, 70 degrees on the 2nd floor and the air from the vent is around 59 degrees.
You can't feel much of an airflow from the duct. My guess is, that there's no attic air entering the duct, but the hot air from the 2nd floor is rising into the return duct, cooling down and falling into the 2nd floor again.
My hope is, that the backdraft damper keeps the rising air in the duct itself, so it won't travel through the round hose to the furnace. This hopefully keeps the air in the duct quite warm. The hose that goes from the return duct in the attic to the furnace is insulated and is around 12 inches in diameter and maybe 8 feet long.
Since the damper opens easily my hope is that the system won't even notice the additional resistance.
Comment: You say that cold air is leaking out of the cold air return duct. How cold is the air - is it cool, but mostly room temp, or is it outside/attic sub-zero temp? Where are you feeling the cold air - in the hallway below the duct or in the attic? What are you attempting to do with the backdraft damper - i.e. where do you plan on installing it in the system and what impact are you expecting it to have?
Comment: Please see my edit above. The text was too long to post it as a comment.
Comment: I can't help you with an answer, but the additional info should help those who know HVAC. Also, editing that into the original question is 100% the way to do it. Comments can get deleted, and many people don't read them.
Answer: This is an old but I have the answer. The cool air flow is caused by the air cooling off inside the return flex duct located in the unconditioned attic. The supply vents are allowing air flow through the furnace/ahu to the return air, it is simply cold air is falling down out of the return air and being replaced with air behind it form the supply side. So yes add dampers to the return side to stop the air from coming out. Question is what type of damper. Electrically operated or not. I have the same problem but single story with ducting in unconditioned attic.
Comment: I have been using butterfly backdraft dampers for a few years now and they have made a difference in keeping the warm air inside conditioned space and preventing it from rising into the cold unconditioned attic. I added dampers in the ceiling vents and also a larger one in the hallway air return vent. These butterfly dampers easily open once the heater turns on and then close again.


Extract Text Files in Google Cloud VM

Question: Noob and beginner here. Just trying to learn the basics of GCP.
I have a series of Google Cloud Buckets that are text files. I also have a VM instance that I've set up via GCP.
Now, I'm trying to write some code to extract the data from Google buckets and run the script via GCP's command prompt.
How can I extract GCP buckets in Python
Comment: Your questions seems a little unclear to me, so I'm assuming you have several text files within a Google Cloud Storage bucket(s) and you're trying to write a script on a Google Compute Engine Instance that will download the specified files. Do you want to invoke this script from the Google Cloud Shell (i.e. outside of the instance)?
Comment: I guess you are looking for solutions to process some data files which is stored in Cloud Storage. With Dataflow in GCP, you could write data pipeline in Python with Apache Beam SDK to get data from Cloud Storage, process it, and output it. GCP Dataflow is a managed service that it manage the VM-instance and the Apache Beam runtime for you. You only need to focus on developing the data pipeline program.
Here is a simple example about doing word count with apache beam. https://github.com/apache/beam/blob/master/sdks/python/apache_beam/examples/wordcount_minimal.py
Answer: I think that you can use the Listing Objects and Downloading Objects GCS methods with Python; in this way, you will be able to get a list of the objects stored in your Cloud Storage buckets to then extract them into you VM instance. Additionally, keep in mind that it is important to verify that the service account that you implement to perform these tasks, has the required roles assigned in order to access to your GCS buckets, as well as provide the credentials to your application by using environment variables or explicitly pointing to your service account file in code.
Once you have your code ready, you can simply execute your Python program by using the
python command. You can take a look on this link to get the instructions to install Python in your new environment.

Extract Text Files in Google Cloud VM


Finding shortest repeating cycle in word?

Question: I'm about to write a function which, would return me a shortest period of group of letters which would eventually create the given word.
For example word abkebabkebabkeb is created by repeated abkeb word. I would like to know, how efficiently analyze input word, to get the shortest period of characters creating input word.
Comment: @Tony The Tiger, the result (shortest period) does not have to be a real word.
Answer: Here is a correct O(n) algorithm. The first for loop is the table building portion of KMP. There are various proofs that it always runs in linear time.
Since this question has 4 previous answers, none of which are O(n) and correct, I heavily tested this solution for both correctness and runtime.
def pattern(inputv):
    if not inputv:
        return inputv

    nxt = [0]*len(inputv)
    for i in range(1, len(nxt)):
        k = nxt[i - 1]
        while True:
            if inputv[i] == inputv[k]:
                nxt[i] = k + 1
                break
            elif k == 0:
                nxt[i] = 0
                break
            else:
                k = nxt[k - 1]

    smallPieceLen = len(inputv) - nxt[-1]
    if len(inputv) % smallPieceLen != 0:
        return inputv

    return inputv[0:smallPieceLen]

Comment: Well [KMP is a known algorithm](https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm). This question was very similar to a homework problem I had, and this is the answer I came up with for the homework. The instructor's solution was a bit different, but also used KMP.
Comment: @LinMa: (Buge wasn't active lately) `nxt[-1] means if the whole string does not match, what index we will be used to compare next` no (contorted grammar, btw.). It is the index to compare next when all of the pattern matched and you want to find its next occurrence in a longer text. `nxt[i] = p` means `pattern[i+1-p:i+1]` equals `pattern[0:p]` (& != for `p+1`). `nxt[-1]` is the index to compare next if the "first" mismatch was "at `len`+1". (In many a presentation/implementation of KMP, there is a special value of -1 at index 0, with the n values as above "shifted to an index higher by one".)
Comment: @Boris I consider `[1, 2]` wrong. The question says "For example word `abkebabkebabkeb` is created by repeated `abkeb` word." But it's not possible to create `[1, 2, 1]` by repeating `[1, 2]`. You need to repeat it, then chop off the end to get `[1, 2, 1]`. But yes, the question is somewhat ambiguous about what the correct answer to `[1, 2, 1]` is.
Comment: So is this a solution you have come up with or is this a known algorithm?
Comment: @LinMa: (`both` are notified, anyway) Let me call `len(inputv)` _len_ and `nxt[-1]` _matchLen_. If _matchLen_ < _smallPieceLen_, the only chance for _smallPieceLen_ to divide _len_ is to be equal to it. If _smallPieceLen_ ≤ _matchLen_, `inputv[0:smallPieceLen]` equals `inputv[smallPieceLen:2*smallPieceLen]`, and `k` never got reset (again): inputv is made up of repetitions of `inputv[0:smallPieceLen]` - the divisibility check just ensures that it ends with a full repetition.
Comment: Hi Buge, love your solution, and vote up. but confused by this line `smallPieceLen = len(inputv) - nxt[-1]`, and `nxt[-1]` means if the whole string does not match, what index we will be used to compare next. `smallPieceLen` represents the differences total length of string and `nxt[-1]`, how it could be represented as shortest repetitive string?
Comment: Hi @greybeard, spend time today to debug your comments and Buge's code carefully, and you are correct, thanks for clarifying the meaning of `nxt[i]=j`. There is one thing I still mis-understand, `len(inputv) - nxt[-1]`, this line checks the longest prefix, which matches suffix of the same string, `smallPieceLen ` is the remaining part length, why if `len(inputv)` could be divided by `smallPieceLen`, then it is shortest repetitive string? Is there a simple prove or some explanation? Is it too aggressive to make the conclusion?
Comment: Maybe this is a question to both @Buge and greybeard. :)
Comment: @greybeard, nice answer, I think about your reply for more than one day, but not sure how do you get this conclusion `inputv[0:smallPieceLen] equals inputv[smallPieceLen:2*smallPieceLen]`, would you elaborate a bit more?
Comment: The way I think about it is `nxt[-1]` is the max amount that the beginning of `inputv` can overlap with the end of itself (without overlapping the entire thing). For example in `abcabcabc` `nxt[-1]==6` because the last 6 letters are the same as the first 6. I specifically like to think of it as the length of the last characters. So in the example it can be split into 2 parts: `abc|abcabc` where the first part has length `smallPieceLen` and the second part has length  `nxt[-1]`. Because of the overlap knowledge, we know `abc` overlaps at the beginning with `abcabc` as far as the overlap or `abc
Comment: Can someone translate this answer to a known programming language like java or C? It would be much appreciated to someone like me who doesn't understand this one. Thank you.
Comment: what does: nxt = [0]*len(inputv) do?
Comment: It's python which I consider a known programming language, the same language as the accepted answer. `[0]*len(inputv)` [means](https://stackoverflow.com/q/3459098/830749) create a python list (array) with the same length as `inputv` and with all elements being `0`. Anyway, [here](https://ideone.com/ViZKCX) it is in Java. C would be a little annoying because of its less flexible strings and arrays.
Comment: This doesn't work the way I expected if the pattern ends abruptly. For example `[1, 2, 1]` should return `[1, 2]` but this code returns `[1, 2, 1]`.
Answer: This is an example for PHP:
<?php
function getrepeatedstring($string) {
    if (strlen($string)<2) return $string;
    for($i = 1; $i<strlen($string); $i++) {
        if (substr(str_repeat(substr($string, 0, $i),strlen($string)/$i+1), 0, strlen($string))==$string)
            return substr($string, 0, $i);
    }
    return $string;
}
?>

Comment: I don't know PHP, but this looks like it's O(n^2).
Comment: @jack44: You can't know if you have the shortest cycle until you've examined the entire string.  Unless you have other knowledge, like what the largest possible cycle might be.  It might be that the last character in the string throws the whole cycle off, you don't know.
Comment: This returns 'abkeb' which should be correct but I'm not sure in what way the OP is asking for 'kebab' rather than 'abkeb'.
Comment: This is what I'm looking for. But it runs in O(n). Any ideas if this can be speeded up?
Comment: @Richard86 - String comparison is going to O(n), though, isn't it?
Comment: @jack44 The speed could be improved. One solution is to start at pos `strlen($string)/2`. Then, if it is a match, you would go to `strlen($string)/4`, `strlen($string)/8`, and so on, until it is not a match, after that, you would check each char from the current position until match. If it isn't a match at pos `strlen($string)/2`, you would check at pos `strlen($string)-strlen($string)/2`, if not a match, continue with `strlen($string)-strlen($string)/4`, `strlen($string)-strlen($string)/8` and so on until a match, and then, check from one step back. I'll use PHP if no one tries with pseudo.
Comment: @jack44 I believe the O(n) solution by @spin is to prefer, and there is no need to improve this answer as it will not be able to be as fast as the O(n) solution is.
Answer: Simpler answer which I can come up in an interview is just a O(n^2) solution, which tries out all combinations of substring starting from 0.
int findSmallestUnit(string str){
    for(int i=1;i<str.length();i++){
        int j=0;
        for(;j<str.length();j++){
            if(str[j%i] != str[j]){
                break;
            }
        }
        if(j==str.length()) return str.substr(0,i);
    }
    return str;
}

Now if someone is interested in O(n) solution to this problem in c++:
  int findSmallestUnit(string str){
      vector<int> lps(str.length(),0);
      int i=1;
      int len=0;

      while(i<str.length()){
          if(str[i] == str[len]){
              len++;
              lps[i] = len;
              i++;
          }
          else{
              if(len == 0) i++;
              else{
                  len = lps[len-1];
              }
          }
      }
      int n=str.length();
      int x = lps[n-1];
      if(n%(n-x) == 0){
          return str.substr(0,n-x);
      }
      return str;
  }

The above is just @Buge's answer in c++, since someone asked in comments.
Answer: O(n) solution. Assumes that the entire string must be covered.  The key observation is that we generate the pattern and test it, but if we find something along the way that doesn't match, we must include the entire string that we already tested, so we don't have to reobserve those characters.
def pattern(inputv):
    pattern_end =0
    for j in range(pattern_end+1,len(inputv)):

        pattern_dex = j%(pattern_end+1)
        if(inputv[pattern_dex] != inputv[j]):

            pattern_end = j;
            continue

        if(j == len(inputv)-1):
            print pattern_end
            return inputv[0:pattern_end+1];
    return inputv;

Comment: I'm afraid the algorithm is incorrect. Please consider the input: "BCBDBCBCBDBC". The smallest repeating pattern is "BCBDBC", but the algorithm above will miss it. Also, I think it doesn't deal correctly with the case "HELLOHELL" (where it returns "HELLO" instead of the complete string).
Comment: @Boris: The problem is finding the smallest sub-sequence of S such that K>=1 repetitions of it would result in S itself. The input "HELLOHELL" has no repeating subsequence with K>1, so "HELLOHELL" should be returned.
Comment: Is `for pattern_end in range(len(inputv)/2)` necessary? I don't think it is.
Comment: @Ishtar - sorry I'm not following.  Do you mean the look of the len()/2 part
Comment: I mean, replacing that line with `pattern_end = 0`.
Comment: @EyalSchneider returning "HELLO" for "HELLOHELL" makes perfect sense. Otherwise you could be using the length of the string to determine which patterns are even allowed. You only need to check patterns whose lengths are combinations of the prime factors (and 1) of the length of the input. For example if you get a string that's 101 characters long what's the point of even trying a 5 letter subsequence? It's not going to fit perfectly into 101 characters. If your input's length is 13 there's no point in even checking, no pattern (except a 1 letter pattern) repeated n times can ever add up to 13.
Comment: This is a correct answer. not the most voted one. This answer is also work for "aabbccaa" and find "aabbcc" but the top answer doesn't work and print "aabbccaa".
Answer: Most easiest one in python:
def pattern(self, s):
    ans=(s+s).find(s,1,-1)
    return len(pat) if ans == -1 else ans

Comment: It will be helpful if you explain what you did
Answer: I believe there is a very elegant recursive solution. Many of the proposed solutions solve the extra complexity where the string ends with part of the pattern, like abcabca. But I do not think that is asked for.
My solution for the simple version of the problem in clojure:
 (defn find-shortest-repeating [pattern string]
  (if (empty? (str/replace string pattern ""))
   pattern
   (find-shortest-repeating (str pattern (nth string (count pattern))) string)))

(find-shortest-repeating "" "abcabcabc") ;; "abc"

But be aware that this will not find patterns that are uncomplete at the end.
Answer: I found a solution based on your post, that could take an incomplete pattern:
(defn find-shortest-repeating [pattern string]
   (if (or (empty? (clojure.string/split string (re-pattern pattern)))
          (empty? (second (clojure.string/split string (re-pattern pattern)))))
    pattern
    (find-shortest-repeating (str pattern (nth string (count pattern))) string)))

Comment: @ward
`(defn find-pattern-string [string]
  (let [pattern ""
        working-str string]
    (reduce
      #(if (not (or (empty? (clojure.string/split string (re-pattern %1)))
                    (empty? (second (clojure.string/split string (re-pattern %1))))))
         (str %1 %2)
          %1)
      pattern working-str)))`
Answer: My Solution:
The idea is to find a substring from the position zero such that it becomes equal to the adjacent substring of same length, when such a substring is found return the substring. Please note if no repeating substring is found I am printing the entire input String.
public static void repeatingSubstring(String input){
    for(int i=0;i<input.length();i++){
        if(i==input.length()-1){
            System.out.println("There is no repetition "+input);
        }
        else if(input.length()%(i+1)==0){
            int size = i+1;
            if(input.substring(0, i+1).equals(input.substring(i+1, i+1+size))){
                System.out.println("The subString which repeats itself is "+input.substring(0, i+1));
                break;
            }
        }
    }
}

Comment: I think this would fail for the string "ababcababc"
Answer: Regex solution:
Use the following regex replacement to find the shortest repeating substring, and only keeping that substring:
^(.+?)\1*$
$1

Explanation:
^(.+?)\1*$
^        $   # Start and end, to match the entire input-string
 (   )       # Capture group 1:
  .+         #  One or more characters,
    ?        #  with a reluctant instead of greedy match†
      \1*    # Followed by the first capture group repeated zero or more times

$1           # Replace the entire input-string with the first capture group match,
             # removing all other duplicated substrings

† Greedy vs reluctant would in this case mean: greedy = consumes as many characters as it can; reluctant = consumes as few characters as it can. Since we want the shortest repeating substring, we would want a reluctant match in our regex.
Example input: "abkebabkebabkeb"
Example output: "abkeb"
Try it online in Retina.
Here an example implementation in Java.
Comment: Oh yeah, my bad I confused between questions, was reading similar question on the same lines. Thanks for the reply tho
Comment: This won't work for the string `abaa` where expected output is `a`
Comment: @HimanshuPoddar If I read the question correctly, the full word is always build from multiple repeating substrings without any other characters, so `abab` (2x `ab`) or `aaa` (3x `a`) are both valid inputs, but `abaa` not (unless you count it as 1x `abaa`).
Answer: This is a solution I came up with using the queue, it passed all the test cases of a similar problem in codeforces. Problem No is 745A.
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

    string s, s1, s2; cin >> s; queue<char> qu; qu.push(s[0]); bool flag = true; int ind = -1;
    s1 = s.substr(0, s.size() / 2);
    s2 = s.substr(s.size() / 2);
    if(s1 == s2)
    {
        for(int i=0; i<s1.size(); i++)
        {
            s += s1[i];
        }
    }
    //cout << s1 << " " << s2 << " " << s << "\n";
    for(int i=1; i<s.size(); i++)
    {
        if(qu.front() == s[i]) {qu.pop();}
        qu.push(s[i]);
    }
    int cycle = qu.size();

    /*queue<char> qu2 = qu; string str = "";
    while(!qu2.empty())
    {
        cout << qu2.front() << " ";
        str += qu2.front();
        qu2.pop();
    }*/

    while(!qu.empty())
    {
        if(s[++ind] != qu.front()) {flag = false; break;}
        qu.pop();
    }
    flag == true ? cout << cycle : cout << s.size();
    return 0;
}

Answer: Super delayed answer, but I got the question in an interview, here was my answer (probably not the most optimal but it works for strange test cases as well).
private void run(String[] args) throws IOException {
    File file = new File(args[0]);
    BufferedReader buffer = new BufferedReader(new FileReader(file));
    String line;
    while ((line = buffer.readLine()) != null) {
        ArrayList<String> subs = new ArrayList<>();
        String t = line.trim();
        String out = null;
        for (int i = 0; i < t.length(); i++) {
            if (t.substring(0, t.length() - (i + 1)).equals(t.substring(i + 1, t.length()))) {
                subs.add(t.substring(0, t.length() - (i + 1)));
            }
        }
        subs.add(0, t);
        for (int j = subs.size() - 2; j >= 0; j--) {
            String match = subs.get(j);
            int mLength = match.length();
            if (j != 0 && mLength <= t.length() / 2) {
                if (t.substring(mLength, mLength * 2).equals(match)) {
                    out = match;
                    break;
                }
            } else {
                out = match;
            }
        }
        System.out.println(out);
    }
}

Testcases:
abcabcabcabc
bcbcbcbcbcbcbcbcbcbcbcbcbcbc
dddddddddddddddddddd
adcdefg
bcbdbcbcbdbc
hellohell
Code returns:
abc
bc
d
adcdefg
bcbdbc
hellohell
Comment: Just looking at the first for loop this is O(n^2), because each .equals() can take n time.
Answer: Works in cases such as bcbdbcbcbdbc.
function smallestRepeatingString(sequence){
  var currentRepeat = '';
  var currentRepeatPos = 0;

  for(var i=0, ii=sequence.length; i<ii; i++){
    if(currentRepeat[currentRepeatPos] !== sequence[i]){
      currentRepeatPos = 0;
      // Add next character available to the repeat and reset i so we don't miss any matches inbetween
      currentRepeat = currentRepeat + sequence.slice(currentRepeat.length, currentRepeat.length+1);
      i = currentRepeat.length-1;
    }else{
      currentRepeatPos++;
    }
    if(currentRepeatPos === currentRepeat.length){
      currentRepeatPos = 0;
    }
  }

  // If repeat wasn't reset then we didn't find a full repeat at the end.
  if(currentRepeatPos !== 0){ return sequence; }

  return currentRepeat;
}

Comment: This is actually O(n^2). That is because you reset `i` to be smaller with `i = currentRepeat.length-1;`. So with a 10 character string ling 'aaaaaaaaab' it takes 46 iterations. With a 20 character string it takes 191 iterations.
Answer: I came up with a simple solution that works flawlessly even with very large strings.
PHP Implementation:
function get_srs($s){
    $hash = md5( $s );
    $i = 0; $p = '';

    do {
        $p .= $s[$i++];
        preg_match_all( "/{$p}/", $s, $m );
    } while ( ! hash_equals( $hash, md5( implode( '', $m[0] ) ) ) );

    return $p;
}

Comment: Would be good if you gave some detail regarding why exactly this works. Providing more detail helps the entire community and helps to get more up votes.


preseed.cfg installed in initrd root not being recognized in Ubuntu installation (17.10 amd64 desktop or server)

Question: I have been using a process for preseeding the initrd in a Debian ISO for some time. I just tried the same process for desktop and server variants of Ubuntu 17.10 ISOs, and everything looks fine until I boot into it and see absolutely no indication that the installer sees the preseed.cfg I placed in its initrd. For example, the installer asks me what language/locale first thing, even though my preseed.cfg has:
d-i debian-installer/locale string en_US.UTF-8
d-i console-setup/ask_detect boolean false
d-i keyboard-configuration/layoutcode string us
d-i debian-installer/keymap select us
d-i keymap select us
d-i keyboard-configuration/xkb-keymap select us

I looked through all the F* key options and could not find any option comparable to the Debian Installer's "Automated Install", which decompresses the initrd and looks for/uses the preseed.cfg at its root to answer, potential, all installer questions. The Ubuntu preseeding docs confirm that Ubuntu preseeding is supposed to work the same way, saying that:

…the point at which the preconfiguration file is loaded and processed. For initrd preseeding this is right at the start of the installation, before the first question is even asked.

Does anyone have any helpful hints for what might be going wrong based on the differences between Ubuntu ISOs and Debian ISOs, and the process of preseeding them via initrd?
These pages (here, here, and here) indicate that newer desktop ISOs have been reported to not be preseedable, and that the server ISOs should work "better". So, I downloaded 17.04 (and 17.10) server, repeated my test with that, and got the same behavior.
FTR, the process for embedding the preseed.cfg in the initrd I'm using was taken from the Debian Wiki. Specifically, I'm using the "isofiles" approach, which is to mount the ISO (I'm using udevil), copy the files to local storage, then add preseed file to the initrd.
Like I said, this process works great for Debian ISOs, but does not appear to work at all for any of the desktop or server Ubuntu ISOs I've tried.
The Ubuntu help confirms that my assumption is valid:

If you are using initrd preseeding, you only have to make sure a file named preseed.cfg is included in the root directory of the initrd. The installer will automatically check if this file is present and load it.

The next thing I tried was to compare my preseed.cfg with the official example Ubuntu preseed file to see if there's some problem with d-i and Ubuntu installers using/supporting different preseed directives. I didn't find much difference. To be sure, I installed, verbatim, the the official example Ubuntu preseed file in the initrd of the 17.10 server ISO, and the resulting installer still requires human to answer the questions as if there was no preseed at all.
Comment: @timblaktu Did you ever figure out how to get this working? I'm trying with 18.04 server and it doesn't seem to want to use my preseed file.
Comment: OK folks, I have repeated my test with ubuntu-17.10.1-server-amd64.iso, and am getting the same result. I have updated the title and issue description.
Comment: Rinzwind, would you please vote to remove this post from "on hold" status, now that it's no longer specific to 17.04? It's been updated to reflect that it is related to 17.10, and also I've deleted my "answers", compiled them into the OP.
Comment: Have you looked at https://askubuntu.com/questions/806820/how-do-i-create-a-completely-unattended-install-of-ubuntu-desktop-16-04-1-lts
Comment: Thank Terrance. His approach isn't what I'm looking for, but Niklas posted a link there to his approach which is identical to my Debian preseed initrd one, plus a little extra magic that mine was missing. He patches grub.cfg and isolinux.cfg to add an "unattended install" boot menu default item that explicitly uses the preseed file. I'm eager to try this approach out, communicate with Niklas, and will report back here if this leads to a real answer to my question. https://github.com/core-process/linux-unattended-installation
Comment: I tried it with 18.04 server as well. The preseed file *is* used for later questions (e.g. hostname), but not for the initial language questions. That is, I get the same behaviour when I put preseed.cfg into intird.gz as if I simply use the file method (overwrite preseed/ubuntu-server.seed).
Comment: Sorry for the delay.. Ive been off in another universe.. don't have the full answer yet but I can say that yes I got it working (with 17.04, will try 18 soon) but only by using Niklas' idea of customizing the boot menu to force unattended install. Also, I think I'm going to consider shifting my process to use netboot/mini.iso releases exclusively since they appear to work the same for all versions. This consistency is invaluable for configuration management Automation..
Answer: On server, to get the lang questions answered, you have add auto=true as an option to boot menu.
Here is an example of a pxe menu using auto=true (grub menu should be similar):
label install
    menu default
    menu label ^Preseed Install
    kernel ubuntu-installer/amd64/linux
    append auto=true vga=normal initrd=ubuntu-installer/amd64/initrd.gz

Taken from https://wiki.debian.org/DebianInstaller/Preseed#Loading_the_preseeding_file_from_a_webserver:

The "auto" command launches the installation in the automated mode, where the configuration of hostname, locale and keymap are postponed so that they can be answered from the preseed file loaded from the network. You could use "install url=..." but you'd have to answer these questions manually, regardless of what you have in the preseed config. If a server path isn't specified the path 'd-i//preseed.cfg' will be tried, for example d-i/stretch/preseed.cfg. Note that network configuration options (netcfg/*) cannot be applied via a network-loaded preseed.cfg file, as the network must be configured before the preseed file can be fetched. If network configuration options must be declared, needed options have be passed as kernel options (eg netcfg/choose_interface=eth0).


Is it necessary to create a new S3 client object for each request in Node.js?

Question: Is it necessary to create a new S3 client object for each request in Node.js?
const aws = require('aws-sdk');
const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
  const s3 = new aws.S3();
  const params = {
    Bucket: "examplebucket",
    Key: "HappyFace.jpg"
  };
  s3.getObject(params, (err, data) => {
   if (err) console.log(err, err.stack); // an error occurred
   else res.send(data);
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

This is just an example code, but the position of const s3 = new aws.S3(); is crucial for me. Let's imagine that the service processes thousands of requests in parallel, then it generates thousands of S3 objects. As it stands, the service can handle it without any problems. My question is, does it even have to? If I only created one S3 object above the route definition, would parallel requests affect each other or not when the code will be changed to
...
const s3 = new aws.S3();

app.get('/', (req, res) => {
  const params = {
    Bucket: "examplebucket",
    Key: "HappyFace.jpg"
  };
  s3.getObject(params, (err, data) => {
   if (err) console.log(err, err.stack); // an error occurred
   else res.send(data);
});
...

Comment: I would rephrase the question as "S3 Clients" or "S3 Client objects", as "S3 Objects" is what files stored in S3 buckets are called.
Comment: @MarkB feel free to report the title to moderators maybe you have right :)
Comment: Why would I report the title to moderators? All you need to do is click the edit button to fix it. I guess I'll do it for you...
Answer: definitly not. The s3 object here is an instance of a manger for the subset of apis you will use from AWS sdk and not an s3 object representation.
Unless you are doing something very specific (which was not precised in the question so i assume that this is not the case) you are good to set it above the app.get part.
You would only go the 1st way you mention if the configuration of the sdk for s3 apis must be different for each request (ex: if you need to use a different aws credential for each request or store the object in a different region for each request)
Comment: If the service uses roles in AWS IAM, then when creating a new S3 object, the credentials are retrieved from the AWS Credentials Metaservice. If the object is defined outside, is it possible that temporary credentials could expire?
Answer: When you do:
const s3 = new aws.S3();

you're only instantiating the S3 class provided by the AWS SDK, thus the only thing that could be a problem is if you need a different initial configuration of the instance, e.g region, version...
That said, from the code you've provided, it's okay to instantiate the S3 class outside the endpoint, and it's probably good practice too.
Comment: If the service uses roles in AWS IAM, then when creating a new S3 object, the credentials are retrieved from the AWS Credentials Metaservice. If the object is defined outside, is it possible that temporary credentials could expire?


Where is TemplateVisualStateAttribute in a WinRT button?

Question: Here's the definition of a WinRt button.
Why can't I find the TemplateVisualStateAttribute?
If it's not tagged on the class itself, how can I possibly discover what visual states and groupings are available to me when implementing a custom button style?
There are some examples for what they are, but I would like to be able to discover what they are on other controls as well - how can I do so if the classes aren't tagged properly?
// Type: Windows.UI.Xaml.Controls.Button
// Assembly: Windows, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null
// Assembly location: C:\Program Files (x86)\Windows Kits\8.0\References\CommonConfiguration\Neutral\Windows.winmd

using System.Runtime.CompilerServices;
using Windows.Foundation.Metadata;
using Windows.UI.Xaml.Controls.Primitives;

namespace Windows.UI.Xaml.Controls
{
  ///
  /// Represents a templated button control that interprets a Click user interaction.
  ///
  [MarshalingBehavior(MarshalingType.Agile)]
  [Composable(typeof (IButtonFactory), CompositionType.Public, 100794368)]
  [WebHostHidden]
  [Threading(ThreadingModel.Both)]
  [Version(100794368)]
  public class Button : ButtonBase, IButton
  {
    ///
    /// Initializes a new instance of the Button class.
    ///
    [MethodImpl]
    public Button();
  }
}

Answer:
how can I possibly discover what visual states and groupings are available

Presumably you have to look at the default styles and templates for the control.  For WPF/Silverlight, they are published on MSDN, but for WinRT it seems you have to look in the SDK:  generic.xaml under c:\Program Files\Windows Kits\8.0\Include\winrt\xaml\design\.
Comment: Gotcha thanks, yeah the winrt visual states are similar but there is enough differences that I couldn't use the WPF/Silverlight document. This is odd - I don't have that folder on my PC >.< Why can't they make this easier?


app store issue with sales and trends

Question: Right now in application on itunesconnect I have a lot of data in Sales And Trends section (about downloads and payments).
But I need to transfer my application to another itunesconnect account (I need to change the company for the application. So in the details of the application I choose More->Transfer).
Will I have all that data in the other itunesconnect account after transferring the application or will I loose all that data about downloading and payments and so on?
Answer: No.

Because you won't be able to view the app information after the
  transfer, make a catalog report (see Requesting Catalog Reports), note
  dates the app was available on the store (see Viewing Status History),
  and save sales and download information (see Viewing Sales and
  Trends).

Apple Documentation Source

app store issue with sales and trends


Why can't we prove Goldbach's Conjecture with modular 2?

Question: "Every even whole number greater than 2 is the sum of two prime numbers."
$2n = p_1 + p_2\hspace{1cm} ,n>1 \\
2n = [(p_1-1) +1] + [(p_2-1) +1] \\
2n = (p_1-1) + (p_2-1) + 2 \\
0 \equiv 0 \mod{(2)}
$
Since $n>1$, then every prime number we are considering is odd. Therefore, both $p_1$ and $p_2$ can't be 2. Then $p_1$ and $p_2$ are 1 away from an even number; subtract 1 and add 1 for both $p_1$ and $p_2$. You can also choose to add 1 and subtract 1. Then modular 2 and we get a equivalence relation.
Is this a legit proof?
Edit: as I was walking to the gym, I just realized that this was one of the dumbest "proofs" ever, but I did observe something and jotted it down with iNotes. I thought about distance from $\mu$, the average that is always just $n$, and I think the distance is the same if we give some constraints.
Let $p_2$ be the smallest possible prime such that we can still add another prime number, $p_1$ to form an even number greater than 2. For some reason, then $p_2$ will typically be 3 or 5, sometimes 7, and should be 2 only one time for 4 = 2 + 2.
Emerging Patterns (I didn't fact check each p1 and p2, but the main idea is still there)
The way we get the 2 working prime numbers is to find some number and add it to n to get the first prime number. Then subtract the same number to get the second prime number.
For example: notice that n = 14, 2n = 28 = 23 + 5. We get those 2 numbers by:

adding 9 to 14 to get 23, 23 = 14 + 9

and then

we subtract 9 from 14 to get 5, 4 = 14 - 9

Therefore, 9 is the number that is relating 23 and 5 to 14.
It seems like if you can find a relationship between n and the number we add and subtract, then you can always find 2 prime numbers that add to the even number $2n$. From this table in this picture, p_2 is special, maybe constraining $p_2$ is very important? Maybe show that the only possible values for $p_2$ are 2,3,5 and 7?
Comment: No. You have presupposed that Goldbach's conjecture is true, and you have only shown that it is consistent in a very narrow sense. Showing congruence mod $2$ does not show equality, and there is no reason, that expert mathematicians have been able to find, for those primes to exist!
Comment: Please don't move the goalposts. I answered your original question, not the question as is now. If you want to ask a substantially different question, please ask it as a *separate* question.
Comment: How do you know that you can write $2n=p_1+p_2$?
Comment: You may have shown that an even number is always the sum of two odd numbers, or perhaps that the sum of two odd primes is always an even number
Answer: Note: This is the answer to the question as it was asked originally. In the meantime, the OP substantially changed it.

This is not a legitimate proof. If you take it at face value, you have only proven that $0\equiv 0\pmod 2$, which you already knew all along!
What is more interesting is what led you to believe that it was legitimate. I think it may be because of the stress in the math education on calculating, rather than logic. The pattern in your proof mimics what we would normally do to solve equations such as, say, $x+\sqrt{x+5}=7$:
$$\begin{array}{rcl}x+\sqrt{x+5}&=&7\\\sqrt{x+5}&=&7-x\\x+5&=&x^2-14x+49\\0&=&x^2-15x+44\\x&=&\frac{15\pm\sqrt{15^2-4\times 44}}{2}=4\text{ or }11\end{array}$$
Oops, $x=4$ is the solution, but $x=11$ isn't! What went wrong???
The answer is: the subsequent rows in the derivation above are only consequences of the previous rows, they are not equivalent to them. In particular we made $3$rd row by squaring the second row. If two numbers are equal ($2$nd row), then their squares are equal ($3$rd row). However, if the squares of two numbers are equal, it does not follow that the numbers themselves are equal! That is why values for $x$ that are not solutions of the initial equation have crept into subsequent equations.
Back to your "proof". Each row is a consequence of the previous row, but it may not be equivalent to it. You ended up with something that is true, but to prove that the thing you've started with is true, you would need to have the subsequent rows imply the previous rows - which is not the case. In fact, at a crucial point you said "$p_1$ and $p_2$ were prime, therefore they were odd". That step is going to be the hardest (read: impossible) to reverse: surely not all odd numbers are prime.

Why can't we prove Goldbach’s Conjecture with modular 2?


How do I make GlideApp Compatible with androidx?

Question: I recently migrated my app from AppCompat to Androidx but now I'm facing a serious issue with GlideApp. Whenever I try building the project, it shows compilation failed.
I tried changing the following import statements,
import android.support.annotation.CheckResult;
import android.support.annotation.NonNull;

in the build folder to:
import androidx.annotation.CheckResult;
import androidx.annotation.NonNull;

But whenever I rebuild it just regenerates the former import statement and returns the following errors:

error: package android.support.annotation does not exist   error:
  cannot find symbol class NonNull
Comment: banned on all search engines? https://github.com/yuyakaido/CardStackView/pull/254
Answer: I found the fix by adding annotationProcessor 'androidx.annotation:annotation:1.1.0' to my dependencies in app build.gradle and was able to build the project with no errors.
Got the solution from here: https://github.com/bumptech/glide/issues/3080#issuecomment-426331231


"Multipart: Boundary not found": File upload issue with Reactjs, Express, Multer and S3

Question: I am trying to upload an image from my React frontend, but running into an Unprocessable Entity error. The server route works as I have successfully uploaded an image through Postman.
const handleFileUpload = async (file: any) => {
    const imageData = new FormData();
    imageData.append("image", file[0]);

    const config = {
      method: "POST",
      headers: {
        "Content-Type": "multipart/form-data",

        Accept: "application/json",
      },
      body: imageData,
    };

    try {
      const req = await fetch(url, config);
      if (req.ok) {
        const res = await req.json();
        console.log(res);
      }
    } catch (err) {
      console.log(err);
    }
  };

Input:
<input
   type="file"
   accept="image/png, image/jpeg"
   onChange={(e: any) => { handleFileUpload(e.target.files ? e.target.files : url); }}
/>

Comment: try with "Content-Type": "application/x-www-form-urlencoded", in my case worked this way.
Comment: With the new "Content-Type" I am now getting a 500 internal server error
Comment: Hmm.. Try checking the exact configuration you used in Postman, and use it here. That will be the right way for you. It depends on what code you have on the API too.
Comment: Does anything in the input, onChange or FormData look off?
Answer: To solve, I removed the headers from the POST request so that fetch would automatically generate them. Server wise, I needed to set a limit on bodyParser to 50mb. Here are my edits:
const handleFileUpload = async (file: any) => {

    const imageData = new FormData();
    imageData.append("image", file);

    const config = {
      method: "POST",
      body: imageData,
    };

    try {
      const req = await fetch(url, config);
      if (req.ok) {
        const res = await req.json();
        console.log(res);
        if (res.success) {
          setURL(res.user.profilePicture);
        }
      }
    } catch (err) {
      console.log(err);
    }
  };

Comment: I'm glad you made it :)
Comment: getting 504 Gateway Time-out after removing header
Answer: Here is my working example:
// the input
<input
    type="file"
    accept="image/x-png,image/jpeg,image/gif"
    className={classes.uploadInput}
    ref={ref => upload = ref}
    onChange={e => uploadAvatar(e.target.files[0])}
/>

// redux action
const uploadAvatar = avatar => ({type: ActionType.TRY_CHANGE_AVATAR, avatar})

// redux-saga

const data = new FormData()
data.append('avatar', avatar)

// axios request

const result = yield axios.post(API_LINK, data)

// in my php I have this headers

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

// and

if (!move_uploaded_file($_FILES['avatar']['tmp_name'], $uploadFolder . $filename))
...

// to upload it.

This is just an example not really an answer to your question, but still i hope this helps in some way.


How can i install dlib in my windows when i have also downloaded visual studio ?? This error starts comming

Question: <code>Microsoft Windows [Version 10.0.17763.805]
(c) 2018 Microsoft Corporation. All rights reserved.

C:\Users\91935>pip install dlib
Collecting dlib
  Using cached https://files.pythonhosted.org/packages/1e/62/aacb236d21fbd08148b1d517d58a9d80ea31bdcd386d26f21f8b23b1eb28/dlib-19.18.0.tar.gz
Installing collected packages: dlib
    Running setup.py install for dlib ... error
    ERROR: Command errored out with exit status 1:
     command: 'c:\users\91935\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\91935\\AppData\\Local\\Temp\\pip-install-87kzpe74\\dlib\\setup.py'"'"'; __file__='"'"'C:\\Users\\91935\\AppData\\Local\\Temp\\pip-install-87kzpe74\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\91935\AppData\Local\Temp\pip-record-wqn_kh20\install-record.txt' --single-version-externally-managed --compile
         cwd: C:\Users\91935\AppData\Local\Temp\pip-install-87kzpe74\dlib\
    Complete output (80 lines):
    running install
    running build
    running build_py
    package init file 'dlib\__init__.py' not found (or not a regular file)
    running build_ext
    Building extension for Python 3.8.0 (tags/v3.8.0:fa919fd, Oct 14 2019, 19:21:23) [MSC v.1916 32 bit (Intel)]
    Invoking CMake setup: 'cmake C:\Users\91935\AppData\Local\Temp\pip-install-87kzpe74\dlib\tools\python -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\Users\91935\AppData\Local\Temp\pip-install-87kzpe74\dlib\build\lib.win32-3.8 -DPYTHON_EXECUTABLE=c:\users\91935\appdata\local\programs\python\python38-32\python.exe -DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\Users\91935\AppData\Local\Temp\pip-install-87kzpe74\dlib\build\lib.win32-3.8'
    -- Building for: NMake Makefiles
    -- The C compiler identification is unknown
    -- The CXX compiler identification is unknown
    CMake Error at CMakeLists.txt:3 (project):
      The CMAKE_C_COMPILER:

        cl

      is not a full path and was not found in the PATH.

      To use the NMake generator with Visual C++, cmake must be run from a shell
      that can use the compiler cl from the command line.  This environment is
      unable to invoke the cl compiler.  To fix this problem, run cmake from the
      Visual Studio Command Prompt (vcvarsall.bat).

      Tell CMake where to find the compiler by setting either the environment
      variable "CC" or the CMake cache entry CMAKE_C_COMPILER to the full path to
      the compiler, or to the compiler name if it is in the PATH.

    CMake Error at CMakeLists.txt:3 (project):
      The CMAKE_CXX_COMPILER:

        cl

      is not a full path and was not found in the PATH.

      To use the NMake generator with Visual C++, cmake must be run from a shell
      that can use the compiler cl from the command line.  This environment is
      unable to invoke the cl compiler.  To fix this problem, run cmake from the
      Visual Studio Command Prompt (vcvarsall.bat).

      Tell CMake where to find the compiler by setting either the environment
      variable "CXX" or the CMake cache entry CMAKE_CXX_COMPILER to the full path
      to the compiler, or to the compiler name if it is in the PATH.

    -- Configuring incomplete, errors occurred!
    See also "C:/Users/91935/AppData/Local/Temp/pip-install-87kzpe74/dlib/build/temp.win32-3.8/Release/CMakeFiles/CMakeOutput.log".
    See also "C:/Users/91935/AppData/Local/Temp/pip-install-87kzpe74/dlib/build/temp.win32-3.8/Release/CMakeFiles/CMakeError.log".
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "C:\Users\91935\AppData\Local\Temp\pip-install-87kzpe74\dlib\setup.py", line 223, in <module>
        setup(
      File "c:\users\91935\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\__init__.py", line 145, in setup
        return distutils.core.setup(**attrs)
      File "c:\users\91935\appdata\local\programs\python\python38-32\lib\distutils\core.py", line 148, in setup
        dist.run_commands()
      File "c:\users\91935\appdata\local\programs\python\python38-32\lib\distutils\dist.py", line 966, in run_commands
        self.run_command(cmd)
      File "c:\users\91935\appdata\local\programs\python\python38-32\lib\distutils\dist.py", line 985, in run_command
        cmd_obj.run()
      File "c:\users\91935\appdata\local\programs\python\python38-32\lib\site-packages\setuptools\command\install.py", line 61, in run
        return orig.install.run(self)
      File "c:\users\91935\appdata\local\programs\python\python38-32\lib\distutils\command\install.py", line 545, in run
        self.run_command('build')
      File "c:\users\91935\appdata\local\programs\python\python38-32\lib\distutils\cmd.py", line 313, in run_command
        self.distribution.run_command(command)
      File "c:\users\91935\appdata\local\programs\python\python38-32\lib\distutils\dist.py", line 985, in run_command
        cmd_obj.run()
      File "c:\users\91935\appdata\local\programs\python\python38-32\lib\distutils\command\build.py", line 135, in run
        self.run_command(cmd_name)
      File "c:\users\91935\appdata\local\programs\python\python38-32\lib\distutils\cmd.py", line 313, in run_command
        self.distribution.run_command(command)
      File "c:\users\91935\appdata\local\programs\python\python38-32\lib\distutils\dist.py", line 985, in run_command
        cmd_obj.run()
      File "C:\Users\91935\AppData\Local\Temp\pip-install-87kzpe74\dlib\setup.py", line 135, in run
        self.build_extension(ext)
      File "C:\Users\91935\AppData\Local\Temp\pip-install-87kzpe74\dlib\setup.py", line 172, in build_extension
        subprocess.check_call(cmake_setup, cwd=build_folder)
      File "c:\users\91935\appdata\local\programs\python\python38-32\lib\subprocess.py", line 364, in check_call
        raise CalledProcessError(retcode, cmd)
    subprocess.CalledProcessError: Command '['cmake', 'C:\\Users\\91935\\AppData\\Local\\Temp\\pip-install-87kzpe74\\dlib\\tools\\python', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=C:\\Users\\91935\\AppData\\Local\\Temp\\pip-install-87kzpe74\\dlib\\build\\lib.win32-3.8', '-DPYTHON_EXECUTABLE=c:\\users\\91935\\appdata\\local\\programs\\python\\python38-32\\python.exe', '-DCMAKE_LIBRARY_OUTPUT_DIRECTORY_RELEASE=C:\\Users\\91935\\AppData\\Local\\Temp\\pip-install-87kzpe74\\dlib\\build\\lib.win32-3.8']' returned non-zero exit status 1.
    ----------------------------------------
ERROR: Command errored out with exit status 1: 'c:\users\91935\appdata\local\programs\python\python38-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\91935\\AppData\\Local\\Temp\\pip-install-87kzpe74\\dlib\\setup.py'"'"'; __file__='"'"'C:\\Users\\91935\\AppData\\Local\\Temp\\pip-install-87kzpe74\\dlib\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\91935\AppData\Local\Temp\pip-record-wqn_kh20\install-record.txt' --single-version-externally-managed --compile Check the logs for full command output.

C:\Users\91935>
</code>
Comment: Can you examine your post and see if you can't improve its content.  It looks very poor to the point where it can't be followed.
Comment: you forgot to describe problem in question. Title is not place for this. Downvote.
Answer: For that you need to install all the dependencies along with visual studio like Cmake and all.
Let me share the proper document for installation

https://www.learnopencv.com/install-dlib-on-windows/
Answer: This link can be helpful: how to install Dlib library
For me the best way is to install Python 3.6 and do like he does. (had many problems already)


Can Worthy of Legend in Dungeon Siege III be cheesed?

Question: The trophy for Worthy of Legend reads:

You completed Dungeon Siege III at the highest difficulty level.

Does this mean I have to start the game at Hardcore difficulty and never set it to an easier level? Or does it just mean I need to complete the final encounter at Hardcore difficulty, allowing me to play at Casual difficulty up to that point?
Comment: It amazes me that they didn't simply restrain you from changing the difficulty mid-playthrough, if they're going to have achievements for it. I'm thinking of other games that have these kinds of achievements, they always restrain you from mid-playthrough difficulty changes.
Comment: @Grace Dragon Age allowed you to change your difficulty at will, and its DLC had difficulty level 'chieves, but they also specifically said which encounter you needed to beat at X difficulty in order to get it: "Defeated the Harvester on Hard difficulty" and such. There's a lot of stuff in DS3 that points to a severe lack of attention to detail, unfortunately.
Answer: You don't even have to play the rest of the game at all.  So yes, all that matters is the difficulty level at the time of beating the last encounter.
Comment: Unless it requires that game to have always been on hardcore, that is. (Although I do doubt it.)


What paint do I use to paint wood in a bathroom?

Question: I have a lot of wood in my bathroom, some in worse wear than others, its really ugly.
So I want to paint it.  My question is what paint do I use, do I need primer/ undercoat/ special bathroom paint?
I'm more concerned about the wood which is the window sill and the wood which holds the sink basin.  I also have to paint a previously painted wooden panel on the bath.
Answer: I'd suggest a quality primer (Killz would be a good brand) and then a high-gloss latex, perhaps with an anti-mildew additive (most paint departments will have anti-mildew bases designed for high moisture areas).
Answer: Couple more factors to consider before you paint. Whenever repainting old work, preparation is the most important step in the process. Old finishes need to be very clean, all soaps, residues removed and surfaces sanded or chemically deglossed.  Be aware, any paints before 1978 may contain lead and should be tested and handled properly to avoid any health risks.
Surfaces should be primed, if there is any bare wood, I like pigmented shellac, like Bin's Bullseye primer. Over old paints, a good high hiding primer like Kilz if fine.  Always do a quick buff sanding and damp wipe down of the dried primer before applying top coats. In bathrooms, I usually prefer a latex enamel semi-gloss paint.  The choice of full gloss or semi-gloss is simply a personal preference.  An enamel give you a very hard finish that cleans well  and will hold up for years. Always use a good quality brush. Please, no bargain basement $0.99 specials. A quality job comes from proper prep, quality products and the right tools.  Good luck.
Answer: For the home bathrooms I just use a good primer and then a semi-gloss latex.  However, at work we always used oil based paints in the bathrooms there.  The heavier usage in a high water/humidity environment made latex not work out so well.
Answer: Ia would always use a primer to start then a good gloss paint I wouldn't use quick dry as that is water base and does not work that well normally an oil based paint is the best as oil repels watet
Comment: This doesn't really add anything that the existing answers don't.


Simple regular express question

Question: I have a title on a blog goes like this Main Idea, key term, key term, keyterm
I want the main idea and the key terms to have a different font sizes. First thing that came to mind was to search for the first comma and the end of the string and replace that chunk with the same thing but surrounded by span tags with a class to make the font smaller.
Here is the plan:
HTML (before)
  Main Idea, key term, key term, key term

HTML (after)
  Main Idea , key term, key term key term

I'm using Rails so I plan to add this as a helper function - for ex:
helper
  def make_key_words_in_title_smaller(title)
      #replace the keywords in the title with key words surrounded by span tags
  end

view
  <% @posts.each do |post |%>
      <%= make_key_words_in_title_smaller(post.title)%>
  <% end -%>

Comment: Is there a reason you didn't include the last key term in the span?
Comment: Is the Main Idea always listed first?
Comment: yes, the main idea is always listed first
Comment: Does @posts have all the key term's (including the Main Idea)?
Comment: the key terms are just a concept and nothing more. It's how i structure the title. ie: it's just a format, syntax... and has nothing to do with actual obejcts
Answer: If you don't care about the Main Idea part being "Welcome home, Roxy Carmichael", that is, with a comman within double quotes
>> t = "Main Idea, key term, key term, key term"
=> "Main Idea, key term, key term, key term"

>> t.gsub(/(.*?)(,.*)/, '\1 \2')
=> "Main Idea , key term, key term, key term"

Answer: If the string is unadorned, (i.e., without tags) either of these works well:
data = 'Main Idea, key term, key term, key term'

# example #1
/^(.+?, )(.+)/.match(data).captures.each_slice(2).map { |a,b| a << %Q{#{ b }}}.first
# => "Main Idea, key term, key term, key term"

# example #2
data =~ /^(.+?, )(.+)/
$1 << %Q{#{ $2 }}
# => "Main Idea, key term, key term, key term"

If the string has tags then using regex to process HTML or XML is discouraged because it breaks so easily. Extremely trivial uses against HTML you control is pretty safe but if the content or format changes the regex can fall apart breaking your code.
HTML parsers are the usual recommended solution because they will continue working if the content or its formatting changes. This is what I'd do using Nokogiri. I was deliberately verbose to explain what was going on:
require 'nokogiri'

# build a sample document
html = 'Main Idea, key term, key term, key term'
doc = Nokogiri::HTML(html)

puts doc.to_s, ''

# find the link
a_tag = doc.at_css('a[href=stupidreqexquestion]')

# break down the tag content
a_text = a_tag.content
main_idea, key_terms = a_text.split(/,\s+/, 2) # => ["Main Idea", "key term, key term, key term"]
a_tag.content = main_idea

# create a new node
span = Nokogiri::XML::Node.new('span', doc)
span['class'] = 'smaller_font'
span.content = key_terms

puts span.to_s, ''

# add it to the old node
a_tag.add_child(span)

puts doc.to_s
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
# >> Main Idea, key term, key term, key term
# >>
# >> key term, key term, key term
# >>
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
# >> Main Ideakey term, key term, key term

In the output above you can see how Nokogiri built the sample document, the span being added, and the resulting document.
It can be simplified to:
require 'nokogiri'

doc = Nokogiri::HTML('Main Idea, key term, key term, key term')

a_tag = doc.at_css('a[href=stupidreqexquestion]')
main_idea, key_terms = a_tag.content.split(/,\s+/, 2)
a_tag.content = main_idea

a_tag.add_child("#{ key_terms }")

puts doc.to_s
# >> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
# >> Main Ideakey term, key term, key term

Comment: Your writing is fantastic! I wish I would have been more clear. What i meant by the css tag was that is how I wanted it to be after the regex or nokogiri was applied so you couldn't use it to get the key terms, you would have to use the first comma and the end of the string as markers. Seriously great post thanks a lot!
Comment: I'm not sure what you mean. It's possible to locate sections in a document without using XPath or CSS but the search will be a lot less accurate. Normally we look for some sort of constant "landmark" to navigate by, even if it means finding it then moving up, down, or sideways to get to the destination. If all you need is to adjust a simple string and add the `` tag, then that is an incredibly simple problem, one I'd expect a Rails developer to have no problem figuring out.
Comment: The landmark would be the first comma and the end of the string so I don't know how Nokogiri would find that. I have used nokogiri for screen scraping such as creating news feeds, but it needs some sort of xml or html class to parse by AFAIK.

Simple regular express question


I need to position a bootstrap modal(dialog) relative to the opener

Question: I use a bootstrap modal for my settings dialog in an angularJS app. but it need to open relative to the opener but the default bootstrap behavior is that it opens in the center of the page.I'm looking for a way to open it up and keep it relative to the opener when scrolling.
Code:
Modal template

HTML

JS
$scope.open = function (size) {
    console.log($document.find('my_items_wdgt').find('settings'))
    var modalInstance = $uibModal.open({
        animation: true,
        appendTo: $document.find('hello123'),
        templateUrl: 'myModalContent.html',
        size: size,
        backdrop: true,
        windowClass: "myItemsModal",
        resolve: {
            brands: function () {
                return $rootScope.usersBrands;
            }
        }
    });
};

Comment: Post your code or better demo. And looks like your image is not relevant at all.
Comment: I edited my post to include the code!
Comment: And the photo shows the modal opened next to the opener.
Comment: Maybe should you used [popover](http://getbootstrap.com/javascript/#popovers-examples) instead of modal....
Comment: Thought about it but it needs to close on click away?
Comment: I said image is not relevant, because it's a popover not a modal on it. So yes, you should use popover. You can also close it on "click away" too.
Comment: Thanks but I actually wanted to use a modal to be able to have scope and more functionality within. but I think a popover would work Thanks
Answer: I was having the same problem today. This is the solution I found and it's working in my project.
        var modalInstance = $uibModal.open({
            animation: true,
            backdrop: true,
            backdropClass: "modal-backdrop-custom",
            template:"
Hello World!
"
        }).rendered.then(function (modal) {
            var element = document.getElementById("elementIdHere"),
                rect = element.getBoundingClientRect(),
                modal = document.querySelector('.modal-dialog');

            modal.style.margin = 0;
            modal.style.left = rect.left + 'px';
            modal.style.top = rect.top + 'px';

        });

Basically you get the position of the relative component and then set the same value to the top and left properties of the modal.
Hope this helps you!
Comment: My modal was jumping with this configuration so what I did was just set the modal dialogs `visibility` to `hidden` (css) and after setting the last `top` set it back to `visible` so that the jump isn't visible.
Answer: It will get target attribute of opener or relative element give in bootstrap button.
$(".position-modal").click(function(e) {
        var getid = $(this).attr("data-bs-target");
        console.log(getid)
        var thisleft = $(this).offset().left;
        var thistop = $(this).offset().top;
        var thiswidth = $(this).width();
        var thisheight = $(this).height();
        var idwidth = $(getid).width();
        var idheight = $(getid).height();
        console.log(thisleft)
        $(getid + " .modal-content").css({left: thisleft - Number(idwidth/2) + Number(thiswidth/2), top: thistop - Number(idheight/2) + Number(thisheight), opacity:0.2});
    });

Comment: I'm guessing this is working on an older BS version.  I had to adjust data-bs-target to  $(this).attr("data-target"); to get to work.


Getting random path hierarchy for CCK fields inside form array

Question: I have created a custom entity and i'm using CCK fields. Each bundle has it's own fields. For example:
function MYMODULE_install() {
  // Check if our field is not already created.
  if (!field_info_field('field_myField')) {
    $field = array(
        'field_name' => 'date_field',
        'type' => 'list_text',
    );
    field_create_field($field);
}

//Enable is executed only once.
function bundle_callback_enable() {

     // Create the instance on the bundle.
    $instance = array(
        'field_name' => 'date_field',
        'entity_type' => 'payment_method',
        'label' => 'Expiration Date',
        'bundle' => 'card',
        'required' => TRUE,
        'settings' => array();

    field_create_instance($instance);
}

My bundles are created from individual modules, so in each install file i am creating the respective fields.
Yesterday i tried to add validation callback functions in those fields and i saw something weird inside form array. Fields with type="text" had the path:
$form[field_name]['und'][0][value] //<! expectable

but fields with type='list_text' had only the path:
$form[field_name]['und'] //<! unexpectable

I couldn't find any solution and i've solved it with this:
function &get_cck_path_value( $field_name, &$form_path) {

  $field = null
  if ( isset( $form_path[$field_name][LANGUAGE_NONE] ) ) {
     $field = &$form_path[$field_name][LANGUAGE_NONE]
  }elseif(isset($form_path[$field_name][LANGUAGE_NONE][0])) {
    $field =  &$form_path[$field_name][LANGUAGE_NONE][0]['value'];
  }
  return $field;
}

I don't like this approach. Is too hucky. Can you tell me if that is a cck feature or bug?
I can't understand when it decides where to put the values( All the process is fulfilled through the "field_attach_form( ... )" )?
Have you faced any problem like this?
Thanks in advance.
Thandem.
Answer: I believe that you are seeing the abbreviated form field in validation because the field had no value entered into it and no default value was defined for it. There is no value, so no array is present to store the value.
Comment: Ed it isn't the abbreviated form field. When i'm using the dsm function i'm seeing in fields with type list_text this:


USB 3.0 memory stick fails with "SEL for device-initiated U2 failed"

Question: This is a Kingston Data Traveler Ultimate G3 memory stick. Device works fine on Windows (same hardware), but it doesn't show up in lsusb on an Ubtuntu 16.10 with Kernel 4.4.0.
dmesg shows the problem:
<code>dmesg | grep -i usb

[63864.126086] usb 2-3.1: new SuperSpeed USB device number 39 using xhci_hcd
[63864.156440] usb 2-3.1: New USB device found, idVendor=0951, idProduct=1697
[63864.156445] usb 2-3.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[63864.156447] usb 2-3.1: Product: DT Ultimate G3
[63864.156449] usb 2-3.1: Manufacturer: Kingston
[63864.156451] usb 2-3.1: SerialNumber: -redacted-
[63869.157678] usb 2-3.1: Set SEL for device-initiated U2 failed.
[63869.157771] usb-storage 2-3.1:1.0: USB Mass Storage device detected
[63869.158411] scsi host38: usb-storage 2-3.1:1.0
[63869.159752] usb 2-3.1: USB disconnect, device number 39
</code>
If I leave the device connected it will infinitly loop recognizing the device then failing settig SEL for device-initiated U2 and disconnecting the device, then reconnecting, failing again and so on.
Please advise
Answer: It sounds very weird, but try inserting flash drive very slowly into the port. Helped for me.
Source: https://bugzilla.redhat.com/show_bug.cgi?id=1295579
Comment: Oddly enough that fixed my problem (I also tried another USB port so maybe that?)


Capacitor javascript new file bytes shows instead of file name

Question: I have an app in a capacitor where I want to convert base64 to File object.
I am using code from this answer, this works fine on the web but when I try to run in the actual android app it is returning a strange file object.
Data from bytes array shows in name instead of actual name, and name shows in localURL.
new File(['bytes'], 'test.png')

This works fine in web, but when I run it as native app
Result of this in web
File {name: "test.png", lastModified: 1623044932737....

Result of this in app
File {name: ['bytes'], lastModified: 1623044932737....

I tried switching parameters as well but still no luck.
Comment: It would appear you may have your constructor params backward. new File(array, filename) seems to be what it's looking at based on your screenshot, but yet the name and local URL props are showing the opposite of what you want them to. This leads me to think your params are backward.
Comment: Also, check this page from the android docs about the File object: https://developer.android.com/reference/java/io/File
Comment: I tried params backward as well but no luck with that either.
Comment: Please don't post images of code or errors. See [ask].
Comment: @DivyeshSavaliya can you post the snippet of code where you're creating this file? Would help immensely
Answer: The problem was when i run app on native device, it has cordova-plugin-file installed and its definition is
var File = function (name, localURL, type, lastModifiedDate, size) {
Which is overriding the existing javascript file function.
Comment: How did you assign the data to the file then?


Categorize the output of ec2-describe-images or ec2-describe-instances

Question: Is there any command/tool/script to categorize the bulky output of ec2-describe-images or ec2-describe-instances.
I have a list of around 100 servers with each and every detail. I want to categorize them under suitable headings like - RESERVATION, INSTANCE, BLOCKDEVICE, TAG (whatever category is available on the output).
Comment: Please give an example of `ec2-describe-images` output.
We will also appreciate if you can report here the response of the same question you posted on http://www.linuxquestions.org/questions/showthread.php?p=4574853#post4574853
Answer: Did you get this sorted? If not...
run ec2-describe-images with the option --headers to give you the categories
ec2-describe-images --private-key ~/private.key --cert ~/my.crt --region us-west-1 --headers

if you just want certain fields then just pipe the output of the above through the linux command cut picking the fields (columns) you are after. Say you want ImageID, Name and Architecture then these would be fields 2,3 and 8 of the output above. Example.
 ec2-describe-images --private-key ~/private.key --cert ~/my.crt --region us-west-1 --headers | cut -f2,3,8 -s

Doing the same for ec2-describe-instances would be similar.
Answer: It's a job for awk (or perl, python or other general purpose scripting language).
awk can handle records with various record/field length, can create associative arrays, and it's a reporting language, which is usually installed on every *nix.
Answer: Add this to your ~/.bashrc or ~/.bash_profile:
ez-ec2-describe-instances() {
    ec2-describe-instances $* --headers | egrep '(ReservationID|running|pending)'|cut -f 2,3,4,6,7,10,12;
}

Logout/login or run ". ~/.bashrc". Then you can use:
$ ez-ec2-describe-instances
ReservationID   Owner   Groups
i-6f194113  ami-1624987f    ec2-107-20-75-13.compute-1.amazonaws.com    running t1.micro    us-east-1a

You can pass arguments to ez-ec2-describe-instances, just like you would pass them to the regular ec2-describe-instances. E.g.:
$ ez-ec2-describe-instances --region eu-west-1
ReservationID   Owner   Groups
i-e4fd6eaf  ami-c37474b7    ec2-54-246-38-35.eu-west-1.compute.amazonaws.com    pending t1.micro    eu-west-1a


if $T: V \rightarrow V$, $T^{n} = 0$ then $I-T(x)$ is bijective.

Question: Trying to show thaT If
 $T: V \rightarrow V$, $T^{n} = 0$ then $I-T(x)$ is bijective.
There is a hint that in polynomials $(1-t)(1+t) = 1 - t^2$.
Not sure where to start.
Comment: Its inverse is $I+T+T^2+\ldots +T^{n-1}$.
Comment: A relevant [question](http://math.stackexchange.com/questions/960111/linear-maps-prove-if-t2-0-then-i-t-is-bijective?rq=1)
Answer: Hint:
$$I-T^n=I.$$
Then factor $I-T^n$.
Answer: The hint handles the $n=2$ case: $(I-T)(I+T)=I-T^2=I$, so $I-T$ is invertible. What is the right generalization of $1+t$ for general $n$?
Comment: For n: it is $(1+T+T^2+...+T^{n-1})$ will be the inverse $I-T$
Comment: Yes, that's right.
Answer: If $T^n = 0$ then the characteristic polynomial of $T$ is $x^i$ for some $i \leq n$. This means that the only eigenvalue of $T$ is $0$. $T-I$ is bijective as $1$ is not an eigenvalue, hence $-(T-I) = I-T$ is bijective.
Answer: Since $T^n=0$ we have $I-T^n=I$, so if we factor that expression we get:
$$I=I-T^n=(I+T+T^2+...+T^{n-1})(I-T)$$
So we see that $I-T$ has an inverse because if we multiply $I-T$ by $I+T+T^2+...+T^{n-1}$ we obtain the identity operator. Since $I-T$ is invertible it is bijective.
Answer: Suppose $(I-T)x = 0$, then $x=Tx$ so that $x$ is a fixed point. Since $T$ is nilpotent this requires $x=0$ hence $I-T$ is injective.
For any $y$ define $y'=\sum_{k=1}^{n-1} T^ky$. Then $Ty' = y'-y$ which may be written $y=(I-T)y'$, showing $I-T$ is surjective.


Azure ASP.NET MVC: avoiding ~3 minute Request Timeout?

Question: I'm trying to download a 100MB file from an ASP.NET MVC controller, but I'm getting timeouts after 3-4 minutes (it varies).
<code>    public ActionResult DownloadMyFile() {
        Server.ScriptTimeout = 60 * 60; // 1 hr timeout for downloading myfile

        Response.AddHeader("Content-Disposition", "attachment; filename=myfile");
        Response.BufferOutput = false;

        this.CloudBlobContainer
              .GetBlobReference("myfile")
              .DownloadToStream(Response.OutputStream);

        return new EmptyResult();
    }
</code>

This doesn't happen on my local machine running it as an ASP.NET MVC application directly, I suspect this is something in the azure stack (the IIS server???).
The timeout appears to be time-based, not file-size based.
The timeout does NOT return an error to browsers, they think they got the whole file and stop with a report of success (!!!).
The file is currently hosted on Azure Storage, but could come from another source in the future, so I don't want to just redirect to a blob storage URL.
This is a rarely used admin-only method and doesn't need to be optimized/complicated to be async or whatever unless this is really the only way to do it.
Comment: @Seth Did you find any solution for this problem?
Comment: I have exactly the same problem... Yes an admin only method that I only want to run a couple of times. I just want a simple brute force way to temporarily increase my timeout limit. I am getting blank pages returned after about 3-4 minutes at the moment...
Comment: Me too.. strange issue, it just times out in 3 mins no matter what i do. The solution given below doesn't works
Answer: You could try to increase the execution timeout in the web.config.
The following changes the timeout to 1 hour (3600 seconds):
<code><system.web>
  <httpRuntime
      executionTimeout="3600"
    />
</code>
The default is 110 seconds
Comment: I'm having a similar problem, and the timeout is closer to 3.5 or 4 minutes than 110 seconds (~2 minutes), so I suspect this is not the problem.


Kubuntu 16.10 tearing issues

Question: After installing Nvidia drivers on the new Kubuntu release (16.10) I'm having issues with general screen tearing (moving windows around, scrolling in the browser etc.)
I'm using GTX 960.
Are there any settings I could change to fix this?
Answer: Graphic tearing is a widespread complaint about nvidia. I have not solved it in a Dell precision 5510, despite trying about 20 fixes. On the laptop itself, tearing is not horrible. On external monitor, it is awful. I get weird pie shaped tares.
If you google this, you will see this is not a Kubuntu problem. It is an Nvidia problem.
Things to try
Run nvidia-settings, find power setting and change to high performance.
Many posts will say set "Vblank", but that option disappeared in new version.
Kubuntu settings, under devices, has settings. Make sure compositor is on. It has buttons to turn.

Kubuntu 16.10 tearing issues


Derivative of a function on a manifold

Question: I want to show that:

Given $f,g \in C^\infty(M)$ defined in a differential manifold of dimension $n$ and $a \in M$, we have $$(dfg)_a=f(a)(dg)_a+g(a)(df)_a,$$

using the following proposition:
Let $M$ be a $n$-dimensional manifold.
Let $(U,\varphi)$ be a coordinate chart around $a$ with coordinates $x_1,\ldots,x_n$.
Then, if $f \in C^\infty(M)$ and in the coordinate chart $f \varphi^{-1} = \phi(x_1,\ldots,x_n)$, we have $$(df)_a=\sum_{i=1}^n \frac{\partial \phi}{\partial x_i}(\varphi(a))(dx_i)_a$$
My atempt: $$f(a)(dg)_a + g(a)(df)_a = f(a)\sum_{i=1}^n \frac{\partial \phi_2}{\partial x_i}(\varphi(a))(dx_i)_a + g(a) \sum_{i=1}^n \frac{\partial \phi_1}{\partial x_i}(\varphi(a))(dx_i)_a$$
So, $$f(a)(dg)_a + g(a)(df)_a = \sum_{i=1}^n [f(a)\frac{\partial \phi_2}{\partial x_i}(\varphi(a)) + \frac{\partial \phi_1}{\partial x_i}(\varphi(a))](dx_i)_a$$
Now confusion begins, I can't proceed but I know that:

$f\varphi^{-1}=\phi_1(x_1,\ldots,x_n)$
$g\varphi^{-1}=\phi_2(x_1,\ldots,x_n)$

I would greatly appreciate it if you give me some hint or solution.
Comment: Oh, I'm seeing that $fg=(\phi_1 \circ \varphi)(\phi_2 \circ \varphi) = \phi_1 \phi_2 \circ \varphi$
Answer: We have $$(dfg)_a = \sum_{i=1}^n \frac{\partial(\phi_1 \phi_2)}{\partial x_i}(\varphi(a))(dx_i)_a,$$
so $$(dfg)_a = \sum_{i=1}^n [\frac{\partial\phi_1}{\partial x_i}(\varphi(a))\phi_2(\varphi(a)) + \phi_1(\varphi(a))\frac{\partial \phi_2}{\partial x_i}(\varphi(a))](dx_i)_a,$$
then $$(dfg)_a = \sum_{i=1}^n [\frac{\partial\phi_1}{\partial x_i}(\varphi(a))g(a) + f(a)\frac{\partial \phi_2}{\partial x_i}(\varphi(a))](dx_i)_a,$$
which matches the attempt.

Derivative of a function on a manifold


SQL Server: How to order by date, if the date is < GetDate()

Question: Here's an interesting one... hope I can explain it well...
I have a collection of competitions in a single table in my SQL Server DB. I'm doing a full text search over them, which works fine. However, some of the competitions are closed, and I want these closed comps to show up after the open comps, while still respecting the rank we get from full text search.
So if I had an IsOpen bit feild, I would them ordered by
ORDER BY IsOpen DESC, KEY_TBL.Rank DESC

Now the problem is I don't have an IsOpen bit field. Instead, I have a ClosedDate field, which is a datetime.
So What I really need to do is something like:
ORDER BY (ClosingDate < GetDate()) ASC, KEY_TBL.Rank DESC

Anyone know how to do this?
Any ideas would be great! Thanks in advance.
-Ev
Answer: add (ClosingDate < GetDate()) to the SELECTed fields and order by that field
select ... , add (ClosingDate < GetDate()) as Foo
from ...
where ...
order by foo

possibly add (ClosingDate < GetDate()) will not be accepted, then you will have to use
    IF(add (ClosingDate < GetDate());1;0)
I don't know the syntax of that IF function by heart, look it up!
Comment: `CASE` is a better choice, but your algorithm is otherwise sound.
Comment: I'd just come to the same conclusion .. is there a select if(..) in TSQL? CASE is more flexible, since it is extensible to other conditions..
Comment: Thanks for the answer, it's the right idea that I was going for - a good steer in the right direction, but the syntax wasn't right -  I couldn't get either the ADD or the IF() workign, but I found the CASE and it worked well. Thanks.
Answer: ORDER BY
  CASE
    WHEN (ClosingDate < GetDate())
    THEN 1
    ELSE 0
  END ASC,
  KEY_TBL.Rank DESC

Comment: @DavidB - thanks a lot for that. It worked a treat. However, I'll mention here, that once I'd implemented your suggestion I realised I could get the same result by simply ordering by the ClosedDate! Haha, but yeah, this is what I asked - thanks for the quick answer! :)


Fast way to inverse B'CB+D

Question:
$\mathbf {A = B'CB}$, where $\mathbf A$ is of dimension $n \times n$, $\mathbf C$ is m by m, positive definite and symmetric, $\mathbf B$ is of dimension $m \times n$, and $n >> m$. Inversion of $A$ is computationally expensive. How can I take advantage of the fact that $\mathbf {A = B'CB}$ so that I can compute $\mathbf A^{-1} $ more quickly?
Furthermore, I want to know if there is a good way to inverse $\mathbf V$ where $\mathbf {V = B'CB + D}$ and $\mathbf D$ is a diagonal matrix. The economic interpretation of this formula is: $\mathbf C$ and $\mathbf V$ are covariance-variance matrices, $\mathbf B$ is $\beta$ loading matrix, $\mathbf D$ is residual variances. Same as above, the size of $\mathbf V$ $>>$ the size of $\mathbf C$.

Updated on Jul-21-2014  :
Thanks to @copper.hat I realized that $\mathbf {A = B'CB}$ is not invertible if B is not full rank. I'll edit my question as below:
I want to know if there is a good way to inverse $\mathbf V$, where

$\mathbf {V = B'CB + D}$,
$\mathbf V$ is of dimension $n \times n$,
$\mathbf C$ is of dimension $m \times m$, positive definite and symmetric,
$\mathbf B$ is of dimension $m \times n$,
$\mathbf D$ is a diagonal matrix, and the diagonal items are positive
$n >> m$.

Inversion of $\mathbf V$ is computationally expensive. How can I take advantage of the fact that $\mathbf {V = B'CB + D}$ so that I can compute $\mathbf V^{-1} $ more quickly?
The economic interpretation of this formula is: $\mathbf C$ and $\mathbf V$ are covariance-variance matrices. V is the cov-var matirx of all individual random variables. C is the cov-var matrix of some common factors.  $\mathbf B$ is $\beta$ loading matrix, $\mathbf D$ is residual variances.

More updates:
Notice that when $m = 1$, we have
$$
\mathbf {V^{-1} =  D^{-1} - \left(\frac{1}{1+\kappa }\right) \hat B' C \hat B}
$$
where
$$
\kappa = \sum_{i=0}^N \left(\frac{\sigma^2 \beta_i^2}{\theta_i^2 }\right)
$$
$$
\mathbf {B'} = \left(\beta_1, \beta_2, ... , \beta_N \right)
$$
$$
\mathbf {\hat B'} = \left(\frac{\beta_1}{\theta_1^2 },\frac{\beta_2}{\theta_2^2 },...,\frac{\beta_N}{\theta_N^2 }\right)
$$
$$
\mathbf C = \left(
        \begin{matrix}
        \sigma^2
        \end{matrix}
\right)
$$
$$
\mathbf D = diag \left(\theta_1^2, \theta_2^2, ... , \theta_N^2 \right)
$$
Is there a way to extend the formula above to cases where $m>1$ ?
Comment: How can $A$ be invertible if $n >m$?
Comment: A is n by n. In this question, assume that A, C and V are all invertible.
Comment: If $n>m$ then it is impossible for $A$ to be invertible.
Comment: Can you help me understand why A is not invertible when n>m? I'm not able to work out the proof of that. Also, if that's true, how about the second part of my question? Can I compute $V^{-1}$ easily by leveraging the fact that V=B'CB+D?
Comment: Any matrix $B: \mathbb{R}^n \to \mathbb{R}^m$, with $n>m$ must have a non-trivial kernel (that is, there is some $x\neq 0$ such that $Bx=0$. Hence $B^T CB x = 0$ also). This follows from the reduced row echelon form.
Comment: Thank you very much @copper.hat. You are absolutely right. I'll modify my question.
Answer: I solved a similar to the  original problem recently. Unfortunately I cannot give you a solution because I am working in a commercial company and don't have right to publish my results. However I can give you few hints.
1. Try to  build  recursion. $V_n^{-1}=f(V_{n-1}^{-1})$. Here $V_n$ is $nxn$ matrix built from $V_{n-1}$ by adding 1 row and 1 column.
2. Use Woodberry identity for building recursion, namely
EDITED
$$
    \left(D+B^TCB\right)^{-1} = D^{-1} - D^{-1}B^T \left(C^{-1}+BA^{-1}B^T \right)^{-1}B D^{-1},
$$
Playing with  1 and 2 I build an efficient way for inversion. More presicely I can calculate $x^TV^{-1}x$ and $\det V$ which are necessary for mulitvariate likelihoods. Since your model resemebles  me a multi factor model of risk - may be you don't need $V^{-1}$ but these quantities.
Actually Woodberry identity even without any recursion indeed gives you a way to inverse your matrix much faster, since $D$ is diagonal and $C$ has much smaller dimension. You just have inverse in a similar form
$$
V^{-1}=D^{-1}-\tilde B^T \tilde C \tilde B
$$
Comment: Big thanks! Having this Woodbury matrix identity is already a big step forward for me.
Comment: I edited my answer a bit to make your life a little easier :).

Fast way to inverse B'CB+D


NSWindowController/NSViewController "Presentation" setting in Storyboard

Question: What exactly does the Presentation option(in Attribute Inspector) do in StoryBoard for Cocoa.

It gives two options to select from

Single
Multiple

P.S When googled the title, results are related to powerpoint presentation
Answer: The presentation style affects "Show" segues. Possibly it affects other segues too, but I only tested a Show segue. I tested on OS X 10.10.5 (Yosemite) with Xcode 7.1.1.
If a window controller's presentation style is "Multiple" (the default), then a Show segue to the window controller always loads a new instance of the window controller from the storyboard. This means that you can end up with multiple instances of the window controller at once, each with its own window on the screen. By default those windows will stack on top of each other, so it won't be obvious what happened until you move or close one.
If a window controller's presentation style is "Single", and an instance of the window controller has already been loaded from the storyboard, and that window controller still exists (presumably because its window is still on screen), then a Show segue to that view controller will not create a new instance. Instead, the Show segue will bring the existing window controller's window to the front.
This behavior is useful if you want behavior like, say, Xcode's Devices window, where there can only be one such window. You create a "Devices" menu item in the Window menu in your storyboard, and connect it to the Devices window controller in the storyboard with a Show segue. Set the Devices window controller's presentation style to Single. Now the menu item will never create a second Devices window controller if one already exists.
You'll probably want to somehow set the window's excludedFromWindowsMenu property to true, so it doesn't appear twice in the Window menu (because by default it appends itself to that menu). You could, for example, use a subclass of NSWindowController that sets it:
class DevicesWindowController: NSWindowController {
    override func windowDidLoad() {
        super.windowDidLoad()
        window?.excludedFromWindowsMenu = true
    }
}

View controllers also have a presentation style, because you can also connect Show segues to view controllers. A Show segue connected to a view controller automatically creates a window controller to contain the view controller at runtime. The window controller's presentation style is effectively set to the view controller's, so you get the same singleton behavior if you set the view controller's presentation to Single.
As far as I can tell, the storyboard setting has no corresponding public property or method you can use in code.
If you connect the Show segue to a storyboard reference (new in Xcode 7), then the segue ignores the presentation style of the destination window controller, and acts as if it were "Multiple". This happens even if the destination is actually in the same storyboard as the reference.


Visual Studio Code: change debug panel's font size and font family and debug console input as well

Question: Is there a way to change the debug panel's font size and appearance in VS Code? I'm referring to the side panel where variables and their values are showed when debugging a program.
Note that I want to change only its font size, not that of the entire editor.
I've come across other similar questions here in Stack Overflow, but the solutions provided required to change the zoom level of the entire editor (and thus of the debug panel too), then adjust the editor's font size. However, as I mentioned before, that's not what I'm looking for. I've searched through the settings but couldn't find anything at all. To me, it seems like a very basic feature for a text editor to have, so I can't believe there's no way to do that.
I'm using VS Code 1.40.1 on Linux
Answer:
Paste these into your settings.json file USER section and change values to your liking.
Note that there is no fontWeight for debug console, but you can state the weight in the fontFamily, like in the example below.
lineHeight seems to be 1/3 bigger than fontSize by default, so that might be a good value to start with.

"debug.console.fontFamily": "Cascadia Code Light",
"debug.console.fontSize": 15,
"debug.console.lineHeight": 21,

Comment: Note: if lineHeight is set to 0 (zero), which is default, it's computed from fontSize. If you don't need extra line spacing, you don't need to set it.
Answer: I would assume the ability to change the debug's views' font/fontSize is coming as part of the ability to move those views to the Panel (See VS Code move debug tab (left panel) to bottom).
Added:
debug.console.fontSize
debug.console.fontFamily
debug.console.lineHeight
Previously, the size didn't apply to the debug console input.  To be fixed in v1.45, see https://github.com/microsoft/vscode/issues/90714 and https://github.com/microsoft/vscode-docs/blob/vnext/release-notes/v1_45.md#notable-fixes.strong text
Answer: I have 1.55.1 on Linux and still don't see an option for font size in the debug variables panel (which, as originally asked, is not the debug console). So to adjust the font size in the debug variables panel independently, use the Zoom feature to adjust the entire VS code application, and then use the available font size settings for Editor, IntegratedTerminal and DebugConsole to unzoom those three back to the desired smaller fontsize.