text:
Q: I am getting an error "Pic is not a constructor" I am getting an error "Pic is not a constructor".
https://i.stack.imgur.com/nOWr1.png
Here is my schema for pics located in: Test\api\models\pic.js
const mongoose = require('mongoose');

const picSchema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: {
        type: String,
        required: true
    },
    cost: {
        type: Number,
        required: true
    }
});

mongoose.exports = mongoose.model('Pic', picSchema);

and this is my route located in: Test\api\routes\pics.js
    const express = require('express');
    const router = express.Router();
    const Pic = require('../models/pic');
    const mongoose = require('mongoose');

    router.post('/', (req, res, next) => {
        const pic = new Pic({
            _id: mongoose.Types.ObjectId(),
            name: req.body.name,
            cost: req.body.cost
        });
        const result = pic.save().then(result => {
            console.log(results);
        }).catch(err => console.log(err));
        res.status(201).json({
            message: 'Handling POST requests to /pics',
            createdPic: pic
          });
    });
    module.exports = router;

The following is my app code located in: Test\app.js
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const uri = process.env.mongo;

mongoose.connect(uri ,{
  useUnifiedTopology: true,
  useNewUrlParser: true
})
.then(() => console.log('Mongodb connected...'))
.catch(err => console.log(err));

app.use(morgan('dev'));
app.use(bodyParser.urlencoded({
  extended: false
}));
app.use(bodyParser.json());

const picsRoutes = require('./api/routes/pics');
app.use('/pics',picsRoutes);

app.use((req,res,next) =>{
    const error = new Error('Not Found');
    error.status = 404;
    next(error);
});

app.use((error, req, res, next) => {
    res.status(error.status || 500);
    res.json({
        error:{
            message: error.message
        }
      });
});

module.exports = app;

I have tried different ways of implementing the same and I keep getting the same error
What am I doing wrong and is there a better way use these objects?


text:
Q: Global variable resets when boolean I was working on the LeetCode problem Graph Valid Tree (#261) and was having some weird issue with Python when using global variables to detect a cycle. Essentially, if I detected a cycle, I wanted to set boolCycle to True. However, sometimes, I would print boolCycle out during the DFS (where it would evaluate to True), and then after running DFS and it would evaluate to False. I couldn't figure out why this is happening as boolCycle is a global variable, and the only change I ever make to it is to set it to True, so it should remain that way.
I instead came up with a hacky solution where I just created a list called cycle and added an element to it if there was a cycle, which ended up working. I'm curious as to why modifying the global list works as intended but modifying the global boolean doesn't.
cycle = []
boolCycle = False
def dfs(parent, node):
    visited.add(node)
    for neighbor in graph[node]:
        if neighbor in visited and neighbor != parent:
            cycle.append('hello')
            boolCycle = True
            return
        if neighbor not in visited:
            dfs(node, neighbor)

A: After
def dfs(parent, node):

add
    global boolCycle

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to write a two-variable function as a sum of two single-variable functions? Let $S$ be a non-empty open subset of $\mathbb{R}^2$, let $B$ be a set (possibly empty) of boundary points of $S$, and let $D = S\cup B$.
Is it possible to have single-variable functions $f_1:\mathbb{R}\longrightarrow\mathbb{R}$ and $f_2:\mathbb{R}\longrightarrow\mathbb{R}$ such that
$$f_1(y)-f_2(x)=(x+x^3)y, \text{ for all} \ (x,y)\in D \ ?$$

A: No, it's not possible.
Suppose that $f_1$ and $f_2$ exist. Let $(x_1,\overline y)$ and $(x_2,\overline y)$ be two points in $S$ such that $ b_1 =x_1+x_1^3\ne x_2+x_2^3=b_2$, and call $a_1=f_1(x_1)$ and $a_2 = f_1(x_2)$. We have that
$$
f_2(y) = -yb_1+a_1\qquad f_2(y) = -yb_2+a_2
$$
in an open neighborhood of $\overline y$, but the two functions are different, since $b_1\ne b_2$.

A: Suppose it were possible.
Then $f_1(0) - f_2(x) = (x + x^3)*0 = 0$ and $f_2(x) = -f_1(0)= c$ for all $x$.  So $f_2(x)$ is a constant function.
Then $f_1(y) - c = (x+x^3)*y$ and $f_1(y) = (x+x^3)*y+c$ is not well defined as it will have different values for different $x$ which are not variables of the function.
... or ... $f_1(y) - f_2(0) = 0*y = 0$ so $f_1(y)=f_2(0) = c$ is also a constant function.
So $f_1(y) - f_2(x) =  -c + c = 0$ is a constant function.  Which $(x+x^3)y$ clearly is not.
So, no.  It is not possible.
....
Or to put it more simply:
$f_1(0) - f_2(0) = 0$
$f_1(0) - f_2(1) = 0$
$f_1(1) - f_2(0) = 0$
$f_1(1) - f_2(1) = 1$.
So we must solve four equations with four unknowns:
$a - b = 0$
$a - d = 0$
$c - b = 0$
$c - d = 1$.
$a = b; a = d; c=b=a=d; c-d = c- c= 0 = 1$.  Impossible.

A: If we assume $f_1$ and $f_2$ are differentiable, and take the derivative with respect to $y$ of your last equation, we get $f_1^{\prime}(y) = x+x^3.$  So a function of $y$ alone somehow equals a function of $x$ alone.


text:
Q: Approximation $\frac{\mathrm{d} x}{x+\mathrm{d} x} \approx \frac{\mathrm{d}x}{x} $? Why is it possible to do the following approximation?
$$\frac{\mathrm{d} x}{x+\mathrm{d} x} \approx \frac{\mathrm{d}x}{x} $$
Why does that  $\mathrm{d} x$ in the denominator "count" less than the one in the numerator?

A: The $dx$ in the denominator is dwarfed by the $x$. The difference between $\frac{0.000001}{1.000001}$ and $\frac{0.000001}{1}$ is miniscule.

A: It's $\displaystyle \frac{dx}{x+dx}=\sum\limits_{k=0}^\infty (-1)^k (\frac{dx}{x})^{k+1}$.
Because of $\displaystyle (\frac{dx}{x})^{k+1}<<\frac{dx}{x}$ for $k\in\mathbb{N}$ you can approximate $\displaystyle \frac{dx}{x+dx}\approx \frac{dx}{x}$.

A: This is only valid as long as $x\not\approx 0$.
We have $x+\mathrm dx\approx x$ because $\mathrm dx\approx 0$ and addition is continuous.
Then provided $x\not\approx 0$,  the claim follows by continutity of division.

A: You are allowed to approx when terms are added as the difference between the results will be negligible however you cannot do the same with multiplication or division $10000+0.0001=10000.0001$ which is quite close however $10000*0.0001$ is definitely nowhere near $10000 $


text:
Q: How to reference properties in liquid I have a Jekyll template pulling in text from data objects.
eg.
{% for speaker_hash in site.data.2015.speakers %}
    {% assign speaker = speaker_hash[1] %}

 {{ speaker.name}}

{% endfor %}

However I would like to have each page specify what year its for with a page.year property.
Is it possible to create the same for loop but specify the year dynamically?
eg
 {% for speaker_hash in site.data.[page.year].speakers %}

A: Answer yes.
1 - Your page.year must be a string as hash indexes are strings. So in you front matter : year: '2015'
2 - Get speakers depending on page.year :
{% for speaker_hash in site.data[{{page.year}}].speakers %}


text:
Q: The for attribute of the label element must refer to a form control? I have read the other questions, but i cant seem to apply it to my problem.
In the validator it is giving me the problem 'The for attribute of the label element must refer to a form control'.
Can someone help me out? here is my code:

Contact Us

<form name="contactform" method="post"
      action="http://dev.itas.ca/~christopher.allison/send_form_email.php">

                First Name *

                <input  type="text" name="first_name" maxlength="50" size="30">

                Last Name *

                <input  type="text" name="last_name" maxlength="50" size="30">

                Email Address *

                <input  type="text" name="email" maxlength="80" size="30">

                Telephone Number

                <input  type="text" name="telephone" maxlength="30" size="30">

                Comments *

                <textarea  name="comments" maxlength="1000" cols="25" rows="6"></textarea>

                    <input value="Submit" title="submit" name="lucky" type="submit" id="btn_i">

</form>

A: The issue you have is that the for attribute must reference the id attribute of the input instead of the name:
First Name *
<input type="text" id="first_name" name="first_name" maxlength="50" size="30">

You can still use the name attribute for whatever you want but to link label with input you need to add an id.
Check out label documentation.


text:
Q: Optimize a SQL query to avoid repeating I have a long sql query that will be executed with 4 different parameters, so I have to repeat this query 4 times. I'm trying to optimize it but it's not working. Here is my query:
IF EXISTS (SELECT TOP 1 Id_Unique FROM Table1 WHERE Parameter= @Parameter1)
BEGIN
    UPDATE Table1
    SET Value = 'True'
    WHERE Parameter = @Parameter1
END
ELSE
BEGIN
    INSERT INTO Table1 (Parameter, Value)
    VALUES(@Parameter1, 'True')
END

The only thing that will change with each iteration is the parameter name: @Parameter1 / @Parameter2 / @Parameter3 /@Parameter4.
Table1 has only 3 columns (Id, Parameter, Value).
Does anyone know how to optimize this query?

A: You can put your parameters and their values into a table variable and then perform a single MERGE statement, if version of your SQL Server instance supports it (2008 and later).
Such as:
-- Incoming set of parameter values
declare @x xml = N'<Parameters>
    <Item Name="Parameter1" Value="Value1" />
    <Item Name="Parameter2" Value="Value2" />
    <Item Name="Parameter3" Value="Value3" />
    <Item Name="Parameter4" Value="Value4" />
</Parameters>';

declare @t table(
    Name varchar(100) primary key,
    Value nvarchar(max) not null
);

insert into @t (Name, Value)
select t.c.value('./@Name', 'varchar(100)') as [Name],
    t.c.value('./@Value', 'nvarchar(max)') as [Value]
from @x.nodes('/Parameters[1]/Item') t(c);

merge dbo.Table1 t
using (select * from @t) s
on t.Parameter = s.Name
when not matched by target then
    insert (Parameter, Value)
    values (s.Name, s.Value)
when matched then
    update set Value = s.Value;

Or, you can use any other way to populate the table variable that is most suitable in your situation - that's up to you.


text:
Q: How to display each result from a .forEach on its div? JavaScript I am building a fuel control app.
I have all the info like: price, date, actual kms, quantity (litters)... of the fuel movement stored on an object, from which I take all the info about actual kms and build an array like this:
[0, 300, 450, 560]

My HTML where each previous info is displayed individually for all fuel movements on a div looks like this:

I worked on this function, which gets the difference from each consequent index and goes to the next one:
function kmDifferenceCalculator(){
    //Get kms difference with the previous load
    for (var i = 1; i < kms.length; i++) {
    var currentElement = kms[i];
    var previousElement = kms[i-1];
    const fuelDiv = document.getElementById("fuel-movement")
    const kmsDifference = document.createElement("li");
    kmsDifference.classList.add("fuel-item","kms-difference")
    kmsDifference.innerHTML = (currentElement-previousElement);
    fuelDivDiv.appendChild(kmsDifference);
    }
}

fuelDiv stands for the div which holds all the info per movement and appends it to the
The thing is that when I console out kmDiffcalculator it shows: 300, 150, 110.
How do I get to show inside each fuel movement div only the difference which belongs to it?
At the moment I have 4 divs, showing: [0kms] [300kms] [450kms] [600kms]
And I want to get each difference showed on its div like: [0kms (+0kms)] [300kms +300kms] [450km +150kms] [560kms + 110kms]


text:
Q: Apache PIG, ELEPHANTBIRDJSON Loader I'm trying to parse below input (there are 2 records in this input)using Elephantbird json loader

[{"node_disk_lnum_1":36,"node_disk_xfers_in_rate_sum":136.40000000000001,"node_disk_bytes_in_rate_22":
  187392.0, "node_disk_lnum_7": 13}]
[{"node_disk_lnum_1": 36, "node_disk_xfers_in_rate_sum":
  105.2,"node_disk_bytes_in_rate_22": 123084.8, "node_disk_lnum_7":13}]

Here is my syntax:
register '/home/data/Desktop/elephant-bird-pig-4.1.jar';

a = LOAD '/pig/tc1.log' USING
com.twitter.elephantbird.pig.load.JsonLoader('-nestedLoad') as (json:map[]);

b = FOREACH a GENERATE flatten(json#'node_disk_lnum_1') AS
node_disk_lnum_1,flatten(json#'node_disk_xfers_in_rate_sum') AS
node_disk_xfers_in_rate_sum,flatten(json#'node_disk_bytes_in_rate_22') AS
node_disk_bytes_in_rate_22, flatten(json#'node_disk_lnum_7') AS
node_disk_lnum_7;

DESCRIBE b;

b describe result:

b: {node_disk_lnum_1: bytearray,node_disk_xfers_in_rate_sum:
  bytearray,node_disk_bytes_in_rate_22: bytearray,node_disk_lnum_7:
  bytearray}

c = FOREACH b GENERATE node_disk_lnum_1;

DESCRIBE c;

c: {node_disk_lnum_1: bytearray}

DUMP c;

Expected Result:

36, 136.40000000000001, 187392.0, 13
36, 105.2, 123084.8, 13

Throwing the below error

2017-02-06 01:05:49,337 [main] INFO
  org.apache.pig.tools.pigstats.ScriptState - Pig features used in the
  script: UNKNOWN 2017-02-06 01:05:49,386 [main] INFO
  org.apache.pig.data.SchemaTupleBackend - Key [pig.schematuple] was not
  set... will not generate code. 2017-02-06 01:05:49,387 [main] INFO
  org.apache.pig.newplan.logical.optimizer.LogicalPlanOptimizer -
  {RULES_ENABLED=[AddForEach, ColumnMapKeyPrune, ConstantCalculator,
  GroupByConstParallelSetter, LimitOptimizer, LoadTypeCastInserter,
  MergeFilter, MergeForEach, PartitionFilterOptimizer,
  PredicatePushdownOptimizer, PushDownForEachFlatten, PushUpFilter,
  SplitFilter, StreamTypeCastInserter]} 2017-02-06 01:05:49,390 [main]
  INFO  org.apache.pig.newplan.logical.rules.ColumnPruneVisitor - Map
  key required for a: $0->[node_disk_lnum_1,
  node_disk_xfers_in_rate_sum, node_disk_bytes_in_rate_22,
  node_disk_lnum_7]
2017-02-06 01:05:49,395 [main] INFO
  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MRCompiler
  - File concatenation threshold: 100 optimistic? false 2017-02-06 01:05:49,398 [main] INFO
  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MultiQueryOptimizer
  - MR plan size before optimization: 1 2017-02-06 01:05:49,398 [main] INFO
  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MultiQueryOptimizer
  - MR plan size after optimization: 1 2017-02-06 01:05:49,425 [main] INFO  org.apache.pig.tools.pigstats.mapreduce.MRScriptState - Pig
  script settings are added to the job 2017-02-06 01:05:49,426 [main]
  INFO
  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler
  - mapred.job.reduce.markreset.buffer.percent is not set, set to default 0.3 2017-02-06 01:05:49,428 [main] ERROR
  org.apache.pig.tools.grunt.Grunt - ERROR 2998: Unhandled internal
  error. com/twitter/elephantbird/util/HadoopCompat

Please help what am I missing?

A: You do not have any nested data in your json,so remove -nestedload
a = LOAD '/pig/tc1.log' USING com.twitter.elephantbird.pig.load.JsonLoader() as (json:map[]);


text:
Q: Accessing Rows from Access Database in Visual Basic 2010 based on Combobox Selection I've been looking for 3 days but I can't find what I need. I am rusty but I work for a company that manages I.T. for hotels. I have an access database that has a column with HOTELNAME, Street, Zip, Phone, etc etc.
The hotel names are populating a combobox on my form. Basically once the user picks the hotel from the drop down I want all of the info from the other rows (matching the row of the selected item) such as location info and phone, to populate a few LABELS but I can't seem to find what code I need for the labels.
CODE:
Public Class Newticket
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Me.HotelsdbTableAdapter.Fill(Me.HotelsDataSet1.hotelsdb)

    Try
        Dim MyConnection As System.Data.OleDb.OleDbConnection
        Dim DtSet As System.Data.DataSet
        Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
        MyConnection = New System.Data.OleDb.OleDbConnection _
        ("provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\David_2\Desktop 2\Skosh\hotelDB.xlsx'; Extended Properties=Excel 12.0;")
        MyCommand = New System.Data.OleDb.OleDbDataAdapter _
            ("select * from [Sheet1$]", MyConnection)
        MyCommand.TableMappings.Add("Table", "TestTable")
        DtSet = New System.Data.DataSet
        MyCommand.Fill(DtSet)

        ' cmbHotels.Items.Add = Sheet1$.Range("A1").Text

        MyConnection.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try

End Sub

Private Sub Newticket_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    FrmMain.Hide()

End Sub
Private Sub NewTicket_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
    FrmMain.Show()
    Me.Close()

End Sub

Private Sub lblHotel_Click(sender As System.Object, e As System.EventArgs) Handles lblHotel.Click

End Sub

Private Sub Label1_Click(sender As System.Object, e As System.EventArgs) Handles lblPoc.Click

End Sub

Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged

End Sub

Private Sub Label7_Click(sender As System.Object, e As System.EventArgs) Handles Label7.Click

End Sub

Private Sub BindingSource1_CurrentChanged(sender As System.Object, e As System.EventArgs)

End Sub
Private Sub DataGridView1_CellContentClick(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs)

End Sub

Private Sub cmbHotels_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbHotels.SelectedIndexChanged

End Sub

Private Function Sheets(p1 As String) As Object
    Throw New NotImplementedException
End Function

Private Function Rows() As Object
    Throw New NotImplementedException
End Function

Private Function Sheet1() As Object
    Throw New NotImplementedException
End Function

Private Sub DataGridView1_CellContentClick_1(sender As System.Object, e As System.Windows.Forms.DataGridViewCellEventArgs)

End Sub

Private Sub BindingSource1_CurrentChanged_1(sender As System.Object, e As System.EventArgs) Handles BindingSource1.CurrentChanged

End Sub

Private Sub FillByHotelToolStripButton_Click(sender As System.Object, e As System.EventArgs)
    Try
        Me.HotelsdbTableAdapter.FillByHotel(Me.HotelsDataSet1.hotelsdb)
    Catch ex As System.Exception
        System.Windows.Forms.MessageBox.Show(ex.Message)
    End Try

End Sub

Basically pick a hotel from combobox. A few labels on  the right with contat info need to populate the hotels info. I have 0 idea what to do for the labels. the combobox is working.
Thanks so much in advance

A: Basically like this ..
Private Sub cmbHotels_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cmbHotels.SelectedIndexChanged
If cmbHotels.SelectedIndex = -1 then exit sub

Dim sHotel As String = cmbHotels.Text
Dim dr As DataRow

MyCommand = New System.Data.OleDb.OleDbDataAdapter _
        ("select * from [Sheet1$] where HotelName = '" & sHotel & "'" ,MyConnection)

DtSet = New System.Data.DataSet
MyCommand.Fill(DtSet)

dr = DtSet.Rows(0)

'fill your label now
lblStreet.Text = dr.item("Stree") '----- or whatever
'etc

End Sub


text:
Q: Delete certain value of a field of separate database by commas and reenter again I need to delete a value from a separate database field by commas and re-enter again.
With the str_replace PHP function can delete all but the first or last, as always left a comma. I'm testing the end PHP function, more thank any solution.
$referenciaDel; // 44

$referencia; // 44,45,46

$replace = str_replace(",".$referenciaDel,"",$referencia);

If the first value to be deleted does not work because it added the comma in the function and the first value has no comma before.

A: Not sure to understand you right.
$strFromDatabase = '1,2,3,4,5';

$toDelete = 4;
echo trim(str_replace([$toDelete, ',,'], ['', ','], $strFromDatabase), ',');
// output: '1,2,3,5'

$toDelete = 5;
echo trim(str_replace([$toDelete, ',,'], ['', ','], $strFromDatabase), ',');
// output: '1,2,3,4'

$toDelete = 1;
echo trim(str_replace([$toDelete, ',,'], ['', ','], $strFromDatabase), ',');
// output: '2,3,4,5'


text:
Q: Add static route on Ubuntu 14.04 server I have set up Ubuntu 14.04 server on a machine and configured /etc/network/interfaces with two gateways. The default one is em1 which is fine, but I need traffic to a specific IP address on the internet to be sent via the other gateway. The following command works from the command line:
sudo route add -net XXX.XXX.XXX.XXX netmask 255.255.255.255 gw 172.16.0.1

but adding it to /etc/network/interfaces does not work on reboot:
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto em1
iface em1 inet static
    address 10.0.2.251
    netmask 255.255.255.0
    gateway 10.0.2.1
    dns-nameservers 8.8.8.8 8.8.4.4

auto em1:0
iface em1:0 inet static
    address 172.16.1.6
    netmask 255.255.0.0
    gateway 172.16.0.1
    dns-nameservers 8.8.8.8 8.8.4.4

post-up route add -net XXX.XXX.XXX.XXX netmask 255.255.255.255 gw 172.16.0.1

Can anyone help?

A:

post-up route add -net XXX.XXX.XXX.XXX netmask 255.255.255.255 gw 172.16.0.1
         remove post-up and change it to "up"

up route add -net XXX.XXX.XXX.XXX netmask 255.255.255.255 gw 172.16.0.1
after that, ifdown em1:0 and ifup em1:0
or u can restart networking.service
cheer.


text:
Q: Call ended event for Phonecalltask? Is there an event for when a phonecall is made from windows phone, and the call ends? if not is it there another possible way of getting such an event?
thanx

A: No you cannot. Windows phone SDK is not providing any such API for developers. Sorry.

A: Within the Windows Phone SDK calls are currently regarded as "non of your business" as an app developer. You can "launch" a call with PhoneCallTask, but you won't know if the call actually happened, when it ended etc. From your app you will just have to make sure you'll handle the application lifecycle well.


text:
Q: How to make array of array objects in javascript and then pass it to java To illustrate my point:
I have Name Age and Address of 4 people
[Sam, 23, nj],
[Nome, 25, ny],
[Sim, 20, pa],
[Jack, 12, pa]

I need to send these 4 rows to the java side.
I am familiar with java side coding so I can retrieve 4 rows from a list etc etc. I am new to javascripts, so I was wondering how to put all this data into a variable and then send it to java, so that java understands i am sending 4 sets of data.
I wanted to do hashmap of objects, either way as I am a newbie i don't know which road to take.pls advice.
I know how to post data through ajax, only part i am struggling with is creating the arrAY  so my java side can parse it.

A: You could serialize it to JSON so it looks something like this:
[{name: "Sam", age: 23, address: "nj"},
 {name: "Nome", age: 25, address: "ny"}]

A: Java supports JSON objects: http://www.json.org/java/
Use these methods.
Convert the array format to a stored variable and use the stringify method.
var a = Array([Sam, 23, nj], [Nome, 25, ny], [Sim, 20, pa], [Jack, 12, pa]);
var jsonText = JSON.stringify(a);
//send jsonText to java via post after this

Edit
To answer below, my Java is rusty from disuse but you will need to use the libraries here https://github.com/douglascrockford/JSON-java, and send the client side data jsonText over post data:
<form method='post' action='/Source/jsp/X.jsp' id='jsonform'>
<input id='json' name='json' value=''>
</form>

Then run a script to fill the value of the input with jsonText and submit it.
Once that is done you can grab the POST data and deserialize it and use it in your Java program.
var input = document.getElementById('json');
var form = document.getElementById('jsonform');
input.value = jsonText;
form.submit();

For the Java part, you said you are familiar with it so I'll leave that bit to you.


text:
Q: How do I generalize this function using JQuery I have a function (below) that, when the DOM loads it finds every select input and adds an attribute data-prev that keeps track of what the previous selected value was in the event the value is changed.
$( document ).ready(function() {

  //For each select field, add a data-prev attribute set for tracking the previous value for when it gets changed
  $('select').each(function(){
    $(this).attr("data-prev", $(this).val())
  });
}

Now, my page includes select fields that get created dynamically (after the page loads) for which I also need to set the data-prev attribute. So, I was thinking it would make sense for me to generalize the function above into something like
function SetDataPrevAttr(element=None)
    if element is None:
        for each select field in DOM set the attribute data-prev to its current value
    else:
        for each select field in the descendant elements of element (including element) set the attribute data-prev to its current value

How would I do this?

A: Why not just set the previous value when the <select> gets focus (ie, before it changes)? That way, you can just use a delegate event handler. For example...
$(document).on('focus', 'select', function() {
    var $sel = $(this);
    if (!$sel.data('prev')) {
        $sel.data('prev', $sel.val());
    }
});

JSFiddle Demo

A: function SetDataPrevAttr(elem) {
    elem.each(function () {
        $(this).attr('data-prev', $(this).val());
    });
}

$(function() {
    SetDataPrevAttr($('select'));
});

Then on adding each new element you could do the following:
var element = $('<select></select>').appendTo(document);
SetDataPrevAttr(element);


text:
Q: Can I list my questions where I did not accept an answer?
Possible Duplicate:
View my questions with unaccepted answers

I would like to improve my accept rate.
Where can I see questions with an answer that I did not accept?

A: You can do a search for:
 user:me hasaccepted:0

This should bring up all questions that you haven't accepted answers for.

A:

*

*1st one is having no answers.

*2nd one have 2 answers but no answer accepted.

*3rd have 3 answers out of which one is accepted.

A: I just have to go to My Profile -> My Questions and check the questions with an answer that are not marked by the green font.


text:
Q: Visual force Page and VF Component Communication I am trying to insert component's form record from parent visual force page's button click.
I am using virtual class to achieve this.
Please visit the below link for Controller Component Communication help : http://wiki.developerforce.com/page/Controller_Component_Communication
In above example, he is increasing the value of a variable that is already in component.
My requirement is that i have to get user input from the page.
please see the below code, so you can understand the issue :
Thanks


text:
Q: Python 3.5 | Split List and convert to csv I have two lists saved in two values. Those look like:
project_titles = ['T1', 'T2', 'T3']
project_loc = ['L1', 'L2', 'L3']

Actual I write the values with this Code into a csv:
with open('data.csv', 'w') as f:
    csv.writer(f).writerow(project_titles)

When I turn the csv to an excel I get:

*

*Cell A1 = T1

*Cell B1 = T2

*Cell C1 = T3

Thats fine, but I need the following result after the csv export:

*

*Cell A1 = T1; Cell B1 = L1

*Cell A2 = T2; Cell B2 = L2

*Cell A3 = T3; Cell B3 = L3

Do you have an idea?

A: You could use zip() to aggregate elements from two or more lists, then write the resulting rows to the file with csvwriter.writerows():
with open('data.csv', 'w') as f:
    writer = csv.writer(f)
    writer.writerows(zip(project_titles, project_loc))


text:
Q: Show that a photon cannot transmit its total energy to a free electron. Contradiction with Photoelectric effect? This is a problem in my textbook and I've shown it this way:
$E_{initial}=\frac{hc}{\lambda} + mc^2$
$p_{initial}=h/\lambda$
After collision with photon having zero energy we get
$p_{final}=h/\lambda$
$E_{final}=\sqrt{(\frac{hc}{\lambda})^2+(mc^2)^2}$
Which is in contradiction with the conservation of energy.
Now, this result is I think contradictory to Einstein's explanation of the photoelectric effect.
In the photoelectric effect the photon is absorbed by the free electron and this is what makes it have kinetic energy.
What am I interpreting wrong? The problem comes from the context of the Compton Effect, by the way.

A: The original problem can be seen in terms of energy and momentum conservation.
Before scatter, there are two particles in the center of mass and the center of mass  has an invariant mass larger than the mass of the electron. For total absorption of the photon there would be only the electron left. As the electron has a fixed mass and at the center of mass it should be at rest, the reaction cannot happen.  It can only happen if a third particle is involved to conserve the overall energy and momentum , and this is what is happening with the photoelectric effect.
  a)
The incoming photon interacts with an electron that is tied to the atom by a virtual photon . The whole system takes up the energy and momentum conservation.
The inverse problem happens with a gamma generating an e+e- pair. The gamma has zero invariant mass, the pair will have at least two electon masses at the center of mass, so a gamma cannot turn into an electron positron pair , a third  particle has to be involved. The simplest is a virtual photon from some nucleus too. The Feynman diagram is the same as the one above with a different interpretation  ( incoming e- is read as outgoing e+)
     _________________

a) diagram copied

A: As the comments indicate, the answer truly is that the electrons in the solid are not really free.
But wait, I hear you say -- the free electron model approximates the electrons in the solid as a free gas of electrons. It certainly isn't perfect, but it can't be that poor of a description. Yes it can, and I'll explain why.
Consider what it means to say that a solid is filled with a free electron gas. For definiteness, say that your solid is a metal cube of side $a$. Surely the electrons in the solid are bound to the solid, which is to say, they're not free throughout all of space. They're free inside the solid. So we can model the solid as a 3d infinite square well of width $a$.
But you can never remove a particle from an infinite square well, no matter how much energy you give, via photons or anything else. So it's utterly inadequate as a model for the photoelectric effect. You probably want then something like a very high but finite square well.
If the well is high enough, the finiteness doesn't change the lowest eigenvalues much, which will still be given by
$$E_{n_x,n_y,n_z} \approx \frac{\hbar^2\pi^2}{2ma^2}\left(n_x^2 + n_y^2 + n_z^2\right)$$
Since electrons are fermions, at zero temperature they will occupy the lowest energy eigenstates up to the Fermi energy $E_F$. If we assume that the energy levels are closely spaced enough that $n_x, n_y$ and $n_z$ may be treated as continuous variables, we'll have the following relation for the filled eigenstates:
$$n_x^2 + n_y^2 + n_z^2 \leq \frac{2m}{\hbar^2 \pi^2 } a^2 E_f$$
In other words, the total number of filled eigenstates is approximately given by the volume of the positive octant of a sphere of radius $\frac{a}{\hbar \pi } \sqrt{2m  E_f}$.
$$N_F \approx \frac{1}{8}\frac{4}{3} \frac{a^3}{\hbar^3 \pi^2 } (2m  E_f)^{3/2}$$
But of course, $N_F$ has to be equal to the number of electrons in the solid (well, up to a factor of two due to spin degeneracy), which is proportional to the volume of the box.
$$C a^3 = 2 N_F  \approx \frac{1}{3} \frac{a^3}{\hbar^3 \pi^2 } (2m  E_f)^{3/2}$$
So the Fermi energy will be given by
$$E_F = \left(3 \pi^2 C \right)^{2/3}\frac{\hbar^2}{2m}  $$
which in accordance with intuition and good sense doesn't depend on $a$. Instead it depends only on $C$ which is a property of the material.
So in order to remove one electron from the material, by whatever means, we need to pay at least the difference between the Fermi energy and the height of the well. This is the work function.
Now I hope it's become clear: the electrons in the box may only be regarded as free as long as their energy is small enough that you can pretend that the well is infinite.
So let's repeat your argument for a photon that has just enough energy to liberate an electron.
\begin{align}
E_{\text{initial}} &= \hbar \omega + mc^2 - W\\
p_{\text{initial}} &= \frac{\hbar \omega}{c}
\end{align}
After the photon is absorbed we have a free electron with zero kinetic energy, so
\begin{align}
E_{\text{final}} &= mc^2\\
p_{\text{final}} &= \frac{\hbar \omega}{c}
\end{align}
Since the condition that the photon has the exact minimum amount of energy to liberate one electron is precisely that $\hbar \omega = W$, the two equations are perfectly consistent and energy is conserved. Of course, since the electron is at rest, it can't have the momentum $p_{\text{final}}$ in the above. So the solid has it, and because it's so much more massive than the electron, its kinetic energy may be neglected. If you cling to the free electron model, I doubt you can go any farther than this.
You might still be feeling uneasy about the whole thing because while the energy imparted to the box is extremely small, it's non zero. That is true. However, the metal is always at some finite temperature so there's always some thermal energy available to supply the minute amount of kinetic energy imparted to the metal. Realistically this would probably be implemented by looking at how the extracted electron scatters off phonons in the lattice or some such.

A: Let's consider a free electron. If this absorbs a photon, then the Feynman diagram associated with it (the fundamental building block of all diagrams) will give probability zero. Because in the rest frame of the outgoing electron it has less energy than the incoming electron and photon. Conservation of energy is lost in this case. So an electron can't absorb a photon and move on freely.
In the same way: the diagram is topological equivalent to an incoming electron and an outgoing electron and photon, and in the centre of mass frame the incoming electron is at rest and the outgoing electron and photon have an energy that's greater than the energy of the incoming electron at rest, which contradicts conservation of energy.
The diagram is also topological equivalent to a real incoming electron and positron and a real outgoing photon. In the COMF of the electron and positron, the total momentum before the collision is zero, while the photon's momentum can't be zero since it always travels at the speed of light, which contradicts conservation of energy.
It has to be connected with the same kind of diagram, but with an incoming real electron and outgoing real electron and photon. The resulting diagram includes a real incoming electron and photon, a virtual electron (in the "middle") and a real outgoing electron and photon. Of course, this is the first order diagram of Compton scattering.
Now a virtual electron isn't on its mass scale, i.e. its momentum and energy are unrelated so it can enforce conservation of 4-momentum at each vortex, which is to say that the combined energy of the electron and photon before the collision is the same as after the collision, as is also the case for the combined momenta of the electron and photon before and after the collision. So if the incoming electron has the described momentum and energy and the photon has zero energy (and thus zero momentum), which is the same as no photon at all, the final four-momentum for the electron must be the same as the initial four-momentum.
I think you make the error to assume that $p_{initial}=\frac h {\lambda}$. Why should it have that value? It must have a value $x$ to match $E_{initial}$ with $E_{final}$. In that case, you get the equation
$\frac{hc}{\lambda}+mc^2=\sqrt{x^2c^2+(mc^2)^2}$, which you can solve for $x$:
$x=\sqrt(\frac{h^2+2hmc\lambda} {\lambda^2})$, so if $x=0$ (in the rest frame of the electron) also $\frac h \lambda=0$.
If you look to the incoming and outgoing electrons in their rest frames then the electrons have only the $mc^2$ term as energy because the "photon" which it absorbs has zero energy, and if energy is conserved in one inertial frame (in this case the rest frame) energy is conserved in every inertial frame.


text:
Q: Xcode 5 throws "Library not loaded" error when adding a test target I've tried adding a test target on Xcode 5 using the Add Target -> Add Cocoa Touch Unit Testing Bundle. However, when I run the test, I get the following error:

2013-09-24 10:43:14.446 Stack Exchange[48895:c07] Error loading
  /Users/arielitovsky/Library/Developer/Xcode/DerivedData/MyApp-fjegcztcnwxqdfdimhonqzzqpdwr/Build/Products/Debug-iphonesimulator/Stack
  Exchange Tests.xctest/Stack Exchange Tests:
  dlopen(/Users/arielitovsky/Library/Developer/Xcode/DerivedData/MyApp-fjegcztcnwxqdfdimhonqzzqpdwr/Build/Products/Debug-iphonesimulator/Stack
  Exchange Tests.xctest/Stack Exchange Tests, 262): Library not loaded:
  /Developer/Library/Frameworks/XCTest.framework/XCTest   Referenced
  from:
  /Users/arielitovsky/Library/Developer/Xcode/DerivedData/MyApp-fjegcztcnwxqdfdimhonqzzqpdwr/Build/Products/Debug-iphonesimulator/Stack
  Exchange Tests.xctest/Stack Exchange Tests   Reason: image not found
  IDEBundleInjection.c: Error loading bundle
  '/Users/arielitovsky/Library/Developer/Xcode/DerivedData/MyApp-fjegcztcnwxqdfdimhonqzzqpdwr/Build/Products/Debug-iphonesimulator/Stack
  Exchange Tests.xctest' Program ended with exit code: 0

Why isn't this working?

A: You must run your test on the iOS 7 simulator. It will not work on iOS 6.x.

A: I have fixed this by setting the General Tab -> Deployment Target to 7.0 (for the app that you are using to "run" the unit tests). This is not great if you want to support earlier than 7.0 for your main App. But since there is no Deployment Target on the unit test build target you cannot set it there. You instead have to set the Target of the unit tests (on General tab) to the App whose Deployment Target is 7.0.  You can setup a "TestApp" to do this so you don't have to restrict your main app's deployment.

A: I had the exact same problem although my CI server was configured with Xcode 5.1.1 and iOS 7.1.
I tried many parameters, finally the right one was -destination.
Here's an example of a full command:
xcodebuild -workspace MyApp.xcworkspace -sdk iphonesimulator7.1 -destination "platform=iOS Simulator,name=iPhone Retina (4-inch)" -scheme MyAppTests test

It also works with xctool 0.1.16.
Credits: http://www.mokten.com/2014/04/xcodebuild-unit-tests-library-not-loaded-no-image-found/
One detail that may explain why I had to add the -destination param, is that I have both iOS 6 and 7.1 SDKs installed. I haven't checked what happens if I delete the iOS 6 SDK though.
HTH


text:
Q: '404 not found' error when loading .glb/.gltf file I created a model in Blender and saved it as .glb file. When I try to load it to Three.js (using Vue.js and to be precise Trois.js) then I encounter some 404 (not found) error. Seems like path is wrong but I tried every single option to make proper relative path, however none of them works. Have no idea what's wrong. Here is my code:
BaseModel.vue
<template>
    <Renderer ref="renderer"
      antialias
      resize=true
      shadow
      :orbit-ctrl="{ enableDamping: true, target }"
      >
      <Camera ref="camera" :position="camera.position" />
      <Scene ref="scene" :background='bg_color'>
        <PointLight ref="light1"
            :intensity="scene.pointLight.intensity"
            :position="scene.pointLight.position" />
        <GltfModel src="~assets/test.glb" />
      </Scene>
    </Renderer>
</template>

and my directory:

I also tried ~/assets/test.glb, /src/assets/test.glb, ../../assets/test.glb but in vain.
Always the same error:

I also checked this issues but it didn't help: GLTF file 404 not found
EDIT: I'm adding folders structure taken from dev tools, I can't see 'text'glb' model loaded to assets folder where I normally store it. Seems it hasn't been loaded, don't know why. And yes, I refreshed the sources (Ctrl+R)


text:
Q: report viewer in windows form not updating even after refresh report i am try to generate report via report viewer using click event on button. its working fine. but when i update my data in database report viewer show only old report . i have tried using refresh report too.its not working. i am using table adapter in dataset to populate my data.
this.reportViewer1.Reset();
            Microsoft.Reporting.WinForms.ReportDataSource reportDataSource2 = new Microsoft.Reporting.WinForms.ReportDataSource();
            reportDataSource2.Name = "LedgerBy_partyID";

            reportDataSource2.Value = this.Ledger_by_Party_IDBindingSource;

           // this.ReportDataset.Ledger_by_Party_ID.Reset();

            this.Ledger_by_Party_IDTableAdapter.Fill(this.ReportDataset.Ledger_by_Party_ID, selected_PartyID);

            this.reportViewer1.LocalReport.ReportEmbeddedResource = "proj.userReport.Ledger_ByPartyID.rdlc";
            this.reportViewer1.LocalReport.DataSources.Clear();
            this.reportViewer1.LocalReport.DataSources.Add(reportDataSource2);
            this.reportViewer1.LocalReport.Refresh();
            this.reportViewer1.RefreshReport();

A: I just solved the same problem. I was searching for a few days in internet but I couldn't find a good answer for it. So I hope my post will help somebody to overcome the same problem.
All you need to do - just define manually the connection, refill the dataset and bind the source to reportviewer. Here is my project example:
using Microsoft.Reporting.WinForms;
    private void ReportForm_Load(object sender, EventArgs e)
    {
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\GD Robotics\VisualProjects\GDPolin\GDPolin\PolinaDB.mdf;Integrated Security=True;Connect Timeout=30";
        conn.Open();
        SqlDataAdapter reportDBTableAdapter = new SqlDataAdapter("SELECT * FROM  [ReportDB]", conn);
        DataTable polinaDBDataSet = new DataTable();
        reportDBTableAdapter.Fill(polinaDBDataSet);
        conn.Close();

        this.reportViewer1.Reset();
        this.reportViewer1.LocalReport.DataSources.Clear();
        this.reportViewer1.LocalReport.ReportPath = @"D:\GD Robotics\VisualProjects\GDPolin\GDPolin\Report1.rdlc";
        ReportDataSource rds = new ReportDataSource("DataSet1", polinaDBDataSet);//"DataSet1" is the name of your dataset. Go to .rdlc form>VIEW>Report Data>"Right click on dataset">Dataset Properties
        this.reportViewer1.LocalReport.DataSources.Add(rds);
        this.reportViewer1.RefreshReport();
    }


text:
Q: How to save tabs in a Chrome extension when closing a window? Is there any way in a Chrome extension to access the chrome.tabs API before a window is closed?
I'm working on an extension that moves any pinned tabs to a different window when the window is closed. However, the chrome.windows.onRemoved() event listener only fires once the window and all its tabs are closed.
I'm OK with a hacky substitute, since (for now) this extension is just for my personal use.

A: Try going from the other direction - save each tab when it's created.
This way, you'll always be synced with the last tabs, before "chrome.windows.onRemoved()" is initiated.
Implementation:
chrome.tabs.onCreated.addListener( function(tab) {
    // add tab to your [tabs list]
} );

chrome.tabs.onRemoved.addListener( function(tab) {
    // remove tab from your [tabs list]
} );


text:
Q: Domain of differential equation Consider the following differential equation
$$
y' + \frac{1}{t-2}y = 7(t-2)^2y^{1/2} \tag{1}
$$
Because it's a Bernoulli equation, by multiplying with $y^{-1/2}$ we get
$$
y^{-1/2}y' + \frac{1}{t-2}y^{1/2} = 7(t-2)^2
$$
and if we let $u = y^{1/2}$ with $u' = \frac{1}{2}y^{-1/2}y'$ we have
$$
u' + \frac{1}{2}\frac{1}{t-2}u = \frac{7}{2}(t-2)^2. \tag{2}
$$
To find the integrating factor we have
$$
\mu(t) = e^{\int \frac{1}{2}\frac{1}{t-2} dt} = e^{ \frac{1}{2} \ln |t-2| } = |t-2|^{1/2}.
$$
So now, we have to multiply $(2)$ by $\mu(t)$. But how can we tell if $t \geq 2$ or not?

A: Given $u^\prime + \frac{1}{2}\cdot\frac{1}{t-2}u = \frac{7}{2}(t-2)^2$ with integrating factor $\mu=\vert t-2\vert^{1/2}$ it matters only that $t\ne2$.
\begin{align}
\vert t-2\vert ^{1/2}u^\prime+\frac{1}{2}\cdot\dfrac{\vert t-2\vert ^{1/2}}{t-2\phantom{^{1/2}}}u &= \frac{7}{2}(t-2)^2\vert t-2\vert ^{1/2}\\
\left(\vert t-2\vert ^{1/2}u\right)^\prime &= \frac{7}{2}(t-2)^2\vert t-2\vert ^{1/2}\\
\vert t-2\vert ^{1/2}u &= (t-2)^3\vert t-2\vert ^{1/2}+C\\
u &= (t-2)^2+C\,\vert t-2\vert ^{-1/2}\\
y &=\left[(t-2)^2+C\,\vert  t-2\vert ^{-1/2}\right]^2
\end{align}


text:
Q: Obtaining a region of evenly distributed points on a sphere There are several questions on this site about distributing points on the surface of a sphere, but all of these are based on actually generating all of the points on that sphere. My favorite thus far is the golden spiral discussed in Evenly distributing n points on a sphere.
I need to cover a sphere in trillions of points, but only ever need to actually generate a tiny region of the surface (earth down to ~10 meters, looking at a roughly 1 km^2 area). The points generated for that region must match the points that would be generated for the entire sphere (i.e., stitching small regions together must yield the same result as generating a larger region), and generation should be pretty fast.
My attempts to use the golden spiral with such a large number of points have been thwarted by floating point precision issues.
The best I've managed to come up with is generating points at equally spaced latitudes and calculating longitudinal spacing based on the circumference at that latitude. The result is far from satisfactory however (especially the resulting horizontal rings of points).
Does anyone have a suggestion for generating a small region of distributed points on the surface of a sphere?

A: The vertices of a geodesic sphere would work well in this application.
You start with an icosahedron, divide each face into a triangular mesh of whatever resolution you like, and project the points onto the surface of the sphere.

A: The Fibonacci sphere approximation is quite easy to generalize efficiently to a subset of points computation, as the analytic formulas are very straight-forward.
The below code computes the subset of points shown below for a trillion points in a few seconds of runtime on my weak laptop and a relatively under optimised python implementation.

Code to compute the above is below, and includes a means to verify the subset computation is exactly the same as a brute-force computation (however don't try it for trillion points, it will never finish unless you have a super-computer!)
Please note, the use of 128-bit doubles is an absolute requirement when you do the computation over more than about a billion points as there are major quantisation artefacts otherwise!
Runtime scales with r' * N where r' is the ratio of the subset to that of the full sphere. Thus, a very small r' can be computed very efficiently.
#!/usr/bin/env python3

import argparse
import mpl_toolkits.mplot3d.axes3d as ax3d
import matplotlib.pyplot as plt
import numpy as np

def fibonacci_sphere_pts(num_pts):
  ga = (3 - np.sqrt(5)) * np.pi  # golden angle

  # Create a list of golden angle increments along tha range of number of points
  theta = ga * np.arange(num_pts)

  # Z is a split into a range of -1 to 1 in order to create a unit circle
  z = np.linspace(1 / num_pts - 1, 1 - 1 / num_pts, num_pts)

  # a list of the radii at each height step of the unit circle
  radius = np.sqrt(1 - z * z)

  # Determine where xy fall on the sphere, given the azimuthal and polar angles
  y = radius * np.sin(theta)
  x = radius * np.cos(theta)

  return np.asarray(list(zip(x,y,z)))

def fibonacci_sphere(num_pts):
  x,y,z = zip(*fibonacci_sphere_subset(num_pts))

  # Display points in a scatter plot
  fig = plt.figure()
  ax = fig.add_subplot(111, projection="3d")
  ax.scatter(x, y, z)
  plt.show()

def fibonacci_sphere_subset_pts(num_pts, p0, r0 ):
  """
  Get a subset of a full fibonacci_sphere
  """
  ga = (3 - np.sqrt(5)) * np.pi  # golden angle

  x0, y0, z0 = p0

  z_s = 1 / num_pts - 1
  z_e = 1 - 1 / num_pts

  # linspace formula for range [z_s,z_e] for N points is
  # z_k = z_s +  (z_e - z_s) / (N-1) * k , for k [0,N)
  # therefore k = (z_k - z_s)*(N-1) / (z_e - z_s)
  # would be the closest value of k
  k = int(np.round((z0 - z_s) * (num_pts - 1) / (z_e - z_s)))

  # here a sufficient number of "layers" of the fibonacci sphere must be
  # selected to obtain enough points to be a superset of the subset given the
  # radius, we use a heuristic to determine the number but it can be obtained
  # exactly by the correct formula instead (by choosing an upperbound)
  dz = (z_e - z_s) / (num_pts-1)
  n_dk = int(np.ceil( r0 / dz ))

  dk = np.arange(k - n_dk, k + n_dk+1)
  dk = dk[np.where((dk>=0)&(dk<num_pts))[0]]

  # NOTE: *must* use long double over regular doubles below, otherwise there
  # are major quantization errors in the output for large number of points
  theta = ga * dk.astype(np.longdouble)
  z = z_s + (z_e - z_s ) / (num_pts-1) *dk
  radius = np.sqrt(1 - z * z)
  y = radius * np.sin(theta)
  x = radius * np.cos(theta)
  idx = np.where(np.square(x - x0) + np.square(y-y0) + np.square(z-z0) <= r0*r0)[0]
  return x[idx],y[idx],z[idx]

def fibonacci_sphere_subset(num_pts, p0, r0, do_compare=False ):
  """
  Display fib sphere subset points and optionally compare against bruteforce computation
  """

  x,y,z = fibonacci_sphere_subset_pts(num_pts,p0,r0)

  if do_compare:
    subset = zip(x,y,z)
    subset_bf = fibonacci_sphere_pts(num_pts)
    x0,y0,z0 = p0
    subset_bf = [ (x,y,z) for (x,y,z) in subset_bf if np.square(x - x0) + np.square(y-y0) + np.square(z-z0) <= r0*r0  ]
    subset_bf = np.asarray(subset_bf)
    if np.allclose(subset,subset_bf):
        print('PASS: subset and bruteforce computation agree completely')
    else:
        print('FAIL: subset and bruteforce computation DO NOT agree completely')

  # Display points in a scatter plot
  fig = plt.figure()
  ax = fig.add_subplot(111, projection="3d")
  ax.scatter(x, y, z)
  plt.show()

if __name__ == "__main__":
  parser = argparse.ArgumentParser(description="fibonacci sphere")
  parser.add_argument(
      "numpts", type=int, help="number of points to distribute along sphere"
  )
  args = parser.parse_args()
  # hard-coded point to query with a tiny fixed radius
  p0 = (.5,.5,np.sqrt(1. - .5*.5 - .5*.5)) # coordinate of query point representing center of subset, note all coordinates fall between -1 and 1
  r0 = .00001 # the radius of the subset, a very small number is chosen as radius of full sphere is 1.0
  fibonacci_sphere_subset(int(args.numpts),p0,r0,do_compare=False)


text:
Q: No value at JSON path during webTestClient entity creation test "Fixed":
My endpoint was returning void instead of the User so it couldn't get the values.
I'm making tests using webTestClient for my application and the POST test has no value at JSON.
Code:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
public class UserResourceTest {

    @Autowired
    private WebTestClient webTestClient;

    @Test
    public void testCreateUser() {
        User user = new User(1L, "Slavik", 19);

        webTestClient.post()
                .uri("/api/user/")
                .contentType(APPLICATION_JSON_UTF8)
                .accept(APPLICATION_JSON_UTF8)
                .body(Mono.just(user), User.class)
                .exchange()
                .expectStatus().isOk()
                .expectBody()
                .jsonPath("$.id").isNotEmpty()
                .jsonPath("$.username").isEqualTo("Slavik");
    }

    @Test
    public void getAllOkForGetAll() {
        webTestClient.get()
                .uri("/api/user/")
                .accept(APPLICATION_JSON_UTF8)
                .exchange()
                .expectStatus().isOk()
                .expectHeader().contentType(APPLICATION_JSON_UTF8)
                .expectBodyList(User.class);
    }
}

The GET method works.
Removing the both JSON lines makes the test pass.
.expectBody(User.class) does not work.
Expecting status OK is correct for my case (should be Create but it's not the issue)
Removing $. also did not work
The Endpoint:
    @PostMapping
    @ResponseStatus(value = HttpStatus.OK)
    public void add() {
        this.userService.add();
    }

User class:
@Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Long id;
    private String username;
    private Integer age;
}


text:
Q: python client throw error "call dropped by load balancing policy grpc" when remote server restart Python Client throw "call dropped by load balancing policy grpc", if remote server restart. And connection never recovered afterwards.
The problem is hard to constant reproduce. But we confirmed that if a remote server restart, python client have chance starting send error message like this.
Other grpc client like java are working fine. I searched online, and it seems related to load balancing policy. And suggest to change from 'roundrobin' to 'pick first'. But I can not find where to add this args in python client.

A: revert fly tiger resolve this issue


text:
Q: Blossom Algorithm I have noticed that in the blossom algorithm, we need to find the blossom while finding the augmenting path. What will happen if I just know there is a blossom in a graph and the contracted graph has an augmenting path. Will the original graph not have that augmenting path or will be same?
Edit to make it clear:-
This is problem 8 from Chapter 10 from Combinatorial Optimization: Algorithms and Complexity Christos H. Papadimitriou
Theorem : Suppose that, while searching for an augmenting path, from a node u of a graph G with respect to a matching M, we discover a blossom b. Then there is an augmenting path from u in G with respect to M iff there is one from u (vb if u is the basis of b) in G/b with respect to M/b.
Show by an example that if G = (V;E) is a graph, M a matching of G, and b a blossom (a circuit with 2m + 1 edges, m of which are in M), then the following may fail to be true : There is an augmenting path in G with respect to M iff there is one in G/b with respect to M/b. Compare with above theorem.

A: What does "just know" mean?  It is hardly something that would be part of an algorithm.
But the important thing to note is that each iteration of the algorithm starts with a valid (possibly null) solution and finds either a better solution or a simpler form of the graph.
So if at any time, you have some magic way of producing a better solution, independent of the algorithm, there's no reason you couldn't simply use it, and then continue using the algorithm on that improved intermediate solution.


text:
Q: Characterization of concave functions I'm reading a paper that claims that if $\forall a,b\in \mathbb{R}^2$ s.t. $a_i>b_i$ for $i=1,2$, one has
$$
f(a_1+b_2)+f(a_2+b_1)>f(a_1+a_2)+f(b_1+b_2)
$$
then $f$ is strictly concave. It's not difficult to see the function is mid-point concave. But what about full concavity?

A: Try to prove that $f$ strictly concave over I is equivalent to
$\forall (A,B,C,D)\in I^4$, such that $A<C\leq D<B$,
$$\frac{f(B)-f(D)}{B-D}<\frac{f(C)-f(A)}{C-A}.$$
and put $B=b_1+b_2$, $A=a_1+a_2$, $C=min(a_2+b_1,a_1+b_2)$, $D=max(a_2+b_1,a_1+b_2)$


text:
Q: Custom Useragents wrong formatted in python Today I tried to make simple requests to a Website and implement custom headers that I defined into a separate file called useragents.txt. I now wasted lot of time working on it to get it to work. The issue is, that python wont request the site during a valueerror: Invalid header value b'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36\n'
I'm not sure why it add a b' and a \n there. If I print the variable the output is without these symbols. Here a little code that might show better what I mean:
    def get_soup(url, header):
        time.sleep(random.choice([1, 2, 3]))
        return BeautifulSoup(urlopen(Request(url, headers=header)), "html.parser")

        with open("useragents.txt", "r") as user_agents_file:
            user_agents_lines = user_agents_file.read().splitlines()
            print(user_agents_lines)
            # count
            user_agent = random.choice(user_agents_lines)
            print(f"USER-AGENT: {user_agent}")
            # for user_agent in user_agents_lines:
            #     count += 1
            #     print(f"Line{count}: {user_agent.strip()}")

The Full error is:
Traceback (most recent call last):
  File "D:\my_python_projects\testingcodes\firstcode\main.py", line 118, in <module>
    scraper() # run the function
  File "D:\my_python_projects\testingcodes\firstcode\main.py", line 69, in scraper
    soup = get_soup(surveyingurl, testheader)
  File "D:\my_python_projects\testingcodes\firstcode\main.py", line 43, in get_soup
    return BeautifulSoup(urlopen(Request(url, headers=header)), "html.parser")
  File "D:\Downloads\Python\python 3.9.6\lib\urllib\request.py", line 214, in urlopen
    return opener.open(url, data, timeout)
  File "D:\Downloads\Python\python 3.9.6\lib\urllib\request.py", line 517, in open
    response = self._open(req, data)
  File "D:\Downloads\Python\python 3.9.6\lib\urllib\request.py", line 534, in _open
    result = self._call_chain(self.handle_open, protocol, protocol +
  File "D:\Downloads\Python\python 3.9.6\lib\urllib\request.py", line 494, in _call_chain
    result = func(*args)
  File "D:\Downloads\Python\python 3.9.6\lib\urllib\request.py", line 1389, in https_open
    return self.do_open(http.client.HTTPSConnection, req,
  File "D:\Downloads\Python\python 3.9.6\lib\urllib\request.py", line 1346, in do_open
    h.request(req.get_method(), req.selector, req.data, headers,
  File "D:\Downloads\Python\python 3.9.6\lib\http\client.py", line 1257, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "D:\Downloads\Python\python 3.9.6\lib\http\client.py", line 1298, in _send_request
    self.putheader(hdr, value)
  File "D:\Downloads\Python\python 3.9.6\lib\http\client.py", line 1235, in putheader
    raise ValueError('Invalid header value %r' % (values[i],))
ValueError: Invalid header value b'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36\n'

Process finished with exit code 1

Below a screenshot that shows how my useragents.txt file looks like:

A: with open("useragents.txt", "r") as user_agents_file:
            user_agents_lines = user_agents_file.read().splitlines()
            print(user_agents_lines)

            user_agent = random.choice(user_agents_lines)
            user_agent = user_agent.replace(b'\n', b'')

            print(f"USER-AGENT: {user_agent}")


text:
Q: Angular: unexpected request (ngMockE2E - $httpBackend) I'm trying to test an Angular directive using Jasmine.
Html looks like this:

        <title></title>

The test directive (/components/test-directive.js)
angular.directive('testDirective', function(){
    return {
        templateUrl:'/views/test-directive.html'
    };
});

The test file (/components/test-directive.spec.js) looks like this:
describe('test directive', function(){
    beforeEach(module('myAppTests'));

    var element, $scope;

    beforeEach(inject(function($compile, $rootScope){
        element = angular.element('

');
        $scope = $rootScope;
        $compile(element)($scope);
        $scope.$digest();
    }));

    it('generates the correct HTML', function(){
        expect(element.html()).toContain('test content');
    });

});

And the /views/test-directive.html

test content

When running the test I get the following error:
'Unexpected request: GET /views/test-directive.html'

A: Try adding this to your filters:
$httpBackend.whenGET(/\.html$/).passThrough();

A: When you use any inject or module in your tests, it implicitly loads ngMock's modules, which includes a mocked $httpBackEnd that doesn't send requests.
One option is to reuse the original $httpBackend.
angular.module('myAppTests', ['myApp', 'ngMock'])
  .factory('$httpBackend', function() {
    // use the original $httpBackend instead of the fake backend
    return angular.injector(['ng']).get('$httpBackend');
  });


text:
Q: How to specify type for a swagger:parameters struct My struct is defined as the following
// swagger:parameters instanceLogs
type SelectorParameter struct {
    // selector
    // in: query
    // required: false
    // type: string
    Selector uint `json:"selector"`
}

However the type show in my generated spec is uint64. Any idea what I'm doing wrong?

A: You did it correctly,
you haven't specified the length of it. so the system has decided about that.
I didn't get what exactly you want set for it, if you want it be integer use just int if you uint32 use uint32
// swagger:parameters instanceLogs
type SelectorParameter struct {
    // selector
    // in: query
    // required: false
    // type: string
    Selector int `json:"selector"`  // it will be Integer
}

what is UINT


text:
Q: How to export a wav file to m4a with 22kHz with AVAssetExportSession? I have a 22kHz wave file and want a 22kHz m4a file. AVAssetExportSession with the preset AVAssetExportPresetAppleM4A automatically converts my wav to 44kHZ. I've tried different presets and nil to create the ExportSession, but without success.
Is there a way to set custom export properties of an AVAssetExportSession or do I need a completely different approach like the one stated in How to convert WAV file to M4A??
here is the code I have so far, which works great if you want a 44kHz file:
AVURLAsset *wavAsset = [AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:wavPath] options:optionsDict];

AVMutableComposition *mutableComposition = [AVMutableComposition composition];
[mutableComposition insertTimeRange:CMTimeRangeMake(kCMTimeZero, wavAsset.duration)
  ofAsset:wavAsset atTime:kCMTimeZero error:&error];

AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
  initWithAsset:[mutableComposition copy] presetName:AVAssetExportPresetAppleM4A];
exportSession.outputURL = [NSURL fileURLWithPath:m4aPath];
exportSession.outputFileType = AVFileTypeAppleM4A;

[exportSession exportAsynchronouslyWithCompletionHandler:^{
  switch (exportSession.status) {
    case AVAssetExportSessionStatusCompleted: {
      [exportSession release];
      completionHandler(nil);
      break;
    }
    case AVAssetExportSessionStatusFailed: {
      NSLog(@"There was an error while exporting the file: %@", exportSession.error);
      completionHandler(exportSession.error);
      break;
    }
    // ... handle some other cases...
    default: {
      break;
    }
  }
}];

Would be great if I just missed something.
Thanks in advance,
Dom

A: I've had some luck with the TPAACAudioConverter available here. It uses the ExtendedAudioFile API in the AudioToolbox Framework.


text:
Q: Maintain passwords while switching from ASP.NET Membership to ASP.NET Core Identity My company is planning to upgrade our applications from .NET Framework to .NET Core, and as part of that to upgrade from ASP.NET Membership to ASP.NET Core Identity server. I found a useful article on this here.
However, there is a sub-note with massive implications:

After completion of this script, the ASP.NET Core Identity app created
  earlier is populated with Membership users. Users need to change their
  passwords before logging in.

We can't ask 600,000 users to change their password as part of this migration. However, the membership passwords are one-way hashed, so we can't retrieve them and then migrate them. So I'm wondering how we would go about maintaining our existing users' passwords with the new Identity Server approach.

A: I did this quite recently.
We had a legacy .net membership system and needed to import about 10k users over to asp.net identity.   I first created an extra column in the asp .net identity core user table when i copied all of the users from the system i brought their legacy password with them.
Then when the user logged in the first time.  I first checked if the legacy password existed if it did then i validated them against that and update the  password on asp. net identity core and deleted the legacy password. This way all of the users ported their passwords to the new system without even realizing it.
I am going to try and explain how i did it but the code is a bit crazy.
I actually added two columns to the applicationuser table
public string LegacyPasswordHash { get; set; }
public string LegacyPasswordSalt { get; set; }

ApplicationSignInManager -> CheckPasswordSignInAsync method does a check if the user is a legacy user
ApplicationSignInManager
public override async Task<SignInResult> CheckPasswordSignInAsync(ApplicationUser user, string password, bool lockoutOnFailure)
        {
        ........

            if (user.IsLegacy)
            {
                Logger.LogDebug(LoggingEvents.ApplicationSignInManagerCheckPasswordSignInAsync, "[user.Id: {user.Id}] is legacy.", user.Id);
                var results = await new LoginCommand(_logger, _userManager, user, password, lockoutOnFailure).Execute();
                if (results.Succeeded)
                {
                    await ResetLockout(user);
                    return SignInResult.Success;
                }
            }
            else if (await UserManager.CheckPasswordAsync(user, password))
            {
                await ResetLockout(user);
                return SignInResult.Success;
            }

            ........
        }

Login Command
 public class LoginCommand
    {
        private readonly ILogger _logger;
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly ApplicationUser _user;
        private readonly string _password;
        private readonly bool _shouldLockout;

        public LoginCommand(ILogger logger, UserManager<ApplicationUser> userManager, ApplicationUser user, string password, bool shouldLockout)
        {
            _logger = logger;
            _userManager = userManager;
            _user = user;
            _password = password;
            _shouldLockout = shouldLockout;
        }

        public async Task<SignInResult> Execute()
        {
            _logger.LogInformation($"Found User: {_user.UserName}");
            if (_user.IsLegacy)
                return await new LegacyUserCommand(_logger, _userManager, _user, _password, _shouldLockout).Execute();
            if (await _userManager.CheckPasswordAsync(_user, _password))
                return await new CheckTwoFactorCommand(_logger, _userManager, _user).Execute();
            if (_shouldLockout)
            {
                return await new CheckLockoutCommand(_logger, _userManager, _user).Execute();
            }
            _logger.LogDebug($"Login failed for user {_user.Email} invalid password");
            return SignInResult.Failed;
        }
    }

LegacyUserCommand
  public class LegacyUserCommand
    {
        private readonly ILogger _logger;
        private readonly UserManager<ApplicationUser> _userManager;

        private readonly ApplicationUser _user;
        private readonly string _password;
        private bool _shouldLockout;

        public LegacyUserCommand(ILogger logger, UserManager<ApplicationUser> userManager, ApplicationUser user, string password, bool shouldLockout)
        {
            _logger = logger;
            _userManager = userManager;
            _user = user;
            _password = password;
            _shouldLockout = shouldLockout;
        }

        public async Task<SignInResult> Execute()
        {
            try
            {
                if (_password.EncodePassword(_user.LegacyPasswordSalt) == _user.LegacyPasswordHash)
                {
                    _logger.LogInformation(LoggingEvents.LegacyUserCommand, "Legacy User {_user.Id} migrating password.", _user.Id);
                    await _userManager.AddPasswordAsync(_user, _password);
                    _user.SecurityStamp = Guid.NewGuid().ToString();
                    _user.LegacyPasswordHash = null;
                    _user.LegacyPasswordSalt = null;
                    await _userManager.UpdateAsync(_user);
                    return await new CheckTwoFactorCommand(_logger, _userManager, _user).Execute();
                }
                if (_shouldLockout)
                {
                    _user.SecurityStamp = Guid.NewGuid().ToString();
                    await _userManager.UpdateAsync(_user);
                    _logger.LogInformation(LoggingEvents.LegacyUserCommand, "Login failed for Legacy user {_user.Id} invalid password. (LockoutEnabled)", _user.Id);
                    await _userManager.AccessFailedAsync(_user);
                    if (await _userManager.IsLockedOutAsync(_user))
                        return SignInResult.LockedOut;
                }

                _logger.LogInformation(LoggingEvents.LegacyUserCommand, "Login failed for Legacy user {_user.Id} invalid password", _user.Id);
                return SignInResult.Failed;
            }
            catch (Exception e)
            {
                _logger.LogError(LoggingEvents.LegacyUserCommand, "LegacyUserCommand Failed for [_user.Id: {_user.Id}]  [Error Message: {e.Message}]", _user.Id, e.Message);
                _logger.LogTrace(LoggingEvents.LegacyUserCommand, "LegacyUserCommand Failed for [_user.Id: {_user.Id}] [Error: {e}]", _user.Id, e);
                return SignInResult.Failed;
            }
        }
    }

TOP TIP: [SecurityStamp] an not be NULL!

A: We've recently migrated from various legacy systems and since they all used various forms of hashing passwords, rather than trying to port that logic over we customised the password authentication code to allow it to do a call out to an API exposed by each legacy system. Each user migrated from such a system had the API URL stored against it.
When a migrated user signs in for the first time we make a call out to said service (which itself was secured using a bearer token and a restricted integration scope) to do the password authentication that first time. If we get a success response then we hash the password in our own format and that is used forever more.
The downside of this is that you do have to keep the old system up (with this new API bolted on) pretty much forever. Since it's all .Net you may fare better by keeping it all in-proc and copying the migrated user hashed passwords to your new DB, assuming you can get an implementation of the old hashing scheme running inside .Net Core.


text:
Q: access each value of associative array hello how can i access or echo each element of this associative array

Array
(
    [0] => Array
        (
            [rule] => admin/user
            [title] => Users Management
            [target] => _parent
            [0] => Array
                (
                    [0] => Array
                        (
                            [rule] => admin/user/add
                            [title] => Add New User
                        )

                )

        )

    [1] => Array
        (
            [rule] => admin/category
            [title] => Category Mangement
            [target] => _parent
            [0] => Array
                (
                    [0] => Array
                        (
                            [rule] => admin/category/add
                            [title] => Add New Category
                        )

                )

        )

)

I want to know which loop will support this and how

A: I suppose that using array_walk_recursive(), with a callback function that would do an echo, would be quite a good solution.


text:
Q: How to populate Constraintlayout as view in carousel apdapter in motionlayout android? I'm trying to use carousel widget in motionlayout for making OnBoardActivity. I'm create three layout contain first, second and third layour. Then I create on_board_activity layout. This is my code:
 <androidx.constraintlayout.motion.widget.MotionLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutDescription="@xml/activity_on_board_scene">

<include
    android:id="@+id/first"
    layout="@layout/first_intro"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<include
    android:id="@+id/second"
    layout="@layout/second_intro"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<include
    android:id="@+id/third"
    layout="@layout/third_intro"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<androidx.constraintlayout.helper.widget.Carousel
    android:id="@+id/carousel"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:carousel_backwardTransition="@+id/backward"
    app:carousel_firstView="@+id/second"
    app:carousel_forwardTransition="@+id/forward"
    app:carousel_infinite="true"
    app:carousel_nextState="@+id/next"
    app:carousel_previousState="@+id/previous"
    app:constraint_referenced_ids="first,second, third" />
  </androidx.constraintlayout.motion.widget.MotionLayout>

I create file activity_on_board_scene.xml, too. But I can't populate view in kotlin file. How can I do that? What do I need for program run ok?
  override fun populate(view: View, index: Int) {
            // need to implement this to populate the view at the given index
            if (view is ConstraintLayout){
               //how can I do that?
            }
        }

A: Carousel allows you to animate using 3  ConstraintSets defined in a MotionScene
It does not use 3 layouts.
In general Carousel is a MotionLayout helper you
should have some working idea how MotionLayout works.

*

*Here is a Carousel demo app

*An explanation of how a
Carousel works

*Introduction Videos on MotionLayout parts


text:
Q: Docker: Empty response from server I am having trouble to connect docker container, server returns empty response however the configuration seems to be correct.
When i use docker-compose up command everything seems fine and working however i am getting empty response from server.
I double checked the port mappings however i couldnt notice anything.
Here is the compose file
    version: '3'

    services:
      authapi:
        build:
          dockerfile: ./docker/Dockerfile.dev
          context: .
        restart: always
        volumes:
          - .:/usr/src/auth
          - /usr/src/auth/node_modules
        environment:
          FBAPPID: ${FBAPPID}
          FBAPPSECRET: ${FBAPPSECRET}
          GOOGLEAPPID: ${GOOGLEAPPID}
          GOOGLEAPPSECRET: ${GOOGLEAPPSECRET}
          GITHUBAPPID: ${GITHUBAPPID}
          GITHUBAPPSECRET: ${GITHUBAPPSECRET}
        ports:
          - ${PORT}:${PORT}
        command:
          - sh
          - -c
          - sleep 20 && npm run start:dev
        depends_on:
          - psql
      psql:
        image: postgres:10-alpine
        ports:
          - 5432:5432
        environment:
          POSTGRES_USER: ${PG_USER}
          POSTGRES_PASSWORD: ${PG_PASSWORD}
          POSTGRES_DB: ${PG_DB}
        volumes:
          - ./pg-data:/var/lib/postgresql/data

Dockerfile
    FROM node:10-alpine

    WORKDIR /usr/src/auth

    COPY ./package.json .

    RUN npm install

    COPY . .

    EXPOSE 9091

    CMD ["npm", "run", "start:prod"]

docker port response
9091/tcp -> 0.0.0.0:9091

docker ps response
CONTAINER ID        IMAGE                 COMMAND
CREATED             STATUS              PORTS                    NAMES
cecbf815523e        authservice_authapi   "sh -c 'sleep 20 && …"   15
minutes ago      Up 15 minutes       0.0.0.0:9091->9091/tcp
authservice_authapi_1
4e5c5f312703        postgres:10-alpine    "docker-entrypoint.s…"   15
minutes ago      Up 15 minutes       0.0.0.0:5432->5432/tcp
authservice_psql_1

here is docker network
NETWORK ID          NAME                  DRIVER              SCOPE
3bb18805e2b1        authservice_default   bridge              local
f7fb02e95fc3        bridge                bridge              local
815dccd6c8b8        host                  host                local
12ca56c3c08d        none                  null                local

authservice_default inspect response
        [
      {
          "Name": "authservice_default",
          "Id": "3bb18805e2b129342ce255017c88b8d72717f050419503d81042f5319b5f5009",
          "Created": "2018-09-26T18:24:01.3773204Z",
          "Scope": "local",
          "Driver": "bridge",
          "EnableIPv6": false,
          "IPAM": {
              "Driver": "default",
              "Options": null,
              "Config": [
                  {
                      "Subnet": "172.18.0.0/16",
                      "Gateway": "172.18.0.1"
                  }
              ]
          },
          "Internal": false,
          "Attachable": true,
          "Ingress": false,
          "ConfigFrom": {
              "Network": ""
          },
          "ConfigOnly": false,
          "Containers": {
              "4e5c5f3127036fe300ec2917fd6023d00ca8d3c4e28b583107c2deabc6fd2dda": {
                  "Name": "authservice_psql_1",
                  "EndpointID": "461b8164f174d436a4a039ff9ff494cac3bc5f6f96c1b8d0619928c8dafb6652",
                  "MacAddress": "02:42:ac:12:00:02",
                  "IPv4Address": "172.18.0.2/16",
                  "IPv6Address": ""
              },
              "cecbf815523e4028c2b9cb1d74104ef61cc8fb8947624c9df8f035193842a9b0": {
                  "Name": "authservice_authapi_1",
                  "EndpointID": "af30a79b70d675002f12bd61ca8aed2d8d5f036bd99c10fa7a205cf3e21ae19b",
                  "MacAddress": "02:42:ac:12:00:03",
                  "IPv4Address": "172.18.0.3/16",
                  "IPv6Address": ""
              }
          },
          "Options": {},
          "Labels": {
              "com.docker.compose.network": "default",
              "com.docker.compose.project": "authservice",
              "com.docker.compose.version": "1.22.0"
          }
      }
    ]

logs of containers
    [nodemon] starting `node ./src/babel.start.js`
    {"level":30,"time":1537987440400,"msg":"Server listening at http://127.0.0.1:9091","pid":63,"hostname":"cecbf815523e","v":1}
    |-----------------------------Start-----------------------------|
    |                                                               |
    |              Server started on http://127.0.0.1:9091
    |                                                               |
    |---------------------------------------------------------------|
    |-----------------------------CPU INFO--------------------------|
    |                                                               |
    |  Cpu 0: Intel(R) Core(TM) i5-5257U CPU @ 2.70GHz => speed 2697
    |  Cpu 1: Intel(R) Core(TM) i5-5257U CPU @ 2.70GHz => speed 2697
    |                                                               |
    |----------------------TOTAL MEMORY ----------------------------|
    |                                                               |
    |========================> 2 GB
    |                                                               |
    |-----------------------FREE MEMORY-----------------------------|
    |                                                               |
    |========================> 155.5 MB
    |                                                               |
    |------------------------PLATFORM-------------------------------|
    |                                                               |
    |========================> linux v4.9.93-linuxkit-aufs x64
    |                                                               |
    |---------------------------------------------------------------|
    |------------------------IFACE IP-------------------------------|
    |                                                               |
    |========================> 172.18.0.3
    |                                                               |
    |---------------------------------------------------------------|

i dont add here postgress one because application has nothing to do with postgress now.
Everything seems fine from my perspective, am i missing something ? Huge thanks already now for those who tries to help :)

A: I have solved the problem by binding the application to 0.0.0.0 and everything started to work.
I hope it would be useful anybody who are looking for solution for this kind of issue.

A: I had same problem but binding to 0.0.0.0 didn't help, this answer helped me saying that container port should be higher than 1024 because of privileges. I was using default port 80, after exposing 8080 and binding 0.0.0.0 it now started to work

A: I encountered the same problem using Dockerize GatsbyJS. As Halil Irmak's comment, the issue was resolved by binding the application to 0.0.0.0. On my case
yarn develop -H 0.0.0.0 -p 8000

A: I encountered this problem and solved it.
The problem is that, although my HOST config is right, I still receive ERR_EMPTY_RESPONSE.
Here's my solution:
The first time you start strapi with docker is really slow. So if you have done everything right, then just wait for the page to start.
I waited 23 mins at the first time...
If you are wondering whether it's slow or something you did is wrong, you can try this:

*

*find strapi container id: run docker ps

*enter the container: run docker exec -it <container id> bash
(if you can enter the container, maybe you have done everything right.)

*check if the port is open: run echo > /dev/tcp/127.0.0.1/1337
When it says 'bash: /dev/tcp/127.0.0.1/1337: Connection refused', it means your strapi service is not ready yet.
if the command returns nothing, then strapi service is ready. Check http://127.0.0.1:1337/admin , you will find what you want.

A: In my case using node:alpine on dockerfile was the problem for me, just changing the image to the Node.js
It turns out the alpine version is not official. The drawback though is image-size.
I was able to make my API talk normally to my DB passing the DB's container name on the Postgres host variable, and setting up a network in the docker-compose file.
By the way, my setup was Nestjs, TypeORM, Postgres and Docker.


text:
Q: Concat to field after query If I do this
Select kindOfAnimal from animal_table
group by kindOfAnimal

I get cat, dog, cow
How can I change query that I get cat1, dog1, cow1. How to concat to value without change in table?

A: Select CONCAT(kindOfAnimal, '1')
from animal_table
group by kindOfAnimal;

This works?


text:
Q: Wierd behaviour of Listview in android main.xml file is:
<ListView
    android:id="@+id/listViewMovies"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:cacheColorHint="@android:color/transparent"
    android:divider="#0EBDFE"
    android:dividerHeight="2dp"
    android:fadingEdge="none" />

and this is my onclick event of listview:
listViewMovies.setOnItemClickListener(new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> arg0, View view, int pos,
                long arg3) {
        // TODO Auto-generated method stub
        Log.i("MainActivity", "clicked position: " + pos);
        Intent intent = new Intent(getApplicationContext(),
                    MovieDetailsActivity.class);
        intent.putExtra("id", arrayIds.get(pos));
        intent.putExtra("name", arrayTitles.get(pos));
        intent.putExtra("release_date", arrayReleaseDate.get(pos));
        intent.putExtra("casts", arrayAbridgedCast.get(pos));
        intent.putExtra("critics_consensus",
                    arrayCriticsConsensus.get(pos));
        intent.putExtra("synopsis", arraySynopsis.get(pos));
        intent.putExtra("trailor", arrayLinks.get(pos));
        intent.putExtra("thumb_img", arrayThumbPosters.get(pos));
        intent.putExtra("profile_img", arrayProfilePosters.get(pos));
            startActivity(intent);
    }
});

But sometimes click event is called but sometimes it is not.
Can anyone suggest me what should the problem?

A: Are you inflating any xml file having button for your list items. If so then button prevents the click event on list item. To overcome this you can add
<Button
   android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:focusable="false"
    android:focusableInTouchMode="false"/>

hope it will help you..


text:
Q: Web API returning JSON content type instead of XML I am brand-spanking-new to Web API.  I am working on a proof of concept project for my team where we will create SSRS 2012 reports based off of Web-API XML data sources.  However, the Web-API should not be configured to only negotiate XML as the content type.  In a future phase, our web-applications should be able to retrieve json objects from the same controllers/actions.
I began by following this tutorial and everything worked, no problem.
Next I configured my routes so I can call actions directly, and I added QueryStringMappings to my Global.asax so I could specify the content type.
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { id = UrlParameter.Optional }
        );
    }
}

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        GlobalConfiguration.Configuration.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
        GlobalConfiguration.Configuration.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml");
    }
}

This works great and I can now use localhost:XXXXX/api/Products/GetAllProducts/?$format=xml as my data source connection string in SSRS.  I'm not sure if this is the best way to do this, but it worked, so I stuck with it.  Without the query string mappings the data source did not work in SSRS.
Here is where I ran into trouble.  I branched off and created my first model/controller/action.  When I run the project in my browser (chrome or IE 10) and try to specify the format as XML (localhost:XXXXX/api/Calcs/ComputeFooCalculation?$format=xml), I get a json result back.  The Products controller continues to work fine for json or xml content types.  But for some reason my action will only render as json.  Here is what my code looks like.  Let me know if you need models or anything else.  FooCalculation has a nested object Bar. Both FooCalculation and Bar have strings, doubles and DateTimes.
Controller:
public class CalcsController : ApiController
{

    public FooCalculation ComputeFooCalculation()
    {
        var Foo = GetFoo();
        var Bar = GetBar();
        var FooCalculation = new FooCalculation(Foo, Bar);

        return FooCalculation;
    }

}

Sample JSON Result:
{"Foo":"XXX","FooRate":{"Foo":"XXX","Bar":"SN","FooBar":-1.00813E-05,"BarFoo":-3.2644199999999995E-06,"FoooBarrr":-4.17501E-06,"BarDate":"2013-05-14T00:00:00"},"BarRate":{"Foo":"XXX","Bar":"1W","FooBar":-2.08687E-05,"BarFoo":-3.11313E-05,"FoooBarrr":-3.3E-05,"BarDate":"2013-05-21T00:00:00"},"BarDate":"2013-05-20T00:00:00","FooDays":6,"FooBar":-7.3741306716417904E-06,"Bar":-0.0011149741306716415}

Thanks in advance for the help.

A: Place a parameterless constructor in your model class. The XML formatting is trying to instantiate an empty XML tree prior to you retrieving all of your data.


text:
Q: Retrieve the RAW content of an environment variable [no expansion] I have a problem dealing with Windows environment variables in a puppet (configuration management) script. My scripts deal with silent instalation of resources and configuration of their requirements (environment variables, files, etc..)
My problem comes here. One of my scripts installs a JDK in a windows system, this means install the executable, configure JAVA_HOME and JRE_HOME and include %JAVA_HOME%/bin into %PATH%. This is easy to perform through setx commands but has a problem when it comes to performing a second execution of the script: the PATH variable ends up being %PATH%;%JAVA_HOME%/bin;%JAVA_HOME%/bin (and further executions will mean a longer var).
The solution to this side effect is perform the command only if %PATH% does not already contains %JAVA_HOME/bin and that could be performed through an echo %PATH% | find "%JAVA_HOME/bin" only if variables would not be expanded by default...
I have to say, that the previous command fails because JAVA_HOME contains its version (like C:\Program Files\Java\jdk_6u30).
So... it is possible to echo an environment variable without expanding its contents? I only need the RAW variable at find command, nothing more.

A: You can read the PATH directly from the registry:
reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path

This will allow to get it's value without expansion.


text:
Q: How to use a single .class file in a java package? I want to write a code like this
package mypackage;
public class A extends B {
}

But all that I have is the B.class file which is compiled from a single B.java file with no package specified.
Could anyone help me out?
Thanks!
I've tried putting B.class in my ./src and A.java in ./src/mypackage and run javac -cp src ./src/package/A.java but it wouldn't compile. It wouldn't compile neither if I put B.class in the same folder as A.java

A: You can't. By your description, class B is in the default (unnamed) package. The Java language rules do not allow classes outside the default package to refer to classes in the default package.
The only way you can use this class is to put A in the default package as well. That is, move it one directory up, and remove the package statement.
Alternatively, you need to have the sources of class B (or decompile it), move it into a package and add a package statement, and recompile.


text:
Q: averageCenter on markerclusterer I am using the google maps API to cluster markers.
For the moment the cluster center is set on the first marker added to it.
Is there a way to put it in the average of all locations?
I am using the google map API V2 in android.
thanks,
EDIT: on this website they are talking about an attribute to set "averageCenter" http://component.kitchen/components/timeu/google-map-markerclusterer
is there an equivalent for android ?

A: If you are using the Google Maps Android API utility library in your project, you can change the algorithm used for clustering.
The default algorithm used is the NonHierarchicalDistanceBasedAlgorithm (you can find the class file in library/src/com/google/maps/android/clustering/algo/).
Now you can:

*

*either edit the source code of the  class,

*or create a new class extending NonHierarchicalDistanceBasedAlgorithm and overriding the getClusters(double) method. Then, use an instance of this class with your ClusterManager using setAlgorithm(Algorithm).

The changes that need to be made in order to calculate the center position of clusters can be found in this commit (I chose to edit the class directly). I did not measure the impact of these changes on the clustering calculation's speed though.

Edit: currently, a simple average is used to calculate the cluster's position, which is incorrect for latitude/longitude coordinates but is a bit faster.
You can find a better center calculation algorithm here: https://stackoverflow.com/a/14231286.


text:
Q: WCF ResponseFormat For WebGet WCF offers two options for ResponseFormat attribute in WebGet annotation in ServiceContract.
[ServiceContract]
public interface IService1
{
    [OperationContract]
    [WebGet(UriTemplate = "greet/{value}", BodyStyle = WebMessageBodyStyle.Bare)]
    string GetData(string value);

    [OperationContract]
    [WebGet(UriTemplate = "foo", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
    string Foo();

The options for ResponseFormat are WebMessageFormat.Json and WebMessageFormat.Xml. Is it possible to write my own web message format? I would like that when client calls foo() method he gets raw string - without json or xml wrappers.

A: WebGetAttribute is shipped by Microsoft, and I don't think you can extend WebMessageFormat. However you could probably extend the WebHttpBinding that uses WebGetAttribute. You could add your own attribute like
[WebGet2(UriTemplate = "foo", ResponseFormat = WebMessageFormat2.PlainText)]
string Foo();

In general, customizing the message layout in WCF is called custom message encoder/encoding. Microsoft provides an example: Custom Message Encoder: Compression Encoder. Also another common extension people do is to extend behavior to add custom error handling, so you could look for some example in that direction.

A: Try using
BodyStyle = WebMessageBodyStyle.Bare

Then return a System.IO.Stream from your function.
Here's some code I use to return an image out of a database, but accessible via a URL:
[OperationContract()]
[WebGet(UriTemplate = "Person/{personID}/Image", BodyStyle = WebMessageBodyStyle.Bare)]
System.IO.Stream GetImage(string personID);

Implementation:
public System.IO.Stream GetImage(string personID)
{
    // parse personID, call DB

    OutgoingWebResponseContext context = WebOperationContext.Current.OutgoingResponse;

    if (image_not_found_in_DB)
    {
        context.StatusCode = System.Net.HttpStatusCode.Redirect;
        context.Headers.Add(System.Net.HttpResponseHeader.Location, url_of_a_default_image);
        return null;
    }

    // everything is OK, so send image

    context.Headers.Add(System.Net.HttpResponseHeader.CacheControl, "public");
    context.ContentType = "image/jpeg";
    context.LastModified = date_image_was_stored_in_database;
    context.StatusCode = System.Net.HttpStatusCode.OK;
    return new System.IO.MemoryStream(buffer_containing_jpeg_image_from_database);
}

In your case, to return a raw string, set the ContentType to something like "text/plain" and return your data as a stream. At a guess, something like this:
return new System.IO.MemoryStream(ASCIIEncoding.Default.GetBytes(string_to_send));

A: I implemented this attribute like this, maybe it will help someone in the future:
[AttributeUsage(AttributeTargets.Method)]
public class WebGetText : Attribute, IOperationBehavior
{

    public void Validate(OperationDescription operationDescription)
    {
    }

    public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
    {
        dispatchOperation.Formatter = new Formatter(dispatchOperation.Formatter);
    }

    public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
    {
    }

    public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
    {
    }
}

public class Formatter : IDispatchMessageFormatter
{
    IDispatchMessageFormatter form;

    public Formatter (IDispatchMessageFormatter form)
    {
         this.form = form;
    }

    public void DeserializeRequest(Message message, object[] parameters)
    {
        form.DeserializeRequest(message, parameters)
    }

    public Message SerializeReply(MessageVersion messageVersion, object[] parameters, object result)
    {
        IEnumerable<object> cl = (IEnumerable<object>)result;
        StringBuilder csvdata = new StringBuilder();

        foreach (object userVariableClass in cl) {
            Type type = userVariableClass.GetType();
            PropertyInfo[] fields = type.GetProperties();

            //            Dim header As String = String.Join(";", fields.Select(Function(f) f.Name + ": " + f.GetValue(userVariableClass, Nothing).ToString()).ToArray())
            //            csvdata.AppendLine("")
            //            csvdata.AppendLine(header)
            csvdata.AppendLine(ToCsvFields(";", fields, userVariableClass));
            csvdata.AppendLine("");
            csvdata.AppendLine("=====EOF=====");
            csvdata.AppendLine("");
        }
        Message msg = WebOperationContext.Current.CreateTextResponse(csvdata.ToString());
        return msg;
    }

    public static string ToCsvFields(string separator, PropertyInfo[] fields, object o)
    {
        StringBuilder linie = new StringBuilder();

        foreach (PropertyInfo f in fields) {
            if (linie.Length > 0) {
            }

            object x = f.GetValue(o, null);

            if (x != null) {
                linie.AppendLine(f.Name + ": " + x.ToString());
            } else {
                linie.AppendLine(f.Name + ": Nothing");
            }
        }

        return linie.ToString();
    }
}

A: There is one way how to achieve this if you're dealing with HTTP, it's not exactly nice, but I thought I could mention it.
You can set the return type of your method to void and just output your raw string directly into the response.
[OperationContract]
[WebGet(UriTemplate = "foo")]
void Foo()
{
   HttpContext.Current.Response.Write("bar");
}