text:
Q: How can I efficiently filter and store maximum and minimum x,y pairs from a large list in Python? I have a loop function to calculate 2 values of the combinations of one list:
xyList = []
for i, j in itertools.combinations(mx, 2):
    x= *some calculation*
    y= *some calculation*
    xyList.append([x,y])

However, the combinations of the list are too many, there is always a MemoryError. Therefore, I tried to only keep the unique value:
    p=[x,y]
        if not (p in xyList):
            xyList.append(p)

But there is still a MemoryError. Now I'm thinking of only keeping the maximum y and minimum y for each x, i.e., the outline of this x, y scattered shape. But I cannot come up with an efficient way to do that. What is the possible solution?

A: You should probably make xyList a dictionary instead. Let's say we call this xy_limits. Each value of xy_limits can be a list which keeps track of the minimum and maximum as its elements. When you encounter a y value that is outside this range, you can replace the correct value. Consider:
xy_limits = {}
for i, j in itertools.combinations(...):
    ...
    if x not in xy_limits:
        xy_limits[x] = [y, y]
        continue

    old_limits = xy_limits[x]
    if y < old_limits[0]:
        old_limits[0] = y
    elif y > old_limits[1]:
        old_limits[1] = y

Since old_limits is a list (a mutable type) modifications to that variable (e.g. by assigning one of its elements) will be seen in all occurrences of the list, such as that in the original xy_limits


text:
Q: Undefined method `to_criteria' with Rails 4.2.7, Pundit, Mongoid and RailsAdmin I have a Rails 4.2.7 app with rails_admin (0.8.1), pundit (1.1.0) and mongoid (5.1.4)
I created Campaign scaffold and added authorize @campaign to set_campaign in CampaignController.  when I browse to http://localhost:3000/campaigns/57b34dd3f5740c23d3066e43 I get unable to find policyCampaignPolicyfor <Campaign _id ...
I ran rails g pundit:policy campaign to create CampaignPolicy and now show action works.  But when I browse to RailsAdmin http://localhost:3000/admin/campaign I get:
undefined method `to_criteria' for Campaign:Class
lib/mongoid/criteria.rb merge! method

I "solved" it by modifying Scope inside CampaignPollicy like this but I am wondering if there is a better solution
class CampaignPolicy < ApplicationPolicy
  def show?
    true
  end
  class Scope
    attr_reader :user, :scope
        def initialize(user, scope)
      @user = user
      @scope = scope
    end
    def resolve
    end
  end
end

A: OK, figured it out and thought I'd share the answer.
class CampaignPolicy < ApplicationPolicy
  ...
  class Scope
    def resolve
      if @user.admin?
        scope.all  # this prevents undefined method `to_criteria'
      else
        scope.where(...) # put some biz logic here
      end
    end
  end
end

redpajama_set_name: RedPajamaStackExchange


text:
Q: HTML 'behind' Javascript therefore preventing any text being seen I have been playing around with this Javascript but I can never get the HTML to be visible on the page. Here is my HTML code and once I open the page I do not see anything except for the canvas particle network.

<title></title>

<link rel="stylesheet" href="main.css">

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

 text

 Test

Once I open the page, I do not see text or Test. What am I doing wrong? If needed, the JavaScript that is running can be found here.

A: That is because your selector is applied to the html element itself, which means your whole page.

You need to remove id="particle-canvas" attribute from the html tag and apply it to a child element in the page.
Ex:

        <title></title>

        <link rel="stylesheet" href="main.css">

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

 text

 Test

Hope it helps :)


text:
Q: Appmaker - combine fields from two datasources I have two DATASOURCES in Google App Maker (both Google Drive Table's).
One is: Employee
The other is: Department
I have created a relation between the two DATASOURCES (one to one) and can't figure out how to create a PAGE with a combination of fields from both DATASOURCES.
Any help is appreciated.

A: *

*You need to add prefetch for your relation (in datasource settings)

*If your main datasource is Employee, then in widget bindings you can access department with code similar to this:
@datasource.item.Department.Name


text:
Q: Send Scheduled Email using email Templates in .NET MVC3 using C# I am working on a .NET MVC3 Web Application
In this my goal is to send Scheduled E-mail in which I will be using E-mail Templates.
I am so confused what should I follow to acquire my goal.
I tried MVC Mailer. But It doesn't works with Scheduler.(Fluent Scheduler)
I tried using RazorEngine with Email templates but somehow not succeeded in attaching HTML Email Templates.
Please Help...

A: Using RazorEngine something like this should help, is very straightforward:
public bool SendEmailMessage(string template, object viewModel, string to, string @from, string subject, params string[] replyToAddresses)
    {
       var compiledTemplate = LoadTemplate(template, viewModel);

       return  SendEmail(from, to, subject, compiledTemplate, from, null, replyToAddresses);

    }

public bool SendEmailMessageWithAttachments(string template, object viewModel, string to, string @from, string subject, List<Attachment> attachedFiles, params string[] replyToAddresses)
        {
            var compiledTemplate = LoadTemplate(template, viewModel);
            return SendEmail(from, to, subject, compiledTemplate, from, attachedFiles, replyToAddresses);
        }

 public string LoadTemplate(string template, object viewModel)
        {
            var templateContent = AttemptLoadEmailTemplate(template);
            var compiledTemplate = Razor.Parse(templateContent, viewModel);

            return compiledTemplate;
        }

    private string AttemptLoadEmailTemplate(string name)
    {
        if (File.Exists(name))
        {
            var templateText = File.ReadAllText(name);
            return templateText;
        }

        var templateName = string.Format("~/Data/EmailTemplates/{0}.html", name); //Just put your path to a scpecific template
        var emailTemplate = HttpContext.Current.Server.MapPath(templateName);

        if (File.Exists(emailTemplate))
        {
            var templateText = File.ReadAllText(emailTemplate);
            return templateText;
        }

        return null;
    }

    private bool SendEmail(string from, string to, string subject, string body, string replyTo, List<Attachment> attachedFiles, params string[] replyToAddresses)
            {
                replyTo = replyTo ?? from;
                attachedFiles = attachedFiles ?? new List<Attachment>();

                var message = new MailMessage(from, to, subject, body);
                message.ReplyToList.Add(replyTo);

                foreach (var attachedFile in attachedFiles)
                    message.Attachments.Add(attachedFile);

        try
        {
            smtpClient.SendAsync(email, null);
            return true;
        }
        catch (Exception exption)
        {
            return false;
        }
      }

Hope it helps
EDIT:
Suppose you have a template called "TestTemplate":
Dear @Model.Name
Just imagine like if this were a normal cshtml view and put your model properties like this: @Model.SomeProperty
Cheers.
With the previous template located in the path I prefixed in my helper method AttempLoadEmailTemplate, then you can send an email like this:
var viewModel = new { Name = "Aks", SomeProperty = "Foo" };

mailService.SendEmailMessage("TestTemplate", viewModel, "aks@gmail.com", "daniel@gmail.com", "testing razor engine", null);


text:
Q: Laravel group by not working if only one key exists? I have this following code:
        $groupedRates = $result->rates->groupBy('minimum_age');

when I try to return it, I get this:
  "rates": [
                [
                    {
                        "id": 1,
                        "cpf_scheme_id": 1,
                        "minimum_age": 0,
                        "minimum_wage": 0,
                    },
                    {
                        "id": 2,
                        "cpf_scheme_id": 1,
                        "minimum_age": 0,
                        "minimum_wage": 750,
                    }
                ]
            ]

however, if I were to add one more key, it returns an associative array as expected.
  "rates": {
                "0": [
                    {
                        "id": 1,
                        "cpf_scheme_id": 1,
                        "minimum_age": 0,
                        "minimum_wage": 0,
                    },
                    {
                        "id": 2,
                        "cpf_scheme_id": 1,
                        "minimum_age": 0,
                        "minimum_wage": 750,
                    }
                ],
                "50": [
                    {
                        "id": 4,
                        "cpf_scheme_id": 1,
                        "minimum_age": 50,
                        "minimum_wage": 100,
                    }
                ]
            }

How do I fix this? It will break apis if it returns an associative array sometimes and a normal array other times!


text:
Q: cordova build ios but error in 'Cannot read property 'toLowerCase' of undefined' I use ionic3 and cordova@8.1.2. Recently my Xcode update to 11.1 and error occured [Cannot read property 'toLowerCase' of undefined].I tried this way:
change:
if (device.name === deviceType.name.replace(/\-inch/g, ' inch') &&
    device.availability.toLowerCase().indexOf('unavailable') < 0) {
    availAcc.push(device);
 }

to:
if (device.name === deviceType.name.replace(/\-inch/g, ' inch')) {
if ((device.availability && device.availability.toLowerCase().indexOf('unavailable') < 0)
|| device.isAvailable == 'YES') {
// XCode 10 and lower
availAcc.push(device);
}
}

Then error occurred in
Cannot read property 'name' of undefined

I cannot find where is this 'name'.

A: Remove platform ios and again add platform ios.
It's working for myself.
cordova platform rm ios
cordova platform add ios

A: My cordova version is 8.1.2. I encountered the same problem recently on ios.Please check your Android or Ios version and make it to latest if you're using older version of it. You don't need to add/modify any code to list-emulator-build file(cordova/lib/list-emulator-build).
It'll be certainly working. latest version of ios is ios(5.0.1).

A: Steps to solve this error:

*

*Connect your iPhone device.

*Open Xcode and select your iPhone device.

*Run command in terminal: ionic cordova build ios


text:
Q: My name includes space - How do I enter my username when typing command? My username in Minecraft is sun solar arrow. This name includes spaces.
Situation - When I want to get OP privilege, a user who has OP privilege will enter:
/op sun solar arrow

But my username includes spaces. So it shows an error message:

Invaild syntax

How do I enter my username?

A: If you surround your name in quotes, the game will read it literally. That means that spaces, brackets, etc will be interpreted as their real characters rather than part of the syntax of the command.
For instance:
/op "sun solar arrow"
/tp "angussidney" ~ ~10 ~

A: From the server console you can do: op @p[name="solar arrow"].


text:
Q: Applied PATCH_SUPEE-6285 - Do I need to do anything else? After being prompted to install the new patch I went ahead and did so straight away.
But now I've gone back and looked at the .sh file I noticed there is changes being made to template files.
I had a custom theme and I also have a onestep checkout extension installed on my site, do I need to apply the patch to those somehow or do I not need to worry?

A: Look at the changes that have been made to the template files. If your custom theme contains these templates (which is most likely with the cart.phtml template), you have to apply the same changes manually in the theme's templates.

A: There's a series of changes you need to make in addition to just running the patch.
I've used the 1.9.1.1 patch as an example here, but sadly, the patches differ dependent on release.

Custom template files
If you have modified or overridden the base/default template with your own package/design, then you'll need to manually apply the patches as necessary to the following.
In app/design/frontend/base/default/template/checkout/cart.phtml,
- <button type="button" title="<?php echo $this->__('Continue Shopping') ?>" class="button btn-continue" onclick="setLocation('<?php echo $this->getContinueShoppingUrl() ?>')"><?php echo $this->__('Continue Shopping') ?></button>
+ <button type="button" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Continue Shopping')) ?>" class="button btn-continue" onclick="setLocation('<?php echo Mage::helper('core')->quoteEscape($this->getContinueShoppingUrl()) ?>')"><?php echo $this->__('Continue Shopping') ?></button>

In app/design/frontend/base/default/template/checkout/cart/noItems.phtml,
-
<?php echo $this->__('Click here to continue shopping.', $this->getContinueShoppingUrl()) ?>

+
<?php echo $this->__('Click here to continue shopping.', Mage::helper('core')->quoteEscape($this->getContinueShoppingUrl())) ?>

In app/design/frontend/base/default/template/checkout/onepage/failure.phtml
-
<?php echo $this->__('Click here to continue shopping.', $this->getContinueShoppingUrl()) ?>

+
<?php echo $this->__('Click here to continue shopping.', Mage::helper('core')->quoteEscape($this->getContinueShoppingUrl())) ?>

In app/design/frontend/base/default/template/rss/order/details.phtml,
- <?php echo $this->__('Customer Name: %s', $_order->getCustomerFirstname()?$_order->getCustomerName():$_order->getBillingAddress()->getName()) ?>

- <?php echo $this->__('Purchased From: %s', $_order->getStore()->getGroup()->getName()) ?>

+ <?php $customerName = $_order->getCustomerFirstname() ? $_order->getCustomerName() : $_order->getBillingAddress()->getName(); ?>
+ <?php echo $this->__('Customer Name: %s', Mage::helper('core')->escapeHtml($customerName)) ?>

+ <?php echo $this->__('Purchased From: %s', Mage::helper('core')->escapeHtml($_order->getStore()->getGroup()->getName())) ?>

In app/design/frontend/base/default/template/wishlist/email/rss.phtml,
- <?php echo $this->__("RSS link to %s's wishlist",$this->helper('wishlist')->getCustomerName()) ?>
+ <?php echo $this->__("RSS link to %s's wishlist", Mage::helper('core')->escapeHtml($this->helper('wishlist')->getCustomerName())) ?>

In app/design/frontend/default/modern/template/checkout/cart.phtml,
- <button type="button" title="<?php echo $this->__('Continue Shopping') ?>" class="button btn-continue" onclick="setLocation('<?php echo $this->getContinueShoppingUrl() ?>')"><?php echo $this->__('Continue Shopping') ?></button>
+ <button type="button" title="<?php echo Mage::helper('core')->quoteEscape($this->__('Continue Shopping')) ?>" class="button btn-continue" onclick="setLocation('<?php echo Mage::helper('core')->quoteEscape($this->getContinueShoppingUrl()) ?>')"><?php echo $this->__('Continue Shopping') ?></button>

.htaccess rules
If you aren't using a .htaccess compatbile web server, then you'll need to manually add the following deny rules.
For Nginx,
location /downloader/Maged/ { deny all; }
location /downloader/lib/   { deny all; }

File permissions
If the user of your web server PHP process isn't the owner of the document root and relies on group permissions, and the var/report or var/log directories are removed - you will encounter issues with the new default file permissions.
Eg. In the following scenario,
PHP User:        www-data
Doc Root User:   sonassi
Doc Root Group:  www-data
www-data members: sonassi, www-data

The revised default file permissions of 0750,  will strip write permissions from the group - which will prohibit your web server from being able to write to the directory.
Equally, if you rely on the everyone permission, all access will be stripped.


text:
Q: Title below Pie charts We are using Highcharts in our UI. I need to have a title shown in the picture. Could you please tell me the way?

A: Set title verticalAlign property to 'bottom':
title: {
    text: 'Browser market shares in January, 2018',
    verticalAlign: 'bottom'
}

Live demo: https://jsfiddle.net/BlackLabel/cd2wyz3g/
API: https://api.highcharts.com/highcharts/title.verticalAlign


text:
Q: Point Cloud library pose estimation given a pre-existing model as truth PCL's github directs these questions here so I don't really know where else to ask this.
I'm trying to implement pose estimation given a mesh and a generated point cloud.  Using PCL, I know you can do pose estimation with two point clouds from the tutorial. In my case I have an accurate faceted model of my target object. Does there exist a PCL pose estimator that can consume faceted truth models? I would like to avoid using mesh_sampling or mesh2pcd as a work around.
Googling does not bring any results relevant to my search with the following 54 terms

*

*point cloud library pose estimation with

*

*mesh

*triangles

*facets

*truth data

*model truth data

*model

*mesh truth data

*vertexes

*vertices

*point cloud library point set registration with

*

*(above)

*point cloud library registration with

*

*(above)

*point cloud library 6DOF with

*

*(above)

*point cloud library pose with

*

*(above)

*point cloud library orientation with

*

*(above)

Maybe I don't know the right words to search?
but it appears like it might be possible, because functors like this
 pcl::SampleConsensusPrerejective<PointNT,PointNT,FeatureT>

and this
 pcl::Registration< PointSource, PointTarget, Scalar >

take what seem to be pretty generic template arguments, only requiring PCL base functionality.  But placing pcl::mesh did not compile (though it doesn't appear to be the only "mesh" type in PCL), since mesh doesn't seem to inherit off of base. The documentation does not talk about what is or is not possible with template types.  Additionally I have found zero documentation that states this is impossible or indicates that only point clouds are allowed.
Can I use the model directly with out point cloud conversion, and if not why?

A: PCL is a library for point cloud processing. While some mesh support is available (pcl::PolygonMesh), practically all the implemented algorithms are based on point cloud data.
However keep in mind that a mesh is just a point cloud + additional triangulation information (faces) - so this means that any point cloud algorithm can be applied on a mesh. You just need to generate a point cloud from your mesh's vertices, and ignore the faces - no need for mesh sampling.


text:
Q: OpenDJ release/3.0.0 compile error It's really odd that I downloaded the source code from Forgerock's stash repo to my linux local, but it always complain an compile error for the ant  stuff . Below is the detailed error msg. Any idea why ?
generateadmin:
     [exec]
     [exec] BUILD FAILED
     [exec] /home/xifeng/Downloads/new_test/3rd/opendj/release-3.0.0/opendj/opendj-server-legacy/build.xml:99: Fatal error during transformation using /home/xifeng/Downloads/new_test/3rd/opendj/release-3.0.0/opendj/opendj-server-legacy/resource/admin/metaMO.xsl: Cannot find external method 'java.io.File.toURI' (must be public).

[INFO] OpenDJ ............................................. FAILURE [ 31.211 s]
[INFO] OpenDJ DSML Gateway ................................ SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-antrun-plugin:1.7:run (generate-config) on project opendj-server-legacy: An Ant BuildException has occured: The following error occurred while executing this line:
[ERROR] /home/xifeng/Downloads/new_test/3rd/opendj/release-3.0.0/opendj/opendj-server-legacy/build.xml:76: exec returned: 1
[ERROR] around Ant part ...<ant antfile="/home/xifeng/Downloads/new_test/3rd/opendj/release-3.0.0/opendj/opendj-server-legacy/build.xml">... @ 4:113 in /home/xifeng/Downloads/new_test/3rd/opendj/release-3.0.0/opendj/opendj-server-legacy/target/antrun/build-main.xml

A: I finally understood the cause.
In my opendj/.gitignore file, I have:
# Package Files #
*.jar

meaning that when I submit those archives to my own git repo, they aren't committed.
Thus, when someone else clones my repo they will fail to compile.


text:
Q: TypeError: Cannot read property 'define' of undefined i try to change my Db from mongodb to mysql, i use sequelize instead of mongoose, and i got this error, i created the User.js model with sequelize format, but something wrong and i don't know why
const User = sequelize.define('users', {
                   ^

TypeError: Cannot read property 'define' of undefined"

Here is my code:
server.js
const Sequelize = require('sequelize');
// DB Config
const db = require('./config/keys');
// Connect to MySql
const sequelize = new Sequelize(db.database, db.user, db.password, {
    host: db.host,
    dialect: 'mysql',
    port: db.port
});

// Test the connection
sequelize
  .authenticate()
  .then(() => {
    console.log('Connection has been established successfully.');
  })
  .catch(err => {
    console.error('Unable to connect to the database:', err);
  });
const serverDB = {};
serverDB.sequelize = sequelize;
serverDB.Sequelize = Sequelize;
module.exports = serverDB;

Users.js
const serverDB = require('../server');
const sequelize = serverDB.sequelize;
const Sequelize = serverDB.Sequelize;

const User = sequelize.define('users', {
        id: {
            type: Sequelize.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        name: {
            type: Sequelize.STRING,
            allowNull: false
        },
        email: {
            type: Sequelize.STRING,
            allowNull: false
        },
        password: {
            type: Sequelize.STRING,
            allowNull: false
        },
        avatar: {
            type: STRING
        },
        date: {
            type: Sequelize.DATE,
            defaudefaultValue: Sequelize.NOW
        }
    });

sequelize.models.modelName

// sequelize.sync()
//     .then(() => {
//         console.log('User db and user table have been created')
//     });

module.exports = User;

A: You should add
const Sequelize = require('sequelize');

in your client too.
And only export and use the lowercase sequelize.
And ensure relative path of server.js is good.


text:
Q: Creating a label from template label in Perforce I'm trying to create a new label by using the p4 commands line, as in, go from template label my_label_template to my_label_1, but I can only find below commands which works create new label from template, but it doesn't seems to have option to input the Revision.
p4 label -o -t my_label_template my_label_1
Is there any way to create new label by using the p4 commands that also included input revision?
Thanks

A: Make sure you have a current version of the p4 CLI binary (2016.1 or newer).
Then use the --field global opt to add in the Revision field:
p4 --field Revision=@whatever label -o -t my_label_template my_label_1 | p4 label -i

https://www.perforce.com/blog/vcs/20161-command-line-roundup


text:
Q: How do I insert tens of thousands of rows without locking? I have a server that receives data from thousands of locations all over the world. Periodically, that server connects to my DB server and inserts records, one row at a time in rapid succession. There can be up to 6 of these processes (perl) running simultaneously and each may have over 50,000 insert statements, and subsequently, the tables are getting locked.
What I am trying to figure out is what causes locking? Am I better off creating a multi-insert with, say, 100 rows at a time and doing them end to end? What do I use for guidelines?
The DB server has 100GB RAM and 12 processors. It is very lightly used but when these inserts come in, everyone freezes up for a couple minutes which disrupts peopel running reports, etc.
Thanks for any advice. I know I need to stagger the inserts, I am just asking what is a recommended way to do this.

A: You cannot get rid of all locking.  However, there are ways to speed up what you are doing:

*

*Use multi-row INSERTs.  100 rows at a time will run 10 times as fast.

*As mentioned, switch to InnoDB using pt-online-schema-change.  Then put multiple INSERTs into a transaction (BEGIN ... COMMIT).

*The 6 threads could write to 6 different tables (such as CREATE TEMPORARY TABLE), then INSERT INTO real_table SELECT * FROM tmp_table.  Even on MyISAM this will run significantly faster because of 6 locks instead of 6*50K.  Read about concurrent_insert to see how to avoid 50K table locks into the tmp tables.

Please show us the SHOW CREATE TABLE.  There could be significant other issues, especially with indexes.


text:
Q: Geometric intuition for torsion in $H_{2}$ of non-orientable $3$-manifold Let $M$ be a compact, connected $n$-manifold. Consider the homology groups $H_n(M)$ with coefficients in $\mathbb{Z}$.
It is well known that if $M$ is not $\mathbb{Z}$-orientable, then we have $H_n(M) =0$ and $H_{n-1}(M) = \mathbb{Z}/2 \oplus \mathbb{Z}^i$ for some $i \ge 0$.
The proofs are clear for me (remark: the main instruments used in the proof are the Universal Coefficients Theorem and the existence of an orientable double cover of $M$), but I'm quite curious if there exists a geometric/intuitive explanation for the torsion summand $ \mathbb{Z}/2$ of $H_{n-1}(M)$.
Can this phenomenon be visualized in the case of a non-orientable $3$-manifold or is this a purely algebraic result?

A: Here is an extended version of my, now deleted, comment.
Let $M$ be connected nonorientable a compact triangulated manifold (every topological 3-manifold admits a triangulation). A similar argument works for a manifold equipped with a CW complex structure, but it is less geometric in this case. I will work with simplicial homology.
Let $c\in C_n(M; {\mathbb Z})$ denote the chain equal to the sum of all top-dimensional simplices. The boundary of this chain is a cycle $b=\partial c$ with even coefficients. Therefore, $a=\frac{1}{2}b$ is still a cycle with integer coefficients. Since $M$ is unorientable,   $a$ defines a nontrivial element of $H_{n-1}(M; {\mathbb Z})$. In order to prove this, you find a 1-cycle $e\in Z_1(M; {\mathbb Z}/2)$ (in the 1-skeleton of the dual triangulation) which has nonzero algebraic intersection number  with $a$: Take $e$ which reverses orientation. From this, you see that $[a]\ne 0$ in $H_{n-1}(M; {\mathbb Z})$ as well. On the other hand, clearly, $2[a]=[b]=0$. Hence, $[a]$ generates ${\mathbb Z}_2$ in $H_{n-1}(M; {\mathbb Z})$.
I do not know how to see geometrically that $[a]$ generates a direct summand of  $H_{n-1}(M; {\mathbb Z})$.


text:
Q: HERE Maps JavaScript API zoomTo Bounding Box BUG I observed some behavior in the HERE/Nokia Maps JavaScript API that appears to be a bug which manifests when zooming to a Container's bounding box.  This can be seen easily in the following example which I have tested in both Linux and Windows using a recent version of Firefox.
bug.html
<html>
 <head>
  <script type="text/javascript" charset="UTF-8" src="http://api.maps.nokia.com/2.2.3/jsl.js?with=maps"></script>
 </head>
 <body>
  <input type=button value=SHOW_GOOD_ZOOM onclick="good_zoom();" />
  <input type=button value=SHOW_BAD_ZOOM onclick="bad_zoom();" />
  <div id="mapContainer" >
   <script type="text/javascript" id="map" src="bug.js"></script>
  </div>
 </body>
</html>

bug.js
nokia.Settings.set("appId", "DemoAppId01082013GAL");
nokia.Settings.set("authenticationToken", "AJKnXv84fjrb0KIHawS0Tg");
var mapContainer = document.getElementById("mapContainer");
var container = new nokia.maps.map.Container();

var display = new nokia.maps.map.Display(mapContainer, {
center: [0, 0],
zoomLevel: 1,
components: [ new nokia.maps.map.component.ZoomBar() ]
});

var container = new nokia.maps.map.Container();
display.objects.add(container);

var point_in_idaho = new nokia.maps.geo.Coordinate(43, -116 );
var bad_afghanistan_point = new nokia.maps.geo.Coordinate(30, 64 );
var good_afghanistan_point = new nokia.maps.geo.Coordinate(30, 63 );

function bad_zoom() {
draw_and_zoom( point_in_idaho, bad_afghanistan_point );
}

function good_zoom() {
draw_and_zoom( point_in_idaho, good_afghanistan_point );
}

function draw_and_zoom( a, b ) {
container.objects.add( new nokia.maps.map.StandardMarker( a ) );
container.objects.add( new nokia.maps.map.StandardMarker( b ) );

alert("TL: " + container.getBoundingBox().topLeft + " / BR: " + container.getBoundingBox().bottomRight);
display.zoomTo( container.getBoundingBox() );
}

Open the bug.html in your browser and click SHOW_GOOD_ZOOM.  Note the two StandardMarkers on the screen and the alert which shows the Bounding Box's Top Left and Bottom Right coordinates:
TL: 43° 0' 0" N, 116° 0' 0" W / BR: 30° 0' 0" N, 63° 0' 0" E
Note that these correspond to Idaho (top left) and Afghanistan (bottom right).  When you click OK on the alert, you'll be zoomed in to a nice view of these two points on the map with the Atlantic Ocean in the middle.
Now reload the page and click SHOW_BAD_ZOOM.  The two StandardMarkers are in almost the same place: the point in Afghanistan has been moved one notch to the East (which you can see in the JavaScript code).  Note the Bounding Box's TL and BR here ....
TL: 43° 0' 0" N, 64° 0' 0" E / BR: 30° 0' 0" N, 116° 0' 0" W
Our Top Left is 43 North (near Idaho) but 64 East (near Afghanistan) and Bottom Right is "inverted" similarly.  What I would expect to see here after clicking OK is a reasonable zoom in, this time with the Pacific Ocean in the middle and both StandardMarkers shown.  What I get though, is the Pacfific Ocean dead center, but I'm zoomed into the maximum zoom level.  Now zoom out ~17 times and you'll see both Afghanastan (with a StandardMarker) and USA (w/o a StandardMarker) on the map!  Zoom out 2-3 more times and you'll see our Idaho marker way to the left of the map display.
This looks like a pretty clear bug to me.  When we zoom into to the Bounding Box of a Container, we obviously want to keep the items in the Container on the screen regardless of how we compute the Bounding Box.
What is really interesting here is that if I click SHOW_BAD_ZOOM and then (without reloading the page) click SHOW_GOOD_ZOOM, I get a good zoom/center.  Notice that Bounding Box coordinates here:
TL: 43° 0' 0" N, 116° 0' 0" W / BR: 30° 0' 0" N, 64° 0' 0" E
See how the "64" is on the bottom right now whereas in the "BAD" scenario, it was in the top left ...

A: FIXED!  turns out I was using an older version (2.2.3) of the API.  With 2.5.4, this works as expected.


text:
Q: How to use self ld, objcopy and ar in cmake? I want use two version of static librares in my project. And I found an answer from
Restricting symbols in a Linux static library.
But I don't know how to use cmake to run following commands:
ld -r obj1.o obj2.o ... objn.o -o static1.o
objcopy --localize-hidden static1.o static2.o
ar -rcs mylib.a static2.o

A: You could use execute_process to call the command, like this:
execute_process(COMMAND "ld" "-r" "obj1.o" "obj2.o" ... WORKING_DIRECTORY "...")

or use add_custom_command like here

A: Use
find_program(CMAKE_OBJCOPY objcopy)

or
find_program(CMAKE_OBJCOPY ${TOOLCHAIN_PREFIX}objcopy)

where TOOLCHAIN_PREFIX is path to your custom toolchain (for example, if you build your solution for ARM, MIPS e.t.c.). See example
Then you may use command like this (use execute_process):
    execute_process(COMMAND
      ${CMAKE_OBJCOPY} --localize-hidden static1.o static2.o
      RESULT_VARIABLE objcopy_result
      ERROR_QUIET
      OUTPUT_VARIABLE objcopy_out)

or use add_custom_command


text:
Q: use .val to get value of fields with same names I have an address field named "addressarr[]". Users can have multiple fields of the address.
I want to know if it's possible for me to check if all addressarr[] fields are filled up.
This is my code that checks the fields.
 function check() {
    var cn = document.getElementById('clientname').value;
    var e = document.getElementById("clienttype");
    var ct = e.options[e.selectedIndex].value;
    var cp= $ ("[name=addressarr").val();

    //var cp = document.getElementById('contactperson').value;
    //var cu = document.getElementById('contactnumber').value;
    if (cn == "") {
        document.getElementById('errormsg').innerHTML = 'Please enter full name';
        $('#modalerror').modal('show');
    }else if (ct == "Select Client Type") {
        document.getElementById('errormsg').innerHTML = 'Please pick client type';
        $('#modalerror').modal('show');
    }else if (cp == "") {
        document.getElementById('errormsg').innerHTML = 'Please enter address';
        $('#modalerror').modal('show');
    }

This is my HTML file.

                        Address

<input type=text class="form-control" rows="2" name="addressarr[]" id="addressarr[]" size="20" maxlength="45" value="<?php if (isset($_POST['addressarr']) && !$flag) echo $_POST['addressarr'][0]; ?>"/>

                          <input type="button" name="addaddress" class=" btn btn-default" id="adda" value="Add Address"/>

This is my code that appends when user wants to have multiple fields.
              $("#adda").click(function() {

              $("#diva").append('

  <input type=text class="form-control" rows="2" name="addressarr[]" id="addressarr[]" size="20 maxlength="45" value="<?php if (isset($_POST['addressarr']) && !$flag) echo $_POST['addressarr'][0]; ?>" />
 <input type="button" name="removeadd" class=" btn btn-danger" id="rema" value="Remove"/>

 0){
    alert('empty fields'); //do whatever you need to do here
}


text:
Q: Conflict On Two Post on Single Page Form(HTML) and PHP I need to keep two forms for login and Logout in one single page including PHP and HTML like
<html>
<body>

<form action="" method="post">
<input type="text" name="username">
<input type="submit" name="SubmitButton"  value="Get in"/>
</form>

<form action="" method="post">
<input type="submit" name="logoutButton"  value="Logout"/>
</form>

</body>
</html>

on PHP part I have
<?php
if(isset($_POST['SubmitButton'])){
  $inputuser = $_POST['username'];
  $_SESSION['user'] = 'A';
 }

if(isset($_POST['logoutButton'])){
      unset($_SESSION['user']);
      header('Location: http://somewhere.com/');
}

As I said I have to keep everything on one single page but this looks like causing conflict between the POST(s) can you please let me know how to stop this and target each Post properly?


text:
Q: Laravel Abort and Exceptions adding debug/stack trace to API response | APP_DEBUG=FALSE If I throw an exception in my API controllers/routes it always returns an object including the stack trace. I have set APP_DEBUG=FALSE and APP_ENV=production yet I always get a stack trace like below...
Say I throw any one of these in a controllers method:
throw new HttpException(410, 'Http Exception is gettting a stack trace.');
abort(404, 'Please tell me debug is not found!');
throw new UpdateResourceFailedException('Even my custom exception! How?', 422);
It returns an object like this:
{
    "message": "Message",
    "status_code": 410,
    "debug": {
        "line": 412,
        "file": "/var/www/example.com/app/Http/Controllers/OrderController.php",
        "class": "Symfony\\Component\\HttpKernel\\Exception\\HttpException",
        "trace": [
            "#0 [internal function]: App\\Http\\Controllers\\OrderController->show()",
            "#1 /var/www/example.com/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(55): call_user_func_array()",
            "#2 /var/www/example.com/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(44): Illuminate\\Routing\\Controller->callAction()",
            "#3 /var/www/example.com/vendor/laravel/framework/src/Illuminate/Routing/Route.php(203): Illuminate\\Routing\\ControllerDispatcher->dispatch()",
            "#4 /var/www/example.com/vendor/laravel/framework/src/Illuminate/Routing/Route.php(160): Illuminate\\Routing\\Route->runController()",
            "#5 /var/www/example.com/vendor/laravel/framework/src/Illuminate/Routing/Router.php(572): Illuminate\\Routing\\Route->run()",
            "#6 /var/www/example.com/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(30): Illuminate\\Routing\\Router->Illuminate\\Routing\\{closure}()",
            "#7 /var/www/example.com/vendor/dingo/api/src/Http/Middleware/Auth.php(55): Illuminate\\Routing\\Pipeline->Illuminate\\Routing\\{closure}()",
            "#8 /var/www/example.com/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(148): Dingo\\Api\\Http\\Middleware\\Auth->handle()",
            "#9 /var/www/example.com/vendor/laravel/framework/src/Illuminate/Routing/Pipeline.php(53): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()"...

I can't turn it off or figure out why it's adding it. Any help would be appreciated. Yes, I have dumped my .env variables and my config file to see what the system thinks the value is and invariably it's:
"debug":false
Any ideas on why this is returning debug?

A: You can always catch these errors and return exception messages as responses.
try{
    //throw exception here
     throw new UpdateResourceFailedException('Even my custom exception! How?', 422);
 }catch(UpdateResourceFailedException $ex){
   // when you want http response
   // return response(['custom_exception'=>$ex->getMessage()], 4xx);
   // when you want resposne as json
     return response()->json(['custom_exception'=>$ex->getMessage()], 4xx);
 }

You can return these exceptions along with status codes.
https://www.php.net/manual/en/throwable.getmessage.php

A: You can create a trait for handling all exception an update your exception/handler.php to call trait instead of showing trace.


text:
Q: Invalid css error when using lumx I have added lumx to my existing project in which I used angular-material . I have used to bower to install lumx referring link .But after the addition I am getting the following error .
"Syntax error: Invalid CSS after \" eot\": expected \")\", was \": \"#{$file-pa...\"\A on line 22 of /var/www/Browndesk/app/bower_components/bourbon/app/assets/stylesheets/helpers/_font-source-declaration.scss\A from line 13 of /var/www/Browndesk/app/bower_components/bourbon/app/assets/stylesheets/_bourbon.scss\A from line 7 of /var/www/Browndesk/app/styles/main.scss"

Please Help .

A: Your problem is with Bourbon, not with Lumx.
Source of error: app/bower_components/bourbon/app/assets/stylesheets/_bourbon.scss
Odds are bourbon is trying to parse some SCSS that it thinks is invalid.

A: The problem is with your sass compiler. I had the same problem when doing sass compile via compass. I switched to using sass compiler without compass and that solved it for me.

A: I Had the same problem. I solved it by updating my sass compiler.
check your sass version and run:
gem install sass


text:
Q: Binding a FlipView with GridView I have a GridView binding with a data source  which works perfectly.
public void LoadXmlData(string dateOfRunAsString)
{
    IEnumerable<RetrieveFromXml> processList = from process in xmlDocument.Descendants("Process")
                                               where process.Parent.Parent.Attribute("Date").Value == dateOfRun
                                               select new RetrieveFromXml(process.Attribute("Name").Value, Convert.ToDouble(process.Elements("ActiveTime").Sum(sec => (int)sec)));
    NameGrid.ItemTemplateSelector = myTemplateSelector;
    NameGrid.ItemsSource = processesList;
}

Now the Problem is I need to Combine the Gridview to a flipView.
Like the FlipView will display a gridview for each day.
Something Like
for(int i = 0; i<10; i++)
{
    flipview.list.add(processfromxml(date+i));
    //Consider processfromxml() is returning a Ienumerable List
}

So that the FlipView will display the GridView for first day and on clicking next it displays the GridView for Next day.
Please help how to Achieve this in XAML ,C# in windows 8
This is my Underlying Class to fetch data.
public class RetrieveProcessFromXml
{
    private string name;
    private double activeTime;

    public RetrieveFromXml(string nameFromXml,double activeTimeFromxml)
    {
        name = nameFromXml;
        activeTime = activeTimeFromxml;
    }

    public string Name
    {
        get { return name; }
        set { name = value; }
    }

    public double ActiveTime
    {
        get { return activeTime; }
        set { activeTime = value; }
    }
enter code here

} //End Class

A: You have loop like this
for(int i = 0; i<10; i++)
{
    flipview.list.add(processfromxml(date+i));
    //Consider processfromxml() is returning a Ienumerable List
}

So if you want to add item in FlipViewthen you have to add GridView not IEnumerable list. You have to assign ItemsSource to particular GridViewand then add that GridViewto FlipView.
Here I am giving you simple example
XAML
<Page.Resources>
    <DataTemplate x:Name="MyTemplate">
        <Border Background="DarkGray" Width="100" Height="100">
            <TextBlock Text="{Binding}"
                       Foreground="White"
                       HorizontalAlignment="Center"
                       VerticalAlignment="Center"
                       FontSize="30"/>
        </Border>
    </DataTemplate>
</Page.Resources>

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <FlipView x:Name="flipview" Height="500" Width="500"/>
</Grid>

C#
List<SolidColorBrush> colors;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
    colors = new List<SolidColorBrush>
    {
        new SolidColorBrush(Windows.UI.Colors.Red),
        new SolidColorBrush(Windows.UI.Colors.Gainsboro),
        new SolidColorBrush(Windows.UI.Colors.BlanchedAlmond),
        new SolidColorBrush(Windows.UI.Colors.Turquoise),
        new SolidColorBrush(Windows.UI.Colors.Azure),
        new SolidColorBrush(Windows.UI.Colors.Teal),
        new SolidColorBrush(Windows.UI.Colors.Tan),
        new SolidColorBrush(Windows.UI.Colors.PowderBlue),
        new SolidColorBrush(Windows.UI.Colors.WhiteSmoke),
        new SolidColorBrush(Windows.UI.Colors.SeaGreen)
    };
    for (int i = 0; i < 10; i++)
    {
        flipview.Items.Add(AddNewGridview(i));
    }
}

int i = 1, j = 0;
GridView AddNewGridview(int k)
{
    var gv = new GridView();
    gv.Background = colors[k];
    gv.ItemTemplate = this.Resources["MyTemplate"] as DataTemplate;
    List<int> IDs = new List<int>();
    while(i < 17 + j)
    {
        IDs.Add(i);
        i++;
    }
    j = i - 1;
    gv.ItemsSource = IDs;
    return gv;
}


text:
Q: "Adding motion" usage in sentence/slogan english is not my tongue language and I am working on a new viral content website, where I am trying to come up with slogan.
Would be correct to say: "Adding motion to your daily boredom"

A: It would be grammatically correct, but doesn't really make sense. Why would making my boredom move be a good thing.
You might want to consider "Adding excitement" instead

A: As a born to English user, may I suggest a different approach ?  Consider dropping the use of 'boredom'.  No one likes to actually *admit * they are bored.
Instead emphasize the positive with some thing like:
"Making travel more exciting than the destination..."

A: I agree that the "adding to" phrasing doesn't make much sense.
How about "Moving you through your daily boredom" instead? It retains the "motion" concept but sounds more natural to me.
You could explore synonyms to both "moving" as well. "Propelling" or "Driving" are also strong active verbs that share the transportation theme.


text:
Q: Problema con for en excel vba Una consulta estoy haciendo un pequeño sistema de diagnostico en excel con  vba , aunque ya lo termine, tengo un problema con la cantidad de codigo
introducir el código aquí
Dim ulcera, wil, dbt As String
Dim valor, valor1, i As Integer
Private Sub CommandButton1_Click()
If txt4.Text = "x" Then
dbt = "25%"
Else
dbt = ""
End If
If txt5.Text = "x" Then
dbt = "25%"
End If
If txt7.Text = "x" Then
dbt = "25%"
End If
If txt8.Text = "x" Then
dbt = "25%"
End If
txtdiabetes = dbt
End Sub

Bueno solo puse una parte del código , porque es muy extenso y el punto es que al marcar un texbox con una x , este tendrá un porcentaje hasta llegar a 100 o la cantidad marcada , son 3 efermedades , pero me di cuenta que la cantidad de codigo es demasiada y tendria problemas si aumentan las enfermedades o los sintomas , entonces quisiera saber como puedo recorrer los texbox usando un for y sumarlos , quise usar controls , pero mi excel no lo reconoce, gracias ...

A: Para tu caso pienso que sería más útil un For Each en lugar del For tradicional. La sintaxis es sencilla:
For Each elemento [ As tipo ] In conjunto
    ' Instrucciones
Next [ elemento ]

Este ciclo lo que hace es repetirse una vez por cada elemento que posee un conjunto. Lo que está entre corchetes son partes opcionales. Ahora explicaré sus partes:
conjunto es una serie de objetos o una variable que los contenga.
En elemento se encuentra el elemento actual de conjunto.
tipo es el tipo de la variable elemento, como los que usas para declarar otras variables.
Dentro del ciclo, puedes escribir 2 instrucciones especiales, Exit For para salir del ciclo y Continue For para saltarte una iteración.
Por último, habrá casos en los que tengas que usar un For Each dentro de otro. Aunque no es necesario, te puede ayudar a diferenciarlos escribiendo de nuevo la variable elemento luego de Next.
Te dejo un ejemplo para iterar sobre un rango de celdas:
For Each celda In Worksheets("Hoja1").Range("A1:D10").Cells
    celda.Value = "Hola"
Next

También puedes indagar más en la documentación oficial o buscar un tutorial.


text:
Q: SSRS Formatting for negative numbers Ok, so I am familiar with formatting the colors of a cell like this
=IIF(SUM(Fields!Dollars.Value) < 0, "Red", "Black")

but, I have inherited a report that has 80 columns and 4 rows of calculated fields which all print out black. I have been tasked with changing the format to represent negative numbers as red.
Does anyone know of an easy was to represent "CurrentValue" in a formula instead of referencing the textbox or report field?
Something along the lines of
=IIF(SUM(CurrentCellValue) < 0, "Red", "Black")

This way I can select the whole table and add this formula to the font color. Otherwise I will have to change the formula on 80*4 fields. I really don't want to do that

A: In the Color expression of the fields use the code below
= Iif (Me.Value <0, "Red", "Black")


text:
Q: Trying to pass variable from JavaScript to PHP using Ajax but got error " Undefined array key" I have had this error for multiple days now, I have tried searching this error up but whenever I search this error up it gives a different reason for the error and when I try to add what other sites say it doesn't work which is why I am asking here as I don't see what else I can do.
I am trying to pass a variable from JavaScript to PHP but it is not working and I have no idea why.
Here is my JavaScript code:
<head>
<script type="text/javascript" src="jquery.js"> </script>
</head>

<script>
var variable = "hello";
console.log(variable);
$.ajax
    ({
        url: "ajax.php",
        type: "POST",
        data:{pass : variable},
        success: function() {
              alert("Success");
        }
    });

</script>

Here is my PHP code:
$variable = $_POST['pass'];
echo($variable);

Everything seems to work perfectly. It writes the variable to the console, it comes up with the alert saying success. However I get an error message saying: 'Undefined array key "pass"'
What is causing this? Thank you?
Edit: People have told me to use isset, I have added that it removed the error however it still does not echo the PHP variable, meaning it is still not been passed to PHP, I am still trying to find how to fix this.

A: Your front end code looks OK, but I don't know your target PHP environement, but maybe your environnement doesn't accept formData.
By default, jQuery send ajax POST data as formData.
Try to send data as JSON
$.ajax({
    url: "ajax.php",
    type: "POST",
    data: JSON.stringify({pass : variable}),
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(data){alert(data);},
});

And then you will probably have to adapt your php code:
$json = file_get_contents('php://input');
// Converts it into a PHP array
$data = json_decode($json, true);
$variable = $data['pass'];
echo($variable);

A: Can you please use the developer tools in chrome browser that will help you to find if data is properly sent to php file.
Also you can try $_REQUEST instead of post just to check what data is coming in REQUEST as it works for GET & POST both. If it still does not help you.
Also can you please use
data: {'pass':variable}

instead of
data: {pass:variable}

let me know if it works for you.

A: If you get this error in your ajax.php file which you Post the data to it, I say it's normal because when you open that file (ajax.php) it's like that there is no $_POST['pass'] because you just opened that file without running JS to send data.
If you want to receive data that you send you can do this:
Your JS code I call this file index:
var variable = "hello";
$.ajax
({
    url: "ajax.php",
    type: "POST",
    data:{pass : variable},
    success: function(res) {
          alert(res);
    }
});

The PHP file:
$variable = $_POST['pass'];
echo($variable);

Then if You open up that index file, after running the JS code it'll send that post data to your PHP file and your PHP file will echo that, then the value will store in that res variable which when every thing went fine, you can see the alert of that res in the page (index file).
Notice that as I said you can't open up the PHP file lonely because it doesn't receive a post data on its own, it is normal for undefined to return.

A: Re: @puckloe your code is working, php echo wouldn't be printed with ajax(correction echo is working but wouldn't show on page if you don't print it with JS too), you have to catch the response in ajax success function ( like success: function(response) ) and print or alert the response --> success: function(response) { alert("hi look this is echo from php"+response) }
you ajax code should look like
$.ajax
    ({
        url: "ajax.php",
        type: "POST",
        data:{pass : variable},
        success: function(response) {
              alert("hi look this is echo from php" + response);
        }
    });


text:
Q: NULL value count in group by for simplification purposes, I will use simple table attribute (meaning the table is bigger) to demonstrate the issue:
I have the following table test:
 id | nbr
----+-----
  1 |   0
  2 |
  3 |
  4 |   1
  5 |   1
 (5 rows)

id and nbr are both numeric values
The following query
select nbr, count(nbr) from test group by nbr;

outputs:
 nbr | count
-----+-------
     |     0
   1 |     2
   0 |     1
(3 rows)

whereas the query:
select nbr, count(*) from test group by nbr;

outputs:
 nbr | count
-----+------
     |     2
   1 |     2
   0 |     1
 (3 rows)

I find it hard to explain the difference between count(nbr) and count(*) regarding null values
can someone explain this to me like I'm five, thanks

A: MySQL explains it in the documentation of function COUNT():

COUNT(expr)
Returns a count of the number of non-NULL values of expr in the rows retrieved by a SELECT statement.
COUNT(*) is somewhat different in that it returns a count of the number of rows retrieved, whether or not they contain NULL values.

PostgreSQL also explains it in the documentation:

Most aggregate functions ignore null inputs, so that rows in which one or more of the expression(s) yield null are discarded. This can be assumed to be true, unless otherwise specified, for all built-in aggregates.
For example, count(*) yields the total number of input rows; count(f1) yields the number of input rows in which f1 is non-null, since count ignores nulls; and count(distinct f1) yields the number of distinct non-null values of f1.

A: count(*) count the number of rows  related  to the group by colums. Inpependntly of the fatc the the column in group by contain null or not null values
count(nbr) count the number  of rows related to the group by column where nbr is not null

A: It's pretty simple:
count(<expression>) counts the number of values. Like most aggregate functions, it removes null values before doing the actual aggregation.
count(*) is a special case that counts the number of rows (regardless of any null).
count (no matter if * or <expression>) never returns null (unlike most other aggregate functions). In case no rows are aggregated, the result is 0.
Now, you have done a group by on an nullable column. group by put's null values into the same group. That means, the group for nbr null has two rows. If you now apply count(nbr), the null values are removed before aggregation, giving you 0 as result.
If you would do count(id), there would be no null value to be removed, giving you 2.
This is standard SQL behavior and honored by pretty much every database.
One of the common use-cases is to emulate the filter clause in databases that don't support it natively: http://modern-sql.com/feature/filter#conforming-alternatives
The exceptions (aggregate functions that don't remove null prior to aggregation) are functions like json_arrayagg, json_objectagg, array_agg and the like.

A: Count with null values:
SELECT nbr, COUNT(*) FROM mytables WHERE nbr IS NULL GROUP BY nbr

UNION

SELECT nbr, COUNT(nbr) FROM mytables WHERE nbr IS NOT NULL GROUP BY nbr


text:
Q: Access elements in bootstrap modal with jquery I am using this angular-bootstrap modal.
Its content:

I have tried these two options:
$("#my_button").click(function(){
    alert("ALERT");
})

$("#my_button").on("click", function(){
    alert("ALERT");
})

How to get access to that button?

A: Wiht Angular JS you should be using ng-click to link event handlers to your buttons.
Like:
Click me

Will execute the iWillClick function of your scope (in your relevant controller). Check this out to understand how ng-click works.
So in your case, if your footer is:

   <button ng-click="ok()" class="btn btn-primary">OK</button>
   <button ng-click="cancel()" class="btn btn-warning">Cancel</button>

will execute the ok() function on OK and the cancel() function on cancel. Both of those should be on your controller.
If for any reason you would like to use normal jQuery for your event handlers you should do
$(".modal-footer .btn-primary").on("click", function(){
    alert("OK");
});

$(".modal-footer .btn-warning").on("click", function(){
    alert("CANCEL");
});


text:
Q: Integrating Spring and Hibernate 3. Application throws exception when creating the beans Good afternoon! I'm starting studies with Dependency Injection and Inversion of Control with data persistence using the frameworks Spring and Hibernate.  I'm trying to integrate the two using Spring to control the Hibernate SessionFactory for all components monitored by Spring can receive as dependence SessionFactory, Spring controlling everything.Unfortunately I am not able to accomplish this goal, I get the following exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'produtosController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private br.com.caelum.estoque.dao.ProdutoDAO br.com.caelum.estoque.controller.ProdutosController.produtoDAO; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'produtoHibernateDAO' defined in file [C:\Program Files\eclipse\apache-tomcat-8.0.15\wtpwebapps\fj27-projeto-spring\WEB-INF\classes\br\com\caelum\estoque\dao\ProdutoHibernateDAO.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.hibernate.SessionFactory]: : Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/app-config.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/app-config.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:298)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1148)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:293)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:191)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:636)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:934)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:602)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:521)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:462)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)

From what he says can not create the bean to the "SessionFactory" and thus can not create the beans for persistence of data, "DAOS". I'm a week with this problem, I have seen and reviewed the settings in the app-config.xml, tried many things, I tried the forum but nothing I tried worked, now I'm asking for your help.
Here are my project files:
ProdutosController
    package br.com.caelum.estoque.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import br.com.caelum.estoque.dao.ProdutoDAO;
import br.com.caelum.estoque.model.Produto;

@Controller
@RequestMapping(value = "produtos")
public class ProdutosController {

    @Autowired
    @Qualifier("produtoHibernateDAO")
    private ProdutoDAO produtoDAO;

    @RequestMapping(value = "index")
    public String index() {
        return "produtos/index";
    }

    @RequestMapping(value = "listar", method = RequestMethod.GET)
    public ModelAndView listar() {
        ModelAndView modelAndView = new ModelAndView("produtos/lista");
        modelAndView.addObject(produtoDAO.listar());
        return modelAndView;
    }

    @RequestMapping(value = "mostrar/{id}", method = RequestMethod.GET)
    public ModelAndView mostrar(@PathVariable Long id) {
        ModelAndView modelAndView = new ModelAndView("produtos/mostrar");
        modelAndView.addObject(produtoDAO.buscarPorId(id));
        return modelAndView;
    }

    @RequestMapping(value = "form")
    public String form() {
        return "produtos/form";
    }

    @RequestMapping(value = "salvar", method = RequestMethod.POST)
    public String salvar(Produto produto) {
        produtoDAO.salvar(produto);
        return "redirect:/produtos/listar";
    }
}

ProdutoHibernateDAO
package br.com.caelum.estoque.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import br.com.caelum.estoque.model.Produto;

@Repository
public class ProdutoHibernateDAO implements ProdutoDAO {

    private Session session;

    @Autowired
    public ProdutoHibernateDAO(SessionFactory factory) {
        session = factory.openSession();
    }

    public void salvar(Produto produto) {
        session.save(produto);
    }

    public void alterar(Produto produto) {
        session.update(produto);
    }

    public List<Produto> listar() {
        List<Produto> produtos = session.createQuery("from Produto").list();
        return produtos;
    }

    public Produto buscarPorId(Long id) {
        return (Produto) session.get(Produto.class, id);
    }
}

ProdutoDAO
package br.com.caelum.estoque.dao;

import java.util.List;

import br.com.caelum.estoque.model.Produto;

public interface ProdutoDAO {

    void salvar(Produto produto);
    void alterar(Produto produto);
    List<Produto> listar();
    Produto buscarPorId(Long id);
}

Produto
package br.com.caelum.estoque.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Produto {

    @Id
    @GeneratedValue
    private Long id;
    private String descricao;
    private Integer quantidade;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public Integer getQuantidade() {
        return quantidade;
    }

    public void setQuantidade(Integer quantidade) {
        this.quantidade = quantidade;
    }
}

app-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!-- Configura aonde o Spring deve buscar por beans anotados -->
    <context:component-scan base-package="br.com.caelum.estoque" />

    <!-- Habilitar suporte a anotação @Controller -->
    <mvc:annotation-driven />

    <!-- Factory Bean para a SessionFactory do Hibernate. Utilizando esta factory
        fazemos com que a SessionFactory do hibernate seja gerenciada pelo Spring. -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/fj21" />
        <property name="username" value="root" />
        <property name="password" value="m19731973f" />
    </bean>

    <!-- Configuração das propriedades do Hibernate -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" value="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.url">jdbc:mysql://localhost/fj21</prop>
                <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
                <prop key="hibernate.connection.username">root</prop>
                <prop key="hibernate.connection.password">m19731973f</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.connection.autocommit">true</prop>
            </props>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>br.com.caelum.estoque.model.Produto</value>
            </list>
        </property>
    </bean>

</beans>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
          http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">

    <display-name>FJ27 Estoque</display-name>

    <!-- Configura o Spring Servlet -->
    <servlet>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                    /WEB-INF/spring/app-config.xml
                </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

aplicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">

</beans>

I tried to change the constructor method like this
@Autowired
public ProdutoHibernateDAO(SessionFactory factory) {
    session = factory.getCurrentSession();
}

and methods
public void salvar(Produto produto) {
    session.getSessionFactory().getCurrentSession().save(produto);
}

The jars both spring and hibernate are in version 4.

A: I solved the problem. I changed both the jarss Spring as the Hibernate to version 4 (spring 4.1.4.RELEASE, hibernate 4.3.8.Final). So I changed my app-config.xml file and let him thus:
<!-- Configuração das propriedades do Hibernate -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.url">jdbc:mysql://localhost/fj21</prop>
                <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
                <prop key="hibernate.connection.username">root</prop>
                <prop key="hibernate.connection.password">m19731973f</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.connection.autocommit">true</prop>
            </props>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>br.com.caelum.estoque.model.Produto</value>
            </list>
        </property>
    </bean>

I think there should be a version conflict of jars. Now is working perfectly.
Thanks for everyone's help.


text:
Q: después de aplicar formulario seguir en la misma pagina me gustaría saber si existe alguna manera de por ejemplo responder un formulario y que ya aplicado su php o la manera que este lanzando la info siga en la misma pagina. no se si me explique mucho pero saben que tengo una pagina donde una parte de ella es un formulario que inserta en una DB pero me gustaria seguir en la misma pagina ya mencionada, claro que inserte en la DB pero que no me mueva o me mande al archivo en el cual estoy mandando la info ( php )
espero haberme explicado bien y espero que me puedan ayudar
PD ya intente usar include, header Location etc pero no se si haya mas formas de hacer esto

A: Esto se puede hacer creando un formulario donde la acción sea #.
En la misma página debe haber un IF que gestione la llegada o no de datos del formulario. Pones un INPUT oculto para controlar la llegada de formularios y los valores de forma normal.
Mira este ejemplo:
    <?php
      if(isset($_POST['insert'])) {
      // Aquí recibes los valores del formulario y le das el tratamiento necesario.

// Aquí podría ir el insert con la gestión de los datos por ejemplo...
// include('mi_php_con_el_inserta_BBDD.php');

      echo "
Estoy en la misma página y me ha llegado el valor: ".$_POST['value'];

      } else {
        echo "
Aún no he recibido ningún valor.";
      }

     ?>

     <form method="post" action="#">
       <input name="insert" type="hidden"  />
       <input value="" name="value" id="value" type="text"  />
       <input type="submit" value="enviar" />
     </form>

Utilizando AJAX
Esto realmente refresca la página. Si queres que realmente no refresque la página, entonces debes utilizar AJAX que lo hace de forma asincrónica.  Ajax con JQuery.
En ese caso se crean dos archivos uno donde esta el JS y el HTML y otro con el php para gestionar los valores...
Archivo formulario.php

   <input name="insert" type="hidden"  />
   <input value="" name="value" id="value" type="text"  />
   <input type="submit" value="enviar" id="enviar"/>

  Resultado de la variable= 0

Archivo formulario_2.php
<?php

echo "Actualizas la Base de datos con el valor de tu variable que és ...".$_POST['variable'];
 ?>


text:
Q: Specify Content Type For Each Part Of A Multipart Form Request I would like to be able to specify the content type for each part of a multipart form request individually, as specified by RFC 2388 section 3. (https://www.ietf.org/rfc/rfc2388.txt)
For example, in cURL, one can invoke the command
curl -v -X POST http://myserver.com/v1/form-data
-F 'request={"hello":"world"};type=application/json'
It was noted last year that many people have requested this, and the feature would be considered for implementation in a future release:
https://stackoverflow.com/a/38529839/4521962
Please reconsider this feature request, as it is a requirement for a number of contemporary REST API's.


text:
Q: Dependent validation for form mapping in play framework 2 Can I create mapping for form, where first validation depend from second value?
val orderForm = Form(
    mapping(
      "requiredDelivery" -> boolean,
      "deliveryAddress" -> text,
      "comment" -> text)
    (Order.apply)(Order.unapply)
)

I want to check deliveryAddress for nonEmptyText if requiredDelivery is true

A: Try:
val orderForm = Form(
    mapping(
      "requiredDelivery" -> boolean,
      "deliveryAddress" -> text,
      "comment" -> text)
    (Order.apply)(Order.unapply) verifying("Address is required!", fields => fields match {
      case order => (order.requiredDelivery && order.deliveryAddress!="") || !order.requiredDelivery
    })
)

A: Any form validation error that is a result from the "verifying" clause after the mapping definition goes into the "global errors". The form helpers won't display these errors, so any typical template will come up blank but not able to successfully submit the form.
The fix is to add something like this to your form template:
@if(userForm.hasGlobalErrors) {

  @for(error <- userForm.globalErrors) {

@error.message

  }

}

You can learn more by looking at this page and skipping to the "Display errors in a view template" section - http://www.playframework.com/documentation/2.3-SNAPSHOT/ScalaForms


text:
Q: sudo apt update Erros — W: Possible missing firmware /lib/firmware/nvidia/gv100/sec2/sig.bin for module nouveau W: Possible missing firmware /lib/firmware/nvidia/gv100/sec2/sig.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/sec2/image.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/sec2/desc.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/nvdec/scrubber.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/gr/sw_method_init.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/gr/sw_bundle_init.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/gr/sw_nonctx.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/gr/sw_ctx.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/gr/gpccs_sig.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/gr/gpccs_data.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/gr/gpccs_inst.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/gr/gpccs_bl.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/gr/fecs_sig.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/gr/fecs_data.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/gr/fecs_inst.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/gr/fecs_bl.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/acr/ucode_unload.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/acr/ucode_load.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/acr/unload_bl.bin for module nouveau
W: Possible missing firmware /lib/firmware/nvidia/gv100/acr/bl.bin for module nouveau

A: Reason:Missing firmware warnings during update - Nvidia, nouveau
sudo find / -name "scrubber.bin"
sudo find / -name "sig.bin"
sudo find / -name "sw_method_init.bin"
sudo find / -name "ucode_unload.bin"

Step 1: Query the computer if these firmware exists, but the firmware file directory error, should be gv100 directory, is now in the gp100 gp107 directory
/lib/firmware/nvidia/gp100  /lib/firmware/nvidia/gp107
sudo mkdir /lib/firmware/nvidia/gv100
cd /lib/firmware/nvidia/gp100
sudo cp -r  acr/ gr/ ../gv100/
cd ../gp107
sudo cp -r  sec2/ nvdec/ ../gv100/

again run sudo apt update. No more errors occurred.

A: Thank you yfluK and herex I have the same issue whit Debian 10 buster, and after update this directories with the ucode_unload.bin as mention above warning message gone for me too.


text:
Q: How to append a DOMnode? This append-procedure is working fine:
document.getElementById('x').appendChild( document.importNode(node, true)  )

But when I try jQuery style, $('#x').append($(node)) or $('#x').append(node), not works.

EDIT: sorry all, I am using DOMnodes in a complex context, when using a simple short example it is working with $('#x').append( node )... See my Wiki-answer.

A: SInce you are using document.importNode that imports a node from another document. In jquery you have to use .contents()
var ele = $(node).contents().html();
$('#x').append(ele)

OR
$('#x').append($(node).contents().html());

A: Suppose normal and into-tag-template paragraph DOMnodes:

...

Standard paragraph1

.. paragraph2, lost?

<template id="t">

Templated node0!

Other...

</template>

See the complete example at this jsfiddle... Tested:
var t = document.getElementById('t');
var all_p = t.content.querySelectorAll("p");
var node0 = all_p[0];
var node1 = all_p[1];
if (!('content' in document.createElement('template'))) alert("NO TEMPLATE")

// append by pure Javascript:
document.getElementById('x').appendChild( document.importNode(node0, true)  )

// append by jQuery:
$('#x').append( $('#p1').clone() )  // standard behaviour as expected
$('#x').append( $('#p2') )  // but LOST IT!

$('#x').append( node0 )  // working fine, not lost!
$('#x').append( $(node0).clone() )  // working fine! (need to clone?)
// $('#x').append( node1.content )  // not work
// $('#x').append($(node1).contents().html()); // not work
$('#x').append( $(node1).html() ); // overhead to translate in to HTML

Conclusions
Denoting std_node as "standard DOMnode" (like paragraph1 of the example), and tpl_node  a node into a <template> tag:

*

*$('#x').append( std_node ): "side effect" deleting the node. It is not "append" but "move node"!

*$('#x').append( tpl_node ): work fine.

*$('#x').append( $(node) ):  same "side effect" deleting the node.

*$('#x').append( $(tpl_node) ): work fine.

*$('#x').append( $(node).clone() ):  work fine.


text:
Q: getBBox returns vastly different x and y positions for similar paths I have an SVG diagram with several paths in it:

For each of the 6 paths present, I call getBBox, to retrieve the X and Y positions (so that I can calculate a midpoint and append some text to the center). Works great.
Except for some nodes, the BBox is huge. Like, as wide as the screen almost. I cannot figure it out. Here is a path giving "normal" BBox values:
<path d="M 300.243 403.205 C 300.243 405.72 299.663 408.102 298.627 410.218 C 306.138 409.212 313.497 406.441 320.057 401.847 L 332.019 418.933 C 304.382 438.283 266.839 435 242.982 411.14 L 257.732 396.396 C 260.945 399.609 264.514 402.29 268.32 404.428 C 268.291 404.025 268.274 403.618 268.274 403.205 C 268.274 394.377 275.431 387.221 284.259 387.221 C 293.088 387.221 300.243 394.377 300.243 403.205 Z" id="midInferior" class="wall-area" fill="#b7eb8f"></path>
BBOX: {x: 242.98199462890625, y: 387.22100830078125, width: 89.03701782226562, height: 44.284881591796875}
And one giving odd values:
<path d="M 1582.498388568 609.217735717 A 122.142 122.142 0 0 1 1532.269773089 688.060868994 L 1511.252785308 658.045499787 A 85.5 85.5 0 0 0 1546.413062883 602.854919191 Z" transform="matrix(0.569203, 0, 0, 0.569203, -537.651855, 25.454704)" id="midInferolateral" class="wall-area" fill="#b7eb8f"></path>
BBOX: {x: 1511.2528076171875, y: 602.8549194335938, width: 71.24560546875, height: 85.2059326171875}
Any ideas?

A: One has a transform the other doesn't. getBBox ignores transforms.
The easiest solution to include transforms is to call getBoundingClientRect instead.

document.querySelectorAll("path").forEach(e => console.log(e.getBoundingClientRect()));
<svg>
<path d="M 300.243 403.205 C 300.243 405.72 299.663 408.102 298.627 410.218 C 306.138 409.212 313.497 406.441 320.057 401.847 L 332.019 418.933 C 304.382 438.283 266.839 435 242.982 411.14 L 257.732 396.396 C 260.945 399.609 264.514 402.29 268.32 404.428 C 268.291 404.025 268.274 403.618 268.274 403.205 C 268.274 394.377 275.431 387.221 284.259 387.221 C 293.088 387.221 300.243 394.377 300.243 403.205 Z" id="midInferior" class="wall-area" fill="#b7eb8f"></path>
<path d="M 1582.498388568 609.217735717 A 122.142 122.142 0 0 1 1532.269773089 688.060868994 L 1511.252785308 658.045499787 A 85.5 85.5 0 0 0 1546.413062883 602.854919191 Z" transform="matrix(0.569203, 0, 0, 0.569203, -537.651855, 25.454704)" id="midInferolateral" class="wall-area" fill="#b7eb8f"></path>
</svg>

A: Just to demonstrate how you can position circle slices and text without running any JavaScript.

<svg viewBox="0 0 100 100" width="300">
  <defs>
    <circle id="pie" r="40" fill="none" stroke="PaleGreen"
      stroke-width="10" stroke-dasharray="0 1 58 360"
      pathLength="360" />
  </defs>
  <g transform="translate(50 50)">
    <use href="#pie" transform="rotate(0)" />
    <use href="#pie" transform="rotate(60)" />
    <use href="#pie" transform="rotate(120)" />
    <use href="#pie" transform="rotate(180)" />
    <use href="#pie" transform="rotate(240)" />
    <use href="#pie" transform="rotate(300)" />
    <text text-anchor="middle" dominant-baseline="central"
      font-size="6">
      <textPath href="#pie" startOffset="30">Test 1</textPath>
      <textPath href="#pie" startOffset="90">Test 2</textPath>
      <textPath href="#pie" startOffset="150">Test 3</textPath>
      <textPath href="#pie" startOffset="210">Test 4</textPath>
      <textPath href="#pie" startOffset="270">Test 5</textPath>
      <textPath href="#pie" startOffset="330">Test 6</textPath>
    </text>
  </g>
</svg>


text:
Q: In UPDATE part of UPSERT, compute expression once for multiple columns I have an INSERT ... ON CONFLICT (primary_key) DO UPDATE query in a PostgreSQL 12 database.
It requires me to do the same calculation for multiple columns in the update clause. The calculation isn't too complex, but I would prefer not to maintain it in two places. The calculation contains a reference to both the conflicting row and to the EXCLUDED virtual table.
Is there any way to perform this calculation once and assign its result to a temporary variable within a single query expression?
The full query is:
INSERT INTO table_name(id, refreshed_at, tokens) VALUES ('id', CURRENT_TIMESTAMP, 60)
    ON CONFLICT (id) DO UPDATE SET
        tokens = GREATEST(
          -1,
          LEAST(
            GREATEST(0, table_name.tokens)
              + EXTRACT(epoch FROM EXCLUDED.refreshed_at)
              - EXTRACT(epoch FROM table_name.refreshed_at),
            100
          ) - 1
        ),
        refreshed_at = CASE
          WHEN (
            GREATEST(0, table_name.tokens)
              + EXTRACT(epoch FROM EXCLUDED.refreshed_at)
              - EXTRACT(epoch FROM table_name.refreshed_at)
            ) > 0 THEN EXCLUDED.refreshed_at
          ELSE table_name.refreshed_at
          END
        RETURNING tokens >= 0;

The tokens column is calculated from the column's prior value the difference in seconds between the time of query and the last time the column was updated. The refreshed_at column should only be changed if the tokens column value was updated, so the same calculation has to be performed in both SET clauses.

A:
The refreshed_at column should only be changed if the tokens column value was updated

Your original idea should work with a subquery:
INSERT INTO table_name(id, refreshed_at, tokens)
VALUES ('id', CURRENT_TIMESTAMP, 60)
ON CONFLICT (id) DO UPDATE
SET    (tokens, refreshed_at)
     = (SELECT GREATEST(-1, LEAST(GREATEST(0, table_name.tokens) + sub.diff, 100) - 1)
             , CASE WHEN sub.diff > 0 THEN EXCLUDED.refreshed_at ELSE table_name.refreshed_at END
        FROM  (SELECT EXTRACT(epoch FROM EXCLUDED.refreshed_at - table_name.refreshed_at)::int) sub(diff))
RETURNING tokens >= 0;
That's an allowed variant of the UPDATE syntax. This way, the difference between timestamps in seconds is only calculated once.
The calculation is cheaper, too, extracting the epoch from the difference (the resulting interval):
EXTRACT(epoch FROM EXCLUDED.refreshed_at - table_name.refreshed_at)

instead of extracting twice and subtracting like in your original:
EXTRACT(epoch FROM EXCLUDED.refreshed_at) - EXTRACT(epoch FROM table_name.refreshed_at)

But the overhead from the added subquery may be more expensive than doing the cheap calculation twice!
Alternative solution
Consider adding a WHERE clause to the UPDATE part instead. Like:
INSERT INTO table_name(id, refreshed_at, tokens)
VALUES ('id', CURRENT_TIMESTAMP, 60)
ON CONFLICT (id) DO UPDATE
SET     tokens = GREATEST(-1, LEAST(GREATEST(0, table_name.tokens) + EXTRACT(epoch FROM EXCLUDED.refreshed_at - table_name.refreshed_at), 100) - 1)
      , refreshed_at = EXCLUDED.refreshed_at
WHERE   EXTRACT(epoch FROM EXCLUDED.refreshed_at - table_name.refreshed_at)::int > 0
RETURNING tokens >= 0;
That would not touch rows at all where the time difference is below 1 second. That's typically superior because empty updates just add cost and bloat. (The cast rounds, you may want to truncate instead?)
Of course that would also not return a row where neither the INSERT nor the UPDATE part went through. If that's a problem, consider:

*

*How to use RETURNING with ON CONFLICT in PostgreSQL?


text:
Q: elasticsearch query_string handle special characters My database is sync with an Elasticsearch to optimize our search results and request faster.
I have an issue querying the users, I want with a query therm look for my users, it can be part of a name, phone, ip, ...
My actual query is
query_string: { fields: ['id', 'email', 'firstName', 'lastName', 'phone', 'ip'], query: `*${escapeElastic(req.query.search.toString().toLowerCase())}*`}

Where req.query.search is my search and escapeElastic comes from the node module elasticsearch-sanitize because I had issues with some symbols.
I have some issue for example if I query for an ipv6, I will have query: '*2001\\:0db8*' but it will not find anything in the database and it should
Other issue if I have someone with firstName john-doe my query will be query: '*john\\-doe*' and it will not find any result.
Seems that the escape prevent query errors but create some issues in my case.
I do not know if query_string is the better way to do my request, I am open to suggestions to optimize this query
Thanks

A: I suspect the analyzer on your fields is standard or similar. This means chars like : and - were stripped:
GET _analyze
{
  "text": "John-Doe",
  "analyzer": "standard"
}

showing
{
  "tokens" : [
    {
      "token" : "john",
      "start_offset" : 0,
      "end_offset" : 4,
      "type" : "<ALPHANUM>",
      "position" : 0
    },
    {
      "token" : "doe",
      "start_offset" : 5,
      "end_offset" : 8,
      "type" : "<ALPHANUM>",
      "position" : 1
    }
  ]
}

Let's create our own analyzer which is going to keep the special chars but lowercase them all other chars the same time:
PUT multisearch
{
  "settings": {
    "analysis": {
      "analyzer": {
        "with_special_chars": {
          "tokenizer": "whitespace",
          "filter": [
            "lowercase"
          ]
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "firstName": {
        "type": "text",
        "fields": {
          "with_special_chars": {
            "type": "text",
            "analyzer": "with_special_chars"
          }
        }
      },
      "ip": {
        "type": "ip",
        "fields": {
          "with_special_chars": {
            "type": "text",
            "analyzer": "with_special_chars"
          }
        }
      }
    }
  }
}

Ingesting 2 sample docs:
POST multisearch/_doc
{
  "ip": "2001:0db8:85a3:0000:0000:8a2e:0370:7334"
}

POST multisearch/_doc
{
   "firstName": "John-Doe"
}

and applying your query from above:
GET multisearch/_search
{
  "query": {
    "query_string": {
      "fields": [
        "id",
        "email",
        "firstName.with_special_chars",
        "lastName",
        "phone",
        "ip.with_special_chars"
      ],
      "query": "2001\\:0db8* OR john-*"
    }
  }
}

both hits are returned.

Two remarks: 1) note that we were searching .with_special_chars instead of the main fields and 2) I've removed the leading wildcard from the ip -- those are highly inefficient.

Final tips since you asked for optimization suggestions: the query could be rewritten as
GET multisearch/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "id": "tegO63EBG_KW3EFnvQF8"
          }
        },
        {
          "match": {
            "email": "john@doe.com"
          }
        },
        {
          "match_phrase_prefix": {
            "firstName.with_special_chars": "john-d"
          }
        },
        {
          "match_phrase_prefix": {
            "firstName.with_special_chars": "john-d"
          }
        },
        {
          "match": {
            "phone.with_special_chars": "+151351"
          }
        },
        {
          "wildcard": {
            "ip.with_special_chars": {
              "value": "2001\\:0db8*"
            }
          }
        }
      ]
    }
  }
}

*

*Partial id matching is probably an overkill -- either the term catches it or not

*email can be simply matched

*first- & lastName: I suspect match_phrase_prefix is more performant than wildcard or regexp so I'd go with that (as long as you don't need the leading *)

*phone can be matched but do make sure special chars can be matched too (if you use the int'l format)

*use wildcard for the ip -- same syntax as in the query string

Try the above and see if you notice any speed improvements!


text:
Q: Validar datas com Jquery validate para dd/mm/yyyy Quero validar as datas com JQuery Validate, porém erro,
Pesquisei bastante mais as soluções encontradas não resolveu meu problema.
meu JS:
// incluir todos elementos do form na pagina
$("form").each(function () {
    // inicializa o plugin no each form
    $(this).validate({
        rules: {
            dataentrada: {
                dateBR: true
            },
            datavenc: {
                dateBR: true
            },
            dataproc: {
                dateBR: true

            }
        }
    });
}
);

//Valida Data PT-BR
jQuery.validator.addMethod("dateBR", function (value, element) {
    //contando chars
    if (value.length != 10)
        return this.optional(element) || false;
    // verificando data
    var data = value;
    var dia = data.substr(0, 2);
    var barra1 = data.substr(2, 1);
    var mes = data.substr(3, 2);
    var barra2 = data.substr(5, 1);
    var ano = data.substr(6, 4);
    if (data.length != 10 || barra1 != "/" || barra2 != "/" || isNaN(dia) || isNaN(mes) || isNaN(ano) || dia > 31 || mes > 12) {
        return this.optional(element) || false;
    }
    if ((mes == 4 || mes == 6 || mes == 9 || mes == 11) && dia == 31) {
        return this.optional(element) || false;
    }
    if (mes == 2 && (dia > 29 || (dia == 29 && ano % 4 !== 0))) {
        return this.optional(element) || false;
    }
    if (ano < 1900) {
        return this.optional(element) || false;
    }
    return this.optional(element) || true;
}, "Informe uma data válida"); /* Mensagem padrão */

Quando no navegador tiro o foco do campo, mostra mensagem de data invalida.

A: *

*Crie um arquivo com o nome  methods_pt.js com o conteúdo abaixo.

*Adicione o arquivo no local onde você faz a chamada o jquery (após)

Veja outra forma de fazer em: https://github.com/aspnet/Docs/issues/4076
jQuery.extend(jQuery.validator.methods, {
    date: function (value, element) {
        return this.optional(element) || /^\d\d?\/\d\d?\/\d\d\d?\d?$/.test(value);
    },
    number: function (value, element) {
        return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:\.\d{3})+)(?:,\d+)?$/.test(value);
    }
});


text:
Q: "dotnet has stopped working" StackOverflowException when adding database migration I'm having a really annoying issue where every time I try to add a migration to my project, dotnet crashes and the migration is not created. This happens regardless of whether I use dotnet ef migrations add or Add-Migration. The command begins to run and compilation occurs if necessary, then it crashes with a StackOverflowException. Debugging yields the following information:
Unhandled exception at 0x00007FFF798C97DE (coreclr.dll) in dotnet.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x000000AC03A75FF8).

It also doesn't matter if my context has one Dbset whose objects have one int property or all objects with their complex properties and collections, et cetera. The only case where I can generate a migration and snapshot is if my context has no DbSets.
I have tried both the prerelease and release versions of .NET Core, as well as fully uninstalling the .NET Core SDK (as there were old versions still installed) and Visual Studio and reinstalling them.
I am using Visual Studio Enterprise 2015.3 on Windows 10 Pro and my model class is below:
public class Player
{
    [Key]
    public int PlayerID { get; set; }
}

and my context is as follows:
public class LeagueContext : DbContext
{
    public LeagueContext(DbContextOptions<LeagueContext> context) : base(context)
    {

    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {

    }

    public virtual DbSet<Player> Players { get; set; }
}

and my service configuration:
services.AddEntityFrameworkSqlServer().AddDbContext<LeagueContext>(config =>
        {
            config.UseSqlServer(Configuration["ConnectionStrings:LeagueContext"]);
        });

My project.json, as requested:
{
  "dependencies": {
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Razor.Tools": {
      "version": "1.0.0-preview2-final",
      "type": "build"
    },
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.AspNetCore.StaticFiles": "1.0.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0",
    "Microsoft.EntityFrameworkCore": "1.0.0",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
    "Microsoft.EntityFrameworkCore.Design": "1.0.0-preview2-final"
  },

  "tools": {
    "BundlerMinifier.Core": "2.0.238",
    "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"
  },

  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },

  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },

  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },

  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "Areas/**/Views",
      "appsettings.json",
      "web.config"
    ]
  },

  "scripts": {
    "prepublish": [ "bower install", "dotnet bundle" ],
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

A: I think I figured it out. While I did cut down my code to just the one collection with one property, I didn't save it before running Add-Migration so it was still using more of the model. What it was using looked like this:
public class Player
{
    [Key]
    public int PlayerID { get; set; }

    public int OrganizationID { get; set; }

    public int CurrentTeamID { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public DateTime JoinDate { get; set; }

    [ForeignKey("PlayerID")]
    public virtual PlayerAccount Account { get; set; }

    //[ForeignKey("PlayerID")]
    //public virtual PlayerCareer Career { get; set; }

    //[ForeignKey("PlayerID")]
    //public virtual PlayerInfo Info { get; set; }
}

and
public class PlayerAccount
{
    [Key]
    public int PlayerID { get; set; }

    public string Category { get; set; }

    public bool LeagueEmails { get; set; }

    public bool GameReminders { get; set; }

    [ForeignKey("PlayerID")]
    public virtual Player Player { get; set; }
}

which indeed has a circular reference. I don't know why I didn't think of that, though I think it is a bit odd that case isn't handled, especially as this seems like a logical way to set up a one-to-one relationship. Thinking back though, I remember not to use the ForeignKey attribute on the independent side, just how EF works.


text:
Q: Is there a way to share the same .NET 1.1 web.config file accross IIS5 and IIS7 I am using Vista, but most of the other developers working on the same projects as me are still using XP. Some of our projects have wildcard script mappings for handling vanity URLs, so each time I work on those sites, my IIS 7 adds a system.webServer/handlers section to the web.config file and when one of the other developers do an update it is not recognised by their IIS 5 systems and results in the following error:
Parser Error Message: Unrecognized configuration section 'system.webServer'

So is there either an IIS 7 setting for it to not store script mappings in the web.config file, or a way of telling IIS 5 to ignore that section?
I have Googled this, but I only seem to find guides from people migrating from IIS5/6 to 7.

A: Managed to answer my own question.
We have to modify the machine.config files on the XP machines. And add
<section name="system.webServer" type="System.Configuration.IgnoreSectionHandler,
System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

to the <configSections> section
That tells .NET on the XP machine to ignore that section.