text:
Q: Has BCS Cooper pair condensate been observed in experiment? Feshbach resonance in s-wave scattering states a BCS Cooper pair condensation at B-field just above the resonance where the scattering length a <0. Just wondering if the condensation has been observed in an experiment in any group? I was looking at a notes written in 2005 which claimed that this observation was the holy grail, and I seem not to be able to find a paper claiming that particular observation in experiment..
Many thanks :)
Simon

A: "BCS Cooper pair condensation" is theoretical method that is used to explain superconductivity/superfluidity in fermion systems.  If we treat "BCS Cooper pair condensation" as a physical phenomenon,  then I do not know if there is a general agreement on what is this physical phenomenon. ie what is the definition of "BCS Cooper pair condensation" as a physical phenomenon? If we define "BCS Cooper pair condensation" phenomenon as the phenomenon of superconductivity/superfluidity in fermion system, then the "BCS Cooper pair condensation" phenomenon has been observed.  But such a definition is not proper since there are superconductivity/superfluidity that has no "BCS Cooper pair condensation" (such as charge 4e condensation).
So, before answering if the  "BCS Cooper pair condensation" phenomenon has been
observed or not, we need to define what is "BCS Cooper pair condensation" phenomenon in terms of EXPERIMENTS. This is actually a very tricky thing to do.
It may be worth while to start a new question: What is the "BCS Cooper pair condensation" as a physical phenomenon in terms of EXPERIMENTS?

A: Yes! Here's an example from January 2004, for Cooper pair condensation with a < 0. DOI: 10.1103/PhysRevLett.92.040403
The authors conclude:
"The experimental realization of condensation in the BCS-BEC crossover regime demonstrated in this Letter follows more than two decades of theoretical investigation and initiates experimental study of this physics."
Here's a further paper from later that year that you might also be interested in, for repulsive (a > 0) Fermi condensates. DOI: 10.1103/PhysRevLett.92.120403


text:
Q: Django get PK dynamically from views.py I have a view that renders a comment form along with a template:
views.py
def news(request):
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.post = Article.objects.get(pk=2)
            print(comment.post)
            comment.author = request.user.username
            comment.save()
            return HttpResponseRedirect('')
    else:
        form = CommentForm()
    return render(request, '../templates/news.html', context={"form": form})

models.py
class Comment(models.Model):
    post = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comments', blank=True)
    author = models.TextField()
    text = models.TextField()

    def __str__(self):
        return self.text

forms.py
class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ('text',)

In views.py, where comment.post is getting assigned to Article objects, I want the pk to be applied dynamically. I tried doing it in the templates, where putting {{ article.pk }} in the templates output the right pk for the Article object but I wasn't sure how I'd go about applying it to my form.
The templates look simple: Article object, below it a comment form.
The problem is simple, I want the news(request) function to dynamically apply the pk of the current Article object in order to make the comment go to the right post.

A: You can either use the path if it's unique or you can just add a hidden field and set the article pk as value:
<input name="post" type="hidden" value={{ article.pk }} />

And your form:
class CommentForm(ModelForm):
    class Meta:
        model = Comment
        fields = ('text', 'post')

and you can access it from validated data in view.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android приложение и взаимодействие с сервером Пишу мобильное приложение-клиент, все действия делает сервер, моему приложению необходимо просто посылать запросы на сервер и оттуда получать информацию.
В целом, функциональность должна быть схожа с приложением olx (продажи).
Есть метод api, который возвращает мне N объявлений.
Как мне на постоянной основе взаимодействовать с сервером и как-нибудь сохранять информацию, чтобы лишний раз не посылать запросы? На данный момент использую IntentService для получения данных + sqlite для хранения промежуточных данных, чтобы UI обновлять из нее + ContentProvider.
Кто-нибудь может посоветовать другое решение или я нахожусь на правильном пути?


text:
Q: php - comparing timestamp dates to make sure user is of minimum age
Possible Duplicate:
How to calculate the difference between two dates using PHP?

When a user signs up the system has to check that they are old enough to do so, in this example they have to be atleast 8 years old
$minAge = strtotime(date("d")."-".date("m")."-".(date("Y")-8));
$dob = strtotime($day."-".$month."-".$year);

$minAge = 01-03-2004, $dob = 01-02-2011
I basically need to make sure this person was born before 2004 but I want to know whether I have to convert the timestamps to do a comparison or whether there is a more efficient way.
Any help is appreciated, thank you

A: With your $dob timestamp, you can subtract that from the current date's timestamp, and then balance those values versus your minAge. ex:
if(($dob-time())=>$minAge) {
   //OVER 8 YEARS
} else {
   //UNDER 8
}

Although, with this method you are comparing minage as a timestamp without days, hours, minutes or seconds, so keep that in mind when using the "time()" value as described in this example.

A: I think you just need to do something like this:
$dob = strtotime('1-1-2012');
$minAge = (60*60*24*365*8);//number of seconds of 8 years
if(time()-$dob>= $minAge)
{
   //OK

}
else
{
   //NOT OK
}

A: With PHP 5 you can use DateTime class for this kind of things:
function allowed_to_watch_adult_movies($birthday) {
  $min_age = 18;
  $user = new DateTime($birthday);
  $min_birthday = new DateTime('now - '.$min_age.' years');
  $interval = date_diff($min_birthday, $user);
  return $interval->invert == 1;
}
printf('Kid is %sallowed to watch adult movies
' ,
       allowed_to_watch_adult_movies('2004-05-18') ? '' : 'not ' );
printf('Grandpa is %sallowed to watch adult movies, but he does not care
' ,
       allowed_to_watch_adult_movies('1954-05-12') ? '' : 'not ' );


text:
Q: postgres materialized views and indexes to improve aggregate performance I have a large table with a number of materialized views used for pre-calculating aggregates. New data is inserted only once a day so think of this as a data warehouse type system.
Obviously when I query my main (non-aggregated) table, the planner uses any indexes it deems appropriate. Does that extend to materialized views? If I query the main table and the query involves aggregates, does it recognize that my materialized view already has the values it needs?

A: No. How would the query processor recognize that it should use the materialized view.  The materialized view is another object.
See  http://www.postgresql.org/docs/9.4/static/rules-materializedviews.html
In part that explains: "When a materialized view is referenced in a query, the data is returned directly from the materialized view."
So materialized views are useful, but you need to program not only for their maintenance, but also doing the necessary coding to use the materialized view.


text:
Q: Error : ORA-00907: missing right parenthesis I'm trying to create a simple table but it's giving me an error says:
Error starting at line : 1 in command -
CREATE TABLE dj_abonent
(
nr_klienti int NOT NULL,
emer_klienti varchar2(10),
sasia_cel int
CONSTRAINT dj_klientID PRIMARY KEY(nr_klienti)
)
Error at Command Line : 6 Column : 35
Error report -
SQL Error: ORA-00907: missing right parenthesis
00907. 00000 -  "missing right parenthesis"
*Cause:
*Action:
Error starting at line : 1 in command -
CREATE TABLE dj_abonent
(
nr_klienti int NOT NULL,
emer_klienti varchar2(10),
sasia_cel int,
CONSTRAINT dj_klientID PRIMARY KEY(nr_klienti)
)
Error at Command Line : 1 Column : 14
Error report -
SQL Error: ORA-00955: name is already used by an existing object
00955. 00000 -  "name is already used by an existing object"
*Cause:
*Action:

A: You are missing a comma:
CREATE TABLE dj_abonent
(
nr_klienti int NOT NULL,
emer_klienti varchar2(10),
sasia_cel int, -- this one right here
CONSTRAINT dj_klientID PRIMARY KEY(nr_klienti)
)

A: Your have the second error because you use dj_klientID as name for both of the constraints. They have to be unique.
Try renaming one of the two constraints and also your second query will be fixed.


text:
Q: Triple Integral In a Sphere Outside of a Cone Find the volume of the solid that lies within the hemisphere $x^2 + y^2 + z^2 =6$, z ≤ 0, and outside the cone $z=-\sqrt{x^2+y^2}$. I am not sure what to do for this question, I tried subtracting the area of the sphere from the cone, I also tried spherical but a unsure of what the limits for phi would be.

A: Due to symmetry, the solid is identical to the one which lies within the hemisphere $x^2 + y^2 + z^2 = 6$, $z \geq 0$ and outside the cone $z = \sqrt{x^2 + y^2}$, the only difference being that one is the mirror image of the other across $xy$-plane. (This is done just to avoid negative signs. This is a personal choice, and you can very well work with either of the solids). We will work with the solid which lies above $xy$-plane.
Notice that this solid is identical to the solid of revolution if we revolve $\Omega = \{(x,y)| \; x,y \geq 0; \; x^2 + y^2 \leq 6; \; x \geq y \}$ around $y$-axis.
Using Disk Method, the volume of this solid of revolution is given by:
$V = \pi \int \limits_{y = 0}^{\sqrt{3}} [(6 - y^2) - y^2] dy = 4 \sqrt{3} \pi$.
Alternatively, using triple integration,
$V = \int \limits_{\phi = 0}^{2 \pi} \; \; \int \limits_{\theta = \pi/4}^{\pi/2} \; \; \int \limits_{\rho = 0}^{\sqrt{6}} %
\rho^2 \; \sin{\theta} \; d\rho \; d\theta \; d\phi = %
4 \sqrt{3} \pi$.

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

Hereafter, $\ds{\bracks{\cdots}}$ are Iverson Brackets. Namely,
  $\ds{\bracks{P} = 1}$ whenever $\ds{P}$ is true and $\ds{0}$ otherwise.

$$
\bbox[15px,#ffe,border:1px dotted navy]{\mbox{You'll see how the calculation is done without worrying with pictures}}
$$
The problem symmetry is claiming for cylindrical coordinates. The volume $\ds{V}$ is given by:
\begin{align}
V & = \iiint_{\large\mathbb{R}^{3}}\bracks{x^{2} + y^{2} + z^{2} < 6}\bracks{-\root{x^{2} + y^{2}} < z < 0}\dd x\,\dd y\,\dd z
\\[5mm] & =
\int_{0}^{2\pi}\int_{-\infty}^{0}\int_{0}^{\infty}
\bracks{r^{2} + z^{2} < 6}\bracks{-r < z}r\,\dd r\,\dd z\,\dd\phi
\\[5mm] & =
2\pi\int_{0}^{\infty}\int_{0}^{\infty}
\bracks{r^{2} + z^{2} < 6}\bracks{r > z}r\,\dd r\,\dd z
\\[5mm] & =
2\pi\int_{0}^{\infty}\bracks{\verts{z} < \root{6}}\int_{0}^{\infty}
\bracks{z < r < \root{6 - z^{2}}}r\,\dd r\,\dd z
\\[5mm] & =
2\pi\int_{0}^{\root{6}}\bracks{z < \root{6 - z^{2}}}
\int_{z}^{\root{6 - z^{2}}}r\,\dd r\,\dd z
\\[5mm] & =
2\pi\int_{0}^{\root{6}}\bracks{z < \root{3}}
{\pars{6 - z^{2}} - z^{2} \over 2}\,\dd z
=
2\pi\int_{0}^{\root{3}}\pars{3 - z^{2}}\dd z = \bbx{4\root{3}\pi}
\end{align}


text:
Q: Nmap does not show all devices connected to my network I want to use xerosploit but when I scan my network, it just shows two devices

*

*My device

*My Router

Then I thought there was some problem in xerosploit, but when I scanned my network through nmap it also shows the same result. Why?
The command I used on nmap is nmap -sn ip addr/24. I even tried the Aggressive Scan option, but it still only showed these two hosts up.

A: Two things come to mind, and both of these could contribute to your problem:

*

*If you inserted your machine's entire IP address and added the /24, this is not a valid netmask for your use case. If you wanted to scan 192.168.1.1 through 192.168.1.254, the proper IP for nmap is 192.168.1.0/24. For a /24, take the first three octets of your computer's IP and set the last digit to zero. If you are on a more complicated network, use a subnet calculator to determine what your scan range should be.

*You may have devices on your network not responding to pings, which in the default mode of nmap, will cause them to report as down without any actual port scanning. To have it try anyways, use the option -Pn.

A: I encountered the same issue. At the end of the troobleshooting, I had an vmware worksation with an overlapped network configured in my computer :/ . You should easily find an overlapping network issue with an ipconfig /all (windows) or ip a (linux). Hope this help you.


text:
Q: Strange pair of type declarations Okay, so it may not be that strange, but I'm really new to Ada. In my job, I am translating legacy Ada to C, and have come across something that I haven't seen yet. I searched around, but couldn't really find it; here it is.
type Discrete_Names is ( ENUM_POS_4,  --label names in an enum
                         ENUM_POS_5,  --that evaluate to 4, 5, and 6
                         ENUM_POS_6); --respectively
type Discrete_Array_Type is Array (Discrete_Names) of Discrete.Does_Not_Matter

Side note—the Discrete.Does_Not_Matter just references another type in a different library.
It would be great if someone could just help me get my bearings and just figure out what is going on here.

A: Well, it is quite simple.  In Ada arrays can be indexed by any discrete type, that is, integers, characters or enumeration types (your case).  The line
type Discrete_Array_Type is Array (Discrete_Names) of Does_Not_Matter

declares Discrete_Array_Type as the type of an array that contains values of type Does_Not_Matter and it is indexed by values of type Discrete_Names.
If your doubt stems from the fact that ENUM_POS_4 has Pos equal to 4 -- so that it seems that the first index of the array is 4 and not 0 -- my suggestion is... forget about it.  The compiler will take care of that.  In Ada arrays can start from any index.  For example, if you say
type Array_Foo is array(Positive range <>) of Characters;
Bar : Array_Foo(10..15);

Bar will be just 6 entries long (not 16) and when you access Bar(12) the compiler -- behind the scenes -- will remove the initial offset "10" to "12" so that you will access the third memory location reserved to Bar. (Actually, I think that for the sake of efficiency it will add 12 to the address of Bar diminished by 10 times the integer sizes, but this is a detail...)
My personal experience is that in cases like this you should not consider the enumerative type like a "integer in disguise" (although it will be internally represented by an integer), but like a type of its own that can be used to index an array.  Let the compiler worry about the internal low-level details.


text:
Q: Call can throw, but it is not marked with 'try' and the error is not handled Hey community I've been troubleshooting this issue for a while now and haven't found a solution on the web that relates to my issue specifically.
I'm new to the swift language I'm assuming this problem seems to have something to do with converting NSString to a String.
the error reads
Cannot convert value of type 'NSString?' to expected argument type 'String?'
In regards to my
let file = PFFile(name: fileName, data: fileData!, contentType: fileType )

here is the entire function
func uploadMessage() {
    var fileData: NSData?
    var fileName: NSString?
    var fileType: NSString?

    if image != nil {
        let newImage = resizeImage(image!, width: view.window!.frame.size.width, height: view.window!.frame.size.height)
        fileData = UIImagePNGRepresentation(newImage)
        fileName = "image.png"
        fileType = "image"
    } else {
        fileData = NSData.dataWithContentsOfMappedFile(videoFilePath! as String) as? NSData
        fileName = "video.mov"
        fileType = "video"
    }

    let file = PFFile(name: fileName, data: fileData!, contentType: fileType )

    file.saveInBackgroundWithBlock { (success: Bool, error: NSError!) -> Void in
        if error == nil {
            let message = PFObject(className: "Messages")
            message.setObject(file, forKey: "file")
            message.setObject(fileType!, forKey: "fileType")
            message.setObject(self.recipients!, forKey: "recipientIds")
            message.setObject(PFUser.currentUser()!.objectId!, forKey: "senderId")
            message.setObject(PFUser.currentUser()!.username!, forKey: "senderName")
            message.saveInBackgroundWithBlock({ (success: Bool, error: NSError!) -> Void in
                if error == nil {
                    //worked!
                    self.reset()
                } else {
                    UIAlertView(title: "Error", message: "Try agian", delegate: nil, cancelButtonTitle: "OK").show()
                }
            })
        } else {
            UIAlertView(title: "Error", message: "Try agian", delegate: nil, cancelButtonTitle: "OK").show()
        }
    }

Thanks in advance community.

A: Well the error is pretty clear... Either make your fileName variable a string, (which since you're using Swift you should probably be doing anyways), or when you're about to set the file, convert the NSString into a String by let file = PFFile(name: fileName as String, data: fileData!, contentType: fileType)
Original answer still stands, but you'll have to do either one of the options like so:
do {
    let file = try PFFile(name: fileName as String, data: fileData!, contentType: fileType)
} catch (_) {
    //this is the default catch which is exhaustive and will catch all errors. here you can find the specific error if you want, or just use this as a way to know the file wasn't created and to let the user know
}


text:
Q: primefaces p:inputSwitch not work in dialog while use update the dialog I am doing a on-off with p:inputSwitch, it's in a dialog. When an ajax call inside a form happens in combination with an update on the inputSwitch, the inputSwitch behaves strange and always resets its state. Here is a simple reproducible example (without the need of a backing bean):
<h:form id="buttonForm">
    <p:commandButton value="button" update="switch" oncomplete="PF('switchDialog').show();" />
    <p:dialog widgetVar="switchDialog">
        <p:inputSwitch id="switch" />
    </p:dialog>
</h:form>

Interesting observations:

*

*When you remove the h:form the problem is gone

*When you remove the update parameter it works

*When the p:inputSwitch is outside of the p:dialog it also works

A: Sorry for this zombie post but i've found a solution that can help.
Add in your

<p:dialog widgetVar="switchDialog" dynamic="true">

Regards


text:
Q: .net framework 4.5.1 missing from Visual Studio 2012 Just did a fresh rebuild of my machine.
Opening a previous project running .Net 4.5.1, it says

"The C# project is targeting .NETFramework,Version=v4.5.1, which is
  not installed on this machine"

Installed 4.5.2, re-installed VS, re-installed IIS, .NET, and did aspnet_iisreg -i as well.
If I create a new project, 4.5.1 is not in the list of Target Frameworks.
4.5.2 is installed on the machine and shown in the add/remove programs list.

A: Once you have Visual Studio 2012 installed (and all applicable updates), you need to install the 4.5.1 Multi-Targeting Pack. Once you have it installed, you'll have 4.5.1 available.
Installing 4.5.2 does not include 4.5.1 for framework targeting. If you want both 4.5.1 and 4.5.2 available as Target Frameworks, you need to install both.


text:
Q: Serialization: Basic understanding and documentation
Within a stream, the first reference to any object results in
  the object being serialized or externalized and the assignment of a
  handle for that object. Subsequent references to that object are encoded as the handle. Using object handles preserves sharing and
  circular references that occur naturally in object graphs. Subsequent
  references to an object use only the handle allowing a very compact
  representation.
Except for serializable fields, primitive data is written to the
  stream in block-data records, with each record prefixed by a
  marker and an indication of the number of bytes in the record.

*

*The above is from the Oracle Docs for Serialization. I am reading into Serialization to get a better and in-depth understanding, can someone please help me decode the highlighted parts in simple English. (I am looking for an answer in the context of how the stream is generated, especially when it talk about how the primitive data is being stored in the buffer)

Serialization is useful when we want to:

*

*Persist the state beyond the lifecycle of the JVM - file/db

*Send data over to another jvm based application over a network - data exchange

Doc: https://docs.oracle.com/javase/6/docs/platform/serialization/spec/serial-arch.html

*I have been working with Spring/Hibernate, and in none of the applications, the models are defined as type Serializable. The main reason to use Serializable is the version control for future enhancement, but without Serializable Hibernate persists the data in the DB/but serialization to a file using ObjectOutputStream fails. Can someone help me understand this, why does Hibernate not require entities to be of the type Serializable?

A: Just my understanding
For #1 The stream of the object after serialization includes basically 5 parts:

*

*A header to claim this is a serialized file and the version of the serialization.

*The information of the class, like name, serialization id(serialVersionUID), number of fields etc.

*Description of the fields

*Information of parent class

*Value of the fields.

Check these codes from ObjectOutputStream:
if (obj instanceof String) {
    writeString((String) obj, unshared);
} else if (cl.isArray()) {
    writeArray(obj, desc, unshared);
} else if (obj instanceof Enum) {
    writeEnum((Enum<?>) obj, desc, unshared);
} else if (obj instanceof Serializable) {
    writeOrdinaryObject(obj, desc, unshared);
} else {
if (extendedDebugInfo) {
    throw new NotSerializableException(
    cl.getName() + "\n" + debugInfoStack.toString());
} else {
    throw new NotSerializableException(cl.getName());
}

For #2 I think hibernate/jpa just write them into database by queries, they do not need to serialize the object. You can implment the entity with Serializable if you need to transfer then cross JVMs or other usage (I think you better to have serialization in a web based application).


text:
Q: How do I put an interstitial ad every time the app is opened (kotlin) I want an interstitial ad to be loaded with admob every time my app is opened, how do I do it? i am working with kotlin

A: You should not place interstitial ads on app load, that would be a disallowed interstitial implementation:

Do not place interstitial ads on app load and when exiting apps as interstitials should only be placed in between pages of app content.


text:
Q: Loop each Items in c# using XElement I am facing some difficulty in swapping the id attribute in the list of Items in a C# XDocument. The id is a reference.
Input:
<Items>
    <Item base="book_bookref1_ref1">
        <Name>Test1</Name>
        <Ref>bookref1</Ref>
    </Item>
    <Item base="book_bookref1_ref2">
        <Name>Test2</Name>
        <Ref>bookref1</Ref>
    </Item>
    <Item base="book_bookref2_ref1">
        <Name>Test3</Name>
        <Ref>bookref2</Ref>
    </Item>
    <Item base="book_bookref2_ref2">
        <Name>Test4</Name>
        <Ref>bookref2</Ref>
    </Item>
</Items>

Expected Output:
<Items>
    <Item base="book_bookref1_ref1" id="book_bookref1_ref2">
        <Name>Test1</Name>
        <Ref>bookref1</Ref>
    </Item>
    <Item base="book_bookref1_ref2" id="book_bookref1_ref1">
        <Name>Test2</Name>
        <Ref>bookref1</Ref>
    </Item>
    <Item base="book_bookref2_ref1" id="book_bookref2_ref2">
        <Name>Test3</Name>
        <Ref>bookref2</Ref>
    </Item>
    <Item base="book_bookref2_ref2" id="bookref2_ref1">
        <Name>Test4</Name>
        <Ref>bookref2</Ref>
    </Item>
</Items>

There is a tag <Ref> where one part of value ex:bookref1 is a reference for Base attribute book_bookref1_ref1 for the 1st and 2nd Item.
I need to write the 2nd 'id' to the 1st Item and write the 1st id to the 2nd Item in the loop. Similarly for the 3rd and 4th Item. There can be many but it's like a combination (1 & 2, 3 & 4, 5 & 6, etc).
The problem here is there can be multiple Items and there is no relation in the Item to map the Id attribute.
The code I'm using is loading XMLDocument into XDocument getting the Items in LINQ.
Var doc = XDocument.Load(xml)
var ItemsList
foreach(var itm in ItemsList)
{
    // I'm stuck here. How do we get the id attribute value based on Ref tag?
}

Please let me know your suggestions.

A: Nothing in XML is impossible with a little LINQ (and MoreLinq, in this example):
var xdoc = XDocument.Parse(input);
foreach(var pair in xdoc.XPathSelectElements("Items/Item").Batch(2).ToArray())
{
    pair[0].SetAttributeValue(XName.Get("id"), pair[1].Attribute(XName.Get("base")).Value);
    pair[1].SetAttributeValue(XName.Get("id"), pair[0].Attribute(XName.Get("base")).Value);
}

This enumerates not each Item, not each Item pair (two elements in a batch). You only need to tweak this to decide what to do if an odd element remains at the end of the loop.
MoreLinq is for .Batch() extension method, but if you need, you can easily write it yourself.


text:
Q: Code from Opengl ES 1.0 tutorial not working (Java N-IDE) I'm using the Java N-IDE app on my android phone, and I'm trying to learn how to use OpenGL ES 1.0. I followed the instructions in two different tutorials, and my code still won't work. The compiled app draws a gray screen like it should, but it never draws the triangle.
Here's my code:
MainActivity.java
package com.example.dland;

import android.app.Activity;
import android.os.Bundle;
import android.opengl.GLSurfaceView;

import com.example.dland.R;

public class MainActivity extends Activity {

    private GLSurfaceView glview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        glview = new MyGLSurfaceView(this);

        setContentView(glview);

    }

}

MyGLSurfaceView.java
package com.example.dland;

import android.content.Context;
import android.opengl.GLSurfaceView;

import com.example.dland.R;

public class MyGLSurfaceView extends GLSurfaceView {

    private final MyGLRenderer renderer;

    public MyGLSurfaceView(Context context) {

        super(context);

        setEGLContextClientVersion(2);

        renderer = new MyGLRenderer();

        setRenderer(renderer);

    }

}

MyGLRenderer.java
package com.example.dland;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

import android.opengl.GLSurfaceView;

import java.nio.FloatBuffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import com.example.dland.R;

public class MyGLRenderer implements GLSurfaceView.Renderer {

    private FloatBuffer triangleVB;

    public void onSurfaceCreated(GL10 gl, EGLConfig config) {

        // Set the background frame color
        gl.glClearColor(0.5f, 0.5f, 0.5f, 1.0f);

        initShapes();

        // Enable use of vertex arrays
        gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);

    }

    public void onDrawFrame(GL10 gl) {

        // Redraw background color
        gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);

        // Draw the triangle
        gl.glColor4f(0.63671875f, 0.76953125f, 0.22265625f, 0.0f);
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, triangleVB);
        gl.glDrawArrays(GL10.GL_TRIANGLES, 0, 3);

    }

    public void onSurfaceChanged(GL10 gl, int width, int height) {
        gl.glViewport(0, 0, width, height);
    }

    private void initShapes() {

        float triangleCoords[] = {
            // X, Y, Z
            -0.5f, -0.25f, 0,
             0.5f, -0.25f, 0,
             0.0f,  0.559016994f, 0
        };

        // initialize vertex Buffer for triangle
        ByteBuffer vbb = ByteBuffer.allocateDirect(
                // (# of coordinate values * 4 bytes per float)
                triangleCoords.length * 4);
        vbb.order(ByteOrder.nativeOrder());// use the device hardware's native byte order
        triangleVB = vbb.asFloatBuffer();  // create a floating point buffer from the ByteBuffer
        triangleVB.put(triangleCoords);    // add the coordinates to the FloatBuffer
        triangleVB.position(0);     // set the buffer to read the first coordinate

    }

}


text:
Q: On USB drive, files disappear after being successfully written I just received 4,000 4GB flash drives for my company. When we try to access video or PDF files that we've written to a folder the folder comes up empty.
For instance, on every drive we load a PDF and a folder with videos about our company. After copying over all the files, which says is successful, the folder is somehow empty. I don't see them with showing hidden files or through the command prompt or anything.
We have tried formatting them with exFat, NTFS and of course FAT32. We've tried to load the files on there manually on a computer or clone from a different flash drive on the duplicator. We've tried not putting the videos in a folder, but that didn't make a difference.
It seems that small files will sometimes stay but nothing very large will. Large files will disappear.
Windows 7

A: I tested the flash drive with a program called h2test2w.exe. The flash drive was mislabeled in the system as 4GB when it actually only had a 215MB capacity. I don't mean just mislabeled like what was printed on the outside -- I mean system properties, other drive analyzers, you name it.
Apparently the displayed size of the drive that every program uses is not based on the ACTUAL capacity of the chip, but on a bit of "header" information on the USB flash drive that someone manually sets with factory tools (see How do I make a USB partition so no one can erase it -- the last image in my answer there shows a Capacity Setting tab).
As long as we never put more than 215MB on the drive it acts fine, but any more than that and it seems to do a revolving overwrite of the first bits of the drive. Like this, if there were only 4 bits:
bit 1 value: 0
bit 2 value: 0
bit 3 value: 0
bit 4 value: 0

Now I will write a file with 6 bits to it: 000011
bit 1 value: 0
bit 2 value: 0
bit 3 value: 0
bit 4 value: 0
bit 1 value: 1
bit 2 value: 1

Which leaves me with:
bit 1 value: 1
bit 2 value: 1
bit 3 value: 0
bit 4 value: 0

So if the "header" had been correct, it wouldn't have written to the drive since the drive was too small. Instead, now the first two bits have been overwritten and the file is corrupt or not even there.
In other words, we got scammed.


text:
Q: Generalization of a determinant with Lucas numbers and totient functions Let $\gcd(a,b)$ denote the greatest common divisor function. H. J. S. Smith proved that
$$\det\left[\gcd(i,j)\right]_{i,j=1}^n=\prod_{k=1}^n\varphi(k),$$
where $\varphi(k)$ denotes Euler's totient function. More generally, it is known that if $\ell\in\Bbb{P}$ then
$$\det\left[\gcd(i,j)^{\ell}\right]_{i,j=1}^n=\prod_{k=1}^n\varphi_{\ell}(k),$$
where $\varphi_{\ell}(k):=\sum_{d\vert k}d^{\ell}\mu\left(\frac{k}d\right)$ denotes Jordan's totient function and $\mu$ is the Mobius function.
Let $L_n(s,t)=s\cdot L_{n-1}(s,t)+t\cdot L_{n-2}(s,t)$, or simply $L_n$, be the Lucas polynomials with the convention that $L_0=0, L_1=1$.
Experimental results suggest the below computation which I like to state our by introducing a "generalized" Jordan totient function.

Question: Let $p$ stand for a prime number. If $n, s, t, \ell\in\Bbb{N}, s\neq1$ and $\gcd(s,t)=1$, then is the following true?
  $$\det\left[\gcd(L_i,L_j)^{\ell}\right]_{i,j=1}^n=\prod_{k=1}^n\sum_{d\vert k}L_d^{\ell}\cdot \mu\left(\frac{k}d\right)
=(L_n!)^{\ell}\prod_{k=1}^n\prod_{p\vert k}\left(1-\frac1{p^{\ell}}\right).$$


text:
Q: OpenLayers caching I have my own data, and I want to create cache images to be used with OpenLayers, I want the format to be WWJ format and 256x256x size, I don't want to create the images, I just want a program that loops though the layer and request all images from my server.

A: Do you use mapserver or geoserver? If you do, you can think about this one: TileCache. It will automatically  create the tiles, for your layer.
and here is the Tutorial of TileCache

A: I would use the Layer.TileCache object, documented here:
http://dev.openlayers.org/apidocs/files/OpenLayers/Layer/TileCache-js.html
That is used to retrieve your own prerendered tiles, and you can specify file extension, size and url.


text:
Q: Where does adb put uninstalled apps on the device? I have adb running and device is connected to my System in debugging mode
I want to find uninstalled apps using command in adb shell.What command can i use?

A: just type on your terminal or command prompt
adb uninstall <package name of application>

i hope it will work for you.


text:
Q: solve linear system using gaussian elimination I want to solve a linear system of the form Ax=b.
First of all I create the augmented matrix (A|b).
I apply some elementary row operations and i obtain the REF form of A.
After than, I do not know what variable to call L, say.
For example,
A
  $$
        \begin{bmatrix}
        0 & 1 & 1 \\
        1 & 1 & 1 \\
        3 & 1 & 1 \\
        \end{bmatrix}
$$
and the matrix b
    $$
        \begin{bmatrix}
        0  \\
        0  \\
        0  \\
        \end{bmatrix}
$$
after the the EROs I obtain the matrix
$$
        \begin{bmatrix}
        1 & 1 & 1 \\
        0 & 1 & 1 \\
        0 & 0 & 0 \\
        \end{bmatrix}
$$
I then create two equations.
(a) $a+b+c=0$
(b) $b+c=0$
I want to Write solutions in the general form x = v+L_1w_1 +...+L_kw_k, for vectors v and
w_1...w_k and arbitrary scalars L_1...L_k
One idea is to let $c=L$.  But I do not understand why.

A: Let $A = \begin{pmatrix} 0 & 1 & 1 \\ 1 & 1 & 1 \\ 3 & 1 & 1\end{pmatrix}$ and $b = \begin{pmatrix} 0 \\ 0 \\ 0 \end{pmatrix}$.
Solving $Ax = b$ using Gaussian elimination, we get:
$$\begin{align*}
\left(\begin{array}{ccc|c}
0 & 1 & 1 & 0\\
1 & 1 & 1 & 0\\
3 & 1 & 1 &0 \\
\end{array}\right) &\to \left(\begin{array}{ccc|c}
0 & 1 & 1 & 0\\
1 & 1 & 1 & 0\\
0 & -2 & -2 &0 \\
\end{array}\right) \tag{$\textrm{row3} - 3\times \textrm{row2}$}\\
 &\to \left(\begin{array}{ccc|c}
0 & 1 & 1 & 0\\
1 & 0 & 0 & 0\\
0 & -2 & -2 & 0 \\
\end{array}\right) \tag{$\textrm{row2} - \textrm{row1}$} \\
 &\to \left(\begin{array}{ccc|c}
0 & 1 & 1 & 0\\
1 & 0 & 0 & 0\\
0 & 0 & 0 & 0 \\
\end{array}\right) \tag{$\textrm{row3} + 2\times \textrm{row1}$}
\end{align*}$$
This means that our null space has dimension 1. That means that there is a vector that forms a basis for this null space. Let's call it $v$. Since it is a basis for the null space, then $Av = 0$, and any scalar multiple of $v$ will also lead to zero: $A (\alpha v) = 0$ for all values of $\alpha$.
From the above, we get $x = 0$ and $y = -z$. This means that our basis vector will look like: $\begin{pmatrix} 0 \\ y \\ -y\end{pmatrix}$. Since our basis vector times any scalar will still be in the null space, it doesn't matter what value we pick for $y$. Let's just pick $y= 1$. Then, our basis vector is $\begin{pmatrix} 0 \\ 1 \\ -1\end{pmatrix}$.
Let's check to see if that's right:
$$\begin{pmatrix} 0 & 1 & 1 \\ 1 & 1 & 1 \\ 3 & 1 & 1\end{pmatrix}\begin{pmatrix} 0 \\ 1 \\ -1\end{pmatrix} = \begin{pmatrix} 0+1\cdot 1 + 1\cdot (-1) \\ 1\cdot 0 + 1 \cdot 1 + 1\cdot (-1) \\ 3 \cdot 0 + 1\cdot 1 + 1 \cdot (-1) \end{pmatrix} = \begin{pmatrix} 0 \\ 0\\ 0\end{pmatrix}.$$
You can check to see that any vector of the form $\begin{pmatrix} 0 \\ a \\ -a\end{pmatrix}$ will be sent to $0$ by $A$.


text:
Q: uib-typeahead is not working I have implement uib-typeahead for tons of time but i am clueless why it is not working
i want to get item name in the uib-typeahead
my code here is like this
$scope.suggestTestbySpeciality = function( texts , sp_id) {
        var spe_id = sp_id.speciality_id;
$http.post('/youclikc/data/searchTest?speciality_id='+spe_id+'&searchtext='+texts)
                        .then(function(response) {

                        return  response.data.testrecords.rows;

                                                 });
                             };

Console.log for function is like this

Angular is like :
<div class="col-md-3 col-sm-3 col-xs-12 form-group has-feedback">
<input  type="text"  uib-typeahead="itemz.test_name as itemz.test_name for itemz in suggestTestbySpeciality($viewValue, data1.template_name) | limitTo:8"
 ng-model="templateVo.test_name" placeholder ="Template Test Name"  class="form-control" ></input>
                        </div>


text:
Q: Django celery trigger manage.py cmd @periodic_task i want to run a manage.py cmd from celery as a periodic task every x Minutes but every time i try to accomplish that as show below i get the following error:

[2019-01-17 01:36:00,006: INFO/MainProcess] Received task: Delete
  unused media file(s)[3dd2b93b-e32a-4736-8b24-028b9ad8da35]
  [2019-01-17 01:36:00,007: WARNING/ForkPoolWorker-3] Scanning for
  unused media files [2019-01-17 01:36:00,008: WARNING/ForkPoolWorker-3]
  Unknown command: 'cleanup_unused_media --noinput --remove-empty-dirs'
  [2019-01-17 01:36:00,008: INFO/ForkPoolWorker-3] Task Delete unused
  media file(s)[3dd2b93b-e32a-4736-8b24-028b9ad8da35] succeeded in
  0.0008139749998008483s: None

tasks.py
from celery import Celery
from celery.schedules import crontab
from celery.task import periodic_task
from celery.utils.log import get_task_logger
import requests
from django.core import management

logger = get_task_logger(__name__)
app = Celery('tasks', broker='redis://127.0.0.1')

...
@periodic_task(run_every=(crontab(minute='*/90')), name="Delete unused media file(s)", ignore_result=True)
def delete_unused_media():
    try:
        print("Scanning for unused media files")
        management.call_command('cleanup_unused_media --noinput --remove-empty-dirs')
        return "success, old media files have been deleted"
    except Exception as e:
        print(e)

that management cmd comes from the following project:
https://github.com/akolpakov/django-unused-media
is my management call simply wrong or whats the deal?
thanks in advance
UPDATE (Celery Config):
settings.py
INSTALLED_APPS = [
...
'celery',
'django_unused_media',
...
# Celery Settings:
BROKER_URL = 'redis://127.0.0.1:6379'
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TIMEZONE = 'UTC'
...
CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": [
            "redis://127.0.0.1:6379/0",
            #"redis://127.0.0.1:6379/1",
        ],
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "SOCKET_CONNECT_TIMEOUT": 15,  # in seconds
            "SOCKET_TIMEOUT": 15,  # in seconds
            "COMPRESSOR": "django_redis.compressors.zlib.ZlibCompressor",
            "CONNECTION_POOL_KWARGS": {"max_connections": 1000, "retry_on_timeout": True}
        }
    }
}

celery.py
from __future__ import absolute_import, unicode_literals
from celery import Celery
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'MyProject.settings')

app = Celery('MyProject')

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings', namespace='CELERY')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

_init__.py
from __future__ import absolute_import, unicode_literals

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ('celery_app')

e.g. This task is working fine:
@periodic_task(run_every=(crontab(minute='*/1')), name="Get exchange rate(s)", ignore_result=True)
def get_exchange_rate():
    api_url = "https://api.coinmarketcap.com/v1/ticker/?limit=1"
    try:
        exchange_rate = requests.get(api_url).json()
        logger.info("BTC Exchange rate updated successfully.")
    except Exception as e:
        print(e)
        exchange_rate = dict()
    return exchange_rate

A: The issue is the way you're calling call_command. call_command takes the name of the command as its first argument, followed by the arguments passed positionally. You're passing the whole lot as a single string. Try changing it to:
management.call_command('cleanup_unused_media', '--noinput', '--remove-empty-dirs')

A: For anyone using Django 1.7+, it seems that simply import the settings module is not enough.
i got it working like this
from celery import Celery
from celery.schedules import crontab
from celery.task import periodic_task
from celery.utils.log import get_task_logger
import requests, os, django
from django.core import management

logger = get_task_logger(__name__)
app = Celery('tasks', broker='redis://127.0.0.1')

@periodic_task(run_every=(crontab(minute='*/1')), name="Delete unused media file(s)", ignore_result=True)
def delete_unused_media():
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyProject.settings")
    django.setup()
    try:
        print("Scanning for unused media files")
        management.call_command('cleanup_unused_media', '--noinput', '--remove-empty-dirs')
        return "success, old media files have been deleted"
    except Exception as e:
        print(e)


text:
Q: turn array of object into keys failed I have this structure
  const raw = [{
      date: '2018-8-1',
      devices: [{
        id: 1,
        name: 'iphone',
        device_age: 12
      }, {
        id: 2,
        name: 'samsung',
        device_age: 10
      }]
    }, {
      date: '2018-8-2',
      devices: [{
        id: 1,
        name: 'iphone',
        device_age: 5
      }, {
        id: 2,
        name: 'samsung',
        device_age: 9
      }]
    }]

I want to transform above sturcture into this
[{date: '2018-8-1', iphone: 12, samsung: 10}, {date: '2018-8-2', iphone:5, samsung:9}]

What's wrong with my attempt below?
let result = raw.map((obj, i) => {
   return {
       date: obj.date,
       [obj.devices.map(innerObj => innerObj.name)]: 'test'
   }
})

https://jsfiddle.net/q74x8106/
or I shouldn't use map for inner loop? I'm lost.

A: You could map the outer array and build a new object with Object.assign and spread syntax ....

const raw = [{ date: '2018-8-1', devices: [{ id: 1, name: 'iphone', device_age: 12 }, { id: 2, name: 'samsung', device_age: 10 }] }, { date: '2018-8-2', devices: [{ id: 1, name: 'iphone', device_age: 5 }, { id: 2, name: 'samsung', device_age: 9 }] }],
    result = raw.map(({ date, devices }) =>
        Object.assign({ date }, ...devices.map(d => ({ [d.name]: d.device_age }))));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: let result = raw.map((obj, i) => {
    let newObj = {};
    obj.devices.forEach(obj => {
        newObj[obj.name] = obj.device_age

    });
    return {
        date: obj.date,
        ...newObj
    }
})


text:
Q: page redirecting to itself <a href="<?php $this->url(array('controller' => 'page', 'action' => 'page-detail', 'page_id' => $show_today['id']));?>"><?php echo $show_today['id']; ?>

Am i syntactically wrong in the above statement. Because the link does not take me anywhere but the same page I am in.
the controller,action and the values are all correct. But the link does not go to the respective page.

A: maybe an echo is missing?
//             here
<a href="<?php echo $this->url(array('controller' => 'page', 'action' => 'page-detail', 'page_id' => $show_today['id']));?>"><?php echo $show_today['id']; ?>


text:
Q: Whitenoise and django-compressor cause 404 for compressed files Trying to deploy a Django application to Heroku using whitenoise and django-compressor.
Deploying it to production with DEBUG = False and COMPRESS_ENABLED = True, all my static assets can be accessed without a problem. However, all the compressed files return a 404, e.g.:

http://*.herokuapp.com/static/CACHE/css/fbfaa35dc638.css Failed to
  load resource: the server responded with a status of 404 (NOT FOUND)

Either enabling DEBUG or disabling COMPRESS_ENABLED fixes the problem, but of course is not what I want.
I'm also setting STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage', but changing this doesn't help.
Some settings (note I have a settings directory with e.g. base.py, local.py, etc. that's why I need an extra ../ on the paths):
STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR, '../staticfiles')

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, '../static'),
)

STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
    'compressor.finders.CompressorFinder',
)

In my base template:
{% compress css %}
<link rel="stylesheet" href="{% static 'css/app.css' %}">
{% block css %}{% endblock %}
{% endcompress %}

[...]

{% compress js %}
<script src="{% static 'js/main.js' %}"></script>
{% block js %}{% endblock js %}
{% endcompress %}

Again, moving them out of the compress blocks fixes the issue. Just the compressed files can't be found.
Any ideas?
EDIT
I forgot to mention one setting I added as per the deployment checklist, namely this:
https://docs.djangoproject.com/en/1.8/ref/templates/api/#django.template.loaders.cached.Loader
TEMPLATES[0]['OPTIONS']['loaders'] = [
    (
        'django.template.loaders.cached.Loader', [
            'django.template.loaders.filesystem.Loader',
            'django.template.loaders.app_directories.Loader',
        ]
    ),
]

Removing this setting makes the page work again. HOWEVER, the JS and CSS files are not compressed... What's going on?
Edit 2
This is not a duplicate of Django staticfiles not found on Heroku (with whitenoise) :

*

*The problem in my question arises from django-compressor, not whitenoise alone

*They're not getting 404s, but rather 500s.

*Their issue was that they forgot to run collectstatic... Which is not the case here.

A: This seems to be a known problem.
According to Squebe - "Compressor's Online mode doesn't work on Heroku because Whitenoise only checks the static folder when the app is loaded (see my comment on issue #680). To use compressor in production I think you need to use it in Offline mode and run python manage.py compress before the app loads using Heroku's post compile hook."
No way to get this to work on Heroku #486


text:
Q: flutter firebase google sign out not working I'm trying to implement google sign in/ sign out, but my sign out's not working. I get an error signOut() was called on null. When I print out user after the user signs in, I do get all the proper information, but when I print out in my signout function, it says it's null. Custom firebase user does work. Here's my auth.dart file:
import 'dart:async';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';

abstract class BaseAuth {
  Future<String> signIn(String email, String password);

  Future<String> signUp(String email, String password);

  Future<FirebaseUser> getCurrentUser();

  Future<void> sendEmailVerification();

  Future<void> signOut();

  Future<bool> isEmailVerified();

  Future<String> signInWithGoogle();
}

class Auth implements BaseAuth {
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  final GoogleSignIn googleSignIn = GoogleSignIn();
  FirebaseUser user;

  Future<String> signIn(String email, String password) async {

    user = (await _firebaseAuth.signInWithEmailAndPassword(email: email, password: password)).user;
    return user.email;
  }

  Future<String> signUp(String email, String password) async {
    FirebaseUser user = (await _firebaseAuth.createUserWithEmailAndPassword(
        email: email, password: password)).user;
    return user.uid;
  }

  Future<FirebaseUser> getCurrentUser() async {
    user = await _firebaseAuth.currentUser();
    return user;
  }
  signOut() async {
    //print("signed in user: ${authService.user}");
    await _firebaseAuth.signOut();
  }

  Future<void> sendEmailVerification() async {
    FirebaseUser user = await _firebaseAuth.currentUser();
    user.sendEmailVerification();
  }

  Future<bool> isEmailVerified() async {
    FirebaseUser user = await _firebaseAuth.currentUser();
    return user.isEmailVerified;
  }

  Future<String> signInWithGoogle() async {
    final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
    final GoogleSignInAuthentication googleSignInAuthentication =
    await googleSignInAccount.authentication;

    final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleSignInAuthentication.accessToken,
      idToken: googleSignInAuthentication.idToken,
    );

   user = (await _firebaseAuth.signInWithCredential(credential)).user;

    assert(!user.isAnonymous);
    assert(await user.getIdToken() != null);

    final FirebaseUser currentUser = await _firebaseAuth.currentUser();
    assert(user.uid == currentUser.uid);
    return 'signInWithGoogle succeeded: $user';
  }

}

Something else strange is if I boot up the app and am already logged in (as google), i hit signout and it appears to work. Nothing in my console, but it goes back to login screen. Then if I log back in as google and signout, error starts happening. Another weird thing is if I happened to already be logged in and I get it to log out after one click, without changing anything if I restart my app in android studio it takes me back to the screen where I'm supposedly already logged in. This is only happening on Google Sign Out (not firebase log out).
Any idea what I might be doing wrong? Thanks
pubspec.yaml
dependencies:
  firebase_auth: ^0.14.0+5

  firebase_database: ^3.0.7
  google_sign_in: ^4.0.7
  firebase_storage:
  image_picker:
  cloud_firestore:
  shared_preferences:
  fluttertoast:
  cached_network_image:
  intl:

one page where I use it: (I have many, but implemented similar to this and it doesn't work in any of my pages)
import 'package:flutter/material.dart';
import 'package:pet_helper/chat.dart';
import 'package:pet_helper/lost_and_found.dart';
import 'package:pet_helper/pet_adoption.dart';
import 'authentication.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key, this.auth, this.userId, this.onSignedOut})
      : super(key: key);

  final BaseAuth auth;
  final VoidCallback onSignedOut;
  final String userId;

  @override
  State<StatefulWidget> createState() => new _HomePageState();
}

class _HomePageState extends State<HomePage> {

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  int _currentIndex = 0;

  @override
  void initState() {
    super.initState();
  }
  final List<Widget> _children = [
    new LostAndFoundPage(),
    new PetAdoptionPage(),
    new ChatPage(),
  ];
  _signOut() async {
    try {
      await widget.auth.signOut();
      widget.onSignedOut();
    } catch (e) {

      print(e);
    }
  }

  onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          automaticallyImplyLeading:false,
          title: new Text('Pet Helper'),
          actions: <Widget>[
            new FlatButton(
                child: new Text('Logout',
                    style: new TextStyle(fontSize: 17.0, color: Colors.white)),
                onPressed: _signOut)
          ],
        ),
        body: _children[_currentIndex], // new
        bottomNavigationBar: BottomNavigationBar(
          onTap: onTabTapped, // new
          currentIndex: _currentIndex, // new
          items: [
            new BottomNavigationBarItem(
              icon: Icon(Icons.home),
              title: Text('Lost & Found'),
            ),
            new BottomNavigationBarItem(
              icon: Icon(Icons.pets),
              title: Text('Pet Adoption'),
            ),
            new BottomNavigationBarItem(
                icon: Icon(Icons.person), title: Text('Chat'))
          ],
        ));
  }
}

and for completion, here's my login page:

import 'package:flutter/material.dart';
import 'package:pet_helper/home_page.dart';
import 'authentication.dart';

class LoginSignUpPage extends StatefulWidget {
  LoginSignUpPage({this.auth, this.onSignedIn});

  final BaseAuth auth;
  final VoidCallback onSignedIn;

  @override
  State<StatefulWidget> createState() => new _LoginSignUpPageState();
}

enum FormMode { LOGIN, SIGNUP }
class _LoginSignUpPageState extends State<LoginSignUpPage> {
  final _formKey = new GlobalKey<FormState>();
  String _email;
  String _password;
  String _errorMessage;

  // Initial form is login form
  FormMode _formMode = FormMode.LOGIN;
  bool _isIos;
  bool _isLoading;

  // Check if form is valid before perform login or signup
  bool _validateAndSave() {
    final form = _formKey.currentState;
    if (form.validate()) {
      form.save();
      return true;
    }
    return false;
  }

  // Perform login or signup
  void _validateAndSubmit() async {
    setState(() {
      _errorMessage = "";
      _isLoading = true;
    });
    if (_validateAndSave()) {
      String userId = "";
      try {
        if (_formMode == FormMode.LOGIN) {
          userId = await widget.auth.signIn(_email, _password);
          print('Signed in: $userId');
        } else {
          userId = await widget.auth.signUp(_email, _password);
          widget.auth.sendEmailVerification();
          _showVerifyEmailSentDialog();
          print('Signed up user: $userId');
        }
        setState(() {
          _isLoading = false;
        });

        if (userId.length > 0 && userId != null && _formMode == FormMode.LOGIN) {
          widget.onSignedIn();
        }

      } catch (e) {
        print('Error: $e');
        setState(() {
          _isLoading = false;
          if (_isIos) {
            _errorMessage = e.details;
          } else
            _errorMessage = 'Incorrect user or password';
        });
      }
    }
  }

  @override
  void initState() {
    _errorMessage = "";
    _isLoading = false;
    super.initState();
  }

  void _changeFormToSignUp() {
    _formKey.currentState.reset();
    _errorMessage = "";
    setState(() {
      _formMode = FormMode.SIGNUP;
    });
  }

  void _changeFormToLogin() {
    _formKey.currentState.reset();
    _errorMessage = "";
    setState(() {
      _formMode = FormMode.LOGIN;
    });
  }

  @override
  Widget build(BuildContext context) {
    _isIos = Theme.of(context).platform == TargetPlatform.iOS;
    return new Scaffold(
        appBar: new AppBar(
          title: new Text('Pet Helper'),
        ),
        body: Stack(
          children: <Widget>[
            _showBody(),
            _showCircularProgress(),
          ],
        ));
  }

  Widget _showCircularProgress(){
    if (_isLoading) {
      return Center(child: CircularProgressIndicator());
    } return Container(height: 0.0, width: 0.0,);

  }

  void _showVerifyEmailSentDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        // return object of type Dialog
        return AlertDialog(
          title: new Text("Verify your account"),
          content: new Text("Link to verify account has been sent to your email"),
          actions: <Widget>[
            new FlatButton(
              child: new Text("Dismiss"),
              onPressed: () {
                _changeFormToLogin();
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  Widget _showBody(){
    return new Container(
        padding: EdgeInsets.all(16.0),
        child: new Form(
          key: _formKey,
          child: new ListView(
            shrinkWrap: true,
            children: <Widget>[
              _showLogo(),
              _showEmailInput(),
              _showPasswordInput(),
              _showErrorMessage(),
              _showPrimaryButton(),
              _showSecondaryButton(),
              _googleSignInButton(),

            ],
          ),
        ));
  }

  Widget _showErrorMessage() {
    if (_errorMessage.length > 0 && _errorMessage != null) {
      return new Text(
        _errorMessage,
        style: TextStyle(
            fontSize: 13.0,
            color: Colors.red,
            height: 1.0,
            fontWeight: FontWeight.w300),
      );
    } else {
      return new Container(
        height: 0.0,
      );
    }
  }

  Widget _showLogo() {
    return new Hero(
      tag: 'hero',
      child: Padding(
        padding: EdgeInsets.fromLTRB(0.0, 30.0, 0.0, 0.0),
        child: CircleAvatar(
          backgroundColor: Colors.transparent,
          radius: 120.0,
          child: Image.asset('assets/babies.png'),
        ),
      ),
    );
  }

  Widget _showEmailInput() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(0.0, 25.0, 0.0, 0.0),
      child: new TextFormField(
        maxLines: 1,
        keyboardType: TextInputType.emailAddress,
        autofocus: false,
        decoration: new InputDecoration(
            hintText: 'Email',
            icon: new Icon(
              Icons.mail,
              color: Colors.grey,
            )),
        validator: (String value) {
        if (value.isEmpty) {
          _isLoading = false;
          return 'Email can\'t be empty';
        }
        else{
          return null;
        }
      },
        onSaved: (value) => _email = value.trim(),
      ),
    );
  }

  Widget _showPasswordInput() {
    return Padding(
      padding: const EdgeInsets.fromLTRB(0.0, 15.0, 0.0, 0.0),
      child: new TextFormField(
        maxLines: 1,
        obscureText: true,
        autofocus: false,
        decoration: new InputDecoration(
            hintText: 'Password',
            icon: new Icon(
              Icons.lock,
              color: Colors.grey,
            )),
        validator: (String value) {
          if (value.isEmpty) {
            _isLoading = false;
            return 'Password can\'t be empty';
          }
          else{
            return null;
          }
        },
        onSaved: (value) => _password = value.trim(),
      ),
    );
  }

  Widget _showSecondaryButton() {
    return new FlatButton(
      child: _formMode == FormMode.LOGIN
          ? new Text('Create an account',
          style: new TextStyle(fontSize: 18.0, fontWeight: FontWeight.w300))
          : new Text('Have an account? Sign in',
          style:
          new TextStyle(fontSize: 18.0, fontWeight: FontWeight.w300)),
      onPressed: _formMode == FormMode.LOGIN
          ? _changeFormToSignUp
          : _changeFormToLogin,
    );
  }

  Widget _showPrimaryButton() {
    return new Padding(
        padding: EdgeInsets.fromLTRB(0.0, 35.0, 0.0, 0.0),
        child: SizedBox(
          height: 40.0,
          child: new RaisedButton(
            elevation: 5.0,
            shape: new RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0)),
            color: Colors.blue,
            child: _formMode == FormMode.LOGIN
                ? new Text('Login',
                style: new TextStyle(fontSize: 20.0, color: Colors.white))
                : new Text('Create account',
                style: new TextStyle(fontSize: 20.0, color: Colors.white)),
            onPressed: _validateAndSubmit,
          ),
        ));
  }

void submitGoogleLogin() async{
  setState(() {
    _errorMessage = "";
    _isLoading = true;
  });
  String userId = "";
  userId = await widget.auth.signInWithGoogle().whenComplete(() {
    widget.onSignedIn();
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) {
          return new HomePage();
        },
      ),
    );
  });
  print('Signed in: $userId');
}

  Widget _googleSignInButton() {
    return OutlineButton(
      splashColor: Colors.grey,
      onPressed: submitGoogleLogin,
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(40)),
      highlightElevation: 0,
      borderSide: BorderSide(color: Colors.grey),
      child: Padding(
        padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image(image: AssetImage("assets/google_logo.png"), height: 30.0),
            Padding(
              padding: const EdgeInsets.only(left: 10),
              child: Text(
                'Sign in with Google',
                style: TextStyle(
                  fontSize: 15,
                  color: Colors.grey,
                ),
              ),
            )
          ],
        ),
      ),
    );
  }
}

Oh and root page changes the state of the user:
import 'package:flutter/material.dart';
import 'login_signup_page.dart';
import 'authentication.dart';
import 'home_page.dart';

class RootPage extends StatefulWidget {
  RootPage({this.auth});

  final BaseAuth auth;

  @override
  State<StatefulWidget> createState() => new _RootPageState();
}

enum AuthStatus {
  NOT_DETERMINED,
  NOT_LOGGED_IN,
  LOGGED_IN,
}

class _RootPageState extends State<RootPage> {
  AuthStatus authStatus = AuthStatus.NOT_DETERMINED;
  String _userId = "";

  @override
  void initState() {
    super.initState();
    widget.auth.getCurrentUser().then((user) {
      setState(() {
        if (user != null) {
          _userId = user?.uid;
        }
        authStatus =
        user?.uid == null ? AuthStatus.NOT_LOGGED_IN : AuthStatus.LOGGED_IN;
      });
    });
  }

  void _onLoggedIn() {
    widget.auth.getCurrentUser().then((user){
      setState(() {
        _userId = user.uid.toString();
      });
    });
    setState(() {
      authStatus = AuthStatus.LOGGED_IN;

    });
  }

  void _onSignedOut() {
    setState(() {
      authStatus = AuthStatus.NOT_LOGGED_IN;
      _userId = "";
    });
  }

  Widget _buildWaitingScreen() {
    return Scaffold(
      body: Container(
        alignment: Alignment.center,
        child: CircularProgressIndicator(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    switch (authStatus) {
      case AuthStatus.NOT_DETERMINED:
        return _buildWaitingScreen();
        break;
      case AuthStatus.NOT_LOGGED_IN:
        return new LoginSignUpPage(
          auth: widget.auth,
          onSignedIn: _onLoggedIn,
        );
        break;
      case AuthStatus.LOGGED_IN:
        if (_userId.length > 0 && _userId != null) {
          return new HomePage(
            userId: _userId,
            auth: widget.auth,
            onSignedOut: _onSignedOut,
          );
        } else return _buildWaitingScreen();
        break;
      default:
        return _buildWaitingScreen();
    }
  }
}

initializing root page
Main.dart
void main() async{
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
        title: 'Pet Helper',
        debugShowCheckedModeBanner: false,
        theme: new ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: new RootPage(auth: new Auth()));
  }
}

A: abstract class BaseAuth {
  Future<String> signIn(String email, String password);

  Future<String> signUp(String email, String password);

  Future<FirebaseUser> getCurrentUser();

  Future<void> sendEmailVerification();

  Future<void> signOut();

  Future<bool> isEmailVerified();

  Future<String> signInWithGoogle();

  void signOutGoogle();
}

class Auth implements BaseAuth {
  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;
  final GoogleSignIn googleSignIn = GoogleSignIn();
  FirebaseUser user;

  Future<String> signIn(String email, String password) async {

    user = (await _firebaseAuth.signInWithEmailAndPassword(email: email, password: password)).user;
    return user.email;
  }

  Future<String> signUp(String email, String password) async {
    FirebaseUser user = (await _firebaseAuth.createUserWithEmailAndPassword(
        email: email, password: password)).user;
    return user.uid;
  }

  Future<FirebaseUser> getCurrentUser() async {
    user = await _firebaseAuth.currentUser();
    return user;
  }
  signOut() async {
    print("signed in user: $user");
    await _firebaseAuth.signOut();
  }

  Future<void> sendEmailVerification() async {
    FirebaseUser user = await _firebaseAuth.currentUser();
    user.sendEmailVerification();
  }

  Future<bool> isEmailVerified() async {
    FirebaseUser user = await _firebaseAuth.currentUser();
    return user.isEmailVerified;
  }

  Future<String> signInWithGoogle() async {
    final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
    final GoogleSignInAuthentication googleSignInAuthentication =
    await googleSignInAccount.authentication;

    final AuthCredential credential = GoogleAuthProvider.getCredential(
      accessToken: googleSignInAuthentication.accessToken,
      idToken: googleSignInAuthentication.idToken,
    );

   user = (await _firebaseAuth.signInWithCredential(credential)).user;

    assert(!user.isAnonymous);
    assert(await user.getIdToken() != null);

    final FirebaseUser currentUser = await _firebaseAuth.currentUser();
    assert(user.uid == currentUser.uid);
    return 'signInWithGoogle succeeded: $user';
  }
}

final Auth authService = Auth(); // add this to the bottom outside the class

Using a global variable
So let me explain. Each time you call Auth(), it creates a new instance of that class. So in one instance, you might sign the user in. In another instance, you might sign the user out. The variables will contain different values for the variables. So if you use a different instance for signing users out than you did for signing them in, the user variable will be null, therefore not allowing you to sign them out and printing null.
Solution
The solution is a global variable to access the Auth class once. Ex. var authService = Auth();
Put the variable outside the Auth class so it can be accessed in any class, anywhere

A: Thanks everyone for you answers and support. I found the problem. When signing in google, widget.onSignedIn redirects me to home page (it's in root page). I was redirecting to homepage in the google sign in button after calling on SignedIn which is how I was losing the scope of the user variable. Thanks everyone!

A: in my case I was getting the Error:"Null check operator used on null value" whenever I call the signout function through the button which was wraped with GetBuilder.
so the solution was that I had to initiate the controller before I call it like:
GetBuilder<LoginController>(
                init: LoginController(),// **I was missing this part**
                builder: (controller) {
                  return Column(...)});


text:
Q: SQLFORM.factory dropdownlist not mandatory I have a custom form which I have designed using SQLForm.factory. I have created a dropdownlist in it as given below:
Field('method',requires=IS_IN_SET([(1,'Method1'),(2,'Method2'),(3,'Method3')],zero='Select'))

When I do not select any options from it it shows error as 'value not allowed'. I do not want it to be a mandatory field. I tried to set required argument of Field class's init method to False but it did not work. Please let me know how do I achieve that?

A: requires=IS_EMPTY_OR(IS_IN_SET(
    [(1,'Method1'), (2,'Method2'), (3,'Method3')], zero='Select'))

Note, the required argument to Field() is enforced by the DAL upon inserts and results in an exception being thrown upon failure. The requires attribute includes a list of one or more validators that are processed during a SQLFORM submission -- violations of validators result in errors being displayed on the form, not Python exceptions.


text:
Q: Automatically detect an image collage I'm trying to automatically detect if an image is a collage vs a single photograph. I'm not too concerned with edge cases. What I'm trying to solve is rectangular collages like below. I've tried edge detection (canny) + vertical and horizontal sobel filtering + line detection (Hough transform) to try to identify perpendicular lines but am getting too many false positives. I'm not very good at image processing so any input would be welcome. Thx!

A: This is a challenge, because images "have the right" to contain verticals and horizontals, and there can be sudden changes in the background due to occlusion for instance.
But a clue can help you: the borders between two pictures are perfectly straight, "unnaturally" straight, and they are long.


text:
Q: Stacking floats vertically How do I stack say three floats on top of each other vertically such that the height of each plot is approximately the third of the text height of the page? (i.e. so they all fit including captions and subcaptions). I don't care about float width as long as the scale to fit the linewidth.
I'd prefer to use the subcaption package.
Appreciate any support,

A: \documentclass[a4paper]{article}
\usepackage{graphicx}
\usepackage{subcaption}

\begin{document}
\begin{figure}[htbp]
\centering
\subcaptionbox{some caption}[\textwidth]{\includegraphics[height=.3\textheight]{example-image-a}}
\subcaptionbox{some caption}[\textwidth]{\includegraphics[height=.3\textheight]{example-image-b}}
\subcaptionbox{some caption}[\textwidth]{\includegraphics[height=.3\textheight]{example-image-c}}
\caption{This is the main caption}
\end{figure}

\end{document}

A: With this stackengine approach, you can control the gap from the bottom of the image to the top of the subcaption (currently 1.1\baselineskip) as well as the gap from the bottom of the caption to the top of the image below (currently 8pt).
\documentclass{article}
\usepackage[usestackEOL]{stackengine}
\setstackgap{S}{8pt}
\setstackgap{L}{1.1\baselineskip}
\usepackage{graphicx}
\begin{document}
\begin{figure}[p]
\centering\Shortstack
{
\def\stacktype{L}
\stackunder{\includegraphics[height=.27\textheight]{example-image-a}}
           {(a) This is subcaption A}
\\
\def\stacktype{L}
\stackunder{\includegraphics[height=.27\textheight]{example-image-a}}
           {(b) This is subcaption B}
\\
\def\stacktype{L}
\stackunder{\includegraphics[height=.27\textheight]{example-image-a}}
           {(c) This is subcaption C}
}
\caption{This is the figure caption}
\end{figure}
\end{document}


text:
Q: RTK Query code generation - can we generate short model names? I am using the documentation here to generate some RTK Query api files/models, using a SWAGGER openApi json file.
https://redux-toolkit.js.org/rtk-query/usage/code-generation
This is all working great, other than one annoyance of the model names being generated with ridiculously long names.  When using these in my components it is looking messy and hard to read as there is always a load of extra text at the front before I get to the model name.
E.g. as an example it is producing the interface names like this:
MyCompanyServiceMyServiceNameWebModelsActualModelNameModel
I understand this will be done to try and minimise conflicts, but I was wondering if there is a way to override this behaviour to give shorter names?
E.g. the model name I actually want from the above example is ActualModelName


text:
Q: Why do the TT, TE and EE power spectra in the CMB lead to different values for the Hubble constant? Table 2 of Planck 2018 results

Why are these three values different? In particular, why is the EE value so much closer to the local universe value, and have so much higher error?

A: The value of the H0 parameter is calculated along with the four Omega parameters to arrive at the best fit for a Friedmann model for a particular collection of astronomical data. I do not know the specific math used to determine best bit, so I cannot provide any additional details.


text:
Q: Can we Export (as CSV or Excel) the list of modified files using SVN tortoise? When using the TortoiseSVN → Check For Modifications menu item, I get a list of modified files from the repository with different statuses.
Is there a way to export this list as CSV or Excel or any format?

A: Check-for-modifications dialog, sort by status. Shift-Click or Ctrl-Click to select all those with "modified" and "added" status. Then simply right-drag the files from the Check-for-modifications dialog to another folder in explorer.
Another way (if you already committed your changes): Show log dialog, select all revisions with the interesting changes. In the lower pane, shift-select all entries, right-click, choose "save as".
Yet another way: Use the repository browser, find the first url (assuming you want to export everything that's changed between two tags, e.g., version 1 and version 2), right-click, "Mark for comparison". Find the second url, right-click, "compare urls". In the following "changed files" dialog, select all files, right-click, choose "export selection to...".

A: After some trials, I got to mark the files I need by simple selection and right-click, then select 'copy all information to clipboard'.
Then I opened a new blank excel sheet and pasted the data in the first cell, I got the data properly arranged in the sheet, and each value took a cell.

A: TortoiseSVN has the ability to optionally install the Subversion command line client. The command line client is guaranteed to be compatible with the GUI client.
That means if you need to save the output of a Subversion command to a file, you can always use the command line client:
C:> svn status > status.txt

I highly recommend that you install the command line client the next time you upgrade your TortoiseSVN installation. The command line client makes it easy to parse Subversion output for all sorts of reasons, and can be easily integrated into Python, Perl, or PowerShell scripts.


text:
Q: Ruby regex for a split every four characters not working I'm trying to split a sizeable string every four characters. This is how I'm trying to do it:
big_string.split(/..../)

This is yielding a nil array. As far as I can see, this should be working. It even does when I plug it into an online ruby regex test.

A: Try scan instead:
$ irb
>> "abcd1234beefcake".scan(/..../)
=> ["abcd", "1234", "beef", "cake"]

or
>> "abcd1234beefcake".scan(/.{4}/)
=> ["abcd", "1234", "beef", "cake"]

If the number of characters isn't divisible by 4, you can also grab the remaining characters:
>> "abcd1234beefcakexyz".scan(/.{1,4}/)
=> ["abcd", "1234", "beef", "cake", "xyz"]

(The {1,4} will greedily grab between 1 and 4 characters)

A: Hmm, I don't know what Rubular is doing there and why - but
big_string.split(/..../)

does translate into

split the string at every 4-character-sequence

which should correctly result into something like
["", "", "", "abc"]

A: Whoops.
str = 'asdfasdfasdf'
c = 0
out = []
inum = 4
(str.length / inum).round.times do |s|
    out.push(str[c, round(s * inum)])
    c += inum
end


text:
Q: The em dash in place of a colon I read in a punctuation guide that a dash can be used in place of a colon. They provided the following example:
The white sand, the warm water, the sparkling sun—this is what brought them to Hawaii.
However, just to clarify, but what precedes a colon must be an independent clause. Is that not the case for an em dash?

A: Rules were made to be broken.  In formal writing, your example might be considered questionable because it does not begin with an independent clause.  However, you will regularly see sentences like this in published works of fiction, because they allow a more natural, conversational flow.
The same sentence could be written with a colon, but it would have a different "feel" to it.  The problem is that dashes are also used to denote interruption, while colons are not.  So with a dash, your sentence connotes a stream of consciousness, with the narrator abruptly generalizing from specific elements to Hawaii as a whole.  With a colon, it connotes an itemized list summarized by the thought about Hawaii, a much more dry and academic style of writing.  But if you want to be dry and academic, you probably want to recast the whole sentence (and move Hawaii to the front), so it doesn't really work with the colon.


text:
Q: How can I make this no recoil script do an additional movement of my mouse? Im brand new at scripting and have no idea what im doing. Found the below code online and want it to make adjustments. So basically, in fallout 4 lets say a gun's recoil goes to up and to the left originally, but then halfway into shooting it goes to the right. I want the script to initially be able to pull the mouse down and to the right, and then (when the guns recoil starts to go in the other direction) go to the left. Is this possible?

EnablePrimaryMouseButtonEvents (true);

function OnEvent(event,arg)
   if IsKeyLockOn("numlock")then
      if IsMouseButtonPressed(3)then
         repeat
            if IsMouseButtonPressed(1) then
               repeat
                  MoveMouseRelative(-1,13)
                  Sleep(75)
               until not IsMouseButtonPressed(1)
            end
         until not IsMouseButtonPressed(3)
      end
   end
end

Above is a script I use to move my mouse down when pressing the shooting buttons in Fallout 4 because I have problems which prevent me from countering recoil.
I want the script to not only move down and slightly to the left (MoveMouseRelative(-1,13)) but I want to be able to specify that after a certain amount of time, I then want the script to move in a different direction that again, I can specify.
How would I do this? I believe this is a LUA script or something, and im using a logitech mouse

A: EnablePrimaryMouseButtonEvents(true)

function OnEvent(event, arg)

   if event == "MOUSE_BUTTON_PRESSED" and arg == 1 and IsMouseButtonPressed(3) and IsKeyLockOn("numlock") then
      -- first group of moves: 10 steps in direction (-1,13), total group time = 750 ms
      for i = 1, 10 do
         MoveMouseRelative(-1,13)
         Sleep(75)
         if not IsMouseButtonPressed(1) then return end
      end
      -- second group of moves: 5 steps in direction (1,12), total group time = 375 ms
      for i = 1, 5 do
         MoveMouseRelative(1,12)
         Sleep(75)
         if not IsMouseButtonPressed(1) then return end
      end
      -- you can add more groups
   end

   if event == "MOUSE_BUTTON_PRESSED" and arg == 1 and IsMouseButtonPressed(3) and IsKeyLockOn("scrolllock") then
      -- first group of moves: 10 steps in direction (-1,13), total group time = 750 ms
      for i = 1, 10 do
         MoveMouseRelative(-1,13)
         Sleep(75)
         if not IsMouseButtonPressed(1) then return end
      end
      -- second group of moves: 5 steps in direction (1,12), total group time = 375 ms
      for i = 1, 5 do
         MoveMouseRelative(1,12)
         Sleep(75)
         if not IsMouseButtonPressed(1) then return end
      end
      -- you can add more groups
   end

end

UPDATE:
Step 0.
You are about to modify the behavior of Left Mouse Button.
This is a potentially dangerous operation: you can do almost nothing on your computer without LMB.
So you must create a "spare LMB".
For example, if you don't use Mouse Button 8, you can make it acting like a clone on LMB.
Go to the big mouse picture in LGS and assign command "Left Click" to your physical MB#8.
Now, if something goes wrong and your LMB stops working, you can press MB#8 instead of LMB.

Step 1.
Do you use Mouse Button 4 ("Back") in the game?

*

*If YES (some action is set to MB#4 in the game), proceed to "Step 2".

*If NO (the game ignores MB#4 press), skip "Step 2" and proceed to "Step 3".

Step 2.
You have to remap game action from MB#4 to some other key.
Do the following:

*

*choose keyboard key you don't currently use in the game
(let's assume the F12 key is not currently used)

*go to the big mouse picture in LGS and assign command F12 to your physical MB#4

*go to your game settings and set the game action to F12 instead of MB#4

As a result, when you press physical MB#4, the game receives F12 and activates the game action.
Now skip "Step 3" and proceed to "Step 4".

Step 3.
Go to the big mouse picture in LGS.
Unassign standard command "Back" from physical MB#4 (select "Unassign" from the drop-down menu).

Step 4.
Set the script (see below).

Step 5.
Go to the big mouse picture in LGS.
Assign command "Back" to your physical LMB.
You will see a warning about a potentially dangerous operation.
Allow this operation because you have the "spare LMB" if something goes wrong.

-- rapid fire (CAPSLOCK) is independent from anti-recoil (NUMLOCK and SCROLLLOCK)

local rapid_fire_interval = 30  -- milliseconds between LMB press/release simulation

local LMB_down, rapid_fire, prev_time, next_LMB_time

local function PressOrReleaseLMB(only_release)
   if LMB_down then
      ReleaseMouseButton(1)
      LMB_down = false
   elseif not only_release then
      PressMouseButton(1)
      LMB_down = true
   end
end

local function Sleep_with_rapid_fire(ms)
   -- returns true if LMB was released by user
   prev_time = prev_time + ms
   while GetRunningTime() < prev_time do
      Sleep(10)
      if not IsMouseButtonPressed(4) then
         return true
      end
      while rapid_fire and GetRunningTime() >= next_LMB_time then
         next_LMB_time = next_LMB_time + rapid_fire_interval
         PressOrReleaseLMB()  -- press LMB (if it's up) or release LMB (if it's down)
      end
   end
end

function OnEvent(event, arg)
   if event == "PROFILE_ACTIVATED" then
      EnablePrimaryMouseButtonEvents(true)
   elseif event == "PROFILE_DEACTIVATED" or event == "MOUSE_BUTTON_RELEASED" and arg == 1 then
      PressOrReleaseLMB(true)  -- release LMB
   elseif event == "MOUSE_BUTTON_PRESSED" and arg == 1 then
      PressOrReleaseLMB()  -- press LMB
      prev_time = GetRunningTime()
      next_LMB_time = prev_time + rapid_fire_interval
      rapid_fire = IsKeyLockOn("capslock")
      if IsMouseButtonPressed(3) then  -- RMB pressed
         if IsKeyLockOn("numlock") then

            -- first group of moves: 10 steps in direction (-1,13), total group time = 750 ms
            for i = 1, 10 do
               MoveMouseRelative(-1,13)
               if Sleep_with_rapid_fire(75) then return end
            end
            -- second group of moves: 5 steps in direction (1,12), total group time = 375 ms
            for i = 1, 5 do
               MoveMouseRelative(1,12)
               if Sleep_with_rapid_fire(75) then return end
            end
            -- you can add more groups

         elseif IsKeyLockOn("scrolllock") then

            -- first group of moves: 10 steps in direction (-1,13), total group time = 750 ms
            for i = 1, 10 do
               MoveMouseRelative(-1,13)
               if Sleep_with_rapid_fire(75) then return end
            end
            -- second group of moves: 5 steps in direction (1,12), total group time = 375 ms
            for i = 1, 5 do
               MoveMouseRelative(1,12)
               if Sleep_with_rapid_fire(75) then return end
            end
            -- you can add more groups

         end
      end
      Sleep_with_rapid_fire(math.huge)  -- until user released LMB
   end
end


text:
Q: Critical dependency is preventing me from updating my app to latest framework version My project relies on a specialized component which is stuck (by its configuration) to an older version of the framework my project is using. This makes updating to the latest version of the framework impossible.
What are the best practices when dealing with this type of issue?

A: Because of reasons like this, dependencies are not just an asset but also a kind of liability: today's rapid development is tomorrows technical debt. Depending on the risks you forsee and want to mitigate, it can make sense to use a dependency only if

*

*you insulate yourself from the dependency as far as possible, e.g. as described in candied_orange's answer.

*you have a plan to either migrate away from the dependency, or can ensure timely fixes to the problems you encounter.

*for proprietary dependencies you have contracts in place with clear support levels, for example that lay out how fast security issues will be fixed, and whether there will be any penalties if that support level is not met.

*for open source dependencies you are prepared to fork the code and fix the bugs yourself, or have retained a consultant who can fix these bugs for you on short notice.

*alternatively, you are prepared to shoulder remaining risk. This might be a sensible approach for well-supported problems with a sizeable community.

E.g. for most companies it does not make sense to maintain their own Linux kernel. On the other hand, that NPM package with only a few thousand downloads? Better fork it right now.
In general, it is a good idea to have your own copies of all open source dependencies that you rely on. It is also preferable to host any packages yourself. This not only gives you the ability to fix any problems, it also gives you more control over updates, and an opportunity to review and test updates.
To which degree that is sensible depends also on how the transitive dependencies are loaded. E.g. dynamically linked libraries that will be updated through your operating system (e.g. Debian) are a lot less problematic than a statically linked binary blob.
Here, your best bet is likely to fork the problematic dependency and perform the fix yourself. If source code is not available you may need to decompile or reverse engineer it. Note that this may not be legal if the dependency was provided to you under a proprietary license, so check that first.
If the dependency cannot be fixed by you, you might need to mitigate the security risk through another approach, e.g.:

*

*temporarily disable your service in whole or in part.

*detect and block or sanitize inputs that could trigger the security vulnerability.

Temporarily taking down your service can give you the time needed to figure out a more permanent solution, e.g. to extract the problematic dependency to a separate process or service so that it can be deployed independently of the framework.
Note that you may be required to take reasonable steps to ensure the security of the data you process if you are subject to various privacy regulations such as the GDPR. Temporarily shutting your service down until the vulnerability can be fixed may be a reasonable measure if you have no way to fix the problem immediately.

A: The critical thing to sort out is the nature of your dependency. Does the older version provide one thing that your project needs or many things? Does the newer version provide one thing or many things for your project?
It's very important to look at the framework through the lens of your projects needs. This keeps you from fixing problems that you don't need to care about.
If you can identify a few needs that your project has that are creating a dependency on some version of the framework you can externalize these dependencies as library calls. Remove direct knowledge of the framework from the inner parts of your app that depends on  it. Satisfy those needs through calls to adapters that hide which version or even which framework is satisfying them.
Configure those adapters at the top of your call stack. This is usually in main. Here is where you decide what will satisfy what needs.
Doing that will reduce the amount of code that has any idea which version of the framework is being used. You would be free to use multiple versions for different parts, create adapters that give you the old features with the new version, or write your own solutions that reduce your reliance on the framework.
If that sounds like a lot of work that's only because it is. Frameworks love to make you dependent on them. Keeping them at arms length so that you remain in charge takes effort.


text:
Q: using a perl regex in c what does this regex match?
How can I use this regex in C?
I am getting error if I do:
if (regcomp(&reg, "/[^\\]\]/", REG_EXTENDED | REG_ICASE) != 0)

error:
warning: unknown escape sequence '\]'

Thanks in advance.

A: I think you need to escape your backslashes:
from "/[^\\]\]/" to "/[^\\\\]\\]/"

A: It worked when I escaped the backslashes and removed /s from both ends.

A: I like perl , and I also like C/C++. To make the best of both,
I wrote a github project to solve this issue.
please see:
    https://github.com/tlqtangok/perlcpp
a short example is here :
P_eval("$a=2;$a=$a**10;");
Int("a") ;   // a= 1024

P_eval("@arr=(0..9);";
P_arr_Int_i("arr", 8 );  // => 8


text:
Q: Why sometimes my python path from venv doesn't work? When I try to run sudo python setup.py install having my venv activated, I get some Django and python version mismatch error, but when I use python path which is there in venv by copying its actual path and running the same command above just by replacing python path, it do works, so I am unable to understand which it worked when I kept actual path int it?
Thanks in advance


text:
Q: How to read image from specific path in SQL Server 2005 stored procedure? I need to read the image from the specific path. I pass only path as parameter and that image will return by the procedures in image or byte format.

A: Take appropriate SQL injection precautions.
EXEC('SELECT image_data
FROM OPENROWSET(
BULK N''' + @Path + ''',
SINGLE_BLOB)
AS ImageSource(image_data);')


text:
Q: Add button to dockble windows in inventor? I have made a tools. But it is not dockeble.  but I this code that make a dockbel windows. but do I add button to it that will run sub ?`

Dim oUserInterfaceMgr As UserInterfaceManager
        oUserInterfaceMgr = ThisApplication.UserInterfaceManager

        ' Create a new dockable window
        Dim oWindow As DockableWindow
        oWindow = oUserInterfaceMgr.DockableWindows.Add("SampleClientId6", "TestWindowInternalName6", "Test Window6")

        ' Get the hwnd of the dialog to be added as a child
        ' CHANGE THIS VALUE!
        Dim hwnd As Long
        hwnd = 4851096

        ' Add the dialog as a child to the dockable window
        oWindow.AddChild(hwnd)

        ' Don't allow docking to top and bottom
        oWindow.DisabledDockingStates = DockingStateEnum.kDockTop And DockingStateEnum.kDockBottom

        ' Make the window visible
        oWindow.Visible = True

how do I add button to it. And how do I add code that run when you click the button ?
`
I want to recreat my current tools into a dockbel windows
my current tools look like this


text: Q: Li-Ion/Li-Polymer Battery Charger mcp73871-2cci/ml Issue Hope someone can help.  I have designed a pcb board based on the mcp73871-2cci/ml. No matter what I change there is no current draw and all the indication LED's remain on. I have seen some example schematics, some have pull down resistor and others do not. I also changed the 10k NTC THERM to a 10k resistor and there is still no change. Any ideas?


text:
Q: gqlQuery returns object, want list of keys Is there a way to convert the GqlQuery object to an array of keys, or is there a way to force the query to return an array of keys?   For example:
items = db.GqlQuery("SELECT __key__ FROM Items")

returns an object containing the keys:
<google.appengine.ext.db.GqlQuery object at 0x0415E210>

I need to compare it to an array of keys that look like:
[datastore_types.Key.from_path(u'Item', 100L, _app_id_namespace=u'items'),
 ..., datastore_types.Key.from_path(u'Item', 105L, _app_id_namespace=u'fitems')]

Note:  I can get around the problem by querying for the stored objects, and then calling .key(), but this seems wasteful.
items = db.GqlQuery("SELECT * FROM Items")
keyArray = []
for item in items:
  keyArray.append(item.key())

A: Certainly - you can fetch the results by calling .fetch(count) on the GqlQuery object. This is the recommended way, in fact - iterating fetches results in batches, and so is less efficient.


text:
Q: how to get more than one number inside of matrices Ok. I have a simple question although I'm still fairly new to Matlab (taught myself). So I was wanting a 1x6 matrix to look like this below:
0

0

1

0

321, 12      <--- needs to be in one box in 1x6 matrices

4,30,17,19   <--- needs to be in one box in 1x6 matrices

Is there a possible way to do this or am I going to just have to write them all in separate boxes thus making it a 1x10 matrix?
My code:
event_marker = 0;
event_count  = 0;
block_number = 1;

date = [321,12] % (its corresponding variables = 321 and 12)

time = [4,30,17,19] % (its corresponding variable = 4 and 30 and 17 and 19)

A: So if I understand you correctly, you want an array that contains 6 elements, of which 1 element equals 1, another element is the array [312,12] and the last element is the array [4,30,17,19].
I'll suggest two things to accomplish this: matrices, and cell-arrays.
Cell arrays
In Matlab, a cell array is a container for arbitrary types of data. You define it using curly-braces (as opposed to block braces for matrices). So, for example,
C = {'test', rand(4), {@cos,@sin}}

is something that contains a string (C{1}), a normal matrix (C{2}), and another cell which contains function handles (C{3}).
For your case, you can do this:
C = {0,0,1,0, [321,12], [4,30,17,19]};

or of course,
C = {0, event_marker, event_count, block_number, date, time};

Matrices
Depending on where you use it, a normal matrix might suffice as well:
M = [0  0  0  0
     event_marker  0  0  0
     event_count  0  0  0
     block_number  0  0  0
     321 12  0  0
     4 30 17 19];

Note that you'll need some padding (meaning, you'll have to add those zeros in the top-right somehow). There's tonnes of ways to do that, but I'll "leave that as an exercise" :)
Again, it all depends on the context which one will be easier.

A: Consider using cell arrays rather than matrices for your task.
data = cell(6,1); % allocate cell
data{1} = event_marker; % note the curly braces here!
...
data{6} = date;   % all elements of date fits into a single cell.

A: If your date and time variables are actually represent date (numbers of days, months, years) and time (hours, mins, sec), they can be packed into one or two numbers.
Look into DATENUM function. If you have a vector, for example, [2013, 4, 10], representing April 10th of 2013 you can convert it into a serial date:
daten = datenum([2013, 4, 10]);

It's ok if you have number of days in a year, but not months. datenum([2013, 0, 300]) will also work.
The time can be packed together with date or separately:
timen = datenum([0, 0, 0, 4, 30, 17.19]);

or
datetimen = datenum([2013, 4, 10, 4, 30, 17.19]);

Once you have this serial date you can just keep it in one vector with other numbers.
You can convert this number back into either date vector or date string with DATEVEC and DATESTR function.


text:
Q: generic way for communication between shopping cart and applet I am building a configurable "applet" (not Flash, but HTML and Javascript). The planned functions are similar to a car configurator, where you select color, engine power or seat covers. The actual product will be listed by various online shops as a single product. The configuration should be done within the page that presents the product.
The shops in question all use different CMSes. The problem is, that I'd have to write code for each shopping system to integrate the applet into the shop. Is there an industry standard for doing this? Or if that is not the case: Where is the point of minimal necessary communication of the shop with the configurator, where I'd best place the interface?
My current idea is to to configure the shop on page load by a JSON object, telling it about its environment and about the last state of the product (someone might want to alter an ordered product). Once the user has finished configuring, an AJAX call is used to send the configuration to the server. There the product is added to the shopping cart and a redirect to another page (product overview etc.) is requested.
Is this a good way to do that? What would be better?


text:
Q: Gravitational potential at large distance tensor Prove that for a bounded body with mass disturbution $\rho (\vec{r'})$
The gravitational potential of the body can be expressed as
$\phi(\vec{r'})=-\gamma\frac{M}{r}+\frac{3\gamma}{2r^5}r_ir_j(I_{ij}-\frac{1}{3}I_{kk}\delta_{ij})$
where $I_{ij}=\int_V dV' \rho(\vec{r'})(r'^2-r_ir_j\delta_{ij})$
Also $\phi(\vec{r})=-\gamma \int_V dV' \frac{\rho\vec(r')}{|\vec(r')-\vec(r)|}$
Not sure how to obtain the higher order term, and also should $I_{kk}$ be zero


text:
Q: d3.js how to dynamically add only those nodes to collapsible tree, selected from a datatable I have been working on collapsible tree in which a large set of data overlapping occurs and the whole tree looks clumsy.
What I am trying to do is to open a data-table and expand only selected nodes from the data-table something like this, on selecting MN type node, a data-table opens here and on selecting any of up to 5 nodes using checkbox,all the 5 nodes shall be expanded to that parent MN node like this but it does not expand here.
This is what I have tried so far
var selected;  //select node to which data shall be expanded
var selectedMnDataArray =[]; //collecting data from data-table
selectedMnDataArray.parent = selected;

if(!selected.children){
                selected.children = [];
                selected.treeData5.children = [];
              }
              selected.children.push(selectedMnDataArray);
              selected.treeData5.children.push(selectedMnDataArray.data);

              update(selected);

But this only expands a link as you can see in the picture.
Another thing I tried is from the post d3.js how to dynamically add nodes to a tree
But this also doesn't work in my case.
please anyone help me out here.