text:
Q: Can I query per hour increment of a accumulation column in clickhouse? I want to save event time and the total amount of generated electric per 30 seconds. The total amount is not reseted to zero everytime. It's just the total from the meter first started to now, not total amount generated in the 30 seconds.
Is there any way of querying daily, weekly or monthly aggregations on the total amount of generated electric column (Maybe not just sum or avg)?
Or by design a AggregatingMergeTree table?
I don't need to keep every record, just need the daily, weekly and monthly aggregations.
For example :
create table meter_record (
   event_time Datetime,
   generated_total Int64
)

A: UPDATE
Prefer to use SimpleAggregateFunction instead of AggregateFunction for simple functions like median, avg, min, max to speed up aggregates calculation.

Let's suggest you need to calculate median, average and dispersion aggregations for this table:
CREATE TABLE meter_record (
   event_time Datetime,
   generated_total Int64
)
ENGINE = MergeTree
PARTITION BY (toYYYYMM(event_time))
ORDER BY (event_time);

Use AggregatingMergeTree to calculate required aggregates:
CREATE MATERIALIZED VIEW meter_aggregates_mv
ENGINE = AggregatingMergeTree()
PARTITION BY toYYYYMM(day)
ORDER BY (day)
AS
SELECT
  toDate(toStartOfDay(event_time)) AS day,
  /* aggregates to calculate the day's section left and right endpoints */
  minState(generated_total) min_generated_total,
  maxState(generated_total) max_generated_total,
  /* specific aggregates */
  medianState(generated_total) AS totalMedian,
  avgState(generated_total) AS totalAvg,
  varPopState(generated_total) AS totalDispersion
  /* ... */
FROM meter_record
GROUP BY day;

To get required daily / weekly / montly (and any day-base aggregation like quarterly or yearly) aggregates use these queries:
/* daily report */
SELECT
  day,
  minMerge(min_generated_total) min_generated_total,
  maxMerge(max_generated_total) max_generated_total,
  medianMerge(totalMedian) AS totalMedian,
  avgMerge(totalAvg) AS totalAvg,
  varPopMerge(totalDispersion) AS totalDispersion
FROM meter_aggregates_mv
/*WHERE day >= '2019-02-05' and day < '2019-07-01'*/
GROUP BY day;

/* weekly report */
SELECT
  toStartOfWeek(day, 1) monday,
  minMerge(min_generated_total) min_generated_total,
  maxMerge(max_generated_total) max_generated_total,
  medianMerge(totalMedian) AS totalMedian,
  avgMerge(totalAvg) AS totalAvg,
  varPopMerge(totalDispersion) AS totalDispersion
FROM meter_aggregates_mv
/*WHERE day >= '2019-02-05' and day < '2019-07-01'*/
GROUP BY monday;

/* monthly report */
SELECT
  toStartOfMonth(day) month,
  minMerge(min_generated_total) min_generated_total,
  maxMerge(max_generated_total) max_generated_total,
  medianMerge(totalMedian) AS totalMedian,
  avgMerge(totalAvg) AS totalAvg,
  varPopMerge(totalDispersion) AS totalDispersion
FROM meter_aggregates_mv
/*WHERE day >= '2019-02-05' and day < '2019-07-01'*/
GROUP BY month;

/* get daily / weekly / monthly reports in one query (thanks @Denis Zhuravlev for advise) */
SELECT
  day,
  toStartOfWeek(day, 1) AS week,
  toStartOfMonth(day) AS month,
  minMerge(min_generated_total) min_generated_total,
  maxMerge(max_generated_total) max_generated_total,
  medianMerge(totalMedian) AS totalMedian,
  avgMerge(totalAvg) AS totalAvg,
  varPopMerge(totalDispersion) AS totalDispersion
FROM meter_aggregates_mv
/*WHERE (day >= '2019-05-01') AND (day < '2019-06-01')*/
GROUP BY month, week, day WITH ROLLUP
ORDER BY day, week, month;

Remarks:

*

*you point that raw-data is not required to you just aggregates, so you can set engine for meter_record-table as Null, manually clean meter_record (see DROP PARTITION) or define the TTL to do it automatically

*removing raw-data is bad practice because it makes impossible to calculate new aggregates on historical data or restore exist aggregates etc

*the materialized view meter_aggregates_mv will contains only the data inserted in the table meter_record after creating the view. To change this behavior use POPULATE in view definition


text:
Q: what is the benefit to using mongoose .exec?   User.find().exec(function (err, users) {
    if (err){
      callback(err);
    } else {
      callback(users);
    }
  });

  User.find(function (err, users) {
    if (err) {
      callback (err);
    } else {
      callback(users);
    }
  });

What is the benefit of using the top code? both seem to work equally well

A: They are identical and there's no benefit in your example
When you do not pass a callback to find function it won't execute but instead returns a query then you need to use exec()
var query = User.find();

now you can add some more criteria
query.where({age: 15});

and some more
query.select({name:1}); // or {firstname:1, lastname:1} etc.

now you've built up your query so to get the results you need to execute it.
query.exec(function(err, users){

});

But you can also do this like
User.find({age:15}, {name:1}, function(err, users){

});

Above is identical to
User.find({age:15}, {name:1}).exec(function(err, users){

});

since there's no callback in find function it will return query which means no results, exec will give you the results

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change of basis related to conics I was trying to solve some change of basis exercises, so I've done them and I want you to tell me if I've done it correctly.

1) Given the coordinates system $(O'; X'' Y'')$ asociated to the
  basis $B=[{b_1=\frac{1}{\sqrt{2}}; \frac{1}{\sqrt{2}};
> b_2=\frac{-1}{\sqrt{2}}; \frac{1}{\sqrt{2}}}]$ with origin in
  $O'=(2;5)$, find the intersection between $Q: y''^2=-4 \sqrt{2} x''$
  and the straight line in $(O,XY)$ $V=(0;5)+t(-1;1) t\epsilon R$

Well, first I tried to write $Q$ in terms of $X$ and $Y$, and not in terms of $X''$ and $Y''$. I used the formula:
$(\begin{matrix}
X''\\
Y'' \\
\end{matrix})$ =$(C)_B$ × $(\begin{matrix}
X-2\\
Y-5 \\
\end{matrix})$
Then I replaced those values in the equation of $Q$ and I got $Q: \frac{(-x+y-3)^2}{2}=-4 \sqrt{2} \frac{(x+y-7)}{\sqrt{2}}$
After that, I found the intersection between $Q$ and $V$ using equations and I got that the intersection points in $(O;XY)$ are $P_1(3;2)$ and $P_2(-1;6)$

2)Given the coordinates system $(O,X'Y')$ asociated to the basis
  $B=[{b_1=\frac{1}{\sqrt{2}}; \frac{1}{\sqrt{2}};
> b_2=\frac{-1}{\sqrt{2}}; \frac{1}{\sqrt{2}}}]$ with origin in
  $O=(0;0)$ and the ellipse $9X'^2+5Y'^2-3X'+2Y'-10=0$ find the
  coordinates of the centre of the ellipse in $(O,XY)$

So, here I found the centre of the ellipse in $(O,X'Y')$ and it was $(\frac{1}{6}; - \frac{1}{5})$, then, doing something similar to what I've done before I found out that the centre in $(O,XY)$ was $( \frac{11}{30 \sqrt{2}};$ $\frac{-1}{30 \sqrt{2}}$)


text:
Q: Tkinter user input Trying to get clients input and make a search google
Example:

client's  input entry = business emails
  output = opens a new tab in
  chrome > searches google for,   "intext:gmail.com business emails"

from tkinter import *
import webbrowser
root = Tk()
def main():
        global userInput
        root = Tk()

Label2 = Label(text="GhostTest")
Label2.pack()

userInput = Entry(bd=2)
userInput.pack()

Button1 = Button(text="Search,", command=userInput)
Button1.pack()

def GoogleSearch():
        new = 2
        userInput = Entry(bd=2)
        term = Entry(userInput)
        tabUrl = "http://google.com/?#q="
        webbrowser.open(tabUrl+str(term.get()),new=new);

root.mainloop()

if __name__=='__main__':
    main()

A: You have to assign function name (without parenthesis) to command=
import tkinter as tk
import webbrowser

# --- functions ---

def google_search():
    new = 2

    # get user input
    term = user_input.get()

    tabUrl = "http://google.com/?#q="
    webbrowser.open(tabUrl+term, new=new);

# --- main ---

root = tk.Tk()

lbl = tk.Label(text="GhostTest")
lbl.pack()

user_input = tk.Entry(bd=2)
user_input.pack()

# run `google_search` on button click
btn = tk.Button(text="Search", command=google_search)
btn.pack()

root.mainloop()


text:
Q: How to swap two XML elements in linq to xml I want to swap two xml elements. How do i do this? Here is the code. I tried the solution here but it did not work for me after all. I want to swap the both  elements. When I run the program the elements are not swapped but when I call ToList() it is swapped in the List but not swapped in the doc variable
<template id="12">
  <tabs>
    <tab>
      <name>test1</name>
      <description />
    </tab>
    <tab>
      <name>test2</name>
      <description />
    </tab>
  </tabs>
</template>

Here is the code to swap them
        var doc = XDocument.Parse(q.XMLtext);
        var Current = doc.ElementOrDefault("template").ElementOrDefault("tabs").ElementsOrDefault("tab").Where(x => (string)x.Element("name") == name).FirstOrDefault();
        var Previous = Current.PreviousNode as XElement;
        var Next = Current.NextNode as XElement;
        var CurrentName = (string)Current.ElementOrDefault("name");
        var PreviousName = (string)Previous.ElementOrDefault("name");
        var NextName = (string)Next.ElementOrDefault("name");
        if (MoveDirection == (int)MoveType.Up)
        {
            doc.ElementOrDefault("template").ElementOrDefault("tabs").ElementsOrDefault("tab").Where(x => (string)x.Element("name") == CurrentName || (string)x.Element("name") == PreviousName).Reverse();

        }
        else
            //doc.ElementOrDefault("template").ElementOrDefault("tabs").ElementsOrDefault("tab").Where(x => x == Current || x == Next).Take(2).Reverse();

        q.XMLtext = doc.ToString();
        context.SaveChanges();

A: I'm afraid I haven't quite worked out exactly which elements you want to swap, but XElement.ReplaceWith is what you're after, I believe. Here's a short but complete program which demonstrates it:
using System;
using System.Xml.Linq;

class Program
{
    static void Main()
    {
        string xml = @"
<root>
  <element1/>
  <element2/>
  <element3/>
  <element4/>
  <element5/>
</root>";
        XDocument doc = XDocument.Parse(xml);
        XElement x = doc.Root.Element("element2");
        XElement y = doc.Root.Element("element4");
        x.ReplaceWith(y);
        y.ReplaceWith(x);
        Console.WriteLine(doc);
    }
}

This swaps element2 and element4.
Note that this works because the first x.ReplaceWith(y) actually creates a copy of y, leaving the original in its existing location... ready to be replaced with x.

A: .Reverse() returns the elements in reverse order.  It's doesn't swap them.


text:
Q: Parsing a template file with C++ Recently I've been busy with some PHP framework - completely off-topic by the way.
Anyhow, I got specific html/template files I would like to parse with C++ (don't ask me why, it's just because I want to write it in C++). Besides that, it might actually be the first useful thing I would ever write in C++.
Anyway, to get back to the problem, imagine I have a file like the following:

        ID
        Title
        Actions

    {foreach from="$pages => $page"}

        {$page.Id()}
        {$page.Title()}
        Edit | Delete

    {foreachelse}

        There are no pages to be displayed

    {/foreach}

And the output should be:

        ID
        Title
        Actions

    <?php if(count($pages) > 0): ?>
    <?php foreach($pages as $page): ?>

        <?php echo $page->getId(); ?>
        <?php echo $page->getTitle(); ?>
        <a href="page/edit/<?php echo $page->getId(); ?>/">Edit | <a href="page/delete/<?php echo $page->getId(); ?>/">Delete

    <?php endforeach; ?>
    <?php else: ?>

        There are no pages to be displayed

    <?php endif; ?>

Why I am doing this might not be exactly clear to you, but it remains a problem, applicable somewhere else in any case.
Anyhow, some forward and backward lookups and modifications in the output files are required. What is the right approach to this problem?

A: You can write a handcrafted parser, which might be nontrivial, depending on your actual requirements. Your next best bet is to use BNF-like C++ parsers, e.g. boost::spirit, so you don't need to sweat processing parsing rules yourself. You will still need to write correct semantic actions to convert { ... } to php.

A: The right approach, in my view, would not to re-invent the wheel (i.e. writing your own parser) but rather an existing library that will make it easier and less time consuming for you. One of those C++ libraries could be wxHTMLParser or wxHTML.

A: For these type of problems I tend to be inclined towards REGEX. Using either boost::regex or the GNU regex classes or any other library. Identifying those markers and converting them is mostly a regex search and replace thing (with parameters for variable names, values, etc.), and you don't have to write code to actually parse the complete HTML and the special inserts.


text:
Q: Find all positions of an occurence in a char array I am trying to write a method which takes in a single letter (string) and a char aray which creates a boolean array. The boolean array is then initialized with all positions as false.
A for loop then iterates through the char array and for each position where the letter (guess) is found in the char array the same position in the boolean array is marked true.  The problem is in the if section of the for loop. The syntax is not what my JDE accepts.
Any tips gratefully received.
    boolean[] printIfTrue = new boolean[wordInArray.length];
    for (int i = 0 ; i == wordInArray.length ; i++) {
        if (wordInArray[i] == guess ){                   // problem
            printIfTrue[i] == true;                      // problem
        }

    }

    return printIfTrue;
}

A: The loop could be rewritten as follows. Furthermore, guess should be of type char.
for (int i = 0 ; i < wordInArray.length ; i++) {
    printIfTrue[i] = wordInArray[i] == guess;
}

A: You can't compare a String with a char. Your guess variable should be of type char (using guess = valueEnteredByTheUserAsString.charAt(0)).
== is a comparison operator. To assign a value to a variable, you must use =:
printIfTrue[i] = true;

I read == as is same as.:
if (wordInArray[i] == guess )

is read as

if the ith char of wordInArray is same as guess

I read = as becomes or takes the value of:
printIfTrue[i] == true;

is read as

the ith element of printIfTrue becomes true

A: == is Relational Operator
 == Checks if the values of two operands are equal or not, if yes then condition becomes true.
(A == B) is not true.

= is Assignment Operator
=   Simple assignment operator, Assigns values from right side operands to left side operand
C = A + B will assign value of A + B into C

Don't mix them , and as said by @JB Nizet ,
you cannot directly compare String with Character , I am assuming wordsInArray is your Array of Characters and guess is the String, So you can use
wordsInArray[i]==guess.charAt(i);
printIfTrue[i] = true;


text:
Q: Reloading/Refreshing Spring configuration file without restarting the servlet container How can I refresh Spring configuration file without restarting my servlet container?
I am looking for a solution other than JRebel.

A: I wouldn't recommend you to do that.
What do you expect to happen to singleton beans which their configuration modified? do you expect all singletons to reload? but some objects may hold references to that singletons.
See this post as well Automatic configuration reinitialization in Spring

A: You can take a look at this http://www.wuenschenswert.net/wunschdenken/archives/138 where once you change any thing in the properties file and save it the beans will be reloaded with the new values.

A: For those stumbling on this more recently -- the current and modern way to solve this problem is to use Spring Boot's Cloud Config.
Just add the @RefreshScope annotation on your refreshable beans and @EnableConfigServer on your main/configuration.
So, for example, this Controller class:
@RefreshScope
@RestController
class MessageRestController {

    @Value("${message}")
    private String message;

    @RequestMapping("/message")
    String getMessage() {
        return this.message;
    }
}

Will return the new value of your message String property for the /message endpoint when refresh is invoked on Spring Boot Actuator (via HTTP endpoint or JMX).
See the official Spring Guide for Centralized Configuration example for more implementation details.

A: Well, it can be useful to perform such a context reload while testing your app.
You can try the refresh method of one of the AbstractRefreshableApplicationContext class: it won't refresh your previously instanciated beans, but next call on the context will return refreshed beans.
import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class ReloadSpringContext {

    final static String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
        "<!DOCTYPE beans PUBLIC \"-//SPRING//DTD BEAN//EN\"\n" +
        " \t\"http://www.springframework.org/dtd/spring-beans.dtd\">\n";

    final static String contextA =
        "<beans><bean id=\"test\" class=\"java.lang.String\">\n" +
            "\t\t<constructor-arg value=\"fromContextA\"/>\n" +
        "</bean></beans>";

    final static String contextB =
        "<beans><bean id=\"test\" class=\"java.lang.String\">\n" +
            "\t\t<constructor-arg value=\"fromContextB\"/>\n" +
        "</bean></beans>";

    public static void main(String[] args) throws IOException {
        //create a single context file
        final File contextFile = File.createTempFile("testSpringContext", ".xml");

        //write the first context into it
        FileUtils.writeStringToFile(contextFile, header + contextA);

        //create a spring context
        FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(
            new String[]{contextFile.getPath()}
        );

        //echo the bean 'test' on stdout
        System.out.println(context.getBean("test"));

        //write the second context into it
        FileUtils.writeStringToFile(contextFile, header + contextB);

        //refresh the context
        context.refresh();

        //echo the bean 'test' on stdout
        System.out.println(context.getBean("test"));
    }

}

And you get this result
fromContextA
fromContextB

Another way to achieve this (and maybe a more simple one) is to use the Refreshable Bean feature of Spring 2.5+
With dynamic language (groovy, etc) and spring you can even change your bean behavior. Have a look to the spring reference for dynamic language:

24.3.1.2. Refreshable beans
One of the (if not the) most
  compelling value adds of the dynamic
  language support in Spring is the
  'refreshable bean' feature.
A refreshable bean is a
  dynamic-language-backed bean that with
  a small amount of configuration, a
  dynamic-language-backed bean can
  monitor changes in its underlying
  source file resource, and then reload
  itself when the dynamic language
  source file is changed (for example
  when a developer edits and saves
  changes to the file on the
  filesystem).


text:
Q: String splitting regex with patterns ignored I have a source string that I want to split the data out:
String source = "data|junk,data|junk|junk,data,data|junk";
String[] result = source.split(",");

The above gives data|junk, data|junk|junk, data, data|junk. To further get the data out, I did this:
for (int i = 0; i < result.length; i++) {
    result[i] = result[i].split("\\|")[0];
}

Which gives what I wanted data, data, data, data. I want to see if it is possible to do it in one split with the right regex:
String[] result = source.split("\\|.*?,");

The above gives data, data, data,data|junk, in which the last two data are not split. Could you please help with the correct regex to get the result I wanted?
Example string: "Ann|xcjiajeaw,Bob|aijife|vdsjisdjfe,Clara,David|rijfidjf"
Expected result: "Ann, Bob, Clara, David"

A: You can change your regular expression to account for the "junk", then keep matching while it matches data:
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class RegexTest {
    public static void main(String[] args) {
        String input = "Ann|xcjiajeaw,Bob|aijife|vdsjisdjfe,Clara,David|rijfidjf";
        Pattern p = Pattern.compile("(\\w+)(\\|\\w+)*,?");
        Matcher m = p.matcher(input);
        while (m.find()) {
            System.out.println(m.group(1));
        }
    }
}

The regular expression looks for word characters (letters, digits, and underscores) and captures that. It then looks for a pipe symbol (escaped so that that it does not have a special meaning in the regular expression) with again word characters. This pipe plus word characters can happen any number (zero to many) of times. After that could be a comma, optionally.
This prints

Ann
Bob
Clara
David

It also captures the "junk", and you could access that with m.group(2) in the loop. If you don't want to capture that, insert a ?: into the regular expression:
Pattern.compile("(\\w+)(?:\\|\\w+)*,?");

A: In the string,

Ann|xcjiajeaw,Bob|aijife|vdsjisdjfe,Clara,David|rijfidjf

\\|.*?, - this will match |anynoncommastring,
but this doesn't match the final |rijfidjf since that does not end in comma. So to match that, use (,|$) instead of just ,, making the regex \\|.*?(,|$)
But the above does not match a single isolated comma, so alternating , with \\|.*?(,|$), makes the final regex (\\|.*?(,|$)|,).
The pattern (\\|.*?(,|$)|,) works,
String source = "Ann|xcjiajeaw,Bob|aijife|vdsjisdjfe,Clara,David|rijfidjf";
String[] result = source.split("(\\|.*?(,|$)|,)");
for (int i = 0; i < result.length; i++) {
    System.out.println(result[i]);
}

Output:
Ann
Bob
Clara
David

A: I came up with the following solution:
String source = "one|junk,two|junk|junk,three,four|junk|junk";
String[] result = source.split("([|](?:(.*?,(?=[^,]+[|,]|$))|.*$))|,");
System.out.println(Arrays.toString(result));

[one, two, three, four]


text:
Q: Cakephp: Email Error SSL config->email.php
public $gmail = array(
    'host' => 'ssl://mail.myserver.co.in:465',
    'username' => 'support@myserver.co.in',
    'password' => 'secret',
    'transport' => 'Smtp',
    'template' =>false,
    'layout' => false,
);

function to send email
public function sendEmail() {

    $layout = "gmail";
    $Email = new CakeEmail();
    $Email -> config('gmail');
    $Email -> from(TEST_FROM);
    $Email ->to(TEST_EMAIL);
    $Email -> subject('Welcome to TaskBucks');
    $Email -> emailFormat('html');
    if ($Email -> send()) {
        return true;
    } else
        return false;

}

Error i am facing
stream_socket_client(): SSL operation failed with code 1. OpenSSL
Error messages: error:14090086:SSL
routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
stream_socket_client(): Failed to enable crypto
stream_socket_client(): unable to connect to
ssl://mail.rapidsoft.co.in:465:25 (Unknown error)

A: Your script is right.
The reason is because you can't send email from your local machine. You need to configure sending email from your local machine then your cakephp sendMail function works.
Here is one of the way you can configure your local machine to send email. If you are using WAMP
http://blog.techwheels.net/send-email-from-localhost-wamp-server-using-sendmail/


text:
Q: Some times getting error while writing in to a text file i am writing a string value to a text file continuously
std::string line =('8101001033900039','00','22','','','','','3','','0'),

this string we are writing to a text file like below
outfile.open((char*)fileName.c_str(), ios::app);

if(outfile.is_open())
    {
        // write inputted data into the file.
        DBGF_TRACE("3.write line : %s", line);
        outfile<< line << std::endl;
        DBGF_TRACE("write line : %s", line);
    }

Now the error i am getting is , sometimes its getting failed to write . Can someone help

A: What is that to begin with:
std::string line =('8101001033900039','00','22','','','','','3','','0');

The compiler should give you something like that:
prog.cc:8:24: warning: character constant too long for its type
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                        ^~~~~~~~~~~~~~~~~~
prog.cc:8:43: warning: multi-character character constant [-Wmultichar]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                           ^~~~
prog.cc:8:48: warning: multi-character character constant [-Wmultichar]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                ^~~~
prog.cc:8:53: error: empty character constant
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                     ^~
prog.cc:8:56: error: empty character constant
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                        ^~
prog.cc:8:59: error: empty character constant
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                           ^~
prog.cc:8:62: error: empty character constant
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                              ^~
prog.cc:8:69: error: empty character constant
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                                     ^~
prog.cc: In function 'int main()':
prog.cc:8:43: warning: left operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                           ^~~~
prog.cc:8:48: warning: right operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                ^~~~
prog.cc:8:53: warning: right operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                     ^~
prog.cc:8:56: warning: right operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                        ^~
prog.cc:8:59: warning: right operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                           ^~
prog.cc:8:62: warning: right operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                              ^~
prog.cc:8:65: warning: right operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                                 ^~~
prog.cc:8:69: warning: right operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                                     ^~
prog.cc:8:72: warning: right operand of comma operator has no effect [-Wunused-value]
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                                                                        ^~~
prog.cc:8:71: error: conversion from 'char' to non-scalar type 'std::__cxx11::string' {aka 'std::__cxx11::basic_string<char>'} requested
     std::string line =('8101001033900039','00','22','','','','','3','','0');
                       ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~~~~

so the data themselves are not OK.
So now, let's replace single quotes with double quotes, since you probably want strings, like this:
std::string line =("8101001033900039","00","22","","","","","3","","0");

then only the right most operand will be assigned to line, meaning that line is now equal to "0". Read more about it in What does i = (i, ++i, 1) + 1; do?

EDIT:
You need this:
#include <fstream>
#include <string>
#include <iostream>

int main(void) {
    std::string fileName = "output.txt";
    std::string line ="('8101001033900039','00','22','','','','','3','','0'),";
    std::ofstream out(fileName.c_str());
    out << line << std::endl;
    out.close();
    return 0;
}


text:
Q: Setting difficulty not working I am making a simple java text game in eclipse luna. Scanner.next() is not working. When I run it, after I ask for the user input, an error displays (java.util.NoSuchElementException). Have I just done something really dumb?
    while(whle) {
        System.out.print("Where do you want to go? Enter gym, store, or mountain. ");
        loc = goTo.next();
        loc = loc.toLowerCase();
        if(loc.equals("gym") || loc.equals("store") || loc.equals("mountain")) whle = false;
        else {
            System.out.println("Please enter an option. ");
            System.out.println();
        }
    }

Everything is defined, and no errors pop up in the actual program, just when I run it.

A: Make sure you have your scanner initialized correctly like this
Scanner loc = new Scanner(System.in); //very important

And you have imported this class
import java.util.Scanner; //in the begining of the source code

it should work (other than that I think its a problem with your IDE, java version)
If that doesn't help, I ran it with this program by itself (with boolean whle initialized, main method and such) and it produces what I believe is what you want.
while(whle) {
    System.out.print("Where do you want to go? Enter gym, store, or mountain. ");
    String locstring= loc.next();
    if(locstring.equalsIgnoreCase("gym") || locstring.equalsIgnoreCase("store") || locstring.equalsIgnoreCase("mountain")){ whle = false;}
    else {
        System.out.println("Please enter an option. ");
        System.out.println();
    }
}


text:
Q: Stuck on an integral while solving an ODE I was solving
$$\left(1+3e^{y/x}\right)\,\mathrm dx+3e^{y/x}\left(1-\dfrac xy\right)\,\mathrm dy=0\\ \implies \dfrac{\mathrm dy}{\mathrm dx}= \dfrac{1+3e^{y/x}}{3e^{y/x}\left(\dfrac xy-1\right)}$$
As usual, I proceeded with $y=vx$.
$$v+x\dfrac{\mathrm dv}{\mathrm dx}= \dfrac{1+3e^v}{3e^v\left(\dfrac 1v -1\right)}$$
Simplifying this, I found that
$$\int\dfrac{3e^v(1-v)}{v(1+3ve^v)}\,\mathrm dv=\int\dfrac{\mathrm dx}{x}$$
(I might not be completely correct, so please check)
Now, I can't evaluate the integral on the left. How can I evaluate it?


text:
Q: Splitting raster in QGIS? without cliper I have polygon grid layer and raster image whitch want to split with my grid layer to have 9 new raster layers.
I was doing it like this guy but my QGIS stop working and shut down every time when I hit run button.
So is there another way, how to split raster with vector layer?

A: There's a QGIS plugin called GridSplitter which will take a raster (or vector layer for that matter) and split it up into one raster layer per grid cell. If you already have a grid polygon layer you can use that to cut up the image, using the 'cut layer' option (see screenshot)
This is probably the easiest way to do this, especially if you need to scale this up (e.g. split a world DEM into degree squares)

A: There is yet another way (of course):
Right-click your raster in Layers.  Select Export->Save As... and click the little Create VRT checkbox to the right of Format option drop-down.  This then opens a previously hidden VRT Tiles options section in th dialog (below 'Resolution').  You can set the columns and rows (tile size e.g. 512x512).  The file name is the folder where all the tiles wil be stored.
The nice thing about this approach is you automatically get a VRT xml file too, ready to go.

A: You can use the approach that I have used with these raster and grid vector layer of next image. First, select the element to clip with "Select features by area or single click" at the grid vector layer. At the attributes table of grid layer, click in "Show selected features" option (at the bottom) and next, at the record, click with right button of the mouse for selecting "Open Form". Copy to your favorite text editor the extent parameters in this order: X_MIN, Y_MAX, X_MAX, Y_MIN (see next image).

Open Clipper Tool in Raster -> Extraction -> Clipper. Select the name of output file, and drag with the mouse one arbitrary area on the map and click on the icon pencil for editing gdal_translate command. Change projwin parameters for the values at your text editor (copy/paste).

After OK, the clipped image it will have the same resolution of raster base; as it can be observed at next image.


text:
Q: Objective-C - Create an image from an array of integers I have an array of integers. Each int represents a pixel and has ARGB information. I also know the width and height of the image.
How can I turn these informations into an image?
It's an IOS app and I'm only going to display the image onscreen, no need to save it. I'm going to create one image per frame.

A: Depends on what type of image you want to create. PPM for example if you have the RGB values you just specify the image type in the header. So you would create an empty file, open it for I/O then write something like this
P6
width height 255
rgbrgbrgbrgb
The problem is not all images are created this way. So I suppose the question is what type of image do you want to create? You will need to write the file differently for each file type you will support.

A: Assuming you are developing for iOS, I would try to join this:
How can I make an UIImage programatically?
With this:
iPhone : How to change color of particular pixel of a UIImage?
Hope this places you on the right track.


text:
Q: PDO returning null object when SQL query returning data When I query my long query to MYSQL directly I get right data
But then I use PDO with same query I get no data (Object size zero) . Following data
SQL Statement :
SELECT table1.field1,table2.field1 FROM table1,table2 WHERE table1.key = table2.key AND table2.field2 ='coffee' AND (table2.date BETWEEN '2014-1-1' AND '2014-12-1');

I get desire output when i directly run the query on mysql.
However, when I run using php file having following content I get nothing
include 'config.php';
$query = 'SELECT table1.field1,table2.field1 FROM table1,table2 WHERE table1.key = table2.key AND table2.field2 ='coffee' AND (table2.date BETWEEN '2014-1-1' AND '2014-12-1')';
$stmt = $db->query($query)->fetchAll();
var_dump($stmt);

output is
array(0) { }

I also tried
$query = "SELECT table1.field1,table2.field1 FROM table1,table2 WHERE table1.key = table2.key AND table2.field2 ='coffee' AND (table2.date BETWEEN '2014-1-1' AND '2014-12-1')";

and
  $query =  ' SELECT table1.field1,table2.field1 FROM table1,table2 WHERE table1.key = table2.key AND table2.field2 = \'coffee\'  AND (table2.date BETWEEN  \'2014-1-1\'  AND  \'2014-12-1\' )' ;

and
$query =  ' SELECT table1.field1,table2.field1 FROM table1,table2 WHERE table1.key = table2.key AND table2.field2 = \'coffee\'  AND  \( table2.date BETWEEN  \'2014-1-1\'  AND  \'2014-12-1\'\)' ;

and
$query =  " SELECT table1.field1,table2.field1 FROM table1,table2 WHERE table1.key = table2.key AND table2.field2 = \'coffee\'  AND  \( table2.date BETWEEN  \'2014-1-1\'  AND  \'2014-12-1\'\)" ;

What am I doing wrong?


text:
Q: Swap method of Linked List Nodes at Position a and b, stuck on infinite loop in Java So, I'm trying to solve this question in my book, it asks for a Node swap in a given Linked List at given positions, well, I've tried implementing a method called "swap" and it gets stuck on an infinite loop, and I can't figure why
here's the method:
    public void swap(LinkedList L1, int start, int end) {
    Node ptr1, prev1, ptr2, prev2;

    ptr1 = head;
    prev1 = ptr1;
    int count1 = 0;
    int count2 = 0;
    if ((start <= size()) && (start > 0) && (end <= size()) && (end > 0)) {
        while (count1 != start && ptr1 != null) {
            prev1 = ptr1;
            ptr1 = ptr1.link;
            count1++;
        }
        ptr2 = head;
        prev2 = ptr2;
        while (count2 != end && ptr2 != null) {
            prev2 = ptr2;
            ptr2 = ptr2.link;
            count2++;
        }
        prev1.setLink(prev2.link);
        ptr2.setLink(ptr1.link);
        prev2.setLink(ptr1.link);
        ptr1.setLink(ptr2.link);
    }
}

and here's the main method, that I've trying to test the method in:
    public static void main(String[] args) {
    LinkedList L1 = new LinkedList();
    L1.addToStart(5);
    L1.addToStart(7);
    L1.addToStart(23);
    L1.addToStart(56);
    L1.addToStart(52);
    L1.addToStart(22);
    L1.addToStart(57);
    L1.addToStart(99);
    L1.addToStart(34);
    L1.addToStart(74);
    L1.outputList();
    L1.swap(L1, 2, 4);
    L1.outputList();

A: You are not linking things correctly. You make both ptr2 and prev2 link to ptr1.link.
Assume this is the list
A -> B -> C -> D -> E -> F

and we want to switch B and E.
prev1 = A
ptr1  = B
prev2 = D
ptr1  = E

Relinked, it looks like
A -> B -> C -> D -> E -> F
|-------------------^
     |-------------------^
          ^---------|
      ^--------|
A -> E -> C -> D -> B -> F

In code:
Node temp = ptr1.link;
prev1.setLink(ptr2);
ptr1.setLink(ptr2.link);
prev2.setLink(ptr1);
ptr2.setLink(temp);


text:
Q: ElasticSearch consistent sort order each day, but randomized across days I am trying to return a randomized result of a filter query to give all my documents a fair chance of being on the first page results. In an effort to not confuse users during repeated searches (and to easily support pagination) the results should stay consistent for the current day.
To do this I have developed the following script sort query. It combines the document id (a guid, so already fairly random) with a daily salt (just the day of year and current year combined) and hashes the result to produce what I would expect to be a fairly random string, that only changes as the 'daily salt' changes each day (ignore the extraneous elements in this specific query, it's generated from code).
{
  "from": 0,
  "size": 20,
  "sort": {
    "_script": {
      "order": "asc",
      "type": "string",
      "script": "org.elasticsearch.common.Digest.md5Hex(dailySalt + doc['id'].value)",
      "params": {
        "dailySalt": "184-2013"
      }
    }
  },
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "tag_id": "Some Tag"
              }
            },
            {
              "match_all": {}
            }
          ]
        }
      }
    }
  },
  "fields": [
    "id"
  ]
}

Inspired from this similar question and answer
It works, but not very well. I get slightly different results as I increment the daily salt, but the same documents keep appearing around the top results. They move slightly, but there's definitely a consistent pattern.
I've tried to change the hash function to another I found:
org.elasticsearch.cluster.routing.operation.hash.djb.DjbHashFunction.DJB_HASH
but it gives very similar results of common top results.
I'm no cryptography expert so I presume this is a behavior of common hash functions and there must be some special hash functions to use for more randomized results based on similar inputs?
Is anyone familiar with one available in ElasticSearch? I'm using Searchbox.io (cloud hosted elastic search service) so installing my own custom function is not an option.
Or am I approaching this problem from a completely wrong angle?
Edit
I just looked at the resultant sort keys produced by the script, and it appears that the script is only being applied to the first page of results, and then sorting that first page (rather than applying to the full result set and therefor changing the documents within the first page).
Here's my first page results (edited for brevity). But you can see on the first page alone that the sort key varies from 0c*** to fa***, for the first 0 - 20 docs, with a total of ~200 docs.
Using 'dailySalt' = 185-2013
{
"took": 2,
"timed_out": false,
"_shards": {
    "total": 1,
    "successful": 1,
    "failed": 0
},
"hits": {
    "total": 196,
    "max_score": null,
    "hits": [{
        "fields": {
            "id": "27662ef8-d2a7-4fde-80f6-1571b83c4cde"
        },
        "sort": ["0cbf8b4e7927f0a53a5b82f2630ff9ad"]
    }, {
        "fields": {
            "id": "d9b11797-053f-495e-a676-0ec959dba879"
        },
        "sort": ["0fa8730a5239f8a3d1286cbe16619bfa"]
    }, {
        "fields": {
            "id": "482c893f-1083-4860-892e-1b25cf442199"
        },
        "sort": ["295edd71cc48ac41c5e2f91315abf5ce"]
    }, {
        "fields": {
            "id": "581fd0f1-9ecb-4e5c-920b-06413bfbf4f7"
        },
        "sort": ["4b9f0d17bc2333d13a1963b4f6afb829"]
    }, {
        "fields": {
            "id": "de3dddb8-e296-4446-ac4c-135cc925669d"
        },
        "sort": ["4c5d0bcb50f5b600e539ba46b33b1007"]
    }, {
        "fields": {
            "id": "c83ad22e-80b4-40f1-8e56-2153a1a1f9e8"
        },
        "sort": ["55efe0a692ab3205405f1c74732b8205"]
    }, {
        "fields": {
            "id": "7bd19829-4f37-4e02-9fd1-0239b8ae8db4"
        },
        "sort": ["5adcd22c7c507244d7ba382812accdf3"]
    }, {
        "fields": {
            "id": "42fcec43-851f-4133-a8db-1d2bf0b86ec8"
        },
        "sort": ["6757f46bd554e3353a2ebf35c6b3d24c"]
    }, {
        "fields": {
            "id": "e119132b-4e93-4047-8513-1ce2452f0cdd"
        },
        "sort": ["6dbcb59a2b5e91523896d57695251b29"]
    }, {
        "fields": {
            "id": "7d0acf5d-7c14-45a2-97b7-17939ff512f4"
        },
        "sort": ["9d99752ec0802e55dcfb3c83bcd2e4bb"]
    }, {
        "fields": {
            "id": "2cdc21e4-3312-460b-9a18-094e4f95a56c"
        },
        "sort": ["9dc43d1d39e64cfe04c6d7b8f565faaa"]
    }, {
        "fields": {
            "id": "0f665cb3-5648-416c-b08f-146d2a019319"
        },
        "sort": ["b61bb718fe63a287b6fcdc8bcd638604"]
    }, {
        "fields": {
            "id": "1e852d49-2b3b-4d7a-9f1b-1495b94e723e"
        },
        "sort": ["ba7ad8a3a6e195a6bc28e341f9d6965b"]
    }, {
        "fields": {
            "id": "ca2a5922-bb42-4317-b61c-129925436a1f"
        },
        "sort": ["bca0411cf8d67b4dcd5b205a5010367f"]
    }, {
        "fields": {
            "id": "b1dac760-7d73-4b60-bd6d-08ea9453e68c"
        },
        "sort": ["be3714cfb2517e98d525aaea6e40cfa5"]
    }, {
        "fields": {
            "id": "c4b08def-59db-4ac0-b16f-0c3fae4c01f2"
        },
        "sort": ["c4220b31c305d536c7a7d1639da32c66"]
    }, {
        "fields": {
            "id": "cc7ac1fd-3e88-4503-a837-2000ebb6e2d9"
        },
        "sort": ["ceb5710fe2418fe3b353bf7b1f737570"]
    }, {
        "fields": {
            "id": "5a5f90c9-b44f-4ca2-9d16-117c8e9fd388"
        },
        "sort": ["dc5fea76598633cb08c1459983ebca62"]
    }, {
        "fields": {
            "id": "6d811d5b-4138-4a41-a186-1b9aa2b65623"
        },
        "sort": ["ea3c55ac123ac9e819b145402407d1de"]
    }, {
        "fields": {
            "id": "b489d2da-b4a1-44de-acde-219109edd42f"
        },
        "sort": ["fab53cc11983b45b081d4b01df555c59"]
    }]
}
}

A: MD5 is a cryptographic hash function, and such functions exhibit a property called the avalanche effect. In short, even a small change in the input completely changes the output. You can experiment with this using an online MD5 calculator for example.
There are no chance collisions either – you wouldn't find two strings that hash to the same value even if you spent your whole life trying to find them.
These two properties guarantee that the script you have written produces a unique, random value for every document every day, forever. The hash function is not the issue here.
How many documents are there? How many results are shown per page? What kinds of patterns do see? There may be a surprisingly large chance that a certain document appears on the front page by random.

A: So it looks like this is a problem with Elastic Search's script sort. It was only applying the script to the 1st page results, and then sorting that 1 page only. I can't find this behavior documented anywhere, so not sure if it's a bug or by-design for performance reasons.
Anyway, using a custom_score query, with a similar script for the score function, gives the desired results (I used DJB hash instead of original MD5 due to speed, designed for strings, and returns an int which is needed for custom score scripts):
{
  "from": 0,
  "size": 20,
  "query": {
    "custom_score": {
      "script": "org.elasticsearch.cluster.routing.operation.hash.djb.DjbHashFunction.DJB_HASH(dailySalt + doc['id'].value)",
      "params": {
        "dailySalt": "185-2013"
      },
      "query": {
        "filtered": {
          "query": {
            "match_all": {}
          },
          "filter": {
            "bool": {
              "must": [
                {
                  "term": {
                    "tag_id": "Some Tag"
                  }
                },
                {
                  "match_all": {}
                }
              ]
            }
          }
        }
      }
    }
  },
  "fields": [
    "id"
  ]
}


text:
Q: Unity3D and Tiled Four weeks of searching I'm using Tiled and Tiled2Unity to make my maps the problem is i have made multiple layer in Tiled (image 1) all is good but when i import it in unity my prefabs are always behinde the the objects (layer 2) of the map i tried to change the Z index but nothing , after multiple tries i found that the sprite renderer is the problem (Image 2) when i create a simple cube with mesh renderer all work great (Image 2) please Help .
Image 1 :

Image 2 :

A: Use unity layer and sorting order to manage your sprites on right place. You can have look at unity documentation or find any tutorial.

A: You probably need to manage the sorting layer name or order on your layers via custom properties in Tiled. See this link.


text:
Q: Specify local tf state file to azurerm provider in pipeline I have been working on deploying terraform package using azure devops pipeline.
We have our tf state file locally, and no plans to move to azure storage account. Could you please help how can we define the attribute values in terraform init step in pipeline.
- task: TerraformTaskV2@2
    displayName: Terraform init
    inputs:
      provider: 'azurerm'
      command: 'init'
      workingDirectory: 'some directory'
      backendServiceArm: 'some service conn'
      **backendAzureRmContainerName: ??
      backendAzureRmResourceGroupName: ??
      backendAzureRmStorageAccountName: ??
      backendAzureRmKey: **

What should be the values for Resource group, storage account name, container name. If I don't specify these values, pipeline is failing with below error
##[error]Error: Input required: backendAzureRmStorageAccountName
Any help on this is much appreciated. Thanks in advance.

A: I'm unsure if you can use the TerraformTaskV2 without utilizing a cloud provider's backend. In the README for said task it doesn't show options for using a local backend, only the following for terraform init:

*

*... AzureRM backend configuration

*... Amazon Web Services(AWS) backend configuration

*... Google Cloud Platform(GCP) backend configuration

I haven't had experience with this yet, but you could look at the extension Azure Pipelines Terraform Tasks, which does explicitly support a local backend:

The Terraform CLI task supports the following terraform backends

*

*local

*...

Just a note on working in teams:
if you're working in a team deploying infrastructure, using a local backend can lead to potential undefined state and/or undesirable outcomes. The benefits of choosing a good backend can offer "...support locking the state while operations are being performed, which helps prevent conflicts and inconsistencies." - docs


text:
Q: Efficient way to string split using CTE I have a table that looks like
ID  Layout
1   hello,world,welcome,to,tsql
2   welcome,to,stackoverflow

The desired output should be
Id  Splitdata
1   hello
1   world
1   welcome
1   to
1   tsql
2   welcome
2   to
2   stackoverflow

I have done this by the below query
Declare @t TABLE(
    ID  INT IDENTITY PRIMARY KEY,
    Layout VARCHAR(MAX)
)
INSERT INTO @t(Layout)
SELECT 'hello,world,welcome,to,tsql' union all
SELECT 'welcome,to,stackoverflow'
--SELECT * FROM @t
;With cte AS(
select F1.id
 ,O.splitdata
 from
 (
 select *,
 cast('<X>'+replace(F.Layout,',','</X><X>')+'</X>' as XML) as xmlfilter
 from @t F
 )F1
 cross apply
 (
 select fdata.D.value('.','varchar(MAX)') as splitdata
 from f1.xmlfilter.nodes('X') as fdata(D)) O
 )

 select * from cte

But performance wise it is very bad. I am looking for a more efficient query but using CTE only.

A: From NullRef's Answer
Function without set operation will be faster according to my understanding of sql server
so this will be more efficient
CREATE FUNCTION fnSplitString(@str nvarchar(max),@sep nvarchar(max))
RETURNS TABLE
AS
RETURN
    WITH a AS(
        SELECT CAST(0 AS BIGINT) as idx1,CHARINDEX(@sep,@str) idx2
        UNION ALL
        SELECT idx2+1,CHARINDEX(@sep,@str,idx2+1)
        FROM a
        WHERE idx2>0
    )
    SELECT SUBSTRING(@str,idx1,COALESCE(NULLIF(idx2,0),LEN(@str)+1)-idx1) as value
    FROM a

A: it's my best solution using CTE:
DECLARE @Char VARCHAR(MAX) = '10||3112||||aaaa||'
DECLARE @Separador CHAR(2) = '||'

;WITH Entrada AS(
    SELECT
        CAST(1 AS Int) As Inicio,
        CHARINDEX(@Separador, @Char) As Fim
    UNION ALL
    SELECT
        CAST(Fim + LEN(@Separador) AS Int) As Inicio,
        CHARINDEX(@Separador, @Char, Fim + 1) As Fim
    FROM Entrada
    WHERE CHARINDEX(@Separador, @Char, Fim + 1) > 0
)
SELECT
    SUBSTRING(@Char, Inicio, Fim - Inicio)
FROM Entrada
WHERE (Fim - Inicio) > 0

A: You seem dead set on using a CTE, so try this:
DECLARE @YourTable table (RowID int, Layout varchar(200))
INSERT @YourTable VALUES (1,'hello,world,welcome,to,tsql')
INSERT @YourTable VALUES (2,'welcome,to,stackoverflow')

;WITH SplitSting AS
(
    SELECT
        RowID,LEFT(Layout,CHARINDEX(',',Layout)-1) AS Part
            ,RIGHT(Layout,LEN(Layout)-CHARINDEX(',',Layout)) AS Remainder
        FROM @YourTable
        WHERE Layout IS NOT NULL AND CHARINDEX(',',Layout)>0
    UNION ALL
    SELECT
        RowID,LEFT(Remainder,CHARINDEX(',',Remainder)-1)
            ,RIGHT(Remainder,LEN(Remainder)-CHARINDEX(',',Remainder))
        FROM SplitSting
        WHERE Remainder IS NOT NULL AND CHARINDEX(',',Remainder)>0
    UNION ALL
    SELECT
        RowID,Remainder,null
        FROM SplitSting
        WHERE Remainder IS NOT NULL AND CHARINDEX(',',Remainder)=0
)
SELECT * FROM SplitSting ORDER BY RowID

OUTPUT:
RowID       Part
----------- -----------------------
1           hello
1           world
1           welcome
1           to
1           tsql
2           welcome
2           to
2           stackoverflow

(8 row(s) affected)

here is an excellent article on splitting strings in SQL Server: "Arrays and Lists in SQL Server 2005 and Beyond, When Table Value Parameters Do Not Cut it" by Erland Sommarskog
EDIT here's another version (but you need a numbers table) returns same results as above:
;WITH SplitValues AS
(
    SELECT
        RowID,ListValue
        FROM (SELECT
                  RowID, LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(',', List2, number+1)-number - 1))) AS ListValue
                  FROM (
                           SELECT RowID, ',' + Layout + ',' AS List2
                           FROM @YourTable
                       ) AS dt
                      INNER JOIN Numbers n ON n.Number < LEN(dt.List2)
                  WHERE SUBSTRING(List2, number, 1) = ','
             ) dt2
        WHERE ListValue IS NOT NULL AND ListValue!=''
)
SELECT * FROM SplitValues

see here for a numbers table: What is the best way to create and populate a numbers table?


text:
Q: Python skip importing submodules that aren't available I have a Python module that runs on a server and has some server specific imports (and functions).  I want to import and run it locally with a django command.  However, on my local machine, the server specific modules are not available.  I am currently using a try/except block in the server module but is there a better way to accomplish this?

A: I suppose you'd like to skip import of missing modules if you're running the module locally. The thing is that you don't want to silently skip importing them if you're running the module on a server and it happens so that required modules are missing.
Better approach is to configure environment and check it on runtime if you should import the modules or not.
It should go like this:

*

*Configure env variable:

    export MY_RUNNING_ENV="production" // on server
    export MY_RUNNING_ENV="development" // locally

*Check variable from code:

    import os
    env = os.getenv("MY_RUNNING_ENV")
    if env == "production"
        import "my_module"


text:
Q: Handling backups of a large table (>1 TB) in Postgres? I have a 1TB table (X) that is a pain to backup.
The table X contains historical log data that is not often updated after creation. We usually only access a single row at a time, so performance is still very good.
We currently make nightly full logical backups, and exclude X for the sake of backup time and space. We do not need historical backups of X, since the log files from which it is populated are backed up themselves. However, recovery of X by re-processing of the log files would take an unnecessary long time.
I'd like to include X in our backup strategy so that our recovery time can be much faster. It doesn't seem feasible to include X in the nightly logical backup.
Ideally, I'd like a single full backup for X that is updated incrementally (purely to save time).
I lack the experience to investigate solutions alone, and I'm wondering what my options are?
Barman for incremental updates? Partition X? Both?
Thanks!


text:
Q: Ubuntu 18.04 setup clang++ How do I properly setup clang to use c++ std library on Ubuntu 18.04?
I have installed a bunch of libraries suggested in other threads
but without success. I also have two gcc compilers (7,9) installed and I make
use of update-alternative to switch between them. Also Clang-6, Clang-9 and llvm-9
are installed.
Some libraries I installed
sudo apt install libstdc++-9-dev
sudo apt install libc++-9-dev
sudo apt install g++-7-multilib
sudo apt install g++-9-multilib

I think there more but the result stayed the same.
#include <iostream>

int main()
{
    std::cout << "Hello World\n";
}

Compiling with
clang++-9 hello_world.cpp
clang++ hello_world.cpp
clang++-9 -stdlib=libstdc++ hello_world.cpp
clang++ -stdlib=libstdc++ hello_world.cpp

All produce
hello_world.cpp:2:10: fatal error: 'iostream' file not found

I found a bunch of posts on this topic, but most of them were on Windows or macOS
or 8 years old. There was also this blog post. I am probably missing something
very obvious and was hoping maybe someone could point me into the right direction.
I installed clang with the following way, but I don't rember the exact order:
sudo add-apt-repository ppa:ubuntu-toolchain-r/test
sudo apt install clang libclang-dev
sudo apt-get install libclang-9-dev
sudo apt-get install clang-9
sudo apt-get install clang++-9

As in the comments suggested tried to compile with
clang++ -v hello_world.cpp given the following output:
$ clang++ hello_world.cpp -v
clang version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
Found candidate GCC installation: /usr/bin/../lib/gcc/i686-linux-gnu/8
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/10
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/6
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/6.5.0
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/7
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/7.5.0
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/8
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/9
Found candidate GCC installation: /usr/lib/gcc/i686-linux-gnu/8
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/10
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/6
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/6.5.0
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/7
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/7.5.0
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/8
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/9
Selected GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/10
Candidate multilib: .;@m64
Selected multilib: .;@m64
 "/usr/lib/llvm-6.0/bin/clang" -cc1 -triple x86_64-pc-linux-gnu -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -discard-value-names -main-file-name hello_world.cpp -mrelocation-model static -mthread-model posix -mdisable-fp-elim -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -v -resource-dir /usr/lib/llvm-6.0/lib/clang/6.0.0 -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++ -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/x86_64-linux-gnu -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/backward -internal-isystem /usr/include/clang/6.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-6.0/lib/clang/6.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fdeprecated-macro -fdebug-compilation-dir /mnt/My_Linux_Files/C++/test2/src -ferror-limit 19 -fmessage-length 80 -fobjc-runtime=gcc -fcxx-exceptions -fexceptions -fdiagnostics-show-option -fcolor-diagnostics -o /tmp/hello_world-0f22e3.o -x c++ hello_world.cpp
clang -cc1 version 6.0.0 based upon LLVM 6.0.0 default target x86_64-pc-linux-gnu
ignoring nonexistent directory "/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/x86_64-linux-gnu"
ignoring nonexistent directory "/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/backward"
ignoring nonexistent directory "/include"
ignoring duplicate directory "/usr/include/clang/6.0.0/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++
 /usr/include/clang/6.0.0/include
 /usr/local/include
 /usr/include/x86_64-linux-gnu
 /usr/include
End of search list.
hello_world.cpp:2:10: fatal error: 'iostream' file not found
#include <iostream>
         ^~~~~~~~~~
1 error generated.

and with clang++-9:
$ clang++-9 hello_world.cpp -v
clang version 9.0.0-2~ubuntu18.04.2 (tags/RELEASE_900/final)
Target: x86_64-pc-linux-gnu
Thread model: posix
InstalledDir: /usr/bin
Found candidate GCC installation: /usr/bin/../lib/gcc/i686-linux-gnu/8
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/10
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/6
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/6.5.0
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/7
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/7.5.0
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/8
Found candidate GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/9
Found candidate GCC installation: /usr/lib/gcc/i686-linux-gnu/8
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/10
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/6
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/6.5.0
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/7
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/7.5.0
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/8
Found candidate GCC installation: /usr/lib/gcc/x86_64-linux-gnu/9
Selected GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/10
Candidate multilib: .;@m64
Selected multilib: .;@m64
 "/usr/lib/llvm-9/bin/clang" -cc1 -triple x86_64-pc-linux-gnu -emit-obj -mrelax-all -disable-free -disable-llvm-verifier -discard-value-names -main-file-name hello_world.cpp -mrelocation-model static -mthread-model posix -mdisable-fp-elim -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -v -resource-dir /usr/lib/llvm-9/lib/clang/9.0.0 -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++ -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/x86_64-linux-gnu -internal-isystem /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fdeprecated-macro -fdebug-compilation-dir /mnt/My_Linux_Files/C++/test2/src -ferror-limit 19 -fmessage-length 0 -fobjc-runtime=gcc -fcxx-exceptions -fexceptions -fdiagnostics-show-option -fcolor-diagnostics -faddrsig -o /tmp/hello_world-9f4c00.o -x c++ hello_world.cpp
clang -cc1 version 9.0.0 based upon LLVM 9.0.0 default target x86_64-pc-linux-gnu
ignoring nonexistent directory "/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/x86_64-linux-gnu"
ignoring nonexistent directory "/usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/backward"
ignoring nonexistent directory "/include"
#include "..." search starts here:
#include <...> search starts here:
 /usr/bin/../lib/gcc/x86_64-linux-gnu/10/../../../../include/c++
 /usr/local/include
 /usr/lib/llvm-9/lib/clang/9.0.0/include
 /usr/include/x86_64-linux-gnu
 /usr/include
End of search list.
hello_world.cpp:2:10: fatal error: 'iostream' file not found
#include <iostream>
         ^~~~~~~~~~
1 error generated.

The line:
Selected GCC installation: /usr/bin/../lib/gcc/x86_64-linux-gnu/10

confuses me, does clang think that gcc-10 is installed? Because I don't
think it is:
$ find /usr/ -iname "*gcc-10*"
/usr/share/gcc-10
/usr/share/doc/gcc-10-base
/usr/share/doc/libgcc-10-dev
$

Solution
As in the comments suggested, installing libstdc++-10 solved my issue

A: In Ubuntu 20.04, I setup by:
sudo apt update
sudo apt install clang

And then I compile & run a test app by:
clang++ -o smeagol smeagol.cpp
./smeagol

A: You may need to install a specifc version of g++ on your system, because clang++ does not come with its own set of headers. For Ubuntu 18.04, do it by invoking: sudo apt install g++-8.  Please see this nice article:
Clang++ missing C++ header?


text:
Q: WebApi Controller with two GET actions I want to have two different GET action to query the data by, name and id,
I have these routes:
        config.Routes.MapHttpRoute(
            name: "ActionApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
            name: "ActionApiByName",
            routeTemplate: "api/{controller}/{action}/{name}",
            defaults: new { name = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

and these actions in the controller:
    [HttpGet]
    public CompanyModel CompanyId(Guid id)
    {
          //Do something
    }

    [HttpGet]
    public CompanyModel CompanyName(string name)
    {
            //Do something
    }

while a call like this: http://localhost:51119/api/companies/CompanyId/3cd97fbc-524e-47cd-836c-d709e94c5e1e   works and gets to the 'CompanyId' method,
a similar call to http://localhost:51119/api/companies/CompanyName/something gets me to 404 not found
but this:
'http://localhost:51119/api/companies/CompanyName/?name=something' works fine
Can anyone explain this behaviour and what am I doing wrong?

A: The Web API route selector has no way to know if the string at the end of your URL is a GUID or not.  Therefore, it is not about to select the correct route for the appropriate GET action.
In order to select the correct route, you need to add a route constraint for the GUID uri template.
    public class GuidConstraint : IHttpRouteConstraint
    {
        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values,
                          HttpRouteDirection routeDirection)
        {
            if (values.ContainsKey(parameterName))
            {
                string stringValue = values[parameterName] as string;

                if (!string.IsNullOrEmpty(stringValue))
                {
                    Guid guidValue;

                    return Guid.TryParse(stringValue, out guidValue) && (guidValue != Guid.Empty);
                }
            }

            return false;
        }
    }

And then, add the constraint to the route that will handle the GUID.
config.Routes.MapHttpRoute(
            name: "ActionApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new { id = new GuidConstraint() }  // Added
        );

Since this route is more specific than the general "string" route, it needs to be placed above the one that is going to resolve name.
This should appropriately route to the actions.
Hope this helps.


text:
Q: Deserialization and serialization using newtonsoft c# My application is binding a REST API, that returns this to me:
{
    key: "XXXX-XXXX",
    fields: {
        customfield_10913: {
             value: "L2"
        }
    }
}

I'm using Newtonsoft JSON to serialize and deserialize and I've created these models to make it work:
public class Issue
{
    [JsonProperty("key")]
    public string Key { get; set; }

    [JsonProperty("fields")]
    public Fields Fields { get; set; }
}

public class Fields
{
    [JsonProperty("customfield_10913")]
    public CustomField Level { get; set; }
}

public class CustomField
{
   [JsonProperty("value")]
   public string Value{ get; set; }
}

The application is deserializing everything ok, using this code:
T model = JsonConvert.DeserializeObject<T>(result);

After a lot of business logic, my WEB API should return a new JSON:
protected T Get()
{
    return model;
}

And I've got everything like the JSON I've read from another API.
So, What I need?

*

*I need to read the field CUSTOM_FIELDXXX, but I can't return it with this name in my WEB API. How could I read this field, but when I'm doing the serialization, it assume another one?

A: You may try below function
Issue model = deserializeObject<Issue>(result);

public T deserializeObject<T>(string result)
        {
            try
            {
                var settings = new JsonSerializerSettings
                {
                    Formatting = Formatting.Indented,
                    NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
                    DefaultValueHandling = DefaultValueHandling.Ignore
                };
                var items = (T)JsonConvert.DeserializeObject(result, typeof(T), settings);

                return items;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {

            }

        }

A: If you can have any property name for your CustomField property, you can serialize that as a Dictionary<string, CustomField>, like so:
public class Issue
{
    public Issue()
    {
        this.Fields = new Dictionary<string, CustomField>();
    }

    [JsonProperty("key")]
    public string Key { get; set; }

    [JsonProperty("fields")]
    public Dictionary<string, CustomField> Fields { get; set; }
}

Then you can use any string-valued name for your custom field.
Working fiddle.


text:
Q: Java program to simulate user saving a page in Firefox I want to emulate a user saving a webpage into a directory (after login) from an external program in Java.
I found that this kind of things are usually done in testing suites such as Selenium or iMacros. Still, how could this be done in normal Java program?
Could I do it using DJnativeSwing?

A: You can perform the action with java.awt.Robot, which will really invoke Firefox. Or do you like to make a http-request with java? Did you think about images, videos, flash, javascript, cookies, referrer?


text:
Q: tree rebuilds when keyboard shows I'm using responsive_sizer package for my app..
my whole tree is rebuilt when the keyboard opens with a textfield.
Here the code of the textfield :

class ProfileNameTextField extends StatefulWidget {
  const ProfileNameTextField({Key? key}) : super(key: key);

  @override
  _ProfileNameTextFieldState createState() => _ProfileNameTextFieldState();
}

class _ProfileNameTextFieldState extends State<ProfileNameTextField> {
  TextEditingController? _controller;
  String _previousName = "";
  FocusNode? _focusNode;
  final String _forbiddenCharacters = "1234567890&)°(+=/,;.£\$*€<>\_#@";
  Widget _subText = Container();

  @override
  void initState() {
    // TODO: implement initState
    _controller = TextEditingController();
    _previousName = CloudUser.instance.username;
    _controller!.text = CloudUser.instance.username;
    _focusNode = FocusNode();
    _focusNode!.addListener(() {
      if(!_focusNode!.hasFocus) {
        print("Focus on name textfield is lost");
        _onSubmitted(_controller!.text);
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    // Clean up the focus node when the Form is disposed.
    _focusNode!.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Widget? _suffix;

    switch(Provider.of<LoadingProvider>(context).state) {
      case LoadingState.busy:
        _suffix = SpinKitRing(
          color: Theme
              .of(context)
              .primaryColor,
          lineWidth: 2,
          size: Theme.of(context).textTheme.subtitle1!.fontSize!
        );
        break;
      case LoadingState.idle:
        _suffix = Container();
        break;
    }

    return CustomTextContainer(
        child: InkWell(
            onTap: _giveFocus,
            child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children:
                [
                  Text(
                      "Prénom",
                      style: Theme.of(context).textTheme.bodyText2!.copyWith(
                        fontSize: Theme.of(context).textTheme.bodyText2!.fontSize!.sp
                      )
                  ),
                  Container(height: Sizer().heightSmallSpace),
                  Container(height: Theme.of(context).textTheme.bodyText1!.fontSize,
                    child: Row(children: [
                      Expanded(
                        child: TextField(
                          keyboardType: TextInputType.name,
                          controller: _controller,
                          onSubmitted: _onSubmitted,
                          focusNode: _focusNode,
                          decoration: InputDecoration(
                              isDense: true,
                              contentPadding: EdgeInsets.zero,
                          ),
                          style: Theme.of(context).textTheme.bodyText1!.copyWith(
                              color: Theme.of(context).primaryColor,

                              fontWeight: FontWeight.w600,
                              fontSize: Theme.of(context).textTheme.bodyText1!.fontSize!.sp
                          ),
                          textAlign: TextAlign.start,
                        ),),
                      _suffix,
                    ]),
                  ),
                  Container(height: Sizer().heightSmallSpace),
                  Row(children: [
                    Spacer(),
                    Container(
                        height: Theme.of(context).textTheme.subtitle1!.fontSize!*1.2,
                        child: Center(child: _subText)),
                  ]),
                  Container(height: Sizer().heightSmallSpace),
                ]
            )
        )
    );
  }

  _onSubmitted(String username) {
    RegExp regExp = RegExp('[' + _forbiddenCharacters + ']');
    if(!regExp.hasMatch(username)) {
      if(_previousName != username) {
        print("name is " + username);
        _previousName = username;
        setState(() {
          _subText = Container();
        });
        Provider.of<LoadingProvider>(context, listen: false).update('username', username).then((result) {
          if(result) {
            CloudUser.instance.username = username;
            setState(() {
              _subText = Text(
                "Enregistré",
                style: Theme
                    .of(context)
                    .textTheme
                    .subtitle1!
                    .copyWith(
                    color: color.success,
                    fontSize: Theme.of(context).textTheme.subtitle1!.fontSize!.sp
                ),
              );
            });
          }
          else
            setState(() {
              _subText = Text(
                "Erreur serveur",
                style: Theme.of(context).textTheme.subtitle1!.copyWith(
                    color: Theme.of(context).errorColor,
                    fontSize: Theme.of(context).textTheme.subtitle1!.fontSize!.sp
                ),
              );
            });
        });
      }
    } else {
      setState(() {
        _subText = Text(
          "Caractères interdits",
          style: Theme.of(context).textTheme.subtitle1!.copyWith(
              color: Theme.of(context).errorColor,
              fontSize: Theme.of(context).textTheme.subtitle1!.fontSize!.sp
          ),
          textAlign: TextAlign.right,
        );
      });
    }
  }

  _giveFocus() {
    _focusNode!.requestFocus();
  }
}

Within Sizer(), i have :
double padding = 2.h;

  double widgetHeight = 8.h;

  double iconButton = 4.h;

  double radius = 15;

  double lineWidth = 3.h;

  double heightSpace = 3.h;

  double heightSmallSpace = 0.9.h;

  double gridSpacing = 0.3.h;

  double widthSpace = 1.25.w;

ProfileNameTextField is included in

class _ProfileControllerState extends State<ProfileController> {
  @override
  Widget build(BuildContext context) {
    return Container(
        color: Theme.of(context).backgroundColor,
        child: Column(
            children: [
              ProfileAppBar(
                onSetting: _onSetting,
              ),
              Flexible(
                  child: Container(
                      padding: EdgeInsets.symmetric(horizontal: Sizer().padding/3),
                      color: Theme.of(context).scaffoldBackgroundColor,
                      child: Scrollbar(
                          child: SingleChildScrollView(
                              physics: ClampingScrollPhysics(),
                              child: Container(
                                  padding: EdgeInsets.symmetric(horizontal: Sizer().padding*2/3),
                                  child: Column(children:
                                  [
                                    Container(height: Sizer().heightSpace),
                                    SvgPicture.asset(
                                      "assets/icons/phone_kisses.svg",
                                      height: Sizer().widgetHeight*3,
                                      width: Sizer().getCustomWidth(66),
                                      fit: BoxFit.contain,
                                    ),
                                    _space(),
                                    ChangeNotifierProvider<LoadingProvider>(
                                      create: (BuildContext context) => LoadingProvider(),
                                      child: ProfileNameTextField(),
                                    ),

I have this problem since the import of the responsive_sizer... I do not understand where the problem can come from.
I tried resizetoavoidbottominset but nothing changed.

A: I found the problem. It's not coming from MediaQuery, but from the Responsive_sizer package.
When I open the keyboard, I actually update the height and width. But this package must necessarily encompass your MaterialApp in the following way:
    MaterialApp(
 home: ResponsiveSizer(
   builder: (context, orientation, screenType) {
     return const HomePage();
   },
 ),
);

And that's the problem. Under my homepage, I have a stream to see if the user is logged in, which then leads to the profile page, among other things. I don't want it to reload, I just want the profile to reload.
My solution: I use MediaQuery in a similar way to Responsive_sizer.... instead of using the .h and .w package, I use MediaQuery.of(context).size.height and its counterpart. The same thing for the font size.
I hope this can help those who have the same problem as me on this package,
good evening.


text:
Q: How to use getline and strtok together in C? this is my first time asking a question here so I hope I am doing it correctly! For a while now I have been trying to get getline and strtok to work together in order to read text from a file and break it into words. Essentially the text file input is an essay and I want to manipulate each word individually later on. The problem I am getting is a constant "assignment makes pointer from integer without a cast"; I have tried everything I can think of. This is my code as of right now:
int nbytes = 100;
char *buffer;
char *token;
buffer = (char *) malloc(nbytes + 1);
getline(&buffer,&nbytes,file);
token = strtok(&buffer, " ");

I feel like it's problem something really simple that I am overlooking. That you for reading and your help!

A: Standard C (on its own) doesn't define anything named getline. To read a line from a file you normally use fgets.
The error you describe sounds like you don't have a prototype for strtok in scope, so the compiler is treating it as if it returned the default type (int). You'd normally eliminate that by adding #include <string.h> somewhere close to the top of the file.

A: I don't think you want &buffer in your strtok() call.  Also, you're not including string.h, which is why you're getting the warning "assignment makes pointer from integer without a cast".  Without a correct prototype for strtok() available, the compiler is assuming that it returns int.  The conversion of that int to char * to make the assignment to token is the assignment it's complaining about.
Edit - thanks to @dmckee for the signature of getline().

A: one more error is using &buffer instead of buffer.
&buffer is pointer to pointer to char, but you need pointer to char.


text:
Q: Runtime Error when running a LDA model of gensim, how can I fix it? I have an runtime error:
RuntimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.
  0%|          | 0/29 [00:48<?, ?it/s]

When I try run this code:
def topic_model_coherence_generator (corpus, texts, dictionary, start_topic_count=2, end_topic_count=10, step=1, cpus=1):
    models=[]
    coherence_scores = []
    for topic_nums in tqdm(range(start_topic_count, end_topic_count+1, step)):
        lda_model = gensim.models.LdaModel(corpus=bow_corpus, id2word=dictionary, chunksize=1740, alpha='auto', eta='auto',
                                   random_state=42, iterations=500, num_topics=topic_nums, passes=20, eval_every=None)

        cv_coherence_model_lda = gensim.models.CoherenceModel(model=lda_model, corpus=bow_corpus,
                                                      texts=norm_corpus_bigrams, dictionary=dictionary,
                                                      coherence='c_v')

        coherence_score= cv_coherence_model_lda.get_coherence()
        coherence_scores.append(coherence_score)
        models.append(lda_model)
    return models, coherence_scores

lda_models, coherence_scores = topic_model_coherence_generator(corpus=bow_corpus,
                                                               texts=norm_corpus_bigrams,
                                                               dictionary= dictionary,
                                                               start_topic_count=2,
                                                               end_topic_count=30,
                                                               step=1, cpus=16)

That I want is obtain the optimal number of topics of my corpus for obtain then the topics and interpreting topic model results.
I'm biologist so I don't know how can I fix it.
Thanks for your help

A: It's good practice, & might be required on Windows before using other code that uses Python multiprocessing, to put your code inside a 'main' block. See more details at answer:
https://stackoverflow.com/a/60459949/130288
(…& possibly the other answer it refers-back to).


text:
Q: Selecting Using XSL Stylesheets <?xml version = "1.0" encoding = "UTF-8"?>
<?xml-stylesheet type="text/xsl" href="student-stylesheet.xsl"?>
<students>
    <student student-number = "1625344">
        <program> BIT </program>
        <study-model> on-campus </study-model>
        <student-type> domestic </student-type>
    </student>
    <student student-number = "2341235">
        <program> MIT </program>
        <study-model> distance </study-model>
        <student-type> international </student-type>
    </student>
    <student student-number = "1234567">
        <program> BMM </program>
        <study-model> on-campus </study-model>
        <student-type> domestic </student-type>
    </student>
    <student student-number = "8899009">
        <program> MIT </program>
        <study-model> on-campus </study-model>
        <student-type> domestic </student-type>
    </student>
    <student student-number = "0987654">
        <program> BIT </program>
        <study-model> on-campus </study-model>
        <student-type> domestic </student-type>
    </student>
</students>

Im trying to select the bottom student number and display it as a table with no header, just containing the student number, program, study-model and student-type.
    <?xml version="1.0" encoding="ISO-8859-1"?>

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">

        Program
        Student Model
        Student Type

        <xsl:value-of select="students/student/program"/>
        <xsl:value-of select="students/student/study-model"/>
        <xsl:value-of select="students/student/student-type"/>

</xsl:template>
</xsl:stylesheet>

This is my current sylesheet, it selects the very first student, not the last and is also missing the student number

A: To get Student number you should put new TD as <xsl:value-of select="students/student/@student-number"/>	. And if you want to get information of last student only, you should use predicate like  <xsl:value-of select="students/student[last()]/@student-number"/>


text:
Q: Matching Values in different ranges In one worksheet I have:
List of Overseas Office Company A       Hot Country        Cold Country
   Country A                              Country E          Country B
   Country B                              Country F          Country C
   Country C                              Country Y          Country N
   Country D                              Country A          Country W
I have Overseas Office = Range1; Hot Country = Range2 and Cold Country = Range3
In a separate worksheet I have:
Company    Hot Country Office  Cold Country Office
As I list companies, I need a formula that will check Range1 against Range2 and Range 3. So for Company A the result would be:
Company   Hot Country Office  Cold Country Office
A               TRUE                TRUE
Reason for the above is that Company A has offices in Countries A, B, C and D, and Country A is a Hot Country and Countries B and C are Cold Countries.
I've tried: =COUNTIF(Range1, Range2) + COUNTIF(Range1, Range3) >=1, however it does not appear this works each time.

A: It appears the following formula works:
=SUMPRODUCT(COUNTIF(Range1, Range2))>=1


text:
Q: Calling function by name (as a string) within an object literal in Javascript I am currently building something in JS and have run into the following scenario:
// these are set programmatically, not like this, just using as an example
var data = {'someData':'blah'};
var widget = 'NameOfWidget';
var command = 'someFunctionName';

// there is a base object that has all widgets and their commands as child objects
// format would be like: UBER.WidgetName.command(data);
// here is how I have tried to call it thus far
UBER[widget][command](data);
window['UBER'][widget][command](data);

I feel like I am close to figuring it out, just need a little help in figuring out exact syntax! Thanks!

A: Is there a reason you're not doing this?
window[UBER.widget.command](data);

Edit: I see what you're trying to do, this answer is currently incorrect should work, given that I understand what you're attempting to do.

A: Try:
UBER['widget']['command'](data);
window['UBER']['widget']['command'](data);

or
UBER.widget.command(data);
window.UBER.widget.command(data);

This assumes command is a function, widget and UBER are objects, and window['UBER'] = UBER.
When you are referencing object properties using bracket syntax, you need to use a string.  If using . syntax, you must use a legal string literal that is not a reserved word in Javascript.
For example:
var command = function(){return 5},
    widget = {},
    UBER = {};
UBER.widget = widget;
widget.command = command;
console.log(UBER['widget']['command']()); // prints 5 to Chrome's developer console or firebug


text:
Q: How to pass arguments (besides SendPort) to a spawned isolate in Dart In this article, they spawned an isolate like this:
import 'dart:isolate';

void main() async {
  final receivePort = ReceivePort();
  final isolate = await Isolate.spawn(
    downloadAndCompressTheInternet,
    receivePort.sendPort,
  );
  receivePort.listen((message) {
    print(message);
    receivePort.close();
    isolate.kill();
  });
}

void downloadAndCompressTheInternet(SendPort sendPort) {
  sendPort.send(42);
}

But I can only pass in the receive port. How do I pass in other arguments?
I found an answer so I'm posting it below.

A: We can get back the type safety by creating a custom class with fields
class RequiredArgs {
   final SendPort sendPort;
   final int id;
   final String name;

   RequiredArgs(this.sendPort, this.id, this.name);
 }

void downloadAndCompressTheInternet(RequiredArgs args) {
  final sendPort = args.sendPort;
  final id = args.id;
  final name = args.name;

  sendPort.send("Hello $id:$name");
}

Code will be much cleaner and safer in this way

A: Since you can only pass in a single parameter, you can make the parameter a list or a map. One of the elements is the SendPort, the other items are the arguments you want to give the function:
Future<void> main() async {
  final receivePort = ReceivePort();

  final isolate = await Isolate.spawn(
    downloadAndCompressTheInternet,
    [receivePort.sendPort, 3],
  );

  receivePort.listen((message) {
    print(message);
    receivePort.close();
    isolate.kill();
  });

}

void downloadAndCompressTheInternet(List<Object> arguments) {
  SendPort sendPort = arguments[0];
  int number = arguments[1];
  sendPort.send(42 + number);
}

You've lost type safety like this, but you can check the type in the method as needed.


text:
Q: Как установить значение textarea (TinyMce) с помощью jQuery? Как установить значение textarea(TinyMce editor) с помощью jQuery
html:

TEST2222

<textarea style="width: 100%; display: none;" cols="100" rows="5" name="elm" id="elm11" aria-hidden="true"></textarea>

jQuery:
$('.sp_comm').dblclick(function () {
    var sp_val = $(this).html();
    var sp_id = $(this).attr('id');
    sp_id = parseInt((sp_id / 10), 10);

    alert(sp_val + ',id:' + sp_id);
    $('#elm11').html('TTT');
})

A: tinymce.get('mceeditor_'+id).setContent(ajax_str);

ENG SO

A:  $('#elm11').val('TTT');

*

*начать, хотя бы, с этого. Только так значение textarea задается при помощи javascript. Про HTML забудьте.


text:
Q: How do I remedy SELinux not allowing legit programs in use access to my system? I have a system where some programs are getting access denied in SELinux when performing their duties. These programs are ClamAV, fail2ban and Logwatch.
I think I've managed to allow all the access for ClamAV (Clamscan), by following the directions in the SELinux Troubleshooter. I allowed fail2ban and Logwatch also in the troubleshooter but I suspect that they still are denied some access.
Here are the commands that allow a program:
grep fail2ban-client /var/log/audit/audit.log | audit2allow -M mypol

and
semodule -i mypol.pp

Question:
How do I find out what access SELinux is denying these programs, the access they need on the system and how to remedy this?
Here is:
ausearch -m avc

A: Sometimes selinux denies the access to resources without logging. Check if the "do not audit" rules enabled or not. Use "semodule -B" or "-DB" to enable or temporary disable it.

A: The location for SELinux logs are on there: logging is done in
/var/log/audit/audit.log

tailf that file and pipe it with grep to search for what you're looking for
Open /etc/selinux/targeted/booleans file using a text editor:
vi /etc/selinux/targeted/booleans

For example, in order to control Apache
Modify value for httpd_disable_trans as follows:
httpd_disable_trans=1
save and close the file. Type the following two commands:
# setsebool httpd_disable_trans 1
# /etc/init.d/httpd restart

if you want to do this on the X
Open a shell prompt
Type the command
system-config-securitylevel &

select SELinux tab > click on Disable SELinux protection for httpd daemon checkbox > Save the changes
# /etc/init.d/httpd r

restart for selinux to take the change


text:
Q: executing an UDF function in excel file from c# code I have a customized Excel User Defined Functions (udf) that gets data from a database to the Excel Sheet.
when I execute this function (=getData(A1,B1)) from a c# code to get data on an excel file, it will be put on a cell without being executed until i manually open the file . here is a part of my code :
var rng = workSheet.Range["A2"];  //where I will put the result table
            try{

            rng.Formula = @"=getData(A1,B1)"; //A1 =Cell from where the function   will get first argument
            String formula = rng.Formula.ToString();
            rng.FormulaHidden = false;
            workSheet.Unprotect();
            workBook.SaveAs(filePath, AccessMode: IExcel.XlSaveAsAccessMode.xlExclusive);
            formula = rng.Formula;
            bool hidden = rng.FormulaHidden;

        }
catch.....
//close opened instances of the Excel file

is there any solution to generate the result automatically and be prevented when the result is generated (it takes a while to get data from database)


text:
Q: probability variance question I would be very grateful if anyone could kindly help me with the following question.

Here is my working :

I get q as a negative probability => something is definitely wrong. Could anyone please let me know where have I gone wrong?
Thank you so much!

A: You basically did it right, double check for errors. It's hard on the eyes, does it say $\sigma^2= 0.99$? It looks wrong... As it stands (as it looks), the minimum variance should happen when $q=0$, which gives $\sigma^2=2.8236$ .


text:
Q: For $\alpha>0$, $\frac{\log x}{x^\alpha}\rightarrow0$ as $x\rightarrow\infty$ Courant & John's Introduction to Calculus and Analysis Volume I, p. 251.

Another simple proof may be suggested: For $x>1$ and $\epsilon>0$
$$\log x=\int^x_1\frac{d\xi}{\xi}<\int^x_1\xi^{\epsilon-1}d\xi=\frac{1}{\epsilon}(x^\epsilon-1);$$
if we choose $\epsilon$ equal to $\alpha$ and divide both members of this inequality by $x^\alpha$, then it follows that $(\log x)/x^\alpha\rightarrow0$ as $x\rightarrow\infty$.

$$\frac{1}{\alpha}\frac{x^\alpha-1}{x^\alpha}=\frac{1}{\alpha}(1-\frac{1}{x^\alpha})\rightarrow\frac{1}{\alpha}\text{.}$$
How does the conclusion follow from this?

A: Yep.
Greg Martin has the right idea,
but it can be done a little more simply.
Writing $c$ for $\epsilon$
because lazy,
you have shown that
$\ln(x)
\lt \dfrac1{c}(x^c-1)
$
so that
$\ln(x)
\lt \dfrac1{c}x^c
$.
Letting $c = \frac{a}{2}$,
this becomes
$\ln(x)
\lt \dfrac1{a/2}x^{a/2}
$
so
$\dfrac{\ln(x)}{x^a}
\lt \dfrac1{a/2}\dfrac{x^{a/2}}{x^a}
= \dfrac{2}{ax^{a/2}}
\to 0
$
as
$x \to \infty
$.


text:
Q: element of object_list in script section of django template my view returns the object_list to the template. I apply a for loop to this list and everything works fine. But when I write some Javascript inside script tags just below a button and try to get {{ post.pk }} inside script tags, it returns the pk of the last element in object_list. For example: if it is the first iteration and when above script tags I try to get {{ post.pk }}, it returns the pk of the current element of object_list. But when I try to do the same thing between script tags, it returns the pk of the last element of object_list.
What is the reason and is there any solution? Thanks in advance

A: I think you want to do something like:
<script>
  var object_list = [
  {% for obj in object_list %}
    {{ obj }}{% if not forloop.last %},{% endif %}
  {% endfor %}
  ];
</script>

Display the source or use an alert() to make sure the list is correct.


text:
Q: Disabled checkboxes if more than three checked in Angular 2+ I've created a table in angular material and i will compare the data of three rows.
Now i have to disable all other checkboxes if i have three boxes on checked.
I know i could use the [disabled] state from the material table, but if i checked three boxes, all boxes are disabled than. But i have to deselect the checked boxes so i could change the collection.
How could i write a if else statement?
Working tree

A: Just add !selection.isSelected(row) in the disabled state :
 <!-- Checkbox Column -->
  <ng-container matColumnDef="select">
    <th mat-header-cell *matHeaderCellDef></th>
    <td mat-cell *matCellDef="let row">
      <mat-checkbox (click)="$event.stopPropagation()" (change)="$event ? selectRow($event, row) : null" (change)="$event ? selection.toggle(row) : null" [checked]="selection.isSelected(row) == true" [disabled]="disableBoxes && !selection.isSelected(row)"
      >
      </mat-checkbox>
    </td>
  </ng-container>

Working Demo


text:
Q: -[UITableView reloadData] shows changes only after scrolling I update the UITableView on timer. I change data in array, then call -[UITableView reloadData]. But nothing is changed until I scroll the table or switch tabs in the tab bar. What's happening? How can I avoid this?

A: Don't reload table on not main thread

A: The problem was in that:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    self.newList = [self loadData];
    [self.delegate list:self didUpdate:self.newList];
});

Delegate call was on the background thread. If you want to update UI you should do in on the main thread.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    self.newList = [self loadData];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.delegate list:self didUpdate:self.newList];
    });
});