text:
Q: Problem with extension method with asp.net web form page code behind i am creating an extension method to check null datarow with c#, i am trying to use the extension method in my asp.net web form code behind but giving me that the method  IsEmpty doesnot in the current context
here is the code i am trying
 public static class IsNullValidator
    {
        public static bool IsNullEquivalent( this object value)
        {
            return value == null
                   || value is DBNull
                   || string.IsNullOrWhiteSpace(value.ToString());
        }
        public static bool IsEmpty( this DataRow row)
        {
            return row == null || row.ItemArray.All(i => i.IsNullEquivalent());
        }
    }

and i call it like this
DataRow[] row =getRowMethod();
if IsEmpty(row){"do some functionality"}

if i changed IsEmpty Signature by removing this keyword to below it works like this
   public static bool IsEmpty(  DataRow row)
            {
                return row == null || row.ItemArray.All(i => i.IsNullEquivalent());
            }
   if IsEmpty(row[0]){"do some functionality"}

i need to work with this extension to check any datarow and in future to check any datatable
and can i use the below method to check null datatable
 public static bool IsEmptyDatatable (DataTable dt)
    {
        return dt == null || dt.Rows.Cast<DataRow>().Where(r=>r.ItemArray[0]!=null).All(i => i.IsNullEquivalent());
    }

A: Extension methods are "extensions" of a type. In your case you are extending the DataRow class. For extension methods you need to have an instance of that class to call it e.g.:
DataRow[] row =getRowMethod();

if row.IsEmpty(){"do some functionality"}

In the example, the extension method is called on the instance row of the DataRow class.
If you think of the this keyword as saying "this method can be called on an instance of 'this' class" - which in your case is DataRow, that might help you to understand it.

A: finally i ended up with the bellow solution ,thank you people ...all what you suggested were helpful
 public static bool IsNullEquivalent( this object value)
        {
            return value == null
                   || value is DBNull
                   || string.IsNullOrWhiteSpace(value.ToString());
        }
        public static bool IsEmptyDataRow(this  DataRow row)
        {
            return row == null || row.ItemArray.All(i => i.IsNullEquivalent());
        }
        public static bool IsEmptyDatatable (this DataTable dt)
        {
            return dt == null || dt.Rows.Cast<DataRow>().All(i => i.IsEmptyDataRow());
        }


text:
Q: How to find and click links/buttons by href? (GeckoFx browser) In the past I were using
       GeckoElementCollection elements = iframe.ContentDocument.GetElementsByName("name");
            foreach (var element in elements)
            {

                 if (element.GetAttribute("href") == "text")
                 {
                     MessageBox.Show(element.GetAttribute("class"));
                 }
              }

So I were finding element by name and then I checked href if its element which im trying to find.
Now I dont have any element name only class (class is same for few elements) and what is unique is href. So I need to search element by href and perform click/input events with it.
I believe that I need to use GeckoNode
    GeckoNode node = iframe.ContentDocument.GetElementsByClassName("classname")[0].FirstChild;
             if (NodeType.Element == node.NodeType)
             {
                 MessageBox.Show(node.GetAttribute("hreff"));

             }

However GetAttribute dont work with nodes.. Any ideas?

A: I know the question is old, but today I had same problem and I fix it. Try something like this :
GeckoElementCollection fblikes = webBrowser.Document.GetElementsByTagName("a");
            foreach (GeckoHtmlElement item in fblikes)
            {
                string aux = item.GetAttribute("href");
                if (!string.IsNullOrWhiteSpace(aux) && aux.Equals("p.php?p=facebook"))
                {
                    item.Click();

                }
            }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Function needed for HTML Registration im trying to make a function so the html code will execute by calling the following function. What do i need to do to to translate it as a recognized function?
 function jquery_register(){

    }

here is the required HTML code

        <form action="#" method="post">

SIGN UP FOR A FREE Reg Name ACCOUNT

                    <input type="text" name="username" id="username" value="username" />
                    At least 4 characters. Uppercase letters, lowercase letters and numbers only.

                    <input type="password" name="password" id="password" value="password" />
                    At least 4 characters. Use a mix of upper and lowercase for a strong password.

                    <input type="password" name="cpassword" id="cpassword" value="password" />
                    If your passwords aren't equal, you won't be able to continue with signup.

                <input class="submit" type="submit" name="submit_first" id="submit_first" value="" />

SIGN UP FOR A FREE Reg Name ACCOUNT

                    <input type="text" name="firstname" id="firstname" value="first name" />
                    Your First Name.
                    <input type="text" name="lastname" id="lastname" value="last name" />
                    Your Last Name.
                    <input type="text" name="email" id="email" value="email address" />
                    Your email address. We send important administration notices to this address.

                <input class="submit" type="submit" name="submit_second" id="submit_second" value="" />

SIGN UP FOR A FREE Reg Name ACCOUNT

                    <select id="age" name="age">
                        <option> 0 - 17</option>
                        <option>18 - 25</option>
                        <option>26 - 40</option>
                        <option>40+</option>
                    </select>
                    Your age range.

                    <select id="gender" name="gender">
                        <option>Male</option>
                        <option>Female</option>
                    </select>
                    Your Gender.

                    <select id="country" name="country">
                        <option>United States</option>
                        <option>United Kingdom</option>
                        <option>Canada</option>
                        <option>Serbia</option>
                        <option>Italy</option>
                    </select>
                    Your country.

                <input class="submit" type="submit" name="submit_third" id="submit_third" value="" />

SIGN UP FOR A FREE Reg Name ACCOUNT

Summary

Username

Password

Email

Name

Age

Gender

Country

                <input class="send submit" type="submit" name="submit_fourth" id="submit_fourth" value="" />

        </form>

0% Complete

After the function is called like i said it will execute on the page from this function and show the form.
I have the jquery functions which are already in place.
All i need to do is complete this bit of code.

A: you have several different ways to do this:
1- create a html file on the server side put your html on it, and use jQuery load function:
function jquery_register(){
    jQuery(document.body).load(html_file_url);
}

2- create the html file like the first solution, use jQuery ajax to load and inject it to your page:
function jquery_register(){
    jQuery.get(html_file_url).then(function(htmlstr, status){
        if(status == "success"){
            jQuery(document.body).html(htmlstr);
        }
    });
}

3- the other way here is define a variable in the client-side and do something like this:
function jquery_register(){
    var html_variable = '
.....the rest';
    jQuery(document.body).html(html_variable);
}

4- or you can simply do:
document.body.innerHTML = html_variable;

or create a container in your page and:
document.getElementById("htmlcontainer").innerHTML = html_variable;


text:
Q: Visual Studio: there are no components that can be placed on the toolbox I am using Visual Studio 2013 Ultimate with Windows 7, and a C# / WinForms project. I have a problem that I cannot add any DLLs to the toolbox. I have already tried searching on Google for the answer, but none of the solutions work: rebuilding the project and re-installing Visual Studio both didn't work.
Even if I create a new project, I cannot drag the DLL to the toolbox or nuGet or use "Choose Item" from the toolbox. I want to use materialSkin, metroframework, and others like that.
Just in case it helps: I have installed Visual C# 2008 and Visual Studio 2010 previously; could that cause any problems with Visual Studio 2013?
Here is the error I see:

Can anyone help please?


text:
Q: Is there an lossless algorithm for division? So that equations in Math(like p * 1/p = 1) will always hold in computers?

A: If you store your number as a numerator/denominator pair then, yes, you can make it lossless.
By that, I mean the number 10, when divided by 3, is stored not as 3.3333333 but instead as the pair {10,3}. This means that, when you multiply it by 3 again, it will become 10.
Of course, that may not work in all edge cases. You still won't be able to represent irrational numbers like PI or the square root of 2, since they can neither be represented as a finite decimal sequence nor a ratio.
But, for division only (using rational numbers), I can't conceive of an edge case where it wouldn't work.

A: Use a arbitrary precision arithmetic library such as the GNU GMP to get "infinite precision" numbers. The library is available at:
http://gmplib.org/


text:
Q: Which Azure storage technology for weather forecast data I would like some advice/tips about the right technology to select in order to store some forecast data on Azure technologies.
My team and I are scraping some weather forecast data everyday from various sources and store it as is on a Azure File Storage. The files format is "grib2" which is a standard format of weather forecast data.
We are able to extract the data from those "grib2" files using python script running on a Azure VM.
We now have several files that represent hundreds gigabytes of data to store and I'm struggling to find which data store from the Azure technologies suits the best our needs in term of praticity and cost.
We started using "Azure Table Storage" first because it's cheap solution,
 but I've read on many posts that it is a bit old and not  very adapted to our solution as it for example does not allow more than 1,000 entites per query and no aggregation on data.
I considered using Azure SQL db but it seems that it can become very expensive very fast.

I also considered the Azure Data Lake Storage Gen2 (and HDinsight) technologies but am not very at ease with those blob storages and am not really able to say if it can suit my needs in terms of praticity and if it is "easy to query".

By now we just plan to achieve that :

1) Extract data from grib2 files thanks to a python script running on an Azure VM
   2) Insert the transformed data into [Azure storage]
   3) Query the [Azure storage] from Azure Machine Learning Service or a local R script (for example)
   4) Insert the computed data into  [Azure storage]

where [Azure Storage] technology is to determine.

Any help or advice would be much appreciated, thanks.

A: A couple of things I would see here:

*

*To store the downloaded files in raw format (grib2 in your case), either place them on good ol' Azure Blob Storage. Cheap storage exactly for your needs.

*Use Azure Databricks to load the data from the storage account and unpack it into memory. (python or scala)

*Load the data in memory - still in Databricks - to run you ML inferencing. You could also use SparkR if you really want to.

*Store the computed files in a serving layer. This really depends on what you want to do with it later. Often Azure SQL Database is an obvious choice. There is a native Spark connector which efficiently writes data from Databricks to SQL DB.

In addition to using Databricks as your inferencing environment, it's also a good choice for ML training (e.g. utilizing Azure ML Service).


text:
Q: Type TIME is not a defined system type We are using Microsoft Server 2012. I need to sum some variables from each day between given time gap.
Here is simplified query:

    SELECT SUM(SomeVariable)
    FROM MyTable
    WHERE CAST([wrkActionDate] as TIME) BETWEEN '19:00:00' AND '07:00:00'

And i get error:

    Type TIME is not a defined system type.

I guess data type doesn't exist in "Microsoft Server 2012" if so how to write query which would do what i want to do?
P.S: Sorry if I made some writing errors. I don't compute English :)

A: FROM and WHERE should be swapped.
The cast to time works - just tried it with SQL Server 2012  - but the range is invalid (starting value greater than the end one) - you should do something like this:
SELECT SUM(SomeVariable)
FROM MyTable
WHERE
  CAST([wkActionDate] AS TIME) BETWEEN '19:00:00' AND '23:59:59' OR
  CAST([wkActionDate] AS TIME) BETWEEN '00:00:00' AND '07:00:00'

You can also use DATEPART:
SELECT SUM(SomeVariable)
FROM MyTable
WHERE
  DATEPART(hour,[wrkActionDate]) BETWEEN  19 AND 24 OR
  DATEPART(hour,[wrkActionDate]) BETWEEN 0 AND 7


text:
Q: Issue separating divs, class affecting other div Ive got a noob question, Im going nuts already. So I have a div under another div, they appear to be separated BUT the class from the top div is affecting the div below it. Is there a way of ending a div or something of that sort. Heres what Ive got. The last button in the menu, the contact button, has a class that changes background on hover, which is having the same effect on the    form div below it when I hover the form.
I would be eternally grateful for an answer.

JEWELRY</l>

OUR COMPANY</l>

OUR COMPANY</l>

OUR COMPANY</l>

ENGAGEMENT</l>

OUR COMPANY</l>

OUR COMPANY</l>

OUR COMPANY</l>

DIAMONDS</l>

OUR COMPANY</l>

OUR COMPANY</l>

OUR COMPANY</l>

WATCHES</l>

OUR COMPANY</l>

OUR COMPANY</l>

OUR COMPANY</l>

CUSTOM CAD</l>

OUR COMPANY</l>

OUR COMPANY</l>

OUR COMPANY</l>

REPAIR</l>

OUR COMPANY</l>

OUR COMPANY</l>

OUR COMPANY</l>

APPRAISAL</l>

OUR COMPANY</l>

OUR COMPANY</l>

OUR COMPANY</l>

OUR COMPANY</l>

OUR COMPANY</l>

OUR COMPANY</l>

OUR COMPANY</l>

CONTACT </l>

OUR COMPANY</l>

OUR COMPANY</l>

OUR COMPANY</l>

The div above has a class called bg9 which is affecting the div below!

    <input name="name"
  type="text"
  class="validate
   [required,custom
   [onlyLetter],
   length[0,100]]
  feedback-input" placeholder="Name" id="name" />

    <input name="email" type="text" class="validate[required,
  custom[email]]       feedback-input" id="email" placeholder="Email" />

    <textarea name="text" class="validate[required,length[6,300]]
    feedback-    input" id="comment" placeholder="Comment"></textarea>

    <input type="submit" value="SEND" id="button-blue"/>

 </form>

A: Rookie mistake youll, forgot to ad an

at the end of the link in the menu. Thank you everyone


text:
Q: How to write 'Git LFS pull after checkout' settings in the Jenkins pipeline I created a configuration file with Jenkins file to configure the Jenkins pipeline.
An error occurred when doing git pull.
The cause was that the groovy file did not have the Git LFS pull after checkout setting.
I do not know how to write Git LFS pull after checkout setting to groovy.
git(
 url: git@...,
 branch: "master",
 credentialsId:"abcdefg"
)

// Git LFS pull after checkout setting??

A: Here's how I was able to use the Git plugin in the pipeline. Refer to the documentation here for more info:
        checkout([  $class: "GitSCM",
            branches: [[name: "refs/heads/${your branch name}"]],
            extensions: [
                [$class: "GitLFSPull"]
            ],
            userRemoteConfigs: [
                [credentialsId: "${your git credential ID}",
                url: "${your git URL}"]
            ]
        ])

Considering you are trying to download a large file, you may want to increase the time out limit too (default is set to 10 minutes):
        checkout([  $class: 'GitSCM',
            branches: [[name: 'refs/heads/'+"${branch_or_tag}"]],
            extensions: [[$class: 'GitLFSPull']]
                       +[[$class: 'CloneOption', timeout: 30]],
            userRemoteConfigs: [
                [credentialsId: "${your git credential ID}",
                url: "${your git URL}"]
            ]
        ])


text:
Q: React: I don't see thumbnails when using react-responsive-carousel I have followed the demo code and all works well except thumbnails. I set it to true so I can see 'ul' for the thumbnails in html, but it does not have any image src.
Here is the code below.
import React from 'react';

import { Carousel } from 'react-responsive-carousel';
import 'react-responsive-carousel/lib/styles/carousel.min.css';

import Image from 'next/image';

const Banner = ({ carousel, isDifferent, className }) => {
  return (

      <Carousel autoPlay infiniteLoop showThumbs>
        {carousel.length !== 0 &&
          carousel?.map((item, idx) => (
            <div className={`relative w-full ${className} cursor-pointer`} key={idx}>
              <Image src={isDifferent ? item?.node?.mediaItemUrl : item.node.bannerInfo.bannerImage.mediaItemUrl} alt="banner" objectPosition="center top" layout="fill" objectFit="cover" priority />

          ))}
      </Carousel>

  );
};

export default Banner;

This is how I use Banner component
      <Banner carousel={product.galleryImages.edges} isDifferent className="md:hidden h-[400px]" />

When I check on the development tool, I see the ul.

Please let know what I am missing.

A: If not using the img html element directly you need to render the thumbnails with renderThumbs
example:
  renderThumbs={() =>
                    mThumbnails.map((thumbnail) => (
                        <Image src={thumbnail.src} alt={thumbnail.alt} key={thumbnail.src} />
                    ))
                }


text:
Q: How to update a final table based on multiple tables in MS Access? So I am making a database where the user is required to essentially do a checklist so I have multiple tables that corresponds to this. For example: User table, Inventory table, Store details etc each table having its own primary key. I have created forms that will individually add records to each table and essentially forming the checklist with date records as to when this was done.
I want to then basically create a report of that specific checklist performed by that specific user at that date - basically printing a report that the checklist was completed. I was thinking of making a new table that basically contains the primary key IDs of the User, inventory and store table to consolidate all the data inputted on the forms by user. So question is how do I get the final table to also update with the primary key IDs created based on the records added?
Do you have any other suggestions on how to do this?


text:
Q: How to get the Radio Button values in another page using while loop Concept in php How to get And Store the Radio Button Values in MysqlDatabase in php using looping concepts
$result = mysql_query($query) or die(mysql_error());

while ($row = mysql_fetch_row($result))
{
     ?>

<form action="update_attendance.php?amid=<?php$row[0];?>&amname=<?php echo $row[1];?>" method="POST">
       <?php echo $row[0]; ?>
       <?php echo date('d-M-Y'); ?>
       <?php echo $row[1]; ?>
       <?php echo $row[6]; ?>

            <input type="radio" name="status" value="Present" checked="checked">Present    </input>
            <input type="radio" name="status" value="Permission">Permission</input>
            <input type="radio" name="status" value="Absent">Absent</input>

            <input type="submit" value="Update" class="btn btn-success btn-medium">

     </form>

A: Your code produces a lot of radio buttons named "status". You need to make every group of radio buttons to have unique name.
Probably one of your columns in table that you are querying on it is id column that is unique.
You can set the id (that maybe is $row[0] in this case) in the name of input like this:
<input type="radio" name="status[<?php echo $row[0] ?>]" value="a">a</input>
<input type="radio" name="status[<?php echo $row[0] ?>]" value="b">b</input>
<input type="radio" name="status[<?php echo $row[0] ?>]" value="c">c</input>

And in your php file after form submit check var_dump($_POST['status']). You will see that all values are available as an array.


text:
Q: Cannot convert value of type 'String?' to expected argument type 'Int' The error I get when I want to find the sum of the data in coredata.
The coredata "kisi.oyuncu1_puan" variable is defined as a string. It must be Int for addition. The conversion process did not happen.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "puanHucre", for: indexPath) as! PuanTableViewCell

    let kisi = oyuncuAd[indexPath.row]

    cell.kacinciElLabel.text = oyunElSayisi[indexPath.row]

    cell.oyuncu1PuanLabel.text = kisi.oyuncu1_puan
    cell.oyuncu2Puan.text = kisi.oyuncu2_puan
    cell.oyuncu3Puan.text = kisi.oyuncu3_puan
    cell.oyuncu4Puan.text = kisi.oyuncu4_puan

    var toplam = 0

    for x in [kisi.oyuncu1_puan] {

        toplam = toplam + x `***Cannot convert value of type 'String?' to expected argument type 'Int'***`
       print(toplam)

     }

    return cell

}

enter image description here

A: If cell.oyuncu1PuanLabel.text = kisi.oyuncu1_puan compiles then the for loop makes no sense because there is only one string.
If so replace the for loop with
if let kisi.oyuncu1_puan = kisi.oyuncu1_puan,
   let intValue = Int(kisi.oyuncu1_puan) {
     toplam += intValue
     print(toplam)
}

It safely unwraps the optional and converts - if possible - the String to Int.
And please, this is Swift. Snake_case variable names are unswifty.


text:
Q: btrace test the memory used by calling a function Using btrace, I want to test how much heap my function used, so I write:

Above the code is samples of btrace I used.
And operating my function twice I got two different results:

As the pic shows, the heaps cost differs:one is as much as twice as another one.

A: You can not tell how much memory is needed by a certain method by diffing the JVM heap usage before and after the method has been invoked. Too many things go on in the system while the method is executing and the numbers you are obtaining represent the memory allocated by the JVM from OS - the results will tell you nothing.
If you want something at least remotely usable you should take a heap dump before and after the method invocation (Sys.Memory.dumpHeap(fileName)) and use a heapwalker to diff those two. Still, you will get quite a lot of noise there but it is much better than relying on the memory allocated by OS.
The most precise memory tracking would consist of capturing allocation info of all new instances created during the method invocation and directly connected to that invocation - eg. created in the invoked method, in all methods invoked from the tracked one recursively and also in all runnables spawned anywhere in the tracked method call tree recursively. Getting this done might be a bit tricky but it is perfectly achievable by BTrace.


text:
Q: Converting cURL from Swiftype API to Parse.httpRequest I can't connect to the Swiftype API by converting their cURL to Parse.httpRequest method. I get either error 400 with info "document" object is missing or info to contact Swiftype.
Here is the cURL that works:
curl -XPOST 'https://api.swiftype.com/api/v1/engines/xxx/document_types/xxx/documents.json' \
-H 'Content-Type: application/json' \
-d '{
  "auth_token":"xxx",
  "document": {
    "external_id": "1",
    "fields": [
      {"name": "title", "value": "The Great Gatsby", "type": "string"},
      {"name": "author", "value": "F. Scott Fitzgerald", "type": "string"},
      {"name": "genre", "value": "fiction", "type": "enum"}
    ]
  }
}'

Note: I entered xxx to hide the actual key I am using.
Parse.Cloud.httpRequest({
        method: 'POST',
        url: 'https://xxx:@api.swiftype.com/api/v1/engines/xxx/document_types/xxx/documents.json',
        header: 'Content-Type: application/x-www-form-urlencoded',
        body:{'document': '{"external_id": "1","fields": []}'},
        success: function(httpResponse) {
            console.log(httpResponse.text);
            response.success(httpResponse.text);
        },
        error: function(httpResponse) {
            console.error('Request failed with response ' + httpResponse.text);
            response.error(httpResponse.text);
        }
    });

Update 1: After some trials and errors the following code authenticates but returns that the "document" parameter is missing
Parse.Cloud.httpRequest({
        method: 'POST',
        url: 'https://api.swiftype.com/api/v1/engines/xxx/document_types/xxx/documents.json',
        headers: 'content-type: application/json',
        params: {auth_token:'xxxx'},
        body: '{"document":{}}',
        success: function(httpResponse) {
            console.log(httpResponse.text);
            response.success(httpResponse.text);
        },
        error: function(httpResponse) {
            console.error('Request failed with response ' + httpResponse.text);
            response.error(httpResponse.text);
        }
    });

Update 2: This validates
Parse.Cloud.httpRequest({
        method: 'POST',
        url: 'https://api.swiftype.com/api/v1/engines/xxx/document_types/xxx/documents.json',
        headers: 'content-type: application/json',
        body:{auth_token:'xxx',
             document: '{}'},
        success: function(httpResponse) {
            console.log(httpResponse.text);
            response.success(httpResponse.text);
        },
        error: function(httpResponse) {
            console.error('Request failed with response ' + httpResponse.text);
            response.error(httpResponse.text);
        }
    });

But when I try to supply object into the document parameter it gives me the error "Can't form encode an Object".
Parse.Cloud.httpRequest({
        method: 'POST',
        url: 'https://api.swiftype.com/api/v1/engines/xxx/document_types/xxx/documents.json',
        headers: 'content-type: application/json',
        body:{auth_token:'xxx',
             document: {'external_id': '1'}},
        success: function(httpResponse) {
            console.log(httpResponse.text);
            response.success(httpResponse.text);
        },
        error: function(httpResponse) {
            console.error('Request failed with response ' + httpResponse.text);
            response.error(httpResponse.text);
        }
    });

I tried JSON.stringify(document) but that didn't work either by giving me an error from Swiftype "contact support".

A: Finally got it to work. The problem? Header needs to be a JSON object
Here is a fully functioning example:
var bodyData = {
    auth_token:"the_token",
    document: {
        external_id: "1",
        fields: [{name: "title", value: "The Great Gatsby", type: "string"}]
    }
};

    Parse.Cloud.httpRequest({
        method: 'POST',
        url: 'https://api.swiftype.com/api/v1/engines/xxx/document_types/xxx/documents.json',
        headers: {'Content-Type': 'application/json'},
        body: bodyData,
        success: function(httpResponse) {
            console.log(httpResponse.text);
            response.success();
        },
        error: function(httpResponse) {
            console.error('Request failed with response ' + httpResponse.text);
            response.error(httpResponse.text);
        }
    });


text:
Q: Unable to import a class in unittest This is probably a beginner question but I'm really pulling my hair out.
I have a very simple Python script "foo":
#!/usr/bin/env python

class Foo():
  def __init__(self):
    self.do_something()

  def do_something(self):
    print "foo"

def main():
  Foo()

if __name__ == '__main__':
  main()

Script works fine:
$ python foo.py
foo

I want to test the function "do_something" in unittest and I have this code:
#!/usr/bin/env python

import unittest
import foo
from foo import *

class TestFoo(unittest.TestCase):
  def test_foo(self):
    Foo()

def main():
  unittest.main()

if __name__ == "__main__":
  main()

If I run the tests, however, I get:
$ python pyunit/foo.py
E
======================================================================
ERROR: test_foo (__main__.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "pyunit/foo.py", line 9, in test_foo
    Foo()
NameError: global name 'Foo' is not defined

----------------------------------------------------------------------
Ran 1 test in 0.000s

FAILED (errors=1)

My project structure:
$ tree
.
├── foo.py
└── pyunit
    └── foo.py

I have been playing around with inspect, dir(), the Python debugger etc but I'm getting nowhere.
Although import foo and from foo import * both execute fine, and I see the function main imported from that file, the class itself Foo doesn't seem to be imported.
My objective, ultimately, is to then write unit tests for the functions in the class Foo.
What am I doing wrong?

A: You shouldn't use the same file name (foo.py) in your module. Change your test module to test_foo instead. Explicit is better than implicit.
When importing a module from a parent directory, you need to use from <parent_dir> import <module_name>, so in your case you should state from <parent_dir> import foo
You encounter the ImportError: No module named foo error becuase your module is not part of your sys.path.
Simplest way to import your local directory to python's lookup path:
import sys
sys.path.append('.')

Before the other import statements. This will append the project dir to the path. If you have multiple classes with the same name, you better use sys.path.insert(0, '.') to push the path into the first position

A: Python tests can be disturbing especially with relative imports.
So I got a work around.
First and Foremost: I suggest you install pytest which resolves the name in the sys.path that the test module is contained.. Install it by running pip install pytest.
For the relative import, you are trying to access the module outside the test package, to resolve this use the dot representation of imports, that is
from ..foo import Foo

Make sure you have removed import foo
Then try running the test pytest or pytest test_foo.py(if you are inside the pyunit folder)


text:
Q: How can I join a Lubuntu machine to a Windows 2008 domain? I have a Lubuntu machine and I want to join it to a Windows domain. I've read that you need to download extra software to make this work, does anybody have any suggestion??

A: You could use PowerBroker. Download it here: http://www.powerbrokeropen.org/powerbroker-open-edition-evaluation/
You can find complete instructions here: http://www.testools.net/2013/10/how-to-add-linux-lubuntu-machine-to.html


text:
Q: pandas how to draw graphs from a dataframe by group, but group number is uncertain I have a data frame like this:
import numpy as np
import pandas as pd

dataA = [["Abc", "8:05", 5], ["Abc", "8:10", 8], ["Abc", "8:15", 7],
    ["Abc","8:20", 4], ["Abc", "8:25", 2], ["Abc", "8:30", 2],
    ["Axy", "8:05", 15], ["Axy", "8:10", 6], ["Axy", "8:15", 1],
    ["Axy", "8:20", 11], ["Axy", "8:25", 12], ["Axy", "8:30", 7],
    ["Aeq", "8:05", 12], ["Aeq", "8:10", 8], ["Aeq", "8:15", 3],
    ["Aeq", "8:20", 7], ["Aeq", "8:25", 15], ["Aeq", "8:30", 14]]

dfa = pd.DataFrame(data = dataA, columns=["An", "coltime", "Val"])

in this sample it only 3 group :Abc  Axy Aeq
in real data ,colum An has uncetain group number, and how to draw line graph ?

A: Use DataFrame.pivot first:
df = dfa.pivot('coltime','An','Val')

df:

An
Abc
Aeq
Axy

coltime

8:05
5
12
15

8:10
8
8
6

8:15
7
3
1

8:20
4
7
11

8:25
2
15
12

8:30
2
14
7

df.plot()


text:
Q: Control de Excepciones Genexus Cordial Saludo,
Mi duda es la siguiente. Existe alguna funcionalidad dentro de Genexus que ayude a controlar las excepciones que se generen ya sea por temas de bases de datos o por temas de conectividad?, esto con el fin de controlar y enviar un mensaje mas sencillo a el usuario, ejemplo "Error en el sistema, consulte al administrador"
Gracias.
Ejemplo mensaje generado que genera inconformidad con los usuarios finales

A: Para controlar errores relacionados con la base de datos, existe la Rule Error_Handler.
Por ejemplo, en el procedure que quieras controlar, en las rules debes agregar:
error_handler('DBErrors');

Y en el source:
Sub 'DBErrors'
    Msg("Código error: " + &gxDBErr)
    Msg("Descripción: " + &gxDBTxt)
    Msg("Operación: " + &gxOper)
EndSub

Para controlar errores de excepciones, a partir de Genexus 16 Upgrade 7, existe la rule Exception_Handler.
En el procedure que quieras controlar, en las rules debes agregar:
Exception_Handler('Controlar_Errores');

Y en el source:
Sub 'Controlar_Errores'
    Msg("Type: " + &GXExceptionType)
    Msg("Details: " + &GXExceptionDetails)
    Msg("Stack: " + &GXExceptionStack)
EndSub

A: Hay las rules Error_Handler y Exception_Handler, pero no hay un tray catch para que el programa no finalize con error.

A: El Exception_Handler solo te permite llamar, por ejemplo, a un proc que te guarde un log con el error, pero se detiene la aplicación.
Lamentablemente vas a tener que insertar código hava o .Net para hacer un Catch/Try y envolver todo dentro de este.


text:
Q: facebook app all integrated in one page (no reloading) I am currently developing UI for a facebook app. Basically, the game is shown on the canvas page and it has navigation in a tab form.
What I need is that when a user clicks "friends" to invite people, the page will show over the game(the game is still in background, and running as it should be). So the page must not reload. To do this I placed the url of the friends requests in the src of an <iframe> and using jquery to hide/show the divs but the problem is the <iframe> will also contain the header, footer and all like facebook.com, but I just want the content because the user is already on facebook. Is there a better approach than what I'm doing? How would I accomplish this?
A good visual example is the navigation of "City of Wonders" facebook app.

A: You'll need to write a server side script that uses the facebook API to get a list of friends. Then you simply generate the HTML that is necessary to display and use this information.
Also, instead of using a an <iframe></iframe>you could just use a <div>, and use javascript to populate it's innerhtml (via ajax).


text:
Q: iPhone App crashing on startup on some devices (not all) I'm starting to get desperate and I need advice. Here's the situation:

*

*My recently updated App has started to crash directly on startup on some devices.

*It did not before the update.

*I cannot replicate this, although I have exactly the same device and software version.

*It does not matter if it is a fresh uninstall/install or update, it crashes anyways.

The crash logs do not tell me anything useful. Here is one, perhaps someone smarter than me knows what happened:
            Incident Identifier: 52C11BF9-A202-4ECC-B227-4A57899CB2E1
            CrashReporter Key:   3129de7e18ddccceb41bf4d0ad0465bc2e66df29
            Hardware Model:      iPhone3,1
            Process:         GT-BetApp [3364]
            Path:            /var/mobile/Applications/5E9BA5D7-4337-44CD-BDAB-CE653680EEB3/GT-BetApp.app/GT-BetApp
            Identifier:      GT-BetApp
            Version:         ??? (???)
            Code Type:       ARM (Native)
            Parent Process:  launchd [1]

            Date/Time:       2012-01-24 18:59:34.573 +0100
            OS Version:      iPhone OS 5.0.1 (9A405)
            Report Version:  104

            Exception Type:  EXC_CRASH (SIGABRT)
            Exception Codes: 0x00000000, 0x00000000
            Crashed Thread:  0

            Last Exception Backtrace:
            0   CoreFoundation                  0x344258bf __exceptionPreprocess + 163
            1   libobjc.A.dylib                 0x346751e5 objc_exception_throw + 33
            2   CoreFoundation                  0x344257b9 +[NSException raise:format:] + 1
            3   CoreFoundation                  0x344257db +[NSException raise:format:] + 35
            4   UIKit                           0x37a42747 -[UINib instantiateWithOwner:options:] + 1567
            5   UIKit                           0x37a43bb9 -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:] + 137
            6   UIKit                           0x3797ca45 -[UIApplication _loadMainNibFileNamed:bundle:] + 37
            7   UIKit                           0x37806227 -[UIApplication _loadMainInterfaceFile] + 223
            8   UIKit                           0x37800313 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 227
            9   UIKit                           0x377ce921 -[UIApplication handleEvent:withNewEvent:] + 1017
            10  UIKit                           0x377ce3bf -[UIApplication sendEvent:] + 55
            11  UIKit                           0x377cdd2d _UIApplicationHandleEvent + 5809
            12  GraphicsServices                0x30c00df3 PurpleEventCallback + 883
            13  CoreFoundation                  0x343f9553 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 39
            14  CoreFoundation                  0x343f94f5 __CFRunLoopDoSource1 + 141
            15  CoreFoundation                  0x343f8343 __CFRunLoopRun + 1371
            16  CoreFoundation                  0x3437b4dd CFRunLoopRunSpecific + 301
            17  CoreFoundation                  0x3437b3a5 CFRunLoopRunInMode + 105
            18  UIKit                           0x377ff457 -[UIApplication _run] + 551
            19  UIKit                           0x377fc743 UIApplicationMain + 1091
            20  GT-BetApp                       0x00002c79 main (main.m:15)
            21  GT-BetApp                       0x00002c44 0x1000 + 7236

            Thread 0 name:  Dispatch queue: com.apple.main-thread
            Thread 0 Crashed:
            0   libsystem_kernel.dylib          0x3634032c __pthread_kill + 8
            1   libsystem_c.dylib               0x33209f54 pthread_kill + 48
            2   libsystem_c.dylib               0x33202fe4 abort + 88
            3   libc++abi.dylib                 0x3384cf64 abort_message + 40
            4   libc++abi.dylib                 0x3384a346 _ZL17default_terminatev + 18
            5   libobjc.A.dylib                 0x346752dc _objc_terminate + 140
            6   libc++abi.dylib                 0x3384a3be _ZL19safe_handler_callerPFvvE + 70
            7   libc++abi.dylib                 0x3384a44a std::terminate() + 14
            8   libc++abi.dylib                 0x3384b81e __cxa_rethrow + 82
            9   libobjc.A.dylib                 0x3467522e objc_exception_rethrow + 6
            10  CoreFoundation                  0x3437b53e CFRunLoopRunSpecific + 398
            11  CoreFoundation                  0x3437b39e CFRunLoopRunInMode + 98
            12  UIKit                           0x377ff450 -[UIApplication _run] + 544
            13  UIKit                           0x377fc73c UIApplicationMain + 1084
            14  GT-BetApp                       0x00002c72 main (main.m:14)
            15  GT-BetApp                       0x00002c3c 0x1000 + 7228

            Thread 1 name:  Dispatch queue: com.apple.libdispatch-manager
            Thread 1:
            0   libsystem_kernel.dylib          0x363303b4 kevent + 24
            1   libdispatch.dylib               0x3705ae78 _dispatch_mgr_invoke + 708
            2   libdispatch.dylib               0x3705ab96 _dispatch_mgr_thread + 30

            Thread 2:
            0   libsystem_kernel.dylib          0x36340cd4 __workq_kernreturn + 8
            1   libsystem_c.dylib               0x331c630a _pthread_wqthread + 610
            2   libsystem_c.dylib               0x331c609c start_wqthread + 0

            Thread 3:
            0   libsystem_kernel.dylib          0x36340cd4 __workq_kernreturn + 8
            1   libsystem_c.dylib               0x331c630a _pthread_wqthread + 610
            2   libsystem_c.dylib               0x331c609c start_wqthread + 0

            Thread 4 name:  WebThread
            Thread 4:
            0   libsystem_kernel.dylib          0x36330010 mach_msg_trap + 20
            1   libsystem_kernel.dylib          0x36330206 mach_msg + 50
            2   CoreFoundation                  0x343f941c __CFRunLoopServiceMachPort + 120
            3   CoreFoundation                  0x343f8154 __CFRunLoopRun + 876
            4   CoreFoundation                  0x3437b4d6 CFRunLoopRunSpecific + 294
            5   CoreFoundation                  0x3437b39e CFRunLoopRunInMode + 98
            6   WebCore                         0x3684f128 _ZL12RunWebThreadPv + 396
            7   libsystem_c.dylib               0x331cbc16 _pthread_start + 314
            8   libsystem_c.dylib               0x331cbad0 thread_start + 0

            Thread 0 crashed with ARM Thread State:
                r0: 0x00000000    r1: 0x00000000      r2: 0x00000001      r3: 0x00000000
                r4: 0x00000006    r5: 0x3eaf3ce8      r6: 0x00000002      r7: 0x2fdffa60
                r8: 0x3fd97dec    r9: 0x3384da4a     r10: 0x0015d9e0     r11: 0x00156150
                ip: 0x00000148    sp: 0x2fdffa54      lr: 0x33209f5b      pc: 0x3634032c
              cpsr: 0x00000010

As the only reference to my code in the report is to main.m, here it is:
            #import <UIKit/UIKit.h>

            int main(int argc, char *argv[])
            {
                NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
                int retVal = UIApplicationMain(argc, argv, nil, nil);
                [pool release];
                return retVal;
            }

So here is my question: How can I determine the cause? What can I do to get more information on this crash (I can send versions to someone who experiences this crash)? What can I do to prevent it?
Any advice is much appreciated and thank you in advance!
UPDATE:
I found the solution and it was a silly mistake on my part.
The MainWindow.xib could not load when there was no localization for the device's language. I always thought, it would fall back English, but it did not (anymore).
In previous versions, this was never an issue. I don't know why this behavior changed.
Thanks for all the replies, you helped me search in the right direction!

A: The application is trying to read the main nib file, as specified in your app's Info.plist file.
In the plist file there is an entry like
NSMainNibFile -> MyMainWindow

which UIApplicationMain uses to load your initial view controller from. This file seems to be damaged. A common error is to use a custom class for a contained object and then change/remove that class later without changing the nib file.
To further understand the error it would be very helpful to know the description of the exception that's being raised. You'll find that in the console log.


text:
Q: Deploy a PHP project from Git to a server that does not have Git installed I need to find a method of deploying a PHP project stored in a git repo to a staging and production server that do not have git installed. Scripts I've found so far (ie Capistrano) require Git on the target server.
Unfortunately, my host does not allow this, and the only way so far is via standard FTP, with which I keep missing files. This makes for an unprofessional look.
I would like to be able to deploy from my local git repo, which will check the .git folder on the target to see which version is on there, then cause the target server to backup the current version and then overwrite it with only the changed files being pushed.
Preferably something in PHP with a web interface.
Not asking much am I ;)
Anyone out there got/seen anything like this?

A: You might be able to use something like Fuse to "mount" the production server as a local drive, and then as far as your copy of git is concerned it's a local operation.  Alternatively, rsync.

A: There are three git-ftp scripts which allow you to "push" a git repository to a FTP server.

*

*git-ftp (bash)

*git-ftp (python)

*PHPloy (php)

A: There's a tool call Dandelion that also does this. From what I can see, it's quite similar to git-ftp, BUT it also supports sftp and Amazon S3, which is handy if you don't want to change deploy tool just because you change server. It comes as a ruby gem, so really easy to install and get going.

A: I have done something like that using ssh2 and php.
first you need to clone the repo on the server. Once cloned, you can do git pull, checkout, etc from php using ssh2. the most practical way I found was doing.
git fetch;
git reset --hard commit_hash;

in order to get set the commit to the one expected.
To execute a php - ssh2 command (supposing you have ssh2 installed), you can use this method.
public static function SSHCommmand($command,$user,$ip) {
        $port = 22;

        if (!function_exists("ssh2_connect"))
            die("function ssh2_connect doesn't exist.");
        $result['debug'] .= " -Connect- 1";
        if (!($con = ssh2_connect($ip, $port, array('hostkey' => 'ssh-rsa')) )) {
            die("unable to establish connection.");
        } else {
            // try to authenticate with username root, password secretpassword
            if (!(ssh2_auth_pubkey_file($con, $user, '/home/' . $user . '/.ssh/deploy_rsa.pub', '/home/' . $user . '/.ssh/deploy_rsa'/* , 'secret' */))) {
                dir("fail: unable to authenticate.");
            } else {
                // allright, we're in!
                // execute a command
                if (!($stream = ssh2_exec($con, $command))) {
                    die("fail: unable to execute command.");
                } else {
                    // collect returning data from command
                    stream_set_blocking($stream, true);
                    $data = '';
                    while ($buf = fread($stream, 4096)) {
                        $data .= $buf;
                    }
                    fclose($stream);
                    return $data;
                }
            }
        }
    }

I'm using ssh-rsa key, the auth method might change. I'm aslo supposing that the keys are in '/home/' . $user . '/.ssh/deploy_rsa.pub' and '/home/' . $user . '/.ssh/deploy_rsa.
The other thing you might take into account is that to execute remote a remote git command, the command should be like:
_GIT_PATH.' --git-dir='.$path.'/.git --work-tree='.$path.' '.$command;

where $path is the toplevel of the working tree.
By using this and the Amazon Api, I've been able to deploy new code to several servers automatically and simultaneously.

A: I use Beanstalkapp.com, which is great. You can deploy via FTP or SFTP.


text:
Q: Why is an Unreachable code error in this sequence of code and not the latter? public String motorNoise() {
    String[] ignition={"vroom","pop","bang"};
    engineNoise=(int)(Math.random()*3);
    startEngine=ignition[engineNoise];
    if (engineNoise==2)
        System.out.println("This car needs a service");
    return startEngine;

    }

But this sequence causes an Unreachable code error. Why is the location of the If statement causing the method to fail?
public String motorNoise() {
    String[] ignition={"vroom","pop","bang"};
    engineNoise=(int)(Math.random()*3);
    startEngine=ignition[engineNoise];

    return startEngine;

    if (engineNoise==2)
        System.out.println("This car needs a service");

    }

A: Because in the first example, if you take all possible paths through the method, all statements will be executed.
However, in your second example, the if statement can never be executed:
public String motorNoise() {
    String[] ignition={"vroom","pop","bang"};
    engineNoise=(int)(Math.random()*3);
    startEngine=ignition[engineNoise];

    return startEngine; // <-- EXECUTED UNCONDITIONALLY, FUNCTION TERMINATES

    if (engineNoise==2)
        System.out.println("This car needs a service");
}

return startEngine is always executed unconditionally and immediately terminates execution of the function. There's no way for if (engineNoise == 2) to be executed.
NB. It always pays off to properly format and indent your code and to use braces. Your first example
public String motorNoise() {
    String[] ignition={"vroom","pop","bang"};
    engineNoise=(int)(Math.random()*3);
    startEngine=ignition[engineNoise];
    if (engineNoise==2)
        System.out.println("This car needs a service");
    return startEngine;
}

Is actually:
public String motorNoise() {
    String[] ignition={"vroom","pop","bang"};
    engineNoise=(int)(Math.random()*3);
    startEngine=ignition[engineNoise];
    if (engineNoise==2) {
        System.out.println("This car needs a service");
    }
    return startEngine;
}

so it is not only the order of lines, but the nesting of your code blocks that affects execution. Anything inside the body of an if-statement is only executed conditionally.


text:
Q: GROUP BY in elasticsearch I am trying to write a GROUP BY query in elastic search using version 5.2
I want to query the data and limit that down to those which have a particular 'tag'. In the case below. I want to select items which contain the word "FIY" in the title or content fields and then narrow that down so as to only search those documents which have the tags "FIY" and "Competition"
The query part is fine but I am struggling to limit it to the given tag.
So far I have got, but I am getting the error.
"reason": "[bool] query does not support [terms]",
GET advice-articles/_search
{
  "query": {
  "bool": {
  "must": [
    {
      "multi_match": {
        "query": "FIY",
        "fields": ["title", "content"]
      }
    }
  ], "filter": {
    "bool": {
      "terms": {
        "tags.tagName": [
           "competition"
        ]
      }
    }
  }
}
 }
}

an example index is
"_index": "advice-articles",
    "_type": "article",
    "_id": "1460",
    "_score": 4.3167734,
    "_source": {
      "id": "1460",
      "title": "Your top FIY tips",
      "content": "Fix It Yourself in April 2012.",
      "tags": [
        {
          "tagName": "Fix it yourself"
        },
        {
          "tagName": "customer tips"
        },
        {
          "tagName": "competition"
        }
      ]

the mappings I have are as follows
{
"advice-articles": {
"mappings": {
  "article": {
    "properties": {
      "content": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "tags": {
        "type": "nested",
        "properties": {
          "tagName": {
            "type": "text",
            "fields": {
              "raw": {
                "type": "keyword"
              }
            }
          }
        }
      }
    }
  }
}
}

}

A: Inside the filter you dont need to put bool.
POST newindex/test/1460333
{
  "title": "Your top FIY tips",
  "content": "Fix It Yourself in April 2012.",
  "tags": [
    {
      "tagName": "Fix it yourself"
    },
    {
      "tagName": "customer tips"
    },
    {
      "tagName": "shoud not return"
    }
  ]
}

POST newindex/test/1460
{
  "title": "Your top FIY tips",
  "content": "Fix It Yourself in April 2012.",
  "tags": [
    {
      "tagName": "Fix it yourself"
    },
    {
      "tagName": "customer tips"
    },
    {
      "tagName": "competition"
    }
  ]
}

Query:
GET newindex/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "multi_match": {
            "query": "FIY",
            "fields": [
              "title",
              "content"
            ]
          }
        }
      ],
      "filter": {
        "terms": {
          "tags.tagName": [
            "competition"
          ]
        }
      }
    }
  }
}

Result :
{
  "took": 4,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 1,
    "max_score": 0.2876821,
    "hits": [
      {
        "_index": "newindex",
        "_type": "test",
        "_id": "1460",
        "_score": 0.2876821,
        "_source": {
          "title": "Your top FIY tips",
          "content": "Fix It Yourself in April 2012.",
          "tags": [
            {
              "tagName": "Fix it yourself"
            },
            {
              "tagName": "customer tips"
            },
            {
              "tagName": "competition"
            }
          ]
        }
      }
    ]
  }
}

A: bool query built using one or more boolean clauses, each clause with a typed occurrence. The occurrence types are:
must, must_not, filter, should
GET _search
{
  "query": {
    "bool": {
      "must": [
        {
          "multi_match": {
            "query": "FIY",
            "fields": [
              "title",
              "content"
            ]
          }
        },
        {
          "nested": {
            "path": "tags",
            "query": {
              "terms": {
                "tags.tagName": [
                  "competition"
                ]
              }
            }
          }
        }
      ]
    }
  }
}

Here is how you can use a must clause for your query requirements.


text:
Q: How to get a top count for distinct records in Oracle? I have a table with a lot of records with some fields duplicated.  I want the most common of each of those duplications.
So, if my table has data like below:
 ID     Field1     Field2
  1      A          10
  2      A          12
  3      B          5
  4      A          10
  5      B          5
  6      A          10
  7      B          8
  8      B          5
  9      A          10

I can select distinct and get counts:
select distinct Field1, Field2, count(Field1)
from Table
group by Field1, Field2
order by Field1, count(Field1) desc

And that will give me
Field1    Field2     Count
A         10         4
A         12         1
B          5         3
B          8         1

However, I only want the records for each Field1 that have the highest count.  I've been fighting with rank() over partition and subqueries, but haven't found the correct syntax for using two fields for uniqueness and selecting the top record by count.  I've been searching, and I'm sure this has been asked, but I can't find it.
I want to get the following
Field1     Field2       (optional) Count
 A          10           4
 B           5           3

The goal is to look at a table that has just a little bit of incorrect data (linking between field1 and field2 wrong) and determine what it SHOULD be based on what it usually is.  I don't know how many bad records there are, so eliminating Count below a certain threshold would work, but seems a bit kludgy.
If it is better, I can make a temp table to put my distinct values into and then select from there, but it doesn't seem like that should be necessary.

A: I think this is what you're looking for:
select field1, field2, cnt from
(select field1, field2, cnt, rank() over (partition by field1 order by cnt desc) rnk
from (select distinct Field1, Field2, count(Field1) cnt
            from Table1
            group by Field1, Field2
            order by Field1, count(Field1) desc)
)
where rnk = 1;

SQL Fiddle: http://sqlfiddle.com/#!4/fe96d/3

A: It's a bit inelegant thanks to multiple layers of nested subqueries.  However it should be reasonably efficient.  And it should be reasonably easy to follow the steps in the SQL
SQL> ed
Wrote file afiedt.buf

  1  with x as (
  2    select 1 id, 'A' field1, 10 field2 from dual union all
  3    select 2, 'A', 12 from dual union all
  4    select 3, 'B', 5 from dual union all
  5    select 4, 'A', 10 from dual union all
  6    select 5, 'B', 5 from dual union all
  7    select 6, 'A', 10 from dual union all
  8    select 7, 'B', 8 from dual union all
  9    select 8, 'B', 5 from dual union all
 10    select 9, 'A', 10 from dual
 11  )
 12  select field1,
 13         field2,
 14         cnt
 15    from (select field1,
 16                 field2,
 17                 cnt,
 18                 rank() over (partition by field1
 19                                  order by cnt desc) rnk
 20           from (select field1, field2, count(*) cnt
 21                   from x
 22                  group by field1, field2))
 23*  where rnk = 1
SQL> /

F     FIELD2        CNT
- ---------- ----------
A         10          4
B          5          3

A: And a third approach ;)
select field1,
       field2,
       max_cnt
from (
  select field1,
         field2,
         cnt,
         max(cnt) over (partition by field1, field2) as max_cnt,
         row_number() over (partition by field1 order by cnt desc) as rn
  from (
      select field1,
             field2,
             count(*) over (partition by Field1, Field2) as cnt
      from idlist
  ) t1
) t2
where max_cnt = cnt
and rn = 1

SQLFiddle: http://sqlfiddle.com/#!4/8461f/1


text:
Q: sessoin mgt b/w action and interceptor in struts2 my application using tomcat7.x with struts 2.x and we are not able to get the same session (using ActionInvocation) in interceptor (which extends AbstractInterceptor) and action class (extends ActionSupport implements SessionAware,             ServletRequestAware, ServletResponseAware)
but same code is executing fine on tomcat 6.x


text:
Q: If we can store images (user images, product images, etc.) in databases (e.g. MongoDB), then why should we use cloudinary to store the images? If we can store images (user images, product images, etc.) in databases (e.g. MongoDB), then why should we use cloudinary to save images?

A: I think it could be compared to relation between RAM and HDD.
Of course, DB and cloudinary both are not volatile.
But if we focus on volume and speed,
the former has relatively small volume, high speed, high cost
the latter has relatively big volume, low speed, low cost.


text:
Q: Picasa API with oAuth 2.0 I want to create an app which gets all my albums from google+ account. I need to use picasa api with oauth 2.0 to accomplish this. Can anyone please guide me in right direction? Or suggest me any tutorial?

A: The best place to start is the documentation for the PicasaWeb GData API: https://developers.google.com/picasa-web/


text:
Q: Show hide in ionic framework I want a show hide function for my ionic app:
Below is what I have done so far, in xyz.html file:
<ion-item>

          {{part.fsp_partner_location}}

          {{part.fsp_partner_location}}

</ion-item>

my xyz.ts file
export class xyzpage{
public PtagClicked: boolean = false;

public onPtagClick(id) {
    {
     this.PtagClicked = !this.PtagClicked;
    }
  }
 public onPtagClick1(id) {
   {
    this.PtagClicked = false;

    }
  }
}

My problem is, I have dynamic numbers of  created on this page, and if I click on 1 item, it show/hide all item's data and not the one I clicked for.
I guess the problem will be solved if I can create dynamic values for ngIf, but I tried and not able to as I am new to ionic.
Any help will be appreciated.
I have latest IONIC installed.
Thanks

A: Use the Renderer2 to addClass, setStyle, or whatever you want, passing the element reference to your click event handler
Here a Demo
HTML
<ion-item *ngFor="let item of items">

{{item}}

  <button ion-button item-right (click)="onShow(text)">Show</button>
  <button ion-button color="danger" item-right (click)="onHide(text)">Hide</button>
</ion-item>

TS
import { Component, Renderer2 } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

public items: string[] = [
    "Item 1",
    "Item 2",
    "Item 3",
    "Item 4",
    "Item 5",
    "Item 6",
    "Item 7",
    "Item 8",
    "Item 9",
    "Item 10",
];

  public PtagClicked: boolean = false;

  constructor(public navCtrl: NavController, private render: Renderer2) { }

  public onShow(controlToShow) {
    this.render.setStyle(controlToShow, 'visibility', 'visible');
  }
  public onHide(controlToHide) {
    this.render.setStyle(controlToHide, 'visibility', 'hidden');
  }

}


text:
Q: How to only keep line that start with a character and the line after I have a FASTA file that has intentionally some sequences with wrong header (i.e absence of >) and some with good header. The file is well-formatted in the sense that the nucleotidic sequence is in one line.
Example :
2865958
AACTACTACAG
>hCoV-19/2832832
ACTCGGGGGG
28328332
ATTCCCCG
>hCoV-19/2789877
ACTCGGCCC

And I want to only keep the sequence with a correct header (i.e line that starts with >) like this :
>hCoV-19/2832832
ACTCGGGGGG
>hCoV-19/2789877
ACTCGGCCC

I've tried various method for it ( sed, grep, awk ) but no proper result :
awk '/^>/ { ok=index($0,"hCoV")!=0;} {if(ok) print;}' combined_v4.fa > combined_v5.fa

sed -n '/^>.*hCoV/,/^>/ {/^>.*hCoV/p ; /^>/! p}' combined_v4.fa > combined_v5.fa

grep -w ">" -A 1 combined_v4.fa > combined_v5.fa

Do you have an idea how to do that?

A: Tell grep too look for lines starting with >, and include the line following it:
grep -A1 --no-group-separator '^>' combined_v4.fa > combined_v5.fa

In case your version of grep does not support --no-group-separator, try this:
grep -A1 '^>' combined_v4.fa | grep -v '^--$' > combined_v5.fa

A: Here's one way with sed:
sed -n '/^>/!d;N;p' file

Note that if the last line of input begins with ">", this will not print it.
With awk:
awk 'prev {print prev ORS $0; prev=""} /^>/ {prev=$0}' file

Wait until the line after ">" to print the two lines. Insead of a regex, index() could be used:
awk 'prev {print prev ORS $0; prev=""} index($0,">")==1 {prev=$0}' file

^> is a regular expression to match a string that begins with ">". index($0,">") returns the starting position of the string ">", which must to be equal to one (...==1) if the record starts with it.
To make sure it also has "hCoV":
sed -n '/^>/!d;/hCoV/!d;N;p' file

awk 'prev {print prev ORS $0; prev=""} /^>/ && /hCoV/ {prev=$0}' file

A: With awk, you could do:
awk '/^>/ {c=2} c-- > 0' file

to print 2 lines when > is seen.

A: I propose this, using GNU sed:
# find the multiline pattern ^digits→ACGT
# and delete those lines
$ sed '/^[[:digit:]]\+$/,/^[ACGT]\+$/d' file
>hCoV-19/2832832
ACTCGGGGGG
>hCoV-19/2789877
ACTCGGCCC

A: With awk you can try:
awk 'f {print; f=0} /^>/ {print;f=1}' file
>hCoV-19/2832832
ACTCGGGGGG
>hCoV-19/2789877
ACTCGGCCC

*

*This excellent post can help you:

"Printing with sed or awk a line following a matching pattern": https://stackoverflow.com/questions/17908555/printing-with-sed-or-awk-a-line-following-a-matching-pattern


text:
Q: Memory upgrade to 8GB on unibody MacBook I bought the 13" unibody MacBook one month prior to it's upgrade to become the new improved 13" unibody MacBook Pro (with unopenable battery compartment, extra 3 hours of battery life, more color gammut, SD slot, firewire 800 port, and a new 8Gb memory limit).
My MacBook says it is limited to 4GB of DDR3 1066mhz memory, in 2 SO-DIMMs. But that was written back when you couldn't get 2 4GB SO-DIMMs. Now that you can get them, the very similar MacBook Pro is shipping with 4GB standard, and can be upgraded to 8GB. I've asked (Apple reps), and I'm repeatedly told that my model cannot be upgraded to 8. When I ask for the reason they alway say: "Because that's the published limit at the time your mac was built." I find this unconvincing. If they said: "Because the memory controller in the chipset is limited to 4GB, despite being seemingly identical to the memory controller in the same chipset newest MacBook model," then I'd just take their word for it.
Has anyone tried it, or found any research as to whether two 4GB DDR3 1066mhz SO-DIMMs can be installed in the unibody MacBook without FireWire?

A: Apple does limit the motherboard on certain models. For example 4GB of RAM was only available on the previous model White Macbook from the 3rd iteration. During each refresh they change the motherboard being used on the base model and this is generally the reason for the restriction.
The series you have definitely does not support 8GB as we went through the exercise at work after upgrading one of the newer models. It will only read the first 4GB of RAM.

A: The October 2009 unibody aluminium Macbooks supports 6GB (4+2) of RAM without any problems.  8GB doesn't work, though.

A: I just found that there IS a way to get the late 2008 macbooks up to 8GB RAM.  Apparently Apple released a firmware upgrade to fix a problem with the optical drive that also expanded the memory limit to 8GB.  Check out this posting on 9to5mac.
In case the link is down, here is a summary of what to do.
Check the Boot ROM Version in your System Profiler.

*

*MacBook Pros with a Model ID of MacBookPro5,1 should have a Boot ROM
  Version of MBP51.007E.B05.

*MacBooks with a Model ID of MacBook5,1
  should have  a Boot ROM version of MB51.007D.B03
Machines with other
  Model IDs are not affected and don't need an update. If your Boot ROM
  version does not match the numbers above, download the appropriate
  firmware updater for your model machine and install according to the
  instructions:

*

*For MacBook Pros (MacBookPro5,1) MacBook Pro EFI Firmware Update 1.8

*For MacBooks (MacBook5,1) MacBook EFI Firmware Update 1.4

A: I tested it with 2x4Gb DDR3 at 1333MHz. It didn't work. I don't know if it was because of the RAM speed which wasn't supported by the board or if the board doesn't support the amount of RAM at all.
By the way, I also tried putting only one of the DDR3 DIMMs and it did the same (the power light kept blinking and a beep every two seconds).
I haven't tried with a set of DIMMs at 1066MHz.
Also, I tried this 2x4Gb@1333MHz kit with an unibody aluminum 13" 2.26GHz MacBook Pro that uses the same memory as the white unibody macbook and it did work, and on the "About this Mac" dialog it said the RAM was working at 1333 MHz. I think since the MacBook Pro has the FireWire and SD interfaces, they might just be different boards and being the white MacBook a cheaper one with limited functions to 8 Gb OR this "different board" can't support a bus speed above 1066 and the RAM I tried can't work at that (not too feasible but this would keep my hope to be able to somehow upgrade to 8 Gb).
So, if you want to try the 8Gb upgrade, try it with a 1066MHz kit. If that works, then Apple has lied about the limit of this white MacBook. And if it doesn't, well... :(

A: 13" Aluminum MacBook can run two 4GB 1066mhz sticks for a total of 8 GB, for some reason it shows my speed as 1333mhz in the system profiler but that is not the speed of RAM that was installed, still, 8GB of RAM!

A: I've discovered through experimentation that my white 13" MacBook Unibody Late 2009 A1342 updated to OS X 10.11.6 (El Capitan) can now run 8 GB (2×4 GB) of DDR3 1333 SODIMM taken from my Lenovo Y570 laptop. I had previously been running it on 4 GB (2×2 GB DDR3 1066).
Here are some screenshots from the MacBook:

Hopefully any brand of 2×4 GB DDR3 1333 SODIMM will work for you, but I suspect that the OEM SODIMMs from when I bought the Lenovo new several years ago
are 1.5 V so I have my doubts that 1.35 V RAM will work.
Anyways, the old "4 GB 1066" rules for this particular MacBook are now gone. :)


text:
Q: Trying to convert a method from a string into an integer I'm writing a program that will count the amount of commas a string the user wrote contains.
I'm doing this by using another method in which the written string gets analyzed and the amount of commas are returned.
The problem I'm having is that I'm using a string, which needs to be  converted into an integer while sitting in a method, if that makes sense.
I know this can be done easier by just removing the method and writing the code in the 'main', but I don't want to since I will be expanding the program to also analyze the amount of full stops and the amount of semicolons in the written string.
Here's my code:
static void Main(string[] args)
    {
        Console.WriteLine("Enter a text:");
        string text = Console.ReadLine();
        int count = 0;
        count = NumberOfCommas(text);
        int kommaCount = count;

        int NumberOfCommas(int text1)
        {
            foreach (char letter in text)
            {
                if (letter == ',' )
                {
                    count++;
                }
            }
            return count;
        }
        Console.WriteLine("There's {0} comma(s) in your text.", kommaCount);
        Console.ReadKey();
    }

The error code I'm getting is "cannot convert from 'string' to 'int'. (the code is referencing to the 'text' part of this line: count = NumberOfCommas(text);)
I hope I explained it well, so my question is: how do I fix this?

A: Change the function signature to
 int NumberOfCommas(string text1) { ...

Also move this function out of the main function.

A: This is because of your method signature.
int NumberOfCommas(int text1) is looking for int text1 and it should be string text1.
Also, I'd like to point out two things.  First, you're using a local function.  There's nothing wrong with that and for what you're doing here it's fine.  I might suggest pulling it out since it really doesn't have any variables that require it to stay scoped to the method.
Another thing is your point about thinking others would prefer you to place it all in main but you said

I will be expanding the program

so you decided against it...
This is a good thing and the correct way of thinking / development so if someone tells you to put it in main for simplicity I tell you stick to your guns.  You're logic is right.

A: static void Main(string[] args)
{
    Console.WriteLine("Enter a text:");
    string text = Console.ReadLine();
    int count = 0;
    count = NumberOfCommas(text);

    Console.WriteLine("There's {0} comma(s) in your text.", count);
    Console.ReadKey();
}

int NumberOfCommas(String text1)
{
    int count;

        foreach (char letter in text1)
        {
            if (letter == ',' )
            {
                count++;
            }
        }
        return count;
}

There were several errors. Parameter data type to the function should be String, text in foreach loop should be text1. And you do not need to count variables.


text:
Q: Is $f(x,y) = \begin{cases}\frac {x^3+y^3}{x^2+y^2}&(x,y)\neq (0,0)\\0& (x,y)=(0,0)\end{cases}$ differentiable at origin? Consider $f(x,y) = \begin{cases}\frac {x^3+y^3}{x^2+y^2}&(x,y)\neq (0,0)\\0& (x,y)=(0,0)\end{cases}$. Does the total derivative at the origin exist?
I checked that the function is continuous at the origin but the partial derivatives are not continuous. So, I am not sure how to proceed.

A: Since $\frac{\partial f}{\partial x}(0,0)=\frac{\partial f}{\partial y}(0,0)=1$, if $f$ is differentiable at $(0,0)$, its derivative at $(0,0)$ is the linear map $(x,y)\mapsto x+y$. Now, since$$\frac{x^3+y^3}{x^2+y^2}-f(0,0)-(x+y)=\frac{-x^2y-xy^2}{x^2+y^2}=-\frac{xy(x+y)}{x^2+y^2},$$the question is: is it true that$$\lim_{(x,y)\to(0,0)}\frac{\left|-\frac{xy(x+y)}{x^2+y^2}\right|}{\|(x,y)\|}=0?$$No. See what happens whe $x=y$.


text:
Q: when I use USB drive, how can I achieve CACLS and ICALS functionality? I need to create a directory, which is not having the functionality of a normal one. I used the CACLS and ICACLS commands to make the directory as Secured and undeletable to others. It was worked successfully when the directory present in my system (NTFS). I created a directory in my USB drive, I used the same command, the out put is "The Cacls command can be run only on disk drives that use the NTFS file system."  Is any command to achieve this concept when the directory was present in USB Drive?

A: After the research, before execute the command format your USB drive in NTFS file system. Now this command work's well.


text:
Q: Looped code doesn't populate correct cells on certain sheets The code below works correctly on certain sheets. The code is supposed to calculate the percent change from 1990 to 2012 and from 2005 to 2012, and put the calculations on the 4th and 5th row from the last non-empty row, respectively. All the sheets are identical except for  3. The sheets that are different only have a different number of years of data. For some reason this causes the VBA script to put the percent change calculations in random rows below the correct location. Also, the VBA script doesn't work correctly on one of the identical sheets. I have no idea why.
Sub PercentChangeCalPIP()
Dim iRow As Long
Dim sheet_name As Range
For Each sheet_name In Sheets("WS").Range("I:I")
    If sheet_name.Value = "" Then
        Exit For
    Else
    With Sheets(sheet_name.Value)
'90-20## Percent Change
iRow = 14
Cell_val = .Cells(iRow, 1)
While Cell_val <> ""
    iRow = iRow + 3
    Cell_val = .Cells(iRow, 1)
Wend
.Cells(iRow + 3, 1) = "1990-2012"
'Column B,2

Cell_val = .Cells(iRow, 2)
While Cell_val <> ""
    iRow = iRow + 3
    Cell_val = .Cells(iRow, 2)
Wend
.Cells(iRow + 3, 2) = "=((B14/VLOOKUP(1990, A14:B46, 2,FALSE))-1)"
'Column C,3

Cell_val = .Cells(iRow, 3)
While Cell_val <> ""
    iRow = iRow + 3
    Cell_val = .Cells(iRow, 3)
Wend
.Cells(iRow + 3, 3) = "=((C14/VLOOKUP(1990, A14:C46, 3,FALSE))-1)"
'Column D,4

Cell_val = .Cells(iRow, 4)
While Cell_val <> ""
    iRow = iRow + 3
    Cell_val = .Cells(iRow, 4)
Wend
.Cells(iRow + 3, 4) = "=((D14/VLOOKUP(1990, A14:D46, 4,FALSE))-1)"
'Column E,5

Cell_val = .Cells(iRow, 5)
While Cell_val <> ""
    iRow = iRow + 3
    Cell_val = .Cells(iRow, 5)
Wend
.Cells(iRow + 3, 5) = "=((E14/VLOOKUP(1990, A14:E46, 5,FALSE))-1)"
'05-20## Percent Changes
Cell_val = .Cells(iRow, 1)
While Cell_val <> ""
    iRow = iRow + 4
    Cell_val = .Cells(iRow, 1)
Wend
.Cells(iRow + 4, 1) = "2005-2012"
'Column B,2

Cell_val = .Cells(iRow, 2)
While Cell_val <> ""
    iRow = iRow + 4
    Cell_val = .Cells(iRow, 2)
Wend
.Cells(iRow + 4, 2) = "=((B14/VLOOKUP(2005, A14:B46, 2,FALSE))-1)"
'Column C,3

Cell_val = .Cells(iRow, 3)
While Cell_val <> ""
    iRow = iRow + 4
    Cell_val = .Cells(iRow, 3)
Wend
.Cells(iRow + 4, 3) = "=((C14/VLOOKUP(2005, A14:C46, 3,FALSE))-1)"
'Column D,4

Cell_val = .Cells(iRow, 4)
While Cell_val <> ""
    iRow = iRow + 4
    Cell_val = .Cells(iRow, 4)
Wend
.Cells(iRow + 4, 4) = "=((D14/VLOOKUP(2005, A14:D46, 4,FALSE))-1)"
'Column E,5

Cell_val = .Cells(iRow, 5)
While Cell_val <> ""
    iRow = iRow + 4
    Cell_val = .Cells(iRow, 5)
Wend
.Cells(iRow + 4, 5) = "=((E14/VLOOKUP(2005, A14:E46, 5,FALSE))-1)"
End With
        End If
    Next sheet_name
End Sub

Any thoughts as to what might be the problem?

A:  While Cell_val <> ""
 iRow = iRow + 3

Instead of jumping rows by increment of 3, why not to try with 1 if there are consecutive non-empty cells in the column.
 iRow = iRow + 1

Maybe you have your own intention here that I am missing out. But using interval jumps to select right row seems to be a little bit odd to me.


text:
Q: Django datatime field I'm reading the PostgreSQL documentation and I see that Postgres does not have a datatime data type but when I run ./manage.py sqlmigrate myapp 0001_initial Django actually generates a datetime field:
CREATE TABLE "myapp_event" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "start" datetime NOT NULL);

So I'm a bit confused. Is datetime suppose to be timestamp?
UPDATE:
I didn't realize I was using a different setting file with SQLite database. Hope this mistake may be useful to someone else.
In PostgreSQL it looks like this:
CREATE TABLE "myapp_event" ("id" serial NOT NULL PRIMARY KEY, "start" timestamp with time zone NOT NULL);

So datetime in SQLite is timestamp with time zone in PostgreSQL.

A: Postgres does not have datetime data type indeed. Neither it has AUTOINCREMENT attribute. Django must be showing you those itself, translating Pstgres timestamp to datetime and SERIAL to AUTOINCREMENT.
PS SERIAL is not a datatype itself either.
here's I change your statement to Postgres one:
t=# CREATE TABLE "myapp_event" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "start" datetime NOT NULL);
ERROR:  syntax error at or near "AUTOINCREMENT"
LINE 1: ... "myapp_event" ("id" integer NOT NULL PRIMARY KEY AUTOINCREM...
                                                             ^
t=# CREATE TABLE "myapp_event" ("id" SERIAL PRIMARY KEY, "start" datetime NOT NULL);
ERROR:  type "datetime" does not exist
LINE 1: ...E "myapp_event" ("id" SERIAL PRIMARY KEY, "start" datetime N...
                                                             ^
t=# CREATE TABLE "myapp_event" ("id" SERIAL PRIMARY KEY, "start" timestamp NOT NULL);
CREATE TABLE


text:
Q: Eclipse is insisting that project name must be a lowercase while not letting me progress to the next step Name(MyGraphics) must start with lowercase
"next", "finish" links are grayed out when same(myGraphics) starts with lowercase


text:
Q: Proof Verification: Using Heine-Borel property to show continuous function maps compact set to compact set. Let $f : M \mapsto N$ be continuous. Consider a compact $K \subseteq M$.
Assume as given: $\forall B \subseteq N$ open, $f^{-1}(B)$ is open in $M$.

*

*Consider an open cover of $f(K)$, call it $A_i$ for $i \in I$.

*Then, $B_i$ is an open cover of $K$, where $B_i = \{x \in M: f(x) \in A_i \}$

*There exists a finite subcover of $K$, call it $B_{n_1}, ..., B_{n_k}$

*Then, $A_{n_1}, ..., A_{n_k}$ is a finite subcover of $f(K)$
Just need to verify this proof, in particular, I am concerned if $(2)$ and $(4)$ need more details.

A: *

*What do you mean by calling the open cover $A_i$?
I would start 'Let $U$ be an open cover of $f(K)$.'

*Yes, more details would be welcome. Why is what you denote $B_i$ an open cover of $K$? Answer: for every $x \in K$, $f(x)$ belongs to some $u \in U$.

*Fine.

*Again, more details would be helpful. Answer: for every $y \in f(K)$ we have $y = f(x)$ where $x \in K$. Then $x \in f^{-1}(U_i)$ for some $i$ and so $y = f(x) \in U_i$.

A very good start to the proof nonetheless. If I were grading I would probably award most of the points, but not all, for the omission of the above.

A: It seems good to me.
(2) works out because $B_i = f^{-1}(A_i)$ is open for all $i$ since $f$ is continuous, and certainly covers $K$, so it is indeed an open cover as you stated.
In a similar fashion for statement (4), $A_{n_1}, \dots, A_{n_k}$ is a finite sub cover since for any $y \in f(K), \; \exists i : x \in B_{n_i} $ (Since $\{B\}_{i \in I}$ is an open cover for $K$) so that $ f(x) =y \in A_{n_i}$ by construction.


text:
Q: How to show failure message on signup using MEAN stack I am developing an SPA which use passport authentication to do the login and signup proccess. The thing is that everything works fine, I can even show a success notification, but I can't find out a way to show an error notification in case the user makes a bad operation.
Here is my code for signup in passport-init:
 passport.use('signup', new LocalStrategy({
    passReqToCallback : true
},
function(req, username, password, done){
  var email = req.body.email;
  User.findOne({$or:
    [
      {username: username},
      {email: email}
    ]
  }, function(err, user){
      if(err){
          return done(err, false);
      }

     if(user) {
          console.log('username or email already taken '+req.body.username);
          return done(null, false, {message: 'Username or email already taken.'});
      }

      user = new User();

      if(req.body.password===req.body.username || req.body.password===req.body.fullname
          || req.body.password===req.body.email){
         console.log('The password can not be equals to your fullname'+
            ', username or email. Try another password.');
          return done(null, false, {message: 'The password can not be equals to your fullname'+
            ', username or email. Try another password.'});
      }

Then if non of this cases happens the method returns no errors with the user data.
Here is the route code to pass results to angular:
  router.get('/failure', function(req, res){
    res.send({state: 'failure', user: null, message: "Invalid username or password"});
});

router.post('/signup', passport.authenticate('signup',{
    successRedirect: '/auth/success',
    failureRedirect: '/auth/failure',
    failureFlash: true
}));

And finally I got this angular in order to call and get a response:
$scope.register = function(){
    $http.post('/auth/signup', $scope.user).then(

    function(data){
        $rootScope.authenticated = true;
        $rootScope.current_user = data.user.username;
        $rootScope.signUp = true;
    },

      function(data, status){
        console.log(status);
      }
    );
};

This is it. Ofcourse the angular code is inside a controller. I just began learning to build MEAN stack applications so, any help will be appreciated.

A: If there's a custom error/ custom logic you should send an error back to the client:
if(user)
return done({error:'userAlreadyTaken'},false);

the same for the other conditions you have in your code.


text:
Q: Why does the image file size change so much when saving from PS? I have a PNG which is 1.27mb.
If I open it in Paint and save it out as a JPG, it becomes 943kb.
If I then take that JPG into Photoshop and save it over the same JPG, with the quality set to 12, it save out at 1.73mb, higher than the original PNG!
If I take the original PNG into PS and save it out as a JPG, it's 1.82mb.
What's happening here?

A: It could be that PS is using different compression techniques for both PNG and JPG. It is up to the program to decide how to implement the PNG and JPG compression techniques.


text:
Q: Golang, variable with type from string Is it possible to create variable with type from string?
Example:
 I have two types:
type FirstType struct {
    ...
}

type SecondType struct {
    ...
}

// also I have a string variable
var1 := "Second"

I want to create variable with type -  String value + "Type":
var variable = []var1+"Type" // slice of "SecondType"

Expected result is like in this case:
var variable = []SecondType

Thanks!

A: This is not possible. Go does not provide functionality to create variables of types that are not known statically. The type of a variable is always known statically. Consider using interfaces instead.


text:
Q: Only show line items containing specific strings in liquid I have the following table:

    {% for lineItem in lineItems %}

      {% assign cleanDesc = lineItem.description | strip %}

        {{lineItem.description}}

            {% if cleanDesc == "VAT" %}
            Standard Rate
            {% elsif cleanDesc == "VAT Gear exempt"%}
            25% Zero Rate, 75% Standard Rate
            {% else %}
            {% endif %}

        £{{lineItem.tax_only_cost | with_delimiter, precision: 2}}

    {% endfor %}

I wish to only display in this table items with lineItem.description == "VAT" or "VAT Gear exempt".
I can get this to work for "VAT", but cannot get it to work for "VAT Gear exempt".
Please could you advise how I can not allow
 rows to be created for any line items, except for descriptions "VAT" and "VAT Gear exempt".

A: Dont strip description, just use "contains" operator like:
{% if lineItem.description contains "VAT" or if lineItem.description contains "VAT Gear exento" %}

{% endif%}


text:
Q: Issue with npm start and compiling in react so i have been assigned to maintain a react website. i am facing some problem with running the project.. npm start takes approx 4-5mins and likewise every changes saved takes upto 2-3mins(which is toooooo long). I am unable to figure out where is the issue. Maybe in webpack configuration or something else. Code details are listed bellow:
webpack.config.js
var path = require('path');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
var webpack = require('webpack');

module.exports = {
    entry: './src/index.jsx',
    output: {
        path: path.resolve('dist'),
        filename: 'bundle.js',
    },
    resolve: {
        extensions: ['.js', '.jsx', '.css'],
    },
    module: {
        loaders: [
            {
                test: /\.jsx?$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel-loader',
                query: {
                    presets: ['react', 'es2015', 'stage-3']
                }
            },
            { test: /\.css$/, loader: "style-loader!css-loader" },
            {
                test: /\.less$/,
                loader: 'style-loader!css-loader!less-loader'// compiles Less to CSS
            },
            {
                test: /\.(png|jpg|)$/,
                loader: 'url-loader?limit=200000'
            }
        ]
    },
    plugins: [new HtmlWebpackPlugin({
        template: './src/index.html',
        filename: 'index.html',
        inject: 'body'
    }), new CopyWebpackPlugin([ { from: 'src/assets', to: 'assets' } ]),
        new webpack.optimize.AggressiveMergingPlugin(),
        new webpack.optimize.OccurrenceOrderPlugin(),
        new webpack.optimize.DedupePlugin(),
        new webpack.optimize.UglifyJsPlugin({
            mangle: true,
            // compress: {
            //     warnings: false, // Suppress uglification warnings
            //     pure_getters: true,
            //     unsafe: true,
            //     unsafe_comps: true,
            //     screw_ie8: true,
            //     conditionals: true,
            //     unused: true,
            //     comparisons: true,
            //     sequences: true,
            //     dead_code: true,
            //     evaluate: true,
            //     if_return: true,
            //     join_vars: true
            // },
            output: {
                comments: false,
            },
            exclude: [/\.min\.js$/gi] // skip pre-minified libs
        }),
    ],
    devServer: {
        historyApiFallback: true
    },
    externals: {
        // global app config object
        config: JSON.stringify({
            // apiUrl: 'http://0.0.0.0:8102',
            siteUrl: 'http://localhost:ls3003',
            apiUrl: 'https://api.xyz.com',
            // siteUrl: 'https://dashboard.mltrons.com',
        })
    }
}

Package.json:
  "name": "react-redux-registration-login-example",
  "version": "1.0.0",
  "repository": {
    "type": "git",
    "url": "https://github.com/cornflourblue/react-redux-registration-login-example.git"
  },
  "license": "MIT",
  "scripts": {
    "start": "webpack-dev-server --host 0.0.0.0 --port 3000 --disableHostCheck",
    "build": "webpack"
  },
  "dependencies": {
    "@amcharts/amcharts4": "^4.2.3",
    "@data-ui/histogram": "0.0.75",
    "@material-ui/core": "^3.9.0",
    "@material-ui/icons": "^3.0.2",
    "@projectstorm/react-diagrams": "^6.0.1-beta.5",
    "chart.js": "^2.7.3",
    "chartjs-plugin-zoom": "^0.6.6",
    "classnames": "^2.2.6",
    "css-loader": "^2.1.0",
    "deni-react-treeview": "^0.2.15",
    "events": "^3.0.0",
    "formik": "^1.4.1",
    "history": "^4.6.3",
    "jquery": "^3.3.1",
    "material-ui-popup-state": "^1.0.2",
    "moment": "^2.23.0",
    "pusher-js": "^4.3.1",
    "rc-steps": "^3.3.1",
    "react": "^16.0.0",
    "react-addons-css-transition-group": "^15.6.2",
    "react-chartjs-2": "^2.7.4",
    "react-circular-progressbar": "^1.0.0",
    "react-craft-ai-decision-tree": "0.0.26",
    "react-datetime-picker": "^2.1.1",
    "react-dom": "^16.0.0",
    "react-dropzone": "^8.0.3",
    "react-facebook-login": "^4.1.1",
    "react-ga": "^2.5.7",
    "react-google-login": "^4.0.1",
    "react-heatmap-grid": "^0.7.3",
    "react-highlight": "^0.12.0",
    "react-joyride": "^2.0.5",
    "react-linkedin-login-oauth2": "^1.0.6",
    "react-paginate": "^6.2.1",
    "react-redux": "^5.0.5",
    "react-router-dom": "^4.1.2",
    "react-table": "^6.8.6",
    "recharts": "^1.8.5",
    "redux": "^3.7.2",
    "redux-logger": "^3.0.6",
    "redux-thunk": "^2.2.0",
    "style-loader": "^0.23.1",
    "web-wechat-login": "^1.0.9",
    "yup": "^0.26.6"
  },
  "devDependencies": {
    "babel-core": "^6.21.0",
    "babel-loader": "^7.1.2",
    "babel-preset-es2015": "^6.18.0",
    "babel-preset-react": "^6.16.0",
    "babel-preset-stage-3": "^6.24.1",
    "copy-webpack-plugin": "^4.6.0",
    "file-loader": "^3.0.1",
    "html-webpack-plugin": "^2.26.0",
    "less": "^3.9.0",
    "less-loader": "^4.1.0",
    "path": "^0.12.7",
    "url-loader": "^1.1.2",
    "webpack": "3.6.0",
    "webpack-cli": "^3.1.2",
    "webpack-dev-server": "2.11.3"
  }
}

src/index.html:

    <base href="/" />
    <meta charset="UTF-8">
    <meta
            name="viewport"
            content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
    >
    <title>dashboard</title>
    <link rel="shortcut icon" href="assets/favicon.ico">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500">

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css">

src/index.jsx:
import { render } from 'react-dom';
import { Provider } from 'react-redux';

import { store } from './_helpers';
import { App } from './App';

render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('app')
);

If u need anything else please let me know.thanks

A: You should add all of webpack.optimize plugins only in production. Turn it off in development and it will take a little less time.
if (PRODUCTION) {
  config.plugins.push(
  ...your optimize plugins here
  );
}


text:
Q: keep track of random numbers in java How do I keep tracking the value of randomNumber  and then use it else where. In the code below every time I click the mouse I get random number between 0 and 10.
If I click 3 times and I get for example the values 1,6 and 7 how do I keep track of these 3 values and use them somewhere else. I want to store them in variable like, int firstClick=?;,int secondClick=?;and int thirdClick=?; how do i do that.
void mousePressed(){
int randomNumber= int(random(11));
System.out.println(randomNumber);
}

A: Use an ArrayList somewhere in your class:
public class MyClass {

    private ArrayList<Integer> randomNumbers = new ArrayList<>();

    public void mousePressed() {
        int randomNumber= int(random(11));
        randomNumbers.add(randomNumber);
        System.out.println(randomNumber);
    }

    public void listNumbers() {
        for (Integer number : randomNumbers) {
            System.out.println(number);
        }
    }

}

This way, you can keep track of any number of mouse clicks and the numbers generated by them. You don't have to assign each individual number to a specific int variable.

A: step 1 : create an arraylist of integers
step 2 : generate random number
step 3 : store random no in arraylist
step 4 : compare this arraylist after generating new random no
step 5 : if new random no doesn't exist in arraylist , use it , store this no in arraylist
step 6 : if random no does exist in arraylist , generate another random no
//global variable
List<Integer> randomNumberArray = new ArrayList<Integer>();

then
void mousePressed()

    {
        for (int i = 0; i < 5; i++)
        {
            int temp = generateRandomNumber();
            if (!randomNumberArray.contains(temp))
            {
                randomNumberArray.add(temp);
            }
        }
        System.out.println(randomNumberArray);
    }

    public int generateRandomNumber()
    {
        Random randomNumber = new Random();
        return randomNumber.nextInt(20);
    }

or you can simply use a Set
void mousePressed()

    {
       Set<Integer> mySet = new HashSet<Integer>();
    for(int i=0;i<5;i++)
    {
        int temp = generateRandomNumber();
        //System.out.println(temp);
        mySet.add(temp);
    }
    System.out.println(mySet);
    }

A: final List<Integer> randomNumbers= new ArrayList<Integer>();
for (int i=0;i<3;i++){
   randomNumbers.add(random(11));
}
// get first one
int i = randomNumbers.get(0);

A: This will require a variable with a scope beyond the method you are dealing with.  Some options are:
// Have the random number be the return value of the method:
public int mousePressed() { return int(random(11)); }

// Have the random number be assigned to a class scoped variable:
static int someN;
public void mousePressed() { someN = int(random(11)); }

Obviously this will need to be extended to have three (or however many) values assigned/returned.  The Object ArrayList<Integer> could come in handy here.