text:
Q: "The last two nights in Las Vegas (have been/were?) wonderful"
"The last two nights in Las Vegas have been wonderful."

Is this sentence grammatically correct? I think it's better to use past simple as the last two nights are finished now.

A: If the speaker of the sentence is no longer in Las Vegas,  then he would use the past simple. This is because the events the last two nights in Las Vegas are indeed completely in the past. They do not extend to and include the moment of speaking.
If the speaker is still in Las Vegas and uses the present perfect, which is the most natural scenario,   it means he is including the moment of speaking in the time period of the last two nights. In other words, the last two nights are still in progress if  the present perfect is used.
If the speaker considers the last two nights to be over and not part of the moment of speaking, he would use the past simple. This could be done  to stress that the last two nights are completely over and done with. Example: it's the third day,  and Jill wants to break up with Jack; she could say The last two nights in Las Vegas were wonderful,  but I'm still breaking up with you (here on this third day in Las  Vegas). This example is a little forced  but it just shows that the expression the last two nights is usually going to take the present perfect if a location is given and the speaker is still at that location.

A: You can think of "the last two nights" as two separate spans of time that began at about 8:00 p.m. on each night and ended when you went to sleep each night, or you can think of "the last two nights" as part of a series of nights that started two nights ago and continues up to the present.
The choice between simple past and present perfect leads your listener to think of the last two nights the first way or the second way, respectively. The present perfect usually leads the listener to understand the past events as part of a process of interest that is still continuing (or just started or just finished). That process is not necessarily mentioned in the sentence, as the examples below will illustrate.
Talking about a vacation: during and after
Suppose that Valerie thinks of Las Vegas as a den of sleaze and organized crime, and didn't want to spend her vacation there, but she reluctantly agreed to go on a four-day trip to Las Vegas with her friend Joanne. On the morning of the fourth day, they have this conversation:

Joanne: So, have you enjoyed the City so far?
  Valerie: I must admit, the last two nights in Las Vegas have been wonderful. But there are still two more days to go.

Valerie uses the present perfect here to suggest that she wants Joanne to understand the last two nights as a time interval that continues to the present and as part of something continuing beyond the present: the vacation. Notice that nobody ever said "vacation". In the situation, the present perfect is enough to suggest it.
Now suppose that Joanne and Valerie are talking about the vacation 20 years later—long after the two nights and long after the end of the vacation:

Joanne: So, how did you enjoy our summer vacation in 1997?
  Valerie: The first two nights in Las Vegas were wonderful. The last two nights, though, were a disaster. I lost every cent I had in a long run of bad luck at the blackjack tables.

Valerie uses the simple past because the story in which those nights are events is over. The vacation is over, and you're talking about the events in connection with the vacation, so the events that are part of the vacation go in the simple past tense.
Distinguishing location and time
By the way, people wouldn't ordinarily say "The last two nights in Las Vegas have been wonderful" except to distinguish them from nights at other locations. This conversation is a little more plausible:

Vito the Boss of Many Casinos: So, how's the take this week?
  Joe the Manager of the Casinos in Tahoe and Las Vegas: Tahoe has been in a dry spell: we barely broke even all week. But the last two nights in Las Vegas have been wonderful: we made $400,000 both nights.

By using the present perfect, Joe suggests that he thinks the high revenue might continue. If he had used the simple past, then he would have reported the same facts without suggesting anything about whether the high revenue will continue.
Also, this conversation, on the fourth morning, is more plausible:

Joanne: So, have you enjoyed Las Vegas so far?
  Valerie: Well, the first night was a disaster, but the last two nights have been wonderful.

The first night is over, and it doesn't extend to the present, so Valerie talks about it in the simple past. She distinguishes it from the present situation, which she frames as part of a span of time that began two days ago. Valerie doesn't mention Las Vegas because there's no distinction to make about the last two nights regarding location.


text:
Q: java.lang.ClassCastException: java.lang.String cannot be cast to com.fastdata.persistence.PersistenceService trait PersistenceService  {
    def setData(x: Any): Unit
    def getData(x:Any) : Any
}

object ConfigurationLoader{
    var p_service: PersistenceService = null
    val persistence_db = component_props.getProperty("persistence_db")
    p_service = (persistence_db+"Service").asInstanceOf[PersistenceService]
}

How i can cast at runtime?

A: We can do by using reflection like below
Class.forName("fully qualified class name").newInstance()

redpajama_set_name: RedPajamaStackExchange


text:
Q: combine two array each element and append to one array I have two array like below. I need to combine two array each data and append to one array. The example are :
var d1 = ["1", "2", "3", "4", "5"]
var d2 = ["A", "B", "C", "D", "E"]
var d3  = [String]()

//O/P needed : ["1-A","2-B","3-C","4-D","5-E"]

Any help would be great.
Thanks

A: Use a combination of zip(_:_:) and map(_:) over d1 and d2 like so,
let d3 = zip(d1, d2).map({ $0.0 + "-" + $0.1})

print(d3) //["1-A", "2-B", "3-C", "4-D", "5-E"]

In case any one of the arrays have extra elements, those extra ones will be ignored while performing the zip operation.

A: var d1 = ["1", "2", "3", "4", "5"]
var d2 = ["A", "B", "C", "D", "E"]
var d3  = [String]()

//O/P needed : ["1-A","2-B","3-C","4-D","5-E"]
// works for diff length of d2
func mergArray(firstArray: [String], secondArray: [String]) -> [String] {
    for (index,val) in d1.enumerated() {
       guard index < d2.count else {
       d3.append(val)
       return d3
   }
   d3.append(val + "-" + d2[index])
}
   return d3
}

print(mergArray(firstArray: d1, secondArray: d2))

A: Do it like -
for i in 0..< d1.count {
    d3.append(d1[i] + "-" + d2[i])
}
print(d3)

You will have your desire result.


text:
Q: Confusion polarization of circuit elements? Imagine you have the following circuit. The  thing is I've been having a little trouble with voltage sign convention and polarization.
Assuming that i(t) is a current that enters the node of the inductor (following a clockwise direction on the loop), then the main equations  we can write  are:
v0 + v1 = L * d(Il)/dt
i + gm *  v1 = Il
v1 = iR

Now assuming that i(t) is a current that exits the node of the inductor (following a anti-clockwise direction on the loop), then the main equations  we can write  are:
v0 + v1 = L * d(Il)/dt
i + Il =  gm *  v1
v1 = iR

They are almost the same equations, but if you try to get the differential equation that shows  the behaviour of Il, there is a symbol that changes. Which one is correct?
How I should take into acount the voltage rises/falls? If I take the Clockwise direction, for example, should I take as a fall in voltage
when the current passes through a passive component and a rise when it passes through a battery? (but in the circuit you could see, that the polarization of R with respect to v1 is inverted if you choose this direction)
If I stick to this, should  the v1 = iR equation in the first case be -v1 = iR because the current leaves through the negative pole (fall of potential)?


text:
Q: Execute interval through Spring Boot JPA + Postgresql + H2 I am trying to create a JPA Repository Query in Spring Boot.

*

*I am using spring-data-jpa 2.1.5, spring-boot 2.1.3, postgresql driver 42.2.5, h2database 1.4.200, Java 1.8

My conditions are :

*

*I have to use PostgreSQL for production and H2 for unit (integration) tests.

*I should not use native query (postgres x h2).

*I need to get customer records from customer's table

*But only the Customers that registered at least 24 hours before the current date.

*So I mean DB date. I cannot use Java to pass any parameter into the query.

My customer Entity looks like this :
@Entity
@Table(name = "customer")
public class Customer {

   @Id
   @Column(name = "cust_no")
   private int custNo;

   @Temporal(TemporalType.TIMESTAMP)
   @Column(name = "registration_timestamp")
   private Date registrationTimeStamp;
}

And my customer repository will be like:
@Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer> {

   @Query(value = "SELECT c FROM Customer c WHERE c.registrationTimeStamp <= SOMETHING")
   List<Customer> getCustomers24HoursAfterRegistration();

}

I really don't know what should I put that place refers SOMETHING. I think I can use something like CURRENT_TIMESTAMP - SOMETHING_REFERS_24_HOURS.
All the examples are about the nativeQuery. Or passing parameter from Java. I can't use INTERVAL because Spring JPA doesnt support.
I can not believe that such a simple process is not in Spring JPA which supports both two RDBMS (PostgreSql and H2). And I want to ask is there any way to do that?

A: If you don`t wanna you native query then you have to use Query methods
you can do something like
 List<User> findByCreatedAtGreaterThanEqual(Data createdAt);

For more, you can see ( https://www.baeldung.com/spring-data-jpa-query-by-date, https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods )


text:
Q: Kibana array hierarchy in pie chart I got logs with arrays in Elastic Index.
each cell in the array represents region.
The higher the index, the higher resolution of the region.
For Example:
[Earth,USA,NYS,NYC,Manhattan]
I would like to visualize the places in a pie chart, so each level corresponds to the matched index in the array
EXAMPLE

A: You can't do that with field of type array. I recommend you to create field name region , field name subregion, and so on,then create visualisation with sub bucket and you will get what you want


text:
Q: proxy_pass based on headers without using if condition I'm looking for a way to reroute all requests that have set an account-id in the HTTP header Account-ID with the last two digits (of a ten digit number) 00 to 05 (to touch only 5% of the total traffic). In addition, if a request has set the HTTP header Server-A, that request should be forwarded to that server regardless of the set account-id. Otherwise and by default, all traffic should be handled by server-b. My current location-rule looks like this:
location /rest/accounts/ {
  if ( $http_account_id ~ '([\d]{8})(0[0-4])') {
    proxy_pass http://server-a.company.com;
  }

  if ( $http_server_a = true) {
    proxy_pass http://server-a.company.com;
  }

  proxy_pass http://server-b.company.com;
}

As I read in the official documents here, if is considered evil.
Is there a better solution for my approach which isn't considered evil?

A: You can actually chain map directives a which would make it cleaner. For example:
map $http_server_a $server_a_check {
    default                 "http://server-b.company.com";
    ""                      "http://server-a.company.com";
}

map $http_account $account_check{
    default                 $server_a_check;
    "~([\d]{8})(0[0-4])"    "http://server-a.company.com";
}

server {
    ....
    location / {
        proxy_pass          $account_check;
    }
}

So proxy_pass is getting its value from $account_check which does a check against Account header with a regex check. Then if none of the variants pass their checks, the default gets its value from the result of $server_a_check which looks for Server-A header with no data for the value as the question didn't state what the accepted values would be.


text:
Q: ggplot, trying to change the order of my x value labels, scale_fill_discrete not working I am plotting a dataframe and the x values are "first", "second" ... so on.
The ggplot function plotted them alphabetically instead of numerically.
I tried to use
scale_fill_discrete(
  breaks = c("First", "Second", "Third", "Fourth", "Fifth", "Sixth")
)

The barplot is still coming out with the wrong order
here is the full code
gender_1 %>%
  ggplot(aes(x = `Call Attempt`, y = `Count`, fill = `Gender`)) +
  geom_col(position dodge) +
  scale_fill_discrete(
    breaks = c("First", "Second", "Third", "Fourth", "Fifth", "Sixth")
  )

I used
scale_fill_discrete(
  breaks = c("First", "Second", "Third", "Fourth", "Fifth", "Sixth")
)

and the order came out alphabetically instead of numerically

A: You probably want to use an (ordered) factor for your gender variable:
library(ggplot2)
# Example data

Gender<-c("First", "Second", "Third", "Fourth", "Fifth", "Sixth")
frame<-data.frame(X=1:6,Y=rnorm(6),Gender)

# ggplot orders this alphabetically (not what you want)
ggplot(frame,aes(X,Y,fill=Gender))+
  geom_bar(stat="identity")

# by using a factor and explicitly specifiying
# its levels (and the order of the levels) you force ggplot to abandon alphabetical order

ggplot(frame,aes(X,Y,fill=factor(Gender,levels = Gender)))+
  geom_bar(stat="identity")


text:
Q: Parsing datetime in Python..? I have a system (developed in Python) that accepts datetime as string in VARIOUS formats and i have to parse  them..Currently datetime string formats are :
Fri Sep 25 18:09:49 -0500 2009

2008-06-29T00:42:18.000Z

2011-07-16T21:46:39Z

1294989360

Now i want a generic parser that can convert any of these datetime formats in appropriate datetime object...
Otherwise, i have to go with parsing them individually. So please also provide method for parsing them individually (if there is no generic parser)..!!

A: As @TimPietzcker suggested, the dateutil package is the way to go, it handles the first 3 formats correctly and automatically:
>>> from dateutil.parser import parse
>>> parse("Fri Sep 25 18:09:49 -0500 2009")
datetime.datetime(2009, 9, 25, 18, 9, 49, tzinfo=tzoffset(None, -18000))
>>> parse("2008-06-29T00:42:18.000Z")
datetime.datetime(2008, 6, 29, 0, 42, 18, tzinfo=tzutc())
>>> parse("2011-07-16T21:46:39Z")
datetime.datetime(2011, 7, 16, 21, 46, 39, tzinfo=tzutc())

The unixtime format it seems to hiccough on, but luckily the standard datetime.datetime is up for the task:
>>> from datetime import datetime
>>> datetime.utcfromtimestamp(float("1294989360"))
datetime.datetime(2011, 1, 14, 7, 16)

It is rather easy to make a function out of this that handles all 4 formats:
from dateutil.parser import parse
from datetime import datetime

def parse_time(s):
    try:
        ret = parse(s)
    except ValueError:
        ret = datetime.utcfromtimestamp(s)
    return ret

A: You should look into the dateutil package.


text:
Q: How to keep DRY when fetching many images using GraphQL in Gatsby Let's say I want to include 50 images in one article on a blog made on Gatsby. Images are fetched using GraphQL. I end up writing very repetitive queries for each of the 50 images, like so:
export const query = graphql`
  query ArticleImageQuery {
    coverImage: imageSharp(id: {regex: "/cover-image/" }) {
      sizes(maxWidth: 700, maxHeight: 525) {
        ...GatsbyImageSharpSizes
      }
    },
    artisan1: imageSharp(id: {regex: "/artisan1/" }) {
      sizes(maxWidth: 700, maxHeight: 525) {
        ...GatsbyImageSharpSizes
      }
    },
    artisan2: imageSharp(id: {regex: "/artisan2/" }) {
      sizes(maxWidth: 700, maxHeight: 525) {
        ...GatsbyImageSharpSizes
      }
    },
    artisan3: imageSharp(id: {regex: "/artisan3/" }) {
      sizes(maxWidth: 700, maxHeight: 525) {
        ...GatsbyImageSharpSizes
      }
    },
    johannystrom1: imageSharp(id: {regex: "/johan-nystrom1/" }) {
      sizes(maxWidth: 700, maxHeight: 525) {
        ...GatsbyImageSharpSizes
      }
    },
    johannystrom2: imageSharp(id: {regex: "/johan-nystrom2/" }) {
      sizes(maxWidth: 700, maxHeight: 525) {
        ...GatsbyImageSharpSizes
      }
    },
    johannystrom3: imageSharp(id: {regex: "/johan-nystrom3/" }) {
      sizes(maxWidth: 700, maxHeight: 525) {
        ...GatsbyImageSharpSizes
      }
    },
    johannystrom4: imageSharp(id: {regex: "/johan-nystrom4/" }) {
      sizes(maxWidth: 700, maxHeight: 525) {
        ...GatsbyImageSharpSizes
      }
    },
    fratello1: imageSharp(id: {regex: "/fratello/" }) {
      sizes(maxWidth: 700, maxHeight: 525) {
        ...GatsbyImageSharpSizes
      }
    },
    booksAntiques1: imageSharp(id: {regex: "/books-antiques1/" }) {
      sizes(maxWidth: 700, maxHeight: 525) {
        ...GatsbyImageSharpSizes
      }
    },
    booksAntiques2: imageSharp(id: {regex: "/books-antiques2/" }) {
      sizes(maxWidth: 700, maxHeight: 525, cropFocus: CENTER) {
        ...GatsbyImageSharpSizes
      }
    },
    pastor1: imageSharp(id: {regex: "/pastor1/" }) {
      sizes(maxWidth: 700, maxHeight: 525) {
        ...GatsbyImageSharpSizes
      }
    },
    pastor2: imageSharp(id: {regex: "/pastor2/" }) {
      sizes(maxWidth: 700, maxHeight: 525, cropFocus: CENTER) {
        ...GatsbyImageSharpSizes
      }
    },
    pastor3: imageSharp(id: {regex: "/pastor3/" }) {
      sizes(maxWidth: 700, maxHeight: 525) {
        ...GatsbyImageSharpSizes
      }
    },
    libertyOrDeath1: imageSharp(id: {regex: "/liberty-death1/" }) {
      sizes(maxWidth: 700, maxHeight: 525, cropFocus: CENTER) {
        ...GatsbyImageSharpSizes
      }
    },
    libertyOrDeath2: imageSharp(id: {regex: "/liberty-death2/" }) {
      sizes(maxWidth: 700, maxHeight: 525, cropFocus: CENTER) {
        ...GatsbyImageSharpSizes
      }
    },
    kaisla1: imageSharp(id: {regex: "/kaisla1/" }) {
      sizes(maxWidth: 700, maxHeight: 525, cropFocus: CENTER) {
        ...GatsbyImageSharpSizes
      }
    },
    blockDylan1: imageSharp(id: {regex: "/block-dylan1/" }) {
      sizes(maxWidth: 700, maxHeight: 525, cropFocus: CENTER) {
        ...GatsbyImageSharpSizes
      }
    },
    blockDylan2: imageSharp(id: {regex: "/block-dylan2/" }) {
      sizes(maxWidth: 700, maxHeight: 525, cropFocus: CENTER) {
        ...GatsbyImageSharpSizes
      }
    },
    blockDylan3: imageSharp(id: {regex: "/block-dylan3/" }) {
      sizes(maxWidth: 700, maxHeight: 525, cropFocus: CENTER) {
        ...GatsbyImageSharpSizes
      }
    },
    blockDylan4: imageSharp(id: {regex: "/block-dylan4/" }) {
      sizes(maxWidth: 700, maxHeight: 525, cropFocus: CENTER) {
        ...GatsbyImageSharpSizes
      }
    },
    blockDylan5: imageSharp(id: {regex: "/block-dylan5/" }) {
      sizes(maxWidth: 700, maxHeight: 525, cropFocus: CENTER) {
        ...GatsbyImageSharpSizes
      }
    },

    /* The list goes on, you get the idea... */
  }
`;

This goes heavily against the DRY (Don't Repeat Yourself) principle. I've tried to fiddle with fragments, but I being a noob GraphQL user I just can't figure out how can I reuse this repetitive code and write it just once, instead of 50 times?
Is there anything I can do to improve this?
Ideally, I'd love to have a code where I could write the repetitive part once and then reuse it for each image that I'm fetching. For example:
/* NOTE: FICTIONAL PSEUDOCODE */

const imageQuery = graphql`
  query ImageQuery($path: String!) {
    imageSharp(id: {regex: $path }) {
      sizes(maxWidth: 700, maxHeight: 525) {
        ...GatsbyImageSharpSizes
      }
    },
  }
`;

export const query = graphql`
  query ArticleImageQuery {
    coverImage: ImageQuery("/cover-image/"),
    artisan1: ImageQuery("/artisan1/"),
    artisan2: ImageQuery("/artisan2/"),
    artisan3: ImageQuery("/artisan3/"),
    johannystrom1: ImageQuery("/johan-nystrom1/"),'
    /* ... AND SO ON */
  }
`;

A: GraphQL Fragments do not have parameters. See this github issue for more info.
When I have a problem similar to yours I select all the images that I need with one query and then process them in the view. For example with such query :
export const query = graphql`
{
  allFile(filter: {absolutePath: {regex: "/img/o-meni/im/"}}) {
    edges {
      node {
        id
        name
        publicURL
        childImageSharp {
          sizes(maxWidth: 700, maxHeight: 525) {
              ...GatsbyImageSharpSizes
          }
        }
      }
    }
  }
}
`

And then you can filter for the specific image like artisan1 or whichever in the React component. To display them all you can use code like this :
{
  this.props.data.allFile.edges.map(({ node }) =>

  )
}


text:
Q: Identify first call using already existing static variables? Is there a way I can identify if a function is being called the for the first time by identifying the internal (hidden?) variables that GCC uses to facilitate static variables (variables that already exist in my function)?
I hope to get at these variables from the C++ code.

A: There's no way to rely on internals of the compiler, and even if you tried there's no guarantee it wouldn't change with the next version.
Use this common idiom:
static bool firsttime = true;
if (firsttime)
{
    firsttime = false;
    // other stuff here
}

A: GCC uses a hidden flag indicating if a variable has been initialized. There is no way to access this. Even so, these don't actually track the "first time" but rather whether the variable has been initialized. Consider the following:
void func()
{
   static T a;
   static T b;
}

But the standard would actually allow that these are initialized by different threads. So if that happens which one got their first. Checking the gcc disassembly it does seem each is handled with its own lock, at least in non-optimized mode, the code changes a lot in optimized mode (so even moreso, "first time" is not clearly defined).
Additionally, as Mark points out in his comment, it greatly depends on what type you are using when the initialization is done. Simple types might, not guaranteed, be initialized globally, others will indeed wait until the function is called first.
Why do you need to know first time entry anyway?


text:
Q: Bash - ANSI color code for purple background with bold black text What is the ANSI color code for a purple (or dark purple) background with black bold text (foreground).
As an example, here is cyan with black bold text:
echo -e "\e[30;1;46mExample\e[0m"

After consulting a number of ANSI color code lists and examples, I can't figure out how to do the same with a purple background. The closest I can come up with is a magenta background with black, bold text, by using 30;1;45m:

A: Your escape sequence \e[30;1;45m is perhaps easier understood as the merger of three sequences:

*

*\e[30m -- this means "black foreground"

*\e[1m -- this means "bright foreground"

*\e[45m -- this means "magenta background"

Now these colour sequences are limited to 8 colors

*

*black

*red

*green

*yellow

*blue

*magenta

*cyan

*white

These are the traditional ANSI colours.
However there are sequences that allow 256 colours to be chosen, if your terminal supports them.
\e[38;5;###m where ### is a number between 0 and 255 will select a foreground colour.
\e[48;5;###m similarly choses the background colour.
So maybe \e[38;5;0;1;48;5;92m might be close to what you want.
Note: if you use 256 colour background settings then you also need to use the 256 colour foreground setting.
FWIW, the following python script will show all the background colours which can help you pick the colour you want.
import sys
for i in range(0, 16):
    for j in range(0, 16):
        code = str(i * 16 + j)
        sys.stdout.write(u"\u001b[48;5;" + code + "m " + code.ljust(4))
    print u"\u001b[0m"

(taken from http://www.lihaoyi.com/post/BuildyourownCommandLinewithANSIescapecodes.html#background-colors )


text:
Q: C++ MAPI RecipDesc Initilise I coded my self a Programm to Create Mails.
First i get a Vector of String with Addresses. Now when I try to Inizilise the RecipDesc with the Size of the Vector i cant compile , couse its waiting for a constant.
Here some Code snippets:
vector<string> to=Createadresse();
static const size_t v=to.size();

    MapiRecipDesc  rdRecipient[v];

I get Following  Erros ( sry the Compile is in German but you will get the Error Code)
error C2466: Zuordnung eines Arrays der konstanten Größe 0 nicht möglich.
error C2133: 'rdRecipient': Unbekannte Größe
error C2070: 'MapiRecipDesc []': Ungültiger sizeof-Operand

thanks for the help!

A: ethrbunny you got it :D Fixxed it with a dynamic Array.
 int v=to.size();
  MapiRecipDesc  *rdRecipient= new MapiRecipDesc[v+1];

thanks anayway =)


text:
Q: Set the custom CI config path in Gitlab Gitlab uses the custom CI config path for the .gitlab-ci.yml file in the root of the project. However, I would like to set it to the project location of build/ci/.gitlab-ci.yml.
How do I set the path and can I do it inside the .gitlab-ci.yml file itself?
I know we can set the path in the Gitlab CI/ CD settings page but I look for a programmable solution so we don't need to enter there (and put it by hand.)


text:
Q: How to make a report parameter selection change another report parameter selection values while allowing multiselect for both of them? Lets say I have a table with a list of names, such as "a, b, c" and each name has several other values assigned (some of the other values can be assigned to several/all of names values, example below).
Table example:
( names - other ):
a - aa
a - ab
a - ac
b - ab
b - bb
b - cb
c - ac
c - bc
c - cc
How do I make in birt so that I could select names in one parameter box and get corresponding other values to select for another parameter? I know it's possible to do that with cascading parameter, but that doesn't allow to have multiselect for the first parameter, which in our example would be names values.

A: Found a solution partly here: https://forums.opentext.com/forums/developer/discussion/61283/allow-multi-value-for-cascading-parameter
and here (thanks google translate ^^): https://www.developpez.net/forums/d1402270/logiciels/solutions-d-entreprise/business-intelligence/birt/birt-4-3-1-multi-value-cascade-parameters/
Steps to do:
change"\birt\webcontent\birt\ajax\ui\dialog\BirtParameterDialog.js" file contents (there is a file to download for replacement in one of the links, but in case it goes dead I'm sharing 2 snippets from it where the changes occur:
    __refresh_cascade_select : function( element )
{
    var matrix = new Array( );
    var m = 0;
    for( var i = 0; i < this.__cascadingParameter.length; i++ )
    {
        for( var j = 0; j < this.__cascadingParameter[i].length; j++ )
        {
            var paramName = this.__cascadingParameter[i][j].name;
            if( paramName == this.__isnull )
                paramName = this.__cascadingParameter[i][j].value;

            if( paramName == element.id.substr( 0, element.id.length - 10 ) )
            {
                //CHANGE//
                //The two way work (String(selectedValue) or Array(SelectedValueArray))
                var l = 0;
                var isFirstElement = true;
                var selectedValue = "";
                var selectedValueArray = new Array();
                for(var test = 0; test<element.options.length;test++){
                    if(element.options[test].selected){
                        if(isFirstElement){
                            isFirstElement = false;
                            selectedValue = element.options[test].value;

                        }
                        else{
                            selectedValue = selectedValue+","+element.options[test].value;
                        }
                        selectedValueArray[l] = element.options[test].value;
                        l++;
                    }
                }
                //CHANGE//

                var tempText = element.options[element.selectedIndex].text;
                var tempValue = element.options[element.selectedIndex].value;

                // Null Value Parameter
                if ( tempValue == Constants.nullValue )
                {
                    this.__cascadingParameter[i][j].name = this.__isnull;
                    this.__cascadingParameter[i][j].value = paramName;
                }
                else if( tempValue == '' )
                {
                    if( tempText == "" )
                    {
                        var target = element;
                        target = target.parentNode;
                        var oInputs = target.getElementsByTagName( "input" );
                        if( oInputs.length >0 && oInputs[1].value != Constants.TYPE_STRING )
                        {
                            // Only String parameter allows blank value
                            alert( birtUtility.formatMessage( Constants.error.parameterNotAllowBlank, paramName ) );
                            this.__clearSubCascadingParameter( this.__cascadingParameter[i], j );
                            return;
                        }
                        else
                        {
                            // Blank Value
                            this.__cascadingParameter[i][j].name = paramName;
                            this.__cascadingParameter[i][j].value = tempValue;
                        }
                    }
                    else
                    {
                        // Blank Value
                        this.__cascadingParameter[i][j].name = paramName;
                        this.__cascadingParameter[i][j].value = tempValue;
                    }
                }
                else
                {
                    this.__cascadingParameter[i][j].name = paramName;
                    //CHANGE//
                    //The two way work (String(selectedValue) or Array(SelectedValueArray))
                    this.__cascadingParameter[i][j].value = selectedValueArray;
                    //CHANGE//
                }

                for( var m = 0; m <= j; m++ )
                {
                    if( !matrix[m] )
                    {
                        matrix[m] = {};
                    }
                    matrix[m].name = this.__cascadingParameter[i][m].name;
                    matrix[m].value = this.__cascadingParameter[i][m].value;
                }
                this.__pendingCascadingCalls++;
                birtEventDispatcher.broadcastEvent( birtEvent.__E_CASCADING_PARAMETER, matrix );
            }
        }
    }
},

and this:
// exist select control and input text/password
        // compare the parent div offsetTop
        if( oFirstITC.parentNode && oFirstST.parentNode )
        {
            // Bugzilla 265615: need to use cumulative offset for special cases
            // where one element is inside a group container
            var offsetITC = Position.cumulativeOffset( oFirstITC );
            var offsetST = Position.cumulativeOffset( oFirstST );

            // compare y-offset first, then x-offset to determine the visual order
            if( ( offsetITC[1] > offsetST[1] ) || ( offsetITC[1] == offsetST[1] && offsetITC[0] > offsetST[0] ) )
            {
                oFirstST.focus( );
            }
            else
            {
                oFirstITC.focus( );
            }
        }

After .js is changed cascading parameters can have multiselect on all levels.
Example:
1st DataSet "DS_country" query:
select CLASSICMODELS.OFFICES.COUNTRY
from CLASSICMODELS.OFFICES

2nd DataSet "DS_office" query:
select CLASSICMODELS.OFFICES.OFFICECODE
from CLASSICMODELS.OFFICES
where CLASSICMODELS.OFFICES.COUNTRY IN ('DS_country')

After datasets are created we can make cascading report parameters CRP_country and CRP_office (keep in mind that UI doesn't let you to choose "Allow multiple values" on the upper levels, but we can change that in property editor after the parameters are made by going to advanced tab and changing "Scalar parameter type" property value to "Multi Value")
The only thing left is to pick lower level cascading parameters (CRP_office in our example) and go to script tab and add this on "beforeOpen":
// Do that if your selections are in String type.
var stringArray = params["CRP_country"].value.toString().split(",");
var result = "";
for(var i =0 ; i < stringArray.length ; i++){
    if(i==0){
        result = "'"+stringArray[i]+"'";
    }
    else{
        result = result+",'"+stringArray[i]+"'";
    }
}

// For String
this.queryText = this.queryText.replace("'DS_country'", result);

//For integer (the first part is useless)
//this.queryText = this.queryText.replace("'DS_country'",
params["CRP_country"].value);


text:
Q: Equivalence of columns spaces Assuming we have matrix B as follows:
$$ B=\begin{bmatrix}
b_{11}&\cdots&b_{1n}\\
b_{21}&\cdots&b_{2n}\\
\vdots&\vdots&\vdots\\
b_{n1}&\cdots&b_{nn}
\end{bmatrix}$$
I want to verify the space spanned by columns of B ,n$\times$n matrix, is equivalent to the space spanned by column of A ,a m$\times$ m matrix as follows:
$$A= \begin{bmatrix}
b_{11}&\cdots&b_{1n}&0&0...&0\\
b_{21}&\cdots&b_{2n}&0&0...&0\\
\vdots&\vdots&\vdots&0&0...&0\\
b_{n1}&\cdots&b_{nn}&0&0...&0\\
0&\cdots&0&1&0&...&0\\
0&\cdots&0&0&1&...&0\\
\vdots&\vdots&...&&&\vdots\\
0&\cdots&0&0&0&...&1\\
\end{bmatrix}$$
I cannot see any reasons to contradict my assumption(Since the the dimension of column vectors of A and B are not the same I was not sure).
Could anyone help please?
Thanks in advance.


text:
Q: Timeout expired while querying large data on Hyperledger Fabric 1.4.1 I am using Hyperledger Fabric 1.4.1, with Kafka ordering service, Couch DB as stateDB, Java chaincode and Java SDK.
I experience timeout expired when I try to send large data to the channel and then query it back.
The data size of the transaction I sent is 512KB, and I can query it from peers.
I tried sending it 7 times with the same id, and I can get all 7 histories with shim function getHistoryForKey. But when I sent it 8 times with the same id, getHistoryForKey failed.
The error message is shown below (from peers):
Error: endorsement failure during query. response: status:500 message:"failed to execute transaction fdfbc5b72efd688136c777f5b114a3cedc62339e42f6c39a27e86ca11b8e3d14: error sending: timeout expired while executing transaction"

I have tried to expand the timeout with following options and their combinations in peer and client:
CORE_CHAINCODE_EXECUTETIMEOUT="120s"
CORE_LEDGER_STATE_COUCHDBCONFIG_REQUESTTIMEOUT="120s"
# (seems this setting is not for Hyperledger Fabric)
CORE_PEER_GRPCOPTIONS_REQUESET_TIMEOUT="120s"

But they didn't help in my case.
I also noticed that the 7 copies of testing data are about 3.5MB, and I tried to query 4MB data (which is about 8 copies) from a peer but failed.
When we check the chaincode runtime docker, we see the following error message:
SEVERE: An error occured on the chaincode stream. Shutting down the chaincode stream.
io.grpc.StatusRuntimeException: RESOURCE_EXHAUSTED:
io.grpc.netty.NettyClientTransport$3: Frame size 6294852 exceeds maximum: 4194304.

It seems like there is a grpc limitation on running the java chaincode docker.
We tested with go chaincode, we do not experience the same issue.

A: We managed to fix that by overriding the ChaincodeBase class
ManagedChannelBuilder<?> newChannelBuilder() throws IOException {
    final NettyChannelBuilder builder = NettyChannelBuilder.forAddress(host, port);
    logger.info("Configuring channel connection to peer.");

    builder.maxInboundMessageSize(104857600);
    logger.info("maxInboundMessageSize is 104857600.");
    if (tlsEnabled) {
        builder.negotiationType(NegotiationType.TLS);
        builder.sslContext(createSSLContext());
    } else {
        builder.usePlaintext(true);
    }
    return builder;
}

I have submitted a ticket on fabric Jira to support changing the variable without overriding.


text:
Q: Dynamic SelectionChange based on current active row I created a worksheet for myself containing multiple dependant dropdown lists.
Basicly I want a range to be cleared when a change happens within a range.
Therefor I wrote the code below, which works as intented but it is far from neat.
This is the code:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Address = Range("D13").Address Then
Range("D13:H13").Value = ""
ElseIf Target.Address = Range("D14").Address Then
Range("D14:H14").Value = ""
ElseIf Target.Address = Range("D15").Address Then
Range("D15:H15").Value = ""
ElseIf Target.Address = Range("D16").Address Then
Range("D16:H16").Value = ""
ElseIf Target.Address = Range("D17").Address Then
Range("D17:H17").Value = ""
ElseIf Target.Address = Range("D18").Address Then
Range("D18:H18").Value = ""
ElseIf Target.Address = Range("D19").Address Then
Range("D19:H19").Value = ""
ElseIf Target.Address = Range("D20").Address Then
Range("D20:H20").Value = ""
ElseIf Target.Address = Range("D21").Address Then
Range("D21:H21").Value = ""
ElseIf Target.Address = Range("D22").Address Then
Range("D22:H22").Value = ""
ElseIf Target.Address = Range("D23").Address Then
Range("D23:H23").Value = ""
ElseIf Target.Address = Range("D24").Address Then
Range("D24:H24").Value = ""
ElseIf Target.Address = Range("D25").Address Then
Range("D25:H25").Value = ""
ElseIf Target.Address = Range("D26").Address Then
Range("D26:H26").Value = ""
ElseIf Target.Address = Range("D27").Address Then
Range("D27:H27").Value = ""
ElseIf Target.Address = Range("D28").Address Then
Range("D28:H28").Value = ""
ElseIf Target.Address = Range("D29").Address Then
Range("D29:H29").Value = ""
End If
End Sub

Now what I would like to achieve is something like this:
If Target.Address = Range("D13:D29").Address Then
Range("D Target.Address.Row : H Target.Address.Row").Value = ""
End If
End Sub

If someone can put me in the right direction of how to use the Target.Address within a range selection or in a better suitable solution/option i`d be very thanksfull :)

A: You can use a loop and Resize so you have not to repeat the same code over and over:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim AffectedRange As Range  'check wich target cells are affected
    Set AffectedRange = Intersect(Target, Me.Range("D13:D29"))

    If Not AffectedRange Is Nothing Then
        Dim Cell As Range
        For Each Cell in AffectedRange ' clear range for each affected cell
            Cell.Resize(ColumnSize:=5).Value = vbNullString
        Next Cell
    End If
End Sub

A: The code could be simplified to this.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    If Not Intersect(Target, Range("D13:D29")) Is Nothing Then
        Target.Resize(, 5).Value = ""
    End If

End Sub


text:
Q: Firemonkey: How to define a component that contain another component? Under Delphi, i want to create a new firemonkey control that will contain another firemonkey control. This is not really a problem because i can do like this :
constructor TMyComponent.Create(AOwner: TComponent);
begin
  inherited;
  FBtn := Trectangle.create(self);
  FBtn.parent := self;
  FBtn.stored := false;
end;

But now i would like to permit end-user to modifie the properties of the FBtn in the Object Inspector also! i don't know how to do :(
if i remove the FBtn.stored := False then i will have in the structure explorer some component with name like < Components[7] > and every time i will do view the form as text and back to view as form then a new component will appear in the structure explorer :(

A: Anything you want to expose in the Objct Inspector must be declared in a published property, eg:
type
  TMyComponent = class(TComponent)
  private
    FBtn: TRectangle;
    procedure SetBtn(Value: TRectangle);
  published
    property Btn: TRectangle read FBtn write SetBtn;
  end;

constructor TMyComponent.Create(AOwner: TComponent);
begin
  inherited;
  FBtn := TRectangle.create(Self);
  FBtn.Parent := Self;
  FBtn.Stored := False;
  FBtn.SetSubComponent(True);
end;

procedure TMyComponent.SetBtn(Value: TRectangle);
begin
  FBtn.Assign(Value);
end;

A: While Remy's answer technically will work, I wouldn't consider it the appropriate approach. This is because when you publish any TComponent descendant as a property, this presumes that you would create such a control externally and then assign it within the object inspector. Surely you don't want to allow this to happen, since this control is created internally. You also presumably only want to allow the user to change certain properties, not all of them.
Instead, I would recommend using a TPersistent which exposes only those properties of the control you actually want to provide access to.
unit MyComponentUnit;

interface

uses
  System.Classes, System.SysUtils,
  Fmx.Controls, FMX.StdCtrls, FMX.Objects;

type
  TMyComponentButton = class(TPersistent)
  private
    FBtn: TRectangle;
    function GetXRadius: Single;
    function GetYRadius: Single;
    procedure SetXRadius(const Value: Single);
    procedure SetYRadius(const Value: Single);
    //And any other property getters/setters you wish to wrap
  public
    constructor Create(ABtn: TRectangle);
    destructor Destroy; override;
    procedure Assign(Source: TPersistent); override;
  published
    property XRadius: Single read GetXRadius write SetXRadius;
    property YRadius: Single read GetYRadius write SetYRadius;
    //And any other properties you wish to wrap
  end;

  TMyComponent = class(TControl)
  private
    FBtn: TRectangle;
    FMyComponentButton: TMyComponentButton;
    procedure SetMyComponentButton(const Value: TMyComponentButton);
  public
    constructor Create(AOwner: TComponent); override;
    destructor Destroy; override;
  published
    property MyComponentButton: TMyComponentButton
      read FMyComponentButton write SetMyComponentButton;
  end;

implementation

{ TMyComponentButton }

constructor TMyComponentButton.Create(ABtn: TRectangle);
begin
  inherited Create;
  FBtn:= ABtn;
end;

destructor TMyComponentButton.Destroy;
begin

  inherited;
end;

procedure TMyComponentButton.Assign(Source: TPersistent);
begin
  if Source is TMyComponentButton then begin
    XRadius:= (Source as TMyComponentButton).XRadius;
    YRadius:= (Source as TMyComponentButton).YRadius;
    //And everything else you need to assign
  end else
    inherited;
end;

function TMyComponentButton.GetXRadius: Single;
begin
  Result:= FBtn.XRadius;
end;

function TMyComponentButton.GetYRadius: Single;
begin
  Result:= FBtn.YRadius;
end;

procedure TMyComponentButton.SetXRadius(const Value: Single);
begin
  FBtn.XRadius:= Value;
end;

procedure TMyComponentButton.SetYRadius(const Value: Single);
begin
  FBtn.YRadius:= Value;
end;

{ TMyComponent }

constructor TMyComponent.Create(AOwner: TComponent);
begin
  inherited;
  FBtn:= TRectangle.Create(Self);
  FBtn.Parent:= Self;
  FBtn.Stored:= False;
  FMyComponentButton:= TMyComponentButton.Create(FBtn);
end;

destructor TMyComponent.Destroy;
begin
  FreeAndNil(FMyComponentButton);
  FreeAndNil(FBtn);
  inherited;
end;

procedure TMyComponent.SetMyComponentButton(const Value: TMyComponentButton);
begin
  FMyComponentButton.Assign(Value);
end;

end.


text:
Q: jQuery validate textarea:filled i have the following form fields...
<textarea name="anchors[]" id="anchors1" cols="45" rows="5" class="linkbox"></textarea>
<textarea name="anchors[]" id="anchors2" cols="45" rows="5" class="linkbox"></textarea>
<textarea name="urls[]" id="urls1" cols="45" rows="5" class="linkbox"></textarea>
<textarea name="urls[]" id="urls2" cols="45" rows="5" class="linkbox"></textarea>

which i'm trying to validate so that if say anchors2 is filled in, then urls2 must also be filled in, however i can't for the life of me get the following to work!...
var validator = $("#projectform").validate({
    rules: {
        project_label: "required",
        keywords: "required",
        urls2: { required: "#anchors2:filled" }
    },
    messages: {
        project_label: "Enter a project label",
    }
    ,errorElement: "div"
    ,submitHandler: function(form) {
        $('input[type=submit]').attr('value', 'Please wait');
        $('input[type=submit]').attr('disabled', 'disabled');
        this.form.onsubmit(); return false;
    }

});

When i click submit the project_label and keywords fields validate(or not) as would be expected, however i see nothing with regards to the anchors[] and urls[] fields. I have css set on the textarea.error to give a visual indiciation too but i don't see that either when attempting to validate.
It should be noted that the following doesn't work either, which may shed some light?
urls1: "required",

A: The validation plugin requires that you use the element name, not the id. In order to do this, I had to change the name to remove the []. So rename your textarea, and try again - like so:
HTML:
<textarea name="url2newname" id="urls2" cols="45" rows="5" class="linkbox"></textarea>

Javascript Snippet:
rules: {
        project_label: "required",
        keywords: "required",
        urls2newname: { required: "#anchors2:filled" }
    }


text:
Q: Hive query: select a column based on the condition another columns values match some specific values, then create the match result as a new column I have to some query and creat columns operations in HiveQL.
For example,
app      col1

app1     anybody love me?
app2     I hate u
app3     this hat is good
app4     I don't like this one
app5     oh my god
app6     damn you.
app7     such nice girl
app8     xxxxx
app9     pretty prefect
app10    don't love me.
app11    xxx anybody?

I want to match a keyword list like ['anybody', 'love', 'you', 'xxx', 'don't'] and select the matched keyword result as a new column, named keyword as follows:
app      keyword

app1     anybody, love
app4     I don't like this one
app6     damn you.
app8     xxx
app10    don't, love
app11    xxx

It seems that I have to use nested query.
The logic is kind of like selecting the matched result rows and setting a matched results which should be saved in a list or something like this as a new column.
But I am not familiar enough with the HiveQL.
Could anyone help me?
Thanks in advances.

A: You could turn the list of words to a table and join it with your table using pattern matching:
select t.app, k.keyword
from  mytable t
inner join (values ('anybody'), ('you'), ('xxx'), ('don''t')) as k(keyword)
    on t.col1 like conca('%', k.keyword, '%')

Note that this will duplicate app if more than one keyword matches on a phrase. You did not specify how you want to handle this use case.
In hive, you can also phrase this as:
select t.app, k.keyword
from  mytable t
inner join table(values 'anybody', 'you', 'xxx', 'don''t') as k(keyword)
    on t.col1 like conca('%', k.keyword, '%')

A: In Hive you can use stack UDTF:
with keywords as (
select stack(4, --the number of tuples
'anybody', 'you', 'xxx', 'don\'t'
) as keyword
)

select t.app, k.keyword
from  mytable t
inner join keywords k
    on t.col1 like concat('%', k.keyword, '%')

Also for older versions of hive join using like will not work, use cross join with stack and filter in the WHERE:
from  mytable t
cross join keywords k
where t.col1 like concat('%', k.keyword, '%')


text:
Q: constructing a sequence that converges to zero fast enough (for the corresponding series to converge) Suppose there is a sequence in $\mathbb{R}$ that converges to $0$, but such that the corresponding series does not necessarily converge.  In this general case, how can I construct a sequence that is guaranteed to produce a convergent series using the terms of the original one?
I know if my example is $X_n = \{\frac{1}{n}\}$ then I could just take the terms that are powers of $\frac{1}{2}$ from $X_n$ and construct a new sequence such that when summed converges (since it is the geometric series).
How can I do this in the very general case

A: Start by picking your favorite convergent positive series $\sum a_n$. You can take $a_n=\frac{1}{2^n}$ for example. Now let $X_n$ be a sequence that converges to $0$. Choose a subsequence $X_{n_k}$ such that for every $k$ you have$$|X_{n_k}|<a_k.$$This guarantees that $\sum X_{n_k}$ is absolutely convergent and in particular convergent.

A: Take the elements $n_k$ such that $n_k\sim k^{1+\epsilon}$ where $\epsilon>0$ i.e $lim_k \frac{n_k}{k^{1+\epsilon}}=1$

A: You can use your idea more generally. You know that
$$\sum_{n=1}^\infty \frac{1}{2^n} = \frac{1}{2}+\frac{1}{4}+\frac{1}{8}+\ldots$$converges and you have a sequence $(a_n)$ with (I assume) positive terms, converging to $0$. You want to construct a sequence $b_n$ using terms from the original sequence but with $\sum b_n$ convergent.
Since $a_n\to 0$, you can find $i_1 \in \mathbb{N}$ such that $a_{i_1} < \tfrac{1}{2}$, the first $i_1$ that works will do: set $b_1=a_{i_1}$. For the next term, take $i_2 > i_1$ such that $a_{i_2} < \tfrac{1}{4}$ and set $b_2 = a_{i_2}$. Continue by finding $i_k$ such that $a_{i_k} < \tfrac{1}{2^k}$ and set $b_k = a_{i_k}$.
In this way, you construct a sequence with terms $b_n$ taken from the $a_n$'s but in such a way that you have $b_n < \tfrac{1}{2^n}$ for all $n$, so $\sum b_n$ converges by the comparison test.


text:
Q: SQL Distinct on different column I have the following query
select t1.work_date, t1.proposal_job_ref, t1.timesheet_time, t2.proposal_title

from dbo.timesheet_entries t1
inner join dbo.proposal t2
    on t1.proposal_job_ref = t2.proposal_ref_code

inner join dbo.consultant t3
    on t3.consultant_id = t1.consultant_id

where t1.consultant_id = 2
and t1.work_date between '01/09/2013' and '30/09/2013'

order by t1.work_date

I'd like to remove records from this query that have the same value for the field proposal_job_ref
I tried adding distinct after the select however this doesn't work as I think it removes duplicate entries based on work_date
Can anyone please help me with this?
Thanks.
UPDATE
work date    proposal_ref_code    timesheet_time    proposal_title
01/09/2013   p11111               8                 Web App Development
02/09/2013   p22222               4                 Mobile Development
03/09/2013   p11111               6                 Web App Development
04/09/2013   p33333               8                 Database Design

Using the table above, once my query is executed I would like the 3rd row to be removed because it is has the same proposal_ref_code as the first row, ie, p11111.
I am using SQL Server 2008

A: Please Try it, I hope it's useful to you
WITH CTE AS
(
SELECT *,RN=ROW_NUMBER() OVER (PARTITION BY work_date ORDER BY work_date DESC) FROM tablename
)
delete from CTE where RN>1


text:
Q: How do we check if a browser's auto-update is enabled through javascript I want to check form the javascript if a browser's auto-update is enabled.
The reason I want this is that our software supports only a set of Browser versions and we want to alert them if auto-update is on.
Is there any way we can do this?
Abhi

A: No. Browsers are highly sand-boxed and will give you almost no information about the users system.
You'll instead have to just do something like check the version and alert them if it isn't up-to-date, with maybe some information on how to check if they have auto-updated turned on.

A: Not sure why you require a set version, but one thing to do is check if the browser supports a specific method (One that your app requires).
If not, tell them to update their browser. This example test if the user has WebSockets:

if (window.WebSocket) {
  alert("BROWSER SUPPORTED");
} else {
  alert("BROWSER NOT SUPPORTED");
}


text:
Q: What are families of graphs called which we can "grow" by induction? Consider the following proof by induction:

Theorem. All trees are $2$-colorable.
Proof. We induct on $n$, the number of vertices in the tree. When $n=1$, we may give the only vertex any color we like.
Assume that all $n$-vertex trees are $2$-colorable. To prove this for $(n+1)$-vertex trees, take an $n$-vertex tree $T$, $2$-color it, and then add an $(n+1)^{\text{th}}$ vertex $v$ connected by an edge to any vertex of $T$. The resulting tree $T+v$ can be $2$-colored by giving $v$ the opposite color of the vertex we just connected it to.
By induction, the theorem holds for all $n$.

This is not a very good proof, but it can be made to work by clarifying an unstated assumption: any $(n+1$)-vertex tree can be obtained by adding on to an $n$-vertex tree. (I've seen a textbook call this the "Tree Growing Procedure", possibly only for the sake of the pun.)
The corresponding assumption is not true for all kinds of graphs, and assuming it's always true leads us to such classic mistakes as:

Theorem. All planar graphs are $4$-colorable.
Nonproof. It suffices to color all maximal (triangulated) planar graphs, because we can always add edges to a planar graph to triangulate it, and a proper coloring of the triangulation is also a proper coloring of the original graph.
We prove this by induction on $n$. For $n \le 4$, a $4$-coloring exists because we may give each vertex its own color.
Assume that all $n$-vertex planar triangulations are $4$-colorable. To prove this for $(n+1)$-vertex planar triangulations, take an $n$-vertex one and add another vertex to it, drawing all possible edges.
The new vertex was added to the middle of a (triangular) face, so it is connected to three vertices of that triangle. The $n$-vertex graph had a $4$-coloring by the inductive hypothesis, which we may extend to a coloring of the new graph by giving the new vertex a color different from any of the three colors use for those vertices.
By induction, the theorem holds for all $n$.

(I'm possibly not making the argument very convincing, because I know it's wrong - but variants of this mistake are very common among students first learning graph theory.)
My question: is there a word for the families of graphs (or of combinatorial objects in general; this issue isn't limited to graph theory) for which a "Growing Procedure" exists, and this type of argument works? Is there a theory of when "Growing Procedures" exist?

A: I have often heard a graph property called hereditary when the property is closed under taking arbitrary induced subgraphs. However, this is somewhat stronger than the property you seem to be looking for: in a hereditary graph class, you can delete any vertex (or any subset of vertices) and get another graph with the desired property, while you just want there to be some vertex whose deletion yields a graph with the desired property. In particular, the property of being a tree is not hereditary, but the property of being a forest (disjoint union of trees) is hereditary, and it's possible to use this fact to prove that forests are 2-colorable in the same way you outlined in your question.

A: There is a class of stronger properties than you ask for, however it is applicable to your example. This class is called connected-hereditary properties, i. e. graph properties that are closed with respect to connected induced subgraphs. Particularly, being a tree is a connected-hereditary property.


text:
Q: C# UWP - cannot connect to the serial port I'm working on UWP app and need to read data from a serial port and display them on the graph.
I'm getting 3 random exception messages :

Message 1 :
"The operation completed successfully"
Message 2 :
"An attempt was made to reference a token that does not exist"
Message 3 :
"The requested lookup key was not found in any active activation
   context"

I don't have a live connection, but I installed a simulator. When I'm trying to establish a connection from the console app it works fine.
Here is my code, which is really simple:
_serialPort = new SerialPort(portName, baudRate);
_serialPort.DataReceived += _serialPort_DataReceived;
try
{
    _serialPort.Open();
}
catch (Exception ex)
{

}

From the _serialPort_DataReceived method I want to update the graph.
I know that there is some limitation with the serial port on UWP, but I can't find an appropriate solution.
There are similar questions on Stack Overflow, but none of the answers are a solution to my problem.

A:
I'm working on UWP app and the case is to read data from a serial port and show them on the graph.

In UWP we use Windows.Devices.SerialCommunication namespace to access serial port. For using above namespace we need add the following capability.
<Capabilities>
  <DeviceCapability Name="serialcommunication">
    <Device Id="any">
      <Function Type="name:serialPort" />
    </Device>
  </DeviceCapability>
</Capabilities>

For the detail steps, please refer this code sample .


text:
Q: How to show image from inside the nested fragments? Although there are many questions about nested fragments but still it got me stumped in this case.I am making an android app which has an Activity having a frame layout.I am loading a fragment(say Fragment B) into the frame layout.Fragment B has a ViewPager that contains two fragments.First fragment of viewpager(say Fragment VP1) has a gridview that loads images from network.Now on griditem image click I want to show the image in full size in a new fragment which has NetowrkImageView. How do i do this? I tried need to call getChildFragmentManager(),but didn't work. If you guys need code I'll show that. Thanks in advance.
onCreateView() of VP1
public View onCreateView(LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.fragment_images_and_videos,null);
        gridItemList=new ArrayList<>();
        gridview= (GridView) view.findViewById(R.id.gridview);
        adapter=new ImagesVideosGridviewAdapter(getActivity(),gridItemList);
        gridview.setAdapter(adapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               // GridItemModel gridItem= (GridItemModel) parent.getItemAtPosition(position);
                Bundle args=new Bundle();
                args.putString("url",gridItemList.get(position).getUrl());
                FragmentTransaction transaction=getChildFragmentManager().beginTransaction();
                transaction.replace(R.id.frame_container_event_specific,new ShowFullImageFragment()).commit();//frame_container_event_specific is present in the main activity.

            }
        });
        new LoadMedia().execute("");
        return view;
    }

Logcat error
java.lang.IllegalArgumentException: No view found for id 0x7f0d008a (com.test.rajat.a10times:id/frame_container_event_specific) for fragment ShowFullImageFragment{ccc6a0 #0 id=0x7f0d008a}

A: Because your VP1 layout doesn't contain R.id.frame_container_event_specific, the fragment manager is unable to find the view. It's in the activity layout, so you better let the fragment manager from the activity to replace the fragment.
But think again about using the fragment approach. I think it's much simpler and easier to make the full image fragment as a standalone Activity. It displays full image anyway. Otherwise, even though you are able to replace the fragment correctly, you have to do a lot to manage the fragment back stack, like replacing the previous fragment when user hits back button.


text:
Q: Is there a way to link Save Results (for an insert DML operation) back to sObjects? Background
I have a list of sObjects I need to insert, but I must first check if the insert will be successful. So, I'm setting a database save point before performing the insert and checking the save results (for the insert statement). Because, I don't want to process if any errors occurred, if there were any errors in the insert results, the database is rolled back to the save point.
Problem & Question
I need to collect the errors for each save (insert) result and associate each error to the specific sObject record that caused the error. According to the documentation Save results contain a list of errors, the Salesforce ID of the record inserted (if successful), and a success indicator (boolean).
How do I associate the Save Result to the original sObject record inserted?
Code/Example
Here's an example I put together that demonstrates the concept. The example is flawed, in that the InsertResults don't always match the sObjectsToInsert. It's not exactly the code I'm using in my custom class, but it uses the same logic.
Map<Id,sObject> sObjectsToInsert; // this variable is set previously in the code
List<Database.SaveResult> InsertResults;

Map<String,sObject> ErrorMessages = new Map<String,sObject>();

System.SavePoint sp = Database.setSavepoint();

// 2nd parameter must be false to get all errors, if there are errors
//   (allow partial successes)
InsertResults = Database.insert(sObjectsToInsert.values(), false);

for(Integer i=0; i < InsertResults.size(); i++)
{
  // This method does not guarantee the save result (ir) matches the sObject
  //   I need to make sure the insert result matches
  Database.SaveResult ir = InsertResults[i];
  sObject s = sObjectsToInsert.values()[i];

  String em = null; // error message
  Integer e = 0; // errors

  if(!ir.isSuccess())
  {
    system.debug('Not Successful');
    e++;

    for(Database.Error dbe : ir.getErrors()) { em += dbe.getMessage()+' '; }
    ErrorMessages.put(em, s);
  }
}

if(e > 0)
{
  database.rollback(sp);

  // log all errors in the ErrorMessages Map
}

A: Your comment says the SaveResult list is not guaranteed to be in order, but I believe that it is. I've used this technique for years and have never had an issue.


text:
Q: Completely remove Unity and use gnome-shell instead
Possible Duplicate:
How can you remove Unity?

I really want to use Gnome-shell instead of Unity. But when i installed gnome-shell if found some interference from Unity in Gnome-shell desktop..
I want to use Gnome-shell as in Fedora or Arch, without any add-ons from Unity.
How to completely remove Unity without affecting my system ?

A: Another solution is to install from an Ubuntu minimal.iso and install gnome shell. After the base package is installed you will reboot to the terminal.  IIRC correctly it was pretty much just sudo apt-get install gnome-shell lightdm xorg gnome-tweak-tool.  Doing it that way is similar to doing a simplified Arch installation.


text:
Q: Oracle select rows above and below condition I'm selecting a certain value from an Oracle database. Once I select the value from the table is it possible to get the values directly above and below the one that I selected? If so, whats the best way to go about that? Have something like:
SELECT *
 FROM table_name
  WHERE name = 'F100'

So I would like to also select the values directly above and below 'F100' in the table
Data:
ID  | Name
123 | F300 <-
123 | F100 <-
123 | F700 <-
123 | F900
123 | F860
129 | F654
129 | F700 <-
129 | F100 <-
129 | F320 <-
129 | F790

A: The rows in a table are inherently unordered.  Concepts like "first", "last", "next", and "previous" all require that you specify some way to sort the data.  Assuming that there is some numeric column, say, id that you want to order by and that you want the "next" or "previous" data based on that id and that you want the next and prior values whether or not they have a name of "F100"
SELECT *
  FROM (SELECT id,
               name,
               lag(id) over (order by id) prior_id,
               lag(name) over (order by id) prior_name,
               lead(id) over (order by id) next_id,
               lead(id) over (order by id) next_name
          FROM your_table)
 WHERE name = 'F100'


text:
Q: GWT: writing excel file to client side I am using jakartaPOI to create an excel file in my GWT application
as it doesnt allow me to write the code on client side ,
So i have the code of writing excel file in my server side .
This creates an excel file correctly on server machine
What I want is to create the same excel file on the client/user machine.
Is there a solution for this
Thanks
Code:
         try {
        FileOutputStream fileOut = new FileOutputStream("D:\\POI111.xls");
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet worksheet = workbook.createSheet("POI Worksheet");

        // index from 0,0... cell A1 is cell(0,0)
        HSSFRow row1 = worksheet.createRow((short) 0);

        HSSFCell cellA1 = row1.createCell((short) 0);
        cellA1.setCellValue(dto.getColumn1());

        workbook.write(fileOut);
        fileOut.flush();
        fileOut.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "exported";
}

A: You cannot save file to the client system using javascript(GWT client side). Java script cannot access the disk contents. So if you need to save the file in client system, one option is to generate the file in server side and let the client download that file and save it.

A: seeing as GWT is compiled into javascript, and creating files of any kind is impossible (and rightly so) in javascript, what you would like to do is not possible in GWT.
At the risk of being ruthlessly down voted you can do this with a flash script, not knowing flash at all I can't really tell you how. In spite of that, I would recommend abandoning the idea altogether. Altering the client side machine should not be done.

A: You probably want to download the file. So you should create the file on the server and pass the client an id which can be use to map the location of the file located on the server. Using a Servlet you should be able to download a file. As for your comment on Email Application file download, the file is not created on the client system, it is downloaded. You might want to look at the existing post on downloading file.


text:
Q: Ignore Where Clause in Room I want to query a table, however I want to ignore WHERE clause if it's equal a certain value : Here is my Code :
@Query("SELECT * FROM content WHERE seen :seen")
public abstract List<content> getContent(String seen);

I want to Ignore the where clause "seen" if it's equal to "False".
I tried with seen = "seen" , similar to column = column, but it didn't work , it does however work in Sqlite Database Browser.
Any help please

A: If I can understands you well, you need to get all the list except that equals to False, you can use the != operator then
@Query("SELECT * FROM content WHERE seen :seen AND seen != 'False'")
public abstract List<content> getContent(String seen);

Or you can pass False as a method parameter
@Query("SELECT * FROM content WHERE seen :seen AND seen != :exclude")
public abstract List<content> getContent(String seen, String exclude);

But I am doubt that you mean you want to exclude the entire WHERE clause if the passed-in String equals to False, this can be done programmatically like below
In Repository:
public void getContent(String seen) {
    if (seen.equals("False"))
        mDao.getContent();
    else
        mDao.getContent(seen);
}

And implement getContent() in Dao that has no arguments.
@Query("SELECT * FROM content")
public abstract List<content> getContent();

Note: you have to handle the list listener in the repository

A: Try one of these (your question could be interpreted in different ways):
Option 1. Ignore "WHERE"-clause if method's parameter seen is 'False'
@Query("SELECT * FROM content WHERE seen =:seen OR :seen = 'False'")
public abstract List<content> getContent(String seen);

Option2. Ignore "WHERE"-clause for table's rows where field seen is 'False'
@Query("SELECT * FROM content WHERE seen =:seen OR seen = 'False'")
public abstract List<content> getContent(String seen);


text:
Q: Bootstrap: Dropdown child element without dropdowning parent element on navbar I have a bootstrap navbar menu. And My content is: "Menu Item" and "Dropdown Item"
In responsive mode, I want to reach "Dropdown Item" content without, opening "Menu Item"
My code:

      <button type="button" data-toggle="collapse" data-target="#navbar-collapse-1" class="navbar-toggle">Menu</button>

      <button type="button" data-toggle="collapse" data-target="#navbar-collapse-2" class="navbar-toggle">Dropdown Item Content</button>

      Brand

Menu Item

Dropdown Item

text

**
jsFiddle
https://jsfiddle.net/mj8qgakz/
**
-- See in responsive mode:
When I click "Menu" and after click "Dropdown Item Content" content is opening.
I want to achieve the same without clicking "Menu"
Is it possible in bootstrap?

A: if you just want to hide the menu item on the phone, something like:

Menu Item

if i understood the question... not sure

A: You don't need javascript or jquery to handle this.It can be achieved by using CSS only.
Here is the updated fiddle : JSFiddle
You can add this media query to your css to control the dropdown menu below 600px :
@media(max-width:600px){
  .dropdown-menu{
    height:auto;
    display:block;
    position:relative;
    background-color:transparent;
    box-shadow:none;
    border:0;
    margin-left:1em;
  }
  .caret{
    display:none;
  }
}


text:
Q: How to get added items list from cart on next activity I'm student and developing online food booking app . I'm getting food list from api and displaying in list.On + button I'm able to add item in cart but I want on cart image click , I move on new activity and there I want to  get all added items list and display in list view.1) 1st code snippet it my adapter class where I have + button to increase the item count .2) 2nd Code is my model class 3) 3rd code snippet is my fragment code where on button click i want to move on order class.
I advance thanks.Please help me.
 static ArrayList<AddedPizzaInfo> bookmarker_array = new ArrayList<AddedPizzaInfo>();
 holder.increase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count++;
                holder.integer_number.setText(String.valueOf(count));
                total_value = holder.integer_number.getText().toString();if(actionListener!=null)actionListener.onItemTap(holder.itemCopyIV);
                AddedPizzaInfo bookmarkerPojo = new AddedPizzaInfo();
                bookmarkerPojo.SetName(c.getName());
                bookmarker_array.add( bookmarkerPojo);// adding item but
=======
public class AddedPizzaInfo {
private String name = "";
public AddedPizzaInfo() {}
public AddedPizzaInfo( String name) {
    this.name = name;
}
public void SetName(String name){this.name = name;}
public String GetName(String name){
    return this.name;
}

}
====textCartItemCount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent startSecondActivityIntent = new Intent(Veg_Pizza_Activity.this, Order_Summary.class);
                startSecondActivityIntent.putExtra("items", Parcels.wrap(bookmarker_array));
                startActivity(startSecondActivityIntent);
                (Veg_Pizza_Activity.this).overridePendingTransition(0, 0);
            }
        });

A: Make your Item class implement @Parcel (using this library https://github.com/johncarl81/parceler)
then, on the first activity:
Intent startSecondActivityIntent = new Intent(this, SecondActivity.class);
startSecondActivityIntent.putExtra("items", Parcels.wrap(yourListOnItems));
startActivity(startSecondActivityIntent);

on the second acitivty:
@Override
protected void onCreate(Bundle savedInstanceState) {
    Bundle bundle = this.getIntent().getExtras();
    listOfItems = Parcels.unwrap(bundle.getParcelable("items"));
}

Alternatively to using Parceler library you could implement Parceleable natively but will take too much time and generate too much boilerplate code.
EDIT:
AddedPizzaInfo.class:
@Parcel
public class AddedPizzaInfo{
    //code whatever

    //add empty constructer, required by parceler
    public AddedPizzaInfo(){}

    //rest of the code
}

build.gradle:
...

dependencies {

   ///other dependencies
    implementation 'org.parceler:parceler-api:1.1.9'
    annotationProcessor 'org.parceler:parceler:1.1.9'
}

and then run the code I first added when you want to send the objects you your second activity.

A: To send list data from one activity use the following code sample
Intent intent = new Intent(this, TargetActivity.class);
        intent.putStringArrayListExtra("your_list",listOfData);
        startActivity(intent);

To retrieve the list in TargetActivity use
if(getIntent()!=null){
    your_array_list = getIntent().getStringArrayListExtra("your_list");
}


text:
Q: What is a good technique to decide step size in sub-gradient method for dual decomposition? I am looking at the following paper to implement dual decomposition for my algorithm:
http://www.csd.uoc.gr/~komod/publications/docs/DualDecomposition_PAMI.pdf
On Pg.29 they suggest setting the step size for the sub-gradient method by taking the difference of the best primal solution and current dual solution and dividing by the L2-norm of the sub-gradient at current iteration.
My doubt is the following: Do I use sub-gradients for each slave problem and compute a different step-size for each slave problem? Or is there some way I can compute the sub-gradient for the combined dual problem?

A: Step-sizes are the crucial and difficult point when using subgradient methods. Basically you need that the step-sizes tend to zero but not too fast. If one uses a-priori step-sizes (e.g. of the form $1/k$) then the method provably converges but in practice it will slow down such that you'll not observe convergence.
The dynamic rule they suggest in the paper (in equation (40)) look like so-called Polyak step-sizes with estimation of the true optimal values (obtained by values of the dual problem). One can prove convergence with these step-sizes under special conditions. I do not know a good reference off the top of my head but many books on (nonsmooth) convex optimization should treat this.

A: I can not found where Stephen Boyd said it during EE364B class at Stanford, but you can not really increase speed of (sub)gradient methods tremendously. Slides:
https://stanford.edu/class/ee364b/lectures/subgradients_slides.pdf
https://stanford.edu/class/ee364b/lectures/subgrad_method_slides.pdf
Videos: You can look for Lecture1-Lecture3 of EE364B with S.Boyd in youtube or itunes university date back to EE364B. They are about subgradient methods for unconstrained convex optimization problems.
You will see various things, including various things.
Also Stephen Boyd has interesting/fun teaching style.
In paper that you mentioned steps size is interesting. When I have a deal with first order primal-dual methods I used usual gradient descend with backtracking.
But during this videos you will observed that you "can do whatever you want" until you minimize Lyapunov (and other names) function which measures or certifies your progress with each step (like distance to optimal point, or value of function at current point)


text:
Q: Providing self-hosted OnlyOffice redirect URI We have self-hosted OnlyOffice on our server.  Let's assume the self-hosted OnlyOffice is running at https://myprivate.onlyoffice.com.
We want to connect OnlyOffice with Google Drive to sync the artifacts.
We have setup OnlyOffice to Google Drive connection using OAuth client id option and configured client id and client secret too at OnlyOffice side. In addition, we have provided https://myprivate.onlyoffice.com as the redirect URI at Google OAuth page.
With all these configuration, when we click on Documents module -> Connect -> Google Drive icon, we get redirect mismatch error with URI required as "https://service.onlyoffice.com/oauth2.aspx".  This URI is a public cloud URI from OnlyOffice.  It's our understanding that we need to provide our self-hosted server URI as redirect URI.
Can you please help accomplish our objective of connecting to Google Drive with our self-hosted server URI?  If that's not possible, we would like to know why we need to use "https://service.onlyoffice.com/oauth2.aspx" for our self-hosted.  Because, that will put things in mix of using self-hosted plus OnlyOffice cloud URI.
Thanks


text:
Q: css grid custom layout flow I need to make list of content, to be formatted,
I have something

  Item
  Item
  Item
  Item
  Item
  Item
  Item
  Item
  Item
  Item
  Item

like this.  Number of items is dynamic and I always want first 6 would be in row mode all others in column. for example
- - - - - -
    - -
    - -
    - -
    - -

in the item order should be:
1 2 3 4 5 6
    7 8
    9 10
    11 12

fill free to options, using grid or flex wrap

A: Using grid would be like this

.container {
  display: grid;
  /* Create six columns and four rows */
  grid-template-columns: repeat(6, 1fr);
  grid-template-rows: repeat(4, 50px);
}

/* Select every second, starting at sixth */
.item:nth-child(2n+7) {
  /* Specify the column to put the item */
  grid-column: 3;
}

  Item
  Item
  Item
  Item
  Item
  Item
  Item
  Item
  Item
  Item
  Item
  Item


text:
Q: Python3: unsupported operand type(s) for +: 'float' and 'str' I'm tryin to add commas to big numbers in my code. When I isolate the code it works:
num = str(12354343)
print("{:,}".format(float(num)))

But inside my code I receive the error unsupported operand type(s) for +: 'float' and 'str'.
def commafy(x):
    x = "{:,}".format(float(x))
    return x

i=1

d = resp.json()
for result in d['results']:
    #print(result['campaign_name'])
    data[i] = {'Source': 'Taboola', 'Campaign': result['campaign_name'], 'Impr.': commafy(result['impressions']), 'CTR': round(result['ctr'],2) + "%", 'Spent': result['spent']}
    i+=1

What is wrong here?
Thank you,

A: Your problem is elsewhere:

'CTR': round(result['ctr'],2) + "%",

The result of round is is a float and you are trying to concattenate it with '%' which is a string.
You are not commafyìng the float result here ...
'CTR': f"{round(result['ctr'],2)}%", # should work for 3.6+ (string interpolation syntax)

or
'CTR': "{}%".format(round(result['ctr'],2)), # should work for below 3.6


text:
Q: Clarification regarding Static local variables In a link Storage Class Specifier
under the topic Static local variables
I read that

Variables declared at block scope with the specifier static have static storage duration but are initialized the first time control passes through their declaration (unless their initialization is zero- or constant-initialization, which can be performed before the block is first entered).

I don't understand what does it actually mean by saying:

which can be performed before the block is first entered

Plus, Does a static local variable can be said to be having No Linkage?
Could you please throw some examples if necessary? Thanks

A: The relevant part is when the init value is known.
When it is known with the additional guarantee that it will not change before the block is first executed.
Below is code with some examples.
int foo(void);

void bar(void)
{
    static int ZeroInit;     // zero init
    static int a = 0;        // constant init
    static int b = 4;        // constant init
    // values for above inits are known at start of runtime and even earlier

    static int c = foo();
    // dynamic init, value unknown before execution of foo(),
    // which cannot (i.e. is defined not to) be done before executing the block

    /* code */
}


text:
Q: Wordpress media uploads are owned by user nobody I goofed and deleted my public_html folder, I had a copy on a different computer and I ftp them over to the server and everything works well accept the media upload.
So my wordpress media uploads gave me an error could not make dir. check permissions. so I 777 the whole directory (unsafe i know) and I successfully uploaded a media file. i look at the new directory it created and the media file and come to find out the directory and image are permissions 777 and owned by user nobody group nobody.
I ran  and its run by the user i want.
How do I get it so wordpress uploads on a user let alone the one I want??


text:
Q: Apache Superset - Problem with CSV upload: FileNotFoundError I've a problem in Apache Superset during the CSV upload. When i try to upload a CSV file, it return this error: FileNotFoundError: [Errno 2] No such file or directory: '/app/pythonpath/app/static/uploads/tmpkvod0plb.csv'
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 2464, in __call__
    return self.wsgi_app(environ, start_response)
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 2450, in wsgi_app
    response = self.handle_exception(e)
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1867, in handle_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 2447, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1952, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1821, in handle_user_exception
    reraise(exc_type, exc_value, tb)
  File "/usr/local/lib/python3.6/site-packages/flask/_compat.py", line 39, in reraise
    raise value
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1950, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python3.6/site-packages/flask/app.py", line 1936, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/usr/local/lib/python3.6/site-packages/flask_appbuilder/security/decorators.py", line 109, in wraps
    return f(self, *args, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/flask_appbuilder/views.py", line 94, in this_form_post
    response = self.form_post(form)
  File "/app/superset/views/database/views.py", line 141, in form_post
    delete=False,
  File "/usr/local/lib/python3.6/tempfile.py", line 551, in NamedTemporaryFile
    (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type)
  File "/usr/local/lib/python3.6/tempfile.py", line 262, in _mkstemp_inner
    fd = _os.open(file, flags, 0o600)
FileNotFoundError: [Errno 2] No such file or directory: '/app/superset/app/static/uploads/tmpt537yamb.csv'*

A: The error message is very generic but without any other detail have a look at /app/pythonpath/app/static/uploads and:

*

*check directory existence

*check privileges

*check if that pathname is writable by the user running Apache Superset

If the directory does not exist, create it:
mkdir /app/pythonpath/app/static/uploads

A: Got the same problem when trying to upload csv to mysql. I found the solution from that issues
The reason is this running container does not have enough privilege. So you need to assign root to the superset when using docker-compose:
    env_file: docker/.env
    build: *superset-build
    container_name: superset_app
    command: ["flask", "run", "-p", "8088", "--with-threads", "--reload", "--debugger", "--host=0.0.0.0"]
    restart: unless-stopped
    ports:
      - 8088:8088
    user: root:root # add here
    depends_on: *superset-depends-on
    volumes: *superset-volumes


text:
Q: Error in linear regression In linear regression we have $Ax=b$. Since the equality is an approximate equality, an error vector is used, that is, $Ax+e=b$. We know that using the least square method (to minimize the squared sum of the elements of $e$) the best $x$ is given by:
$x=A^+b$ where the plus sign represents the pseudoinverse: $A^+=(A^TA)^{-1}A^T$.
Depending on $A$ and $b$, there must be some error which is often nonzero as in linear regression we are doing a non-perfect curve estimation. However,
$e=b-Ax$ which is $e=b-AA^+b$ and since $AA^+=I$ always holds, the error is always zero, that is,
$e=b(I-AA^+)=b(I-I)=zero$.
Why is that? I think the error vector should not be zero regardless of $A$ and $b$. Can one explain this to me. Thank you!

A: No.
In linear regression the matrix $A$ has more rows than columns, and hence (according to the "Definition" section of the wikipedia article) $AA^+$ is not the identity matrix, but rather the projection matrix onto the column space of $A$.
The normal equations folded into the formula $x=A^+b$ forces the fitted error vector $e=b-AA^+b$ to  perpendicular to the column space of $A$, so the analysis of variance (or Pythagorean theorem) $\|b\|^2=\|Ax\|^2+\|e\|^2$ holds


text:
Q: Using dot source function in params I'm going to start by saying I'm still pretty much a rookie at PowerShell and hoping there is a way to do this.
We have a utils.ps1 script that contains just functions that we dot source with in other scripts.  One of the functions returns back a default value if a value is not passed in.  I know I could check $args and such but what I wanted was to use the function for the default value in the parameters.
param(
    [string]$dbServer=$(Get-DefaultParam "dbServer"),
    [string]$appServer=$(Get-DefaultParam "appServer")
)

This doesn't work since the Util script hasn't been sourced yet.  I can't put the dot source first because then params doesn't work as it's not the top line.  The utils isn't a module and I can't use the #require.
What I got working was this
param(
    [ValidateScript({ return $false; })]
    [bool]$loadScript=$(. ./Utils.ps1; $true),
    [string]$dbServer=$(Get-DefaultParam "dbServer"),
    [string]$appServer=$(Get-DefaultParam "appServer")
)

Create a parameter that loads the script and prevent passing a value into that parameter.  This will load the script in the correct scope, if I load it in the ValidateScript it's not in the correct scope.   Then the rest of the parameters have access to the functions in the Utils.ps1.  This probably is not a supported side effect, aka hack, as if I move the loadScript below the other parameters fail since the script hasn't been loaded.

*

*PowerShell guarantee parameters will always load sequential?

*Instead should we put all the functions in Utils.ps1 in global scope?  this would need to run Utils.ps1 before the other scripts - which seems ok in scripting but less than ideal when running the scripts by hand

*Is there a more supported way of doing this besides modules and #require?

*Better to not use default value of params and just code all the checks after sourcing and check $args if we need to run the function?

A: It would be beneficial to instead turn that script into a PowerShell Module, despite your statement that you desire to avoid one. This way, your functions are always available for use as long as the module is installed. Also, despite not wanting to use it, the #Require directive is how you put execution constraints on your script, such as PowerShell version or modules that must be installed for the script to function.

If you really don't want to put this into a module, you can dot-source utils.ps1 from the executing user's $profile. As long as you don't run powershell.exe with the -NoProfile parameter, the profile loads with each session and your functions will be available for use.


text:
Q: ¿Por qué "null instanceof Object" retorna false? Si typeof null es igual a "object", ¿por qué null instanceof Object es igual a false?

console.log(typeof null);
console.log(null instanceof Object);

A: Es así por diseño, así que la única respuesta objetiva a esta pregunta es ...

Porque así lo dice la especificación ECMAScript.

En la página de MDN vemos que ellos cumplen con el estandar pero no están de acuerdo con el mismo:

typeof null        // object (bug en ECMAScript, debería ser null)
typeof undefined   // undefined
null === undefined // false
null  == undefined // true

Si la pregunta es "por qué se diseñó así", el único que podría responder es Brendan Eich, pero podemos elucubrar:
Javascript fue diseñado en tiempo récord y tomó muchas ideas y la sintaxis de Java. En Java sólo una variable cuyo tipo declarado sea una clase puede valer null. Los tipos primitivos no trabajan con null, por lo que en Java tenemos que si declaramos lo siguiente:
class A {
    int a;
}

Y luego hacemos lo siguiente:
A ejemplo = null;

Tenemos una variable cuyo tipo es A (que extiende Object, como todas las clases), pero puesto que su valor es null no es todavía una instancia de A
ejemplo instanceof A //devuelve false

Una vez que instanciamos:
ejemplo= new A();
if (ejemplo instanceof A) {
    println(ejemplo.a;) //0
}

La propiedad a es de un tipo primitivo que no puede ser null, así que si no declaramos su valor valdrá 0.
Java no tiene el operador typeof porque no lo necesita, sabemos el tipo de las variables porque es un lenguaje con tipado estático.
Volviendo a Javascript, creo que su creador se basó en esto para definir el comportamiento de typeof y de instanceof.

A: Partimos de que null es uno de los tipos de datos primitivos que posee JS como lenguaje.

*

*String

*Number

*undefined

*null

*booleanos

*bigint revisar compatibilidad
Basándonos en la Especificación de ES1, tenemos por ejemplo que para los valores primitivos de tipo String estos mismos pertenecen al grupo de los String que a su vez si es una instancia del Object.
Si por ejemplo hacemos esto:

    console.log(String instanceof Object)

Lo cual nos devuelve true
String posee algunos métodos como los siguientes:

*

*length

*name

*prototype

Lo mismo pasa ahora con Boolean que posee métodos como los siguientes:

*

*apply

*arguments

*bind

*etc.

Sin embargo si ahora nos vamos a la misma especificación, en el apartado: 4.3.11 y 4.3.12 que habla sobre null value y Null Type respectivamente; donde como notas no indica pertenecer como miembro de Object
Lo interesante de esto es que podemos leer que es una ausencia intencional de valor asignado a una variable o constante....
EJEMPLO
En el siguiente script puedes notar por ejemplo que, la variable tiene un valor asignado de: null y dentro del ciclo de vida del operador ternario comprobamos si efectivamente dicha variable posee ese valor; una vez que eso se confirma le reasignamos un nuevo valor a dicha variable que ahora será un string

    let valor = null

    console.log((valor === null) ? valor = "Hola" : 0)

Si revisas el siguiente enlace2 podrás encontrar que aunque el hecho de escribir typeof null devuelva object esto esta considerado como un bug y  no es el valor que realmente debería retornarte.
Por ejemplo si escribes el siguiente código la salida será 0 ya que el valor asignado a la variable no es null:

    let valor = 123

    console.log((valor === null) ? 1 : 0)

Referencias

*

*1 ECMASCRIPT SPEC

*2 Null value

A: Creo la respuesta se debe a que object es el tipo de dato default cuando el tipo de dato no corresponde a ningún otro tipo de dato primitivo de javascript.
Mientras que en la segunda evaluación que haces te devuelve falso porque null por definición no es la instancia de ningúna clase, por tanto da igual contra que lo compares siempre será falso.


text:
Q: Can't make og:determiner work on Open graph object I am trying to post an open graph action with one of my objects.
Everything works fine except that I need the 'a' article used with my object, so I added the og:determiner meta tag as described in the docs:
<meta property="og:determiner" content="a" />

But when I check the post on my timeline I see that the determiner is not used at all and the sentence comes out strange.
What might be wrong? am I missing some definition in the dev app?


text:
Q: How to tell tell the ./configure file where to take the dependencies from? I want to install Libav locally in a folder and for that I have to install yasm (I can disable the dependency but I don't want to just for the sake of the argument). The installation of the package is done in the terminal via "./configure" and "make" (when I run "./configure" I receive the message, that yasm is missing). How can I tell to "./configure" to take it's yasm dependencies from the path "./libs" (there is a folder with libraries in the parent folder). Should I modify the makefile (and if yes should I change only the LDflags? to what?) or add the " --extra-ldflags="-L./libs" " to the ./configure command? What would be the use of cflags here?

A: To have autotools' configure use dependencies from a specific directory, the following may or may not work, as the configure script can be written differently:

*

*--extra-ldflags (there should be --extra-cflags too) is fine, if it's there;

*for library dependencies, you can add CFLAGS="-I<path>" CXXFLAGS="<same>" LDFLAGS="-L<path>" to ./configure's environment or to its command line arguments;

*cleaner approach: if you have pkg-config configuration generated and installed for your dependencies, you can specify a PKG_CONFIG_PATH instead. In special cases of cross-compilation, one can use PKG_CONFIG_SYSROOT_DIR.

*for local host executables, append/prepend to PATH.

Related question: https://unix.stackexchange.com/questions/19663/how-to-change-the-compiler-settings-with-automake


text:
Q: Passing parameters to a resolve function I'm having trouble figuring out how I could pass a parameter to a function that is a part of resolve of ngRoute.
In my case I'm doing stuff with tokens. These tokens are typed, so you cannot use the same token for confirming and email and reseting a password. Here's how my routes are defined:
.when("/confirm/:token", {
    controller: "confirmEmailController",
    templateUrl: "/app/views/confirmEmail.html",
    resolve: {
        tokenStatus: getTokenStatus
    }
})
.when("/reset/:token", {
    controller: "resetPasswordController",
    templateUrl: "/app/views/resetPasswordEmail.html",
    resolve: {
        tokenStatus: getTokenStatus
    }
})

Here's the getTokenStatus function that's being called for both of them:
var getTokenStatus = ["$q", "$route", "tokenService", function($q, $route, tokenService)
{
    var deferred = $q.defer();

    var tokenType = ???? //<-- how do I pass this?

    tokenService
        .getTokenStatus($route.current.params.token, tokenType)
        .success(function(response)
        {
            deferred.resolve(true);
        })
        .error(function()
        {
            deferred.resolve(false);
        });

    return deferred.promise;
}];

The problem is that in order to avoid code duplication I need to somehow pass the value of the token type, as marked in the code. How could I do that?
I've been messing about with this for the last 2 hours, but can't seem to figure it out.

A: 1. You can try to include token type into route
.when("/:tokenType/:token", {
    controller: "confirmEmailController",
    templateUrl: "/app/views/confirmEmail.html",
    resolve: {
        tokenStatus: getTokenStatus
    }
})
.when("/:tokenType/:token", {
    controller: "resetPasswordController",
    templateUrl: "/app/views/resetPasswordEmail.html",
    resolve: {
        tokenStatus: getTokenStatus
    }
})

And then just get it from $route.current.params.tokenType. But it's not clean solution - you should check your URL for validity.
2. You can use function wrapping
$routeProvider.when("/confirm/:token", {
    controller: "confirmEmailController",
    templateUrl: "/app/views/confirmEmail.html",
    resolve: {
        tokenStatus: getTokenStatus("confirm")
    }
})
.when("/reset/:token", {
    controller: "resetPasswordController",
    templateUrl: "/app/views/resetPasswordEmail.html",
    resolve: {
        tokenStatus: getTokenStatus("reset")
    }
});

var getTokenStatus = function(tokenType) {
    return ["$q", "$route", "tokenService", function($q, $route, tokenService) {
        var deferred = $q.defer();
        tokenService
            .getTokenStatus($route.current.params.token, tokenType)
            .success(function(response)
            {
                deferred.resolve(true);
            })
            .error(function()
            {
                deferred.resolve(false);
            });
        return deferred.promise;
    }];
};

3. You can move get-token-status logic into separate servise
$routeProvider.when("/confirm/:token", {
    controller: "confirmEmailController",
    templateUrl: "/app/views/confirmEmail.html",
    resolve: {
        tokenStatus: ['tokenStatusGetterService', function(tokenStatusGetterService){
            return tokenStatusGetterService("confirm");
        }]
    }
})
.when("/reset/:token", {
    controller: "resetPasswordController",
    templateUrl: "/app/views/resetPasswordEmail.html",
    resolve: {
        tokenStatus: ['tokenStatusGetterService', function(tokenStatusGetterService){
            return tokenStatusGetterService("reset");
        }]
    }
});

//...

.service('tokenStatusGetterService', ["$q", "$route", "tokenService", function($q, $route, tokenService) {
    return function(tokenType) {
        var deferred = $q.defer();
        tokenService
            .getTokenStatus($route.current.params.token, tokenType)
            .success(function(response)
            {
                deferred.resolve(true);
            })
            .error(function()
            {
                deferred.resolve(false);
            });
        return deferred.promise;
    };
}]);

A: one way to do it is to put a function on your getTokenStatus service.
this is a simplified example, yet it shows how to pass an argument to your resolve function.
app.factory('getTokenStatus',['$q', '$timeout', '$route', function($q, $timeout, $route){
  this.action = function(tokenType) {
    var defer = $q.defer();

    $timeout(function(){
      var res = {
        path: $route.current.params.token,
        tokenType: tokenType
      }
      defer.resolve(res);
    },1000);

    return defer.promise;
  }

  return this;
}]);

and call it from your resolve object:
app.config(function($routeProvider){
  $routeProvider
  .when("/123/:token", {
    template: "
hello
",
    controller: 'testCtrl',
    resolve: {
      tokenStatus: function(getTokenStatus) {
        return getTokenStatus.action('firstToken').then(function(res){
          console.log(res);

        });
      }
    }
})

here's a plnkr