text:
Q: RXJS: Multiple Subscriptions in Order I've searched the web (StackOverflow, Rxjs, blogs, etc.) for an answer to my specific case, but I've not found anything for what I'm specifically looking for.
In my Angular component, I have the following:
  ngOnInit(): void {
    this.activatedRoute.queryParams.subscribe((params: any) => {
      if (!!params.page) {
        if (params.page <= 1) this.skip = 0;
        else this.skip = (params.page - 1) * this.limit;
      }
    });
    this.activatedRoute.params.subscribe((params: any) => {
      this.filter = params.filter;
      this.term = params.term;
      this.year = params.year;
      this.month = params.month;
    });
    this.activatedRoute.data.subscribe((data: any) => {
      this.setProvider(data.route);
      this.loadData(data.route);
    });
  }

My problem is I need the queryParams and the params subscriptions to complete and assign the public values before the data subscription takes place (queryParams and params can complete in any order as they don't have dependencies on each other).
In all of the examples I've seen, they show where each subscription is dependent on the previous and uses the values of the previous (passed down as variables). If I was using pure functions, I could possibly see where this is beneficial, but given that the code-behind in Angular also functions as a ViewModel, I'm simply setting public variables and then referencing them in the setProvider and loadData functions.
The below code works (basically chaining pipes), but given my limited knowledge on all that there is Rxjs, I wasn't sure if there was a cleaner, more efficient way to write this. It seems rather silly to return an observable just to use its values in the next chain of the pipe.
  ngOnInit(): void {
      this.activatedRoute.queryParams.pipe(concatMap((query: any) => {
        if (!!query.page) {
          if (query.page <= 1) this.skip = 0;
          else this.skip = (query.page - 1) * this.limit;
        }

        return this.activatedRoute.params;
      })).pipe(concatMap((params: any) => {
        this.filter = params.filter;
        this.term = params.term;
        this.year = params.year;
        this.month = params.month;

        return this.activatedRoute.data;
      })).subscribe((data: any) => {
        this.setProvider(data.route);
        this.loadData(data.route);
      });
  }

Thanks everyone!
Edit
The below also works using concat:
  ngOnInit(): void {
    concat(
      this.activatedRoute.queryParams.pipe((q: any) : any => {
        let query = q.getValue();

        if (!!query.page) {
          if (query.page <= 1) this.skip = 0;
          else this.skip = (query.page - 1) * this.limit;
        }
      }),
      this.activatedRoute.params.pipe((p: any) : any => {
        let params = p.getValue();

        this.filter = params.filter;
        this.term = params.term;
        this.year = params.year;
        this.month = params.month;
      }),
      this.activatedRoute.data.pipe((d: any) : any => {
        let data = d.getValue();

        this.setProvider(data.route);
        this.loadData(data.route);
      })
    );
  }

A: Thanks to Joosep for the answer. I've updated it due to the his recommended function signature being deprecated.
Here's the updated version:
  ngOnInit(): void {
    combineLatest([
      this.activatedRoute.queryParams,
      this.activatedRoute.params,
      this.activatedRoute.data,
    ]).subscribe(
      ([queryParams, params, data]) => {

        if (!!queryParams['page'] && queryParams['page'] <= 1) {
          this.skip = 0;
        } else {
          this.skip = (queryParams['page'] - 1) * this.limit;
        }

        if (params) {
          this.filter = params['filter'];
          this.term = params['term'];
          this.year = params['year'];
          this.month = params['month'];
        }

        if (queryParams && params && data) {
          this.setProvider(data['route']);
          this.loadData(data['route']);
        }
      }
    );
  }

A: If it has to be done with manual subscriptions I would combine latest for the activatedRoute queryParams, params and data and with a basic if check run the last part when appropriate.
Something like this maybe:
    combineLatest(
      this.activatedRoute.queryParams,
      this.activatedRoute.params,
      this.activatedRoute.data,
      (queryParams: Params, params: Params, data: any) => ({
        queryParams
        params,
        data,
      })
    ).subscribe((res: {queryParams: Params; params: Params; data: any }) => {

      if (!!queryParams.page && queryParams.page <= 1) {
       this.skip = 0;
      } else {
        this.skip = (queryParams.page - 1) * this.limit;
      }

     if (params) {
      this.filter = params.filter;
      this.term = params.term;
      this.year = params.year;
      this.month = params.month;
     }

      if (queryParams && params && data) {
        this.setProvider(data.route);
        this.loadData(data.route);
      }
    });

Also try to enforce strong types if possible.


text:
Q: How to pass data to newly added array element components How to pass additional data to newly added array element components by onAddClick props?
onAddClick: (event) => void: A function that adds a new item to the array.
docs
I just need to copy item and create new one with data of clicked one.
This is how I remove an item
const handleRemove = () => {
if (typeof formContext.removeObject === 'function') {
  formContext.removeObject(index, props.onDropIndexClick(index), title);
} else {
  props.onDropIndexClick(index)();
}

};
This is how I render them
export function CardArray(props) {
  const classes = useStyles();
  const { title, items, canAdd, onAddClick, formContext } = props;

  return (
    <Card className={classes.wrapper}>
      <CollapseTitle title={title}>
        {items.map(element => arrayItem(element, formContext, classes,
         title))}
      </CollapseTitle>
      {canAdd && (
        <CardActions>
          <Fab
            className={classes.addObjButton}
            color="primary"
            size="small"
            onClick={onAddClick}
          >
            <AddIcon />
          </Fab>
        </CardActions>
      )}
    </Card>
   );
 }

A: You can use an updater function when modifying states:
const onAddClick = () => {
 this.setState(prevState => ({
  items: [...prevState.items, newItem]
 }))
}

you could als us concat cuz it returns a new array:
const onAddClick = () => {
  this.setState({
   items: this.state.items.concat([newItem])
  })
}

or if you are familiar with ES6 (which I think you do) then you can use the Spread Operator:
const onAddClick = () => {
  this.setState({
   arrayvar: [...this.state.arrayvar, newelement]
  })
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Full url with schema, domain and port How do assemble (using Zend Routes) the full url with schema, domain and port, not just a root-based path?
Sample use case: we need to specify full url in the emails sent to the clients.
AFAIK there is no any built-in solution but what is a best practice in this case and/or what do you specifically use in such cases?

A: Use a combination of ServerUrl and Url view helpers, eg
<a href="<?php echo $this->serverUrl($this->url(array(
    'url' => 'params'), 'route', $reset, $encode)) ?>">My Link


text:
Q: Why I can't use a random colour generated with rgba? When I use this function to generate random colours the lint said:
Converts a string to an integer.
@param string — A string to convert into a number.
@param radix
A value between 2 and 36 that specifies the base of the number in string. If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. All other strings are considered decimal.
function colorGenerate() {
  const red = parseInt(Math.random() * 256);
  const green = parseInt(Math.random() * 256);
  const blue = parseInt(Math.random() * 256);
  return `rgb(${red}, ${green}, ${blue})`;
}


text:
Q: GSAP ScrollTrigger background color change animation not working well on Safari I'm trying to make a gsap animation that switches the viewport's background color depending on your scrolling position. The animation works great on Chrome and on FireFox, but on Safari it just looks bad, very laggy and the colors don't transition into the page, but rather just pop up with a delay.
Here is my animation (I am using Vue.js)
backgroundAnimation() {
      let $projects = gsap.utils.toArray(this.htmlID + " .project-wrapper");
      let projectListTl = gsap.timeline({
        scrollTrigger: {
          trigger: this.htmlID,
          start: "top center",
          end: "bottom center",
          ease: "none",
          scrub: true,
          markers: false,
          onLeave: ({ progress, direction, isActive }) =>
            document.documentElement.style.setProperty("--background", "white"),
        },
      });
      $projects.forEach(($project, i) => {
        projectListTl.to("html", {
          duration: 0.1,
          "--background": $project.dataset.projectColor,
        });
        projectListTl.to("html", {
          delay: 0.3,
          duration: 0.2,
          "--background": "transparent",
        });
      });
    },

(The method above runs when there is an update on the component)
  updated: function () {
    this.$nextTick(function () {
      this.backgroundAnimation();
      const self = this;
      ScrollTrigger.matchMedia({
        "(min-width: 1024px)": function () {
          self.scrollAnimation();
        },
      });
    });
  },

Does anybody have any ideas as to why this is happening on Safari?


text:
Q: accessing class_attribute from module in Rails 4 I have a module that defines custom attr_accessible attribute as follow:
module MyModule
    include ActiveModel::MassAssignmentSecurity
    %w[var1 var2].each do |key|
        attr_accessible key
    end
end

class MyClass
    include MyModule
end

Since attr_accessible is defined in ActiveModel::MassAssignmentSecurity, I include it in MyModule.
However, when I call object = MyClass.first; object.var1
I get the following error:
NoMethodError: undefined method `class_attribute'

Now, this method seems to be defined in active_support/core_ext/class.rb. However, even after
require 'active_support/core_ext/class'

I still get the same error message.
Which module I should include in order to access this method? I am using Rails 4, with protected_attributes gem.
Update1: add include ActiveModel::MassAssignmentSecurity


text:
Q: C++ command prompt my program does not display in command prompt when i run it (even when the codes are correct, I tested with the simplest program of all- Hello World). I usually work with Code Blocks, I thought that was the problem but encountered the same problem with DEV C++. I have followed a couple of instruction online to get the problem resolved using Dev C++, the problem persist. Please help
See attached picture.

A: There may be several reasons why the console application run from IDE does not show message.
I am trying to consider some of them.

*

*Your program ends immediately after start and printed text disappears for some reason
(in some IDE console window for your code will appear for a fraction of a second)
Add some code that will wait input, e.g.:

#include <iostream>

using namespace std;

int main(void)
{
    int number;
    cout << "Enter a number, please" << endl;
    cin >> number;
    return 0;
}

*Your IDE executes previously compiled program that was build from source code without any output.
Try to clean current project and then rebuild it again (or create new project with the same code)

*Perhaps, properties of your console window do not allow you to see printed text.
Make sure that Screen text color is set to light (Move mouse arrow to top-left corner of console screen -> right-click -> properties -> colors tab -> Screen text option -> select a color)


text:
Q: How to tell make to track the output of a python script and only run the script if the input file was updated I know that in the context of creating a c/c++ executable, make automatically takes care of creating the executable only if the dependency files have been updated.
I have been wondering if there is a way to specify the input and output files of a python script to make, such that make can do its magic depending on the status of the input file.
Makefile entry:
update_info:
    python update_info.py info.xml

# Output file : info.hpp

Basically I would like make to check the version of info.xml. If it has not been updated, I don't want make to run the update_info.py script.
Just trying to find out if there is an existing way to do it. I can live with it, if this cannot be done.
Thanks.

A:
I have been wondering if there is a way to specify the input and
  output files of a python script to make, such that make can do its
  magic depending on the status of the input file.

Of course.  At its core, make is a very simple and general system.  It defines a format for expressing the prerequisites for building various targets, and for expressing machine-actionable instructions for actually building those targets from their designated prerequisites.  Given that information, make figures out which recipes, if any, to execute to build a requested target or to bring it up to date with respect to its direct and indirect dependencies.
Make knows nothing about the nature of the targets and prerequisites other than that they are timestamped files (or so it assumes).  Make having been designed with building software in mind, it does come with some built-in rules aimed at building programs from source code written in a few select languages, but that's a convenience feature, not a limitation.
If you want to provide for building a file named info.hpp based on another file named info.xml then info.hpp is the target and info.xml is the (a) prerequisite.  A rule along these lines would then be appropriate:
info.hpp: info.xml
    python update_info.py info.xml

Generally speaking, though, it is best to avoid repeating target and prerequisite names in the recipe wherever possible.  Instead, use the appropriate automatic make variables, such as $^, which represents the distinct elements of the prerequisite list:
info.hpp: info.xml
    python update_info.py $^

Under some circumstances, you might want the Python script to be a prerequisite, too, since changes to the script could cause it to produce meaningfully different output from the same input.

A: Figured out a way to do this for existing files which are updated by a script:
The solution is to create a new file by copying the make target file.
update_info: target/info.hpp

target/info.hpp: info.xml
    python update_info.xml info.xml
    cp info.hpp target/info.hpp

This way, the current folder can contain a previous version of info.hpp. Make tracks the info.hpp file in target folder and will only run the script if the input file info.xml has changed.
The side effect of this is that the info.hpp in the current folder is updated only if info.xml has changed. Which is what was needed.
If you are using git, you may need to add the target/info.hpp file to the ignore list.
This method is helpful in using make to track those files in a repository with an existing file which is updated by a script.


text:
Q: Another reference for higher order Fourier analysis I am trying to read Tao's Higher order Fourier analysis but I would be very happy to find another book on the subject. I would like to learn something about the Gowers norm and about Roth's theorem (density increment and energy increment arguments). Sorry if this question is a bit too open ended . Lecture notes, even separately on each topic I just mentioned are absolutely fine.
Part of the reason is that I am not sure what the natural context for Fourier measurability and complexity is, whatever natural means and I was hoping I could understand these if I had another reference. Thanks!

A: You could try "Nilpotent structures in Ergodic theory" by Host and Kra, which covers this topic in greater depth.

A: There are a couple of references I have found immensely useful, incidentally co-written by the same author.

*

*The primes contain arbitrarily long arithmetic progressions, Annals of Mathematics,167(2008), 481–547.

*Green B., Tao T. (2010) An Arithmetic Regularity Lemma, An Associated Counting Lemma, and Applications. In: Bárány I., Solymosi J., Sági G. (eds) An Irregular Mind. Bolyai Society Mathematical Studies, vol 21. Springer, Berlin, Heidelberg.
Note that the notion of Fourier-measurability in the book listed above coincides with that of s-measurability in the second paper (Def 2.2).


text:
Q: Disable Delve Per User PowerShell Is there a way using PowerShell to disable Delve on a per user basis?
On the settings cog on the About Me page for Delve I can see an option to turn Delve off. This setting only applies to my account.
As an admin I need to apply this setting for all users.


text:
Q: Implementing 3 variable boolean function od 2-1 multiplexers Recently i've been given a task from my lecturer to implement  \$f=\sum(1, 3, 4, 5, 7)\$ on "2-bit multiplexers". That's it. I assume he meant 2:1 MUX.
I've came up with following k-map...
+------+---+---+
| AB/C | 0 | 1 |
+------+---+---+
| 00   | 0 | 1 |
| 01   | 0 | 1 |
| 11   | 0 | 1 |
| 10   | 1 | 1 |
+------+---+---+
\$A\overline B + C\$
... and following 2 schematics:
1)

2)

Since the execrise's desscription consists plural multiplexers- is the second example OK? And if the description would mention using only one MUX- is the first example OK?

A: Both are ok. You have saved 4 pcs of 2 to 1 muxes when compared to canonical 8 input solution.


text:
Q: Log in session with specific commands I would like to build a service program which allow user specific command in Ubuntu lightdm loggin page.
When the user tape for example Ctrl + X, my session is open. I do know how to build a service program but I don't know how to autorise my service to be able to open my session ( and the command to do that).
Do I need to store my password somewhere on my computer or service priviliges are enough to open my session without my password?
Edit: In fact I found documentation on linux PAM.  Can I add a service on the /etc/pam.d/lightdm as sufficient which check if the user tape Ctrl + X ?


text:
Q: i am trying to use importlib.import_module(package_name, class_name) but facing the below error  Error occurred in import_library function ::: Traceback (most recent call last):
  File "C:\Users\alok.jha\Anaconda3\envs\myenv_dedupe\lib\DataManipulationLib\data_manipulation.py", line 2984, in import_local_libs
    interim_obj = importlib.import_module(package_name, class_name)
  File "C:\Users\alok.jha\Anaconda3\envs\myenv_dedupe\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1030, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1007, in _find_and_load
  File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 680, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 850, in exec_module
  File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed

i am trying to use  importlib.import_module(package_name, class_name) but facing the below error

A: I'm facing similar problem, and here is my solution.
Supposing I want to import class Man from the path root.human
import importlib

package = importlib.import_module('root.human')

Then I can call the Man class by package.Man.


text:
Q: Expand ContentPanel in AccordionLayoutContainer In my project I using gwt 2.5.1 + gxt 3.0.1 + gwtp (plugin for eclipse), and MVP - pattern.
I use AccordionLayoutContainer with 3 ContentPanel. When the application loads all panels collapsed.
How to make that one panel was expanded, depending on which parameter is specified in the link?

A: With:
navigator = new AccordionLayoutContainer();
navigator.setExpandMode(ExpandMode.SINGLE_FILL);

tells GXT to have only one panel open at one time.
And with navigator.setActivePanel(widget); you can set the active widget.


text:
Q: How can I make a 'Today's featured article' extraction from a MySQL DataBase in PHP? How could I make a 'Today's featured article' system using PHP and MySQL?
Each day, the first time a user visits the site, I need to randomly select one article from the database, and that will be used for the whole day, for every user that comes to the site.
This would happen without any intervention of the administrator, so the script would be triggered by the users visiting.
As I understand it, the first time a user visits the page on a new day, the script would randomly (or on some other basis) select an article, then flag it in the database, at the same time unflagging the article from the previous day. But what if two users are visiting the same page at the same time? This would probably mean there will be two articles flagged at the same time!
And how do you cope with time zones?

A: What I would do is:

*

*Run a cron job at midnight UTC.  You can write offline cron jobs in PHP.

*Randomly select an article id.  This can take a few seconds depending on how you do it, so it's best to do it in an offline job, not during any user's PHP request.

*Generate from the article a fragment of HTML, e.g. the intro for the article with a "read more..." link.  Of course be careful about creating HTML containing XSS vulnerabilities.

*Store the fragment of HTML in memcached under a known key.

Then when visitors visit the site, their page view just extracts the HTML fragment from memcached and outputs it directly in the page.  At midnight, the HTML fragment changes atomically and the next PHP request fetches the newly saved article.
Since the cron job is the only code choosing a random article, it's not running concurrently with any other code, so no need for locking.
Not running memcached?  Get used to it.  Web app architecture needs some judicious, application-specific caching, and memcached is the best solution for this.
Regarding timezones, the short answer is use UTC for everything.  For a lot more detail, listen to the OurSQL Podcast episode 46: It's About Time.

A: You will need to construct 2 databases. One with the obvious news articles, the other which holds the article ID for that particular date. You can run checks in the PHP when the site is loaded to check the current date and if there exists an article. If not, the user is the first to arrive on the site and therefore find a random article and insert it into the table with the articles by day.
I am not going to write the entire script for you, but I will give you a few elements of it. As for time zones, you will use the server time and not the end-user's computer time. This is a breach of security, as they could have set a date in the future or past, over writing any data.
For users who visit the site at the "same time", this is very unlikely.
For selecting a article by date from the MySQL database you can use:
$check_sql = "SELECT * FROM todays_article
          WHERE date = '" . date("j-n-Y") . "'
          LIMIT 1";
$check_qry = mysql_query ($sql);
if (mysql_num_rows ($check_qry) == 1) {
    // Do nothing
}
else {
    $random_sql = "SELECT article_id FROM articles
               ORDER BY RAND() LIMIT 1";
    $random_qry = mysql_query ($random_sql);
    $random_row = mysql_fetch_assoc($random_qry);
    $insert_sql = "INSERT INTO todays_article
               ('article_id', 'date') VALUES
               ('" . $random_row["article_id"] . "', '" . date("j-n-Y") . "')";
    $insert_qry = mysql_query($insert_sql);
}

It's untested, but it gives you an idea of what you wanted to achieve.

A: You can do it without having to save anything anywhere by using the date to seed a hash function that spits out an article id. I don't know that I'd recommend actually doing this, but it's fun to think about alternate solutions anyway. :)
$id = hexdec(substr(md5(date('Ymd')), 0, 8)) % $number_of_articles;

Note:

*

*$id is not necessarily article.id, but the Nth article.

*You can change how often the article changes just by changing the date format. If you want to change it hourly, just make it: date('H')


text:
Q: regex wildcard find and replace notepad++ Hi I am trying to do a simple regex that is annoying me because it should be easy - I am using notepad++  and that might be filtering "differently"
here is what I have
I want to find inside the string id=0&name=/1274-IMG_2919.JPG the bit that is the wildcard 1274-IMG_2919 so that it becomes after it's replaced id=0&name=/1274-IMG_2919.JPG -O 1274-IMG_2919.JPG
here is what I have and it doesn't work
FIND:         \&name\=\/([a-zA-Z0-9]+)\.JPG
REPLACE:      &name=/$1.JPG -O $1.JPG

A: Your looking for a string with - and _ but they are not part of the character set you define: [a-zA-Z0-9], this works for me;
\&name\=\/([a-zA-Z0-9\-_]+)\.JPG

(or briefer &name=\/([\w\-]+)\.JPG)


text:
Q: Pcrecpp matches I use pcrecpp c++ ( PCRE lib )
And i need get all matches in cycle. How can i do it?
For example pattern:
"hello"
and subject:
"hello hello hello"
Cycle should loop 3 times ( because 3 matches )
1 hello
2 hello
3 hello
Pseudocode
pcrecpp::RE pPattern ( "hello" );
std::string strBase = "hello hello hello";
// ...
int iMatches = // Match count
for ( int i = 1; i < iMatches; i++ )
{
    printf( "%d %s", i, pPattern[ i ].c_str () );
}

Please give me some example code how to do it with pcrecpp.h.
Sorry for my bad english.

A: Even though this question is already some months old, I'll provide a solution here:
#include <pcrecpp.h>
#include <iostream>

int main(void)
{
  pcrecpp::RE regex("(hello)");
  std::string strBase = "hello hello hello";

  pcrecpp::StringPiece input(strBase);

  std::string match;

  int count = 0;
  while (regex.FindAndConsume(&input, &match)) {
    count++;
    std::cout << count << " " << match << std::endl;
  }
}

For more information, this site might help.


text:
Q: PHP preg_replace(): Unknown I get this warning message - "Warning: preg_replace(): Unknown modifier '+'" when I run this code:
$newString = preg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","\\0", $originalString);
return $newString;

How do I stop this?

A: You need to add delimiters to your expression:
$newString = preg_replace("~[[:alpha:]]...~"

Here, I used the tilde ~, but you can use something else if you prefer.


text:
Q: Model factory Zend 2 I would like an elegant way of creating a factory of models (TableGateway) by using Zend Framework 2.
I would not like to put all the dependency injection in file module.config.php.

A: Well, i don't like that either and for a better readability i put it all into factory classes.
Module.php
class Module implements \Zend\ModuleManager\Feature\ServiceProviderInterface
{
    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'namespace-model-servicename' => 'Namespace\Factory\SomemodelServiceFactory'
            )
        );
    }
}

Namespace\Factory\Servicename.php
<?php
namespace Namespace\Factory;

use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\FactoryInterface;
use Namespace\Model\SomemodelService;

class SomemodelServiceFactory implements FactoryInterface
{
    /**
     * Create service
     *
     * @param ServiceLocatorInterface $serviceLocator
     * @return \Namespace\Service\SomemodelService
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $service = new SomemodelService();
        $service->setEntityManager($serviceLocator->get('Doctrine\ORM\EntityManager'));
        return $service;
    }
}

This now is an example of a ServiceFactory that injects Doctrines EntityManager. Obviously you'd need to refactor all classes and stuff to fit your needs, but basically this is the approach you'd be running.


text:
Q: Dimension of a representation needs to be the same as the number of its invariant subspaces? Does a representation of a group have the same number of invariant subspaces as the  dimension of the representation?
Supposing a matrix representation of a group (W) whose elements in the representation are matrices of dimension $n \times n$ with $n ∈\mathbb N$. Are there always going to be n linear independent vectors that are going to be invariant subspaces?
Or is it possible that the dimensions of the matrix and the number of invariant subspaces are different (i.e. $\dim(W)=n$ and $\dim(V)=m$ with $n≠m$ being  $V$ the span of the invariant subspaces)?


text:
Q: Equivalent of SUMPRODUCT in dataframe with strings What would be the equivalent in Pandas of the PRODUCTSUM in Excel? I have this formula in Excel with PRODUCTSUM inside a conditional IF.
IF(PRODUCTSUM((A$2:A2=A2)*(C$2:C2=C2)*(B$2:B2=B2))>1;0;1)

I have found some examples in other posts like these:
Excel Sumproduct equivalent in Pandas
but these refer to columns with integers and since my columns are composed of strings I do not know how to proceed. Any help would be appreciated.
Let's pretend my df is like:
A        B             C             Output
'John'   'Sanchez'  'Active'         1
'Mike'   'Isner'    'Inactive'       1
'Mike'   'Isner'    'Inactive'       0

A: you can use groupy
df['Output']=df.groupby(['A','B','C']).cumcount()
df.Output = df.Output + 1
df.loc[(df.Output > 1),"Output"] = 0


text:
Q: Function analytic in each variable does not imply jointly analytic I have heard that a function $f: \mathbb R^2 \to \mathbb R$ can be analytic in each variable (i.e. $f(x,y_0) = \sum_{n=0}^{\infty} a_n x^n, \forall x \in \mathbb R$, and the same for $y$) without being jointly analytic (i.e. $f(x,y) = \sum_{i,j=0}^{\infty} a_i b_j x^i y^j, \forall x,y \in \mathbb R$).
Is there some standard example of such a function?

A: $$
f(x,y) = \begin{cases}
\dfrac{xy}{x^2+y^2} & \text{if $(x,y)\ne(0,0)$} \\
0 & \text{if $(x,y) = (0,0)$} \\ \end{cases}
$$
is analytic in each variable, but it is not continuous at $(0,0)$.

A: For completeness, I add a jointly $C^\infty$ example, taken from separate vs joint real analyticity:
$$f(x,y) = xy\exp\left(-\frac{1}{x^2+y^2}\right),\qquad f(0,0)=0 \tag1$$
The restriction to each coordinate axis is identically zero. The restriction to other lines parallel to coordinate axes is real analytic since it's a composition of real analytic functions.
But $f$ is not jointly analytic, since it decays faster than any polynomial at $(0,0)$:
$$\lim_{(x,y)\to (0,0)} (x^2+y^2)^{-N} f(x,y)=0 \qquad \forall N$$
(A function that is representable by a power series cannot do this, since it's asymptotic to the sum of the lowest-degree nonzero terms of the series.)

A relevant result was proved by J. Siciak in A characterization of analytic functions of n real variables, Studia Mathematica 35:3 (1970), 293-297: if a jointly $C^\infty$ function is real-analytic on every line segment, then it is jointly real-analytic. The function (1) fails the condition of Siciak's theorem, since it is not real-analytic on the line $y=x$.


text:
Q: Remove blocked users from chat messages list I have a list of all messages like this which contains the user id who sent it
$messages= Chat::all();

And a list of blocked users like this with the id of the user who was blocked
$blockedUsers=BlockUser::where('user_id', $user->id)->get();

My question is How to remove a message if the user id of the message exist in the blocked list?

A: To delete all messages of a blocked user you can do it in the following way.
if ($blockedUsers = BlockUser::pluck('id')) {
    $messages = Chat::whereNotIn('user_id', $blockedUsers)->get();
}

It should be noted that there are many ways to do this, directly with 1 single query doing Subqueries, but this will be enough to solve your problem and you will understand it much better, the other ways require a deeper knowledge of the framework.

A: The filter messages, blocked users
public function getMessages(): JsonResponsive
{
  $messages = Chat::where('user_id', '!=', $blockedUserId)->get();

  return response()->json($messages)
}


text:
Q: GAE + JPA + JsonMappingException + You have just attempted to access field I'm new with JPA and GAE. I'm having some problems trying to retrive some entities to the front end. I copy mi entity code:
@Entity
public class User implements Serializable{

   private static final long serialVersionUID = -7949567692618870100L;

   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   private Key key;

   private String userName;

   private String email;

   @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL)
   private List<User> friends;

   @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
   private Credential Credential;

   //getters & setters
}

The Credential entity only contains userName and pass:
@Entity
public class Credential implements Serializable{

  private static final long serialVersionUID = -3277842132830057420L;

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Key key;

  private String userName;

  private String pass;

  //getters and setters
}

I generate UserEndpoint with GAE Eclipse Plugin and then I added a method to simulate a Login, this is the method:
@ApiMethod(name = "CredentialLogin")
public User CredentialLogin(@Named("pass") String pass,@Named("userName") String userName){
    EntityManager mgr = getEntityManager();

    Query query = mgr.createQuery("SELECT FROM User u WHERE u.email = :email");
    query.setParameter("email", userName);

    User user = null;
    try {
        user = (User) query.getSingleResult();
        if (!user.getCredential().getPass().equals(pass))
            //INVALID LOGIN
    }
    finally {
        mgr.close();
    }
    return user;
}

Debugging the code I get the correct User from the datastore. Doing "user.getCredential()" the Credential fetchs to the User entity. As the "friends" field has LAZY fetching when I return the User entity I will appear NULL (This is what I want).
After the return I'm getting this error:
"com.google.appengine.repackaged.org.codehaus.jackson.map.JsonMappingException: You have just attempted to access field "friends" yet this field was not detached when you detached the object. Either dont access this field, or detach it when detaching the object."
I don't want to put EAGER fetching to my "friends" attribute because the list could be really big.
I don't want to remove my "friends" getter and setter method, because without them I couldn't access to the field.
Somebody knows what should I do.
Thank you very much

A: You can change the enhancement process to call a listener instead of throwing an exception when an undetached field is accessed. See http://www.datanucleus.org/products/accessplatform_3_1/enhancer.html  and "detachListener" option


text:
Q: How can a User create dates in my Calender (java)? I m currently trying to code a Calender with java.
I created 3 classes:
1. Date( includes year, month....)
2. Event(includes people, place, the class Date ... + an option to create dates )
3. Mainclass My mainclass that contains the menu.
My problem is that I don't know how the user is able to create his own date, because I have to create the object Termin myself... So, can somebody help me fix this? Thx in advance!
public class Event {
   private String mDescription, mPlace, mNames;
   private Date mStart, mEnd;

Termin(String description, String place, String names, Date start, Date end) {
    mBetreff = description;
    mOrt = place;
    mNamen = names;
    mBeginn = start;
    mEnde = end;
}

public void create() {
    Scanner read = new Scanner(System.in);
    System.out.println("Enter 1. description 2. place 3. names 4. start 5. end ein");
    mDescription = read.nextLine();
    mPlace = read.nextLine();
    mNames = read.nextLine();
}

public String toString() {
    return "Description : " + mDescription + "\nPlace: " + mPlace + "\nNames: " + mNames + "\nIts starts at " + mStart
            + " and ends at " + mEnd;
 }
}

public class Date {
   private int year, day, month, hours, minutes;

Datum(int year, int month, int day, int hours, int minutes) {
    this.day= day;
    this.year= year;
    this.month= month;
    this.hours= hours;
    this.minutes= minutes;
}

public String toString() {
    return "\n" + day + "." + month + "." + year + " um " + hours+ ":" + minutes;
}

public void enterDate() {
}
}

EDIT:
I asked this question 2 years ago, back when I just started coding and had no idea of oop and encapsulation ...
To answer my own question, for every newbie that also tries to create a terminal calender:
Date needs the following methos:
public setDate() {
   this.year = read.nextLine();
   ...
}

for every member.
Event takes the resulting object Date, either in the constructor or in a setter like method.

A: Creating an instance-method to create an appointment is kind of... strange since one needs to create an appointment (called Termin in your case) to create an appointment. One possibility would be the builder pattern. By having a public static inner builder class, you can set the constructor(s) private and enforce the use of that builder:
 public class Main {

    private int value;

    private Main(int value) {
        this.value = value;
    }

    public int getValue() {
        return (this.value);
    }

    public static class MainBuilder {

        boolean valueWasSet;
        int value;

        public MainBuilder() {
            this.valueWasSet = false;
            this.value = -1;
        }

        public void setValue(int value) {
            this.value = value;
            this.valueWasSet = true;
        }

        public Main build() {
            if (!this.valueWasSet) {
                throw new IllegalStateException("value must be set before a Main can be build.");
            }

            return (new Main(this.value));
        }
    }
}

(this is a simplified sketch to show the core mechanism on how to assert that certain values are set before constructing a Main through MainBuilder.
The process of constructing a Main would be:
MainBuilder builder = new MainBuilder();

builder.setValue(100);
// all following Main's will have a value of 100
Main mainOne = builder.build();
Main mainTwo = builder.build();

builder.setValue(200);
// all following Main's will have a value of 200
Main mainThree = builder.build();
Main mainFour = builder.build();


text:
Q: What installs the JET ODBC Driver? I know that Excel is not a multi user app and one should not attempt to use it in a multi user web environment, but is using the JET Driver to read Excel files OK?
What installs the Jet Driver? My guess is that you get it when you install ACES or EXCEL or some other Office apps and that I wouldn't normally expect it to be found on a web server. Is this correct?
If it can be installed separately, is using this driver to read an uploaded Excel file a viable approach provided that the XLS file will only be read once when the file is uploaded into a table?

A: Here's a very good C# project for reading Excel files in purely managed code with no dependencies and is safe for use in ASP.NET.
http://www.codeproject.com/KB/office/ExcelReader.aspx
If you have significant existing code and want to stick with Jet, you can download an installer here.  Yes, it is safe for use in ASP.NET (Office automation isn't, but Jet is fine).
http://support.microsoft.com/kb/239114

A: Microsoft Data Access Components (MDAC)


text:
Q: How to fill nan value in pandas dataframe from value in another column and above row? I have df as follows:
df = pd.DataFrame({"A":[0,np.nan,0,0,np.nan,1,np.nan,1,0,np.nan],
                   "B":[0,1,0,0,1,1,1,0,0,0]})

Now, I need to replace nan values in column A with values from column B and one above row. for example: 2nd row for column A should be 0, 7th row equals to 1 etc.
I defined this function but it doesnt work trying to apply into dataframe
def impute_with_previous_B(df):
    for x in range(len(df)):
        if pd.isnull(df.loc[x,"A"]) == True:
            df.loc[x,"A"] = df.loc[x-1,"B"]

df["A"] = df.apply(lambda x: impute_with_previous_B(x),axis=1)

Can you please tell me what is wrong with that function ?

A: df['A'] = df['A'].fillna(df['B'].shift())

     A  B
0  0.0  0
1  0.0  1
2  0.0  0
3  0.0  0
4  0.0  1
5  1.0  1
6  1.0  1
7  1.0  0
8  0.0  0
9  0.0  0


text:
Q: Logical operators I have come across an answer and I can't seem to figure out why it's right.
So there are two int variables x and y and they represent 0x66 and 0x39 respectively.
The question asked what is the result value based on the expression.
x && y is apparently 0x01 (1)
x || y is 1
!x || !y is 0
x && ~y is 1

From what I was thinking, I thought as long as an argument was not zero it was considered true. So as long as x and y were some non-zero value then && operator would produce a 1, and of course as long as one of them is true the || operator would produce a 1.
So why is the third question 0? Is the ! different from the bitwise ~ operator? So originally x is 0101 0101 in binary since it's non zero it is true in the logical sense, but the ! of it would be false or would it do the one's complement of the number so its 1010 1010?

A: A boolean result is always true or false, and in C true is represented by 1 and false by 0.
The logical not operator ! gives a boolean result, i.e. 1 or 0. So if an expression is "true" (i.e. non-zero) then applying ! on that expression will make it false, i.e. 0.
In your example you have !x || !y. First !x is evaluated, and it evaluates to false, leading to !y being evaluated, and it also evaluates to false, so the while expression becomes false, i.e. 0.

A: Yes, ! is different from the bitwise not ~. It's a logical not. It yields either 0 or 1.

A: ~(0x01) will 0x10 and
!(0x01) will 0x00
'~' is a bitwise operator.
'!' is a logical operator.

A:
From what I was thinking, I thought as long as an argument was not
  zero it was considered true. So as long as x and y were some non-zero
  value then && operator would produce a 1, and of course as long as one
  of them is true the || operator would produce a 1.

This is all correct.
So why is the third question 0? Is the ! different from the bitwise ~ operator?

Yes. It is logical NOT. Just like the other logical operators && and ||, it only cares about if a variable has a non-zero value or not.
!0 will yield 1.
!non_zero will yield 0.

Note that all logical operators in C yield type int rather than bool, as an ugly, backwards-compatibility remain from the time before C had a boolean type. In C++ and other C-like languages, logical operators always yield type bool.
Similarly, true and false in C are actually just macros that expand to the integers 1 and 0. In other languages they are keywords and boolean constants.


text:
Q: Do a join and merge the foreign document in the same structure I have two collections that I am using to build a survey form:
Survey Collection has a document :
{
    "_id" : ObjectId("5bbcebfc2436f1d3e6275a5c"),
    "name" : "Some survey name",
    "score" : 12,
    "evidences" : [
        {
            "name" : "Evidence Method 1",
            "sections" : [
                {
                    "name" : "section1",
                    "questions" : [
                        "QID1",
                        "QID2"
                    ]
                },
                {
                    "name" : "section2",
                    "questions" : [
                        "QID3",
                        "QID4"
                    ]
                }
            ]
        },
        {
            "name" : "Evidence method 2",
            "sections" : [
                {
                    "name" : "section1",
                    "questions" : [
                        "QID5"
                    ]
                },
                {
                    "name" : "section2",
                    "questions" : [
                        "QID6"
                    ]
                }
            ]
        }
    ]
}

Question Collection has below documents :
/* 1 */
{
    "_id" : ObjectId("5bbcec1e2436f1d3e6275a6a"),
    "questionId" : "QID1",
    "answer" : "",
    "options" : [
        {
            "value" : "yes",
            "label" : "YES"
        },
        {
            "value" : "no",
            "label" : "NO"
        }
    ]
}

/* 2 */
{
    "_id" : ObjectId("5bbcec322436f1d3e6275a73"),
    "questionId" : "QID2",
    "answer" : "",
    "options" : [
        {
            "value" : "yes",
            "label" : "YES"
        },
        {
            "value" : "no",
            "label" : "NO"
        }
    ]
}

/* 3 */
{
    "_id" : ObjectId("5bbe12fd2436f1d3e62795e7"),
    "questionId" : "QID3",
    "answer" : "",
    "options" : [
        {
            "value" : "yes",
            "label" : "YES"
        },
        {
            "value" : "no",
            "label" : "NO"
        }
    ]
}

/* 4 */
{
    "_id" : ObjectId("5bbe130a2436f1d3e62795ef"),
    "questionId" : "QID4",
    "answer" : "",
    "options" : [
        {
            "value" : "yes",
            "label" : "YES"
        },
        {
            "value" : "no",
            "label" : "NO"
        }
    ]
}

/* 5 */
{
    "_id" : ObjectId("5bbe7fdc2436f1d3e627a108"),
    "questionId" : "QID5",
    "answer" : "",
    "options" : [
        {
            "value" : "yes",
            "label" : "YES"
        },
        {
            "value" : "no",
            "label" : "NO"
        }
    ]
}

/* 6 */
{
    "_id" : ObjectId("5bbe7fe92436f1d3e627a10e"),
    "questionId" : "QID6",
    "answer" : "",
    "options" : [
        {
            "value" : "yes",
            "label" : "YES"
        },
        {
            "value" : "no",
            "label" : "NO"
        }
    ]
}

I am using mongodb 4 and at present using the below query, I am able to join the 2 collections, but what it does is put the referenced doc in a separate field in the document, and I want it to be in the document structure itself.
db.createView (
"surveyquestions",
"survey",
    [
        {
                $lookup: {
                from: "questions",
                localField: "evidences.sections.questions",
                foreignField: "questionId",
                as: "question_docs"
            }
        }
    ]
)

Answer by Veeram, works except that it generates 2 different documents by evidences rather than one as below -
/* 1 */
{
    "_id" : {
        "_id" : {
            "_id" : ObjectId("5bbcebfc2436f1d3e6275a5c"),
            "evidences_name" : "Evidence Method 1"
        }
    },
    "name" : "Some survey name",
    "score" : 12,
    "evidences" : [
        {
            "sections" : [
                {
                    "name" : "section1",
                    "questions" : [
                        {
                            "_id" : ObjectId("5bbcec1e2436f1d3e6275a6a"),
                            "questionId" : "QID1",
                            "answer" : "",
                            "options" : [
                                {
                                    "value" : "yes",
                                    "label" : "YES"
                                },
                                {
                                    "value" : "no",
                                    "label" : "NO"
                                }
                            ]
                        },
                        {
                            "_id" : ObjectId("5bbcec322436f1d3e6275a73"),
                            "questionId" : "QID2",
                            "answer" : "",
                            "options" : [
                                {
                                    "value" : "yes",
                                    "label" : "YES"
                                },
                                {
                                    "value" : "no",
                                    "label" : "NO"
                                }
                            ]
                        }
                    ]
                },
                {
                    "name" : "section2",
                    "questions" : [
                        {
                            "_id" : ObjectId("5bbe12fd2436f1d3e62795e7"),
                            "questionId" : "QID3",
                            "answer" : "",
                            "options" : [
                                {
                                    "value" : "yes",
                                    "label" : "YES"
                                },
                                {
                                    "value" : "no",
                                    "label" : "NO"
                                }
                            ]
                        },
                        {
                            "_id" : ObjectId("5bbe130a2436f1d3e62795ef"),
                            "questionId" : "QID4",
                            "answer" : "",
                            "options" : [
                                {
                                    "value" : "yes",
                                    "label" : "YES"
                                },
                                {
                                    "value" : "no",
                                    "label" : "NO"
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

/* 2 */
{
    "_id" : {
        "_id" : {
            "_id" : ObjectId("5bbcebfc2436f1d3e6275a5c"),
            "evidences_name" : "Evidence method 2"
        }
    },
    "name" : "Some survey name",
    "score" : 12,
    "evidences" : [
        {
            "sections" : [
                {
                    "name" : "section1",
                    "questions" : [
                        {
                            "_id" : ObjectId("5bbe7fdc2436f1d3e627a108"),
                            "questionId" : "QID5",
                            "answer" : "",
                            "options" : [
                                {
                                    "value" : "yes",
                                    "label" : "YES"
                                },
                                {
                                    "value" : "no",
                                    "label" : "NO"
                                }
                            ]
                        }
                    ]
                },
                {
                    "name" : "section2",
                    "questions" : [
                        {
                            "_id" : ObjectId("5bbe7fe92436f1d3e627a10e"),
                            "questionId" : "QID6",
                            "answer" : "",
                            "options" : [
                                {
                                    "value" : "yes",
                                    "label" : "YES"
                                },
                                {
                                    "value" : "no",
                                    "label" : "NO"
                                }
                            ]
                        }
                    ]
                }
            ]
        }
    ]
}

A: You can try below aggregation.
db.createView(
    "surveyquestions",
    "survey",
    [
      {"$unwind":"$evidences"},
      {"$unwind":"$evidences.sections"},
      {"$lookup":{
        "from":"questions",
        "localField":"evidences.sections.questions",
        "foreignField":"questionId",
        "as":"evidences.sections.questions"
      }},
      {"$group":{
        "_id":{"_id":"$_id","evidences_name":"$evidences.name"},
        "name":{"$first":"$name"},
        "score":{"$first":"$score"},
        "sections":{"$push":"$evidences.sections"}
       }},
       {"$group":{
         "_id":"$_id._id",
         "name":{"$first":"$name"},
         "score":{"$first":"$score"},
         "evidences":{"$push":{"name":"$_id.evidences_name","sections":"$sections"}}
       }}
     ]
)


text:
Q: Regex to accept only 5 numbers and then a dash or a letter on typescript I am dealing with an issue with Regex.
I have a input which has maxLength 10.
I achieved till now to have the first given value can be digits for example 12345 but then it waits for a dash and after it you can write a letter or again a number maxLength=10 for example: 12345-a121 is allowed and it works with the currrent
But I want to be possible after the 5 digits to be allowed letters or dash because for the moment with this regex it is allowed only dash after 5 digits.
For example 12345a or 12345- to be allowed.
This is the actual regex what I am using.
Valid/Matches: 12345a235, 123a, 12345-aa1, 12345a, 12345-a.

Not Valid/Does not matches: -11, 111111, aaaa,

(?=^[^W_]{1,5}-[^W_]{1,8}$)^.{1,10}$|^[^W_]{1,5}$

I am debugging on the regex101.com but I am not finding a way for that to allow.
12345a for example
This is the condition to check if it matches or not.
if (!this.value.toString().match('^\d{1,5}(?!\d+)[-\p{L}\d]+$') && this.value.toString()) {
      return ValidationInfo.errorCode("You need to do something");

Thank you for the help

A: Edit since the patterns of the first approach can be simplified and also were missing the limitations of the ending sequence's length.

*

*for matching only with Letter unicode property escapes

*

*/^\d{1,5}[-\p{L}][-\p{L}\d]{0,9}$/u

*matching and capturing with Letter unicode property escapes

*

*/^(?<digitsOnly>\p{N}{1,5})(?<miscellaneous>[-\p{L}][-\p{L}\p{N}]{0,9})$/u
Example code ...

const multilineSample = `12345a235
123a
12345-aa1
12345a
12345-a

12-a235dkfsf
12-a235dkfsfs

123a-dssava-y
123a-dssava-1a

12345-aa1--asd-
12345-aa1--asd-s

-11
111111
aaaa`;

// see ... [https://regex101.com/r/zPkcwv/3]
const regXJustMatch = /^\d{1,5}[-\p{L}][-\p{L}\d]{0,9}$/gmu;

// see ... [https://regex101.com/r/zPkcwv/4]
const regXNamedGroups =
  /^(?<digitsOnly>\p{N}{1,5})(?<miscellaneous>[-\p{L}][-\p{L}\p{N}]{0,9})$/gmu;

console.log(
  'matches only ...',
  multilineSample.match(regXJustMatch)
);
console.log(
  'matches and captures ...', [
    ...multilineSample.matchAll(regXNamedGroups)
  ]
  .map(({ 0: match, groups }) => ({ match, ...groups }))
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

1st approach

*

*straightforward and plain ... /^\d{1,5}(?!\d+)[-\p{L}\d]+$/u

*with named capture groups ... /^(?<digitsOnly>\p{N}{1,5}(?!\p{N}+))(?<miscellaneous>[-\p{L}\p{N}]+)$/u
For both variants it is obvious to start with ...

*

*a digit sequence of at least 1 and up to 5 digits ...

*

*traditional ... ^\d{1,5}

*unicode property escapes ... ^\p{N}{1,5}
It's also clear, one wants to end with a character sequence of any of dash and/or word. Due to having to exclude _ one can not just use the \w escape for letters and digits since \w covers/includes _ as well. But one could use unicode property escapes, thus ...

*

*a regex covering the end of a line with a valid character class is ...

*

*already mixed ... [-\p{L}\d]+$

*mostly unicode escapes ... [-\p{L}\p{N}]+)$
A combined regex like ... /^\d{1,5}[-\p{L}\d]+$/u ... almost covers the requirements but fails for 111111 which of cause gets matched even though it shouldn't according to the requirements.
A negative lookahead ... (?!\d+) respectively (?!\p{N}+) ... which follows the starting digit sequence does prevent any other (terminating) digit-only sequence, thus 123456 does not get matched anymore.
Example code ...

const multilineSample = `12345a235
123a
12345-aa1
12345a
12345-a

-11
111111
aaaa`;

// see ... [https://regex101.com/r/zPkcwv/1]
const regXJustMatch = /^\d{1,5}(?!\d+)[-\p{L}\d]+$/gmu;

// see ... [https://regex101.com/r/zPkcwv/2]
const regXNamedGroups =
  /^(?<digitsOnly>\p{N}{1,5}(?!\p{N}+))(?<miscellaneous>[-\p{L}\p{N}]+)$/gmu;

console.log(
  'matches only ...',
  multilineSample.match(regXJustMatch)
);
console.log(
  'matches and captures ...', [
    ...multilineSample.matchAll(regXNamedGroups)
  ]
  .map(({ 0: match, groups }) => ({ match, ...groups }))
);
.as-console-wrapper { min-height: 100%!important; top: 0; }


text:
Q: format numbers to 4 digits in Azure Pipline I try to format 4 digits in Azure pipeline (YAML) but its not working, someone help?
i have this variable >> serialNumber: 2
I used the following yaml syntax:
formatnumber: $[format('{0:D4}', variables.serialNumber)]

formatnumber: $[format('{0:0000}', variables.serialNumber)]

formatnumber: $[format('{0:####}', variables.serialNumber)]

i want to convert the number 2 to 0002 with format but i get the following error:

An error occurred while loading the YAML build pipeline. The format specifiers 'D4' are not valid for objects of type 'String'

A: The above formater doesnot work is because the type of the value returned by variables.serialNumber is string not int type.
There is a workaround to achieve this. You can add a powershell task to format the number. You can check below example.
trigger:
- master
variables:
  number: 2
pool:
  vmImage: 'ubuntu-latest'
steps:
- powershell: |
    $number = $(number)
    $format = "{0:0000}" -f $number
    echo "##vso[task.setvariable variable=formatnumber]$format"

- powershell: echo "$(formatnumber)"

Above script in powershell task formats the variable number, and set the formatted number to variable 'formatnumber'. Then the following task can refer to the formatted number by $(formatnumber)


text:
Q: Converting time to UTC using java 8 I have some APIs in Java which accept times as strings.
The UI sends plain string like "10:00:00". I am creating a LocalTime out of that and saving in the db (MySQL).
Later in another API I use a LocalDate object and the above time with Zone UTC to create a ZonedDateTime object that is saved to the db. My problem is that the time is not getting converted to UTC.
ZonedDateTime.of(LocalDate.now(ZoneId.of("UTC")),LocalTime.now(ZoneId.of("UTC")), ZoneId.of("UTC"));
ZonedDateTime.of(LocalDate.now(ZoneId.of("UTC")),dto.getStart(), ZoneId.of("UTC"));

Both of these are different though I am sending for eg 07:00:00 which is my time in India. Please guide me as to how I should convert the time alone to UTC.
EDIT:: I have set jvm Duser.Timezone to UTC.When I do this:
ZonedDateTime.of(LocalDate.now(ZoneId.of("UTC")),dto.getStart(), ZoneId.of("UTC")).getOffset().getTotalSeconds();

It gives 0 as seconds
EDIT::
ZoneId z = ZoneId.of("Asia/Calcutta");
ZoneId z1 = ZoneId.of("UTC");
TimeZone.getTimeZone(z).getRawOffset();

Tried this and it gives the diff in ms. I will try using this provided the UI sends the actual local zone. Will update..

A: If the input corresponds to your local time, you can create a ZonedDateTime to get the current date in India timezone, set the time and then convert it to UTC:
LocalTime time = LocalTime.parse("10:00:00"); // 10 AM

ZonedDateTime utc = ZonedDateTime
    .now(ZoneId.of("Asia/Calcutta")) // current date/time in India
    .with(time) // set time to 10 AM
    .withZoneSameInstant(ZoneOffset.UTC); // convert to UTC

The value of variable utc will be 2018-01-29T04:30Z (running the code today, January 29th). The time in UTC is 4:30 AM, which is equivalent to 10 AM in India.
I believe that MySQL can't save a ZonedDateTime, so you can first convert it to an Instant by calling utc.toInstant(). Or if the driver you use is an older version and it works only with java.util.Date, you can convert it using Date.from(utc.toInstant()).
Also note that I used the constant ZoneOffset.UTC, which is equivalent to (but better than, IMO) calling ZoneId.of("UTC").

A: For now We have decided to allow the UI to change the time to whatever is its timezone. JVM timezone for the server is set to UTC...

A: I would advise against storing a ZonedDateTime in a MySQL database. MySQL timestamps don't store the timezone information so you can't guarantee you'll get back the same time that you save.
Instead I would store a LocalDateTime and standardise on UTC for internal times and then format with a timezone when you need to display etc. To get the current time in UTC you can do something like this.
LocalDateTime now = LocalDateTime.now(Clock.systemUTC());

To build a UTC timestamp for today and a provided time you could do something like this.
LocalTime time = getTime();
LocalDateTime = LocalDateTime.of(LocalDate.now(Clock.systemUTC()), time);

To build a timestamp using the date for the current timezone, a provided time and then convert to UTC for saving to the database.
ZoneId timezone = ZoneId.of("Asia/Calcutta");
LocalTime time = getTime();
ZonedDateTime zdt = ZonedDateTime.of(LocalDate.now(timezone), time, timezone);
LocalDateTime utcDateTime = LocalDateTime.ofInstant(zdt.toInstant(), ZoneOffset.UTC);


text:
Q: Creating date_trunc index via Hibernate 4.3.5 / JPA 2.1 I want to create index like this below:
CREATE INDEX idx_foo_req_date
ON foo
USING btree
(date_trunc('day'::text, req_date));

How/Can I create it via java hibernate annotations?
I have already read about @Index annotation to use it like:
@Table(name = "foo", indexes = { @Index(name = "idx_foo_req_date", columnList = "req_date") })

but it will create smth like this:
CREATE INDEX idx_foo_req_date
ON foo
USING btree
(req_date);

UPDATE:
I thought maybe it is pretty flexible and simple and i have tried:
@Table(name = "foo", indexes = { @Index(name = "idx_foo_req_date", columnList = "date_trunc('day'::text, req_date)") })

However org.hibernate.AnnotationException has been thrown, complaining about columns in columnList.

A: Hibernate uses the JPA @Index annotation which doesn't support function-based indexes.
You'd better use Flyway and keep your schema migration in incremental scripts.


text:
Q: Syntax of process.nextTick - arguments passed I was learning about process.nextTick and playing around with it. Got a small doubt regarding that itself. The first argument of process.nextTick is a callback function, what is the second or third argument?
Consider the following code:
This is printing error on console but not printing "First line" console.log value -
function promise(value, cb) {
    if (typeof value !== 'string') {
        return cb(new TypeError('Value should be string'));
    }
    cb(null, Promise.resolve('Hello'));
}

promise(1, (err, success) => {
    if (err) throw err;
    success.then((res) => console.log(res));
});

console.log('First line');

I tried to correct it using the following code using process.nextTick and it prints "First line" console on the terminal and then the error, which is fine, understandable but I had to pass the callback function and the error to process.nextTick. Is that how it works? Can someone maybe give a better explanation about that? I'm talking about the syntax and number of arguments of process.nextTick here, to be specific -
function promise(value, cb) {
    if (typeof value !== 'string') {
        return process.nextTick(cb,
            new TypeError('Value should be string'));
    }
    cb(null, Promise.resolve('Hello'));
}

promise(1, (err, success) => {
    if (err) throw err;
    success.then((res) => console.log(res));
});

console.log('First line');

A: Docs is pretty clear:

process.nextTick(callback[, ...args])

*

*callback <Function>

*...args <any> Additional arguments to pass when invoking the callback

That's how the method works, it takes a callback and optional args to pass to the callback when invoked.
https://nodejs.org/api/process.html#processnexttickcallback-args


text:
Q: finite dimensional marginal distribution I am trying to understand the following theorem:
"The distribution of a stochastic process is uniquely determined by the family of all its finite-dimensional marginal distribution (and vice versa)"
I am not very familiar with this definition of fdmd which is given as follows:
"For each set of indices $J=\{t_1,...,t_n\}\subset [0,\infty)$ with $t_1<...<t_n$, we can view
$$\mu^{(J)}:=\mathbb{P}\circ(X_{t_1},...,X_{t_n})^{-1}$$ as the distribution of the vector $X_{(J)}:=(X_{t_1},...,X_{t_n})$ under $\mathbb{P}$, as a probability measure on $\mathbb{R}^{\mid J\mid}=\mathbb{R}^n$. We call this the finite-dimensional marginal distribution (fdmd) of $X$ for the coordinates in $J$".
So if I am right then the theorem would consider all possible vectors $X$ (constructed choosing all possible finite set $J$) with all possible number of components and states that the distribution of a stochastic process is so determined (uniquely) by the distributions of all these possible vector. I am a bit confused since I usually from the distribution of single random variables we can't recover the one of the vector. Is this theorem stating when this actually happens? Am I right?
Thanks


text:
Q: When reviewing answers, add the entirety of the question in the reading pane? Sometimes it is difficult to tell whether or not an answer (especially for first post users) has already been addressed by previous answers. An example here:

Here I am reviewing a user's first post.   It seems to simply answer the question asked. However, when navigating to that very same question...

As you can see, the currently accepted answer to that question has already listed what this new answer has, so this post brings nothing to the table. That said, for a person who has just been granted privileges to use the review queue, they may not be as able to understand the context within the question and its answers and could have trouble determining if this was a legitimate answer.
Could it be possible to at least add some context from the question to the review reading pane?


text:
Q: Eclipse Gradle multiprojects I've just been through the ringer trying to get this to work so I thought i would share my experience.
The problem (so I can answer it QA style):
I have a flat project structure where the sub-projects are siblings of the root project:
rootProject
childProject1
childProject2
childProject3

In my rootProject:settings.gradle I used an include:
include '../childProject1', '../childProject2', '../childProject3'

This worked for the simple builds (no real gradle configuration had yet been performed).
Then upon Gradle Import > Build Model the import dialog showed:
[] rootProject

And there were no childProjects.
I did a bit of reading and had the Aha! moment when i re-read the doco and saw I actually want includeFlat.  So I changed it to:
includeFlat 'childProject1', 'childProject2', 'childProject3'

However it didn't work.  Grumble grumble grumble.
What could I do to fix this?

A: After a bit of playing around I had to do:

*

*Delete these files from the project's:

*

*.project

*.settings

*.gradle

*Sometimes that wasn't enough and I had to shut down Eclipse / STS and delete the contents of the workspace directory
Then it worked and upon build Model of the RootProject I would see in the import dialog:
[] rootProject
    [] childProject1
    [] childProject2
    [] childProject3

Problem solved.
I've never encountered a situation like this where I had to do lots of eclipse project metadata cleanup to get functionality functioning.


text:
Q: How to export android Log? I need to export the log that my application create, there is a way to do that?
or at least there is a way to get all the log written by my application?
edit: i need to do that directly on my application.
Edit: solved using this guide
http://www.helloandroid.com/tutorials/reading-logs-programatically

A: If you use are using a linux machine you can run something like this
adb logcat org.myorg.myapp > LOG
or
adb logcat | grep org.myorg > LOG


text:
Q: mysqladmin won't accept password I have a new MBP with Yosemite. I have installed the latest version of MySQL (5.6.21 via the pkg file) and have successfully set up its password and see it through Sequel Pro. However, I cannot login to mysqladmin. Normally, like with Ubuntu, I can do:
 mysqladmin -u root -p

But terminal dumps me to the helpful help file. Of course, the rules haven't changed. The help file confirms that if I leave off the password after the -p argument that the TTY will take over but it does not.
 mysqladmin -u root --password

yields the same help message.
 mysqladmin -u root -password 'password'

asks for a password expected BUT when I pass it then yields unknown command 'password'.
I did do the /usr/local/bin/mysql_secure_installation script but didn't change any values. If my root password has changed why would I still be able to connect via sequel pro and other PHP connections?
I'm sure it's something I'm overlooking but appreciate is there's something I've not found in my Google searches, thanx, sam

A: The program mysqladmin is not an interactive client. It is a client-based utility. mysqladmin allows you run connect to mysqld, run a single command from a specific set of commands, and then, disconnect.
EXAMPLE #1
Some commands that can be done in the mysql client can be done in mysqladmin.
mysqladmin -uroot -ppassword flush-hosts
mysqladmin -uroot -ppassword processlist

EXAMPLE #2
Some commands that cannot be done in the mysql client can be done in mysqladmin.
For instance, an orderly shutdown of mysqld can be done like this:
mysqladmin -uroot -ppassword shutdown

Of course, service mysql stop will work as well. Unfortunately, service mysql stop does not work when the socket file is gone. This can sometimes happen when a person issues service mysql start with mysqld already running. That deletes the socket file. Running mysqladmin -uroot -ppassword shutdown requires the socket file because you are connecting as root@localhost. If you have the user root@127.0.0.1 defined, you can still issue an orderly shutdown by connecting via TCP/IP with mysqladmin like this
mysqladmin -uroot -ppassword -h127.0.0.1 --protocol=tcp shutdown

I have many posts about this such as these

*

*Mar 06, 2013 : How to properly kill MySQL?

*May 08, 2012 : How to properly stop MySQL server on Mac OS X?
With regard to your original quesiton, if you want to test the password, you should be using mysql, not mysqladmin. You should do this
mysql -uroot -p

As an alternative, if you still want to use mysqladmin, do this
mysqladmin -uroot -ppassword ping

Give it a Try !!!


text:
Q: Encoding issues with CLD After some issues getting Chrome Compact Language Detection library installed on Windows, I installed CLD from this easy_install.
I can now use CLD, but getting some encoding issues.
Background
Pulling Tweets into a python script, and after stripping out the hashtags and links, passing them to CLD to detect the language.
Following is a simplified version of my code:
s = "I am a tweet from Twitter"
clean_s = s.encode('utf-8')
lan = cld.detect(clean_s, pickSummaryLanguage=True, removeWeakMatches=True)

Problem
4 out of 5 times, this works as expected (get returned a response about what language it is).
However, I keep getting this error popping up:

UnicodeEncodeError: 'charmap' codec can't encode character u'\u2019'
  in position 15: character maps to undefined

I did read that:

"You must provide CLD clean (interchange-valid) UTF-8, so any encoding
  issues must be sorted out before-hand."

However, I thought I had this covered with my statement to encode to UTF8?
I assume that I need to ensure that I pass a string to CLD that preserves fonts in languages such as arabic, asian, etc.
This is my first python project, so likely this is a rookie mistake.  Can anyone point out my mistake and how to rectify?
Let me know in comments if I need to gather more info, and I will edit my Q to provide more info.
EDIT
If it helps, here is my rookie code (cut down to replicate issue).
I am running Python 2.7 32bit.
Running this code, after awhile, I get this error.
Let me know if I have not correctly implemented the error reporting.
Raw: Traceback (most recent call last):
  File "LanguageTesting.py", line 71, in <module>
    parse_tweet(tweet)
  File "LanguageTesting.py", line 43, in parse_tweet
    print "Raw:", raw
  File "C:\Python27\ArcGIS10.1\lib\encodings\cp850.py", line 12, in encode
    return codecs.charmap_encode(input,errors,encoding_map)
UnicodeEncodeError: 'charmap' codec can't encode characters in position 29-32: character maps to <undefined>

A: It looks like you are failing on the print statement right?  This means Python cannot encode the unicode string into what it thinks the console's stdout encoding is ("print sys.getdefaultencoding()").
If python is wrong about what your terminal expects, you can set the env var ("export PYTHONIOENCODING=UTF-8") and it will encode your printed strings to utf-8.  Alternatively, before printing, you can encode to whatever charset your terminal expects (and will likely have to ignore/replace errors to avoid exceptions like the one you hit)...


text:
Q: node-red-node-mysql full disk I have a project with node-red and I am using node-red-node-mysql to manipulate data inside my Mysql Workbench.
I do the next actions: insert data, update data, query for some rows to display them on the screen.
When I start my project, the PC's disk is almost instantly at 99% by "mysql.exe"
Below you can see 2 of my flows that use the connection to my database.

If I stop my server, my Disk usage goes to 1%
I refer to Disk like in the image below

Could somebody help me out here with a suggestion?
Could it be something from the configuration of mysql?
P.S: I am jut a n00b trying to understand node-red and use it :)

A: I investigated a bit the pc and decided to use another station.
After moving everything to another server, it works just fine. I think that the problem came after a windows update — my HDD runs slower, much slower.


text:
Q: Open Visual Studio (Not Visual Studio Code) from the ubuntu bash terminal on windows I was wondering if it is possible to open Visual Studio (Not Visual Studio Code) from the ubuntu bash terminal on windows.
Opening Visual Studio Code just works fine but I couldn't find a way on how I could actually open Visual Studio from the command line.
Thank you in advance!

A: It is possible to refer to anything in the Windows file system from inside WSL.  However, understand that, since Visual Studio is a Windows exclusive application, it will run in the context of your host Windows OS, not the Ubuntu guest OS.  By contrast, Visual Studio Code is a Linux-native application; so it can run in either context.
Try this:
'/mnt/c/Windows/System32/cmd.exe /c "/mnt/c/Program Files (x86)/Microsoft Visual Studio/2019/Community/Common7/IDE/devenv.exe"'

If this works, you can save the command as an alias in your .bashrc
References:

*

*https://learn.microsoft.com/en-us/windows/wsl/interop

*https://medium.com/@heinrich10/launching-windows-application-on-windows-subsystem-for-linux-wsl-60cc2c165029


text:
Q: Why won't this paragraph line up correctly between the quotes? I'm having trouble keeping the paragraph square between the quote marks. In firefox the last line between the quotes sticks out too far to the left. The image is what I would like it to look like.

http://jsbin.com/elohej  <-This shows the problem exactly in firefox.

<meta charset="UTF-8" />

“Frank is the best. I take my Z to Hill’s for all my maintenance and car needs, and I’ll never take it to the dealership again. Better service. Better prices. ”

 Test Paragraph Test ParagraphTest ParagraphTest ParagraphTest ParagraphTest ParagraphTest ParagraphTest ParagraphTest ParagraphTest ParagraphTest ParagraphTest ParagraphTest ParagraphTest ParagraphTest Paragraph

A: You could achieve this by absolutely positionning your opening quote instead of floating it, and adding padding-left on your p tag.
blockquote p {
     padding-left: 80px;
     position: relative;
}

.bqstart {
     font-size: 700%;
     color: #605f5f;
     height:25px;
     position: absolute;
     left: 0;
     top: 0;
 }


text:
Q: How to remove item from listbox and have changes reflected in entity I'm trying to bind an entity to a listbox, and when I remove something from the entity, I want it to be reflected in the listbox.
Here is a code snippet:
SportsClubEntities spe = new SportsClubEntities

BindingSource bs = new BindingSource();

var stm =
    from xyz in spe.SomeEntity where xyz.prop == 66
    select new { Name = xyz.name, rec = xyz }

bs.DataSource = stm.ToList();

ListBox.DataSource = bs;
ListBox.DisplayMember = "Name";
ListBox.ValueMember = "rec";

I have a button, which when I click, I want it to remove the selected item in the listbox, but more than that, I want it to remove the item from the underlying entity.  ie: when xyz is selected and removed from the listbox, I want xyz removed from spe.
If I do a bs.Remove(item) that removes the item from the listbox (when I then call bs.ResetBindings(), but it doesn't update the entity (spe.SomeEntity).  Initially, I thought it would, but then I realised that the LINQ is a query, returning some results.
When I click the remove button, I can do spe.SomeEntity.Remove(item), but then the listbox doesn't get updated.
Is there a way I can perform the remove on just one of the them, and have both updated?
Am I doing this completely wrong?  Is there some sort of 'standard' way to do this sort of thing?
I can't bind spe.SomeEntity.ToList() to the listbox directly, because I need a subset of the records in the entity.
Appreciate any help, I'm still learning.

A: Here's how you can do it:
    private void Form1_Load(object sender, EventArgs e)
    {
        list1 = new List<Person>();

        using (SportsClubEntities spe = new SportsClubEntities())
        {
            list1 = (from p in spe.People
                      select p).ToList();
        }

        bs = new BindingSource();
        bs.DataSource = list1;

        listBox1.DataSource = bs;
        listBox1.DisplayMember = "FirstName";
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Person p1 = (Person)listBox1.SelectedItem;
        list1.Remove((Person)listBox1.SelectedItem);
        bs.ResetBindings(false);

        using (SportsClubEntities spe = new SportsClubEntities())
        {
            Person p2 = (from p in spe.People
                     where p.BusinessEntityID == p1.BusinessEntityID
                     select p).FirstOrDefault();

            spe.People.Remove(p2);
            spe.SaveChanges();
        }
    }

Removing a guy named "Jossef":


text:
Q: SQL server stored proc "Procedure or function expects parameter, which was not supplied." I've recently changed a couple of functions recently while debugging a cte query (have gotten help here). I just changed a couple of functions.. this got my query to work.. but now when my C# client code calls those functions through stored procs for my program logic, I get the error "Procedure or function 'DateTimeOfNextAvailableDataRun' expects parameter '@NextDateTime', which was not supplied.
" Maybe multiple values are coming back?
Here's the function in its current form:
ALTER FUNCTION dbo.NextAvailableDataDownloadDateTime()
    RETURNS date
BEGIN
    RETURN (SELECT DATEADD(hour, 18, MIN(TradingDate)) AS TrDate
    FROM tblTradingDays
    WHERE (DATEADD(hour, 18, TradingDate) > dbo.LatestDataDownloadDate()))
END

And the stored proc that invokes it:
ALTER PROC DateTimeOfNextAvailableDataRun
    @NextDateTime DateTime2 OUTPUT
AS
    SELECT @NextDateTime = dbo.NextAvailableDataDownloadDateTime()

And lastly my client code, which did run before the change:
public DateTime DateTimeOfNxtAvailableDataRun()
            {
                DateTime dateTimeOfNxtAvailableDataRun;

                using (SqlCommand cmd = new SqlCommand("DateTimeOfNextAvailableDataRun", this.sqlConnection))
                {
                    cmd.CommandType = System.Data.CommandType.StoredProcedure;
                    cmd.ExecuteNonQuery();
                    dateTimeOfNxtAvailableDataRun = (DateTime)cmd.ExecuteScalar();
                }

                return dateTimeOfNxtAvailableDataRun;
            }

Any takers? Again, the functions work within my sql server query (see recent posts by me) but now the calling code disagrees..

A: You should modify the body of the using statement and add an output parameter before executing the command.
var outputParameter = new SqlParameter {
    ParameterName = "@NextDateTime",
    Direction = ParameterDirection.Output
};
cmd.Parameters.Add(outputParameters);
cmd.ExecuteNonQuery();
return (DateTime)outputParameter.Value;


text:
Q: Can't open attachment in appropriate application from Thunderbird When I try to open a PDF file from an attachment in an email in Thunderbird, I only get a few applications and none of them are appropriate to open PDF files:

When I save the file to my HD, it opens by default with the correct application (Document Viewer) and I can also choose a lot of other applications:

Edit: When I go to Preferences -> Attachments -> Incoming I don't see any filetypes that I can set any action for:

Why can't I open this file with the correct application from Thunderbird? How to fix this?

A: Did you install thunderbird via snap? I had the same issue.
After deleting the snap instance and reinstalling via
apt-get install thunderbird

it worked well.
(Be aware: deleting the snap instance will automatically delete all the data, so backup your emails before doing that!)


text:
Q: Solr fails to index text field When trying to index documents with text_general fields I get the following error:
Exception writing document id 93cf6aeb-54b0-471a-9325-5b8e95801131 to the index; possible analysis error: cannot change field "content" from index options=DOCS to inconsistent index options=DOCS_AND_FREQS_AND_POSITIONS

The document I attempted to index looks as follows:
{
    "filename": "FooBar.pdf",
    "content": "my test"
}

The schema definition for this field is:
  <field name="content" type="text_general" uninvertible="true" indexed="true" required="true" stored="true"/>

With the field type defined as:
<fieldType name="text_general" class="solr.TextField" positionIncrementGap="100" multiValued="true">
    <analyzer type="index">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true"/>
      <filter class="solr.LowerCaseFilterFactory"/>
    </analyzer>
    <analyzer type="query">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StopFilterFactory" words="stopwords.txt" ignoreCase="true"/>
      <filter class="solr.SynonymGraphFilterFactory" expand="true" ignoreCase="true" synonyms="synonyms.txt"/>
      <filter class="solr.LowerCaseFilterFactory"/>
    </analyzer>
</fieldType>

How do I succcessfully index a document with a text_general field?

A: This is caused by there already being content indexed for the field that was indexed with a different field type. Delete the index and re-index your content.


text:
Q: Is debugging a waste of time? I work on a lot of projects for fun, so I have the freedom to choose when I want to finish the project and am not constrained by deadlines.
Therefore, if I wanted to, I could follow this philosophy:

Whenever you hit a bug, don't debug. Instead, spend time learning about topics related to the bug from textbooks and work on other projects until one day you can come back to the bug and solve it instantly thanks to your piled up knowledge.

However, maybe the 'philosophy' is bad because

*

*debugging is a skill that should be practiced so that when I need to finish projects by a deadline I will have acquired the skills necessary to debug quickly.

*staring at lines of code and struggling to understand them when debugging makes you a much better programmer than writing new lines of code does.

*debugging isn't a waste of time for some reason which I hope you'll tell me.

A: I would approach the topic from the other side: how to avoid creating bugs in the first place? Quality has to be built in, not tacked on afterwards.
Anyway, I feel there's a very simple reason not to allow bugs to fester if you find them: they tend to get worse when left alone.
It even happens quite frequently that the behaviour of bugs is something future development relies on for other functionality. Then when you do get around fixing that bug, you wind up breaking other stuff.

A: Depends what you mean by debugging. In your approach debugging looks like just trying around until the bug is fixed.
From my point of view debugging is a little broader, i.e. reproducing the bug in an isolated scenario, evaluating the cause of the bug, fixing the bug, testing in a common scenario, etc. Iterations are possible ;)
To answer the question, debugging (like defined in the previous paragraph) is not a waste of time.

A: In layman's words:
I beats me how on earth can someone separate the process of programming from the proccess of debugging.
If you write perfect programs the very first time you try, then you are Neo, the chosen one from Matrix trilogy, otherwise writing a program is a process of writing, testing and debugging.
Then, no, debugging is not a waste of time, it's a neccessity arised from the fact that you can't simply write a perfect program at the first try.

A:
Whenever you hit a bug, don't debug. Instead, spend time learning
  about topics related to the bug from textbooks and work on other
  projects until one day you can come back to the bug and solve it
  instantly thanks to your piled up knowledge.

You make the false assumption that people "write" bugs because of lack of knowledge. A lot of bugs are mistakes, and making false assumptions. And actually the debugging in itself is a learning experience which will develop you as programmer.
Yes, debugging is usefull because of:
3: you would never deliver a working product if you didn't.

A: Your customers will greatly appreciate it if they report a critical bug and you take the approach of just letting it sit there until suddenly a light goes on in your head and you come to the realisation just what exactly caused it several months later without ever having put any effort into actually analysing the problem...
Debugging isn't just mindlessly reading source code and hoping to spot the error. If the error were that obvious it shouldn't have ever made it into production in the first place.

A: Debugging and researching a bug are not very interchangeable.
Debugging is going through your code(using a debugger, running it while printing internal stuff, reviewing the code etc.) trying to find the part of your code that doesn't do what you meant it to do.
Researching is needed when you find a problem in a "black box" - a part of the code you can't probe, either because it's part of the language, or you don't have access to it's source code, or you simply lack the experience/knowledge/time to probe the source code by yourself. When you give that black box input you think is correct and it gives you incorrect output or side-effects, that means that either you don't use it properly or there is a bug in the component itself. At any rate - you need to research it in order to solve it.
Debugging can not be replaced with researching. Problems that need debugging are usually problems specific to your own code. If your function returns 2 instead of 3, you can't google the bug because even if you find someone else whose function return 2 instead of 3 it'll probably be because of different reasons. Even if your bug falls into a broader pattern that you can research, you'll often need to do some debugging first to find out which pattern it is, and by doing that you have probably already solved the bug.
Researching can not be replaced with debugging. If you find such a black box you're not going to just throw input at it randomly until you happen to make it work. Since the problem is with something external you can actually look it up. If a function from external library returns 2 instead of 3, and you find someone else on the internet who has the same problem, it's probably from the same reason, since you both use the same function.
Debugging and researching a bug are not very interchangeable. Which approach you should take(sometimes you'll need both!) depends on the bug at hand, not on some general rule decided beforehand.

A: All good answers here.
I would only add that bugs fall into two categories.
When you write a program, you have in mind, if not on paper, a notion of what you want it to do - a set of requirements.
When a program fails to meet its requirements, let's call that a type 1 bug.
Example: printing the wrong output.
When a program fails to meet any possible requirement, let's call that a type 2 bug.
Example: a crash or hang.
Either way, it's as important to know how to take bugs out as it is to put them in.

A: For me a bug is when something doesn't work in a way I expect it to. Which usually means I don't understand how something work and in most cases I've seen it means that it is just a sign of something more serious going bad somewhere deeper. Which means I have to find why I see what I see. In some cases the result is "I don't even know how this worked before". Which is good - I just found a serious error by noticing that something is out of place.
So no, it is not a waste of time.

A: Bugs generally happen because of a wrong assumption of how something works. Most of the time, the wrong assumption is about how your own code works. The algorithm you came up with for calculating something doesn't quite do what you think, especially in edge cases. You make an assumption about the input that doesn't actually hold. And so on.
In a few cases, the wrong assumption will be about something external. You misunderstood how initialization order during construction works (or maybe you got confused because it works differently in the language you're used to - just compare initialization of objects in Java, C# and C++). You thought the modulo operator never returns negative results.
In the latter case, learning additional things may help you, although stumbling across the right bit of knowledge is a big stroke of luck.
But most of the time, the additional knowledge you need is what precisely the code you wrote is doing. And learning that means studying the code, possibly watching it execute, and that's exactly what debugging is.

A:
Whenever you hit a bug, don't debug.

I'm not the original author so don't know for sure, but I don't believe they are arguing that you should never debug. I believe they are arguing against the tendency to immediately start debugging, as soon as you find a bug. I am guilty of this, sometimes, and it can be very tempting because sometimes it is a quick way to find the problem.
But debugging cannot replace a good understanding the code, and indeed, having that good understanding can help you debug the issue more quickly.
The skill, which only comes with experience of trying both, is understanding how much time to spend understanding the code, without a debugger, and when to just leap in with the debugger and "see what is actually going on"

A: Its an interesting concept once you get past the emotional response many of these answers give.
Imagine the question said "never debug, instead write a test to reproduce the issue and fix the offending code from that". That's more ofd my understanding where the questioner was coming from.
Its a nice idea, but in the practical world, flawed because bugs don't often come from poor code, but poor data (yea, ok, it still counts as poor code because it doesn't handle the data given). Its the input that matters though. Code that works because it received expected data during testing is still working code, but when you deliver it the sheer complexity of a system says that you'll get very unexpected data - especially in circumstances where the data may be correct, but some other data elsewhere may cause a conflict. this is why you debug, you try to figure out why your 'working' code fails to work as expected.
A valid alternative is much logging, but if you put enough in, you usually end up narrowing the cause down which leaves you with a reduced debugging task - that still requires some debugging.


text:
Q: Web API Json Response I am developing Web API for my client. They have suggestion that all response should be a common JSON structure.
{ Data:"", Status:true, Message:"" }

If error means
{ Error:"", Status:false, Message:"" }

Which is the best method to create a common JSON structure as returns.
Now I created a class having these properties. And created 2 classes from IHttpActionResult,Error.cs and Success.cs, From that the response is created and returned from the controller.
The thing is in my controller,
public IHttpActionResult GetNewsAndAnnouncements()
    {
        var data = newsAndAnnouncementsDataServices.NewsAndAnnouncements();
        if (data != null && data.Count() > 0)
        {
            return new Success(Request, "News and Announcements Retrieved Successfully", data);
        }
        return new Error(Request, "No News and Announcements Found");
    }

Error.cs
public class Error : IHttpActionResult
{
    private readonly string _message;
    private readonly HttpRequestMessage _request;
    private IErrorResponseModel errorResponse;

    public Error(HttpRequestMessage request, string message)
    {
        _message = message;
        _request = request;
        errorResponse = new ErrorResponseModel();
    }
    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        errorResponse.Message = _message;
        errorResponse.Status = false;
        errorResponse.Error = _message;
        var response = new HttpResponseMessage(HttpStatusCode.BadRequest)
        {
            Content = new ObjectContent<object>(errorResponse, new JsonMediaTypeFormatter()),
            RequestMessage = _request
        };
        return Task.FromResult(response);
    }
}

Success.cs
public class Success : IHttpActionResult
{
    private readonly string _message;
    private readonly object _data;
    private readonly HttpRequestMessage _request;
    private IDataResponseModel dataResponse = new DataResponseModel();
    public Success(HttpRequestMessage request, string message, object data)
    {
        _message = message;
        _request = request;
        _data = data;
    }
    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        dataResponse.Message = _message;
        dataResponse.Status = true;
        dataResponse.Data = _data;
        var response = new HttpResponseMessage(HttpStatusCode.OK)
        {
            Content = new ObjectContent<object>(dataResponse, new JsonMediaTypeFormatter()),
            RequestMessage = _request
        };
        return Task.FromResult(response);
    }
}

DataResponseModel.cs
public class DataResponseModel : Mobility.Common.IDataResponseModel
{
    public object Data { get; set; }
    public string Message { get; set; }
    public bool Status { get; set; }
}

ErrorResponseModel.cs
public class ErrorResponseModel : Mobility.Common.IErrorResponseModel
{
    public object Error { get; set; }
    public string Message { get; set; }
    public bool Status { get; set; }
}

Is this a right method. I need suggestion. Is there any other way to achieve this. I heard about delegating handler something. But I don't have much idea on these.
Please help me.

A: Another solution to this problem is to hook into the ASP.NET pipeline using custom handlers to build a common response object.
For instance:
[DataContract]
public class ApiResponse
{
  [DataMember]
  public string Version { get { return "1.2.3"; } }

  [DataMember]
  public int StatusCode { get; set; }

  [DataMember(EmitDefaultValue = false)]
  public string ErrorMessage { get; set; }

  [DataMember(EmitDefaultValue = false)]
  public object Result { get; set; }

  public ApiResponse(HttpStatusCode statusCode, object result = null, string   errorMessage = null)
  {
      StatusCode = (int)statusCode;
      Result = result;
      ErrorMessage = errorMessage;
  }
}

Have a look at this post for a reference implementation http://www.devtrends.co.uk/blog/wrapping-asp.net-web-api-responses-for-consistency-and-to-provide-additional-information


text:
Q: Express API: Error [ERR_HTTP_HEADERS_SENT] I know this question has been asked a lot but none of the answers served my case.
I keep getting this error even though I send a response to client only once. Please could anyone point to me what I'm missing? I appreciate any help. Here is my router code:
router.get("/trainers/:page/:limit", verifyToken, (req, res) => {

  const numPerPage = req.params.limit; // number of items per page
  const page = req.params.page;
  let result; //final object to be sent to client

  connection.query("Select count(*) as totalCount from trainers", (err, rows, fields) => {
    if (err) {
      return res.sendStatus(500).json({error: err})
    }
    var totalCount = rows[0].totalCount;
    var numPages = Math.ceil(totalCount / numPerPage);

    connection.query("SELECT id FROM trainers LIMIT ? OFFSET ?", [numPerPage, (page-1) * numPerPage], (err, rows, fields) => {
      if (err) {
        return res.sendStatus(500).json({error: err})
      } else {
        result = { rows, numPages }
        res.json()
      }
    })
  })
})

here is the error log:
throw err; // Rethrow non-MySQL errors
      ^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:526:11)
    at ServerResponse.header (/Users/diego/Documents/DT Personal Training App/express-api/node_modules/express/lib/response.js:771:10)
    at ServerResponse.send (/Users/diego/Documents/DT Personal Training App/express-api/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/Users/diego/Documents/DT Personal Training App/express-api/node_modules/express/lib/response.js:267:15)
    at Query. (/Users/diego/Documents/DT Personal Training App/express-api/routes/admin/trainers.js:53:36)
    at Query. (/Users/diego/Documents/DT Personal Training App/express-api/node_modules/mysql/lib/Connection.js:526:10)
    at Query._callback (/Users/diego/Documents/DT Personal Training App/express-api/node_modules/mysql/lib/Connection.js:488:16)
    at Query.Sequence.end (/Users/diego/Documents/DT Personal Training App/express-api/node_modules/mysql/lib/protocol/sequences/Sequence.js:83:24)
    at Query.ErrorPacket (/Users/diego/Documents/DT Personal Training App/express-api/node_modules/mysql/lib/protocol/sequences/Query.js:92:8)
    at Protocol._parsePacket (/Users/diego/Documents/DT Personal Training App/express-api/node_modules/mysql/lib/protocol/Protocol.js:291:23) {
  code: 'ERR_HTTP_HEADERS_SENT'
}

A: As per express docs
res.sendStatus(500) // equivalent to res.status(500).send('Internal Server Error')

so you need to use res.status(500).json({error: err}) to avoid this error :)