text:
Q: Sorting every column in a csv file I have a csv file with following entries:
    Year,Month,Company A, Company B,Company C, .............Company N
    1990, Jan, 10, 15, 20, , ..........,50
    1990, Feb, 10, 15, 20, , ..........,50

I am trying to sort the csv file data for Company A, and so on, till Company N.
My piece of code works fine for the 1st run in the loop, but fails for the 2nd.
    try:
        reader = csv.DictReader(open(self.filename,'r')) #Try and open the file with csv dictreader
    except IOError:
        print "Error Opening File -- Check if file exists"

    ncols = reader.next()
    print ncol.keys()
    for key in ncols.keys():
        if key != 'Month' and key != 'Year':
            print key
            result = sorted(reader, key=lambda d: float(d[key]))
            result = result[-1]
            #print "Year " ,
            print result['Year'],
            #print "Month ",
            print result ['Month'],
            print key,
            print result[key]

Output:
    Company-E
    2008 Oct Company-E 997
    Company-D

    Traceback (most recent call last):
    File "<pyshell#105>", line 1, in <module>
    read.ParseData()
    File "C:/Users/prince/Desktop/CsvRead.py", line 55, in ParseData
    result = result[-1]
    IndexError: list index out of range

A: I would suggest using pandas:
import pandas
df = pandas.read_csv(filename)
for col in df.columns:
    if col != 'Month' and col != 'Year':
        df = df.sort(col)
df.to_csv(out_filename, index=False)

A: The code did work by adding two more lines:
I needed to rewind the file to initial position.
fh.seek(0)
fh.next()
Here's the working piece of the code:
        actualResult = {}
        try:
            fh = open(filename,'r')
            reader = csv.DictReader(fh) #Try and open the file with csv dictreader

            #Get the field names in the file:
            fields = set(reader.fieldnames)
            if not fields or ('Year' not in fields and
            'Month' not in fields):
                raise BadInputFile(filename)
            companies = fields - {'Year', 'Month'}
            print companies
            for name in companies:
                #sorting the csv file data based on column data with Company Name as Key
                result = sorted(reader, key=lambda d: float(d[name]), reverse=True)
                result = result[0]
                tup = (result[name],result['Year'],result['Month'])
                if name not in actualResult.keys():
                    actualResult.update({str(name): tup})
                else:
                    raise BadInputFile(filename)
                fh.seek(0) #rewinding the file to initial position
                fh.next()  #Moving to the 1st row
        except (IOError, BadInputFile) as e:
            print "Error: ", str(e) # Invalid input file
            raise

        return actualResult


text:
Q: What makes the SE network higher quality than other Q&A sites (such as Yahoo! Answers)?
Possible Duplicate:
Stack Overflow vs Yahoo! Answers vs Experts-Exchange vs ProgrammingTalk etc

I've never really used a Q&A site different from the Stack Exchange. Browsing Yahoo! Answers gives me the feeling someone is pouring snow into my trousers and reminds me I'm happy where I am. But what is it that sets the Stack Exchange network apart? Is it better due to a number of conscious design decisions? What are those, how do those differ from other Q&A websites? Or is it better just because of its audience, and might we regress down to the Yahoo! Answers level as soon as Relationships & Dating goes live?
In summary, What is it that makes the SE network higher quality than other Q&A sites?

A: There are three things that set Stack Exchange apart from every other Q&A site:

*

*Laser sharp focus,

*Gamification, and

*Community moderation.

Gamification is what keeps us all hooked1, and the combination of our laser sharp focus and vigilant community moderation is what keeps the quality of the content high, it's really as simple as that. There's also the fact that Stack Exchange site's are free to use, but that's really only in contrast with a certain Q&A for Sex Change Experts.
1 Just got a Guru badge while I was writing this, it's shiny!

A: Just browsing through the list of questions on Yahoo Answers, I get the impression that there's no organization or quality control. There's also not a beacon for which experts can rally around. The community on Yahoo Answers is essentially, anyone!
When questions are asked, it just doesn't feel like there are experts there, not like there are on Stack Overflow. The top questions under the search for "programming" are all asking "What language should I learn", which is hardly a question that an expert programmer would ask.
Stack Exchange thrives by focusing experts on different topics. By having a separate site for Project Management, English, Physics and more, all with their own rules and community moderators, the community is able to attract experts, which leads to better questions.
When Relationships and Dating goes live, if it goes live, it too will get its own private beta, public beta, pro-temp moderators, and child meta site for discussing quality issues. During the private beta, members will ask questions that experts would answer, and this will help design a Q&A site much like others already on the network.
Like other Stack Exchange sites, there will be people who show up that try to make it into something it's not. Surely you see this happen on Stack Overflow every day when someone tries to post something off-topic or too broad. If I were a part of the Relationships and Dating community, I would certainly expect questions that don't show research effort to be closed early and often. I'd expect editing to occur, and guidance from the community for new users on how to ask good questions. Meta plays a big part in working through these issues, and it will likely be busy with lots of questions about what to put in the FAQ, what to do about questions about general dating advice, etc.
In short, there's a lot of work that goes into making Stack Exchange Q&A sites stand out above the competition, and I don't see it regressing as long as people are passionate about expert Q&A.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to highlight text with callouts? This screenshot is from a presentation by Brian Frezza at Wolfram Data Summit 2014.
In what clearly is a Mathematica notebook. How is the text highlighted with the callouts?

Some sample text (Julius Caesar) with computed parts-of-speech:
TextStructure[
  StringTake[
   Import["http://shakespeare.mit.edu/julius_caesar/full.html",
    "HTML"], {969, 1150}], "PartsOfSpeech"] //
 Query[1, 1, 1,
  All, {Query[1],
   Query[2, Values /* Replace[{Entity[_, pos_]} :> pos]]}]

{{Second,Adjective},{Commoner,Noun},{Nay,ProperNoun},{,,Punctuation},{I,Pronoun},{beseech,Verb},{you,Pronoun},{,,Punctuation},{sir,Noun},{,,Punctuation},{be,Verb},{not,Adverb},{out,Particle},{with,Preposition},{me,Pronoun},{:,Punctuation},{yet,Adverb},{,,Punctuation},{if,Preposition},{you,Pronoun},{be,Verb},{out,Adverb},{,,Punctuation},{sir,Noun},{,,Punctuation},{I,Pronoun},{can,Verb},{mend,Verb},{you,Pronoun},{.,Punctuation}}

A: I think this is an example closer to the requirements of the question:
dynamic linkage of LocatorPane and InputField.
InputField and Overlay and
DynamicModule[{z = 120},
 Panel@Column[{Style["Degree", 16],
    Overlay[{Experimental`AngularSlider[
       Dynamic[z, (z = Round[#, 1]) &], {0, 360},
       Experimental`BoundaryAction -> "Wrap", ImageSize -> 200],
      Graphics[{Text[
         Framed[Style[Dynamic[Round[z, 1]] \[Degree], 16],
          FrameStyle -> None], Scaled@{3/4, 4/10}, {-1, 1}],
        Text[Framed[Style[Dynamic[Round[z Degree, Pi/2^7]], 16],
          FrameStyle -> None], Scaled@{3/4, 4/10}, {-1, -1}]}]}, All,
     1], InputField[Dynamic[z, (z = Round[#, 1]) &],
     ImageSize -> {100, 24}, BaseStyle -> 16]}, Alignment -> Center]]

.
This is an example moving the framed text around even in a plot:
automatic-placement-of-legend-box-with-placed-equivalent-to-best-in-matplot
This shows how to define Your own overlay graphics and display them dynamically over a given background object:
optional-grid-in-overlay
From the Mathematica Overlay documentation stems the idea to overlay plot on texts:
Overlay[{StringTake[ExampleData[{"Text", "ToBeOrNotToBe"}], 400],
  Plot[Sin[E^-x], {x, 0, 5}]}]

The splines are done with Spline offered in the standard of Mathematica.
There is only the need to put this all together. There is an example over at the Mathematica Demonstration named Pottery Wheel to draw such nice Splines.
Only some simple steps to show such a nice text analysis in a slide show.
There are several problems open in this free sketch of a solution.
First we need a graphic primitive how to highlight the pos
"word" //
 Framed[#, FrameStyle -> Red, RoundingRadius -> 10,
   FrameMargins -> 10, Background -> Lighter@LightRed] &

This only works in the postfix form!
Now we need to get the pos tags into our text. It turns out that only
TextStructure["The cat sat on the mat.", "ConstituentStrings"]

works. The output is
{"(Sentence, ((NounPhrase, (Determiner, The), (Noun, cat)), \
(VerbPhrase, (Verb, sat), (PrepositionalPhrase, (Preposition, on), \
(NounPhrase, (Determiner, the), (Noun, mat)))), (Punctuation, .)))"}

That is not a string in Mathematica nor an expression.
We have to get rid of the Sentence and the Punctuation, and if punctuation is in the text we have to extra handle this as well.
I skip this passage and will add it later.
It is possible to cut text into sentences with a built-in.
After having converted the above construct to a string we can proceed further.
A possible reduction is
Grid[Partition[(Framed[#,
       FrameStyle ->
        Switch[ToString[#], "NounPhrase", Red, "Noun", Red,
         "Determiner", Red, "VerbPhrase", Blue, "Verb", Blue,
         "PrepositionalPhrase", Green, "Preposition", Green, _,
         False], RoundingRadius -> 10, FrameMargins -> 10,
       Background ->
        If[Switch[ToString[#], "NounPhrase", True, "VerbPhrase", True,
           "PrepositionalPhrase", True, _, False], LightGreen,
         If[Switch[ToString[#], "Determiner", True, "Noun", True,
           "Verb", True, "Preposition", True, _, False], LightRed,
          LightBlue]]] & /@ {NounPhrase, Determiner, The, NounPhrase,
      Noun, cat, VerbPhrase, Verb, sat, PrepositionalPhrase,
      Preposition, on, NounPhrase, Determiner, the, NounPhrase, Noun,
      mat}), 3] // Transpose]

This avoid the splines for the commentary texts to the in text places of the tags. It only uses POS tagging as built-in.
There is a nice solution how to do it on this community is places are well-defined: how can i route edges manually for a graph.
This is still far from this:

The biggest problem seem how to step further from POS tagging to the sentiment tagging of the original?
At present, I think on this AmbiguityFunction. We possibly need AmbiguityList.
Some insider hint was that the document was done in https://www.v7labs.com/document-processing!


text:
Q: Is there a way to resolve this "npm install" issue? I have a Vue 2 project running on a windows 10 system. My Node version is v16.13.0 and npm is 8.5.0. I got some errors when I tried serving the app, so I deleted the node_modules folder and tried to reinstall the packages. However, I keep on getting this instead.
npm WARN deprecated loadash@1.0.0: Package is unsupport. Please use the lodash package instead.
npm WARN deprecated source-map-url@0.4.1: See https://github.com/lydell/source-map-url#deprecated
npm WARN deprecated @hapi/topo@3.1.6: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated eslint-loader@2.2.1: This loader has been deprecated. Please use eslint-webpack-plugin
npm WARN deprecated @hapi/bourne@1.3.2: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated source-map-resolve@0.5.3: See https://github.com/lydell/source-map-resolve#deprecated
npm WARN deprecated chokidar@2.1.8: Chokidar 2 does not receive security updates since 2019. Upgrade to chokidar 3 with 15x fewer dependencies
npm WARN deprecated chokidar@2.1.8: Chokidar 2 does not receive security updates since 2019. Upgrade to chokidar 3 with 15x fewer dependencies
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated html-webpack-plugin@3.2.0: 3.x is no longer supported
npm WARN deprecated @hapi/address@2.1.4: Moved to 'npm install @sideway/address'
npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
npm WARN deprecated babel-eslint@10.1.0: babel-eslint is now @babel/eslint-parser. This package will no longer receive updates.
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated @hapi/hoek@8.5.1: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated @hapi/joi@15.1.1: Switch to 'npm install joi'
npm WARN deprecated svgo@1.3.2: This SVGO version is no longer supported. Upgrade to v2.x.x.
[##################] | reify:rxjs: timing reifyNode:node_modules/core-js Completed in 142899ms

This process gets stuck at the above line after which you get the following errors:
npm WARN deprecated source-map-url@0.4.1: See https://github.com/lydell/source-map-url#deprecated
npm WARN deprecated @hapi/topo@3.1.6: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated eslint-loader@2.2.1: This loader has been deprecated. Please use eslint-webpack-plugin
npm WARN deprecated @hapi/bourne@1.3.2: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated urix@0.1.0: Please see https://github.com/lydell/urix#deprecated
npm WARN deprecated har-validator@5.1.5: this library is no longer supported
npm WARN deprecated source-map-resolve@0.5.3: See https://github.com/lydell/source-map-resolve#deprecated
npm WARN deprecated chokidar@2.1.8: Chokidar 2 does not receive security updates since 2019. Upgrade to chokidar 3 with 15x fewer dependencies
npm WARN deprecated chokidar@2.1.8: Chokidar 2 does not receive security updates since 2019. Upgrade to chokidar 3 with 15x fewer dependencies
npm WARN deprecated resolve-url@0.2.1: https://github.com/lydell/resolve-url#deprecated
npm WARN deprecated html-webpack-plugin@3.2.0: 3.x is no longer supported
npm WARN deprecated @hapi/address@2.1.4: Moved to 'npm install @sideway/address'
npm WARN deprecated querystring@0.2.0: The querystring API is considered Legacy. new code should use the URLSearchParams API instead.
npm WARN deprecated babel-eslint@10.1.0: babel-eslint is now @babel/eslint-parser. This package will no longer receive updates.
npm WARN deprecated uuid@3.4.0: Please upgrade  to version 7 or higher.  Older versions may use Math.random() in certain circumstances, which is known to be problematic.  See https://v8.dev/blog/math-random for details.
npm WARN deprecated request@2.88.2: request has been deprecated, see https://github.com/request/request/issues/3142
npm WARN deprecated @hapi/hoek@8.5.1: This version has been deprecated and is no longer supported or maintained
npm WARN deprecated @hapi/joi@15.1.1: Switch to 'npm install joi'
npm WARN deprecated svgo@1.3.2: This SVGO version is no longer supported. Upgrade to v2.x.x.
npm ERR! code UNKNOWN
npm ERR! syscall lstat
npm ERR! path C:\Users\USER\AppData\Local\npm-cache\_cacache\content-v2\sha512\9d\0c\a9d28d7f98d75b4ced4f3ba9079304ab9a0674313fe3082a4d8b06d48c6a11378765061a89b6842e0a710e2b3813570834656882a10cba4b131e6d0561f0
npm ERR! errno -4094
npm ERR! UNKNOWN: unknown error, lstat 'C:\Users\USER\AppData\Local\npm-cache\_cacache\content-v2\sha512\9d\0c\a9d28d7f98d75b4ced4f3ba9079304ab9a0674313fe3082a4d8b06d48c6a11378765061a89b6842e0a710e2b3813570834656882a10cba4b131e6d0561f0'

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\USER\AppData\Local\npm-cache\_logs\2022-02-16T09_14_55_692Z-debug-0.log

A: I have the same issue when run npm i or npm i --legacy-peer-deps or npm i --force. I found this article is quite usefull : https://sebhastian.com/npm-warn-deprecated/ by running npm install --loglevel=error and solved my problem


text:
Q: Get the current and next value in a Jinja for loop Is there a way to iterate over a list in Jinja2 that can access the nth and (n+1) th element in a single iteration?
{% for x in my_list %}

{{x}}, {{x+1}} <-- this is wrong but hopefully highlights the problem

{% endfor %}

Also, does the for loop allow for a "step" increment?

A: Jinja has a loop.index variable that you can use to access the next value in your list:
@app.route('/')
def index():
    return render_template_string("""

            {% for x in my_list %}

                    {{ x }} {{ my_list[loop.index] }}

            {% endfor %}

    """, my_list=range(10))

0 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
9

A: As of Jinja v2.10, we can use loop.nextitem instead of the my_list[loop.index] trick. Similarly loop.previtem is also available. :-)
From the above hyperlinked changelog:

Added previtem and nextitem to loop contexts, providing access to the previous/next item in the loop. If such an item does not exist, the value is undefined.

A: Maybe an example with loop.nextitem would help.
The value I'm monitoring is in the first column of my list of rows.
Try something like this:
{% for row in mylist %}
    {% if row.rowtype == "Selection" %}
        {% if loop.changed(row.rowid) %}

{{ row.rowprompt }}:
            <select name="{{ row.rowname }}" id="{{ row.rowname }}">
            <option value="{{ row.rowvalue }}">{{ row.rowvalue }}</option>
             {% set isSelectStart = 1 %}
        {% else %}
                <option value="{{ row.rowvalue }}">{{ row.rowvalue }}</option>
        {% endif %}
        {% if loop.nextitem is defined and row.rowid != loop.nextitem[0] %}
                    </select>
        {% endif %}
        {% if loop.nextitem is not defined %}
                    </select>
        {% endif %}
    {% endif %}
{% endfor %}


text:
Q: Compiling error with MPFR package on mac When I try to compile the newly installed package MPFR I get the following error:
Undefined symbols for architecture x86_64:
  "_mpfr_init2", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I use Codelite on a macbook pro and I think I successfully installed the package using the instruction on the website.
Any ideas on how to solve it?

A: From the limited information given, I suspect that you are not linking the MPFR library during the linking phase of main.cpp. What is the exact command you are using?
Make sure that -lmpfr is passed at the end of the clang++ command, like so:
clang++ main.cpp -lmpfr

or:
clang++ main.cpp -c
clang++ main.o -lmpfr

If libmpfr.so is installed in a nonstandard place, then you need to tell the compiler where, using the -L option:
clang++ main.cpp -L"$MPFR_PATH" -lmpfr

or:
clang++ main.cpp -c
clang++ main.o -L"$MPFR_PATH" -lmpfr

If not, then please provide more information.


text:
Q: How can I improve this long-winded Python code? I have a data structure like this:
items = [
    ['Schools', '', '', '32'],
    ['Schools', 'Primary schools', '', '16'],
    ['Schools', 'Secondary schools', '', '16'],
    ['Schools', 'Secondary schools', 'Special ed', '8'],
    ['Schools', 'Secondary schools', 'Non-special ed', '8'],
]

It's a list of spending items. Some are aggregates, e.g. items[0] is aggregate spending on all schools, and items[2] is aggregate spending on secondary schools. Those that are not aggregates are items[1], items[3] and items[4].
How can I elegantly reduce the list so it only shows non-aggregate items? In pseudocode:
for each item in items
   check if item[1] is blank, if it is
       check if item[0] matches another item's[0]
       if it does and if that item's[1] isn't blank
           delete item
   check if item[2] is blank, if it is
       check if item[1] matches another item's[1]
       if it does and if if that item's[2] isn't blank
           delete item

Here's my (lame!) attempt so far:
for i in range(len(items)):
    i -= 1
    if items[i]:
        if items[i][1] == "":
            for other_item in items:
                if items[i][0]==other_item[0] and other_item[1]!="":
                    items_to_remove.append(i)
                    continue
        elif items[i][2]=="":
            for other_item in items:
                if items[i][1] == other_item[1] and other_item[2] != "":
                    items_to_remove.append(i)
                    continue
new_items = [ key for key,_ in groupby(items_to_remove)]
new_items.sort(reverse=True)
for number in new_items:
    temp_item = items[number]
    items.remove(temp_item)

This is just so ugly. What can I do better?
NB: I could use dictionaries instead of lists, if that would make life easier :)

A: Firstly, I suggest your data structure should look more like this:
items = [
    ['Schools', None, None, 32],
    ['Schools', 'Primary schools', None, 16],
    ['Schools', 'Secondary schools', None, 8],
    ['Schools', 'Secondary schools', 'Special ed', 4],
    ['Schools', 'Secondary schools', 'Non-special ed', 4],
]

We can sort them into a dictionary like this:
result = {}

for item in items:
    if not item[0] in result or not isinstance(result[item[0]], dict): result[item[0]] = {}
    if not item[1] in result[item[0]] or not isinstance(result[item[0]][item[1]], dict): result[item[0]][item[1]] = {}
    if not item[2] in result[item[0]][item[1]] or not isinstance(result[item[0]][item[1]][item[2]], dict): result[item[0]][item[1]][item[2]] = {}

    if not item[0]:
        result = item[3]
    elif not item[1]:
        result[item[0]] = item[3]
    elif not item[2]:
        result[item[0]][item[1]] = item[3]
    else:
        result[item[0]][item[1]][item[2]] = item[3]

And you should end up with a dictionary like:
result = {
    'Schools': {
        'Secondary schools': {
            'Non-special ed': '4',
            'Special ed': '4'
        },
        'Primary schools': '16'
    }
}

My routine could probably be optimized and made recursive.
Also, the numbers total to 24 -- is this an error on your part?

A: list_keys = [ "".join(x[:-1]) for x in items ]
for i in range(len(list_keys)-1):
  if not list_keys[i+1].startswith(list_keys[i]):
     print items[i]
print items[-1]

Here I find the "key" of each item, which is all entries in an item, concatenated, except the last value.
An aggregate item's key is always a prefix of succeeding items' keys, so we can use this test to detect aggregate items and dismiss them.
This alg. prints (on your input):
['Schools', 'Primary schools', '', '16']
['Schools', 'Secondary schools', 'Special ed', '4']
['Schools', 'Secondary schools', 'Non-special ed', '4'],

Note:
This assumes all items are ordered neatly in a tree structure (as your original data). If it's not, it'll be (slightly) more complicated as you'll have to sort the keys before the loop (and keep track of which key belongs to which item).

A: How about making your items objects?
class School (object):
    __init__(self, is_aggregate=false):
        self.is_aggregate = is_aggregate

A: I'm using a helper function that

*

*makes a set of the entries with more fine-grained data

*returns a function suitable for filter that removes aggregate items

Run your example data through this function, and it will give the desired output :)
def remove_aggregates(items):

    def mk_pred(index_i, blank_i, items):
        posts = set(x[index_i] for x in items if x[blank_i] != '')
        def pred(item):
            return not (item[blank_i] == '' and item[index_i] in posts)
        return pred

    items = filter(mk_pred(0,1,items), items)
    items = filter(mk_pred(1,2,items), items)
    return items

A: You've asked how to do so elegantly, and further, how to do so better. Your nota bene suggests that the structure you're working with is still malleable. If you want to be able to do so more elegantly, I would suggest changing the way the data is stored. Some options are:
Include an additional field in each list, which indicates whether it is an aggregate value or not:
items = [
    ['Schools', '', '', '32', True],
    ['Schools', 'Primary schools', '', '16', False],
    ['Schools', 'Secondary schools', '', '8', True],
    ['Schools', 'Secondary schools', 'Special ed', '4', False],
    ['Schools', 'Secondary schools', 'Non-special ed', '4', False],
]

Split your data into two lists:
items = [
    [
        ['Schools', '', '', '32'],
        ['Schools', 'Secondary schools', '', '8'],
    ],
    [
        ['Schools', 'Primary schools', '', '16'],
        ['Schools', 'Secondary schools', 'Special ed', '4'],
        ['Schools', 'Secondary schools', 'Non-special ed', '4'],
    ],
]

Make the aggregate values contain a list of their children (although this still wouldn't be much fun to reduce):
items = [
    ['Schools', '', '', '32', [
        ['Schools', 'Primary schools', '', '16', []],
        ['Schools', 'Secondary schools', '', '8', [
            ['Schools', 'Secondary schools', 'Special ed', '4'],
            ['Schools', 'Secondary schools', 'Non-special ed', '4'],
        ],
    ],
]

I would say that the current structure of your data does not allow you to do anything elegant with it. You require logic along the lines of "if this index is blank but it isn't for another entry that has the same value at another of my indexes", and this has to be done twice per list entry, because that logic can occur at two separate pairs of index locations. Fix the way you store your information, and you will be able to write an elegant method of reducing that data.
For example, if you went with the first option I listed (using booleans to indicate whether the entry is aggregate), you could reduce the list with:
reduced = [item for item in items where item[4] == False]

A: This attemp tries not to be dependend of sorting of the input:
items = [
    ['Schools', '', '', '32'],
    ['Schools', 'Primary schools', '', '16'],
    ['Schools', 'Secondary schools', '', '16'],
    ['Schools', 'Secondary schools', 'Special ed', '8'],
    ['Schools', 'Secondary schools', 'Non-special ed', '8'],
]

def path(item,upto=None):
    return ".".join([p for p in item[:-1] if p][:upto])

from collections import defaultdict
children_counter = defaultdict(int)
for i in items:
    children_counter[path(i,-1)] += 1

for i in items:
   if children_counter[path(i)] == 0:
        print i

A: You could use a list comprehension, as follows:
items = [a for a in items if a[1] != '' and a[2] != '']

Or, if an empty string in any position denotes an aggregate item:
items = [a for a in items if '' not in a]

Of course, you don't necessarily need to assign the reduced list to items - you can use it however you like.


text:
Q: Adding an object to an array in a separate class edit:
I am looking to pass HomeBuyers Objects to my homeBuyers ArrayList in my CreditUnion class. The this.homeBuyers.add function throws a "cannot find symbol" error. I have tried making the firstName, lastName, and creditScore vars static and passing the object in with HomeBuyers(HomeBuyers.firstName, HomeBuyers.lastName, HomeBuyers.creditScore). That avoided errors but did not add the object to the ArrayList.
public class LabProgram {

public static void main(String[] args) {

    CreditUnion cu = new CreditUnion();

    cu.addHomeBuyer(new HomeBuyers("first","last",600));

    }

}

  public class HomeBuyers {
    public String firstName;
    public String lastName;
    public int creditScore;

public HomeBuyers(String firstName, String lastName, int creditScore) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.creditScore = creditScore;
  }

  }

   public class CreditUnion {
     public ArrayList<HomeBuyers> homeBuyers;

public CreditUnion() {
    this.homeBuyers = new ArrayList<>();
      }

public void addHomeBuyer(HomeBuyers homeBuyers) {
     this.homeBuyers.add(HomeBuyers(firstName, lastName, creditScore));
}

A: You have multiple problems here.
The right syntax for creating a new object is new HomeBuyers(...). Not HomeBuyers().
Separately, firstName doesn't exist as a variable in your addHomeBuyer method. The only variable that does exist is homeBuyers. You could write homeBuyers.firstName. However, you already have an instance of your class HomeBuyers. There is no need to make another one with identical values. this.homeBuyers.add(homeBuyers) would have done the job.
These questions are incredibly simplistic; stack overflow probably isn't the right venue. I suggest any of the many nice tutorials out there, they tend to take a little more time to explain things in an orderly fashion.


text:
Q: Getting Updated HTML Source I'm trying to get the HTML source code of a website that doesn't have all content available right off the bat. The reloading of HTML is done via JavaScript. When I try to connect to the URL and get the HTML it will not contain everything.
This is my code so far:
import java.io.IOException;

import org.jsoup.Jsoup;

public class AudioLibrary
{
    public static void main(String[] arguments) throws IOException
    {
        String htmlSource = Jsoup
                .connect("https://www.youtube.com/audiolibrary/music").get()
                .html();
        System.out.println(htmlSource);
    }
}

How do I make sure that JavaScript finishes its job before retrieving the HTML source? In my case it obviously is the list of free downloadable music from the YouTube Audio Library.

A: JavaScript runs in the browser, so all you will get is the basic page, probably with the JavaScript code, but not the final, modified HTML page, created by the JavaScript since you never execute the JavaScript.
You are downloading basically a text file (HTML). That's it. If you were a browser, you would now run the JavaScript in the page which would then modify this HTML. But since you don't run the JavaScript, nothing gets modified and you are stuck with the basic page.


text:
Q: Javascript map to array, get and set let myMap = new Map();

myMap.set(1, [1,2,3]);
myMap.set(1, myMap.get(1).push(4));

console.log(myMap);

In the above code, 1 is mapped to the array [1,2,3]. Then I want to add 4 to this array. However when I do a console.log, myMap turns out to be just 4 and not the array [1, 2, 3, 4]
Why?
But if I do
olds = myMap.get(1);
olds.push(4)

then things work as expected.

A: It's because push returns the new length of the array which happens to be 4 in this case and you are setting it to be the new value. You are basically doing this:
// ...
const new_length = myMap.get(1).push(4);
myMap.set(1, new_length);

A: Your instruction myMap.set(1, myMap.get(1).push(4)); actually translates to myMap.set(1, 4) as the length of the array is returned on the push method.
I think what you want to do is myMap.get(1).push(4) which will assign [1, 2, 3, 4] to 1 in myMap. (but still return the length of the array)


text:
Q: MongoDB schema design for document that can be embedded or stand alone I am relatively new to MongoDB and am still getting used to schema design.
In a project that I am currently working on, users can tag files that they upload. There are three types of tags: descriptive, brand, and store_department. They are presented as three fields to the user but in reality they are merged together and saved as tags, i.e.:
"tags" : [
  {
    "type" : "descriptive",
    "tag" : "this is my tag"
  },
  {
    "type" : "brand",
    "tag" : "this is another tag"
  }
]

This is to make searching very easy. By using a type, I can present the user three distinct fields to encourage them to provide the information as well as then allow for more advanced queries such as search by brand or store department. A default search will just search for matching tags.
The issue is that I provide autocomplete functionality in all of the fields. As the user types in the "brand" field, all created tags of type "brand" are displayed that match their input. This is easily accomplished by having a stand alone tag collection. New tag documents are created and updated when the file document is saved. The autocomplete queries against the stand alone tag collection instead of the embedded tags for performance.
Something feels wrong with this design. It is a duplication of efforts in some regard but seems to work great as far as the user experience is concerned. I use Mongoid and to accomodate this design have had to create two models for my tag collections. One that defines the two attributes and a second that inherits from the first but adds the embedded_in macro.
I could see this pattern being useful in other instances as well: products and shopping carts, products and purchase orders, etc. Is there a better way?

A:
Something feels wrong with this design. It is a duplication of efforts in some regard but seems to work great as far as the user experience is concerned.

In a NoSQL database, you have to denormalize sometimes. This will lead to some amount of data duplication. But as it can greatly improve performance (and works great for user experience), this should be worth it.
So a collection with distinct tag name to be used for autocompletion might make sense. It will be much smaller than the non-distinct tags in the embedded documents. Nothing wrong with that approach.
This "master" collection would be a good place to add additional meta-data for the tag, for example the description and wiki Stackoverflow has for tags here.
Also, it might be better to have a separate field for every type of tag if there are only a few types. This way, you can index them separately.
"tags" : { "descriptive: [ "this is my tag" ],
           "brand": ["this is another tag" ] }


text:
Q: Cannot install node modules when deploying Azure App Service I have a Node.js App Service in Azure which I created following this tutorial and then adding some more stuff. My app consists in one file:
var http = require("http");
//var mongoClient = require("mongodb").MongoClient; // !!!THIS LINE!!!

var server = http.createServer(function (request, response) {
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end('Hello World\n');
});

var port = process.env.PORT || 1337;
server.listen(port);

Keep in mind the highlighted line for later.
Deployment
Since I am using MongoDB, I have this line in my package.config:
"dependencies": {
  "mongodb": "^3.0.1"
}

Azure must run npm install when deploying. So, following the Azure Guidelines for deployment, I have added a .deployment file:
[config]
command = bash deploy.sh

Note that my app is hosted on Linux. File deploy.sh takes care of running the command for installing npm deps:
if [ -e "$DEPLOYMENT_TARGET/package.json" ]; then
  echo Installing NuGetpackages.
  cd "$DEPLOYMENT_TARGET"
  eval $NPM_CMD install --production
  exitWithMessageOnError "npm failed"
  cd - > /dev/null
fi

The problem
If I keep that line commented, everything is fine. But if I uncomment it, then deployment fails. Locally it works on my box!, but not in the cloud. When inspecting deployment logs, I can see that the npm install command is executed:
Command: bash deploy.sh
Handling node.js deployment.
Handling KuduSync.
Kudu sync from: '/home/site/repository' to: '/home/site/wwwroot'
Ignoring: .deployment
Copying file: '.gitignore'
Copying file: 'LICENSE'
Copying file: 'README.md'
Ignoring: deploy.sh
Copying file: 'package.json'
Copying file: 'process.json'
Deleting file: 'deploy.cmd'
Ignoring: .git
Copying file: 'src/db.js'
Copying file: 'src/index.js'
Copying file: 'src/settings.json'
Copying file: 'src/data/info.js'
Copying file: 'src/data/page.js'
Detecting node version spec...
Using package.json engines.node value: >=6.9.1
Node.js versions available on the platform are: 4.4.7, 4.5.0, 6.2.2, 6.6.0, 6.9.3, 6.10.3, 6.11.0, 8.0.0, 8.1.0.
Resolved to version 8.1.0
Detecting npm version spec...
Using default for node 8.1.0: 5.0.3
NPM versions available on the platform are: 2.15.8, 2.15.9, 3.9.5, 3.10.3, 3.10.10, 5.0.3.
Resolved to version 5.0.3
Installing NuGet packages.
npm WARN lifecycle The node binary used for scripts is /usr/bin/node but npm is using /opt/nodejs/8.1.0/bin/node itself. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.
up to date in 2.885s
myuser-web-srv@0.1.0 /home/site/repository
npm ERR! missing: mongodb@^3.0.1, required by myuser-web-srv@0.1.0
`-- UNMET DEPENDENCY mongodb@^3.0.1

But mongodb does not get installed. Why?.
Using KUDU
If I log in the Kudu tools for my app service and open a Bash session, and run npm install --production under wwwroot, then mongodb is successfully installed :(

A: According to your description, I followed this tutorial to create my Node.js web app in Azure App Service on Linux. Azure App Service understands package.json and npm-shrinkwrap.json files and can install modules based on entries in these files. I just created the following package.json file and committed it to my bitbucket repository.
My repository:

package.json:

{
    "name": "app-service-hello-world",
    "description": "Simple Hello World Node.js sample for Azure App Service",
    "version": "0.0.1",
    "private": true,
    "license": "MIT",
    "author": "Bruce Chen",
    "engines": {
        "node": ">=6.9.1"
    },
    "scripts": {
        "start": "node index.js"
    },
    "dependencies": {
        "mongodb": "^3.0.1"
    }
}

Then, I checked the deployment traces under the "DEPLOYMENT > Deployment options" section of my azure web app via Azure Portal and retrieved the Running deployment command activity as follows:

Using KUDU, I found the dependencies have been successfully installed as follows:

Moreover, my deployment script could automatically generate successfully. I do not need to Custom Deployment Script.

A: It's an old question I know but I ended up here and wanna share that you can put a setting in app service configuration saying SCM_DO_BUILD_DURING_DEPLOYMENT=true which seem to be needed in some cases (when kudu detects its node it wont do npm install without this setting).


text:
Q: How to fix "could not open socket in Zend Mail (Zend Framework 2) Please help me fix problem on Mac OS, when I type on my windows, It works.
I try on my mac, it shows "could not open socket".
Everybody could help me.
public function indexAction(){
    $mail = new Mail\Message;
                $mail->setFrom('paradise.losebaby@gmail.com','Flyoverfly Training');
                $mail->addTo('thanhbvh@yahoo.com.vn','maithanh');
                $mail->setSubject('Xác nhận việc phục hồi mật khẩu');
                $mail->setBody('maithanh');

                $transport = new SmtpTransport;
                $option = new SmtpOptions(array(
                    'name' => 'smtp.gmail.com',
                    'host' => 'smtp.gmail.com',
                    'port' => 465,
                    'connection_class' => 'login',
                    'connection_config' => array(
                        'username' => 'myemail@gmail.com',
                        'password' => 'mypass',
                        'ssl' => 'ssl'
                    )
                ));
                $transport->setOptions($option);
                $transport->send($mail);
    return new ViewModel;
}

A: May be a firewall issue. However I'm pretty sure php-openssl doesn't installed/enabled on your OS. Under the hood Zend will call stream_socket_client() in order to connect to remote server.
As sending email through gmail requires security layer (SSL/TLS), stream_socket_client() will require open ssl support (ssl://).
So you must have ssl support on OS, check:

Or getting the list of supported socket transports:

And here goes some useful links:

*

*Roll your own PHP to support OpenSSL instead of Secure Transport (Mac)

*How to upgrade OpenSSL in OS X?

*Important note for curl users on OS X Mavericks 10.9

*fsockopen() (go to hostname option for details)

*Can't run Composer on my Mac Mountain Lion - openssl extension

*OpenSSL support in PHP under MAMP

*OpenSSL Version MacOSX Homebrew

*Building OpenSSL on your Mac (MacOS X)

*Zend Mail Abastract Protocol (stream_socket_client under the hoods)

*stream_socket_client()

*OpenSSL installation

*Net Transports

*stream_get_transports()


text:
Q: Can I use a 1D barcodes for an inventory tracking system? I am to develop an inventory tracking system (e.g. keyboards, mice, phones, etc.) I am wondering if it is possible to use 1D barcodes UPC standard for this, will I be able to track each individual item or can I only categories the assets?

A: Short version

I am to develop an inventory tracking system (e.g. keyboards, mice, phones, etc.)

You can start with a requirements analysis of the tracking system, without pinning down what technology or barcode format to use.
As part of the requirements analysis, you will decide what infrastructure and capabilities would be needed to meet the goals by making use of the information (that is to be attached to inventory items). Without that infrastructure, the information (e.g. barcode label) itself wouldn't serve any purpose.
Some basic motivations might be: tracking the whereabouts (location / position), inventory accounting (tracking the number of items), tracking the usage or current owner or persons responsible, security i.e. loss prevention (early loss detection).
(If you can share what your motivations are, this answer can be tailored better to suit your needs.)

I am wondering if it is possible to use 1D barcodes UPC standard for this,

You can use a 1D barcode format.
You can use the same barcode format that UPC uses, but it is highly unlikely you will want to pay hundreds of US dollars to register unique product codes for your items, if you are not in a business selling your own products for profit.
There are many more 1D barcode formats. Refer to Wikipedia articles on Barcode and GS1 (standards organization).

will I be able to track each individual item or can I only categories the assets?

It is your choice. You can devise your in-house item identification code scheme, convert them into barcode, print the barcode alongside the human-readable string on labels, and apply those labels to your items.

After the short version
After the requirements analysis, there should also be an analysis on the constraints.
To give a few (extreme) examples about constraints: if there is no network (neither Ethernet nor WiFi) and no cellular signal in the warehouse, or if the use of light is forbidden in the warehouse, or if there is no electricity, or if the environment is too harsh or unsuitable for electronic devices, these constraints need to be clearly documented in the analysis.

There are different barcode formats. Barcodes encode character strings; different barcode formats have their own character subset, therefore read about those. Read about Code 128.

In developing and deploying anything that use barcodes, the main considerations are:

*

*Decide the usage scope of the barcode. Is it for:

*

*Strictly internal use,

*Used by business partners also,

*Used by general public, such as retail channels

*Decide what information the barcode should carry:

*

*A unique category code

*A unique item identification code (two items from the same category will have different codes, as the code's purpose is to uniquely identify the item)

*A large amount of information needed for business operations (example: a shipping address barcode may contain the entire address, requiring use of high density barcode formats.)

*Decide how barcode terminals and devices should use the data.

*

*Dumb devices must be attached to a computer in order to be useful, as all capabilities are to be implemented on the computer, not on the device.

*Capture devices will remember the barcodes scanned, which must then be transferred to a computer to access the capabilities. These are battery-powered for extended hours of operations between having to unload at a computer.

*Smart devices will have data input/output interfaces, so that most capabilities can be performed with the smart device.

*Smartphones, whether company-owned or bring-your-own-devices (BYOD), also count as smart devices. To use smartphones, a mobile application may need to be developed. Also, smartphone cameras are less reliable in capturing barcodes compared to dedicated scanning or imaging sensors. There are modification kits that adds a dedicated barcode sensor to smartphones.

*Decide the capabilities, scope, and implementation budgets for the infrastructure.

Projects like this are prone to scope creep. The best way to de-risk such projects would be to have a good "tinkerer" trying different existing technologies at a low cost to see how things would work out, before spending money to buy equipment or approving a budget for software development work.


text:
Q: Flask/Docker - data not send by 127.0.0.1 I have a flask app, if use "python app.py" to start the server, it runs perfectly. The browser client can get what I want.
However, if I use docker container, If I use below DockerFile:
FROM python:3.6.5-slim
RUN mkdir /opt/convosimUI
WORKDIR /opt/convosimUI

RUN pip install Flask
RUN pip install grpcio
RUN pip install grpcio-tools
ADD . .

EXPOSE 5000

ENV FLASK_APP=app.py

CMD ["python", "-u", "app.py"]

The browser (on windows) can not get response from server, in the linux container, everything works perfect and I can use wget to get content of 127.0.0.1, but outside the container, everything in container is not accessible.
If I change the lask line of DockerFile into:
CMD ["flask", "run", "--host", "0.0.0.0"]

Not use python app.py, then it works again.
Why this happen? And how if I want to use python app.py command?
It because there're some other parallel processing in app.py which I need to share the client of another service, and this client must be always on when turn on the web server. So I can not just put them in separate place.
Any ideas are welcome. Thanks!


text:
Q: $(...).autocomplete is not a function error I have the following files
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/boostrap-min.css" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />

Then I have javascript function

But is not working, is showing error
Uncaught TypeError: $(...).autocomplete is not a function
@using (Html.BeginForm("Index", "Produktet", FormMethod.Get, new { @class = "navbar-form navbar-left" }))
    {

        Search:@Html.TextBox("search", null, new { id = "txtSearch" })
        <input class="btn btn-default" type="submit" value="Search" />

    }

A: Comment out (or remove) the code I commented below. $(function() { }) is not going to initialize inside a $(document).ready() call.
 //$(document).ready(function () {
        $(function () {
            $("#txtSearch").autocomplete({
                source: '@Url.Action("MerrBarkodet","Produktet")'
            });
        });
 //   });

A: Possible causes for the issue.

*

*The order that jquery.js get loaded. jquery.js must be present before jqueryui.js

*Possible duplicate of jquery.js reference. Ensure that there is no jquery reference in your file. If you are implementing a layout file,or an external library ensure there is no jquery called there.

*try using the jQuery.noConflict() method for a test. It basically just makes you use a different alias for jQuery.
Ex:
var j = jQuery.noConflict();
j("div p").hide();

*Check that you're function call isn't getting hit before the document is loaded:
$(function(){
   var $searchBox = $('#txtSearch');
   $searchBox.autocomplete(...);
});


text:
Q: Do black holes have a graviton accumulation limit? Black holes seem to be a sink for baryons, photons, neutrinos and gravitons.
I understand a black hole accumulating vast amounts of the first three, but will a black hole become it's own gravity wave (or something) if it eats gravitons for long enough ?

A: No. When a black hole absorbs a graviton, it simply becomes more massive because the graviton has a tiny amount of energy. There is no limit to how many gravitons it can "eat".


text:
Q: How to get Images and CSS shown in login/error files for Tomcat authentication I have Tomcat authentication for my web app and my problem is that the login.jsp and error.html files used as login and error forms don't seem to support styling or images. I've tried getting the path of the files and they're showing that they're in the correct path, so I don't get it why they dont' support images or CSS? Any ideas how to enable css for this?
Edit:
Well I tested in the following manner, if I try to access a secure path and will get redirected to login.jsp which is in
D:\Dropbox\EclipseWorkspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp7\wtpwebapps\GenTreeUploader\

In the same directory where the login.jsp is there is index.html. and if I access it directly it also opens and it shows that it's in the same directory as for the login.jsp. Now the differences are that for index.html css and images work and for login.jsp they don't, the files have basically the same templates for styles. The directory is the same as Web Content as shown in the pic below:

My login.jsp has this code in it:
 <!DOCTYPE html>

        <meta charset="utf-8">
        <TITLE>GenTreeFromWord (GDIA) </TITLE>
        <link rel="stylesheet" href="bootstrap/css/bootstrap.css">

Go back to GMIS

GenTreeFromWord (GDIA)

Contact

About

                        Welcome to GDIA

                        <% System.out.println(request.getRealPath("/")); %>

                        <%

                        String url = ((HttpServletRequest)request).getRequestURL().toString();
                        String queryString = ((HttpServletRequest)request).getQueryString();

                        System.out.println(url + "?" + queryString);

                        %>

                        <form class="form-signin" name="credentials" action="j_security_check" method="post">

Please sign in

                              <input type="text" name="j_username" class="input-block-level" placeholder="Username" tabindex="1">
                                <input type="password" name="j_password" class="input-block-level" placeholder="Password" tabindex="2">
                            <button class="btn btn-large btn-primary" type="submit" value="Login" tabindex="3">Sign in</button>

                        </form>

A: The answer to this problem is the same as for the problem in here:
Tomcat redirects to wrong url after logging in
Additional details would be, that by testing previously, the paths were messed up, so I changed them to absolute paths, I found this out by inspecting the source code of the login.jsp file... Thanks to everybody helping to formulate this answer.


text:
Q: css3 rotation doesn't work in IE9 This code allows me to slowly rotate images whenever the mouse is over one of them.
 .foo img {
     -webkit-transition: all 0.5s ease;
     -moz-transition: all 0.5s ease;
       -o-transition: all 0.5s ease;
      -ms-transition: all 0.5s ease;
          transition: all 0.5s ease;
    }
     .foo img:hover {
      -webkit-transform: rotate(-10deg);
     -moz-transform: rotate(-10deg);
      -o-transform: rotate(-10deg);
      -ms-transform: rotate(-10deg);
          transform: rotate(-10deg);
    }

It works in FF18 and Opera. However, I can't get it to work on IE9, even is -ms-transform should be the proper solution.
IE9 acts as if there's no specific css img:hover rule.
Any hints?
thanks

A: http://modernizr.com/download/
Modernizr should do the trick.


text:
Q: How to link package lib in react native ios? I tried to link packages using react native link command as well as manually and what does mean by Recovered References. my unlinked libs are showing there and how to resolve it?.
2.) Unable to link libRNvectoricons.a under Build Phrases > Link Binary With Libraries. could not find option there to link up.
Any help would be greatly appreciated.

A: Follow these steps:

*

*Delete the node_modules folder inside the project

*run npm uninstall react-native-app-auth

*run npm install react-native-app-auth --save

*run react-native link react-native-app-auth

*Then follow these steps (iOS Setup & Android Setup)


text:
Q: Цвет гистограммы Matplotlib Как изменить цвет гистограммы при переходе через 0?

A: import matplotlib.pyplot as plt
import numpy as np
s = np.random.normal(0, 100, 10000)
n, bins, patches= plt.hist(x=s, bins='auto', color='orange')
for bn, pt in zip(bins, patches):
    if bn<=0:
        pt.set_facecolor("b")

Аналогично можно раскрасить хоть каждый бин в отдельности.

A: colors = ['blue' if i > 0 else 'red' for i in y]
ax.bar(x, y, color=colors)


text:
Q: Postgres DISTINCT Query issue SELECT DISTINCT "Users"."id" , "Users".name,
  "Users"."surname", "Users"."gender",
  "Users"."dob", "Searches"."start_date"
FROM "Users"
  LEFT JOIN "Searches" ON "Users"."id" = "Searches"."user_id"
WHERE (SQRT( POW(69.1 * ("Users"."latitude" - 45.465454), 2) + POW(69.1 * (9.186515999999983 - "Users"."longitude") * COS("Users"."latitude" / 57.3), 2))) < 20
  AND "Users"."status" = true
  AND "Users"."id" != 18
  AND "Searches"."activity" = \'clubbing\'
  AND "Users"."gender" = \'m\'
  AND "Users"."age" BETWEEN 18 AND 30
ORDER BY ABS( "Searches"."start_date"  - date \'2016-07-07\' )

For some reasons the above query returns the following error:
for SELECT DISTINCT, ORDER BY expressions must appear in select list

I only want to return unique users but I really don't know what's wrong with it.
Thanks for your help

A: In Postgres, you can use DISTINCT ON to get one row per user id:
SELECT DISTINCT ON (u."id") u."id", u.name, u."surname", u."gender", u."dob", s."start_date"
FROM "Users" u LEFT JOIN
     "Searches" s
     ON u."id" = s."user_id"
WHERE (SQRT( POW(69.1 * (u."latitude" - 45.465454), 2) + POW(69.1 * (9.186515999999983 - u."longitude") * COS(u."latitude" / 57.3), 2))) < 20 AND
      u."status" = true AND
      u."id" != 18 AND "Searches"."activity" = \'clubbing\' AND
      u."gender" = \'m\' AND
      u."age" BETWEEN 18 AND 30
ORDER BY users.id, ABS(s."start_date"  - date \'2016-07-07\' );

Notice how table aliases make the query easier to write and to read.

A: Just doing what the error message says I would include the expression ABS( "Searches"."start_date"  - date '2016-07-07' ) in the SELECT list.  No need to change your query logic.
absdiffdate can be discarded later when processing the result.
SELECT DISTINCT "Users"."id" , "Users".name,
  "Users"."surname", "Users"."gender",
  "Users"."dob", "Searches"."start_date",
  ABS( "Searches"."start_date"  - date '2016-07-07' ) absdiffdate
FROM "Users"
  LEFT JOIN "Searches" ON "Users"."id" = "Searches"."user_id"
WHERE (SQRT( POW(69.1 * ("Users"."latitude" - 45.465454), 2) + POW(69.1 * (9.186515999999983 - "Users"."longitude") * COS("Users"."latitude" / 57.3), 2))) < 20
  AND "Users"."status" = true
  AND "Users"."id" != 18
  AND "Searches"."activity" = 'clubbing'
  AND "Users"."gender" = 'm'
  AND "Users"."age" BETWEEN 18 AND 30
ORDER BY ABS( "Searches"."start_date"  - date '2016-07-07' )

Will this new column results in possibly more records when DISTINCT is applied?
I don't think so because you are subtracting a constant from start_date and for similar start_date corresponds similar outcome.


text:
Q: Rails: = provide(:title, t('.title')) fails if there is a single quote I can't figure out how to fix a problem with a title translation that contains a single quote. More of that it happens only when calling
= provide(:title, t('.title'))

When referencing the same YAML translation as H2, it is displayed correctly:
.row
  h2 = t('.title')

Here is a line of YAML translation line:
home:
    faq:
      title: FAQ
    about:
      title: "À propos d\'Entreprise"

The title is displayed as follows
À propos d'Entreprise

Any idea about how to solve that ? Thank you.
OS: OS X
Rails 4.2.5
Ruby 2.3.0
YAML

A: Found out how to fix that. I think it is due to the way that Slim interprets code snippets
So here is what I had in application.tml.slim:
title =full_title(yield(:title))

The working version is:
title ==full_title(yield(:title))

Hope this helps.


text:
Q: How to check if previous command asked for input? This question is related to this one in case someone is interested.
I want to write script like that
$@ | tee /tmp/unique_name
if [[ "${pipestatus[1]}" -eq 0 ]]; then
    sleep 2
    tmux select-pane -t.0 \; resize-pane -Z
elif [[ $(wc -l /tmp/unique_name | awk '{print $1}') -gt $LINES ]] && [[ $(grep pdb /tmp/unique_name) ]]; then
    tmux copy-mode
fi

Checking with grep would be just a heuristic that works only for one language, so I'd like to avoid that and to know for sure that program asked user for input.


text:
Q: What's a good and simple way to backup an SVN repo to an FTP server? I'd like to make a backup of my SVN repo using tar and ftp from a cronjob once a day. This is quite easy, but I would like to make sure there's no commit etc. running while the backup is made. While there are times of the day / night where this is highly unlikely, but I'd rather not rely on that, because if I'm already up at night in some crunch, the last thing I need is my SVN or my backups getting messed up.
I'm looking for some very simple but effective safeguard. It's OK if SVN clients get an error while the backup is running (it won't take that long). Should I use

*

*something on the filesystem level

*some SVN hook script

*something else entirely

I started posting this over at serverfault, but then decided that it is slightly closer to programming than to sysadmin, especially if hooks are involved. Feel free to move it if you think otherwise.

A: The theoretical way of doing a backup safely is to use the svnadmin hotcopy command (more details here). It basically does a copy of one repository (not a dump, a copy), taking care to block all the operations during that time.
This operation is quite fast, so I shouldn't think any client would have an error, they may experience some delay though (depending on the server load and so on).
You can find an example of script on the Apache subversion project website.
If you do a dump, besides the huge time it takes, you won't be sure it will done in an atomic way. Dumps are useful to

*

*make sure you can migrate from one version to the next - think long-term backups. For example if your server is upgraded from version 1.4 to 1.5, or to 1.6, it's interesting to make a dump then a load of your repositories to take full advantage of the improvements. In some more drastic upgrades it's a necessity because the repository format changes too much.

*filter files out, or merge repositories, those are more complex operations, out of topic here.

Before opting for a dump, should you prefer that anyway, I encourage you to do the operation manually before, to make sure it is not too long. Make sure also to compress those files, which are much bigger than a repository (hotcopy) - the latter is very well compressed.

A: svnadmin dump /path/to/repo > repobackup_date
Now you can run tar, gzip, whatever on repobackup_date and svnadmin should take care of controlling access to the repository for you.
To restore, use svnadmin load /path/to/repo < repobackup_date.

A: I do this for all of my production svn repositories.
You should always use svn dump to make a single-file backup of your repository. This makes sure there are no dirty transactions in flight, that could corrupt a filesystem copy. Then just use your favorite ftp app to copy the file over.
I suggest running the results of svn dump through gzip or some other zipping program first.

A: Use svnadmin dump to do a backup, then cURL to FTP upload.

A: Here there is a a text about repository backup and why you should use svnadmin hotcopy

A: I'd recommend using this svn-backup tool. It combines the best of both full and incremental repository backups, and will only ever generate a single backup file per repository, no matter how many times it is run or how many revisions are in the repository. This particular script will run much faster than a regular svnadmin dump because it only dumps additional revisions since the last backup.
I used this script to reduce the backup time of a very active subversion server from 8+ hours to ~20 minutes. Once the backup process is complete you can upload to an FTP server.


text:
Q: Use math equation in excel chart label I created a excel document for algorithm evaluation, and need to display a bar chart for visualizing, however I don't know how to place an equation to bar label.
I did a same thing with LaTEX and now I have to create another version with excel bar chart, please help me.
This is the latex result

A: *

*in order to really get the superscript characters to the chart, use an unicode font

*unicode fonts normally provide a complete set uf sub- and superscript characters ... I used Calibri - the superscript T is U+1D40 - "modified T"

*

*write Greek letters either using an Unicode font or e.g. Symbol ... I used Calibri here as well

*your formulae are the vertical axis titles

*your values are data

*select and press [Bar] to create a bar chart

note that in the first vertical axis title I used the U-1D40-T and additionally formatted it as "superscript" ... no effect in the chart (plain letters behave the same way)


text:
Q: Artifactory Enforcement of Standards for Deployed Artifacts Can Artifactory enforce the types of artifacts that are deployed to it?
Even better on a per-repository basis?
For example, if I want to deploy a tar.gz to repository x then it has to be 3-digit versioned
i.e. I can deploy 13.02.01.tar.gz but not 13.02.tar.gz
Thanks,
Sean

A: While this is not supported out of the box, your goal can be achieved via the User-Plugins extension mechanism.
You can take a look here, here, and here, for some ideas on how to achieve your goal.


text:
Q: Positioning networkx nodes by shared node attributes Is it possible to position nodes in a networkx graph so that nodes sharing a certain (single) attribute are clustered near each other?
For example, if the nodes represent people and each has an attribute 'age', how can I make it so that people of the same age are near each other when I draw the graph? Is this possible?

A: You can specify the x,y coordinates of each node.  So if you have some idea on how you want it to look it can be programmed.  You could try a spring layout but this isn't going to be hit or miss, it's going to be more misses.  The way to attempt it is by connecting the nodes of the same data to each other. (people of the same age have one or more edges between them)
The only way I see this working well with large amounts of data is using a tool called Gephi to manipulate by hand based on node data etc... it's like a photoshop of network graphs.

A: I would suggest yet another approach. Create an extra attribute for your nodes that corresponds to a range of values of the attribute you want to use for the grouping. For example, if your attribute is age, then create ranges 18-30, 31-40, etc. Save the result in GraphML format and load the network with NodeXL (which is not free anymore but you could buy it for a small fee)
In NodeXL you can group the nodes by some attribute and it lays out the different groups so that nodes belonging to the same group are laid out close to each other. You can also choose how nodes in a group are laid out, from a list of layout options)


text:
Q: Showing that the derivative of the integral is the function itself The task at hand is to show that the integral for some function $f$ obeying $\oint f(z) dz = 0$,
\begin{align*}
F(z) = \int_a^{z} f(w) dw,
\end{align*}
is well defined, and that it obeys the relation
\begin{align*}
\lim_{h\rightarrow0} \frac{F(z+h) - F(z)}h = f(z), \tag{$\dagger$}
\end{align*}
that is, the derivative of the integral is well defined to be the function itself.
Assuming I've already proven that the integral is well-defined (i.e. it is unique and it exists), I have to show that the derivative of the integral is the function itself (expression $(\dagger)$). I've managed to formulate a proof which I just handed in as "incomplete, but whatever" since I couldn't figure out what step to take next.
Now here comes the kicker, my TA graded the proof as sufficient and I'm puzzled as to why. Therefore my question is: why is my proof sufficient? Should I argue that I can keep choosing $w-z$ to be smaller so that the limit goes to zero? What's needed to understand my own proof (I know how silly this sounds...).

First I calculate what the function $f(z)$ integrated over variable $w$ is from $z$ to $z+h$ (why we're doing this will be apparent later)
\begin{align*}
\int_z^{z+h} f(z) dw = f(z) \int_z^{z+h} dw = h f(z) \Rightarrow f(z) = \frac{\int_z^{z+h} f(z) dw}{h}
\end{align*}
and calculate
\begin{align*}
\lim_{h\rightarrow 0} \frac{F(z+h) - F(z)}h &= \lim_{h\rightarrow 0} \frac{\int_a^{z+h} f(w)dw - \int_a^{z} f(w)dw}h\\
&= \lim_{h\rightarrow 0} \frac{\int^{z+h}_{z} f(w)dw+\int_a^{z} f(w)dw - \int_a^{z} f(w)dw}h\\
&= \lim_{h\rightarrow 0} \frac{\int_z^{z+h} f(w)dw}h.
\end{align*}
Now conclude
\begin{align*}
\lim_{h\rightarrow 0} \frac{F(z+h) - F(z)}h -f(z) &= \lim_{h\rightarrow 0} \frac{\int_z^{z+h} [f(w)-f(z)] dw}h.
\end{align*}
If we now use the ML inequality, it follows that
\begin{align*}
\left\lvert \frac{\int_z^{z+h} [f(w)-f(z)] dw}h\right\rvert = \frac1{\lvert h\rvert} \left\lvert\int_z^{z+h} [f(w)-f(z)] \right\rvert dw \leq \frac1{\lvert h\rvert} \varepsilon\lvert h\rvert = \varepsilon,
\end{align*}
for some constant $\varepsilon$, obeying $\lvert f(w)-f(z)\rvert <\varepsilon$ when $\lvert w-z\rvert <\delta$, $\delta>0$.

A: There's an important piece of information missing here, you don't say what is assumed of the domain of $f$ [you also don't mention that $f$ is assumed to be continuous, but that's inferable from the context alone].
If the domain of $f$ is assumed to be convex (and nonempty, to avoid trivialities), then the only point is that at the end you write "$\lvert \dotsc \rvert \leq \varepsilon$ for some constant $\varepsilon$, obeying $\lvert f(w) - f(z)\rvert < \varepsilon$ when $\lvert w-z\rvert < \delta$, $\delta > 0$". The correct order is that you first pick an arbitrary $\varepsilon > 0$, and then deduce that there is a $\delta > 0$ such that
$$0 < \lvert h\rvert < \delta \implies \biggl\lvert \frac{F(z+h) - F(z)}{h} - f(z)\biggr\rvert \leqslant \varepsilon.\tag{1}$$
By the continuity of $f$, for the given $\varepsilon$ there is an $\eta > 0$ such that $\lvert w-z\rvert < \eta$ implies $\lvert f(w) - f(z)\rvert < \varepsilon$, and choosing $0 < \delta \leqslant \eta$ so that $\lvert h\rvert < \delta$ guarantees that the straight line segment connecting $z$ and $z+h$ lies in the domain of $f$ then yields $(1)$ following your computation - of course for a convex domain, the latter condition is trivially satisfied, so one chooses $\delta = \eta$ (and doesn't even mention $\eta$). One can also put that informally at the end, writing something like "$\lvert\dotsc\rvert \leqslant \varepsilon$ for any given $\varepsilon > 0$ if $0 < \lvert h\rvert < \delta$ for an appropriate $\delta > 0$". In a complex analysis course, one might assume that it is known what "appropriate" means here, and that it can be correctly translated into [more] formal language. But it may be necessary to make the "appropriate" more explicit if one can't count on that assumption.
If the domain of $f$ is not assumed to be convex, there are some more small explanations missing, and your TA has been a bit magnanimous if they awarded full marks for it (the essential bits are there, so I wouldn't deduct much, but without a convexity assumption I'd have deducted some points).
First thing is that it's not said what $\int_a^z f(w)\,dw$ means. If the domain of $f$ is convex, or just star-shaped with respect to $a$, we have the standard interpretation that it should be the integral over the straight line segment connecting $a$ and $z$, and no explanatory remark is necessary. If the domain of $f$ is an arbitrary (nonempty) connected open set, it ought to be said that one chooses a path $\gamma$ (sufficiently regular for integration, that could mean piecewise $C^1$; rectifiable would suffice) from $a$ to $z$ and lets $\int_a^z f(w)\,dw$ denote $\int_{\gamma} f(w)\,dw$. Since the value of the integral is independent from the chosen path (as was shown before), the short-hand of dropping the path and mentioning only start and end points is legitimate.
Next, in your calculation you split $\int_a^{z+h} f(w)\,dw$ into $\int_z^{z+h} f(w)\,dw + \int_a^z f(w)\,dw$. The splitting is legitimate by the premise that the integral of $f$ over all closed paths shall vanish, and if the domain of $f$ is convex, there is no problem, as we can assume the standard interpretation of integrating over a straight line segment for the integrals. If the domain is not convex, the question is about the interpretation of $\int_z^{z+h} f(w)\,dw$. If that is to mean the integration over an arbitrary path from $z$ to $z+h$, that is valid, but doesn't help in the end. To reach the conclusion (by way of the ML inequality) we need $\int_z^{z+h} f(w)\,dw$ to mean the integral over the straight line segment connecting $z$ and $z+h$ (strictly, we can also take some other family of paths, but we need that the length of the path is bounded by $C\cdot \lvert h\rvert$ for some constant $C$, taking the straight line segment is most convenient and easy). So, without a convexity assumption, you should - at about that place - say that from now on you assume $\lvert h\rvert$ small enough that the straight line segment from $z$ to $z+h$ lies in the domain of $f$. (The domain is open, so there's an $r > 0$ such that the disk $D_r(z) = \{ w \in \mathbb{C} : \lvert w-z\rvert < r\}$ lies in the domain of $f$, then $\lvert h\rvert < r$ guarantees that.)
To recapitulate: First one picks an $r > 0$ so that for $\lvert h\rvert < r$, the straight line segment from $z$ to $z+h$ is contained in the domain of $f$. Then one uses the premise "$\oint f(z)\,dz = 0$" to see that - for $\lvert h\rvert < r$ - one has
$$F(z+h) - F(z) = \int_z^{z+h} f(w)\,dw,$$
where the integral means the integral over the straight line segment. Finally, one uses the continuity of $f$ at $z$ to have for every $\varepsilon > 0$ a $0 < \delta \leqslant r$ with $\lvert w-z\rvert < \delta \implies \lvert f(w) - f(z)\rvert < \varepsilon$. The ML inequality then shows that for $0 < \lvert h\rvert < \delta$ we have
$$\biggl\lvert \frac{F(z+h)-F(z)}{h} - f(z)\biggr\rvert < \varepsilon.$$


text:
Q: Trying to convert to exe from the py file I am trying to convert the py file to exe file but after conversion I have successfully converted the py to exe .But on clicking on the exe file the terminal just closes and open and nothing happens. My script displays a notification with a new word and its meaning  everyday when I run on the ide(Pycharm) but after the conversion to exe using auto-py-to-exe nothing is happening.I have also tried by importing the missing modules
import urllib.request  # used to send requests basically https requests
from bs4 import BeautifulSoup  # used to parse xml and html pages so that we can extract data from webpages. It
# creates a parse tree for webpages
import time
from plyer import notification

if __name__ == '__main__':
    url = "https://www.dictionary.com/e/word-of-the-day/"  # any url can be inserted here as u wish
    html_file = urllib.request.urlopen(url)
    soup = BeautifulSoup(html_file, 'lxml')  # for documentation check this https://zetcode.com/python/beautifulsoup/

    soup1 = soup.find(class_="otd-item-headword__word")  # inspect the page and find the specific data to crawl the
    # data from the html code

    try:
        soup1 = soup1.get_text()
    except AttributeError:
        print('No words for today. You have learnt enough')
        exit()

    txt10 = soup1.rstrip()  # The rstrip() method returns a copy of the string by removing the trailing characters
    # specified as argument.
    soup2 = soup.find(class_="otd-item-headword__pos")
    soup2 = soup2.get_text()
    txt11 = soup2.rstrip()
    soup3 = soup.find(class_="wotd-item-origin__content wotd-item-origin__content-full")
    txt = soup3.get_text()
    txt1 = txt.rstrip()

    notification.notify(
        title="*** WORD OF THE DAY ***" + "\n" + ' '.join(txt10.split()) + "\n",
        message="MEANING:" + ' '.join(txt11.split()),
        # app_icon=r"C:\Users\HP\PycharmProjects\MyProjects\book.ico",
        app_icon=r"C:\Users\purba\PycharmProjects\pythonProject\dictionary.ico",
        ticker=r"Vocab APP",
        app_name=r"PYTHON PROJECT: VOCAB APP 365",
        timeout=60
    )
    time.sleep(60 * 60)

A: This is normal behavior. The python script will exit immediately after it completed its job. To make your application hang before closing, you can add this code at the end of your script:
input("Press any key to exit...")

A: Follow these step or watch this YouTube tutorial:

*

*Install pip install pyinstaller module in python.

*Go to your python installed directories.
and open command prompt then install pyinstaller

*After open command prompt and type "pyinstaller --onefile -w then your file path or name

A:          pip uninstall typing

That should fix it. Thereafter run your pyinstaller code, your exe file will be created and when you run it, it won't crash.


text:
Q: How to make the chapter number 1 inch from top of page? I'm writing a thesis, and the department requires all main headings;i.e., chapter numbers (including the title of table of contents) to be 1 inch from top of of the page. I'm using \usepackage[margin=1in]{geometry}. In another post, someone suggested that I use
\usepackage{titlesec}
\titleformat{\chapter}[display]{\centering \Large}{\chaptertitlename\ \thechapter}  {1ex}{}{}
\titlespacing{\chapter}{0pt}{0pt}{0pt}

But still the headings are not 1 inch from top. Also this doesn't change the spacing for the title of table of contents.
Here's my code:
\documentclass[12]{report}
\usepackage[utf8]{inputenc}
\usepackage[margin=1in]{geometry}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{amsthm}
\usepackage{tikz-cd}
\usepackage{enumerate}
\usepackage{tocloft}
\usepackage{parskip}
\usepackage{indentfirst}
\setlength{\parindent}{1cm}
\usepackage{setspace}
\usepackage[nottoc]{tocbibind}
\usepackage{sectsty}
%\usepackage{hyperref}
%\usepackage[linktocpage=true]{hyperref}
\setlength{\cftbeforetoctitleskip}{2mm}
\renewcommand{\cftchapfont}{\normalfont}
\renewcommand{\cftchappagefont}{\normalfont}
\renewcommand{\cfttoctitlefont}{\hfill \Large}
\renewcommand{\cftaftertoctitle}{\hfill\hfill}
\renewcommand{\contentsname}{Table of Contents}

\usepackage{titlesec}
\titleformat{\chapter}[display]{\centering \Large}{\chaptertitlename\ \thechapter}{1ex}{}{}
\titlespacing{\chapter}{0pt}{0pt}{0pt}

\chapternumberfont{\centering \large}
\chaptertitlefont{\centering \large}
\sectionfont{\large}

\newtheorem{theorem}{Theorem}[section]
\newtheorem{corollary}[theorem]{Corollary}
\newtheorem{proposition}[theorem]{Proposition}
\newtheorem{lemma}[theorem]{Lemma}
\theoremstyle{definition}
\newtheorem*{definition}{Definition}
\theoremstyle{remark}
\newtheorem*{remark}{Remark}
\newtheorem{case}{Case}
\newtheorem{example}[theorem]{Example}\newcommand{\gen}[1]{\langle #1\rangle}
\newcommand{\F}{\mathbb{F}}
\newcommand{\Z}{\mathbb{Z}}
\newcommand{\C}{\mathbb{C}}
\newcommand{\N}{\text{N}}
\newcommand{\T}{\text{T}}
\newcommand{\Tr}{\text{Tr}}
\newcommand{\legendre}[2]{\ensuremath{\left(\frac{#1}{#2}}\right)}

% For signature page
\newcommand{\signaturerule}{\rule{20em}{.4pt}}
\newcommand{\daterule}{\rule{10em}{.4pt}}

\begin{document}

\input{Titlepage}

\pagenumbering{roman}

\setcounter{page}{2}\doublespacing

\tableofcontents

\pagebreak

% Abstract page

\addcontentsline{toc}{chapter}{Abstract}
\chapter*{Abstract}\pagebreak
\pagenumbering{arabic}

\chapter{Preliminaries}
\input{chapters/Preliminaries}

\chapter{Main Results}
\input{chapters/chapter2}

\chapter{}
\input{chapters/chapter3}

\chapter{}
\input{chapters/chapter4}

\bibliographystyle{plain}
\bibliography{bibliography.bib}
\end{document}

A: As far as I can see you've got the inch. See below, screenshot from Acroreader. To enable frames showing your layout settings use \usepackage[showframe]{geometry}. Frankly, geometry should do the job w.o. need for further adjustments.
What might be under discussion is the red area I indicated. However, I think moving sections headers fürther up can be demanded. But I'd make sure that's what they want you to do.
I adjusted your code a little bit, as we don't have your 5 files you \input. See % <<< in the code.

\documentclass[12]{report}
\usepackage[utf8]{inputenc}
\usepackage[margin=1in, showframe]{geometry}% <<<
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage{amsfonts}
\usepackage{amsthm}
\usepackage{tikz-cd}
\usepackage{enumerate}
\usepackage{tocloft}
\usepackage{parskip}
\usepackage{indentfirst}
\setlength{\parindent}{1cm}
\usepackage{setspace}
\usepackage[nottoc]{tocbibind}
\usepackage{sectsty}
%\usepackage{hyperref}
%\usepackage[linktocpage=true]{hyperref}

\usepackage{blindtext}% <<< workaround

\setlength{\cftbeforetoctitleskip}{2mm}
\renewcommand{\cftchapfont}{\normalfont}
\renewcommand{\cftchappagefont}{\normalfont}
\renewcommand{\cfttoctitlefont}{\hfill \Large}
\renewcommand{\cftaftertoctitle}{\hfill\hfill}
\renewcommand{\contentsname}{Table of Contents}

\usepackage{titlesec}
\titleformat{\chapter}[display]{\centering \Large}{\chaptertitlename\ \thechapter}{1ex}{}{}
\titlespacing{\chapter}{0pt}{0pt}{0pt}

\chapternumberfont{\centering \large}
\chaptertitlefont{\centering \large}
\sectionfont{\large}

\newtheorem{theorem}{Theorem}[section]
\newtheorem{corollary}[theorem]{Corollary}
\newtheorem{proposition}[theorem]{Proposition}
\newtheorem{lemma}[theorem]{Lemma}
\theoremstyle{definition}
\newtheorem*{definition}{Definition}
\theoremstyle{remark}
\newtheorem*{remark}{Remark}
\newtheorem{case}{Case}
\newtheorem{example}[theorem]{Example}\newcommand{\gen}[1]{\langle #1\rangle}
\newcommand{\F}{\mathbb{F}}
\newcommand{\Z}{\mathbb{Z}}
\newcommand{\C}{\mathbb{C}}
\newcommand{\N}{\text{N}}
\newcommand{\T}{\text{T}}
\newcommand{\Tr}{\text{Tr}}
\newcommand{\legendre}[2]{\ensuremath{\left(\frac{#1}{#2}}\right)}

% For signature page
\newcommand{\signaturerule}{\rule{20em}{.4pt}}
\newcommand{\daterule}{\rule{10em}{.4pt}}

\begin{document}

%\input{Titlepage}% ! MISSING

\blindtext{}% <<< workaround

\pagenumbering{roman}

\setcounter{page}{2}\doublespacing

\tableofcontents

\pagebreak

% Abstract page

\addcontentsline{toc}{chapter}{Abstract}
\chapter*{Abstract}\pagebreak
\pagenumbering{arabic}

\chapter{Preliminaries}
%\input{chapters/Preliminaries}

\blindtext{}% <<< workaround

\chapter{Main Results}
%\input{chapters/chapter2}
\blindtext{}% <<< workaround

\chapter{}
%\input{chapters/chapter3}
\blindtext{}% <<< workaround

\chapter{}
%\input{chapters/chapter4}
\blindtext{}% <<< workaround

\bibliographystyle{plain}
%\bibliography{bibliography.bib}
\blindtext{}% <<< workaround
\end{document}


text:
Q: How to get x value from mschart based on clicked mouse position Hello i have Mschart on a winform y axis is value 1,2 ... and x axis is date/time.I need to get the  time of the clicked point till i tried several version but i out of bussines
void detailChart_MouseClick(object sender, MouseEventArgs e)
{
    string ceva = detailChart.Series[1].Points[e.X].GetValueByName("X").ToString();
}

A: I have been battling with this with Line Charts for a few hours and came up with a solution using Cursor position and use the MouseUp or MouseDown event to get the date time object from the X axis.
You can change the Cursor colour if you need to hide it, and please refer to Cursors in the Chart Samples provided with MSCharts.
private void chartLine_MouseUp(object sender, MouseEventArgs e)
{
    DateTime dateTime = DateTime.FromOADate(chartLine.ChartAreas[0].CursorX.Position);
}


text:
Q: I get incorrect numbers while dividing two columns With this code and the attached photo why I get incorrect numbers ?!! In the last column in each row I want to get a division of two numbers in each row
priceofeachunit = DIVIDE(data_sales_20k[20KG_Bag_RevenueEUR],data_sales_20k[20KG_Bag_UnitsSold])


text:
Q: A new generalisation of Fermat's little theorem? I would like to share a personal result, which I interpret as a "generalisation of Fermat's little theorem". I know that there exist already several generalisations (e.g. Euler's) but I would like to know whether the result I found is something original or not. Let me explain...
Some years ago, my researches on binary representation of numbers lead me to this sequence of naturals: 1, 2, 1, 2, 3, 6, 9, 18, 56, ... . After some researches, I found that this was already indexed as A001037 sequence in OEIS; this is known as number of "binary Lyndon words of length $n$" or "$n$-bead necklaces with beads of 2 colors". Such sequence can easily be generalised to other bases than 2. After naming $\lambda_a(n)$ the number of $n$-bead necklaces with beads of $a$ colors with $a \ge 2$, I found that
$$ a^n = \sum_{d|n}  d \lambda_a(d) $$
For example,
$$ 2^6 = 1\lambda_2(1) + 2\lambda_2(2) + 3\lambda_2(3) + 6\lambda_2(6) = 2 + 2 + 6 + 54 = 64 $$
This is NOT an original result since you can find this relationship on the afore-mentioned OEIS page, at least.
QUESTION 1: Can someone provides references for a proof of this equation (papers, books, ...)?
Now, after defining
$$ \sigma_a(n) \triangleq \sum_{\substack{ d|n \\ 1<d<n}} d \lambda_a(d) $$
the previous equation can be rewritten
$$ a^n = a + n\lambda_a(n) + \sigma_a(n) $$
Then, using modular arithmetic, we obtain a generalisation of Fermat's little theorem:
$$ a^n \equiv a + \sigma_a(n) \pmod {n} $$
Note that this is indeed a generalisation since it applies on any natural $n$ and it boils down to
$$ a^p \equiv a \pmod {p} $$
for any prime $p$, that is the Fermat's little theorem.
This relationship looks appealing to me, at least for studying Fermat pseudoprimes: these are the composites $n$ having the "rare" property that $\sigma_a(n) \equiv 0 \pmod {n}$.
QUESTION 2: Is this generalisation of Fermat's little theorem a known result? If yes, could you please provide references?
Thanks,
PS: Please, be indulgent: this is my very first post on MO!

A: Here's a massive generalization, with references.
Consider a sequence $\{a_n \}_{n\ge 1}$ of integers. We'll say it satisfies the necklace congruences if $a_{n} \equiv a_{n/p} \mod n$ whenever $p \mid n$ ($p$ prime).
Here are some equivalent formulations:

*

*$a_{p^{k+1} m} \equiv a_{p^k m} \mod {p^{k+1}}$ for all $p,m,k$

*$\sum_{d \mid n} a_d \mu(n/d) \equiv 0 \mod n$ for all $n$

*The Mobius function can be replaced by any arithmetic function $f$ satisfying $\sum_{d \mid n} f(d) =0 \mod n, f(1) = \pm 1$.

So any such sequence gives rise to an integer sequence $\lambda_{\tilde{a}}(n) := \frac{1}{n}\sum_{d \mid n} a_d \mu(n/d)$ which satisfies $a_n = \sum_{d \mid n} d \lambda_{\tilde{a}}(n)$ by Mobius inversion. One can then define $\sigma_{\tilde{a}}(n):=\sum_{d \mid n, 1<d<n} d\lambda_{\tilde{a}}(d)$ and obtain the following generalization of Fermat's little theorem:
$a_n \equiv a_1 + \sigma_{\tilde{a}}(n) \mod n$
Now, let's go back to necklace congruences. A less obvious equivalence is the following:
Theorem: $\{a_n\}_{n \ge 1}$ satisfies the necklace congruences iff $\zeta_{a}(x):=\exp(\sum_{n\ge1} \frac{a_n}{n}x^n)$ has integer coefficients.
Proof: Write, $\zeta_a$ formally as $\prod_{n\ge 1} (1-x^n)^{-\frac{b_n}{n}}$. The $b_n$'s are uniquely determined, and in fact (by taking logarithmic derivative) it can be seen that they are $b_n = \sum_{d \mid n} a_d \mu(n/d)$. Now one direction is immediate and the other requires an inductive argument. $\blacksquare$
(Reference: Exercise 5.2 (and its solution) in Richard Stanley's book "Enumerative Combinatorics, vol. 2")
As Sergei remarked, for any integer square matrix $A$, the sequence $a_n := \text{Tr}(A^n)$ satisfies the necklace congruences. This is immediate from the last theorem, as the corresponding "zeta" function $\zeta_a$ is just:
$\exp( \sum_{n \ge 1} \frac{\text{Tr}((Ax)^n)}{n}) = \exp (\text{Tr} (- \ln (I -Ax)))=\det(I-Ax)^{-1} \in \mathbb{Z}[x]$
In particular, by taking a 1 on 1 matrix, we recover your observation.
Another generalization is $a_n = [x^n]f^n(x)$, where $f \in \mathbb{Z}[[x]]$. By taking the linear polynomial $f(x)=1+ax$ we recover your example, by taking $f(x)=(1+x)^m$ we get $a_n = \binom{nm}{n}$.
The really interesting feature is that this notion has a local version. Specifically, theorems of Dieudonne-Dwork and Hazewinkel give the following result:
Theorem: Given $\{ a_n \}_{n\ge 1} \subseteq \mathbb{Q}_{p}$ ($p$-adic numbers), the following are equivalent:

*

*$\zeta_{a}(x) := \exp(\sum_{n\ge 1} \frac{a_n }{n}x^n)\in\mathbb{Z}_{p}[x]$

*$\exp( \sum_{n \ge 1} p \frac{a_n - a_{n/p}}{n} x^n) \in 1+px\mathbb{Z}_{p}[x]$ (I defnite $a_{n/p}=0$ if $p\nmid n$)

*$\sum_{n \ge 1}  \frac{a_n - a_{n/p}}{n} x^n) \in \mathbb{Z}_{p}[x]$

*$p \mid n \implies a_n \equiv a_{n/p} \mod {n\mathbb{Z}_{p}}$

Applying this simultaneously for all $p$, we recover the previous theorem.
A reference for this theorem is "A Course in p-adic Analysis" by Alain M. Robert (the theorems are stated there in a much more general context).

A: In this paper (in Russian) : http://www.mathnet.ru/php/archive.phtml?wshow=paper&jrnid=mp&paperid=238&option_lang=eng
there are discussion of this result, including theorem of Gauss, generalization to matrices by V.I.Arnold and so on.


text:
Q: Howto check for LsaLogonUser session, and or create one under wine I'm using visual C++ 2009 under wine.
I have all paths set correctly for command line operation (cl.exe, link.exe, etc.) and can compile normal programs just fine.  However, when I supply the -Zi or -ZI flags to include debugging information, the program exits with an error:
: fatal error C1902: Program database manager mismatch; please check your installation
I have all the strictly necessary dll's and exe's in the path:
mspdb80.dll, mspdbcore.dll, mspdbsrv.exe
And I even made sure to try the program with the native window dll's rather than just wine's build in version, eg: msvcr90.dll and msobj90.dll and msvcp90.dll  but it makes no difference.
But: oddly enough -- I can successfully start the server manually without the error:
C:mspdbsrv.exe -start -spawn -shutdowntime -1
So ... it's not the server program itself which has a mismatch, but some kind of error when cl.exe tries to communicate with the server ; eg: because running cl.exe has exactly the same failure even when mspdbsrv.exe is already running.  (Mixed versions are ruled out, anyhow -- this is a clean install).
The only possible cause I have located so far on the web for this error is this one: quoted

It tries to impersonate, but it looks to me as if it does not make the necessary
  call to LsaLogonUser. As a result, the wrong SID is in the token as the primary
  user. According to filemon, the debug server calls into secur32, which suggests
  that it is doing interpretive access control. It finds the service's SID
  instead of the users SID in some slot in the token that it gets via RPC, and
  then everything goes downhill from there.
Why VS feels the need to put the PDB access in a separate process under
  separate access rights is very puzzling, but there it is.
  ...

So -- I think what I am probably looking for are some command line tools / source code to answer the following questions -- but I have no idea where to get them.
1) How can I check what kind of authentication/logon session the server is running, and what cl.exe actaully needs. I have processexplorer, and it says that mspdbsrv.exe when running manually has the following security -- but I don't know if this is enough information (I'm new to windows security.)
User: darkstar\andrew3
SID:S-1-5-21-0-0-0-1000
Session:0
Logon Session: 0

     ...Group...                  ...Flags...
BUILTIN\Administrators              Owner
BUILTIN\Users                       Mandatory
Everyone                            Mandatory
LOCAL                               Mandatory
Logon SID (S-1-5-5-0-1)             Mandatory
NT AUTHORITY\Authenticated Users    Mandatory
NT AUTHORITY\INTERACTIVE            Mandatory

Group SID is: S-1-5-4
     ....privelege....         ...flags....
SeChangeNotifyPrivilege     Default Enabled
SeSecurityPrivilege         Disabled
SeBackupPrivilege           Disabled
SeRestorePrivilege          Disabled
SeSystemtimePrivilege       Disabled
SeShutdownPrivilege         Disabled
SeRemoteShutdownPrivilege   Disabled
SeTakeOwnershipPrivilege    Disabled
SeDebugPrivilege            Disabled
SeSystemEnvironmentPrivilege Disabled
SeSystemProfilePrivilege    Disabled
SeProfileSingleProcessPrivilege Disabled
SeIncreaseBasePriorityPrivilege Disabled
SeLoadDriverPrivilege       Default Enabled
SeCreatePagefilePrivilege   Disabled
SeIncreaseQuotaPrivilege    Disabled
SeUndockPrivilege           Disabled
SeManageVolumePrivilege     Disabled
SeImpersonatePrivilege      Default Enabled
SeCreateGlobalPrivilege     Default Enabled

But I have no idea which permissions are important to tell if server is logged in, or merely in some kind of impersonation mode.  Which values are important?
2) How can I change/set the present logon type ?  ( I found, for example this: lsalogon example , but it doesn't compile because of missing header, includes, etc... not to mention, I'm not sure what login name/password to use.  Is the login darkstar\andrew3 fine, or do I need to create some special admin account?
3) Does anyone know of a very simple program (source code) that I can compile from mingw to be able to access microsoft's pdb server?  For if I have a program that I can compile with mingw / gcc / g++ -- I can use GDB to figure out exactly what is triggering the error message... but I can't debug cl.exe worth a darn using gdb; I really do need something with source code...
Any help, greatly appreciated.

A: The misleading error message can be caused by mspdbsrv.exe's RPC/login not being handled correctly by wine; eg: if an additional package, winbind, is not installed -- because login based security/RPC appears to be partially handled by samba.
So, when the mspdbrv.exe starts correctly from the command prompt using -start -spawn, but cl.exe reports a wrong version; the likely solution is just to install SAMBA binaries for your system (I used a Linux slackware package and didn't even bother configuring samba, or starting it...) Once the winbindd binary is installed, wine does the rest correctly and cl.exe produces pdb files exactly as expected.


text:
Q: ASP.NET MVC C# - Using array values to loop through model fields e.g. model.[Array Value] I am trying to use array to loop through model fields
@Html.DisplayNameFor(model => model.[fld]) where fld is in an array
flds see code below. Please let me know how to do this.
@model IEnumerable<SchoolAutomationSite.Models.tblClass>

    @{
        ViewBag.Title = "List Of Classes";
    }

@ViewBag.Title

        @Html.ActionLink("Create New Class", "Create")

This is the Array

    @{
        string[] DisplayName = { "name", "description", "createdAt", "updatedAt" };
    }

    @foreach (var fld in flds)
    {

                @Html.DisplayNameFor(model => model.[fld])

How to do the above line?

    }

    @foreach (var item in Model) {

            @foreach (var fld in flds)
            {

                    @Html.DisplayFor(modelItem => item.[flds])

            }

            use the above instead off
            ----------

                @Html.DisplayFor(modelItem => item.name)

                @Html.DisplayFor(modelItem => item.description)

                @Html.DisplayFor(modelItem => item.createdAt)

                @Html.DisplayFor(modelItem => item.updatedAt)

            ----------

    }

A: You can convert a dotNet object to a dictionary and then iterate through the keys collection.  Here's an extension method I've used in the past:
    public static class ObjectExtensions
{
    ///
    /// Turns object into dictionary
    ///
    /// <param name="o"></param>
    /// <returns></returns>
    public static IDictionary<string, TVal> ToDictionary<TVal>(this object o)
    {
        if (o != null)
        {
            var props = TypeDescriptor.GetProperties(o);
            var d = new Dictionary<string, TVal>();
            foreach (var prop in props.Cast<PropertyDescriptor>())
            {
                var val = prop.GetValue(o);
                if (val != null)
                {
                    d.Add(prop.Name, (TVal)val);
                }
            }
            return d;
        }
        return new Dictionary<string, TVal>();
    }

}

And then call it like this:
var fields = Model.ToDictionary();
foreach (var key in fields.Keys) {

        @fields[key]

}

or, using your flds array:
var fields = Model.ToDictionary();
foreach (var fld in flds) {

        @fields[fld]

}


text:
Q: Embed swf with jquery fallback I am not very clued up about HTML5 or Jquery, and therefore I need help with the following:
I want to embed a swf in my html, but if users view the site on iOS, I need it to fallback to Jquery. I can't seem to find anything online, as most of people only explain how to do this with videos. I need a fallback to a full Jquery gallery, not just a video. Any suggestions on how this can be done?

A: Detect iphone or ipad device with the help of navigator.userAgent or navigator.platform then embed flash if not iphone/ipad else embed your gallery.
var iOS = ( navigator.userAgent.match(/(iPad|iPhone|iPod)/i) ? true : false );

if(!iOS){
     //render the flash
}
else {
     //render the gallery.
}


text:
Q: OData new entity but partial payload I'm trying to access OData from C# using this VS extension this VS extension (which seems to be the recommended way). It generates a Connected service inside the project, to access (in my case) a Business Central API.
When I create an object (here a vendor), through this kind of code,
var context = new BCNS.NAV(new Uri(_serviceRoot));
var vendor = Vendor.CreateVendor(Guid.NewGuid());
context.AddToVendors(vendor);
context.SaveChanges();

it fails because 2 of the properties of vendore are read-only; the context sends every property in the serialized json and it fails. (if I remove them by hand it succeeds)
These 2 properties don't look different in the $metadata:
<Property Name="balance" Type="Edm.Decimal" Scale="Variable" />
<Property Name="lastModifiedDateTime" Type="Edm.DateTimeOffset" />

Don't jnow how it could guess they are readonly.
I've seen here how to send a partial payload during an update request, and I am desperately trying to make similar thing for a creation.
I saw there is a possible parameter "PostOnlySetProperties" for context.SaveChanges that "can only be used when using DataServiceCollection", but I fail trying to add an object through it. It seems to handle only objects it's tracking, not new ones.
Would someone know how to send a partial payload when creating a new item ?
Thanks in advance.

A: Ok, found it.
I let this answer here, cause it was so difficult to find that maybe some day it can help.
I had to use the DataServiceCollection, which, correctly initialized, works also for new elements. New elements seem to have to be initialized after (for obvious tracking reasons I guess).
The following code worked.
var context = CreateContext("vendors");

DataServiceCollection<Vendor> vendors = new DataServiceCollection<Vendor>(context, "Vendor", null, null);

var vendor = new Vendor();
vendors.Add(vendor);
vendor.Id = Guid.NewGuid();
vendor.DisplayName = "Attempt to create vendor 03";

context.SaveChanges(SaveChangesOptions.PostOnlySetProperties);`

A partial payload is then sent.