Q: How to compare two sentences by considering the space only in dynamic portion? I need to compare two sentences. First one is defined in a database like below.
var text1 = "Dear {#dynamic#} {#dynamic#} Welcome to MAX private ltd"

Then the text which comes from customer is given below.
"var text2 = "Dear joe harry Welcome to MAX private ltd"

Here in place of dynamic there could be any value that customer can substitute and send as an input ( 0- 10) is the character limit for dynamic content.
I need to compare both the sentences and return the response. Problem here is, we should not consider spaces in the other portion of the sentence except for dynamic part. For example,
   "var text3 = "Dear joe harry Welcome to MA Xprivatel td"

While comparing text1 with text3 , it should be valid even though we have spaces near the MA Xprivatel td". But for dynamic portion , if {#dynamic#}{#dynamic#} comes continuously, it can be 20 characters max including spaces. If two
{#dynamic#} {#dynamic#} with spaces, max character limit can be 21 including spaces.
My current code is below,
   text1 = text1.replace(/(^|.)\s($|.)/g, (x, g1, g2) => (x == "} {" ? "}\\s+{" : g1 + "\\s\*" + g2));
   var separators_regex = /{#dynamic#}|((\s\*))/gi;
   text1= text1.replace(separators_regex, (x, y) => y ? y : ".{0,10}");
   let regex1 = RegExp("^" + text1+ "$", "i");
   if (!regex1.test(text2)) {  // or regex1.test(text3)
        Status = "Fail"
    }

Whatever I try, at some scenario it is failing. The above code is failing for text3.
Im stuck with these for too long. Can anybody please help me with this?

A: You can use

var text2 = "Dear 1234567890 12345678901 Welcome to MAX private ltd"
var text1s = ["Dear {#dynamic#} {#dynamic#} Welcome to MAX private ltd {#dynamic#}"];
var text2 = "Dear joe harry Welcome to MAX private ltd";
for (var text1 of text1s) {
  var rx = new RegExp(text1.replace(/\s*(\{#dynamic#}(?:\s*\{#dynamic#})*)/g, (x, y) =>
    '\\s*.{0,' + ((y.match(/\{#dynamic#}/g) || ['']).length * 10 + (y.match(/\s/g) || '').length) + '}'))
  console.log(rx)
  console.log(rx.test(text2))
}

This means:

*

*Sequences of possibly whitespace-separated {#dynamic#} chunks are replaced with the necessary .{0,x} patterns

*If there are spaces in between, these are added up to x

*If there are leading whitesapces, they will be made optional, \s* will replace any amount of whitespaces.


Q: Conjectures in Grothendieck's "Pursuing stacks" I read on the nLab that in "Pursuing stacks" Grothendieck made several interesting conjectures, some of which have been proved since then.  For example, as David Roberts wrote in answer to this question,

Grothendieck conjectured, and Cisinski proved, that the class of weak equivalences in the Thomason model structure was the smallest basic localizer.

I am interesting in knowing what other conjectures made in PS have turned out to be true, or  other "ideas" that have been successfully realized/formalized.  Ideally it would be nice to include references to the relevant papers.

A: To dash off a quick answer, Pursuing Stacks is composed of (if memory serves correctly) three themes. The first was homotopy types as higher (non-strict) groupoids. This part was first considered in Grothendieck's letters to Larry Breen from 1975, and is mostly contained in the letter to Quillen which makes up the first part of PS (about 12 pages or so). Maltsiniotis has extracted Grothendieck's proposed definition for a weak $\infty$-groupoid, and there is work by Ara towards showing that this definition satisfies the homotopy hypothesis.
The other parts (not entirely inseparable) are the first thoughts on derivators, which were later taken up in great detail in Grothendieck's 1990-91 notes (see there for extensive literature relating to derivators, the first 15 of 19 chapters of Les Dérivateurs are themselves available), and the 'schematisation of homotopy types', which is covered by work of Toën, Vezzosi and others on homotopical algebraic geometry (e.g. HAG I, HAG II) using simplicial sheaves on schemes. This has taken off with work of Lurie, Rezk and others dealing with derived algebraic geometry, which is going far ahead of what I believe Grothendieck envisaged.
During correspondence with Grothendieck in the 80s, Joyal constructed what we now call the Joyal model structure on the category of simplicial sets simplicial sheaves to give a basis to some of the ideas being tossed around at the time. (Edited 2022)

Edit: I forgot something that is in PS, and that is the theory of localisers and modelisers, Grothendieck's conception of homotopy theory which you mention, which is covered in the work of Cisinski.

Edit 2019: Toën has a new preprint out

Bertrand Toën, Le problème de la schématisation de Grothendieck revisité, arXiv:1911.05509

with abstract starting

"The objective of this work is to reconsider the schematization problem of [Pursuing Stacks], with a particular focus on the global case over Z. For this, we prove the conjecture [Conj. 2.3.6 of Toën's Champs affines]..."

A: I agree with Tim that calling Pursuing Stacks  a "letter to Quillen" is erroneous, especially as Quillen never replied.
Grothendieck also wrote: "This is written in English in response to a correspondence in English." At one stage he planned more volumes in French but it seems got diverted from this. I hope the following will be of help,  in addition to David Robert's answer, to put the situation with regard to models for homotopy theory in context.
In a letter dated 02/05/1983 Alexander Grothendieck
wrote to me: "Don't be surprised by my supposed efficiency in
digging out the right kind of notions--I have just been following,
rather let myself be pulled ahead, by that very strong thread
(roughly: understand non commutative cohomology of topoi!) which I
kept trying to sell for about ten or twenty years now, without
anyone ready to ``buy'' it, namely to do the work. So finally I got
mad and decided to work out at least an outline by myself."
But this question is about the homotopy theory of categories and the related question of "Why simplicial sets?", for which see also the good answers in March 2011 to Is there a high-concept explanation for why "simplicial" leads to "homotopy-theoretic"?.
Dan Kan's first contribution to combinatorial homotopy was in terms of cubical sets. When he went to Princeton the disadvantages of cubical sets were found: cubical groups did not satisfy the extension property, and the geometric realisation of the cartesian product of cubical sets had the wrong homotopy type, while as shown by Moore and Milnor respectively, the situation was fine for simplicial sets. So they did not attempt to refine the cubical theory. In my doctoral studies at Oxford, 1956-59, the exposition was all simplicial, especially when Michael Barratt came back from Princeton in 1957.
However the 1960 book by Hilton and Wylie on algebraic topology was cubical, as were some 1962 notes of Federer from Brown University, a later book by Massey, and cubical sets continued to be found useful in various places. Our 2011 book on "Nonabelian algebraic topology" is almost entirely cubical, because of its emphasis on the use of higher homotopy Seifert-van Kampen theorems.

My 1965 intuition for using cubical sets was based on generalising the van Kampen theorem to higher dimensions. It seemed entirely reasonable that the above diagram could be expressed as: the big square is the composition of the little squares. C. Ehresmann's 1965 book on "Categories structuree"  gave a definition of double categories which expressed this nicely. Indeed, I have answered this on mathoverflow as using matrix notation where $(a_{ij})$ denotes a composable array and $[a_{ij}]$ denotes the composite. So one has an easy definition of the $n$-fold cubes of the nerve of an $n$-fold category, except that there seems currently no name for the cubical type geometry underlying an $n$-fold category.   Note that composable sequences of morphisms in a category are used in describing the nerve of a category, but it seems more difficult, at least for me,  to define multiple compositions in simplicial or globular terms, although the simplicial nerve of an $n$-fold category is easily defined as an $n$-fold simplicial set.
By contrast, the singular cubical complex of a space, or filtered space, is ideally suited for the description of multiple compositions, using an array notation. I have already explained this in answer to this mathoverflow question.
So in considering what category in which to work the question of "what should be adequacy and convenience?" is crucial. It is as reasonable to ask this for combinatorial models of homotopy theory as it was in 1963 to ask it for categories for topology in  my paper Ten topologies.
A property that  was also required for the conjectured proof of a putative higher van Kampen theorem using homotopy classes of maps  was the notion of "commuting cube", and that "any composition of commuting cubes is commutative". Chris Spencer and I found that the notion of "connection" for a double groupoid was good for this, and that it allowed  an equivalence between crossed modules and single pointed edge symmetric  double groupoids with connections. Then Philip Higgins and I found in 1974 the construction of the homotopy double groupoid of a pair $(X,A,x)$ of pointed spaces using homotopy classes of maps $I^2 \to X$ which take the edges to $A$ and the vertices to $x$. This gave the first homotopy fundamental double groupoid, which enabled the proof of a 2-dimensional van Kampen theorem, including the usual theorem for the fundamental group as a special case, not just an implication.
There are grounds for suggesting that simplicial sets are convenient,  but are not entirely adequate, since they cannot  easily express multiple compositions. On the other hand, cubical sets with connections are adequate for this test, but not entirely convenient! Andy Tonks proved that cubical groups with connection are Kan complexes. One reason for inconvenience    is that although they have been shown to form a strict test category in the sense of Grothendieck, in the paper given here,  the geometric realisation of the categorical  product is only of the homotopy type of the product of the realisations, not   actually homeomorphic to the product as in the case of simplicial sets. The latter homeomorphism property implies that in the right convenient category, the geometric realisation of a simplicial group is a topological group.
The cubical setup is also not sufficient to describe the geometry underlying $n$-fold categories, and indeed there seems currently no name for such a structure in which cubes have different types of faces in different directions. Yet Grothendieck remarked to me on my affirming Loday's theorem, that (strict) $n$-fold groupoids model weak homotopy $n$-types: "That is absolutely beautiful!"
So it as well not to assume we have the final story, and to investigate options!
January, 2015: This answer is related to my answer to
https://math.stackexchange.com/questions/1112107/why-does-seifert-van-kampen-not-hold-with-n-th-homotopy-groups/
November, 2016 There is more discussion in this preprint Modelling and Computing Homotopy Types: I.

A: This is more a comment than an answer, but its length makes me post it as an answer. I want to react to what I have just read, for the first time, about "Pursuing Stacks" at the nLab, and the words used there as well as in your question. I find it extremely irritating when people only use words such as "ideas" and "conjectures" to describe the content of "Pursuing Stacks". It makes me wonder whether they have read it or not. The words "rigorous", "results" or "theorems" are not used unless they describe other people's work. This is perfectly true that you would find ideas and conjectures in "Pursuing Stacks", but it does not prevent many notions and results regarding them to be "rigorously worked". It absolutely blows my mind that, nearly thirty years after the writing of this text, people still talk about it in that disrespectful way. (Those who do not think this is disrespectful to credit Grothendieck with "ideas" and "conjectures", no matter how "deep" or "beautiful", while others get the credit for the rigorous results, can read "Récoltes et semailles", where this question is precisely addressed at length.)
This is nevertheless true that "Pursuing Stacks" contain many ideas and conjectures, and David Roberts's answer gives, to my very partial knowledge, an accurate rough overview of what has been developed since then. I would just mention the fact that Grothendieck did not view simplicial sets as more homotopically relevant than other test categories. As regards $\infty$-groupoids, his approach is purely algebraic. Therefore, while I certainly do not claim that one of the approaches is better than the others, the prevalent simplicial approaches do not seem to me to be the one advocated by Grothendieck.
EDIT 1 (10 December 2012): This "answer" has got one downvote and someone has canceled their upvote. Perhaps I should have explained more. I find the question and the answers given so far quite sad because they all point out the fact that almost nobody has read "Pursuing Stacks", and people mostly talk about it by word of mouth. If some people had read it carefully, then sure enough they would have cited accurately some of Grothendieck's results. What are these precises references in the literature? I only know that there was a working group organized by Bénabou in the eighties, devoted to Pursuing Stacks, soon after its sending, but it quickly came to an end, and that someone in the Netherlands asked a student, whose name nobody seems to recall, to work on test categories, which he did not pursue very far. There certainly has been a lot of work in "categorical homotopy theory" since the writing of "Pursuing Stacks", but have Lurie, Rezk, Toën, Vezzosi (all cited by David Roberts) read "Pursuing Stacks" (I certainly do not claim they should have)? I think one should be very careful before claiming that one's own work or other people's work is indeed related to the content of "Pursuing Stacks" and even more before stating that it "realize" (?) or "formalize" some "ideas" of "Pursuing Stacks". To some extent, this text is like the Bible: everybody talks about it but almost nobody knows what is written there.


Q: Function decide where to store the pallets I would like to store the pallets into pallet rack "PRD6" if my typeID = 1, else I would like to store them into pallet rack "PRD7". My agent type is Pallet. I don't know how to build up the function. I'm currently learning java basics but I don't know either how to declare the variables. I read it in the help document but it doesn't help. Thank you for helping.

A: the correct syntax is the following:
agent.typeID==1 ? PRD6 : PRD7

but if you have lots of options, you should call a function here that returns a PalletRack and generate the if/else statement in that function


Q: Integral of a product of five Bessel functions of order $0$ Does the following integral have a closed form?
$$ \mathcal{J}(2,3,5,7,11) = \int_0^\infty x J_0(x\sqrt{2})J_0(x\sqrt{3})J_0(x\sqrt{5})J_0(x\sqrt{7})J_0(x\sqrt{11})\,dx. $$
I know that some similar integrals do have a closed form
$$ \mathcal{J}(2,3,5) = \frac{1}{\pi \sqrt{6}} \approx 0.12995. $$
$$ \mathcal{J}(2,3,5,7) = \frac{1}{\pi^2 210^{1/4}}K(\tfrac14\sqrt\alpha) \approx 0.110411, \qquad 43-672\alpha+42\alpha^2 = 0, \qquad \alpha\approx 15.9358. $$
(Here $K(k)$ is the complete elliptic integral of the first kind with modulus $k$.)
Numerically, the integral is approximately
$$ 0.061064349908721692\ldots, $$
but I could not find a symbolic value for this constant.


Q: Opened mat-menu items should be close after other mat-menu items clicked (i.e should be act as an mat-tab) Opened mat-menu items should be closed when other mat-menu items clicked ...
And i tried Mat-trigger methods but no use in that
Here is the code
In that I used an reusable component to trigger data of mat-menu items through @Input and I need an functionality like as mat-tab methods for these code .
When I use trigger method trigger.toArray().forEach its not looped to another items its looped for once only,So I cant set that correctly
<ng-container *ngIf="!child">
    <div
        class="sample"
        [matMenuTriggerFor]="matMenu"
        [matMenuTriggerData]="item"
        #trigger="matMenuTrigger" >
        <ng-container *ngTemplateOutlet="itemTemplate; context: {$implicit: item}"></ng-container>
    </div>
</ng-container>

<mat-menu  backdropClass="custom__menu"
    [overlapTrigger]="false"
    #matMenu="matMenu" xPosition="before" >

    <ng-container *ngFor="let item of item.children;">

        <ng-container *ngIf="(item.hidden && !item.hidden(item)) || !item.hidden">

            <!-- Basic -->
            <ng-container *ngIf="item.type === 'basic'" >
                <div

                    [disabled]="item.disabled"
                    mat-menu-item>
                    <horizontal-navigation-basic-item
                        [item]="item"
                        [name]="name"></horizontal-navigation-basic-item>
                </div>
            </ng-container>

        </ng-container>

    </ng-container>

</mat-menu>

<ng-template
    let-item
    #itemTemplate>

    <div
       (click)="triggerChangeDetection(item)"

     </div>

 </ng-template>


Q: Label position and size i have a network of labeled nodes based on sizes. But I can't get the labels to be smaller and off the node and not overlapping.
import networkx as nx
import matplotlib.pyplot as plt

"Create a Blank Graph Page"
G = nx.Graph()

"Single Node"
#G.add_node(1)
#G.add_node(2)

"Single Edge"
#G.add_edge(1,2)

"Many Nodes"
NxNodeList = ["fish","water","and","in","plant","of","to","aquarium","rock","blue","relationship","tank","are","is","swimming","color","for","yellow","coral","with","good","other","ecosystem","different","environment","fishtank","that","between","green","need","be","filter","goldfish","on","each","orange","living","can","oxygen","school","small","there","it","life","live","red","rule","see","together","dependent","many","species","they","family","gravel","have","pebbles","same","algae","all","around","community","don't","provides","underwater","decorations","eats","feed","food","must","none","some","survive","animals","big","cleans","grass","habitat","hide","home","keeps","know","large","like","mates","reaction","reef","saltwater","sand","so","stone","system","this","types","white","alive","aquatic","filled","from","glass","group","has","humans","nature","or","seaweed","their","them","tree","air","allows","along","beautiful","bottom","breathe","by","cannot","circulating","cooperating","direction","exist","friendly","give","grey","harmony","into","items","light","love","made","makes","mom","ocean","owner","person","place","places","plastic","produce","sea","structure","sure","symbiosis","things","through","up","variety","1","2","3","act","action","applies","as","away","because","broke","bunch","caretakers","clear","coexisting","creatures","dad","decoration","do","either","excellent","flower","form","full","getting","great","greenery","grouper","grow","healthy","helping","homes","how","inside","interact","just","lets","lighting","lights","little","marriage","me","merge","more","multiple","near","not","part","pet","picture","pipe","plankton","plants","pretty","pump","react","rely","schools","sealife","seaweeds","seem","seen","shelter","similar","smaller","space","still","supply","survival","swim","symbiotic","then","therefore","unity","varying","vase","very","waste","well","without","yet","6","able","adapt","adds","aerator","alabaster","alone","also","any","apart","apparently","appear","appears","applicable","archive","arrived","at","attention","awesome","baby","back","based","being","belong","best","biology","bit","blend","boring","bright","bubbles","builded","bushes","called","captivity","carnivorous","cave","chain","change","cleaning","coexistence","cohabiting","collar","comfortable","compatible","complex","conditions","confused","connected","contrast","cool","create","decor","designs","dippy","direct","dishes","distance","distract","docile","dropped","ecological","enjoy","enjoyment","entertain","essential","etc","evenly","everything","exhale","fake","falls","farmer","fauna","feel","female","few","find","fishbowl","fishing","floor","flowing","flows","freely","fresh","freshwater","functioning","gang","gather","get","gills","go","golden","grew","groovy","groups","growing","hand","happy","he","help","helps","here","hides","hiding","hippy","hold","holding","holds","holes","homeowners","household","idea","imprison","improve","including","incredibly","inductive","interested","interesting","job","join","jug","kinds","larger","leaves","lit","lonely","lots","loving","lucky","maintain","male","marine","matter","may","maybe","medium","most","motion","multicolored","needed","no","nome","nothing","office","offspring","ok","one","ones","organisms","ornamental","ornaments","others","outside","parent","partners","parts","peacefully","peer","perspective","pink","pitcher","plantlife","play","pot","pots","predators","principle","prisoners","pvc","real","really","reed","relies","rest","right","salinity","salt","science","screensaver","seabed","seagrass","seeing","settled","several","share","shark","shine","sibling","side","single","size","smooth","someone","spaced","stay","stripe","substrate","supplies","supplying","supports","sweet","take","tandem","temperature","than","thermometer","these","think","three","thrive","tolerate","too","top","toward","trees","tubes","under","undersea","understand","unsure","upon","used","uses","usually","various","vegetation","viewed","wallpaper","walls","want","what","which","work","world","you","your"]
G.add_nodes_from(NxNodeList)

node_sizes = [404,154,79,67,62,61,61,56,49,41,41,40,32,30,28,26,24,23,21,20,19,19,17,16,16,16,16,15,15,15,14,14,14,14,13,13,12,11,11,11,11,11,10,10,10,10,10,10,10,9,9,9,9,8,8,8,8,8,7,7,7,7,7,7,7,6,6,6,6,6,6,6,6,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,4,4,4,4,4,4,4,4,4,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]

"Draw and Show Graph"
nx.draw(G,with_labels=True,node_size=node_sizes)
plt.savefig("NetworkGraph_part1.png")

Which creates this mess:
enter image description here

A: You must specify figsize together with dpi to get the plot big enough and has proper resolution. For the text's size, specify smaller font_size. For example, the relevant code is as follows:-
fig, ax = plt.subplots(figsize=(12,9), dpi=360)
nx.draw(G, with_labels=True, node_size=node_sizes, font_size=4)


Q: print all SubClass in a SuperClass and all SuperClass in a SubClass I want in SuperClass print all subClasses and in a subClasses  print all SuperClasses:
class SuperClass():
    def Print(self):
        print('my sub classes are : ')
        #print all childs

class Sub1(SuperClass,...):
    def Print(self):
        print('My parents are :')
        #print all SuperClasses

class Sub2(SuperClass,...):
    def Print(self):
        print('My parents are :')
        #print all SuperClasses

SuperClass has Print that print all classes that inherit from , and Sub  has Print method that print all his SuperClasses . how do that ?

A: Python classes have three attributes that help here:

*

*class.__subclasses__(); a method that returns all subclasses of the class.

*class.__bases__, a tuple of the direct parent classes of the current class.

*class.__mro__, a tuple with all classes in the current class hierarchy. Find the current class object in that tuple and everything following is a parent class, directly or indirectly.
Using these that gives:
class SuperClass(object):
    def print(self):
        print('my sub classes are:', ', '.join([
            cls.__name__ for cls in type(self).__subclasses__()]))

class Sub1(SuperClass):
    def print(self):
        print('My direct parents are:', ', '.join([
            cls.__name__ for cls in type(self).__bases__]))
        all_parents = type(self).__mro__
        all_parents = all_parents[all_parents.index(Sub1) + 1:]
        print('All my parents are:', ', '.join([
            cls.__name__ for cls in all_parents]))

Demo:
>>> SuperClass().print()
my sub classes are: Sub1
>>> Sub1().print()
My direct parents are: SuperClass
All my parents are: SuperClass, object


Q: Reset form to empty values new to redux-form... I was looking at an example from redux-form docs where one can initialize form values from initialValues (forked example here: https://codesandbox.io/s/6v3n9lwnpr).
Is it possible to have functionality where one can use 'Undo Changes' to reset form to InitialValues, but also have another button to reset to empty form?

A: If you go to the redux-form documentation, you will find what you need under the action creator section. With that, let's answer your questions.

one can use 'Undo Changes' to reset form to InitialValues

In its documentation, Redux-Form lists out a couple of actions that you can use. You can either use an action creator or used an action that is already bound to the dispatch. For your requirement, you'll need to use the library's reset function
a) using action creator
import { reset } from 'redux-form';

...// then inside a function you can dispatch the reset action.
resetMyForm() {
 const action = reset('myFormName');
 dispatch(action);
}

b) using an action already bound to the dispatch
I wont type this since there is an example in the library on GitHub here
And as for

button to reset to empty form

similar to the initial answer but you would have to use the clearFields function instead.
Hope this helps.


Q: Issue in starting the nginx web platform open-resty in wsl-ubuntu I'm currently running Ubuntu using wsl-2 in windows and when I tried out an Open Resty tutorial for dynamic redirection, it was running well.
I configured kind cluster and setup nginx ingress to tryout ingress services and it also worked fine. But after this when I tried to start the Open Resty the same way as before, the nginx web platform fails to start.
I also checked using $which openresty and got the output /usr/bin/openresty. So this confirms that it is properly installed as well.
I want to know whether using nginx in both the kind cluster and using Open Resty causes this issue or is there any other reason for this issue?
Command used -  $sudo service openresty start
Output -  * Starting full-fledged web platform nginx                                                        [fail]
Note - Redirection using lua scripts is working but still the openresty service status is  * nginx is not running


Q: Cannot compare http request response using Result I have a class that defines a send function to make an http request that returns a Result type.
Result is a system-defined type basically is a generic enum that contains 2 possible values: .success(...) and .failure(...)
public typealias ResultCallback<Value> = (Result<Value, Error>) -> Void
class NetworkManager: NetworkManagerType{

    func send(_ requestUrl: URL, completion: @escaping
    ResultCallback<(response: HTTPURLResponse, data: Data)>)  // equivalent to (Result<(response: HTTPURLResponse, data: Data), Error>)
 ...
}

In my unit test I would be able to compare expected Result objects with the actual Result returned by the send function.
func testFailureResponse() {
        // PREPARE MOCK DATA
        session.mockHttpResponse = mockFailedHttpResponse
        session.mockData = mockData
        session.mockError = NetworkManagerError.httpRequestFailed(response: mockFailedHttpResponse, data: mockData)

        // MAKE REQUEST
        netManager.send(myTaxyUrl, completion:  {  (result: Result<(response: HTTPURLResponse, data: Data), Error>) -> ()  in
              let expectedResult = Result<(response: HTTPURLResponse, data: Data), Error>.failure(  NetworkManagerError.httpRequestFailed(response: mockFailedHttpResponse, data: mockData))

              XCTAssertTrue( expectedResult == result) // !! Errors here!!
              ...
}

The errors are:

*

*' (Self.Type) -> (Self, Self) -> Bool'
requires that '(response: HTTPURLResponse, data: Data)' conform to
'Equatable'

*Type '(response: HTTPURLResponse, data: Data)' does not conform to
protocol 'Equatable'

It seems that saying the tuple does not conform to protocol Equatable, still it is possible to equate my tuples:
let t1 = (response: mockFailedHttpResponse, data: mockData)
let t2 = (response: mockFailedHttpResponse, data: mockData)
print(t1 == t2) // true

So, given that swift doesn't allow to enforce Equatability on a tuple type ( because a tuple it is not a named type), how can I compare actual and expected results?


Q: Как узнать положения элемента в списке без использования index (Python) s = ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"]
print (s)
s.sort()
print (s)

надо найти положение элемента "Февраль" после сорта БЕЗ ИСПОЛЬЗОВАНИЯ INDEX

A: s = ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"]

s.sort()

months = {
    m: idx for idx, m in enumerate(s, start=1)
}

print(
    months.get('Февраль')
)

Ну или так можно проверить:
s = ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"]

s.sort()

months = {
    m: idx for idx, m in enumerate(s)
}

print(
    s[months.get('Февраль')]
)
# Февраль

A: s = ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"]
for i in range(len(s)):
    if s[i] == "Февраль":
        print(i)
        break

A: print(next(i for i,j in enumerate(s) if j=='Февраль'))


Q: Fultter GridView scrolling I have try to set physics to enable scrolling function, but it will scroll the whole screen.
Only red box available to scroll
How can I set to another Widget is fix position, only enable scrolling in GridView?
Only want to scrollable in GridView, Please refer to the photo, That's is more clearly to understand.
child: Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('Sanfield Mobile App'),
        actions: <Widget>[
            IconButton(
              icon: Icon(
                Icons.exit_to_app,
                color: Colors.white,
              ),
              onPressed: () {
                showConfirmLogoutDialog(context,'Confirm logout','Do you want to logout?');
            },
          )
        ],
      ),
      drawer: CustomDrawer(),
        body:SingleChildScrollView(
            physics: new NeverScrollableScrollPhysics(),
            child:Column(
            children: <Widget>[
            Card(
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  ListTile(
                  leading:
                  image(),
                  title: Text(updateDate),
                  subtitle: Text(weatherDetails),
                ),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  RichText(
                    text: TextSpan(
                      style: new TextStyle(
                      fontSize: 24.0,
                      color: Colors.black,
                    ),
                  children: <TextSpan>[
                    TextSpan(text: mintemp.toString()+' C - ', style: new TextStyle(color: Colors.lightBlue)),
                    TextSpan(text: maxtemp.toString()+' C ', style: new TextStyle(color: Colors.red)),
                    TextSpan(text: '       Update:'+updateTime, style: new TextStyle(color: Colors.black,fontSize: 14)),
                ],
              ),
              ),
              ],
            ),
          ],
        ),
      ),
      Container(
        height: 80,
            child: new ListView.builder(
              itemCount: 6,
              itemBuilder: (context, index){
                return new Card(child: new Container(
                //width: MediaQuery.of(context).size.width,
                 width:320,
                 height: 80,
                 child: new Text('Hello'),alignment: Alignment.center,));
              }, scrollDirection: Axis.horizontal,
            ),
          ),
          Container(
            height: 889,
           child:GridView.count(
                    physics: ScrollPhysics(),
                    primary: false,
                    padding: const EdgeInsets.all(10),
                    crossAxisSpacing: 10,
                    mainAxisSpacing: 10,
                    crossAxisCount: 3,
                    children: <Widget>[
                      Container(
                        padding: const EdgeInsets.all(20),
                        decoration: BoxDecoration(
                          image: DecorationImage(
                            image: AssetImage(
                                'images/hkphoto.jpg'),
                            fit: BoxFit.fill,
                          ),
                          shape: BoxShape.circle,
                        ),
                        child: InkWell(
                          /*onTap: () => Navigator.push(
                              context, MaterialPageRoute(builder: (context) =>)
                            ),*/ // handle your onTap here
                        ),
                      ),
                      InkWell(
                          child:Container(
                                    padding: const EdgeInsets.all(8),
                                    child: const Text('phs'),
                                    color: Colors.teal[200],
                          ),
                          /*onTap: () => Navigator.push(
                              context, MaterialPageRoute(builder: (context) =>
                            )
                          ),*/
                      ),
                      InkWell(
                        child:Container(
                          padding: const EdgeInsets.all(8),
                          child: const Text('whs'),
                          color: Colors.teal[200],
                        ),
                        /*onTap: () => Navigator.push(
                            context, MaterialPageRoute(builder: (context) =>
                          ),
                        ),*/
                      ),
                      InkWell(
                        child:Container(
                          padding: const EdgeInsets.all(8),
                          child: const Text('whs'),
                          color: Colors.teal[200],
                        ),
                        /*onTap: () => Navigator.push(
                            context, MaterialPageRoute(builder: (context) =>
                          ),
                        ),*/
                      ),
                      InkWell(
                        child:Container(
                          padding: const EdgeInsets.all(8),
                          child: const Text('whs'),
                          color: Colors.teal[200],
                        ),
                        /*onTap: () => Navigator.push(
                            context, MaterialPageRoute(builder: (context) =>
                          ),
                        ),*/
                      ),
                      InkWell(
                        child:Container(
                          padding: const EdgeInsets.all(8),
                          child: const Text('whs'),
                          color: Colors.teal[200],
                        ),
                        /*onTap: () => Navigator.push(
                            context, MaterialPageRoute(builder: (context) =>
                          ),
                        ),*/
                      ),
                ],
              )
              ),
            ]
          ),
        )
      )

A: Remove the SingleChildScrollView at the top-level of the body and set the scrollPhysics of the GridView to AlwaysScrollableScrollPhysics().

A: Try removing the SingleChildScrollView like this:
Column(
        children: <Widget>[
        Card(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              ListTile(
              leading:
              image(),
              title: Text(updateDate),
              subtitle: Text(weatherDetails),
            ),
          Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: <Widget>[
              RichText(
                text: TextSpan(
                  style: new TextStyle(
                  fontSize: 24.0,
                  color: Colors.black,
                ),
              children: <TextSpan>[
                TextSpan(text: mintemp.toString()+' C - ', style: new TextStyle(color: Colors.lightBlue)),
                TextSpan(text: maxtemp.toString()+' C ', style: new TextStyle(color: Colors.red)),
                TextSpan(text: '       Update:'+updateTime, style: new TextStyle(color: Colors.black,fontSize: 14)),
            ],
          ),
          ),
          ],
        ),
      ],
    ),
  ),
  Container(
    height: 80,
        child: new ListView.builder(
          itemCount: 6,
          itemBuilder: (context, index){
            return new Card(child: new Container(
            //width: MediaQuery.of(context).size.width,
             width:320,
             height: 80,
             child: new Text('Hello'),alignment: Alignment.center,));
          }, scrollDirection: Axis.horizontal,
        ),
      ),
      Container(
        height: 889,
       child:GridView.count(
                physics: ScrollPhysics(),
                primary: false,
                padding: const EdgeInsets.all(10),
                crossAxisSpacing: 10,
                mainAxisSpacing: 10,
                crossAxisCount: 3,
                children: <Widget>[
                  Container(
                    padding: const EdgeInsets.all(20),
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage(
                            'images/hkphoto.jpg'),
                        fit: BoxFit.fill,
                      ),
                      shape: BoxShape.circle,
                    ),
                    child: InkWell(
                      /*onTap: () => Navigator.push(
                          context, MaterialPageRoute(builder: (context) =>)
                        ),*/ // handle your onTap here
                    ),
                  ),
                  InkWell(
                      child:Container(
                                padding: const EdgeInsets.all(8),
                                child: const Text('phs'),
                                color: Colors.teal[200],
                      ),
                      /*onTap: () => Navigator.push(
                          context, MaterialPageRoute(builder: (context) =>
                        )
                      ),*/
                  ),
                  InkWell(
                    child:Container(
                      padding: const EdgeInsets.all(8),
                      child: const Text('whs'),
                      color: Colors.teal[200],
                    ),
                    /*onTap: () => Navigator.push(
                        context, MaterialPageRoute(builder: (context) =>
                      ),
                    ),*/
                  ),
                  InkWell(
                    child:Container(
                      padding: const EdgeInsets.all(8),
                      child: const Text('whs'),
                      color: Colors.teal[200],
                    ),
                    /*onTap: () => Navigator.push(
                        context, MaterialPageRoute(builder: (context) =>
                      ),
                    ),*/
                  ),
                  InkWell(
                    child:Container(
                      padding: const EdgeInsets.all(8),
                      child: const Text('whs'),
                      color: Colors.teal[200],
                    ),
                    /*onTap: () => Navigator.push(
                        context, MaterialPageRoute(builder: (context) =>
                      ),
                    ),*/
                  ),
                  InkWell(
                    child:Container(
                      padding: const EdgeInsets.all(8),
                      child: const Text('whs'),
                      color: Colors.teal[200],
                    ),
                    /*onTap: () => Navigator.push(
                        context, MaterialPageRoute(builder: (context) =>
                      ),
                    ),*/
                  ),
            ],
          )

Let me know if it doesnt work


Q: Handling tap on Pushpin in a fixed Map I have a Map control showing a few Pushpins. I do not want the user to navigate in the map so I disable it. But I do want the user to be able to tap on a Pushpin (and in the event I navigate to a detail page).
However when the Map.IsEnabled is false, the Pushpins don't seem to receive any gestures either. I've also tried using IsHitTestVisible, but with no luck.
Some code showing what I'm trying to do. Does anyone have any ideas?
<maps:Map Name="Map"
          VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
          CopyrightVisibility="Collapsed" LogoVisibility="Collapsed" ScaleVisibility="Collapsed" ZoomBarVisibility="Collapsed"
          IsEnabled="False">
    <maps:MapItemsControl ItemsSource="{Binding TheCollection}">
        <maps:MapItemsControl.ItemTemplate>
            <DataTemplate>
                <maps:Pushpin Name="Pin" Location="{Binding Coordinate}" Content="{Binding Ix}">
                    <maps:Pushpin.Background>
                        <SolidColorBrush Color="{StaticResource PhoneAccentColor}"/>
                    </maps:Pushpin.Background>

                    <toolkit:GestureService.GestureListener>
                        <toolkit:GestureListener Tap="PinTap"  />
                    </toolkit:GestureService.GestureListener>
                </maps:Pushpin>
            </DataTemplate>
        </maps:MapItemsControl.ItemTemplate>
    </maps:MapItemsControl>
</maps:Map>

A: Setting IsEnabled to false prevents the Map control from responding to user input, which affects the child Pushpin as you've seen. If you want the map to be read-only but the Pushpin to respond to gestures then I think you have two options:

*

*Handle all the gesture events on the Map control and set e.Handled to true, which will prevent the Map itself from processing the event, but should leave the PushPin free to handle the tap gesture.

*Create a WriteableBitmap of the Map and show that instead, and then display the Pushpin on top (NOTE: I suspect that the Pushpin control won't work outside of the Map control, so you'd need to create/re-template a control to look like a Pushpin).

UPDATE: The events that you need to handle on the Map to make it appear "read-only" but remain enabled are MapPan and MapZoom.

A: So here's how I solved it after a lot of testing and browsing MSDN. It turns out that things are a bit different in the Map control on Windows Phone (see MSDN). There are new behaviors and events compared to normal Silverlight.
<maps:Map Name="Map"
          VerticalAlignment="Stretch" HorizontalAlignment="Stretch"
          CopyrightVisibility="Collapsed" LogoVisibility="Collapsed" ScaleVisibility="Collapsed" ZoomBarVisibility="Collapsed"
          MapZoom="Map_MapZoom" MapPan="Map_MapPan">
    <maps:MapItemsControl ItemsSource="{Binding TheCollection}">
        <maps:MapItemsControl.ItemTemplate>
            <DataTemplate>
                <maps:Pushpin Name="Pin" Location="{Binding Coordinate}" Content="{Binding Ix}">
                    <maps:Pushpin.Background>
                        <SolidColorBrush Color="{StaticResource PhoneAccentColor}"/>
                    </maps:Pushpin.Background>

                    <toolkit:GestureService.GestureListener>
                        <toolkit:GestureListener Tap="PinTap"  />
                    </toolkit:GestureService.GestureListener>
                </maps:Pushpin>
            </DataTemplate>
        </maps:MapItemsControl.ItemTemplate>
    </maps:MapItemsControl>
</maps:Map>

...

private void Map_MapPan(object sender, MapDragEventArgs e)
{
    e.Handled = true;
}

private void Map_MapZoom(object sender, MapZoomEventArgs e)
{
    e.Handled = true;
}


Q: Google maps android vector rendering : how do they make it that fast? Most of the question is in the title.
If you are on android (I believe its the same on IOS) and use maps you will notice the quality of the maps app and how the vector maps are drawn in a very fluid manner.
From what I understand, they are delivering vector tiles wich are encoded using protocol buffers which is pretty easily achievable on my side.  However I was wondering how they managed to achieve real-time rendering of vector tiles in such a fluid manner.
I am currently using mapsforge to render vector based maps but the rendering times of tiles are pretty far from what I can see in google maps.
Any ideas on how I can approach such awesomness ? What kind of voodoo tricks are they using ?
Thanks for any insight !

A: Google has built their own vector map rendering engine based on OpenGL ES version 2:
https://developers.google.com/maps/documentation/android/start#requiring_opengl_es_version_2
Here's a link about OpenGL ES on Android:
http://developer.android.com/training/graphics/opengl/index.html
OpenGL lets you leverage the underlying power of the GPU and get performance on par with 3D mobile game engines.  Given the complexity of most high-end mobile games these days, rendering out some vector map tiles and 3D buildings seems like it would be on the low end of performance requirements.
This is why the requirement of the Maps API V2 is Android 2.2 and higher, since the OpenGL ES Android libraries also require Android 2.2 and higher.
As far as implementing your own version of this, I'd look into some general 3D rendering examples using OpenGL ES and available libraries for Android.
This SE post has some info:
https://stackoverflow.com/questions/9450308/android-latest-open-source-3d-libraries-for-android
...and this:
http://ntt.cc/2011/05/08/8-open-source-android-game-engines.html
I haven't seen any 3D OpenGL ES engines aimed at map rendering, but they might exist.


Q: How to use table valued parameter with the IN keyword Edit:
I tried to replace:
@LocationIDs NVARCHAR(MAX) = null,

with
@LocationIDs LocationIdArray READONLY,

but now I get an error saying:

Must declare the scalar variable "@LocationIDs".

--END EDIT--
I have this stored procedure that I need to address:
CREATE PROCEDURE [dbo].[spAP_GetTechnician_Door_Unlock]
    @LocationIDs NVARCHAR(MAX) = NULL,
    @AlarmDateFrom DATETIME = NULL,
    @AlarmDateTo DATETIME = NULL,
    @TechnicianID INT = NULL,
    @LocationId INT = NULL
AS
BEGIN
    IF (@LocationIDs = 'x')
    BEGIN
        SELECT @LocationIDs = dbo.fn_GetAll_Location_Id()
    END

    DECLARE @query NVARCHAR(MAX);

    SET @query = 'WITH CTE AS (SELECT ROW_NUMBER() OVER(ORDER BY al.Alarm_Log_ID desc)AS RowNumber,
 isnull(t.Technician_ID,'''')[Technician_ID], (isnull(t.Last_Name,'''') +'' ''+  isnull(t.Name,''''))  TechnicianName,isnull(t.Emailid,'''') as EmailID,isnull(t.phone,'''') as Phone,dbo.fNAP_DateFormat(al.Alarm_date) as Alarm_date,
 Al.Site_ID,s.Name as SiteName,al.point_Address,l.location_Name,l.Location_ID ,shs.StatusData
from z_EntityMast_Alarm_Log al
left join  z_EntityMast_Technician t on al.Technician_ID=t.Technician_id
left join z_EntityMast_Site s on s.Site_ID=al.Site_ID
left join z_EntityMast_Location l on s.Location_ID=l.Location_id
left join z_EntityMast_Site_Hardware_Status shs on s.site_id=shs.siteid
left join z_SysVar_Alarm_Type_00004 at on al.Alarm_Type=at.ID
where at.Is_Linkable=1 and al.Alarm_Type !=70'
if(isnull(@LocationId,0)!=0)
set @query=@query+' and s.Location_ID ='+convert(varchar(12),@LocationId);
else
set @query=@query+' and s.Location_ID in ('+@LocationIDs+')';
if(isnull(@AlarmDateFrom,0)!=0 and @AlarmDateFrom !='')
set @query=@query+'and (DATEDIFF(DAY,'''+convert(varchar(30),@AlarmDateFrom)+''', al.Alarm_Date)>=0 and  DATEDIFF(DAY,'''+convert(varchar(30),@AlarmDateTo)+''',al.Alarm_Date)<=0)';
if(isnull(@TechnicianID,0)!=0)
set @query=@query+'and t.Technician_ID ='+ convert(varchar(10),@TechnicianID);
set @query=@query + ')';
set @query=@query +'select * from CTE ';

    -- PRINT @query
    EXEC (@query)
END

I need to optimize it and I have to use table valued parameters for the LocationIds parameter, instead of it using NVARCHAR(MAX).
The problem is in this line of code:
SET @query  = @query + ' and s.Location_ID in ('+@LocationIDs+')';

My question is: how does one replace that line of code and replace it with a table valued parameter in such a way that the concatenation would still work?
Thanks!

A:
SET @query  = @query + ' and s.Location_ID in ('+@LocationIDs+')';
  My question is: how does one replace that line of code and replace it
  with a table valued parameter in such a way that the concatenation
  would still work?

Suppose your LocationIdArray has this definition:
create type LocationIdArray as table (LocationId int);

Then your IN should look like this:
and s.Location_ID in (select LocationId from @LocationIDs)

This won't work within your exec because @LocationID is in the outer scope respect to exec, you can pass it as a parameter in sp_executesql but the best you can do is to rewrite your dynamic query to static one as there is no reason to use dynamic code here.


Q: Сравнение двух множеств чисел По заданию получаем 2 массива чисел.
Нужно написать функцию, которая проверяет похожие ли массивы.(массивы похожие, если совпадают множества чисел в них).
Нужно использовать сортировку слиянием и обменом.
Как я понимаю - нужно отсортировать массивы используя разные сортировки, а после поэлементно проверять совпадение массивов. Но в таком случае сортировка не имеет смысла.

A: Как мы можем сравнить два объекта, если они имеют несколько представлений? Например, равны ли два рациональных числа 4/10 и 12/30? Совпадают ли корни уравнений x2+2x+4 и 5x2+10x+20? Совпадают ли множества [1; 2; 3] и [1; 3; 2]?
Если решать задачу «в лоб», то объекты не совпадают, но в действительности 4/10 == 12/30. Лобовое решение неправильно.
Для того, чтобы решать такие задачи, объекты приводят к единому виду, который часто называют нормальным, а само приведение — нормализацией. Дроби сокращают, все коэффициенты квадратного уравнения делят на коэффициент при x2, а массивы сортируют.
Иногда возможны разные способы нормализации. Если числа у вас небольшие, вместо массива вы можете хранить их в битовом массиве. Например, для множество чисел от 0 до 31 можно хранить в одном тридцатидвухбитном целом числе, установив соответствующие биты.
Тогда сравнение множеств сведётся к сравнению двух целых чисел. Но, если наши числа могут быть произвольными, битовый массив может оказаться слишком большим. В этом случае хорошо работает сортировка. Сравнение двух отсортированных массивов сводится к простому попарному сравнению с временной сложностью O(N). Это, конечно, не очень быстро, но гораздо быстрее, чем попарное сравнение сортированных массивов со сложностью O(N2).

A: Смотря на каком языке это делать. На php например можно сразу без сортировки сделать array_diff и сравнить его count() с count() первоначальных массивов, они если меньше нужного значения (например если меньше 20%) то да массивы содержат одинаковые значения на 80%.
Если же вручную надо проделать сверку то да, тут другая ситуация, но тогда можно подсмотреть как работаю похожие функции в каком-то языке, т.к. самому оптимальный алгоритм сходу сложно придумать.


Q: how to call custom data from Django User models im using the built in User model of django and have added few custom fields one of them being the user type, i want to set up conditional statements according to the e_type
this is my code.
models.py
from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from django.contrib import auth
from django.conf import settings

class User(auth.models.User,auth.models.PermissionsMixin,models.Model):
    EMPLOYEE='em'
    MANAGER='mn'
    USER_TYPE=[
        (EMPLOYEE,'employee'),
        (MANAGER,'manager'),
     ]
    e_type=models.CharField(max_length=2,choices=USER_TYPE,default=EMPLOYEE)
    no_of_leaves=models.IntegerField(null=False,validators=[MinValueValidator(1),
                                   MaxValueValidator(24)],default=24)

    def __str__(self):
        return "@{}".format(self.username)

views.py
from django.shortcuts import render
from django.contrib.auth import views as auth_views
from .models import *
from django.views.generic import TemplateView

def home(request):
    user=request.user.e_type
    return render(request,"leaveApp/home.html")


Q: Get current user in angular using firebase? Currently trying to build an app using ionic v2 & firebase v3.
Unfortunately I'm struggling to simply grab hold of the logged in user's details.
In my app.ts, I connect correctly to my firebaseapp and the logged in user is recognised and the user is shown the homepage:
import {Component} from '@angular/core';
import {Platform, ionicBootstrap, NavController} from 'ionic-angular';
import {StatusBar} from 'ionic-native';
import {HomePage} from './pages/home/home';
declare var firebase:any;
import {Data} from './providers/data/data';
import {LoginPage} from './pages/login/login';

@Component({
  template: '<ion-nav [root]="rootPage"></ion-nav>',
  providers: [Data]
})
export class MyApp {
  rootPage: any = LoginPage;

  constructor(platform: Platform) {
    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      // Here you can do any higher level native things you might need.
      StatusBar.styleDefault();

      // Initialize Firebase
      var config = {
        apiKey: "xxxx",
        authDomain: "xxxx.firebaseapp.com",
        databaseURL: "https://xxxx.firebaseio.com",
        storageBucket: "xxxx.appspot.com",
      };

      firebase.initializeApp(config);

      firebase.auth().onAuthStateChanged((user) => {
        if (user) {
          // If there is a user, take him to home page.
          console.log("User is logged in!");
          //console.log(user);
          this.rootPage = HomePage;
        } else {
          // If there is no user logged in, send to login page.
          this.rootPage = LoginPage;
        }
      });
    });
  }
}

ionicBootstrap(MyApp);

Then in another of my files where I wish to retrieve the logged in user's ID using
var authData = firebase.auth().currentUser();

I get the following error in my console:
EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in :0:0
ORIGINAL EXCEPTION: TypeError: firebase.auth(...).currentUser is not a function
ORIGINAL STACKTRACE:
TypeError: firebase.auth(...).currentUser is not a function
    at new AddItemPage (http://localhost:8100/build/js/app.bundle.js:97:40)
    at DebugAppView._View_AddItemPage_Host0.createInternal (AddItemPage_Host.template.js:20:27)
    at DebugAppView.AppView.create (http://localhost:8100/build/js/app.bundle.js:30016:21)
    at DebugAppView.create (http://localhost:8100/build/js/app.bundle.js:30228:44)
    at ComponentFactory.create (http://localhost:8100/build/js/app.bundle.js:29245:36)
    at ViewContainerRef_.createComponent (http://localhost:8100/build/js/app.bundle.js:30436:45)
    at http://localhost:8100/build/js/app.bundle.js:53117:47
    at ZoneDelegate.invoke (http://localhost:8100/build/js/zone.js:323:29)
    at Object.onInvoke (http://localhost:8100/build/js/app.bundle.js:35470:41)
    at ZoneDelegate.invoke (http://localhost:8100/build/js/zone.js:322:35)
ERROR CONTEXT:
[object Object]

I'm confused as to why currentUser() is not a function, when the documentation says it is?
https://firebase.google.com/docs/auth/web/manage-users#get_the_currently_signed-in_user
Thanks!

A: the documentation says that
firebase.auth().currentUser NOT firebase.auth().currentUser() is the correct way to get the user


Q: Removing phantom applications from Application Pools in IIS7 I have an application in one of my application pools that has a virtual path of /Site/login.aspx.  I want to remove it but it no longer exists on my computer and it's causing me issues setting up AppFabric.
I understand that you can remove these phantom applications by recreating the application in IIS and then hitting Remove.  That will get rid of the application from the pool but in this case I can't recreate the application due to the /login.aspx in the virtual path
Any ideas how I remove this erroneous entry?

A: This is probably safer and simpler than editing applicationHost.config.
Powershell
PS C:\Windows\system32> import-module WebAdministration
PS C:\Windows\system32> iis:
PS IIS:\> cd .\AppPools
PS IIS:\AppPools> ls
PS IIS:\AppPools> del [name of phantom AppPool]

A: Since I had the same issue; application pools with applications that did not exist anymore, I did some research and finally managed to solve the issue.
Here are some steps:

*

*Locate and edit your IIS 7 configuration file "applicationHost.config" with a text editor.  It should be stored in "C:\windows\system32\inetsrv\config" Since the folder is somehow "protected", I usually edit like the following:

*

*Open Windows Explorer

*Navigate to "C:\windows\system32\inetsrv\config"

*Copy the file "applicationHost.config"

*Paste it to a folder where you can edit it, e.g. your Desktop

*Open it with your editor of choise and edit it

*Copy it back with Windows Explorer to "C:\windows\system32\inetsrv\config"

*Make a backup of your "applicationHost.config" file!

*Search with a text editor in your "applicationHost.config" for your non-existing applications. They should be located somewhere inside an <application ...> XML node.

*Delete the <application ...> node(s) of all your phantom applications.

*Save the file and copy it back to "C:\windows\system32\inetsrv\config"

*Refresh the IIS management console. Your application pools should now be without the phantom applications you previously deleted.

*Actually remove the now empty application pool.

That worked for me, if it does not work for you, please post a comment here. A good help was this posting on the IIS forum.
Please be also aware that when editing the "applicationHost.config" file directly in its original location, you need to use a 64-bit editor (e.g. Notepad++ 64-bit), because otherwise it would get stored in "C:\Windows\SysWOW64\inetsrv\Config" instead of the correct location.

A: There is an easy way to fix this.

*

*Select the site with the Phantom applications in the application pool.

*On the right side "Action" menu select "View Applications". This list should show all the applications that is in the site, Phantom or not.

*All you need to do is select the Application and select "Remove" in the right "Action" menu.

A: Child applications aren't automatically deleted and the IIS Manager can't display them in the tree, so that's your problem...
A quick and robust way is to use a PowerShell script to get all applications, test whether the physical path still exists and if not, delete the application:
# This is for IIS 7, make sure the snap-in is installed first: https://www.iis.net/downloads/microsoft/powershell
Add-PSSnapin WebAdministration

# Get all IIS sites
Get-ChildItem IIS:\Sites | foreach {
    $site = $_;

    # Get all applications without existing physical path
    $applications = Get-ChildItem $site.PsPath | Where-Object { $_.NodeType -eq "application" -and (Test-Path $_.PhysicalPath) -eq $False };

    # List all phantom applications
    $applications | FT

    # Remove applications
    $applications | Remove-WebApplication -Site $site.Name
}

A: Much more simple:

*

*View stale application X and remember the (old) path Y

*Create the (old) path / folder Y with Explorer

*Refresh IIS Management Console

*You will find the just created folder Y and assigned application X

*Right click on (old) application X and choose "Remove"

*Remove path Y with Explorer

*Refresh IIS Management Console again

*Hurray

A: Why not edit MetaBase.xml directly? Of course, back it up before that.
Or create a "temp" pool, move all other apps there, remove the orig pool, and rename (if needed) the new pool.

A: I did a combination of two answers listed above since I did not want to tinker applicationHost.config manually.
Step 1 - Create a temporary app pool - let's say "temp".
Step 2 -
    Move all the phantom applications to this temp app pool.
Step 3 - Use Powershell from one of the answers above -
Powershell
PS C:\Windows\system32> import-module WebAdministration
PS C:\Windows\system32> iis:
PS IIS:\> cd .\AppPools
PS IIS:\AppPools> ls
PS IIS:\AppPools> del [name of phantom AppPool]

Voila!


Q: Database error in model using Code Igniter Error:
(POST http://localhost/codeigniter/Purchase/transaction/update?id=7 500 (Internal Server Error)
Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near ''supp_id2` =
s.`supp_id` WHERE p.purch_id =' at line 1

SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as s ON
p.'supp_id2` = s.`supp_id` WHERE p.purch_id =

Filename: C:/xampp/htdocs/codeigniter/system/database/DB_driver.php

Line Number: 691

this is the Controller of my code, this is where the transaction is located at
function transaction($txn = null) {
    switch ($txn) {
        case 'list':

            $response['data']=$this->Purchase_model->get_all_purchase();
            echo json_encode($response);

        break;

        case 'create':
            $purchase =
            array(
                'po_number' => $this->input->post('po_number'),
                'date' => $this->input->post('date'),
                'supp_id2' => $this->input->post('supp_id2'),
                'contact_person' => $this->input->post('contact_person'),
                'delivered_to' => $this->input->post('delivered_to'),
                'plu_number' => $this->input->post('plu_number'),
                'address' => $this->input->post('address'),
                'remarks' => $this->input->post('remarks'),
            );

            $insert = $this->Purchase_model->purchase_add($purchase);

            $resp['row_added'] = $this->Purchase_model->get_purchase($insert);
            $resp['title'] = 'Success!';
            $resp['stat'] = 'success';
            $resp['msg'] = 'Purchase Information successfully created.';

            echo json_encode($resp);
        break;

        case 'update':
            $data =
            array(
                'po_number' => $this->input->post('po_number'),
                'date' => $this->input->post('date'),
                'supp_id2' => $this->input->post('supp_id2'),
                'contact_person' => $this->input->post('contact_person'),
                'delivered_to' => $this->input->post('delivered_to'),
                'address' => $this->input->post('address'),
                'plu_number' => $this->input->post('plu_number'),
                'remarks' => $this->input->post('remarks'),
            );

this is the purchase model I created
 public function get_purchase($purch_id)
 {
    $db = "SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as
 s ON p.'supp_id2` = s.`supp_id` WHERE p.purch_id = $purch_id ";
 return $this->db->query($db)->result();-
    $this->db->from($this->table);
    $this->db->where('purch_id',$id);
    $query = $this->db->get();

    return $query->row();
}

if you need to see the other details please ask so a I can send it to the comment section or edit this post, how to solve this?
UPDATE:
I changed the 'supp_id2tosupp_id2` and it shows a new but I think the same error:
 Error Number: 1064

 You have an error in your SQL syntax; check the manual that corresponds to
 your MySQL server version for the right syntax to use near '' at line 1

 SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as s ON
 p.`supp_id2` = s.`supp_id` WHERE p.purch_id =

 Filename: C:/xampp/htdocs/codeigniter/system/database/DB_driver.php

 Line Number: 691

A: The syntax is wron:
 $db = "SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as
    s ON p.'supp_id2` = s.`supp_id` WHERE p.purch_id = $purch_id ";

copy this select
  $db = "SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as
 s ON p.`supp_id2` = s.`supp_id` WHERE p.purch_id = $purch_id ";

A: As you can see at the error
Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near ''supp_id2` =
s.`supp_id` WHERE p.purch_id =' at line 1

SELECT p.*, s.supp_name FROM purchase as p LEFT JOIN supplier as s ON
p.'supp_id2` = s.`supp_id` WHERE p.purch_id =

Filename: C:/xampp/htdocs/codeigniter/system/database/DB_driver.php

Line Number: 691

Purchase id is not passing to the query.


Q: Is it safe to read a weak pointer while it's being deallocated? Is it safe to read a nonatomic weak pointer from a different thread than the object is being deallocated from?
In general, I know properties should be made atomic whenever there may be simultaneous accesses, at least one of which is a write operation.  But I have to wonder if ARC's write operation (setting the pointer to nil) is somehow special.  Otherwise, I would've expected to see more warnings about this possible issue.  Perhaps weak pointers are implicitly atomic?

A: It is safe. Accessing weak pointer and Zeroing weak pointer is in between spinlock_lock and spinlock_unlock.
Take a look at the runtime source code
http://opensource.apple.com/source/objc4/objc4-646/runtime/NSObject.mm
Accessing weak pointer
id
objc_loadWeakRetained(id *location)
{
    id result;

    SideTable *table;
    spinlock_t *lock;

 retry:
    result = *location;
    if (!result) return nil;

    table = SideTable::tableForPointer(result);
    lock = &table->slock;

    spinlock_lock(lock);
    if (*location != result) {
        spinlock_unlock(lock);
        goto retry;
    }

    result = weak_read_no_lock(&table->weak_table, location);

    spinlock_unlock(lock);
    return result;
}

Zeroing weak pointer
void
objc_object::sidetable_clearDeallocating()
{
    SideTable *table = SideTable::tableForPointer(this);

    // clear any weak table items
    // clear extra retain count and deallocating bit
    // (fixme warn or abort if extra retain count == 0 ?)
    spinlock_lock(&table->slock);
    RefcountMap::iterator it = table->refcnts.find(this);
    if (it != table->refcnts.end()) {
        if (it->second & SIDE_TABLE_WEAKLY_REFERENCED) {
            weak_clear_no_lock(&table->weak_table, (id)this);
        }
        table->refcnts.erase(it);
    }
    spinlock_unlock(&table->slock);
}

And the Object deallocating flow
https://stackoverflow.com/a/14854977/629118


Q: Display external website page in asp .net mvc 5 I am building a website for a class project using ASP NET MVC 5, wherein I need a section of the website to display a page from a different website. The goal is to somehow embed that page in my view, so UI interactions are still possible with the embedded page, as if the page was visited directly in the browser (the end effect is that the page is rendered and allows interaction but my website theme always stays around it)
I know one way to do it is to just put it inside an iframe in my View. But I want to know if there is a different solution. My instructor suggested using partial views, but I can't figure out how to achieve the same result. Can anyone suggest a different way to achieve this ? Also, what would be the right way to do this in terms of security (I believe iframe is), but I want to know other's opinion ?
Thanks.

A: I suggest you use a sandboxed IFrame e.g.
http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/
<iframe sandbox="allow-same-origin allow-scripts allow-popups allow-forms"
    src="https://blah.com/index.html"
    style="border: 0; width:130px; height:20px;">
</iframe>

You can tweak how much power the content in the Iframe has (i.e. can it run scripts).
I guess you could also look at using a partial view. My guess is you'd need to use a WebClient instance to download the HTML source of the target webpage, and then pass that HTML into a partial view. But I don't see how any script tags would render correctly for you, which means the page would not be interactive.


Q: In LibreOffice Calc, how do I change through LibreOffice Basic the value of a cell with an event listener set to it without crashing the program? I am trying to create two tables which mirror changes made to any of them to one another automatically.
To that end, I added event listeners which are triggered when the cells of these tables are edited by the user.
Unfortunately, editing one of the tables causes LibreOffice to crash, even though the changes are indeed reflected correctly, as seen upon reopening the file.
I thought the crash might be due to a never-ending circular reference, but it still crashes after it has been made non-circular (by commenting out the relevant parts of the code so that changes are reflected only one way rather than both ways).
I noticed the code worked fine when writing to a cell that didn't have an event listener set to it.
How can I write to one of the cells with event listeners set to them without causing LibreOffice to crash?
You may want to download the following file. Please run Main and then try editing the cell C3 of the Planning sheet. The arbitrary string "C" should be written in the cell C4 of the Services sheet.
Here is a simplified version of the code :
REM  *****  BASIC  *****

const SERVICESSHEET_NUMBER = 2
const SERVICESSHEET_SERVICES_COLUMN = 2

Type cellStruct
    columnNumber As Integer
    rowNumber As Integer
End Type

Sub UpdateServicesSheet(editedCell As cellStruct, newValue As String)

    Dim oSheets
    Dim servicesSheet

    oSheets = ThisComponent.getSheets()
    servicesSheet = oSheets.getByIndex(SERVICESSHEET_NUMBER)

    servicesSheet.getCellByPosition(SERVICESSHEET_SERVICES_COLUMN, 3).setString(newValue)

End Sub

Private oListener, cellRange as Object

Sub AddListener
    Dim sheet, cell as Object

    sheet = ThisComponent.Sheets.getByIndex(0)  'get leftmost sheet
    servicesSheet = ThisComponent.Sheets.getByIndex(2)

    cellRange = sheet.getCellrangeByName("C3")
    oListener = createUnoListener("Modify_","com.sun.star.util.XModifyListener")  'create a listener
    cellRange.addModifyListener(oListener)  'register the listener

    cellRange = servicesSheet.getCellrangeByName("C4")
    oListener = createUnoListener("Modify_","com.sun.star.util.XModifyListener")  'create a listener
    cellRange.addModifyListener(oListener)  'register the listener
End Sub

global CircularReferenceAllowed As boolean

Sub Modify_modified(oEv)

    Dim editedCell As cellStruct
    Dim newValue As String

    editedCell.columnNumber = 2
    editedCell.rowNumber = 2

    If CircularReferenceAllowed Then
        CircularReferenceAllowed = false
        UpdateServicesSheet(editedCell, "C")
    End If

End Sub

Sub Modify_disposing(oEv)
End Sub

Sub RmvListener
    cellRange.removeModifyListener(oListener)
End Sub

Sub Main

    CircularReferenceAllowed = true
    AddListener

End Sub

Crossposted to :

*

*OpenOffice forums

*LibreOffice discourse platform

A: It seems like the event trigger is within another event's function is causing the crash. In any case, the solution is to remove the listener, then add it back after modifying the other cell.
You do need to global the Listener and the Cell objects to make this work.
This code is simplified to work on C3 and C15 on the first sheet. It would also output some information on C14, which isn't really necessary for your purpose, but I use it to see what's happening. You need to adopt the according to what you need.
global goListener as Object
global goListener2 as Object
global goCellR as Object
global goCellR2 as Object
global goSheet as Object

global giRun as integer
global giUpd as Integer

Sub Modify_modified(oEv)
    Dim sCurStr$
    Dim sNewStr As String
    'xRay oEv

    giRun = giRun + 1
    sCurStr = oEv.source.string

    oCell = goSheet.getCellByPosition(2, 14)
    If (oCell.getString() <> sCurStr) Then
        ' only update if it's different.
        giUpd = giUpd + 1
        goCellR2.removeModifyListener(goListener2)
        oCell.setString(sCurStr)
        goCellR2.addModifyListener(goListener2)
    End If
    sNewStr =sCurStr & " M1 Run=" & giRun & " Upd=" & giUpd
    goSheet.getCellByPosition(2, 13).setString(sNewStr)
End Sub

Sub Modify2_modified(oEv)
    Dim sCurStr$
    Dim sNewStr As String
    Dim oCell as Object
    'xRay oEv

    giRun = giRun + 1
    sCurStr = oEv.source.string
    oCell = goSheet.getCellByPosition(2, 2)
    If (oCell.getString() <> sCurStr) Then
        ' only update if it's different.
        giUpd = giUpd + 1
        goCellR.removeModifyListener(goListener)
        oCell.setString(sCurStr)
        goCellR.addModifyListener(goListener)
    End If
    sNewStr =sCurStr & " M2 Run=" & giRun & " Upd=" & giUpd
    goSheet.getCellByPosition(2, 13).setString(sNewStr)
End Sub

Sub Modify_disposing(oEv)
    MsgBox "In Modify_disposing"
End Sub

Sub Modify2_disposing(oEv)
    MsgBox "In Modify2_disposing"
End Sub

Sub RmvListener
    MsgBox "In RmvListener"
    goCellR.removeModifyListener(goListener)
    goCellR2.removeModifyListener(goListener2)
End Sub

Sub AddListener

    goSheet = ThisComponent.Sheets.getByIndex(0)  'get leftmost goSheet
    'servicesSheet = ThisComponent.Sheets.getByIndex(2)

    goCellR = goSheet.getCellrangeByName("C3")
    goListener = createUnoListener("Modify_","com.sun.star.util.XModifyListener")  'create a listener
    goCellR.addModifyListener(goListener)  'register the listener

    goCellR2 = goSheet.getCellrangeByName("C15")
    goListener2 = createUnoListener("Modify2_","com.sun.star.util.XModifyListener")  'create a listener
    goCellR2.addModifyListener(goListener2)  'register the listener
End Sub

Sub Main
    giRun = 0
    giUpd = 0
    AddListener

End Sub


Q: Why the swift compiler cannot use my subscript? I have code that resembles this
I created custom subscript to do the unwrapping for me to make things easier.
enum MyEnum {
   case one
   case two
   case three
}

struct MyStruct {
   static var empty: Self {
       return .init()
   }

   //Some Variables Here
}

class MyClass {
   var index = 0

   var data: [MyEnum: MyStruct] = [
       .two: .empty,
       .three: .empty,
       .one: .empty
   ]

   var allTypes: [MyEnum] {
       switch Bool.random() {
           case true:
               return [.two, .three]
           case false:
               return [.one]
       }
   }

   var currentSelectedType: MyEnum {
       return allTypes[index]
   }

   func myMethod(type: MyEnum) {
       let one: MyStruct = data[type]!
       let two: MyStruct = data[currentSelectedType]!
       let three: MyStruct = data[allTypes[index]]
       let four: MyStruct = data[.one]

   }
}

fileprivate extension Dictionary {
   subscript(_ key: Key) -> Value where Key == MyEnum, Value == MyStruct {
       get {
           return self[key]!
       }
       set {
           self[key] = newValue
       }
   }
}

in my MyClass myMethod why I have to forcely unwrapp one and two but not three and four otherwise I get a compile time error
       let one: MyStruct = data[type] // Error Value of optional type 'MyStruct?' must be unwrapped to a value of type 'MyStruct'
       let two: MyStruct = data[currentSelectedType] //Error Value of optional type 'MyStruct?' must be unwrapped to a value of type 'MyStruct'

Is there something I'm missing here?

A: I don't have an answer on why compiler isn't picking the expected overload in this situation.
I would recommend clarifying the overload you wish to use at call site, like following.
fileprivate extension Dictionary {
    subscript(safe key: Key, defaultValue: Value = .empty) -> Value where Key == MyEnum, Value == MyStruct {
        get { return self[key, default: defaultValue] }
        set { self[key] = newValue }
    }
}

With above, you can tell compiler explicitly to use your preferred overload.
func myMethod(type: MyEnum) {
    let one: MyStruct = data[safe: type]
    let two: MyStruct = data[safe: currentSelectedType]
    let three: MyStruct = data[safe: allTypes[index]]
    let four: MyStruct = data[safe: .one]
}


Q: How to populate my Django Model 'updated_by' field with logged in User automatically using a formset? I am a beginner with Django and I have been enjoying it so far. I figured out how to use model formsets, but I cannot figure out how to make my form automatically use logged in User as the 'updated_by' field.
models.py
class Inventory(models.Model):
    item = models.CharField(max_length=50, unique=True)
    stock = models.IntegerField()
    par = models.IntegerField()
    date_updated = models.DateTimeField(auto_now=True)
    updated_by = models.ForeignKey(User, on_delete=models.PROTECT)

    def __str__(self):
        return self.item

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    phone = PhoneField(blank='True', help_text='Contact Phone Number')

    def __str__(self):
        return f'{self.user.username} Profile'

    def save(self):
        super().save()

A: I think the problem lies in your views.py. Try getting request.user before saving the form.

A: i think you should have made form for Inventory if yes(let InvntoryForm) than in view.py file you have done something like this:-
    if request.method == 'POST':
      Inven_form=InventoryForm(data=request.POST)

       if Inven_form.is_valid():
           user=Inven_form.save()
           #in between add this
           Inven_form.updated_by=request.user.username
           user.save()

A: I would use the 'commit=False' argument which will create a new object and assign it without saving to your database.  You can then set the user attribute and call save() with no arguments.
For example, this is how I assigned the user attribute to my blog app.
in views.py
if form.is_valid():
            # Create a new entry and assign to new_article.
            new_article = form.save(commit=False)

            # Set the new article attribute to the current user.
            new_article.user = request.user

            # Save to database now the object has all the required data.
            new_article.save()

Here is the full code for the add_article view if this helps.
@login_required
def add_article(request):
    """ Add a new article. """
    if request.method != 'POST':
        # No data submitted, create a blank form.
        form = AddArticleForm()
    else:
        # POST data submitted, process data.
        form = AddArticleForm(request.POST, request.FILES)
        if form.is_valid():
            new_article = form.save(commit=False)
            new_article.author = request.user
            new_article.save()
            return back_to_blog_page()

    context = {'form': form}
    return render(request, 'add_article.html', context)


Q: Move Primary Key to Filegroup (SQL Server 2012) How can I move a clustered primary key to a new filegroup? I already have found a possible "algorithm" but it is horribly inefficient:

*

*Drop non-clustered indexed (requires them to be resorted and rebuilt)

*Drop clustered index (requires the whole table to be resorted)

*Create new primary key constraint (huge sort operation)

*Create all non-clustered indexes (sorting and writing required)

Is there a more efficient way? This is horribly inefficient and will take a long time as the table is 50GB in size on a weak server.
Isn't there a way to skip all of these and just do a rebuild on a new filegroup? That would not require any sorting of data.

A: CREATE UNIQUE CLUSTERED INDEX Your_PK_Name
    ON YourTable(YourColumnList)
WITH (DROP_EXISTING =  ON )
ON [YourOtherFileGroup]

This preserves the logical PK property despite it not being mentioned in the syntax.


Q: Deploying with composer on fabric I am looking for the right way on doing a wordpress deployment using

*

*Fabric

*Composer

What I have:

*

*A nginx, php-fpm and mysql plataform running on Ubuntu 12.04 LTS

*A common sudoer user, as example, I will name "deployer"

*A web user name www-data with a group named www-data
What I am looking for:

*

*Deploy a wordpress site with composer using fabric

*Deployment would be done with the sudoer user named "deployer" but www-data directory owned

*Deploy must be done on /var/www/my_wordpress_site
Issues

*

*Composer couldn't write /home/deployer/.composer, I guess composer try to use it directory since teh user used for the deploy is deployer

*Composer couldn't install dependences

Question:

*

*Could be possible to install the wordpress site on a directory like /home/deployer/my_wordpress_site and make it nginx writable?

*What would be the right way for make deploys on web sites

Fabric Code
<pre>

STAGES = {
        'development' : {
            'hosts'       : ['deployer@deployment-server'],
            'code_dir'    : '/var/www/my_wordpress_site' ,
            'code_branch' : 'development'
            },
            ....
        }

def stage_set(stage_name='development'):
    env.stage = stage_name
    for option, value in STAGES[env.stage].items():
        setattr(env, option, value)
....

@task
def development():
    stage_set('development')

@task
def deploy():
    require('stage', provided_by=(production, staging, development))
    with settings(warn_only=True):
        if sudo("test -d %s" % env.code_dir, user='www-data', group='www-data').failed:
            sudo("git clone git@bitbucket.org:myuser/my_wordpress_site.git %s" % (env.code_dir), user='www-data', group='www-data')
            with cd(env.code_dir):
                sudo("php -r \"copy('https://getcomposer.org/installer', 'composer-setup.php');\"", user='www-data', group='www-data')
                sudo("php -r \"if (hash_file('SHA384', 'composer-setup.php') === '55d6ead61b29c7bdee5cccfb50076874187bd9f21f65d8991d46ec5cc90518f447387fb9f76ebae1fbbacf329e583e30') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;\"", user='www-data', group='www-data')
                sudo("php composer-setup.php", user='www-data', group='www-data')
                sudo("php -r \"unlink('composer-setup.php');\"", user='www-data', group='www-data')
                sudo("php composer.phar install --no-dev", user='www-data', group='www-data')
    with cd(env.code_dir):
        sudo("git pull", user='www-data', group='www-data')
        sudo("php composer.phar update --no-dev", user='www-data', group='www-data')
        </pre>


Q: C Library checksum for binary file in windows and linux I'm using CRC library for checksum, for text file the result same in windows and linux, but for binary file the result different.
I'm using mingw for compiler my c program in windows, checksum result different. is there a way checksum result same between windows and linux using CRC library?
Adding code :
I using this code for checksum file, found it from some web googling. (forgot to save the link).
crc32.c
#include <sys/types.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>

#define CRC(crc, ch)     (crc = (crc >> 8) ^ crctabb[(crc ^ (ch)) & 0xff])

static const uint32_t crctabb[256] = {
    0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
    0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
    0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
    0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
    0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
    0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
    0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
    0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
    0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
    0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
    0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940,
    0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
    0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116,
    0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
    0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
    0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
    0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a,
    0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
    0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818,
    0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
    0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
    0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
    0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c,
    0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
    0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
    0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
    0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
    0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
    0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086,
    0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
    0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4,
    0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
    0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
    0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
    0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
    0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
    0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe,
    0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
    0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
    0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
    0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252,
    0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
    0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60,
    0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
    0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
    0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
    0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04,
    0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
    0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
    0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
    0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
    0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
    0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e,
    0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
    0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
    0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
    0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
    0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
    0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0,
    0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
    0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6,
    0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
    0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
    0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d,
};

uint32_t crc32_total = 0;

int crc32(int fd, uint32_t *cval, off_t *clen)
{
    uint32_t lcrc = ~0;
    int nr ;
    off_t len ;
    char buf[BUFSIZ], *p ;

    len = 0 ;
    crc32_total = ~crc32_total ;
    while ((nr = read(fd, buf, sizeof(buf))) > 0)
        for (len += nr, p = buf; nr--; ++p) {
        CRC(lcrc, *p) ;
        CRC(crc32_total, *p) ;
    }
    if (nr < 0)
        return 1 ;

    *clen = len ;
    *cval = ~lcrc ;
    crc32_total = ~crc32_total ;
    return 0 ;
}

checksum.c
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "crc32.c"

int main (int argc,char *argv[]){
        uint32_t val;
        int ch, fd;
        off_t len;
        int (*cfncn)(int, uint32_t *, off_t *);

        cfncn = crc32;
        fd = STDIN_FILENO;
        if ((fd = open(argv[1], O_RDONLY, 0)) < 0) {
        }
        if (cfncn(fd, &val, &len)) {
        }
        printf("%d\n",val);
}

I run this code checksum binary file
Windows result 10992
Linux result 1663

A: In Windows, you must open the file in binary mode by adding the _O_BINARY flag:
fd = open(argv[1], O_RDONLY | _O_BINARY, 0)

If you don't, the C++ runtime will perform translations on the contents of the file as it's read in. The most obvious result will be to remove all the \r characters from the input, but an even greater danger is that it will signal end-of-file when it reads \x1a and you'll stop prematurely. The first is an attempt to normalize the line-endings between text files on the *nix systems where C was first developed (which uses \n by itself), and text files on Windows (which uses the pair \r\n). The second is backwards compatibility run amok, retaining a convention that existed before DOS when file sizes couldn't be specified in blocks less than 128 characters.


Q: Wordpress Custom taxonomy template I am trying to create custom template for custom taxonomy. For example i have a custom taxonomy registered in WP with name brands and slug brand
i used following code to register custom taxonomy.
function brand() {

$labels = array(
    'name'                       => _x( 'brands', 'Taxonomy General Name',  'text_domain' ),
    'singular_name'              => _x( 'brand', 'Taxonomy Singular Name', 'text_domain' ),
    'menu_name'                  => __( 'Brands', 'text_domain' ),
    'all_items'                  => __( 'All Brands', 'text_domain' ),
    'parent_item'                => __( 'Brand Parent Item', 'text_domain' ),
    'parent_item_colon'          => __( 'Parent Item:', 'text_domain' ),
    'new_item_name'              => __( 'New Brand', 'text_domain' ),
    'add_new_item'               => __( 'Add New Brand', 'text_domain' ),
    'edit_item'                  => __( 'Edit Brand', 'text_domain' ),
    'update_item'                => __( 'Update Brand', 'text_domain' ),
    'view_item'                  => __( 'View Brand', 'text_domain' ),
    'separate_items_with_commas' => __( 'Separate items with commas', 'text_domain' ),
    'add_or_remove_items'        => __( 'Add or remove Brands', 'text_domain' ),
    'choose_from_most_used'      => __( 'Choose from the most used', 'text_domain' ),
    'popular_items'              => __( 'Popular Brands', 'text_domain' ),
    'search_items'               => __( 'Search Brands', 'text_domain' ),
    'not_found'                  => __( 'Not Found', 'text_domain' ),
);
$rewrite = array(
    'slug'                       => 'brand',
    'with_front'                 => true,
    'hierarchical'               => true,
);
$args = array(
    'labels'                     => $labels,
    'hierarchical'               => true,
    'public'                     => true,
    'show_ui'                    => true,
    'show_admin_column'          => true,
    'show_in_nav_menus'          => true,
    'show_tagcloud'              => true,
    'rewrite'                    => $rewrite,
);
register_taxonomy( 'brand', array( 'product' ), $args );

}

// Hook into the 'init' action
add_action( 'init', 'brand', 0 );

I am trying to create a template to show details of brand taxonomy in a page.  i tried creating page templates with name
taxonomy-brand.php   (taxonomy-{slug}.php)
taxonomy-brands.php   (taxonomy-{name}.php)
single-brand.php    (single-{slug}.php)
single-brands.php    (single-{name}.php)

But they are not working and wordpress is showing brand details on single.php instead of showing on a custom template. Please tell me where i am doing wrong.
Thank you

A: I think you are using brand taxonomy for the post type product.
You should create a file taxonomy-brand.php in your theme directory to display whatever you want in this page. You need not to create page template with this name, only create a file with this name in your theme. If you create any page by name brand please rename or delete it because page details will be open if you created by this name. If you want to display details of the product, create single-product.php in your theme directory.

A: Just changed permalink settings ti default and then changed them to post_name and then it worked fine.
page templates were created fine and taxonomy were registered fine as well. issue was with .htaccess file.


Q: How to change onclick text's position? Hi guys so I'm new to all this html stuff.
Basically;
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick
When i do this the text shows up under the button. I want it next to the button (right)
How can i do that?

A: Add display:inline-block to p tag
Try this.
<button onclick="myFunction()">Click me</button>

Fiddle:https://jsfiddle.net/9yqs14p4/

A: I'm afraid you need to spend a bit more time learning about this. Realistically you'll need to use CSS to style the HTML that is output by your Javascript.
Both CodeSchool and Codecademy have great tutorials on learning the basics of HTML, CSS and Javascript. You'll need to learn these basics if you want to do this sort of thing yourself.
https://www.codeschool.com/
https://www.codecademy.com/
I've copied your example into a CodePen, which helps to show you the roles played by HTML, CSS and Javascript. As an example, the CSS could be;
http://codepen.io/tombeynon/pen/rVQvMO
button{
    float:left;
    margin-right:5px;
}

#demo{
    float:left;
}

A: First of all you have to know, that in HTML there are inline elements, e.g  and block elements, e.g
. That means, what the word says.
You can test the difference:
// block

div1

div2

// inline
span1span2

In the example is used the
 tag which is a block element. Therefore
you see the text below.
<button> is an inline element. If you simply use a span:

it works!


Q: Two independent sequences in $l_\infty$ that are bounded by $1$, and their sum is bounded by $2$
Prove that there are $2$ independent vectors $x,y \in(l_\infty)$ such that $||x||=||y||=1$ and $||x+y||=2$
(Here $l_\infty = \{(a_n)|a_n\in \mathbb{C}, sup|a_n|<\infty\}$ and $||x||=sup|x_n|$).

I was thinking about the following -
$x=(x_n)=(1-\frac{1}{n})$, $y=(y_n)=1$.
It is easy to see that $||x||=||y||=1$, and also that $||x+y||=||1-\frac{1}{n}+1||=2$.
What I'm not sure is, are $x,y$ independent?
(My definition of being independent - $x_1,x_2,...,x_n\in E$ are independent in $E_0$ if: $\sum_{i=1}^n\alpha_ix_i \in E_0 \iff\alpha_i=0 \forall 1\le i \le n$).


Q: Action Script 3 Errors 1061 and 1120 I'm new to this, not sure what I'm doing wrong, Thank you for help
Please see my code below:
protected function getXMLUrl(vid:String):String {

    //return 'http://v.iask.com/v_play.php?vid='+ vid;

    var rand:*   = Math.random();
    var f1:*     = function (param1:Number) : Number {

        var _loc_2:* = param1.toString(2);
        var _loc_3:* = _loc_2.substring(0, _loc_2.length - 6);
        return parseInt(_loc_3, 2);
    };

    var Str1:*   = "Z6prk18aWxP278cVAH";
    var Date1:*  = new Date();
    var Num:*    = this.f1(int(Date1.time / 1000));
    var str:*    = vid.toString() + str1 + Num + rand.toString();
    var hash:*   = MD5.hash(str);
    var encode:* = hash.substr(0, 16).toString() + Num.toString();

    return 'http://v.iask.com/v_play.php?vid='+ vid + "&ran=" + rand + "&p=i&k=" + encode;
}

And here are the Errors I'm getting
1061: Call to a possibly undefined method f1 through a reference with static type

1120: Access of undefined property MD5.

1120: Access of undefined property str1.

A: Never mind, I fixed it
add
import com.adobe.crypto.MD5;

also deleted all the " :* "


Q: There are N fish in a pond There are N fish in a pond. You use a net to catch them, and each fish is equally likely to be caught.
One day, you catch 40 fish, tag each of them, and then throw them back. The next day, you catch 30 fish in the net and note that 6 have tags.
What is your best guess of the value of N?
I think this relates to the capture - recapture problem where N= total population; n=first sample, k=tagged items, m=second sample.
$\frac{\binom{n}{k}\binom{N-n}{m-k}}{\binom{N}{m}}$
but I honestly do not know how to proceed.

A: As you said, we need to use the capture-recapture formula, but this does not involve combinatorics. Here is the formula below: $$N=\frac{1st\:sample\:\times\:2nd\:sample}{2nd\:sample\:previously\:marked}$$ So in this case, $N =(40×30)/6=1200/6=200 $

A: Keeping it simple:

on Day 1 proportion of fish in pond that are tagged $=\frac{40}{N}$

on Day 2 proportion of fish in sample that are tagged $=\frac{6}{30}$

so solve $\frac{40}{N}$ = $\frac{6}{30}$ to get N = 200

A: Define a function $f:\mathbb{Z}_{\geq 64}\rightarrow [0,1]$ by $f(n)=\frac{{40 \choose 6}{n-40 \choose 24}}{{n \choose 30}}$. Then $f(n)=P(X=6|N=n)$ where $X$ is the number of tagged fish in your second sample of $30$ fish. I would use the value of $n$ that maximizes $f(n)$ as my estimate for $N$.


Q: How to draw a point beside a line? I have an arrow that can point at any direction. I need to draw a point alongside, at a specific distance. The point needs to remain on the correct side of the arrow. How do I do this? I know the angle of the arrow.
Illustration:
--->
o

A: If you have a vector representing the arrow, you could make a unit vector then times it by the length that you want and place the point at the end of the new shortened vector.

A: You already know the angle and location of the arrow, so what you should do is just draw the point based on the arrows end-point (the blunt end-point) and in the direction of the arrow + 90º.