text:
Q: How to merge overlapped groups in Snowflake I have a many-many relationship table, and I want to find the overlapped groups and merge them into one.
In the example below, user 2 is in groups 7 and 8, so groups 7 and 8 should be merged into one that contains the records 1, 2, 4. The merged group id can be either 7 or 8, it doesn't matter.

user_id
group

1
7

2
7

2
8

4
8

5
9

6
9

I wish to see output like this:

user_id
group

1
7

2
7

4
7

5
9

6
9

A: This is similar to the one asked earlier, where-in grouping needs to be done to the top level in hierarchy.
The below query aggregates user_id based on group_id into array and then compares those arrays with each other.
When two arrays match they both get same group id.
Once arrays match and they have been assigned their parent group id based on minimum group value, we need to get the top of the hierarchy.
There could also be multiple hierarchies in the data-set, so we set starting point of each hierarchy as NULL.
Lastly, we use hierarchical query to get the final grouping.
with data(user_id,group_id) as (
  select * from values
  (1,7),(2,7),(2,8),(4,9),(5,9),(5,8),
  (6,9),(70,8),(21,51),(22,51),(23,52),
  (24,51),(24,52),(25,26)
),cte_1 as
  (select group_id,array_agg(user_id) arr
  from data
  group by group_id
), cte_2 as
  (select c1.group_id g1, c2.group_id g2 ,
  c1.arr arr1, c2.arr arr2,
  case when arrays_overlap(arr1, arr2) then g1 end flag,
  min(flag) over (partition by g2) grp,
  case when g2 <> grp then grp end final_grp
  from cte_1 c1, cte_1 c2
), cte_3 as
  (select distinct g2, connect_by_root g2 as parent from cte_2
  start with final_grp is null
  connect by final_grp = prior g2
  order by g2
), cte_4 as
  (select c3.parent, c1.arr
  from cte_1 c1 left join cte_3 c3
  where c1.group_id = c3.g2
) select distinct value, parent as final_group
  from cte_4,
  lateral flatten(input=>arr)
  order by value;

VALUE
FINAL_GROUP

1
7

2
7

4
7

5
7

6
7

21
51

22
51

23
51

24
51

25
26

70
7

Adding another query, that is simpler.
with data(user_id,group_id) as (
  select * from values
  (1,7),(2,7),(2,8),(4,9),(5,9),(5,8),
  (6,9),(70,8),(21,51),(22,51),(22,52),
  (22,53),(23,52),(25,26)
), cte_1 as
  (select a.group_id grp1, b.group_id grp2
  from data a, data b
  where a.user_id = b.user_id
  and a.group_id < b.group_id
), cte_2 as
  (select grp2, connect_by_root grp1 as parent
  from cte_1
  start with grp1 not in (select grp2 from cte_1)
  connect by grp1 = prior grp2
) select a.user_id,
  coalesce(b.parent, a.group_id) final_grp
  from data a left join cte_2 b
  on a.group_id = b.grp2;

A: Answering my own question here, below is the SQL I built that fits my needs. This is inspired by @pankaj 's answer.
with data(user_id,group_id) as (
  select * from values
    (1,7),(2,7),(2,8),(4,9),(5,9),(5,8),
    (6,9),(70,8),(21,51),(22,51),(23,52),
    (24,51),(24,52),(25,26)
), group_members as (
    select
        group_id, array_agg(user_id) users
    from data
    group by group_id
), overlapped_group as (
    select
        c1.group_id g1,
        c2.group_id g2,
        -- c1.users,
        -- c2.users,
        least(g1, coalesce(g2, g1)) as min_group,
        min(min_group) over (partition by g2) as merge_to
    from group_members c1
    left join
        group_members c2 on arrays_overlap(c1.users, c2.users)
        and g1 <> g2
), merge_mapping as (
    select distinct
        g1 as group_id,
        iff(g2 is null, g1, min(merge_to) over (partition by g1)) as merge_to
    from overlapped_group
)

select
    user_id,
    m.merge_to as group_id
from data
left join merge_mapping m using(group_id);

A: One way:
select user_id, STRTOK(listagg(group, ', ') within group (ORDER BY user_id ),',',1)
from <table>
GROUP BY user_id ORDER BY user_id;


text:
Q: Disk Cached IO very slow I have two boxes with exactly same hardware configuration. Both having RAID0 (created using mdadm) over SATA disks. But I am getting different cached reads while testing using hdparm command.
$ hdparm -tT /dev/sda

/dev/sda:
 Timing cached reads:   924 MB in  2.00 seconds = 462.20 MB/sec
 Timing buffered disk reads: 290 MB in  3.04 seconds =  95.44 MB/sec

While on the other box,
$ hdparm -tT /dev/sda

/dev/sda:
 Timing cached reads:   18404 MB in  2.00 seconds = 9201.42 MB/sec
 Timing buffered disk reads: 322 MB in  3.00 seconds = 107.18 MB/sec

Can someone help me in solving this issue. Why I am getting low cached reads on one of the server. Is there any BIOS settings handling this ?
Edit 1:
I tried perf tool on both the machines.
Output on the box where issue is coming:
# perf stat dd if=/dev/zero of=/dev/null count=1000000
1000000+0 records in
1000000+0 records out
512000000 bytes (512 MB) copied, 6.22039 s, 82.3 MB/s

Performance counter stats for 'dd if=/dev/zero of=/dev/null count=1000000':

    5692.357502  task-clock-msecs         #      0.913 CPUs
             72  context-switches         #      0.000 M/sec
              7  CPU-migrations           #      0.000 M/sec
            220  page-faults              #      0.000 M/sec
      975469183  cycles                   #    171.365 M/sec
     1374701843  instructions             #      1.409 IPC
          65350  cache-references         #      0.011 M/sec
          17986  cache-misses             #      0.003 M/sec

Output on the other box:
$ perf stat dd if=/dev/zero of=/dev/null count=1000000
1000000+0 records in
1000000+0 records out
512000000 bytes (512 MB) copied, 0.280017 s, 1.8 GB/s

 Performance counter stats for 'dd if=/dev/zero of=/dev/null count=1000000':

     278.388839  task-clock-msecs         #      0.994 CPUs
              0  context-switches         #      0.000 M/sec
              0  CPU-migrations           #      0.000 M/sec
            220  page-faults              #      0.001 M/sec
      725024593  cycles                   #   2604.359 M/sec
     1371073131  instructions             #      1.891 IPC
          15921  cache-references         #      0.057 M/sec
           1847  cache-misses             #      0.007 M/sec

I didn't understand why there are so many context switches and value of task-clock-msecs is also high. Can someone please help me in debugging further.
Edit 2:
I am getting the following output for smartctl command:
# /usr/local/sbin/smartctl -i /dev/sda
smartctl 6.2 2013-07-26 r3841 [x86_64-linux-2.6.32-5-amd64] (local build)
Copyright (C) 2002-13, Bruce Allen, Christian Franke, www.smartmontools.org

=== START OF INFORMATION SECTION ===
Device Model:     ST91000640NS
Serial Number:    9XG40W61
LU WWN Device Id: 5 000c50 050920a25
Add. Product Id:  DELL(tm)
Firmware Version: AA09
User Capacity:    1,000,204,886,016 bytes [1.00 TB]
Sector Size:      512 bytes logical/physical
Rotation Rate:    7200 rpm
Device is:        Not in smartctl database [for details use: -P showall]
ATA Version is:   ATA8-ACS T13/1699-D revision 4
SATA Version is:  SATA 3.0, 3.0 Gb/s (current: 3.0 Gb/s)
Local Time is:    Sun Sep 29 00:03:33 2013 IST
SMART support is: Available - device has SMART capability.
SMART support is: Enabled

# /usr/local/sbin/smartctl -i /dev/sdb
smartctl 6.2 2013-07-26 r3841 [x86_64-linux-2.6.32-5-amd64] (local build)
Copyright (C) 2002-13, Bruce Allen, Christian Franke, www.smartmontools.org

=== START OF INFORMATION SECTION ===
Device Model:     ST91000640NS
Serial Number:    9XG41K1L
LU WWN Device Id: 5 000c50 05093c434
Add. Product Id:  DELL(tm)
Firmware Version: AA09
User Capacity:    1,000,204,886,016 bytes [1.00 TB]
Sector Size:      512 bytes logical/physical
Rotation Rate:    7200 rpm
Device is:        Not in smartctl database [for details use: -P showall]
ATA Version is:   ATA8-ACS T13/1699-D revision 4
SATA Version is:  SATA 3.0, 3.0 Gb/s (current: 3.0 Gb/s)
Local Time is:    Sun Sep 29 00:03:33 2013 IST
SMART support is: Available - device has SMART capability.
SMART support is: Enabled

A: The disk read numbers are within about 10 percent or so. I wouldn't worry about such a small difference. (The cached reads are not disk I/O and has nothing to do with your disks, or with I/O. See the hdparm man page for an explanation of why this is meaningless.)

A: I think @DavidSchwartz has the right idea here, obviously the problem is somewhere else since the disk speeds look pretty similar.
The best resource I've seen for tracking down performance related issues is by using the USE method described by Brendan Gregg.  Since you're using Linux, there is a related post also by him which is tailored specifically for Linux.

redpajama_set_name: RedPajamaStackExchange


text:
Q: .htaccess & error pages - Stay on page and don't redirect This seems very simple. ErrorDocument redirection to another page:
RewriteEngine On

ErrorDocument 400 /err/e=400
ErrorDocument 401 /err/e=401
ErrorDocument 403 /err/e=403
ErrorDocument 404 /err/e=404
ErrorDocument 500 /err/e=500

But the problem with these custom error pages is that the browser actually redirects to the page /err/e=404 instead of just showing its content. When not using custom error pages, the URL in the browser stays the same, thus allowing the user to correct the URL without having to type it again.
Question: How to create custom error pages that do not alter the URL and leave it like domain.tld/nonexistantfile ?
Background: Debian Wheezy, Apache2 and PHP are used.
Update posting the entire .htaccess file
RewriteEngine On

ErrorDocument 400 /err/e=400
ErrorDocument 401 /err/e=401
ErrorDocument 403 /err/e=403
ErrorDocument 404 /err/e=404
ErrorDocument 500 /err/e=500

RewriteRule ^favicon.ico$ favicon.ico [L]
RewriteRule ^css/(.*) css/$1 [L]
RewriteRule ^downloads/(.*) downloads/$1 [L]
RewriteRule ^images/(.*) images/$1 [L]
RewriteRule ^js/(.*) js/$1 [L]

RewriteRule index.php(.*) index.php$1 [L]
RewriteRule ^(.*)/(.*=.*) index.php?controller=$1&$2 [L]
RewriteRule ^(.*=.*) index.php?$1 [L]
RewriteRule ^(.*) index.php?controller=$1 [L]

The last part enables URL's like /home or page1/page2/param=123

A: You must have a rule to avoid rewrite for real files/directories like this:
ErrorDocument 400 /err/e=400
ErrorDocument 401 /err/e=401
ErrorDocument 403 /err/e=403
ErrorDocument 404 /err/e=404
ErrorDocument 500 /err/e=500

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^([^/]+)/([^=]+=.*)$ index.php?controller=$1&$2 [L,QSA]
RewriteRule ^([^=]+=.*)$ index.php?$1 [L,QSA]
RewriteRule ^(.+)$ index.php?controller=$1 [L,QSA]

I also removed some redundant rules.


text:
Q: Can't click on an object more than once on Mobile. The code works fine on the laptop I want to animate an object on click but the click only registers once on mobile for some reason. Works fine on laptop.
I have tried using mousedown and changing A-Frame version but it doesn't seem to do the job. Using 0.8.2.
    AFRAME.registerComponent("foo", {
        init: function() {
          let anim = document.querySelector("#Kanye")
          let anim2 = document.querySelector("#ball")

          this.el.addEventListener("click", (e) => {
            //console.log(e)
            //this.el.emit("bar")
            anim2.setAttribute('visible','true')
            anim2.emit("bar")
          })

        }
      })

A: This issue has been fixed. You are in an old version. Use A-Frame 0.9.2


text:
Q: JavaScript TypeError: Cannot read property 'startsWith' of undefined - discord bot I must start this question by saying that I have very little knowledge of javascript (I'm practiced in Java) and just wanted to make a (somewhat) simple Discord bot that would say messages at random times. I Frankensteined 2 pieces of code from various tutorials together and currently have this:
var Discord = require('discord.io');
var logger = require('winston');
var auth = require('./auth.json');
//random bot code
var randomMessage;
var randOn = false;
var responseArray = [ //add more messages here
  "Ayy, lmao!",
  "Say what?",
  "roflmaotntpmp"
];

var prefix = "!";
var timer = [5,10]; //set min and max in seconds for random messages

// Configure logger settings
logger.remove(logger.transports.Console);
logger.add(new logger.transports.Console, {
    colorize: true
});
logger.level = 'debug';
// Initialize Discord Bot
var bot = new Discord.Client({
   token: auth.token,
   autorun: true
});
bot.on('ready', function (evt) {
    logger.info('Connected');
    logger.info('Logged in as: ');
    logger.info(bot.username + ' - (' + bot.id + ')');
});

bot.on('message', (msg) => {

  if (msg.content.startsWith(prefix + "on")) {
        if (randOn) {
            msg.channel.sendMessage("Already running.");
        }
        else {
            msg.channel.sendMessage("Random message started.")
        randomMessage = setTimeout(function() {
                randMsg(msg.channel);
            }, 1000*timer[0]);
        }
  }
  else if (msg.content.startsWith(prefix + "off")) {
        if (randOn) {
            clearTimeout(randomMessage);
            msg.channel.sendMessage("Random message disabled.");
        }
        else {
            msg.channel.sendMessage("Not running.");
        }
  }

});

function randomIntFromInterval(min, max) {
  return Math.floor(Math.random()*(max-min+1)+min);
}

function randMsg(msgChan) {
    console.log("callback");
    var interval = 1000*randomIntFromInterval(timer[0],timer[1]);
  var rand = randomIntFromInterval(0,responseArray.length-1);
  if(responseArray[rand]) {
    msgChan.sendMessage(responseArray[rand]);
  }
    randomMessage = setTimeout(function() {
        randMsg(msgChan);
    }, interval);
}

The problem is occurring in this block:
 bot.on('message', (msg) => {

      if (msg.content.startsWith(prefix + "on")) {
            if (randOn) {
                msg.channel.sendMessage("Already running.");
            }

Every time I attempt to command the bot in my discord chat (!on) I get the error "TypeError: Cannot read property 'startsWith' of undefined" in Node.js/command prompt. I've tried various things to fix it (removing "content" from both msg.content... statements - no complaints but absolutely nothing happens) but... I honestly have no idea what I'm doing. I've checked every post on the internet that deals with similar things and nothing has been able to answer this. I'm hoping it's a simple syntax thing/something not declared properly... If you have some time and pity for me, please help. I know I've gotten myself into a mess but I refuse to abandon it!
Let me know what other information I can provide to help.

A: Your issue is, that you mix discord.js with discord.io
discord.js is object oriented where discord.io is not, so in discord.io your message is already a string!
Example discord.io message event.
bot.on('message', function(user, userID, channelID, message, event) {
    if (message === "ping") {
        bot.sendMessage({
            to: channelID,
            message: "pong"
        });
    }
});

A: Maybe jam something like if(!msg || !msg.content) return; in there to bail out if the msg object or its content property is undefined.

bot.on('message', (msg) => {

  if(!msg || !msg.content) return;

  if (msg.content.startsWith(prefix + "on")) {
        if (randOn) {
            msg.channel.sendMessage("Already running.");
        }
        else {
            msg.channel.sendMessage("Random message started.")
        randomMessage = setTimeout(function() {
                randMsg(msg.channel);
            }, 1000*timer[0]);
        }
  }
  else if (msg.content.startsWith(prefix + "off")) {
        if (randOn) {
            clearTimeout(randomMessage);
            msg.channel.sendMessage("Random message disabled.");
        }
        else {
            msg.channel.sendMessage("Not running.");
        }
  }

});


text:
Q: Fix issues with getting rabbitmq to work in the notification-service & the customer-service in the yaml file Has anybody had any issues with getting rabbitmq to work in the notification-service & the customer-service in the yaml file?
Ive refreshed all the attached microservices
Renstalled them
Invalidated cached and restarted and I cant get this to work.
Please fix this error


text:
Q: Problem with massive data importation to PostGIS/PostgreSQL I need to import a huge SIG data into PostgreSQL (my shapefile table have almost 1.700.000 rowns and 43 columns).
I'm using PostgreSQL 12.4 and PostGIS 3.0.x, that came together with PostGIS Bundle 3 DBF Loader, which I'm using for the importation.
The thing is that my data is being loaded, at first look with no problem, but verifying the integrity of the table, I noticed the information are all messed up - with column values misplaced between them (the number of rows is aparently ok).
Does someone know the reason for that? Is that a size limit for data to be sucessfully loaded from external environment into PostgreSQL/PostGIS?
I'm new in this topic, and don't know what other information is important for someone to help me.


text:
Q: Can I add a check constraint to a child checking the value of its parent in MySQL? I have a similar database with two tables as follow:
+----------------------+           +------------------------+
|Persons               |           |phones                  |
+----------------------+           +------------------------+
|id       int          +-----+     |id          int         |
|name     varchar(100) |     +---->+person_id   int         |
|allowed  tinyint(1)   |           |number      int         |
+----------------------+           +------------------------+

One person could have as many phones as he wants but he has to be allowed to it (allowed > 0).
So, I created both tables using
CREATE TABLE `phones` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `persons_id` int(11) DEFAULT NULL,
  `phonenumber` int(5) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `phones_ibfk_1` (`persons_id`),
  CONSTRAINT `phones_ibfk_1` FOREIGN KEY (`persons_id`) REFERENCES `persons` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8`

But this doesn't check what I want. What I want to know if it is possible make a query like ALTER TABLE phones ADD CONSTRAINT chk_person CHECK (persons.allowed  > 0). Is this possible? There's another alternative?

A: the check constraint doesn't work a solution is to create a trigger before
insert so you check the values if you find something wron do an insert into the same table that will cause a erreur in
DELIMITER ||
CREATE TRIGGER  trigger_check  before insert ON phones  FOR EACH ROW
begin
DECLARE is_allowed boolean;
select allowed into @is_allowed from Persons where id = new.person_id;
if @is_allowed <1 then
  insert into phones values ('','','','');  #make erreur doesn't metter
  end if ;
end ||
DELIMITER ;

that's how we do it for now hope that check constraint work in the new versions


text:
Q: Given the characteristic equation of A.Find equation for B. Given that $\chi_A(x)=x^3-ax^2+bx-c$
Find $\chi_B(x)$ For:
a)B=A-2I
b)$B=A^2$
For a) would you put x+2 in for x in the $\chi_A(x)$. As Det(XI-B)=Det(XI+2I-A)= det((X+2)I-A)
And b: Im not sure how to do but you have to square the eigenvalues?

A: From $A^3-aA^2+bA-cI=0$ you get
$$
               A(A^2+bI)=aA^2+cI
$$
Squaring both sides,
$$
               A^2(A^4+2bA^2+b^2I)=a^2A^4+2acA^2+c^2I \\
               B(B^2+2bB+b^2I)=a^2B^2+2acB+c^2I \\
                B^3+2bB^2+b^2B-a^2B^2-2acB-c^2I=0 \\
                B^3+(2b-a^2)B^2+(b^2-2ac)B-c^2I=0.
$$


text:
Q: jQuery Mobile for desktop and mobile What browsers on desktop jQuery Mobile supports?
Can I develop single interface on jQuery Mobile both desktop and mobile?
What do you think about web app with such interface for desktop users? I mean usability.
So supported PC browsers:

*

*Chrome 10+

*Firefox 3.6+

*Opera 11

*IE 7+

A: jQuery Mobile doesn't seem to actively ensure that it works on any particular desktop browsers like it ensures that it works on particular mobile browsers. Because of this, you will not have the security of knowing that the next jQuery Mobile release has been rigorously tested on desktop browsers. To ensure it works for the desktop browsers you want it to, you'll have to test it on your own.
That being said, from experience it tends to work well on any up to date desktop browser I've tried it on. This isn't much of a surprise since desktop browsers are so mature and have the added advantage of access to a fast processor and lots of memory. Because there are so few commonly used desktop browsers out there, it shouldn't be too hard to test out your app on all of them every now and then.

A: *

*Chrome Desktop 11-13 - Tested on OS X 10.6.7 and Windows 7

*Firefox Desktop 3.6-4.0 - Tested on OS X 10.6.7 and Windows 7

*Internet Explorer 7-9 - Tested on Windows XP, Vista and 7 (minor CSS
issues)

*Opera Desktop 10-11 - Tested on OS X 10.6.7 and Windows 7

For the full list check here: http://jquerymobile.com/demos/1.0rc1/docs/about/platforms.html

A: Those that are having problems with jqm not styling "pages" correctly in IE etc.. should try duplicating the styles in question inline on the pages that they're ajaxing in. Not sure why this works but it seems to help in a lot of these cases. They'll need to do that anyway, in some form, if you're allowing linking directly to those pages.
Maybe different browsers have different specificity rules or something.
As far as the original question about using jqm for both mobile and desktop, I thought it was a good idea and am working towards that end right now, but have ran into problems with basic positioning (mainly with a google maps div working perfectly in desktop and not mobile, or mobile and not desktop). If you do attempt such things, I would avoid having separate inline "pages" and also ajax "pages." I wanted to do so so I could better preload some data, but I think that is where I'm running into trouble.
And to have it look nice on both mobile and desktop, it appears that you can get it working pretty nicely with some simple style sheets, but not all websites will be suitable for such a reflow without some compromises.

A: In my testing it works on FireFox 3.6 and above and Chrome 10 and above.  Not all effects like page transitions seem to work though.
It looks awful in IE8.


text:
Q: Rails and memcached in a logged env I see a lots of how to about rails and memcached.
But I cannot find an updated how to that teach how to use memcached in a site where there is both a public section and a logged users section.

A: Assuming you have gone through all of the relevant Railscasts and the official RailsGuides, you should check out the Scaling Rails series.
Your public pages will likely not have any dynamic (user dependent) context, so page caching is good there.  The user dependent pages get a little tricky and require fragment caching or a mixture of page/action caching with ajax calls to get the user dependent content.
Here is a basic example.


text:
Q: Q. Reducible polynomials in $\mathbb{Z}[x]$ Show that $x^3+ax^2+bx+1$ $\in \mathbb Z[x]$ is reducible on $\mathbb{Z}$  if and only if  $a=b$ or $a+b=-2$.
If it is reducible, then it has root in $\mathbb Z$. Be $u$ the root, so i can write it as:
$x^3+ax^2+bx+1=(x-u)(x^2+cx+d)$
That developing the right expression, I get my conditions.
To make the reverse path, can I simply assume a factorization and suppose conditions to reach my original polynomial?

A: $x^3+ax^2+bx+1\in\mathbb{Z}[x]$ is of degree $3$.
If this polynomial is reducible, it must have a root in $\mathbb{Z}$ which means you can factor the polynomial like this:
$x^3+ax^2+bx+1=(x^2+cx+d)(x+e)$
Factor out the LHS and compare the coefficients.

A: If $x^3 + ax^2 + bx + 1$ is reducible in $\Bbb Z[x]$, then we have
$x^3 + ax^2 + bx + 1 = (x^2 + cx + d)(x + e)$
$= x^3 + ex^2 + cx^2 + ecx + dx + ed = x^3 + (c + e)x^2 + (ec + d)x + ed; \tag 1$
we know that $x^3 + ax^2 + bx + 1$ must factor in this form since (i.) a cubic, if reducible, may always be written as the product of a linear and a quadratic polynomial; (ii.) the product of the leading coefficients of the factors is $1$.  Choosing each leading coefficient of the factors to be $1$ is possible since this case can always be obtained by reversing the signs of the factors.
Then, comparing coefficients of like terms,
$c + e = a, \tag 2$
$ec + d = b, \tag 3$
$ed = 1; \tag 4$
therefore,
$e = d = 1 \vee e = d = -1; \tag 5$
$e = d = 1 \Longrightarrow c + 1 = b, \; c + 1 = a \Longrightarrow a = b; \tag 6$
$e = d = -1 \Longrightarrow -c - 1 = b, \; c - 1 = a \Longrightarrow a + b = -2; \tag 7$
we can run the logic engine in reverse; if
$a = b, \tag 8$
we simply choose
$e = d = 1, \; c = a - 1; \tag 9$
then it is easy to check that
$(x^2 + (a - 1)x + 1)(x + 1) = x^3 + x^2 + (a - 1)x^2 + (a - 1)x + x + 1$
$= x^3 + x^2 + ax^2 - x^2 + ax - x + x + 1 = x^3 + ax^2 + ax + 1$
$= x^3 + ax^2 + bx + 1; \tag{10}$
if $a + b = -2$, then we pick
$e = d = -1, \; c = a + 1 = -b - 1; \tag{11}$
thus,
$(x^2 + (a + 1)x - 1)(x - 1) = x^3 - x^2 + (a + 1)x^2 - (a + 1)x - x + 1$
$= x^3 - x^2 + ax^2 + x^2 - ax - x - x + 1 = x^3 + ax^2 - (a + 2)x + 1$
$= x^3 + ax^2 + bx + 1. \tag{12}$

A: We can factorize this polynomial in $\mathbb{Z}$ iff $1$ or $-1$ is one of it zeros, so
1. case $x_1=1$, by Vieta formula we have $$ 1+x_2+x_3=-a$$ $$x_2x_3+x_2+x_3 = b$$ $$x_2x_3 = -1$$ so $$-1+(-a-1) = b\implies a+b=-2$$
2. case $x_1=-1$, by Vieta formula we have $$ -1+x_2+x_3=-a$$ $$x_2x_3-x_2-x_3 = b$$ $$x_2x_3 = 1$$ so $$1+(-a+1) = b\implies a=b$$


text:
Q: SEDE did not update SEDE currently states it was updated 11 minutes ago:

However this does not appear to be the case, as this query:
select
  max(creationdate) [last action],
  datediff(day, max(creationdate), getdate()) [days ago]
from posthistory

When run on SO, currently yields:
last action         days ago
------------------- --------
2017-07-02 05:18:54 8

Which suggests that no data exists for the past 7 days.
I had originally just assumed this was an issue on all sites but the comment below points out (and I've confirmed) that it's not. So far I haven't found any other sites that exhibit this behavior besides SO (including MSO, which is up-to-date).

A: The job failed this weekend because the READ UNCOMMITTED gods were against us. Luckily we sacrificed some regexes on the pillar of please-let-this-workiness to the hamster gods and it's re-running. It takes many hours.
The screen isn't wrong, but I totally see how it's misleading here. Some data was refreshed just now, but Stack Overflow hasn't been hit yet, it'll take several more hours to finish. The process goes from newest sites to oldest (meaning Stack Overflow is last), I'll be keeping an eye on it.


text:
Q: JBoss EAP 7.2 Oracle Hibernate Dialect I am using JBoss EAP 7.2 with Oracle 12c ojdbc7.jar
The application used to work. However after a restart of the JBoss Server I now get
"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"monitoring4.war#primary\"" => "org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [oorg.hibernate.dialect.Oracle12cDialect] as strategy [org.hibernate.dialect.Dialect]
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [oorg.hibernate.dialect.Oracle12cDialect]
Caused by: java.lang.ClassNotFoundException: Could not load requested class : oorg.hibernate.dialect.Oracle12cDialect"}}

I have used a simple persistence.xml without a hibernate dialect
<persistence version="2.0">
  <persistence-unit name="primary">

     <jta-data-source>java:/blabla</jta-data-source>

  <properties>
     <!-- Properties for Hibernate -->

     <property name="hibernate.show_sql" value="true" />

  </properties>

I have tried to add
<property name="hibernate.dialect"
              value="oorg.hibernate.dialect.Oracle12cDialect"/>

no I get
{"WFLYCTL0080: Failed services" => {"jboss.persistenceunit.\"monitoring4.war#primary\"" => "org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [oorg.hibernate.dialect.Oracle12cDialect] as strategy [org.hibernate.dialect.Dialect]
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [oorg.hibernate.dialect.Oracle12cDialect]
Caused by: java.lang.ClassNotFoundException: Could not load requested class : oorg.hibernate.dialect.Oracle12cDialect"}}

What Oracle dialect should I use with EAP 7.2 ???
Any idea why the application has stopped working without any change (that I know of) certainly not in the project.
Thanks,
Hans

A: <property name="hibernate.dialect"
              value="org.hibernate.dialect.OracleDialect"/>

solved the problem

A: Check which version of hibernate-core is in your project/JBoss instance(depends if your war or JBoss provides it).
org.hibernate.dialect.Oracle12cDialect is supported from hibernate-core >= 5.0.


text:
Q: With which noun should a verb following "(person) or I" agree? In the sentence below, should the bolded word be prepare or prepares?

When my family eats at home, my mom or I prepares the meal.

Normally, I would side with the verb agreeing with its corresponding noun in the sentence. However, since this is an exclusive or, where it's either my mom or I doing the preparation, that means that it would be my mom prepares or I prepare.
I'd like to avoid writing it like the sentence below, as it just sounds a bit awkward.

When my family eats at home, one of either my mom or me prepares the meal.

I was unable to find any existing questions that covered my scenario exactly. Most deal with (person) and I or the order of the two verbs in the sentence.
How can I write this using the my mom or I syntax?

A: The bolded word should be prepare.

When my family eats at home, my mom or I prepare the meal.

The rule is: If a compound subject contains or or nor, the verb should agree with the part of the subject that is nearer the verb.

A: "When my family eats at home, either my mom or I prepares the meal."
The prepare is correct, add either instead.

A: Interesting. I think I would get round it by writing "my mom prepares the meal or I do".


text:
Q: Login failed for user 'adminUsr'. Reason: Failed to open the explicitly specified database ' Dim sConnection As String = "Data Source = svr1066; Initial Catalog =
    PFSEditTest;Integrated Security = true;"

Using Con As New SqlConnection(sConnection)
    Con.Open()
    Dim Com As New SqlCommand("Select * From PFSEEditTestTable WHERE ID = @ID", Con)
    Com.Parameters.AddWithValue("@ID", TextBoxID.Text)
   'Reading information from Database into Form
    Using Com

I'm trying to access a database and when I do a Server Log review says Error 18456, Severity 14, State: 38.  I looked up the codes and they mean user can fix and Login Valid but Database Unavailable with Reason: Failed to open the explicitly specified database.  I'm able to run a query in SSMS against the database and it returns the information in the rows correctly.

A: I found the error - the table isn't PFSEEditTestTable it should be PFSEditTestTable.  I also ended up publishing the application as available only online (through the server) which I like better because the users can just run it from the server and don't need it on their desktops.


text:
Q: dynamic drop down box? I got a database table called category as shown:

I am trying to do a dynamic drop down box and the index script is shown as:
<?php

try {

$objDb = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$objDb->exec('SET CHARACTER SET utf8');

$sql = "SELECT *
        FROM `category`
        WHERE `master` = 0";
$statement = $objDb->query($sql);
$list = $statement->fetchAll(PDO::FETCH_ASSOC);

    } catch(PDOException $e) {
echo 'There was a problem';
    }

    ?>
    <!DOCTYPE HTML>

<meta charset="utf-8" />
<title>Dependable dropdown menu</title>
<meta name="description" content="Dependable dropdown menu" />
<meta name="keywords" content="Dependable dropdown menu" />
<link href="/css/core.css" rel="stylesheet" type="text/css" />

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

    <select name="gender" id="gender" class="update">
        <option value="">Select one</option>
        <?php if (!empty($list)) { ?>
            <?php foreach($list as $row) { ?>
                <option value="<?php echo $row['id']; ?>">
                    <?php echo $row['name']; ?>
                </option>
            <?php } ?>
        <?php } ?>
    </select>

    <select name="category" id="category" class="update"
        disabled="disabled">
        <option value="">----</option>
    </select>

    <select name="colour" id="colour" class="update"
        disabled="disabled">
        <option value="">----</option>
    </select>
</form>

The update.php is shown as:
<?php
if (!empty($_GET['id']) && !empty($_GET['value'])) {

$id = $_GET['id'];
$value = $_GET['value'];

try {

    $objDb = new PDO('mysql:host=localhost;dbname=test', 'root', '');
    $objDb->exec('SET CHARACTER SET utf8');

    $sql = "SELECT *
            FROM `category`
            WHERE `master` = ?";
    $statement = $objDb->prepare($sql);
    $statement->execute(array($value));
    $list = $statement->fetchAll(PDO::FETCH_ASSOC);

    if (!empty($list)) {

        $out = array('<option value="">Select one</option>');

        foreach($list as $row) {
            $out[] = '<option
value="'.$row['id'].'">'.$row['name'].'</option>';
        }

        echo json_encode(array('error' => false, 'list' => implode('',
$out)));

    } else {
        echo json_encode(array('error' => true));
    }

} catch(PDOException $e) {
    echo json_encode(array('error' => true));
}

} else {
echo json_encode(array('error' => true));
}

The 2nd drop down box is not showing the values dependent on the 1st drop down box as shown:

Can someone help me please.

A: Here is an example that will do what you want. Essentially, you can use jQuery / AJAX to accomplish this.
I updated my example code to match your server login / table / field names, so if you copy/paste these two examples into files (call them tester.php and another_php_file.php) then you should have a fully working example to play with.
I modified my example below to create a second drop-down box, populated with the values found. If you follow the logic line by line, you will see it is actually quite simple. I left in several commented lines that, if uncommented (one at a time) will show you what the script is doing at each stage.
FILE 1 -- TESTER.PHP

    <select name="students" id="stSelect">
        <option value="">Please Select</option>
        <option value="John">John Doe</option>
        <option value="Mike">Mike Williams</option>
        <option value="Chris">Chris Edwards</option>
    </select>

FILE 2 - another_php_file.php
<?php

//Login to database (usually this is stored in a separate php file and included in each file where required)
    $server = 'localhost'; //localhost is the usual name of the server if apache/Linux.
    $login = 'root';
    $pword = '';
    $dbname = 'test';
    mysql_connect($server,$login,$pword) or die($connect_error); //or die(mysql_error());
    mysql_select_db($dbname) or die($connect_error);

//Get value posted in by ajax
    $selStudent = $_POST['theOption'];
    //die('You sent: ' . $selStudent);

//Run DB query
    $query = "SELECT * FROM `category` WHERE `master` = 0";
    $result = mysql_query($query) or die('Fn another_php_file.php ERROR: ' . mysql_error());
    $num_rows_returned = mysql_num_rows($result);
    //die('Query returned ' . $num_rows_returned . ' rows.');

//Prepare response html markup
    $r = '

Found in Database:

            <select>
    ';

//Parse mysql results and create response string. Response can be an html table, a full page, or just a few characters
    if ($num_rows_returned > 0) {
        while ($row = mysql_fetch_assoc($result)) {
            $r = $r . '<option value="' .$row['id']. '">' . $row['name'] . '</option>';
        }
    } else {
        $r = '
No student by that name on staff
';
    }

//Add this extra button for fun
    $r = $r . '</select><button id="theButton">Click Me</button>';

//The response echoed below will be inserted into the
    echo $r;

To answer your question in the comment: "How do you make the 2nd drop down box populate fields that are only relevant to a selected option from the 1st drop down box?"
A.  Inside the .change event for the first dropdown, you read the value of the first dropdown box:

    $('#dropdown_id').change(function() {
        var dd1 = $('#dropdown_id').val();
    }

B.  In your AJAX code for the above .change() event, you include that variable in the data you are sending to the 2nd .PHP file (in our case, "another_php_file.php")
C.  You use that passed-in variable in your mysql query, thereby limiting your results. These results are then passed back to the AJAX function and you can access them in the success: portion of the AJAX function
D.  In that success function, you inject code into the DOM with the revised SELECT values.
That is what I am doing in the example posted above:

*

*The user chooses a student name, which fires the jQuery .change() selector

*Here is the line where it grabs the option selected by the user:
var sel_stud = $(this).val();

*This value is sent to another_php_file.php, via this line of the AJAX code:
data: 'theOption=' + sel_stud,

*The receiving file another_php_file.php receives the user's selection here:
$selStudent = $_POST['theOption'];

*Var $selStudent (the user's selection posted in via AJAX) is used in the mysql search:
$query = " SELECT * FROM `category` WHERE `master` = 0 AND `name` = '$selStudent' ";
(When changing the example to suit your database, the reference to $selStudent was removed. But this (here, above) is how you would use it).

*We now build a new <SELECT> code block, storing the HTML in a variable called $r. When the HTML is fully built, I return the customized code back to the AJAX routine simply by echoing it back:
echo $r;

*The received data (the customized <SELECT> code block) is available to us inside the AJAX success: function() {//code block}, and I can inject it into the DOM here:
$('#LaDIV').html(whatigot);
And voila, you now see a second dropdown control customized with values specific to the choice from the first dropdown control.
Works like a non-Microsoft browser.


text:
Q: How to ignore Liferay user removed from LDAP errors? I have a Liferay 6.1 instance that is connected to LDAP. New users get imported nicely, but when I remove a user from the LDAP directory, Liferay starts throwing exceptions when it tries to sync users from LDAP.
These seem to be safe to ignore, but they produce several megabytes of log and it makes log parsing highly annoying. Also I think it might affect performance. If a deleted user logs in, they see nothing.
16:13:54,422 ERROR [liferay/scheduler_dispatch-790][PortalLDAPImporterImpl:995] LDAP user not found with fullUserDN cn=foobar,ou=people,o=foo,dc=bar,dc=baz
javax.naming.NameNotFoundException: [LDAP: error code 32 - No Such Object]; remaining name 'cn=foobar,ou=people,o=foo,dc=bar,dc=baz'
    at com.sun.jndi.ldap.LdapCtx.mapErrorCode(LdapCtx.java:3057)
    at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2978)
    ... etc

How could I convince Liferay that this is really OK? Or is there something else I should do?

A: Until missing users in LDAP are supported by Liferay you can turn off the logging for this particular message. Just create the file ROOT.war/WEB-INF/classes/META-INF/portal-log4j-ext.xml with the following content:
<?xml version="1.0">
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <!-- Copy all appenders from
         ROOT.war/WEB-INF/lib/portal-impl.jar/META-INF/portal-log4j.xml
         and add the following filter: -->
    <appender ...>
        ...
        <filter class="org.apache.log4j.filter.StringMatchFilter">
            <param name="StringToMatch" value="LDAP user not found with fullUserDN" />
            <param name="AcceptOnMatch" value="false" />
         </filter>
    </appender>

    <!-- Keep the root definition from portal-log4j.xml
         to trigger the parsing of the appenders: -->
    <root>
        <priority value="INFO" />
        <appender-ref ref="CONSOLE" />
        <appender-ref ref="FILE" />
    </root>
</log4j:configuration>

You can find more about logging in the Liferay Wiki.


text:
Q: How do I create an infinitely scrollable div (y-axis)? I'm trying to create a column (

) inside of which the user will be able to scroll infinitely upwards or downwards.
I believe the trick is to increase the height of

 downwards every time the user's scroll is about to reach the bottom and increase its height upwards every time the user's scroll is about the reach the top.
Alternatively (seems easier), the top  of

 could be increased every time the user's scroll is about to reach the bottom and vice versa.
However, I can't seem to find the right combination. I tried the 2nd version (increasing the top of

) and obviously only managed to make it infinitely scrollable downwards. Decreasing the top when moving upwards didn't work so I have omitted that part from the code.
Any suggestions ?
You can see it in action here : http://jsfiddle.net/1uzdj12d/5/
CSS
#scroller {
    position: absolute;
    top: 0px;
    left: 0px;
    height: 200px;
    width: 100px;
    overflow: hidden;
    border: 1px solid black;
}

#scroller>div {
    position: absolute;
    top: 0px;
    left: 0px;
    height: 100%;
    width: 100%;
    overflow-x: hidden;
}
#scrollee {
    position: absolute;
    top: -10px;
    left: 0px;
    height: 200%;
    width: 100%;
}
span {
    position:absolute;
    top:0px;
    left: 300px;
}

HTML

Javascript
var timeout;
$("#scroller>div").scroll(function ()
{
    clearTimeout(timeout);
    $('span').text('scrolling');
    timeout = setTimeout(function ()
    {
       $('span').text('');
    }, 500);
});

$("#scroller>div").scroll(function ()
{
    var currentTop = $("#scroller>div").scrollTop();
    $(this).find('div').css({top : currentTop});
});

A: Turns out it was easier than I thought :-)
If you want to create an infinitely scrollable div (on the y-axis), all you need to do is set the height of
 to the height of
 plus 20px. You also need to set its initial scrollTop to 10px (this will allow an upwards and downwards scrolling).
Now every time a scroll occurs, reset the scrollTop of
 to 10px.
You can see my solution in action here : http://jsfiddle.net/vxzw68jk/22/
If you're wondering why I'm using :

instead of simply :

It's because if you set the width of #scroller>div to 150% the scrollbar will be hidden which can be useful (at least for my project..), you can check it out here : http://jsfiddle.net/8psu5L6v/1/
CSS
#scroller {
    position: absolute;
    top: 0px;
    left: 0px;
    height: 200px;
    width: 100px;
    overflow: hidden;
    border: 1px solid black;
}

#scroller>div {
    position: absolute;
    top: 0px;
    left: 0px;
    height: 100%;
    width: 100%;
    overflow-x: hidden;
}
#scrollee {
    position: absolute;
    top: 0px;
    left: 0px;
    height: 220px;
    width: 100%;
}
span {
    position:absolute;
    top: 0px;
    left: 300px;
}

HTML

Javascript
$("#scroller>div").scrollTop(10);
var timeout;
$("#scroller>div").scroll(function ()
{
    $('span').text('scrolling');
    $("#scroller>div").scrollTop(10);
    clearTimeout(timeout);
    timeout = setTimeout(function ()
    {
        $('span').text('');
    }, 500);

});


text:
Q: Onclick listner not triggering in fragment page adapter I'm trying to display all contacts from phone to recyclerView when a user presses any item it should do some work. I have a list of contacts in a fragment which is inside a fragment page adapter when ever I click in the recyclerView item onClicklistener is not executing
I have used same code in a previous app but onclicklisteners are triggering

   public class ListOfContacts extends Fragment implements OnContactListener {
    private static final String TAG = "ListOfContacts";
    ArrayList<ContactModel> arrayList = new ArrayList<>();
    RecyclerView mRecyclerview;
    ListOfContactsRAdapter listOfContactsRAdapter;
    Cursor cursor;

    public static ListOfContacts getInstance(ArrayList<ContactModel> arrayList) {
        ListOfContacts listOfContacts = new ListOfContacts();
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList("listofcontacts", arrayList);
        listOfContacts.setArguments(bundle);
        return listOfContacts;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_list_of_contacts, container, false);
        mRecyclerview = view.findViewById(R.id.loc_r_view);
        listOfContactsRAdapter = new ListOfContactsRAdapter(getActivity(), this, arrayList);
        mRecyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerview.setAdapter(listOfContactsRAdapter);
        mRecyclerview.addItemDecoration(new DividerItemDecoration(mRecyclerview.getContext(), DividerItemDecoration.VERTICAL));
        mRecyclerview.setHasFixedSize(true);
        return view;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                arrayList.addAll(Objects.requireNonNull(getArguments().<ContactModel>getParcelableArrayList("listofcontacts")));
                Log.d(TAG, "contact recived " + arrayList.get(0).getContactName());

            } else {
                if (getArguments().getStringArrayList("listofcontacts") != null)
                    arrayList.addAll(getArguments().<ContactModel>getParcelableArrayList("listofcontacts"));

            }
        }

    }

    @Override
    public void onDueListener(int position) {
        Log.d(TAG, "onDueListener: ");
        ContactModel contactModel = new ContactModel();
        contactModel.setContactName(arrayList.get(position).getContactName());
        contactModel.setContactNumberp(arrayList.get(position).getContactNumberp());
        contactModel.setState(true);
        Intent intent = new Intent(getActivity(), AddDue.class);
        intent.putExtra("userDetails", contactModel);
        startActivity(intent);

    }
}

public ListOfContactsRAdapter(Context context, OnContactListener a, ArrayList<ContactModel> arrayList) {
    Log.d(TAG, "ListOfContactsRAdapter: +" + arrayList.size());
    ContactListener = a;
    this.arrayList = new ArrayList<>();
    if (arrayList != null)
        this.arrayList.addAll(arrayList);
    mContext = context;
}

@NonNull
@Override
public CustomViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.loc_r_container, viewGroup, false);

    customViewHolder = new CustomViewHolder(view, ContactListener);
    return customViewHolder;
}

@Override
public void onBindViewHolder(@NonNull CustomViewHolder customViewHolder, int i) {
    customViewHolder.contactName.setText(arrayList.get(i).getContactName());
    customViewHolder.contactNumber.setText(arrayList.get(i).getContactNumberp());
    customViewHolder.contactDp.setText(String.valueOf(arrayList.get(i).getContactName().charAt(0)));

}

@Override
public int getItemCount() {
    Log.d(TAG, "getItemCount: ");
    return arrayList.size();
}

static class CustomViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    OnContactListener Listener;
    TextView contactName;
    TextView contactNumber;
    TextView contactDp;
    Button button;
    LinearLayout linearLayout;

    CustomViewHolder(@NonNull View itemView, OnContactListener mOnContactListener) {
        super(itemView);
        contactName = itemView.findViewById(R.id.contact_name);
        contactNumber = itemView.findViewById(R.id.contact_number);
        button = itemView.findViewById(R.id.action);
        contactDp = itemView.findViewById(R.id.contactDp);
        linearLayout = itemView.findViewById(R.id.container);
        linearLayout.setOnClickListener(this);
        Listener = mOnContactListener;
        button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Log.d(TAG, "onClick: ");
        Listener.onDueListener(getAdapterPosition());

    }
}

}

A: What i did is create an Interface in your RecyclerView Adapter:
public interface OnClickItem { // create an interface
    void onClickItem(int position); // create callback function
}

Then in OnBindViewHolder:
customViewHolder.(yourView).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               ContactListener.onClickItem(customViewHolder.getAdapterPosition());
            }
});

In your Fragment:
public class ListOfContacts extends Fragment implements ListOfContactsRAdapter.OnClickItem { ...

Implement the method:
@Override
  public void onClickItem(int position) {
  ...
  }


text:
Q: How to reverse serialize in django with many to many relations I have first made category crud, and then product crud with many-to-many relation with category.
models.py (category):
class Category(models.Model):
    name = models.CharField(max_length=191, blank=False, null=False)
    description = models.TextField(blank=True, null=True)

models.py (product):
class Product(models.Model):
    product_code = models.CharField(max_length=191, blank=False, null=False)
    name = models.CharField(max_length=191, blank=False, null=False)
    description = models.TextField(blank=False, null=False)
    price = models.DecimalField(max_digits=19, decimal_places=2)
    photo = models.ImageField(upload_to='pictures/products/', max_length=255, null=False, blank=False)
    category = models.name = models.ManyToManyField(Category)

How to achieve following result:
  {
        "categories": [
            {
                "id": 1,
                "name": "Indoor Muscle Training",
                "description": null,
                "products":{
                       "name":"product_name",
                       "code":"product_code"
                }
            },
            {
                "id": 2,
                "name": "Outdoor Muscle Training",
                "description": null,
                "products":{
                       "name":"product_name",
                       "code":"product_code"
                }
            }
        ]
  }

A: using serializer-method field can be an option for this case. Our goal is get product information from category serializer. So for this
class CategorySerializer(serializers.ModelSerializer):
    products = serializers.SerializerMethodField()

    class Meta:
        model = Category
        fields = ('') # add relative fields

   def get_products(self, obj):
       products = obj.product_set.all() # will return product query set associate with this category
       response = ProductSerializer(products, many=True).data
       return response


text:
Q: Resend emails via Exchange WebService API I've the requirement to resend Emails that were already sent. I don't have to change anything on the mail, only resend it to the original recipients. In the outlook client, it' possible via Message tab, in the Move group, click Actions, and then click Resend This Message.

A: It's simple:
EmailMessage message = EmailMessage.Bind(...);
EmailMessage.send();


text:
Q: How do I make a GenServer that processes messages at a specific rate? (every n seconds) One of my services talks to an external API that is rate-limited, so I want to ensure that I send no more than 1 call every 10 seconds.
My naive approach would be to have a long-running API service, and time it out after each call:
def handle_cast({:call_api, data}, state) do
  send_to_external_api(data)
  :timer.sleep(10000)
  {:noreply, state}
end

I'm not sure if there's a proper way to do this.

A: Edit: The original solution dropped messages in between 10s ticks, as burmajam suggested. The edit provides a more appropriate solution.

EDIT
Due to the fact that GenServer handle_* functions do not actually receive messages from the queue, but just process them, we cannot exploit pattern matching to receive selectively only each 10s from the processes queue.
Therefore, since we're picking up messages in order of their arrival, we need out internal queue as part of GenServer's state.
defmodule RateLimited do
  use GenServer

  def start_link do
    GenServer.start_link(__MODULE__, %{queue: []})
  end

  def init(state) do
    allow_work()
    {:ok, state}
  end

  def handle_cast({:call_api, data}, %{"queue" => queue} = state) do
    {:noreply, %{state | queue: queue ++ [data]}}
  end

  def handle_info(:work, %{"queue" => [data | queue]} = state) do
      send_to_external_api(data)
    allow_work()

    {:noreply, %{state | queue: queue}}
  end

  defp allow_work() do
    Process.send_after(self(), :work, 10000) # after 10s
  end

  defp send_to_external_api (data) do end
end

So we're just moving messages from process queue to state queue and we process the head when we signal ourselves that 10s have passed.
But in the end, we actually achieve the same result as if we put the process to sleep for 10 seconds. Your solution seems easier and achieves the same result.

The solution is based on How to run some code every few hours in Phoenix framework?
First, let your GenServer store a flag in its state (work = true/false).
Then let GenServer use Process.send_after to signal itself when it can work. You receive the signal in handle_info where you set the work state flag to true.
Now notice pattern matching on state in the handle_cast function: it will only pick up the message when work state flag equals true. Otherwise, messages will be put in the queue waiting.
And after you send the message to external service, you run Process.send_after again to schedule the next signal and return state which has work flag set to false to prevent next messages from being immediately picked up.
defmodule RateLimited do
  use GenServer

  def start_link do
    GenServer.start_link(__MODULE__, %{work: false})
  end

  def init(state) do
    allow_work()
    {:ok, state}
  end

  def handle_cast({:call_api, data}, %{"work" => true} = state) do
    send_to_external_api(data)
    allow_work()
    {:noreply, %{state | work = false}}
  end

  def handle_info(:work, state) do
    {:noreply, %{state | work = true}}
  end

  defp allow_work() do
    Process.send_after(self(), :work, 10000) # after 10s
  end
end


text:
Q: JSON requests and responses in WCF I am trying to make request and receive response from a WCF web service (written in c#) in JSON format.
This is the endpoint's configuration:
 <service behaviorConfiguration="UserServiceBehavior" name="UserService">
    <endpoint address="JSON" binding="webHttpBinding" contract="IUserService"
              behaviorConfiguration="JSONEndpointBehavior" bindingConfiguration="" name="RESTEP">
    </endpoint>
    <endpoint address="" binding="basicHttpBinding" contract="IUserService">
      <identity>
        <dns value="localhost"/>
      </identity>
    </endpoint>
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
  </service>

...
<endpointBehaviors>
    <behavior name="JSONEndpointBehavior">
      <webHttp/>
    </behavior>
  </endpointBehaviors>

The annotation on methods is something like this:
[WebInvoke(Method = "GET", UriTemplate = "myUriTemplate", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]

For methods returning a CLR type it works great: responses are in JSON format (and also requests, I suppose).
For methods returning non-CLR types (in my case, a proxy client) if I try to make requests and to receive responses in JSON the server brings me a 404 error, but if I cut off this:
RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json

the server replies with an XML document containing the data I'm searching for.
Could this be a problem related to the client proxy? How can I generate e client proxy which supports JSON serialization and de-serialization?
If I turn on the help page I can actually see the method in methods list, but I can't fire it from the URL.

A: Problem found. Thanks to the SvcTracingTool I've discovered that all of that was due to a serialization problem, as the exception raised says:

The InnerException message was 'The type 'xxxxxxxxx' cannot be serialized to JSON because its IsReference setting is 'True'. The JSON format does not support references because there is no standardized format for representing references. To enable serialization, disable the IsReference setting on the type or an appropriate parent class of the type.'.  Please see InnerException for more details.

Now, the next step is understand why WCF returned a 404 error instead of the exception.


text:
Q: A curious case of Print in VB6 I have this code in VisualBasic 6:
iLinha = FreeFile
Open strPath For Output As #iLinha
Dim strHeader As String

'***Assign a value to the string `Content`

Print #iLinha, strHeader

Now I'm trying to do the same of this code but using the Word.Application, you know ?
And When I code this:
Word.Selection.TypeText strHeader

All I got is just codes and characters like: {rtf1\ansi\ansipg1252\deff0....
Could anyone explain to me that code above ? The  Print #iLinha
Update
streamFile.Type = adTypeBinary
streamFile.Open
streamFile.Write rstAux.Fields("text")
streamFile.SaveToFile strCaminhoTemp, adSaveCreateOverWrite
streamFile.Close

Obs: I tried change the adTypeBinary to adTypeText but several errors ocurred...
maybe this code has something to do with my problem ?!!

A: Looks like strHeader is a formatted text, not a pure text.
Looks like strHeader at some point gets its value from an RTF (RichText) control and it gets a formatted text, not pure text.
more info on the RTF control: MSDN

A: Not sure why my post didn't get sent a while ago.  Anyway, as George pointed out, it's just RTF text.  My suggestion is that you apply the text to an RTF control and retrieve it back as plain text.  That will remove all the RTF code and leave you with the plain text that you so desire.
To do this, while your project is open in VB6, press Ctrl+T, and check "Microsoft Rich TextBox Control". You can add this new control to your form, but make it invisible. Then set the RTFText property to your strHeader, and grab the rich edit control's Text property.

A: To convert from the RTF format to Text format, you can write something like this manually, if you are not interested in using the RTF control, as you indicated - which I don't recommend:
Dim RTF As String
RTF = strHeader

Dim Text As String
Dim X As Long
Dim InTag As Boolean
Dim TagStarted As Boolean
For X = 1& To Len(RTF)
    Select Case Mid$(RTF, X, 1&)
    Case "{", "}"
        If InTag And Not TagStarted Then
            Text = Text & Mid$(RTF, X, 1&)
            TagStarted = True
        End If
    Case "\"
        If InTag And Not TagStarted Then
            Text = Text & Mid$(RTF, X, 1&)
            TagStarted = True
        Else
            InTag = True
            If Mid$(RTF, X, 5&) = "\par " Or Mid$(RTF, X, 4&) = "\par\" Or Mid$(RTF, X, 6&) = "\line " Or Mid$(RTF, X, 5&) = "\line\" Then
                Text = Text & vbCrLf
            End If
        End If
    Case " "
        If InTag Then
            InTag = False
        Else
            Text = Text & " "
        End If
    Case Else
        If InTag Then
            TagStarted = True
        Else
            Text = Text & Mid$(RTF, X, 1&)
        End If
    End Select
Next X

MsgBox Text

Please note, that there is likely a few tweaks that may have to be made, as the code was quickly written.


text:
Q: locationManager didEnterRegion not called in XCode 9 Simulator I have an app that does geofencing.  When I run it in the Simulator (Xcode 8.3.3 and Xcode 9), everything seems to work with the exception that my CLLocationManager didEnterRegion is never called.
It is called just fine when I run the app on my iPhone, either out in the real world (entering a region) or in Xcode via location simulation.
Any idea why this would be?
One difference I've discovered is that the simulator only supports monitoring location when in use, so I had to set things up so I had had both permission strings in my plist file, but other than that I'm stumped.
Since I'm not providing code (it's way too complex and distributed in my app), let me note what is working in the simulator:

*

*In my app's scheme, I have 'Allow Location Simulation' checked and I have a have a few .gpx files added for locations I'm monitoring. I have a default location set.

*My location manager delegate is being called when I start up. I get .authorizedWhenInUse in the Simulator and .authorizedAlways on the phone.

*locationManager(:didUpdateLocations:) is being called when the location changes.

*When didUpdateLocations is called, I do the following:
for r in manager.monitoredRegions {
    if let cr = r as? CLCircularRegion {
        if cr.contains(location.coordinate) {
            log.debug("Am in the region!")
        } else {
            let crLoc = CLLocation(latitude: cr.center.latitude,
                                  longitude: cr.center.longitude)
            log.debug("distance is: \(location.distance(from: crLoc))")
        }
}

and it works.  So my regions are being monitored and my location is where I think it should be.

*Finally, my locationManager delegate's monitoringDidFailFor and didFailWithError are NOT being called.  Not that they've never been - they have during development, but not now.
So I'm stumped. Again, it works fine on the phone and not in the simulator.
What am I doing wrong?

A: Ok, I found the problem. First, there is a change needed for Xcode 9/iOS 11. I had filed a bug with Apple and received the following:

In iOS11 all applications must support WhenInUse authorization if they
  support Always authorization. With this change the Location Services usage
  description keys have changed. For an application to get an Always prompt to
  show they must have both NSLocationAlwaysAndWhenInUseUsageDescription and
  NSLocationWhenInUseUsageDescription in their App's Info.plist.

So if you are calling: locationManager.requestAlwaysAuthorization(), for iOS 11, you need to have both NSLocationAlwaysAndWhenInUseUsageDescription and NSLocationWhenInUseUsageDescription.   If you want your app to keep working on pre-iOS 11 you need to also keep the NSLocationAlwaysUsageDescription, so you'll have 3 keys.
I confirmed this with Ray Wenderlich tutorial that Kuhncj's referenced. As is, it doesn't work with Xcode 9, but does with Xcode 8.
My problem was an error in my part. While I had the 3 correct keys, but in reviewing where I asked for permissions, I had the following:
var permission : Permission = SimulatorPlatform.isSimulator ? .locationWhenInUse : .locationAlways
So I was basically running different code for the simulator vs the device.  After changing that, my app did get called arriving at a monitored region.

A: For iOS 11 use the following in your info.plist:
  <key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
  <string>Need Location</string>

  <key>NSLocationAlwaysUsageDescription</key>
  <string>Need Location</string>

  <key>NSLocationWhenInUseUsageDescription</key>
  <string>Access For Location</string>


text:
Q: Comparación con el operador lógico and (&&) entre un dato tipo string y uno parseado con parseInt: ¿es posible en Javascript? En este código la idea inicial era agregar un solo if para las dos variables, es decir, plantearlo con el operador lógico &&... pero en ese caso la variable "tipoArroz" al ser un string y la "variableCantidad" al ser un dato parseado, no se pueden poner juntas y que el condicional if lo tome como válido. En otras palabras, cuando se probó el hacer eso, en vez de saltar el alert "no se ingresaron datos", la función seguía ejecutándose y saltaba el alert de la función pero arrojando NaN.
¿Cómo se pudieran juntar en un solo condicional if a esas dos variables declaradas con let, con el operador lógico &&, si uno es un string y el otro un dato parseado con parseInt? ¿habría que parsear luego o incluso no parsear?
Así se probó esta porción del código con un solo condicional if y no funcionó:
if (tipoArroz && variableCantidad == "") {
      alert("No se ingresaron datos")
      continue
}

Por lo tanto tuvo que dividirse en dos condicionales, así:
//VARIABLES Y CONSTANTES

let tipoArroz = prompt("Ingrese tipo de arroz que comera")

console.log(tipoArroz);

//CONDICIONAL #1

if (tipoArroz == "") {

alert("No se ingresaron datos")

continue

}

let variableCantidad = parseInt(prompt("Ingrese cantidad de personas que comeran"));

//CONDICIONAL #2

if (variableCantidad == "") {

alert("No se ingresaron datos");

continue

}

¿De qué manera se podría mejora u optimizar esto? ¿Es correcto el planteamiento con un solo if para mejorarlo o debería dejarse así como está?

A: No se si lo he entendido bien porque en realidad tu la consulta la puedes hacer sobre el mismo if con cada variable por separado. Te dejo aquí un ejemplo en el que compruebo si el tipoArroz es vacío y si la variableCantidad es 0:

var tipoArroz="";
var variableCantidad=0;

if (tipoArroz=="" && variableCantidad == 0) {
      alert("No se ingresaron datos");
}

Si lo que quieres comprobar es si se cumple una de las 2 condiciones, entonces tienes que utilizar el or:

var tipoArroz="";
    var variableCantidad=0;

    if (tipoArroz=="" || variableCantidad == 0) {
          alert("No se ingresaron datos");
    }

Un saludo!


text:
Q: Node Error on installing custom script I have some code that a programmer made for our company using Node 0.10 that I am trying to update to node 6.9 in a dev environment. I am not a Node guru, this is a project helping me to learn Node and the code left for us.
When I run the reccomended install script, I get this error:
# node install.js --production
path.js:7
    throw new TypeError('Path must be a string. Received ' + inspect(path));
    ^

TypeError: Path must be a string. Received undefined
    at assertPath (path.js:7:11)
    at Object.dirname (path.js:1324:5)
    at new daemon (/var/www/ClientResponder/node_modules/node-linux/lib/daemon.js:208:30)
    at Object.<anonymous> (/var/www/ClientResponder/install/install.js:13:11)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)

I look at the file install.js, line 11 starts off like this:
/**
 * Created by Tim.
 */

var Service = require('node-linux').Service;

var env = null;
if(process.argv.length === 3){
    env = process.argv[2] === "--production" ? "production" : "staging";
}

// Create a new service object
var svc = new Service({
    name:'Client Responder',
    description: "Optional web server which can be deployed to a Media Server providing user clients the ability to ping the server for speed tests.",
    script: '/var/www/ClientResponder/server.js',
    env: [{
        name: "NODE_ENV",
        value: env ? env : "staging"
    },{
        name: "PORT",
        value: 8888
    }]
});

// Listen for the "install" event, which indicates the
// process is available as a service.
svc.on('install',function(){
    svc.start();
});

svc.install();

I didn't see anything there about the path, so I look at the daemon.js file at line 208 and get this:
cwd: {
  enumerable: false,
  writable: true,
  configurable: false,
  value: config.cwd || p.dirname(this.script)
},

What am I missing here? I realize it is hard to know when you don't have full access to all source code, what more can I provide that would help short of full access?

A: The suggested workaround here is to follow this issue.
And change:
var svc = new Service({
    name:'Client Responder',
    description: "Optional web server which can be deployed to a Media Server providing user clients the ability to ping the server for speed tests.",
    script: '/var/www/ClientResponder/server.js',
    env: [{
        name: "NODE_ENV",
        value: env ? env : "staging"
    },{
        name: "PORT",
        value: 8888
    }]
});

To:
var svc = new Service({
    name:'Client Responder',
    description: "Optional web server which can be deployed to a Media Server providing user clients the ability to ping the server for speed tests.",
    script: 'server.js', // here
    cwd: '/var/www/ClientResponder/', // and here
    env: [{
        name: "NODE_ENV",
        value: env ? env : "staging"
    },{
        name: "PORT",
        value: 8888
    }]
});


text:
Q: ASP .NET MVC 4 IValidatableObject calling frequency/timing I am trying to understand the communication between client and server within the context of an IValidatableObject.
I have a ViewModel with one of the properties, CompanyId, decorated with [Remote("ValidateCompanyId", "Home")].
In my "Home" controller, of course, I have the ValidateCompanyId action.
The view has a textbox for CompanyId.  When the view is first displayed, I can type as much as I want into the text box and there is no interaction with the server.  When the text box loses focus, the ValidateCompanyId action is called.  If the validation fails, I get my error message back in the view.  So far, so good.
At this point, however, each subsequent keystroke makes a call to the server.  For example, if I originally typed 8500 and got an error, if I want to change my value to 8200, I am seeing server calls for 850, then 85, then 8, then 82, then 820, then, finally, 8200.
I think I would prefer that the validation call wait for the text box to lose focus again (as it does at first).  Particularly, in this case, because the validation requires a database call.  What controls this?

A: That's the default behavior. Before a field is marked as invalid, validation is lazy allowing you to tab through controls, but once its marked as invalid, it is eagerly validated (Refer documentation). You can prevent validation on keyup using the following script
var validator = $("form").data("validator");
if (validator) {
  validator.settings.onkeyup = false;
}

Note this disables keyup validation for all controls. If you want it for only one control try (not tested)
$(yourSelector).keyup(function() { return false } );


text:
Q: Disable Interval Label from AxisY as the title says, I need to disable Interval Labels from AxisY but only mantaining the extremes maximum and minimum axis y labels, is this possible?
I searched at this website and there nothing like my question...
Also, I need to know if the maximum axis y label and minimum axis y label can be rotated +45° and -45° respectively
Thank you!

A: I think you will have to use two CustomLabels.
Note the they all must have the same angle.
Use a suitable delta, i.e. a small number that determines the range of the label, and a suitable format..
ChartArea ca = chart1.ChartAreas[0];
Series series = chart1.Series[0];
double delta = 0.1;

double yMin = series.Points.Min(x => x.YValues[0]);
double yMax = series.Points.Max(x => x.YValues[0]);
CustomLabel clyMax = new CustomLabel();
CustomLabel clyMin = new CustomLabel();

clyMax.FromPosition = yMax - delta;
clyMax.ToPosition = yMax + delta;
clyMin.FromPosition = yMin - delta;
clyMin.ToPosition = yMin + delta;

clyMax.Text = yMax.ToString("0.0");
clyMin.Text = yMin.ToString("0.0");

ca.AxisY.LabelStyle.Angle = 45;

ca.AxisY.CustomLabels.Add(clyMax);
ca.AxisY.CustomLabels.Add(clyMin);


text:
Q: Hangfire Autofac integration is not able to resolve service with registred dependency I'm using hangfire to lauch background job but I have a problem when I try to use the hangfire autofac integration with generic to resolve automaticly the task service it's not working because it's is not able to be resolve one of the dependency. I suppose because I don't receive any error.
 BackgroundJob.Enqueue<IBackgroundTask>(x => x.RunAsync() );

If I use the other way around by resolving by myselft it's working.
 var service = ApplicationContainer.Resolve<IBackgroundTask>();
 BackgroundJob.Enqueue(() => service.RunAsync() );

I figured out that in my constructor I have a test service that cause the problem. If I remove the service in the constructor the service get resolved.
    public class ConvertCarteCreditService : IBackgroundTask
    {
      private readonly ILogger logger;
      private readonly ITest testService;

      public BackgroundTask(ILogger logger, **ITest test**)
      {
        this.logger = logger;
        this.testService = test;
        // this.testService = Startup.Resolve<ITest>();
      }

I have configured autofac in the startup class like this :
    public void ConfigureServices(IServiceCollection services)
    {

     var builder = new ContainerBuilder();

     ServiceLayerInstaller.ConfigureServices(builder);
     DataLayerInstaller.ConfigureServices(builder, connectionString,  readOnlyConnectionString);

     builder.RegisterAssemblyTypes(typeof(WorkerRoleInstaller).
GetTypeInfo().Assembly).Where(t => t.Name.EndsWith("Test"))
.AsImplementedInterfaces();

     WorkerRoleInstaller.ConfigureServices(builder);

     builder.Populate(services);
     ApplicationContainer = builder.Build();

     var autofacJobActivator = new AutofacJobActivator(ApplicationContainer);

     GlobalConfiguration.Configuration.UseActivator(autofacJobActivator);

    }

A: I found my probleme was that I didn't return the service provider** from the configures services function but instead create the function as void and return nothing.
    public **IServiceProvider** ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        services.AddDirectoryBrowser();
        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

        var builder = new ContainerBuilder();

        builder.Populate(services);

        ServiceLayerInstaller.ConfigureServices(builder);

        WorkerRoleInstaller.ConfigureServices(builder);

        ApplicationContainer = builder.Build();

        var autofacJobActivator = new AutofacJobActivator(ApplicationContainer, false);
        GlobalConfiguration.Configuration.UseActivator(autofacJobActivator);

        **return new AutofacServiceProvider(ApplicationContainer);**
    }


text:
Q: Does mysql have path separators functionality? For instance, in Nodejs you have path.sep, in Java you have File.separator. Do you have something similar in mysql? If not, which would be the best way to deal with path separators in a way that works in any operating system?
I need it so I can pass correct paths to the LOAD_FILE() function without worrying about current operating system.

A: I found that I could pass the value of path.sep or File.separator in a parameterized query:
"insert into MY_TABLE (file_contents) values (LOAD_FILE(?))", my_folder+File.separator+filename

Not what I was really looking for, but at least works for me.


text:
Q: How to use constants for enums in SQL Server How do people deal with constants in SQL that represent things like enums in software?
For example, I have an enum in my C# project
enum SocialMedia
{
Twitter = 1,
Facebook = 2
}

in the database, ideally I don't really want to write things like:
WHERE SocialMediaType = 2

(also next week I might add to the enum, such as Instagram = 3 and this would possibly need lots of stored procedures to change)


text:
Q: Error when calling API in Front using React I have an error that shows when I try to click button to subscribe. This is the error message in browser console:

Access to fetch at 'https://api.exhia.com/api/accounts/addaccount' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

This the the code example that handle the click:
 handleFormSubmit(event) {
    event.preventDefault();
    this.setState({ msg: 'checked' });
    const validation = this.validator.validate(this.state);
    this.setState({ validation });
    this.submitted = true;
    if (
      this.state.checked === true &&
      validation.subConfirm_pwd.isInvalid === false
    ) {
      fetch(`${API}/api/accounts/addaccount`, {
        method: 'POST', // 'GET', 'PUT', 'DELETE'
        body: JSON.stringify({
          email: this.state.sub_mail,
          password: this.state.sub_pwd,
          acceptCGU: this.state.checked,
        }),
        headers: {
          'Content-Type': 'application/json;charset=utf-8',
          Accept: 'application/json',
        },
      })
        .then(res => res.json())

.....

I am working on prod to handle this issue, this is my webpack.config:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
var OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");

module.exports = {
    mode: 'production',
    entry: './src/index.js',
    output: {
        path: path.resolve(__dirname, 'build'),
        publicPath: '/',
        filename: 'bundle.js'
    },
    devServer: {
        contentBase: path.join(__dirname, './build'),
        compress: true,
        port: 3000,
        historyApiFallback: true,
    },
    performance: {
        hints: false,
        maxEntrypointSize: 512000,
        maxAssetSize: 512000
    },
    module: {
      rules: [
        {
          test: /\.(css|sass|scss)$/,
          use: [
            MiniCssExtractPlugin.loader,
            {
              loader: 'css-loader',
              options: {
                sourceMap: true,
                importLoaders: 2
              },
            },
            {
              loader: 'sass-loader',
              options: {
                sourceMap: true,
              },
            },
          ],
        },
        {
          test: /\.(js|jsx)$/,
          exclude: /node_modules/,
          use: {
            loader: "babel-loader"
          }
        },
        {
          test: /\.(png|svg|jpg|gif)$/,
          use: ["file-loader"]
        },
        {
            test: /\.(woff(2)?|ttf|otf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
            use: [
              {
                loader: 'file-loader',
                options: {
                  name: '[name].[ext]',
                  outputPath: 'fonts/'
                }
              }
            ]
        }
      ]
    },
     //remove comments from JS files
    optimization: {
        minimizer: [
        new UglifyJsPlugin({
            uglifyOptions: {
            output: {
                comments: false,
            },
            },
        }),
        new OptimizeCSSAssetsPlugin({
            cssProcessorPluginOptions: {
            preset: ['default', { discardComments: { removeAll: true } }],
            }
        })
        ],
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: "[name].css"
        }),
        new ManifestPlugin(),
        new CleanWebpackPlugin(),
        new HtmlWebpackPlugin({
            template: path.resolve('./public/index.html'),
        }),
    ]
};

I am not sure where the bug comes from. How can I fix it?

A: http://localhost:3000 has been blocked by CORS policy so All you need to do is add an HTTP header to the server which serves your API. That means changing the API.
In your case this is either ( fatboar.extia.com ) or (api.exhia.com) - I can't tell which as you seem to use them interchangeably in your question / comments.
This site provides details on how to do that: https://enable-cors.org/server.html - should you need further guidance I would investigate how to add header for your particular platform. You should be able to see the header coming back in a tool like Postman (https://www.getpostman.com/) - I would explore the API first with that to check the header, then proceed with your code in the browser.
1) Access-Control-Allow-Origin: http://localhost:3000

Note. When you move to production, you may need to change the above to match the server making the call. So for example, locally at the moment you are hosting the app on localhost:3000. When you move to production assuming you are hosting on blah.com, your access control header would also need to change.
2) Access-Control-Allow-Origin: http://blah.com

Do not be tempted by answers suggesting a wild card e.g.
3) Access-Control-Allow-Origin: *

This will allow any authorised person to access the API from any domain, which is likely not what you want. So any site can make a request to your site on behalf of their visitors and process its response.

A: This is because you are trying to call a service which is running in different server.
More on cors issue
If it is for development environment, you should be using some kind of proxy for example webpack Dev server proxy
Another option is to disable the cors check in browser by some kind of plug in, simple search in chrome app store will give you many plug ins.


text:
Q: Running gradlew lint on specific file(s) I'm trying to create pre-commit hook with code style check and other errors. It's a multi-module project in Android Studio (java and kotlin).
I was hoping to use lint, but no luck.
My condition is to check only new and modified files (baseline is in order ofc) as the project is way too big to run checks on every commit on every file.
My sh command looks like this:
git diff --name-only HEAD | xargs -I '{}' ./gradlew lint {}\;

It translates to:
./gradlew lint /path/to/the/file.java

But it always fails on trying to find task called "the path to the file".
When I try to use lint from Android SDK it just prints main: Error: "main" is a Gradle project. To correctly analyze Gradle projects, you should run "gradlew :lint" instead.
Any advice?

A: You can use Library/Android/sdk/tools/bin/lint for specific files


text:
Q: Case insensitive search in ElasticSearch? I forced with problem searching by email. Email has keyword type. Some users add an email with capital letters, so I can't search all of them via term construction. Locally I tried to change keyword to text but the new problem has appeared.
Example: search by email@gmail.com - elastic splits this email to several parts and returns wrong results: email@site.com, new@gmail.com and etc.
What is the best way to do this kind of search via elastic? (it would be better to avoid full reindex)
ElasticSearch 6.6.1
"mappings": {
        "_doc": {
            "properties": {
                "email": {
                    "type": "text"
                }

A: You will have to reindex your index (or add a secondary field with unsensitive case analyzer and query on this field, delete the first field and rename fieldname, but it will be a little more complicated maybe ). Indeed, as if you could add an analyzer by closing and reopening index, elastic have to reindex older data.
For the analyzer a lowercase should be ok in your case.
    "analyzer":{
      "analyzer_lowcase":{
        "tokenizer":"keyword",
        "filter":"lowercase"
      }


text:
Q: How to produce html text in UI popup using Google Apps Script? I have the following Google Apps Script:
function popUp() {
const ui = SpreadsheetApp.getUi();
var message = ""
  + "The meeting is at 10am."
  + "";

var popUP = ui.alert(message, ui.ButtonSet.OK);
}

When I apply this function to a button in my Google Sheets, the popup pops up as expected.
However, the text in the popup carries all the "messy" HTML coding.
How can I get the popup to show actual HTML formatted text?
In other words, how can I make the UI popup use the HTML-laden text I added for var message but in a way that actually formats the text to use the HTML I added?
IS there some kind of HTML wrapper function?

What I get vs what I want:

A: Here's a simple example closer to what you want. I don't think the alert takes html. It requires simple ascii text. Note: google.script.host.close() doesn't work when deployed as a web app.
function popUp() {
  var s='The meeting is at 10:30AM.
<input type="button" value="OK" onClick="google.script.host.close();" />';
  SpreadsheetApp.getUi().showModalDialog(HtmlService.createHtmlOutput(s), 'PopUp');
}

See this in the 'Custom Dialog' documentation for Apps Script: https://developers.google.com/apps-script/guides/dialogs