text:
Q: heroku build failed. "mongoUrl"://"mongodb........" syntax error and more I must admit, I'm quite a beginner in programming.
I'm doing an online course where I want to connect an api using heroku and mongodb. I think I've got some problems following the instructions because the video is older than the current state of heroku and mongodb.
I managed to git push heroku master but when I got to heroku and start the app it says an error occured. Then I ran heroku logs --tail, I checked my build and this showed
-----> Node.js app detected

-----> Creating runtime environment

       NPM_CONFIG_LOGLEVEL=error

       NODE_ENV=production

       NODE_MODULES_CACHE=true

       NODE_VERBOSE=false

-----> Installing binaries

       engines.node (package.json):  8.10.0

       engines.npm (package.json):   unspecified (use default)

       Resolving node version 8.10.0...

       Downloading and installing node 8.10.0...

       Using default npm version: 5.6.0

-----> Installing dependencies

       Installing node modules (package.json)

       > uws@9.14.0 install /tmp/build_63fff292b65e6a987cf3dc9195527d57/node_modules/uws

       > node-gyp rebuild > build_log.txt 2>&1 || exit 0

       > core-js@2.6.10 postinstall /tmp/build_63fff292b65e6a987cf3dc9195527d57/node_modules/core-js

       > node postinstall || echo "ignore"

       added 608 packages in 32.816s

-----> Build

       Running build

       > slacky-slack@1.0.0 build /tmp/build_63fff292b65e6a987cf3dc9195527d57

       > babel src -s -D -d dist --presets es2015,stage-0

SyntaxError: src/config/index.js: Unexpected token, expected , (7:21)

   5 |   // "mongoUrl": "mongodb://localhost:27017/chat-api",

   6 |   "port": process.env.PORT,

>  7 |   "mongoUrl": mongodb://esteP:<CEpalacios2019>@chattychatchat-shard-00-00-6ydjb.mongodb.net:27017,chattychatchat-shard-00-01-6ydjb.mongodb.net:27017,chattychatchat-shard-00-02-6ydjb.mongodb.net:27017/test?ssl=true&replicaSet=chattychatchat-shard-0&authSource=admin&retryWrites=true&m=majority ,

     |                      ^

   8 |   "bodyLimit": "100kb"

   9 | }

  10 |

npm ERR! code ELIFECYCLE

npm ERR! errno 1

npm ERR! slacky-slack@1.0.0 build: `babel src -s -D -d dist --presets es2015,stage-0`

npm ERR! Exit status 1

npm ERR!

npm ERR! Failed at the slacky-slack@1.0.0 build script.

npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:

npm ERR!     /tmp/npmcache.5odQG/_logs/2019-10-19T12_28_48_165Z-debug.log

-----> Build failed

       We're sorry this build is failing! You can troubleshoot common issues here:

       https://devcenter.heroku.com/articles/troubleshooting-node-deploys

FYI this index.js file looks like this import mongodb from 'mongodb'; export default { // "port": 3005, // "mongoUrl": "mongodb://localhost:27017/chat-api", "port": process.env.PORT, "mongoUrl": "mongodb://esteP:<**********>@chattychatchat-shard-00-00-6ydjb.mongodb.net:27017,chattychatchat-shard-00-01-6ydjb.mongodb.net:27017,chattychatchat-shard-00-02-6ydjb.mongodb.net:27017/test?ssl=true&replicaSet=chattychatchat-shard-0&authSource=admin&retryWrites=true&w=majority", "bodyLimit": "100kb" }
I don't understand most of these errors, except for the syntax error, but I don't know where is the problem.
Thanks for all the help you can give to this noob :)

A: Try to edit src/config/index.js and change this:
"mongoUrl": mongodb://esteP:<CEpalacios2019>@chattychatchat-shard-00-00-6ydjb.mongodb.net:27017,chattychatchat-shard-00-01-6ydjb.mongodb.net:27017,chattychatchat-shard-00-02-6ydjb.mongodb.net:27017/test?ssl=true&replicaSet=chattychatchat-shard-0&authSource=admin&retryWrites=true&m=majority

to this:
"mongoUrl": "mongodb://esteP:<CEpalacios2019>@chattychatchat-shard-00-00-6ydjb.mongodb.net:27017,chattychatchat-shard-00-01-6ydjb.mongodb.net:27017,chattychatchat-shard-00-02-6ydjb.mongodb.net:27017/test?ssl=true&replicaSet=chattychatchat-shard-0&authSource=admin&retryWrites=true&m=majority"


text:
Q: Select data within a date range using form I would like to search a mysql database for a list of products that have been inserted between a date range.
Say I have a table called product which has: id, name, brand, and datecreated, I can do this in mysql:
select id, name, brand, datecreated
  from product
 where datecreated between '2013-09-12' and '2013-10-10'
 order by datecreated desc;

This will obviously return the desired result either in Mysql or within php.
However I would like to define the date range in the select statement with a form which asks the user for the to and from dates.  Not sure what the method will be either ?
    <form action="?" method="">

            Enter your dates here:

            From:<textarea id="fromdate" name="fromdate" rows="1" cols="5"></textarea>
            <lablel for="todate">To:<textarea id="todate" name="todate" rows="1" cols="5"></textarea>

<input type="submit" value="Search"/>

    </form>

So what I am unsure of is how the user defined date range from the form can be added/inserted to the select statement to return the data within the defined date range?
Cheers
Volterony

A: The user-submitted values would come in as $_POST['fromdate'] and $_POST['todate'], or $_GET['fromdate'] and _$GET['todate'], depending on whether your form method above was post or get (I'd generally recommend post in case there is a specific reason for using get, like wanting to bookmark the page).
So your code to handle this could look something like this (assuming $pdo is your database PDO object):
$fromdate = new DateTime( $_POST['fromdate'] );
$todate   = new DateTime( $_POST['todate'] );

$query = <<<SQL
  SELECT id, name, brand, datecreated
    FROM product
   WHERE datecreated BETWEEN :fromdate AND :todate
   ORDER BY datecreated desc
SQL;

$result = $pdo->prepare( $query );
$result->execute( array(
    ":fromdate" => $fromdate->format( "Y-m-d" ),
    ":todate"   => $todate->format( "Y-m-d" );
));

$rows = $result->fetchAll( PDO::FETCH_ASSOC ):

$rows now contains an array of all of the rows of your table that match the specified criteria.

A: The exact syntax depends on how you're interacting with your database (MySQLi, PDO, etc.).  You basically need to take the POSTed form values, do some straightforward validation to make sure that the user hasn't entered anything dangerous, then insert the values into the query:
$from = mysqli_real_escape_string($_POST['fromdate']);
$to = mysqli_real_escape_string($_POST['todate']);
$sql = "select id, name, brand, datecreated from product where datecreated between '$from' and
'$to' order by datecreated desc";

The action on the form would be whichever page you place the above code in - it could be the same page as the form.  In that case, the action would be <?php echo basename($_SERVER['PHP_SELF']); ?> and the method would be POST.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Practical vs. theoretical buck converter I am currently looking at open loop buck converters. I am running it with the following:

*

*Switching frequency (f) = 62500

*Inductance (L) = 100e-6

*Input voltage (Vi) = 5

*Output current (Io) = 0.06

Using this, I changed the output resistance to observe how the buck behaves for a fixed output current and input voltage and changed the output resistance.
Using this I was able to obtain the following:

There are some things about this I am struggling to understand.
The equation used for CCM, continuous mode is Vo/Vi = duty cycle.
The equation used for DCM, discontinuous mode is
$$\frac{V_o}{V_i} = \frac{1}{1+ \frac{\displaystyle 2fLI_o}{\displaystyle V_i*D^2}}$$
Question 1: Why is it that the data gathered experimentally is different the theoretical one?
Question 2: The buck seems to enter and leave DCM between 0.2 and 0.8. I don't really understand why this is I tried doing it mathematically can't seem to see why this is.
Question 3: Between 0 and 0.2 duty cycle, it seems to be DCM and not CCM. Why is this?
Question 4: Between 0.8 and 1 duty cycle, it seems to be CCM and not DCM. Why is this?

A:
Question 1: Why is it that the data gathered experimentally is
different the theoretical one?

Your simplified theoretical model doesn't take into account all the relevant properties of the physical circuit.

Question 2: The buck seems to enter and leave DCM between 0.2 and 0.8.
I don't really understand why this is I tried doing it mathematically
can't seem to see why this is.

Your graph provides a clue to why the transition occurs at ~20% and 80% PWM, as at these points the same output voltage occurs with both DCM and CCM. If you examine the current waveform for CCM you should notice that between 20% and 80% the minimum current in the triangle wave is negative, which is not possible with a single-ended drive (switch plus flyback diode).

Question 4: Between 0.8 and 1 duty cycle, it seems to be CCM and not
DCM. Why is this?

At 100% PWM the inductor current must be continuous. Whether it will be continuous or discontinuous at lower PWM ratios depends on how much it changes as it ramps up and down. With the PWM frequency, inductance and current you chose it will be discontinuous at medium PWM ratios.
To illustrate this I put your values into a half bridge ('synchronous') buck converter circuit and simulated it in LTspice using 'real' components. At 50% PWM the result was this:-

The green line is the output voltage (2.5V with a small ripple). The blue square wave is the voltage across the inductor, and the red triangle wave is the current going through it. In the first 8 ms the current rises by 200 mA as the inductor has +2.5 V across it, then in the next 8 ms the current falls by the same amount as the inductor voltage switches to -2.5V. In order for the average current to be 60 mA it must swing from -40 mA to +160 mA.
If the circuit is changed to a single switch with flyback diode the current cannot go negative because the diode switches off, producing a discontinuous current waveform:-

Here we see that apart from some ringing while the diode is off, the current does not go below zero during the flyback phase. As a result the peak current required to get 60 mA average is a bit less. The flyback diode has a voltage drop of ~0.7 V when conducting, which raises the inductor voltage and increases the ramp down rate, while in the PWM on phase the inductor voltage is reduced so the current ramps up slower. To balance this the output voltage increases to just over 3 V.


text:
Q: Calling existing C code from C# I am trying to call functions from a c library in c#. I received this library from a manufacturer of some hardware that is connected to my computer. I have read about using dlls to achieve this; However, all of the tutorials I have seen focus on linking some existing dll or a new dll solution to a c# solution.
I'm having trouble understanding how to go about generating the dll files from an existing c project. My current understanding is that I should create a new c dll project and add the classes that I am making calls to and simply make wrappers for them using pinvoke.
Is this a correct mindset? It seems like there should be more to this involving any dependencies and imports that these classes have. Is there a simpler solution that would just allow me to link one function?
To address the duplicate question: I am not asking how to link a c dll to c#, I am asking about the process of making the dll from a c solution that builds an exe. This is a step that I believe must be done before the solution linked.


text:
Q: Computer Vision: labelling camera pose I am trying to create a dataset of images of objects at different poses, where each image is annotated with camera pose (or object pose).
If, for example, I have a world coordinate system and I place the object of interest at the origin and place the camera at a known position (x,y,z) and make it face the origin. Given this information, how can I calculate the pose (rotation matrix) for the camera or for the object.
I had one idea, which was to have a reference coordinate i.e. (0,0,z') where I can define the rotation of the object. i.e. its tilt, pitch and yaw. Then I can calculate the rotation from (0,0,z') and (x,y,z) to give me a rotation matrix. The problem is, how to now combine the two rotation matrices?
BTW, I know the world position of the camera as I am rendering these with OpenGL from a CAD model as opposed to physically moving a camera around.

A: The homography matrix maps between homogeneous screen coordinates (i,j) to homogeneous world coordinates (x,y,z).
homogeneous coordinates are normal coordinates with a 1 appended. So (3,4) in screen coordinates is (3,4,1) as homogeneous screen coordinates.
If you have a set of homogeneous screen coordinates, S and their associated homogeneous world locations, W. The 4x4 homography matrix satisfies
S * H = transpose(W)
So it boils down to finding several features in world coordinates you can also identify the i,j position in screen coordinates, then doing a "best fit" homography matrix (openCV has a function findHomography)
Whilst knowing the camera's xyz provides helpful info, its not enough to fully constrain the equation and you will have to generate more screen-world pairs anyway. Thus I don't think its worth your time integrating the cameras position into the mix.
I have done a similar experiment here: http://edinburghhacklab.com/2012/05/optical-localization-to-0-1mm-no-problemo/


text:
Q: Error when using sql query containing IFNULL and serial number column in Phoenix I have a SQL query as follows:
Select
    @sl:=@sl+1 as slNum,
    IFNULL(startTime,'-'),
from
    race,
    (Select @s1:=0) x ;

I get the desired result when i run the above query in mysql, but I want to execute the same query on Phoenix for the table stored in Hbase.
I get the following error for @sl:
org.apache.phoenix.exception.PhoenixParserException: ERROR 601 (42P00): Syntax error. Encountered "@" at line 'x', column 'y'.
Caused by: NoViableAltException(15@[])

And when I comment out the serial number, i get this:
org.apache.phoenix.exception.PhoenixParserException: ERROR 603 (42P00): Syntax error. Unexpected input. Expecting "LPAREN", got "IFNULL" at line x2, column y2.
Caused by: UnwantedTokenException(found=IFNULL, expected 91)

Does Phoenix not support them or is there some other way of doing this?
Any suggestions will be helpful.

A: I don't know whether or not Phoenix supports dynamic SQL, but there is a way to generate row number without dynamic SQL:
SELECT
    COALESCE(r1.startTime, '-') AS startTime
    (SELECT COUNT(*) FROM race r2 WHERE r2.startTime <= r1.startTime) slNum
FROM race r1;

I assume that the start time provides the ordering.  Your current logic is not well defined using row number without an ordering.  You may replace startTime with another column in the WHERE clause of my subquery.


text:
Q: How to import the 'listpicker' control in vs2012 for windows phone 8? I downloaded the Silverlight for windows phone Toolkit,but I don't konw how to import it to vs2012.I searched the method on the Internet,only finding the method for vs2010.And I found it doesn't fit for vs2012.So what's the method for vs2012 to import the Toolkit to use the control 'listpicker'?

A: A great free extension for Visual Studio 2012 is the NuGet Package Manager. It will handle the adding or removing of packages to your VS project. I used this to import the ToolKit.
Once NuGet is installed, in VS go to Project > Manage NuGet Packages... Search for "Windows Phone Toolkit" and click Install. That's it.


text:
Q: Projecting from custom spatial reference? I have a shapefile with a WKT spatial reference below:
PROJCS["Prj_suplic",GEOGCS["Geo_suplic",DATUM["",SPHEROID["",1.0,0.0]],PRIMEM["",0.0],UNIT["",1.0]],PROJECTION["Aitoff"],PARAMETER["False_Easting",0.0],PARAMETER["False_Northing",0.0],PARAMETER["Central_Meridian",0.0],UNIT["Meter",1.0]]

How can I project from it to another standard spatial reference such as epsg:3857?
details
the data and spatial reference comes from this website
.
I can export arcgis json file from this website, however,when i try to converse it to a shpaefile through ArcMap -> ArcToolbox -> Conversion Tools -> JSON TO Features, it fail. A error message" coordinates out of bounds" showed. Although I search on the google .It seems that no one has faced a problem like that.
In order to make sure that the problem is lead by the spatial reference.Firstly, I create a custom spatial reference the same as it in the arcgis. Secondly, I created a shapefile with this spatial reference, and add some features to it. Thirdly, I export the shapefile to json with the json to features tool. In the end, I try to convert the output json file back to shp and it fail and show the same error message.
So can any one give me some solutions. It won't be restricted to projecting. Any other solution that can adjust the data to  normal position is welcome.

A: I don't think the coordinate reference system is correct. it's on a sphere of radius=1m while the units are equivalent to radians. When I try to unproject the reported extent values from the website to radians, and then to decimal degrees, I get an extent that covers most of the world. Here's the input and output values (in radians):
   Esri Projection Engine version 10.5.1.7203
   84433.24213013862 9814.51376415799
   171427.5913951584 53914.07924522892
   84433.24213013862 53914.07924522892
   171427.5913951584 9814.51376415799

   2.047708176973035       0.1960157648041461
   0.2740195567333302      0.08569952216737914
  -2.106671846975123       0.8374317581680009
  -1.102894630172711      -0.05991882886180464

The first output pair, converted to degrees, is at 11N, 117E. So there is likely some other obfuscation going on.


text:
Q: Como utilizar a função ROUND no Laravel insira o código aquiTenho a seguinte consulta no PHP:
$transferencia = $conecta->rawSelect(
    'SELECT * FROM register WHERE ROUND(valor,2)="' . $json->VALORLIQUIDO . '"  '
);

Como realizo essa mesma consulta utilizando o Eloquent Laravel?
Esse campo valor é um valor float.
tentei assim
$transferencia = Register::where('valor',$json->VALORLIQUIDO)->get()

Ele não encontra nenhum resultado, mesmo sendo certo que tem esse registro no banco, como a coluna tem um valor float a consulta não localiza o resultado.
Então preciso entender como realizar uma consulta no laravel utilizando o eloquent para buscando registros em colunas que tenha valores float.

A: Presumindo que vc tem o model de register criado corretamente.
$transferencia = Register::where('ROUND(valor,2)',$json->VALORLIQUIDO)->get();
$transferencia = Register::whereRaw('ROUND(valor,2)',$json->VALORLIQUIDO)->get();

DB::table('register')->whereRaw('ROUND(valor,2)', $json->VALORLIQUIDO)->get();
DB::table('register')->whereRaw('ROUND(valor,2)="' . $json->VALORLIQUIDO . '"')->get();

De uma testada nesses e dai um feedback


text:
Q: file extension with .o in cmake I am working on a C project. I am using cmake as build generator.
I have set the below things in my cmakelists.txt just below project() command
set(CMAKE_C_OUTPUT_EXTENSION_REPLACE 1)
set(CMAKE_ASM_OUTPUT_EXTENSION_REPLACE 1)
set(CMAKE_C_OUTPUT_EXTENSION .o)
set(CMAKE_ASM_OUTPUT_EXTENSION .o)

I have files with .c extensions and assembly files with .s extensions.
During compilation, i see that files are created with .obj extension(file.c --> file.obj)
my expectation is with .o extension(file.c --> file.o).
anything i have to set apart from the above commands ?


text:
Q: UnsatisfiableError: pyqt and py-opencv in conflict For my College project, i tried installing pyqt with command conda install pyqt=4 but it shows error as shown below (even this error comes after solving environment for few minutes).
I am new to these stuffs, can anyone please help me over this!
(tensorflow_cpu) F:\BE project\TensorFlow\addons\labelImg>conda install pyqt=4

Solving environment: failed
UnsatisfiableError: The following specifications were found to be in conflict:
- py-opencv
- pyqt=4

Use "conda info <package>" to see the dependencies for each package.

A: The problem is that py-opencv requires python 3.6 or above where as pyqt=4 requires python2.7. Hence there will be a conflict between these two packages.
To avoid this conflict and use both the packages together, follow the below steps. Note that here the pyqt version will get upgrade to 5.9.2
Commands:
Create a new conda environment to avoid package mismatches.
conda create -n pyqt python=3.6

Here pyqt is the conda environment name
Activate the environment:
activate pyqt

Install py-opencv
conda install -c anaconda py-opencv

Install pyqt package:
conda install -c alges pyqt

While executing this step, pyqt version will be 5.9.2
Now you will be able to use both the packages with python3.6


text:
Q: How do you create a "Class initiated" Event or is there one? I want to have an event that is triggered when a class instance is created. I would like to have this happen from within the class. I know I could just raise the event one line after the new instance code is executed, but that defeats the OOD purpose if you have several places where the class is re-newed.
I tried to raise event from Sub New, and that results in the trigger being fired, but the instance is not created at that time, so when the event handler fires the instance is nothing.

A: Solution - use a factory method with shared event

public class MyClass

    public shared event SomeEvent As EventHandler

    private sub New()
    end sub

    public shared sub CreateInstance()
        Dim instance as new MyClass()
        RaiseEvent SomeEvent(instance, new EventArgs())
        return instance;
    End Sub

end class

Consume
AddHandler MyClass.SomeEvent, AddressOf SomeHandlerMethod

dim cls as MyClass = MyClass.CreateInstance()

SomeHandlerMethod will run before you get cls


text:
Q: Loading an Iframe With JQuery (Correct Method) Which is the correct way to load an Iframe using JQuery?
Actually I have a menu with several links and I want to load each link into The Iframe whenever user clicks on it. I am working on an ASP.NET website with my default page having this menu and Iframe both inside it.
I used Target="IframeName" but I dont want this method due to some other problem with it.
So Please tell me how to create a JQuery function to load such an Iframe.
I searched for it and I Found several methods but no one seems to be working and I am struck with it , Moreover I am not able to understand which one is right.

A: The Iframe HTML Code

jQuery
jQuery("#myIframe").attr("src","newPage.html");

JavaScript
document.getElementById("myIframe").src = "newPage.html";

HTML link
FOO

Form submission
<form action="newPage.html" target="myIframe">
    <input type="submit" name="btnSubmit" value="clicky"/>
</form>

A: $('#iFrameName').load('somefile.html');
This selects the iframe (you need id="iFrameName" or the like in the iframe tag) and loads a file into it. But, you can just use the target attribute on the a href.. I see you mention there are problems... what is your DOCTYPE of the html? What problems are you having with a basic a href?


text:
Q: $T(X)$ be the set of all function $f :X \rightarrow \{0,1\}$.Then which of the following statement is True? For a  set $X$, let $\mathcal{P}(X)$  be the set of all  subsets of $X$  and $T(X)$  be  the  set of all function $f: X \to \{0,1\}$.
Then which  of the  following statement is True ?

*

*If  $X$ is  finite ,then  $P(X)$ is  finite

*There is one-one correspondence between $X$ and $\mathcal{P}(X)$
My Approach
I  take  $X = N$  then  I get $\mathcal{P}(X) = 2^N$   which is uncountable so option a) is  discarded  i mean  option $a)$ is not correct
im doubt in option  2.


text:
Q: How do I bind data to an element created with this.$createElement I created an InfoWindow from Google maps and I want to put a vue component (specifically an input) inside the content property and bind it to a data. I'm also using vuetify and if possible, I want to use it's VTextfield component. If not, then a regular input would be ok as well.
Example:
data
data () {
  return {
    inputVal: null
  }
}

methods
renderInfoWindow () {
  let input = /* create an input and bind it to inputVal  */
  return new google.maps.InfoWindow({
    content: input
  })
}

A: According to the Template Compilation section in the docs,
<input v-model="inputVal">

is this render function:
function anonymous(
) {
    with(this){
        return _c('input', {
            directives: [{
                name: "model",
                rawName: "v-model",
                value: (inputVal),
                expression: "inputVal"
            }],
            domProps: { "value": (inputVal) },
            on: {
                "input": function($event) {
                    if ($event.target.composing)
                        return;
                    inputVal=$event.target.value
                }
            },
        })
    }
}

I haven't used render functions yet, so I hope this is what you need.


text:
Q: Sendgrid Azure PHP I am a newbie to php, azure, and sendgrid.
here is some code I found that I am trying to use for the html form.

Contact Me

<form class="contact" action="a_test_mailer_processor.php" method="post">

Name:

<input type="text" name="name" />

E-mail:

<input type="text" name="email" />

Subject:

<input type="text" name="subject" />

Message:

<textarea name="message" syle="width: 45%; text-align: center;">Please leave a short message here</textarea>

<input class="send" type="submit" value="Send">
</form>

Here is the PHP I am trying to use
I updated the code as follows, swapping out my credentials and email address. No errors but still not working for me. Is there something else I can test?
<?php

ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
var_dump(function_exists('curl_version'));

$url = 'https://api.sendgrid.com/';
$user = 'MYSENDGRIDUSERNAME';
$pass = 'MYSENDGRIDPASSWORD';

$params = array(
    'api_user'  => $user,
    'api_key'   => $pass,
    'to'        => 'MYEMAILADDRESS',
    'subject'   => 'testing from curl',
    'html'      => 'testing body',
    'text'      => 'testing body',
    'from'      => 'MYEMAILADDRESS',
  );

$request =  $url.'api/mail.send.json';

// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

// obtain response
$response = curl_exec($session);
curl_close($session);

// print everything out
print_r($response);

?>

And here are the errors I am getting.
bool(true)
Notice: Undefined variable: curl in D:\home\site\wwwroot\a_test_mailer_processor.php on line 36 Warning: curl_setopt() expects parameter 1 to be resource, null given in D:\home\site\wwwroot\a_test_mailer_processor.php on line 36
I tried simply removing line 36, curl_setopt($curl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); and the errors stopped but the form still did not get sent/received. Let me know what I am doing wrong.

A: As you hadn't defined $curl before setting parameters using curl_setopt, and here is a code sample on SendGrid code examples page, please try it:
<?php

$url = 'https://api.sendgrid.com/';
$user = 'USERNAME';
$pass = 'PASSWORD';

$params = array(
    'api_user'  => $user,
    'api_key'   => $pass,
    'to'        => 'example3@sendgrid.com',
    'subject'   => 'testing from curl',
    'html'      => 'testing body',
    'text'      => 'testing body',
    'from'      => 'example@sendgrid.com',
  );

$request =  $url.'api/mail.send.json';

// Generate curl request
$session = curl_init($request);
// Tell curl to use HTTP POST
curl_setopt ($session, CURLOPT_POST, true);
// Tell curl that this is the body of the POST
curl_setopt ($session, CURLOPT_POSTFIELDS, $params);
// Tell curl not to return headers, but do return the response
curl_setopt($session, CURLOPT_HEADER, false);
// Tell PHP not to use SSLv3 (instead opting for TLS)
curl_setopt($session, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($session, CURLOPT_RETURNTRANSFER, true);

// obtain response
$response = curl_exec($session);
curl_close($session);

// print everything out
print_r($response);

?>

--Update--
If you get error message as not defined constant CURL_SSLVERSION_TLSv1_2, we can directly set integer variable to CURLOPT_SSLVERSION.
We can find details in http://php.net/manual/en/function.curl-setopt.php:

One of CURL_SSLVERSION_DEFAULT (0), CURL_SSLVERSION_TLSv1 (1), CURL_SSLVERSION_SSLv2 (2), CURL_SSLVERSION_SSLv3 (3), CURL_SSLVERSION_TLSv1_0 (4), CURL_SSLVERSION_TLSv1_1 (5) or CURL_SSLVERSION_TLSv1_2 (6).

set as: curl_setopt($session, CURLOPT_SSLVERSION, 6);
And I have to set an additional option :
curl_setopt($session, CURLOPT_SSL_VERIFYPEER, false);
so that I can succeed to set my request to SendGrid Server.


text:
Q: Credit card numbers in html5 localStorage What if I stored encrypted credit card info in the browser's localstorage?  When the user visits the site again, the credit card field is prepopulated by Javascript.  The form itself points directly to a payment processor, so credit card info is never transmitted to my server.
Of course, my site and the payment processor's site are accessed via https.
Is this PCI compliant?  Is this a bad way to do things?

A: I am not certain that falls under the pci-dss regulations. Storing customer data in potentially hackable files is the big concern.

A: Not sure about PCI compliance, but you can also store credit card info in a HTTPS-only cookie.

A: Since the card # would essentially be stored on the client's machine, then (with my interpretation of pci-dss) you have no way to restrict or monitor access to that data even though its encrypted.  Sounds to me to be non-compliant.


text:
Q: Stackoverflow exception with @ToString annotation in test I'm using a MongoDB database in a Grails 3 application and I'm having some issues while doing some unitary tests.
This is my domain class
@ToString(includeFields = true, includeNames = true, excludes = "dateCreated, lastUpdated, metaClass, sites")
@EqualsAndHashCode(excludes = "site")
class Campaign {

    static mapWith = "mongo"

    ObjectId id
    String name
    Boolean manualActive
    Date startDate
    Date endDate

    static belongsTo = [site:Site]

    static constraints = {
        name size: 1..255, blank:false

        manualActive nullable:true, validator: {val, obj->
            (val != null && obj.startDate == null && obj.endDate == null) || (val == null && obj.startDate != null)
        }
        startDate nullable:true, validator: {val, obj->
            (val != null && obj.manualActive == null) || (val == null && obj.manualActive != null)
        }
        endDate nullable:true, validator: {val, obj ->
            (val != null && obj.startDate != null) || (val == null)
        }
    }
}

I'm also using build-test-data plugin to ease data creation for the tests and if I try something like the following, I receive a StackoverflowException:
@TestFor(CampaignService)
@Mock([Site, Campaign])
@Build([Site, Campaign])
class CampaignServiceSpec extends Specification {

    def setup() {
    }

    def cleanup() {
    }

    void "Test that isSameCampaign throws a ForbiddenException if no site is given"() {
        given:
            def campaign = Campaign.build(id:new ObjectId(), manualActive:true)
            def site = null
        when:
            service.isSameSite(site, campaign)
        then:
            thrown ForbiddenException
    }

    void "Test that isSameCampaign throws a ForbiddenException if it mismatches from the campaign"() {
        given:
            def site = Site.build(id:new ObjectId(), )
            def campaign = Campaign.build(id:new ObjectId(), manualActive:true)
        when:
            service.isSameSite(site, campaign)
        then:
            thrown ForbiddenException
    }

    void "Test that isSameCampaign does NOT throw a ForbiddenException if no campaign is given"() {
        given:
        def site = Site.build(id:new ObjectId(), )
        def campaign = Campaign.build(id:new ObjectId(), site:site,manualActive:true)
        when:
            service.isSameSite(site, campaign)
        then:
            notThrown ForbiddenException
    }
}

But if I remove de @ToString() annotation from the domain class and implement my own toString method the tests are run ok.
Any ideas why it's happening this stackoverflowException? May it be related with the ObjectId field?


text:
Q: Rails run with puma in dockerfile and enable https This is an example of a Dockerfile for ruby on rails project.
I want to run it with ssl key and cert
RUN apt-get update -yqq && apt-get install -y npm && npm install -g yarn
RUN apt-get install -y ruby-full
RUN apt install libsqlite3-dev
RUN gem install rails --version=6.1
RUN mkdir /var/app
WORKDIR /var/app
COPY . .
RUN bundle install --without development test

RUN npm install --force
RUN export SECRET_KEY_BASE=...............................
EXPOSE 3000
EXPOSE 80
EXPOSE 443
EXPOSE 8443
RUN rails webpacker:install
#RUN rake assets:clean
RUN rake assets:precompile
CMD rails s -b 0.0.0.0 -e production

A: FROM ruby:3.0.2
RUN apt-get update -yqq && apt-get install -y npm && npm install -g yarn
RUN apt-get install -y ruby-full
RUN apt install libsqlite3-dev
RUN gem install rails --version=6.1
RUN mkdir /var/app
WORKDIR /var/app
COPY . .
RUN bundle install --without development test

RUN npm install --force
RUN export SECRET_KEY_BASE=...............................
EXPOSE 3000
EXPOSE 80
EXPOSE 443
EXPOSE 8443
RUN rails webpacker:install
#RUN rake assets:clean
RUN rake assets:precompile
CMD puma -b 'ssl://0.0.0.0:8443?key=yourkey.key&cert=yourcertificat.pem&verify_mode=none' -b 'tcp://0.0.0.0:80' -e production

In config/environment/production.rb add: config.force_ssl=true
You can you freessl to get ssl key and certificat for your domain;
https://freessl.org/
To run it on you virtual machine or instance: docker run -d -p 443:443 -p 80:80 yourimage:tag


text:
Q: Mostrar result grid no mysql Workbench Ao executar consultas no meu MYSQL WorkBench, não consigo ver a Result Grid, apenas a tela de output dizendo se houve erro ao executar o comando ou não.
Como posso ativar a aba do Result Grid para visualizar a tabela?
Segue print para melhor entendimento. Essa é a aba que aparece no lugar do Result Grid.


text:
Q: Linux install goes to blank screen I downloaded both latest Centos and Fedora ISO and burned onto CD using Imgburn. I then first booted up with Centos CD on my old HP DC5000 computer. It appears to boot to the CD just fine and gives me options:

*

*Install Centos

*Verify files and install Centos

etc...
I select Install Centos, it then goes to a blank screen. I waited over an hour and still just a blank screen.
I tried the same with the Fedora CD and the same exact issue happened, it booted off the CD, asked which option, even when I select the second option, same thing happens, goes to a blank screen and stays there.
Any ideas/suggestions?
Thanks

A: The problem could be that you are trying to install the "official" CentOS 7 distro on a 32 bit machine. In this case, you will get the "Install CentOS" screen, and after you hit "install" it will turn blank. This is because the official CentOS 7 is 64 bit.
To install CentOS 7 on an older 32 bit computer, you need to visit the CentOS Special Interest Group and download the 32bit version from there: http://mirror.centos.org/altarch/7/isos/i386/
The alternative is to install CentOS 6.8 32bit...

A: This happens often on computers with old graphics hardware. By default the system tries to use a 1024x768 framebuffer mode to start the system with, but this doesn't work with some old PCs.
In this case, you can select Troubleshooting from the menu, and then select Install <distro> in basic graphics mode.

On some really ancient computers, even this won't work. In that case you'll need to do a text mode installation. Do this by selecting Install <distro> but instead of pressing Enter, press Tab and add  nomodeset text to the end of the boot command line.


text:
Q: Is there a way to configure eclipse that it treats gss files like css files? I want to enable eclipse specific code completion and syntax highlighting for css to files that ends with gss. The gss files are similar to css files. They are called closure-stylesheets.
Is there a way to configure eclipse that it treats gss files like css files to get code completion enabled?

A: For individual files you can just right click on the file and select 'Open With > CSS editor' (this will be remembered for future editing)
To set for all files go to 'Preferences > General > Content Types'. Find 'CSS' under 'Text' and click 'Add...' to add a '*.gss' association.


text:
Q: Reactjs in kubernetes getting error net::ERR_CONNECTION_REFUSED when using axios "GET" in backend express using DNS service endpoint I'm trying to deploy my ReactJs in Kubernetes and my backend server is running ExpresssJs (cors enabled).
But I'm getting this error message net::ERR_CONNECTION_REFUSED in my Reactjs chrome console when trying to GET.
GET https://express-api.dev-d.svc.cluster.local/v1/api/ net::ERR_CONNECTION_REFUSED
but when trying to execute the CURL command in my Reactjs pod to my ExpressJs URL there are no issues at all I'm getting the right response.
Not sure if this is a limitation in Kubernetes?

A: After further research, seems this is not possible from what I've read.
from here: Communication from Pod to Pod on same node inside kubernetes in GCP


text:
Q: Showing that $T+S$ is firmly nonexpansive
Show that $T+S$ is firmly nonexpansive considering that $T$ and $S$ are firmly nonexpansive mappings from $\mathbb R^n$ to $\mathbb R^n$.

Definition: We say that $F$ is firmly nonexpansive if: $$\|F(x)-F(y)\|^2+\|(I-F)(x)-(I-F)(y)\|^2\le \|x-y\|^2$$

A: [copied from comment]
It is false. Let $T = S = I$. Then $T+S = 2I$ which once you plug in you see that is not firmly nonexpansive. Do you perhaps mean to consider $\frac12(T+S)$? In which case the desired conclusion follows from triangle inequality applied many times.


text:
Q: What is the purpose of tilde character ~ in YAML? I have looked into YAML official documentation and I have also gone through some tutorials.
I am working with Symfony and I like adding configurations with YAML. But I can't find any explanation for this tilde character ~ in YAML.
For example, see the code below:
firewalls:
    # ...
    main:
        anonymous: ~
        http_basic: ~

Sometimes, I removed this ~ character and I did not see any effect on logic. So what is the purpose of this tide character in YAML?

A: The tilde is one of the ways the null value can be written. Most parsers also accept an empty value for null, and of course null, Null and NULL.
These are defined in the first two lines of the regular expressions for the core schema tags in the YAML standard.


text:
Q: Apache running as root instead of user specified in httpd.conf I'm trying to enable WordPress to upload files to the wp-content folder without setting permissions for the folder to 777. However, I'm having some difficulties.
The group and user set for the wp-content folder match the group and user Apache is configured to be using in httpd.conf. However, when I run the below command, it appears that Apache is actually running as root rather than the user specified in httpd.conf.
httpd.conf Configuration

User xxx
Group yyy

Command Run to Determine User Apache is Running As
ps aux | grep httpd
Output from the above command
513       1294  0.4  1.4 316420 54864 ?        S    08:30   0:06 /usr/sbin/httpd
513 is the correct UID for user xxx, so that appears correctly. However, I'm still not able to upload files within WordPress without setting permissions for the wp-content folder to 777.
Can somebody tell me what the issue is here?

A: Apache always needs to start as root, then it uses setuid to switch to user context of specified user in httpd.conf.
Without root (uid = 0) you can not create listening socket on privileged ports (below 1024)
For details read this documents:

*

*http://www.thegeekstuff.com/2011/03/apache-hardening/

*http://httpd.apache.org/docs/2.2/misc/security_tips.html
From first link:
# ps -ef | grep -i http | awk '{print $1}'
root
apache
apache
apache
apache
apache


text:
Q: How to manually set the attribute 'name' when Serializing it seems to me that the answer is quite simple, but I could not manage to find an it, how do I change the name attribute when serialising using DRF? Check the circle in the image, I just got it from the DRF website in the Metadata section.

A: As specified on the documentation on metadata [drf-doc]. You probably use the SimpleMetadata class [GitHub]. Here we see that the options are determined with:
    def determine_metadata(self, request, view):
        metadata = OrderedDict()
        metadata['name'] = view.get_view_name()
        metadata['description'] = view.get_view_description()
        metadata['renders'] = [renderer.media_type for renderer in view.renderer_classes]
        metadata['parses'] = [parser.media_type for parser in view.parser_classes]
        if hasattr(view, 'get_serializer'):
            actions = self.determine_actions(request, view)
            if actions:
                metadata['actions'] = actions
        return metadata
The get_view_name of a APIView [GitHub] is implemented as:
    def get_view_name(self):
        """
        Return the view name, as used in OPTIONS responses and in the
        browsable API.
        """
        func = self.settings.VIEW_NAME_FUNCTION
        return func(self)
The settings will thus by default determine the name of the function that calculates the view. This is specified by the VIEW_NAME_FUNCTION setting [drf-doc] that defaults to 'rest_framework.views.get_view_name'.
If we inspect the source code of this get_view_name function [GitHub], we see:
def get_view_name(view):
    """
    Given a view instance, return a textual name to represent the view.
    This name is used in the browsable API, and in OPTIONS responses.
    This function is the default for the `VIEW_NAME_FUNCTION` setting.
    """
    # Name may be set by some Views, such as a ViewSet.
    name = getattr(view, 'name', None)
    if name is not None:
        return name

    name = view.__class__.__name__
    name = formatting.remove_trailing_string(name, 'View')
    name = formatting.remove_trailing_string(name, 'ViewSet')
    name = formatting.camelcase_to_spaces(name)

    # Suffix may be set by some Views, such as a ViewSet.
    suffix = getattr(view, 'suffix', None)
    if suffix:
        name += ' ' + suffix

    return name
If your view thus contains a .name attribute, it will use that as the name. You thus can implement your APIView as:
class SomeAPIView(APIView):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.name = 'Another name than To Do List'
If there is no name attribute, it will thus take the name of the view, try to get rid fo the View or ViewSet suffix, convert the camelcase to spaces, and optionally add a suffix (like 'List' for an ListAPIView).


text:
Q: How to add a controller variable to a database row in rails? I'd like to add a variable in the controller to a database row using activerecord and rails.
To do this now I have to add a hidden input tag to my view which contains the username of the member who is adding the row. This tag then gets picked up by my controller and added into the database.
Here is my hidden input field:
<% f.hidden_field(:uploader, value: @current_user.username) %>

And this is the code which creates the building
def create # (post) Add new records
    @bld = Building.new(params[:bld].permit(:name, :uploader, :description, :down_link))

    if @bld.save
      redirect_to my_buildings_url, :alert => 'Here\'s your new building!'
    else
      render :new
    end
end

Is there any way to eliminate my hidden input tag and have the value of @current_user.username added to the database row in the controller (if you know what I mean)?

A: This would be done in the controller action as current user would be the person logged in. Therefore in your create action.
def create # (post) Add new records
    @bld = Building.new(params[:bld].permit(:name, :description, :down_link))
    @bld.uploader = current_user.username

    if @bld.save
      redirect_to my_buildings_url, :alert => 'Here\'s your new building!'
    else
      render :new
    end
end

However you'd be better off defining an association called uploader which calls your user model. Then all you have to store is an integer. Also you don't open yourself to params trickery.


text:
Q: How can I go about translating Doctrines YAML models into json-schema Basically I am looking to be able to reuse model definitions to target both Doctrine models and JSON-Schema.
I don't care if it means defining it in a 3rd model language and having the ability to convert that to both yml and json-schema or if it is from json-schema -> yml as long as I have 1 place to update both of them.

A: Just off the top of my head, you could try parsing the YAML files into PHP arrays and then parsing the arrays into JSON with json_encode() or go the other way and json_decode() the JSON files and then parse the result into YAML format.  The included sfYaml classes should be all you need for the YAML parsing/encoding and json_encode/json_decode are included in PHP 5.2 and up.


text:
Q: how to hide/show dropdownlist using jquery I´m new developing on .net and using jquery. I´m trying to hide/show a dropdownlist and a checkbox that I have on my page. I can hide succesfully, but when i try to show nothing happens or i get a error on my code like this:
http://imageshack.us/photo/my-images/811/sinttuloxs.jpg/
I tried using differents forms of show without any success.
$("#ddListaPrecios").Show();

or
$('#ddListaPrecios').Show('slow');

        $(document).ready(function() {
            $("#ddListaPrecios").hide();

            $("#codigoCliente").autocomplete({
                minLength: 1,
                source: getData,
                select: function(event, ui) {
                    cambiaElementos(ui.item.value);
                    updateCiudades(ui.item.value);
                    updateListaVendedores(ui.item.value);
                    updateListaPrecios(ui.item.value);
                }
            });

            $("#codigoCliente").change(function() {

                if ($("#codigoCliente").val().length == 6) {
                    cambiaElementos($("#codigoCliente").val());
                    updateCiudades($("#codigoCliente").val());
                    updateListaVendedores($("#codigoCliente").val());
                    updateListaPrecios($("#codigoCliente").val());

                    $("#ddListaPrecios").show();

                }
            });

            $("#ddListaPrecios").change(function() {
                //window.alert($("#ddListaPrecios").val());
                changePrecio($("#ddListaPrecios").val());

            });

            $("#ddCiudad").change(function() {
                updatePuntosEntrega($("#codigoCliente").val(), $("#ddCiudad").val());

            });
        });

        <label>Lista de Precios: </label>
        <label id="lbListaPrecios"> </label>
        <%= Html.DropDownList("ddListaPrecios") %>
       <!-- <%= Html.CheckBox("cbCambioLista") %> <label class="inline" for="cbCambioLista">Desea cambiar lista de precios?</label>  -->

A: Your call to jquery $("#ddListaPrecios").Show(); needs to be all lowercase like this $("#ddListaPrecios").show();
see the doc here http://api.jquery.com/show/


text:
Q: Solve system of equations $9^y=3^x$ and $2\log_2{x}-\log_43=\log_2y$. Solve system of equations $9^y=3^x$ and $2\log_2{x}-\log_43=\log_2y$.
I got $2y=x$ and $2\log_2{x} - \frac{1}{2}\log3=\log_2\frac{1}{2}x$. I am stuck at this point. Could you provide a hint ?

A: Hint:
Rewrite $$2\log_{2}x-\frac{1}{2}\log_{2}3\rightarrow\log_{2}x^2-\log_{2}3^{1/2}=\log_{2}\frac{x^{2}}{3^{1/2}}$$

A: Remember that by definition, $\log_43$ is the real number, say $z,$ such that $4^z=3.$ Put another way, $(2^2)^z=3.$ Put yet another way, $2^{2\cdot z}=3.$ Translated back into terms of logarithms, $$2z=\log_23,$$ so that $$\log_43=z=\frac12\log_23.$$
This may have been what you've done already, though your post doesn't actually show it (there's an index missing). If that is what you've done, then your second equation should actually show $$2\log_2x-\frac12\log_2 3=\log_2y,$$ or equivalently, $$4\log_2x-\log_23=2\log_2y.$$ This is again equivalent to $$4\log_2x=2\log_2y+\log_23,$$ or $$\log_2x^4=\log_2y^2+\log_23,$$ or $$\log_2x^4=\log_23y^2,$$ or finally $$x^4=3y^2.$$ Since $x=2y,$ and since $x$ and $y$ are both positive (do you see why?) what can we conclude?

A: Hint:
$\boxed{2\log_2x - \log_2\left(\frac x2 \right)}= \log_2(x^2) - \log_2\left(\frac x2\right) = \log_2\left(\frac{x^2}{x/2}\right) = \boxed{\log_2(2x) }$

A: You are almost there.
We have
$$2\log_2{x} - \frac{1}{2}\log_23=\log_2\frac{1}{2}x\\
2\log_2x-\frac12\log_23=\log_2x-1\\
\log_2x=\frac12\log_23-1\\
x=\frac{\sqrt3}{2}\\
y=\frac{\sqrt3}4
$$


text:
Q: Representing a tensor in terms of a matrix How can we show a tensor map in to some matrix representation? For instance if we have some tensor $T$ is a $(1,1)$ tensor on $\mathbb{R}^{2n}$ given by:
$$T =\sum_{i=1}^n dx^i \otimes \frac{\partial}{\partial x_{i+n}}$$
Can anyone show me how this tensor will have an explicit matrix representation respect to some basis $\{\frac{\partial}{\partial x_i}\}$ for $i=1,...2n?$

A: A $(1, 1)$-tensor $T$ on $\mathbb{R}^{2n}$ can be written as
$$T = \sum_{i, j = 1}^{2n}T_{ij}\,dx^i\otimes\frac{\partial}{\partial x^j}.$$
The matrix representation of $T$ is then the $2n \times 2n$ matrix $[T_{ij}]$.
For the tensor in your question, we have
$$T_{ij} = \begin{cases}
1 & 1 \leq i \leq n, j = i + n\\
0 &\ \text{otherwise}.
\end{cases}$$
It follows that the matrix representation of $T$ is
$$\left[
\begin{array}{c|c}
 0 & I_n\\
 \hline
 0 & 0
\end{array}\right].$$


text:
Q: One Hyperlink In Many Different Locations I'd like to implement a hyperlink in many locations on my website, however I just want to have it defined once not several times over.  What is the best way to achieve this?
I started down the road of listing it in the  node of web.config but I was only able to get that to list as a literal and wasn't successful in having it end up as a hyperlink.
I don't know much about master pages, but what I do know about them seems to me that they aren't the answer for this task because they wouldn't allow for that hyperlink to be located on some pages and not others and in different locations on some pages than others.
Help please! :)
I'm working in ASP.net VB.net

A: Put a HyperLink control on each page where you want it.
e.g. <asp:HyperLink runat="server" id="LogInLink">Login</asp:HyperLink>
Then either set the NavigateUrl property on the hyperlink in code-behind, e.g. this.LogInLink.NavigateUrl = Global.MySpecialUrl; or use <%=Global.MySpecialUrl%> notation to reference the value you want from your code in the NavigateUrl in the markup.
[Sorry, that's C# code]

A: You can create a custom control that inherits from HyperLink. This method will not require to use code-behind on individual pages but you will need to create a new class and modify your web.config file. Alter the namespaces as needed.
SpecialLink.vb
Namespace YourWebSite.Controls
 Public Class SpecialLink
  Inherits HyperLink

  Public Sub New()
   NavigateUrl = "~/SpecialLinkUri.aspx"
   Text = "Special Link Text"
  End Sub
 End Class
End Namespace

web.config (add this to the system.web node)
This allows you to use this control on any page/master page/user control throughout your site
<pages>
  <controls>
   <add namespace="YourWebSite.Controls" tagPrefix="YourWebSite"/>
  </controls>
</pages>

Using it on your page

This is some text, here's the link: <YourWebSite:SpecialLink></YourWebSite:SpecialLink>

This is some text, <YourWebSite:SpecialLink>here's the link</YourWebSite:SpecialLink>.


text:
Q: when use req.end it prints two times in console. why? I am new to Node.js
what is the use of req.end in Node.js .I use that but ,it print two times
app.use('/',function(req,res){
  res.send("hello world");  //send to browser
  console.log("by");  //print in console
  req.end;     //req is end here
}).listen(3000);

A: app.use('/',function(req,res){
  res.send("hello world");  //send to browser
  console.log("by");  //print in console
  req.end;     //req is end here
}).listen(3000);

In the above code when you hit localhost:3000/ from your browser, browser hit two requests at the same time one for favicon and one for '/ ' endpoint and you create only '/' router then all request will catch in '/' route.
when you hit this endpoint from postman it will print one time in the console.


text:
Q: Finding an optimal path "around" a function I would like to know how can I put some conditions on a function $d(x)$ when solving this optimalization problem:
Given a continuous function $p:[a,b]\rightarrow\mathbb{R}$ on $[a,b]$ find a function $d:[a,b]\rightarrow\mathbb{R}_0^+$ where $d(a)=d(b)=0$ such that the function $d(x)$ minimizes the following functional: $$\int_a^b
F(x,d,d')dx=\int_a^b\sqrt[]{1+[p'(x)+d'(x)]^2}dx$$
To find $d(x)$ I tried to apply the Euler-Lagrange equation:
$$\frac{\partial F}{\partial d}-\frac{d}{dx}\frac{\partial F}{\partial d'}=0$$
Hence
$$0-\frac{d}{dx}\frac{p'+d'}{\sqrt[]{1+[p'+d']^2}}=0$$
$$p'+d'=c\sqrt[]{1+[p'+d']^2}$$
$$(p'+d')^2=c^2+c^2(p'+d')^2$$
$$p'+d'=c_1$$
$$d(x)=c_1x+c_0-p(x)$$
Applying our boundary conditions we get:
$$d(x)=\left(\frac{p(a)-p(b)}{a-b}\right)(x-a)+p(a)-p(x)$$
But becouse $d:[a,b]\rightarrow\mathbb{R}_0^+$ this can only be true if $p(x)\le\left(\frac{p(a)-p(b)}{a-b}\right)(x-a)+p(a)$ on $[a,b]$.
My question is that if there is some more general solution with no further restrictions (also gives the correct answer if $p(x)\gt c_1x+c_0$)
Thanks for any kind of help with this problem.

A: In this answer, we'll give a geometric description of OP's variational problem.
Problem. There is given a continuous function profile
$$[a,b]~\ni~ x~~\mapsto~~ p(x)~\in~\mathbb{R}.$$
We want to minimize the arclength of the continuous$^1$ function profile
$$[a,b]~\ni~ x~~\mapsto~~ f(x)~\in~\mathbb{R}.$$
We are allowed to increase (but not decrease!) the function value
$$ f(a)~=~p(a)~~\wedge~~f(b)~=~p(b)~~\wedge~~ \forall x~\in~]a,b[:~~f(x)~\geq~p(x) .$$
Solution: The optimal function profile $f_{\ast}$ is then given by (the boundary of) the convex upward hull of the $p$-profile.
Examples:

*

*If $p$ is convex upward, then $f_{\ast}=p$.

*If $p$ is concave upward, then $f_{\ast}$ is the straight line through the endpoints $(a,p(a))$ and $(b,p(b))$.
--
$^1$ Even though OP does not explicitly say so we assume that $f$ must be continuous. Else the problem is trivial: Just pick a constant majorant function $f$ on the open interval $]a,b[$.


text:
Q: Filling List> from second dimension first I have List<List<Integer>> called test. I want to fill it up from the second dimension as is seen in the (incorrect) code below.
One solution which is obvious is to firstly create two separate List<Integer> that are equal to {1,...,100} and then use test.add( ... ) two times to get the desired object. However, I'm looking for a non-hacky solution since in my case I have multitudinous lists that need to be added to the second dimension of test.
public class Testing {
    public static void main(String[] args) {
        List<List<Integer>> test = new ArrayList<List<Integer>>();

        for(int i = 0; i < 100; i++) {
            test.get(0).add(i);
            test.get(1).add(i);
        }

    }
}

What I want to end up with is to be able to call test.get(0) and test.get(1) that both return the list of integers: {1,...,100}.

A: You must be looking for something like this? Here i represents the 1st dimension and j represents the 2nd. And below code forms 2x100 2d array list
    List<List<Integer>> test = new ArrayList<List<Integer>>();

    for(int i=0; i< 2; i++) {
        test.add(i, new ArrayList<Integer>());
        for(int j = 1; j <= 100; j++) {
            test.get(i).add(j);
        }
    }


text:
Q: Show that $z(t) = A \cos(bt) + B \sin(bt)$ is second order weakly stationary process I know that in order for a stochastic process to be a  second-order weakly stationary process.
Then for every $t$, the following conditions should hold:
$$E(Z(t)) = \mu$$
$$D(Z(t)) = \sigma$$
and $$\operatorname{cov}(Z(t), Z(t+p)) = \gamma(p)$$
but I just cannot show it mathematically like
$$E(z(t)) = E (A \cos(bt) + B \sin(bt) ) = A (E(\cos(bt))) + B (E(\sin(bt)))$$
and I have no clue after that. So, any help will be appreciated on solving this

A: When all $A$, $B$ and $b$ are constant, the whole expression will be a function of $t$. No uncertainty remains in it, and although it is still valid, there is no reason to call it as stochastic. In this case, the mean is also a function of $t$, so the process is not mean stationary, which means it is also not WSS: $$E[Z(t)]=Z(t)=A\cos(bt)+B\sin(bt)=\mu(t)$$
The covariance will be $0$ because both $Z(t),Z(t+p)$ are constants. Typically, what I encounter is $A,B$ being random. In that case, for the mean being stationary, you should have $E[A]=E[B]=0$ (for this specific case), since:
$$E[A\cos(bt)+B\sin(bt)]=E[A]\cos(bt)+E[B]\sin(bt)$$
and there is no combination of constants to make this expression constant, other than zero-means.

A: Assuming that $A$ and $B$ are independent random variables (and $b$ is a constant), and using standard notation for the moments of these random variables, you have the mean function:
$$\begin{align}
\mu(t)
&\equiv \mathbb{E}(Z(t)) \\[6pt]
&= \mathbb{E}(A \cos(bt) + B \sin(bt)) \\[6pt]
&= \mathbb{E}(A) \cos(bt) + \mathbb{E}(B) \sin(bt) \\[6pt]
&= \mu_A \cos(bt) + \mu_B \sin(bt), \\[6pt]
\end{align} \quad \quad \quad \quad \quad \quad \quad$$
and autocovariance function:
$$\begin{align}
\quad \quad \quad \quad \gamma(t,k)
&\equiv \mathbb{C}(Z(t),Z(t+k)) \\[6pt]
&= \mathbb{C}(A \cos(bt) + B \sin(bt), A \cos(bt+bk) + B \sin(bt+bk)) \\[6pt]
&= \mathbb{V}(A) \cos(bt)\cos(bt+bk) + \mathbb{V}(B) \sin(bt)\sin(bt+bk) \\[6pt]
&= \sigma_A^2 \cos(bt)\cos(bt+bk) + \sigma_B^2 \sin(bt)\sin(bt+bk) \\[6pt]
&= \sigma_A^2 \cos(bk) + [\sigma_B^2 - \sigma_A^2] \sin(bt)\sin(bt+bk). \\[6pt]
\end{align}$$
Second-order weak stationarity occurs when neither of these functions depend on $t$.  Assuming that $b \neq 0$ (giving a non-trivial problem), a sufficient condition for this is to have $\mu_A = \mu_B = 0$ and $\sigma_A^2 = \sigma_B^2 \equiv \sigma^2$, which gives $\mu(t) = 0$ and $\gamma(t,k) = \sigma^2 \cos(bk)$.  (Note also that weak-sense stationarity is only achieved when these amplitude values are random; once you condition on the amplitude values the series is no longer stationary.)


text:
Q: How does one take information such as variables located in a specific structure and store it in a single pointer located in another structure I am attempting to read different values from standard input and store them in variables located in a structure I created called the process structure.Then I will take the info in this structure and store it in a pointer variable in a priority queue structure. This process structure looks as follows:

typedef struct proc{

int creationTime;
int pid;
int runTime;
int ioTime;
int repeat;
}proc;

The Structure for my Priority queue is as follows:
// type of one element in a queue

typedef struct _Queue_element {
  void *info; //<- THIS IS WHERE ALL INFO FROM THE PROCESS STRUCTURE WILL BE STORED WHEN ADDED TO THE QUEUE
  int priority;
  struct _Queue_element *next;
} *Queue_element;

//basic queue type

typedef struct Queue {
  Queue_element queue;
  Queue_element tail;
  Queue_element current;
  Queue_element previous;
  unsigned long queuelength;
  unsigned int elementsize;
  unsigned int duplicates;
  int (*compare) (const void *e1, const void *e2);
  pthread_mutex_t lock;
  int priority_is_tag_only;
} Queue;

Lastly This is the add element to queue function in a readymade queue package I am using.
static void nolock_add_to_queue(Queue *q, void *element, int priority) {

  Queue_element new_element, ptr, prev = NULL;

  if (! q->duplicates && ! q->compare) {
    fprintf(stderr, "If duplicates are disallowed, the comparison function must be specified in init_queue().\n");
    exit(1);
  }

  if (!q->queue ||
     (q->queue && (q->duplicates || !nolock_element_in_queue(q, element)))) {

    new_element = (Queue_element) malloc(sizeof(struct _Queue_element));
    if (new_element == NULL) {
      fprintf(stderr, "malloc() failed in function add_to_queue()\n");
      exit(1);
    }
    new_element->info = (void *)malloc(q->elementsize);
    if (new_element->info == NULL) {
      fprintf(stderr, "malloc() failed in function add_to_queue()\n");
      exit(1);
    }

    memcpy(new_element->info, element, q->elementsize);

    new_element->priority = priority;

    (q->queuelength)++;

    if (q->queue == NULL) {             // first element
      new_element->next = NULL;
      q->queue = new_element;
      q->tail = new_element;
    }
    else if (q->priority_is_tag_only) { // FIFO queue
      q->tail->next = new_element;
      q->tail = new_element;
      new_element->next = NULL;
    }
    else {                              // priority queue
      ptr=q->queue;
      while (ptr != NULL && priority <= ptr->priority) {
    prev = ptr;
    ptr = ptr->next;
      }

      if (! prev) {   // queue only had one element and new element
              // has higher priority
    new_element->next=q->queue;
    q->tail = q->queue;
    q->queue=new_element;
      }
      else {         // insert new element
    new_element->next = prev->next;
    prev->next = new_element;
    if (new_element->next == NULL) {
      // new tail
      q->tail = new_element;
    }
      }
    }

    nolock_rewind_queue(q);

  }
}

What I am confused about Is how this add to queue function will correctly store the info from typedef struct proc; to the void *info variable in typedef struct _Queue_element;. Please let me know if this question is lacking any information such as other functions Included in my package or any other points I may clarify. Even if you are unable to provide specific solutions to my problem any materials I may read up on that could help me understand these topics will certainly be useful.
UPDATE: I have realized that this function does not need to be changed whatsoever. But am still confused as to how it will receive the info from proc.

A:
But am still confused as to how it [the function nolock_add_to_queue] will receive the info from proc.

Well, I would rather say that the same pieces of information certainly can be accessed both in the function nolock_add_to_queue, through its arguments, and outside it, through variables of the type proc. But let's analyse it calmly. I took the liberty to format the code a bit differently, maybe it will be more readable.
First, we have this typedef declaration:
typedef struct proc {
    // ...
} proc;

Here, we do two things:

*

*define a type struct proc,

*declare the identifier proc as an alias for this type.

Note that the second identifier proc means a different thing than the first identifier proc.
Next, we have this typedef declaration:
typedef struct _Queue_element {
    void *info; //<- THIS IS WHERE ALL INFO FROM THE PROCESS STRUCTURE WILL BE STORED WHEN ADDED TO THE QUEUE
    // ...
} *Queue_element;

Here, we also do two things:

*

*define a type struct _Queue_element,

*declare the identifier Queue_element as an alias for the pointer type struct _Queue_element *.

Next, we have this typedef declaration:
typedef struct Queue {
    Queue_element queue;
    // ...
} Queue;

Here, we also do two things:

*

*define a type struct Queue,

*declare the identifier Queue as an alias for this type.

Similarly as before, the second Queue is different from the first one.
Next, we have this function definition:
static void nolock_add_to_queue (Queue *q, void *element, int priority) {
    // ...
}

Here, we define a function nolock_add_to_queue that:

*

*is static,

*takes a variable of the pointer type Queue * as its first argument,

*takes a variable of the pointer type void * as its second argument,

*takes a variable of the type int as its third argument,

*returns nothing.

Finally, how it all works together?
The function nolock_add_to_queue takes a Queue * variable as its argument. What follows, this function has access to every member of the type Queue through this variable.
Also, this function takes a void * variable of as its argument. What follows, it has access to the same memory that this variable has access. Note that I've written "memory", not "variable of type" or "member of type". It is because a void * variable may be considered something like "a pointer variable to data of no type". For details on void *, you can see for example the question What does void* mean and how to use it?, the question Concept of void pointer in C programming, or the question What does void mean in C, C++, and C#?.
When nolock_add_to_queue is invoked, it accesses, among others, the member queue of Queue by using q->queue. queue could access its member info (it is not accessed directly in the function). As to proc, there is no usage of the members of it directly, but I suppose they are used in the code that invokes nolock_add_to_queue. The usage is most probably not needed, as the function operates on Queue and its elements, and not directly on the data that its elements hold.
If something what I've written is unclear, feel free to ask in the comments for clarification.


text:
Q: override what objects.all() returns when using PassThroughManager in django-model-utils? I'd like to use
PassThroughManager.
Example covers how to define custom manager methods, but can't find info on how to change the default queryset, ie. objects.all().
How can I specify what my objects.all() will return when using PassThroughManager?
--- edit --
For future readers,
django 1.7 seems to have PassThroughManager built-in
https://docs.djangoproject.com/en/dev/topics/db/managers/#custom-managers-and-model-inheritance

A: Can't you just override the all() method on your custom QuerySet?
class PostQuerySet(QuerySet):
    def all(self):
        ...

A: As of Django 3.0+, you can no longer override the all function in QuerySet. The latest solution for this without having to use any third party is:
from django.db import models

class CustomQuerySet(models.query.QuerySet):
    pass

class CustomManager(models.Manager):
    def get_queryset(self):
        qs = CustomQuerySet(self.model, using=self._db)
        return qs.filter(...)    # your custom logic here

class CustomModel(models.Model):
    objects = CustomManager()

Django 3.1 Documentation on custom manager & queryset

A: See the @jproffitt answer, but if you really need to define that method in manager
I guess you can do:
from django.db import models
from django.db.models.query import QuerySet
from model_utils import managers

class MyManager(models.Manager):
    def all(self):
        # ... Your custom method

class MyQuerySet(QuerySet):
    pass

MyThThroughManager = managers.create_pass_through_manager_for_queryset_class(MyManager, MyQuerySet)

I saw the model utils docs and its code


text:
Q: SharpSSH invalid privatekey I use SharpSSH to connect to a stfp-server.
This for I need to add a privatekey-file like this:
sftp.AddIdentityFile(KeyFilePath);

But this throws an exception:
invaid privatekey: C:\KeyFile\privatekey_2.ppk

The file was created with puttygen and works with filezilla.
The privatekey-type doesn't matter (SSH-1 RSA, SSH-2 RSA, SSH-2 DSA). Everytime the same result.
Do you know how to handle this problem?

A: You have to convert your key to OpenSSH Format:
Use PuttyGen to generate and convert the key (Conversion -> export OpenSSH Key)


text:
Q: For which negative values of $s$ is $\delta\in W^{2,s}(\mathbb{R}^{n})$? Recall that
$$\delta\in W^{2,s}(\mathbb{R}^{n})\iff\int_{\mathbb{R}^{n}}(1+|\xi|^{2})^{s}|\langle\hat{\delta},\varphi\rangle|^{2}d\xi<\infty,\qquad\varphi\in\mathcal{S}(\mathbb{R}^{n}).$$
We have
$$\begin{aligned}
\int_{\mathbb{R}^{n}}(1+|\xi|^{2})^{s}|\langle\hat{\delta},\varphi\rangle|^{2}d\xi&=\int_{\mathbb{R}^{n}}(1+|\xi|^{2})^{s}|\langle\delta,\hat{\varphi}\rangle|^{2}d\xi
\\
&=\int_{\mathbb{R}^{n}}(1+|\xi|^{2})^{s}|\hat{\varphi}(0)|^{2}d\xi
\\
&\le\int_{\mathbb{R}^{n}}(1+|\xi|^{2})^{s}d\xi
\end{aligned}$$
Then we are just integrating a polynomial here, which is convergent for arbitrarily many negative $s$, no?

A: The integral $\int_{\mathbb{R}^{n}}(1+|\xi|^{2})^{s}d\xi$ converges if and only if $2s<-n$, that is $s<-n/2$. This determines the range of $s$ for which the delta-function is in the Sobolev space of order $s$.
As a notational remark: $W^{s,2}$ is the more common way of ordering the exponents: order of derivative first, exponent of integrability second (compare to $C^{k,\alpha}$ where the order of derivative also comes first). The space is also often denoted by $H^s$.


text:
Q: How to add a node in front of boost property_tree I have a xml
<MyXML>
    <Tag2>2</Tag2>
    <Tag3>3</Tag2>
    <Tag4>4</Tag3>
</MyXML>

and read it into boost::property_tree::ptree xmlroot using boost::property_tree::read_xml
Now if I add a new node by
xmlroot.add("MyXML.Tag1", "1");

This new node will add to back of existing tags. After boost::property_tree::write_xml, I get
<MyXML>
    <Tag2>2</Tag2>
    <Tag3>3</Tag2>
    <Tag4>4</Tag3>
    <Tag1>1</Tag1>
</MyXML>

Is there a way to insert new node in front of Tag2?

A: It's possible, but it's outside of scope of standard accessors like get and add so one has to go the longer and more cumbersome way of iterators. Basically you need to get an iterator for your node and use insert or push_front insert a new node at required place.
Full example.:
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <string>
#include <exception>
#include <iostream>
namespace pt = boost::property_tree;

int main()
{
    try
    {
        std::string xml_content =
"<MyXML> \
    <Tag2>2</Tag2> \
    <Tag3>3</Tag2> \
    <Tag4>4</Tag3> \
</MyXML>";
        std::stringstream xml (xml_content);
        pt::ptree tree;
        pt::read_xml (xml, tree);
        /* ~~~~ KEY STUFF ~~~~ */
        auto root = tree.find("MyXML");
        root->second.push_front({"NewTag", decltype(tree)("1")});
        /* ~~~~ KEY STUFF ~~~~ */
        pt::write_xml (std::cout, tree);
    }
    catch (std::exception &e)
    {
        std::cout << "Error: " << e.what() << "\n";
    }
    return 0;
}

Key stuff explained:
    auto root = tree.find("MyXML");
    root->second.push_front({"NewTag", decltype(tree)("1")});

Ok, so 1st line is a no brainer, we need to get our "work" node.
Second line uses push_front, which inserts a new node at the front of the caller. But out caller is at the second field of the iterator, which is the result of find("MyXML").
Then push_front expects a pair of key and self_type. I used brace initialization for pair, and a string literal for key. Creating a new node of matching type is a little bit more tricky, since the constructor using value is marked as explicit. So, one has to use it's type. I got it using decltype of the tree.
If anything can be simplified I happily welcome all improvements.


text:
Q: How to get value from php javascript? I have a file php javascript
in news.js
news_id  = 1;
document.write('

');
function output(strHtml) {
    document.getElementById('news-id').innerHTML = strHtml;
}

in news.php is using
<?php
    $news_id =
?>
news_id
<?php
    $str = '
This is id:
'.$news_id;
?>
output(<?php echo json_encode($str); ?>);

And index.html i call

When i run index.html is error, how to get news_id from js to using in php

A: You can't call news.php like this. It should be included in the html file like this:
include("news.php");

and you should change the extension of your html file to .php

A: Well, as wrong as the original question is, there is a way to get the a JS variable into a PHP file.
In the HTML:

In news.js:
var myvar = "HELLO";

In news.php:
alert("<?php echo $_GET["myvar"]?>");

Again, I highly discourage this approach... but it works.

A: To use PHP as javascript source


text:
Q: Connection between PCA and linear regression Is there a formal link between linear regression and PCA? The goal of PCA is to decompose a matrix into a linear combination of variables that contain most of the information in the matrix. Suppose for sake of argument that we're doing PCA on an input matrix rather than its covariance matrix, and the columns $X_1, X2, ..., X_n$ of the matrix are variables of interest. Then intuitively it seems that the PCA procedure is similar to a linear regression where one uses a linear combination of the variables to predict the entries in the matrix. Is this correct thinking? How can it be made mathematically precise?
Imagine enumerating the (infinite) space of all linear combinations of the variables $X_1, X_2, ...,X_n$ of a matrix of data and doing linear regression on each such combination to measure how much of the rows of the matrix the combination can 'explain'. Is there an interpretation of what PCA doing in terms of this operation? I.e. how in this procedure PCA would select the 'best' linear combinations? I realize this procedure is obviously not computationally feasible, I only present it to try to make the link between PCA and linear regression. This procedure works directly with linear combinations of columns of a matrix so it does not require them to be orthogonal.

A: The difference between PCA and regression can be interpreted as being mathematically only one additional multiplication with an inverse matrix...
Here is a correlation matrix with three groups of variables:
group g1: $x_{1,1},x_{1,2}$ correlated
group g2: $x_{2,1},x_{2,2},x_{2,3}$ correlated
group g3: $y$ composed by the variables of group g1 and g2

The correlation matrix looks like
cor         x1_1    x1_2    x2_1    x2_2    x2_3    ___y
-----------------------------------------------------------
x1_1        1.000   0.976   0.472   0.444   0.430   0.642
x1_2        0.976   1.000   0.594   0.567   0.538   0.767
x2_1        0.472   0.594   1.000   0.998   0.979   0.919
x2_2        0.444   0.567   0.998   1.000   0.986   0.917
x2_3        0.430   0.538   0.979   0.986   1.000   0.904
___y        0.642   0.767   0.919   0.917   0.904   1.000
-----------------------------------------------------------

This is the loadings-matrix in its initial triangular cholesky form when not yet rotated to PC-position:
tri         f1       f2      f3      f4      f5      f6
-----------------------------------------------------------
x1_1        1.000   0.000   0.000   0.000   0.000   0.000
x1_2        0.976   0.218   0.000   0.000   0.000   0.000
x2_1        0.472   0.612   0.634   0.000   0.000   0.000
x2_2        0.444   0.615   0.649   0.054   0.000   0.000
x2_3        0.430   0.543   0.700   0.119   0.128   0.000
___y        0.642   0.644   0.350   0.156   0.112   0.117
-----------------------------------------------------------

In pca we do not distinguish between independent and dependent variables; so we might do a rotation to PCA-position, where then the first axis/column denotes the first principal component and so on.
[22] pca = rot(dr,"pca")

pca         f1        f2      f3      f4      f5      f6
-----------------------------------------------------------
x1_1        0.714   -0.692   0.100   0.041  -0.020   0.005
x1_2        0.810   -0.584  -0.031  -0.047   0.025  -0.007
x2_1        0.948    0.300   0.063  -0.081   0.003   0.018
x2_2        0.940    0.333   0.050  -0.049  -0.015  -0.019
x2_3        0.926    0.351   0.072   0.114   0.016  -0.001
___y        0.973    0.045  -0.226   0.027  -0.010   0.004
-----------------------------------------------------------

We see, that all variables have one common factor, but we might also see, that only two or three factors are "relevant".  A quartimax-rotation might locate the three main factors better related to the variable-groups
[26] qua = rot(pca,"quartimax",1..6,1..3)

qua.max       f1      f2      f3      f4      f5      f6
-----------------------------------+------------------------
x1_1        0.373   0.925   -0.060   0.041  -0.020   0.005
x1_2        0.505   0.859    0.068  -0.047   0.025  -0.007
--------
x2_1        0.988   0.112   -0.059  -0.081   0.003   0.018
x2_2        0.994   0.078   -0.048  -0.049  -0.015  -0.019
x2_3        0.989   0.056   -0.071   0.114   0.016  -0.001
--------
___y        0.908   0.342    0.240   0.027  -0.010   0.004
-----------------------------------+------------------------

We see that we have two main groups with high in-group correlations, saying they measure nearly the same, in the x-variables and a less sharp separated "group" with only the y-variable which is correlated to both groups but has still an individual variance (in factor f3).
This is classical PCA with Quartimax/Varimax-rotation, the "little jiffy"-procedure.
Now we move on to regression. In regression we define one variable as dependent, in our case the variable y. We are interested, in which way y is composed by the independent variables; a still pca-inherent point of view would be that we find the pca of the independent variables only and leve the factor f6, which shows a part of y-variance which is uncorrelated , alone as taken from the initial triangular cholesky-factor.
[29] pca = rot(dr,"pca",1..5)

pca.reg      f1       f2      f3      f4      f5      f6
---------------------------------------------------+--------
x1_1        0.729   -0.680   0.067  -0.048  -0.002  0.000
x1_2        0.816   -0.571  -0.067   0.055   0.001  0.000
-------------------
x2_1        0.946    0.315  -0.066  -0.033   0.019  0.000
x2_2        0.936    0.348  -0.041  -0.013  -0.023  0.000
x2_3        0.923    0.366   0.117   0.036   0.004  0.000
---------------------------------------------------+--------
___y        0.957    0.057  -0.076   0.245  -0.039  0.117
---------------------------------------------------+--------

Still the axes show the "factors" and how each variable is composed by that common (f1 to f5) or individual (f6) factors.
Regression asks now for composition of y not by the factors/coordinates on the axes but by the coordinates on variables x if they are taken as axes.
Happily we need only multiply the current loadings-matrix by the inverse of the x-submatrix to get axes defined by the x and have the "loadings" of y on x:
[32] B = (pca[*,1..5]*inv(pca[1..5,1..5]) ) || pca[*,6]

reg.B       x1_1    x1_2    x2_1    x2_2    x2_3    ___y
---------------------------------------------------+--------
x1_1        1.000   0.000   0.000   0.000   0.000   0.000
x1_2        0.000   1.000   0.000   0.000   0.000   0.000
-------------------
x2_1        0.000   0.000   1.000   0.000   0.000   0.000
x2_2        0.000   0.000   0.000   1.000   0.000   0.000
x2_3        0.000   0.000   0.000   0.000   1.000   0.000
---------------------------------------------------+--------
___y        -1.442  1.989   -1.394  0.955   0.876   0.117

We see, that each of the axes is identified with one of the variables and also the "loadings" of y on that axes. But because the axes show now the directions of the x the loadings of y in the last row are now also the "regression"-weights/ coefficients, and the regression weights are now
B = [-1.442  1.989   -1.394  0.955   0.876 ]

(Because of the strong correlations in the groups the regression-weights are above 1 and also the signs are alternating. But this is not much of concern here in that methodic explanation)

[Update]

Relating PCA and regression in this way, there occurs very fluently another instructive example which might improve intuition. This is the problem of multicollinearity, which if occurs in regression is a problem for the researcher, but if occurs in PCA only improves the validity of estimation of separate components and the loadings of the items on such (latent) constructs.
The means, which I want to introduce here, is the "main direction" of the multicollinear items (which of course is the first principal component) respectively the two sets of independent items $x1$ and $x2$. We can introduce latent variables which mark the pc's of the two sets of x-items. This can practically be done applying pc-rotation with maximizing criterion taken from the sets only:

[32] pc1 = rot(tri,"pca",1..2,1..5)  //rotating for pc of items 1..2 only
[33] pc1 = {pc1,marksp(pc1,{1,2})}   //add markers for that pc's

PC1       pc1_1     pc1_2     c3        c4        c5        c6
--------------------------------------------------------------
x1_1      0.994    -0.109     0         0         0         0
x1_2      0.994     0.109     0         0         0         0
--------------------------------------------------------------
x2_1      0.562     0.571     0.599     0         0         0
x2_2      0.536     0.578     0.613     0.054     0         0
x2_3      0.521     0.516     0.657     0.123     0.125     0
--------------------------------------------------------------
y         0.722     0.575     0.316     0.151     0.11      0.116
===============================================================
pc1_1     1         0         0         0         0         0
pc1_2     0         1         0         0         0         0
===============================================================

If we were looking at the system of $x1_1,x1_2$ and $y$ only, we had already
the beta-values for the pc's of that $x1$-item set as $b_{pc1_1}=0.722$ and
$b_{pc1_2}=0.575$ - no hazzle because of (multi)collinearity!
The same can be done with the second set of independent items $x2_1,x2_2,x2_3$:
[37] pc2 = rot(pc1,"pca",3..5,1..5)
[38] pc2 = {pc2,marksp(pc2,{1,2,3})}

PC2       pc2_1     pc2_2     pc2_3     c4        c5        c6
--------------------------------------------------------------
x1_1      0.477    -0.124    -0.464     0.729     0.101     0
x1_2      0.599    -0.189    -0.389     0.636     0.221     0
--------------------------------------------------------------
x2_1      0.997    -0.078    -0.022     0         0         0
x2_2      0.999    -0.041     0.027     0         0         0
x2_3      0.993     0.119    -0.005     0         0         0
--------------------------------------------------------------
y         0.923    -0.029    -0.058     0.212     0.294     0.116
===============================================================
pc1_1     0.542    -0.157    -0.429     0.687     0.162     0
pc1_2     0.557    -0.300     0.343    -0.424     0.55      0
--------------------------------------------------------------
pc2_1     1         0         0         0         0         0
pc2_2     0         1         0         0         0         0
pc2_3     0         0         1         0         0         0
===============================================================

The beta-value for the first pc of the second set of items (in a model without the first set) were $b_{pc2_1}=0.923$ which is more than that $b_{pc1_1}=0.722$ for the first pc of the first set of independent items.
Now to see the betas using the joint model requires again only the inversion of the submatrix of the loadings of the whole set of 5 pc-markers and postmultiplying the first 5 columns with that. This gives us the "loadings", if the 5 pcs are taken as axes of a coordinate system. We get
[42] beta = pca1[*,1..5]* inv(pca1[7..11,1..5]) || pca1[*,6]

beta      pc1_1     pc1_2     pc2_1     pc2_2     pc2_3     c6
--------------------------------------------------------------
x1_1      0.994    -0.109     0         0         0         0
x1_2      0.994     0.109     0         0         0         0
--------------------------------------------------------------
x2_1      0         0         0.997    -0.078    -0.022     0
x2_2      0         0         0.999    -0.041     0.027     0
x2_3      0         0         0.993     0.119    -0.005     0
--------------------------------------------------------------
y         0.540     0.375     0.421     0.169     0.045     0.116
===============================================================
pc1_1     1         0         0         0         0         0
pc1_2     0         1         0         0         0         0
--------------------------------------------------------------
pc2_1     0         0         1         0         0         0
pc2_2     0         0         0         1         0         0
pc2_3     0         0         0         0         1         0
===============================================================

In short:
beta      pc1_1     pc1_2  |   pc2_1     pc2_2     pc2_3   |  c6
---------------------------+-------------------------------+--------
y         0.540     0.375  |   0.421     0.169     0.045   |  0.116
===========================+===============================|========

In that joint model the "main direction" of the first set of independents has a beta-weight of 0.540 and the "main direction" of the second set of 0.421 .
The value at $c6$ is here only for completeness: its square $0.116^2$ is the unexplained variance of the dependent item $y$.

A: No.  PCA returns mixtures of (typically dependent) variables that most contribute to observed variance.  Linear regression does not mix variables while expressing the output variables as linear combinations of the input variables.  (Linear combinations?  Yes.  Mixtures of input and output variables?  No.)
PCA is computed by singular value decomposition.  Linear regression is not.  Consequences:  linear regression misbehaves if two or more input variables are correlated (i.e., the system is rank deficient), typically producing outputs sensitively dependent on noise.  PCA merges the (almost) indistinguishable variables together and continues giving sane results.  This merging of strongly correlated variables can result in reduction in the apparent dimensionality of the system, generally improving explanatory power and prediction.
The process of using PCA for linear regression is called Principal Component Regression.


text:
Q: Spring Boot Thymeleaf JavaMail -"class path resource [images/logo.png] cannot be opened because it does not exist " with streams.foreach I am using Spring Boot and Thymeleaf to send emails. I have one inline image as a signature in the email. Everything works fine if I send one email at a time. But, my use case is to send an individual email to a list of recipients. I am able to do that without the image. But, when I add the image, the first email is getting sent and for the second time I get class path resource [images/tp-logo.png] cannot be opened because it does not exist.

*

*When I call emailService.send() from the stream.forEach() I get above error.

*When I call it from a normal for loop, it works fine.

I understand that the streams are lazy, but why the resource is missing?
Working Caller method code:
for(ContactIfo contact : contactInfoList) {
   ExecutorService emailExecutor = Executors.newCachedThreadPool();
   emailExecutor.execute(() -> {
       final String emailAddress = contact.getEmailAddress();
       if (StringUtils.isNotBlank(emailAddress)) {
          emailService.sendEmail(emailAddress);
       }
   });
 }

Failing caller method code:
contactInfoList.parallelStream().forEach(contact -> {
    ExecutorService emailExecutor = Executors.newCachedThreadPool();
    emailExecutor.execute(() -> {
        final String emailAddress = contact.getEmailAddress();
        if (StringUtils.isNotBlank(emailAddress)) {
            emailService.sendEmail(emailAddress);
        }
    });
});

Callee:
private void sendEmail(Mail mail) throws MessagingException {
    MimeMessage message = emailSender.createMimeMessage();
    MimeMessageHelper helper = new MimeMessageHelper(message,
            MimeMessageHelper.MULTIPART_MODE_MIXED_RELATED,
            StandardCharsets.UTF_8.name());

    Context context = new Context();
    context.setVariables(mail.getProps());

    String html = templateEngine.process("me-event-update-template", context);

    helper.setText(html , true);
    helper.setTo(mail.getMailTo());
    helper.setSubject(mail.getSubject());
    helper.setFrom(mail.getFrom());
    // adding inline resources with matching cId to the variable name/value
    helper.addInline("logo", new ClassPathResource("images/logo.png"), "image/png");
    emailSender.send(message);
}


text:
Q: Using actionperform to call a method in others class for Java I'm programming a download button, when the user clicks the download button, it will call the method(getDownload()) in others class which is not inside a same Java program for execution and pass back the message when the process is finish but I get some error display in my client side program.
Now, btn2 is my download button, I tried to use the class to create an object to invoke the method inside it but it fails to work:
 if(e.getSource()== btn2)
       {
             String choice3 = String.valueOf(cmb3.getSelectedIndex());
             runCC(choice3);
       }
 public static void runCC(String choice3)
       {
         DownloadCenter dc = new DownloadCenter();
         String ServerReplyMessage = dc.getDownload(choice3);
         JOptionPane.showMessageDialog(null,"Downloading" +ServerReplyMessage);
       }

I get an error in
DownloadCenter dc = new DownloadCenter()

and the error message is

constructor DownloadCenter in class DownloadCenter can't apply to given type

Here is the link that is reference idea for me to develop the program but why it still gives error? Can I know where is my error?
This is my full program for the other class.

A: The constructor you have specified in the class DownloadCenter requires a String parameter to make an object...
While you are making an object without passing the string parameter...
Now you can do two things...

*

*Provide a default constructor in the class DownloadCenter.

public DownloadCenter()
{
  // do what you want...
}
or

*Make the object by passing a String Parameter.

DownloadCenter dc = new DownloadCenter("Your_String_Value");

For more on constructors in java see this


text:
Q: Get specific column foreach row in DataTable How can I get specific column from each row in DataTable. In this example I want to get top 3 news and I got problem with Image. This code gives allways a image from first row, because I defined dr.Rows[0]["Image"]. How can i change this to get right image for every row?
SqlCommand cmd = new SqlCommand("SELECT TOP 3 Title, Content, Date, Autor, Category, Image FROM News", con);
    con.Open();
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    da.Fill(dt);

    foreach (DataRow row in dt.Rows)
    {
        Panel panel = new Panel();
        panel.Attributes.Add("class", "post");

        HtmlGenericControl header = new HtmlGenericControl("h2");
        header.InnerHtml = row["Title"].ToString();
        header.Attributes.Add("class", "naslovPosta");
        panel.Controls.Add(header);

        HtmlGenericControl date = new HtmlGenericControl("p");
        date.InnerHtml = ((DateTime)row["Date"]).ToString("dd.MM.yyyy.");
        date.Attributes.Add("class", "datumPosta");
        panel.Controls.Add(date);

        Image img1 = new Image();
        img1.ImageUrl = ResolveUrl("~/Images/" + dt.Rows[0]["Image"]);
        panel.Controls.Add(img1);

        HtmlGenericControl content = new HtmlGenericControl("pre");
        content.InnerHtml = row["Content"].ToString();
        panel.Controls.Add(content);

        pnlNews.Controls.Add(panel);
    }

A: You already enumerate all rows, you find the current row in the row-variable, so replace:
img1.ImageUrl = ResolveUrl("~/Images/" + dt.Rows[0]["Image"]);

with
img1.ImageUrl = ResolveUrl("~/Images/" + row["Image"]);

like you did it already f.e. at row["Title"].ToString();


text:
Q: check if network bridge on windows is up and running My setup has a network bridge setup where an ethernet and TAP-devices are running on a bridge. Everything worked fine, until recently the network bridge due to some unkown reason disappeared. It took me half a day to figure out, that this was the case.
Is there any command line to check if a network bridge of windows is still up and running?

A: We can check if the virtual network adapter of TAP-devices is still existing manually, if so, we can create the network bridge between ethernet and virtual network adapter of TAP-devices.
If the virtual network adapter of TAP-devices is not existing, the network bridge between ethernet and TAP-devices must be not up and running. So we need to recreate the virtual network adapter of TAP-devices, then create the network bridge between ethernet and virtual network adapter of TAP-devices.
We can check it like this:


text:
Q: Fastest way to see which pixel has changed when using a listener I am trying to get EDS spectra on every scanned pixel using STEM.
I am using the EDSStartAcquisition( 2048, 10,fexposure*2, 1) command and
I have attached the following simple listener object into the shown 1D spectrum image:
string messagemap = "data_value_changed:MyImageAction"
    Class MyListenerClass1
    {
    String event_desc;

    MyListenerClass1(Object self); //Result("\n");
    ~MyListenerClass1(Object self);// Result("\n");

        Void MyImageAction(Object self, Number e_fl, Image Img)
        {
        ImageGetEventMap().DeconstructEventFlags( e_fl, event_desc )
        Result(GetTime(1)+": Image message : " + event_desc + " 0x" + Binary(e_fl) + "\n" )
        }
    }

ListenerID1 = EDSIm.ImageAddEventListener( Listener1, messagemap)

Since speed is the issue here, I figured to try the continuous mode of the EDS acquisition. But then I would need to listen which counts belong to each scanned pixel. The following topic (How to getting acquired frames at full speed ? - Image Event Listener does not seem to be executing after every event) shows how to listen to the last pixel change of an image. But what would be the fastest way to directly see which slice of the 1D spectrum has changed on every event? Without going through every slice...
thanks in advance!

A: An images' data_value_changed is fired whenever a) an image locker (the object that ensures there is single access to the memory) is released, or b) a specific update-call is made in the code.
As such, when a cumulative EDS spectrum is acquired, the whole array gets "locked", then modified (on one or more positions) and then 'updated'. There is no specific information carried on where the array was modified.
Therefore, the only way to find out where the spectrum changed is by comparing a copy of the "before" with the "now" - which is not super efficient.


text:
Q: How to TOP CROP Image using PhotoView Android? I have 1 ImageView with layout_width & layout_height is match_parent, two of them is screen width and height size. I need display photo to fill full width and when image is higher than ImageView height, it can be scroll up and down. I'm using PhotoView library to zoom, scroll, tap... now i'm using centerCrop scale type but it is not solution i need. It show a part of center image and i need scroll up to view from beginning.
I tried lot of custom view extended ImageView to display Top Crop style but when i touch to image, it changed to default PhotoView scale type. It only work when not use PhotoViewAttacher
How i can make a Top Crop and scroll + zoom + touch... image by using PhotoView library ?

A: You can achieve a TopCrop scale changing the CENTER_CROP scale under updateBaseMatrix() in PhotoViewAttacher of Chris Banes`s PhotoView.
Here is the code:
else if (mScaleType == ScaleType.CENTER_CROP) {
   float scale = Math.max(widthScale, heightScale);
    mBaseMatrix.postScale(scale, scale);
    //Changed dy = 0 for top crop
    mBaseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2F, 0);

Source: http://www.widecodes.com/fxSzNWPeVX/android-image-view-top-crop.html

Since I so that people are requesting more scaleTypes in ImageView: https://code.google.com/p/android/issues/detail?id=58468 I added custom scale types to Chris Banes`s PhotoView.
I send a PR to him. Since I don't know if he will accept the PR(or when), you can get the project in my github: https://github.com/jonathanrz/PhotoView/ and add the aar to your project manually.
You can see an example of usage in CropTypeActivity in the sample project inside the library.

A: If you don't want to modify PhotoView library,
How about this solution using CustomAttacher class.
Inherit PhotoViewAttacher then override getDrawMatrix() method.
public class CustomAttacher extends PhotoViewAttacher {

    public CustomAttacher(ImageView imageView) {
        this(imageView, true);
    }

    public CustomAttacher(ImageView imageView, boolean zoomable) {
        super(imageView, zoomable);

    }

    @Override
    public Matrix getDrawMatrix() {
        Matrix mx = super.getDrawMatrix();
        float[] values = new float[9];
        mx.getValues(values);
        values[Matrix.MTRANS_Y] = 0;
        mx.setValues(values);
        return mx;
    }

}