text:
Q: Can I expedite VLC stream to make files faster? I want to split a long 50 minute video file into two 25 minute parts. I finally found out how to stream one video file into another video file via the command line thanks to http://www.videolan.org/doc/streaming-howto/en/ch03.html and http://www.videolan.org/doc/streaming-howto/en/ch04.html docs.
Here is the terminal command I used to achieve this:
vlc original_video.mp4 --start-time 0 --stop-time 1500 --sout "#standard{access=file,mux=ts,dst=/home/max/Desktop/video_A.mp4}"

The only problem is that it seems as though VLC is just sitting there streaming the original_video.mp4 into video-A.mp4. I stopped it after 5 minutes and saw that video_A.mp4 was only 5 minutes long.
Is there a way to exedite this process?

A: I would use ffmpeg's segment muxer (scroll down a bit on that link for some examples). Basically:
ffmpeg -i input.mp4 -c copy -f segment -segment_times 1500 output%02d.mp4

This will produce two files, 'output01.mp4' and 'output02.mp4'. If you were to use output%03d.mp4, you would instead get 'output001.mp4' and 'output002.mp4'.
-segment_times calls for a comma-separated list of split-points, measured in seconds. As you only want to split once, at 25 minutes, just use 1500 (=25*60). Note that -segment_time (without the 's') is a completely separate option - you'd use that if you wanted to split the file every five seconds (for example), without putting in a big list of every specific time.
You may find that you need to use -reset_timestamps 1 for the files to play correctly:
ffmpeg -i input.mp4 -c copy -f segment -segment_times 1500 -reset_timestamps 1 output%02d.mp4

There are a lot more options on the documentation page. This should be pretty quick, and lossless (so you'll get identical video with no extra video artefacts). However, it won't be 100% accurate, since ffmpeg needs to split on a key frame, which can't be guaranteed without re-encoding.
If you need accurate splitting, the documentation recommends re-encoding and using the -force_key_frames and -segment_time_delta options to ensure that there will be I-frames on the times that the segment muxer will attempt to split on (see also the libx264 and AAC encoding guides on the ffmpeg wiki):
ffmpeg -i input.mp4 -c:v libx264 -crf 22 -preset veryfast -c:a libfdk_aac -vbr 3 \
-force_key_frames 1500 -f segment -segment_times 1500 -segment_time_delta 0.05 output%02d.mp4

The version of ffmpeg in most Linux repositories is going to be quite old, and in the case of Debian and Ubuntu et al the situation is even worse: they do not provide ffmpeg, but rather the fork, avconv, from the libav team (see also LordNeckbeard's answer here). AVconv is a perfectly fine tool on its own, but I can't guarantee that the ffmpeg syntax will work with it 100% of the time, especially with 'advanced' stuff like this.
I would recommend either grabbing a static build from the ffmpeg Downloads page or compiling it yourself. The main benefit of compiling it yourself is that you can get access to libfdk_aac, the best AAC audio encoder that ffmpeg can use - which cannot be legally distributed in a compiled ffmpeg binary, due to licensing conflicts (fdk_aac uses a custom copyleft license, which isn't quite compatible with ffmpeg's GPL).


text:
Q: Object reference not set to an instance of an object - Model Binding I have read Object reference not set to an instance of an object. and What does "Object reference not set to an instance of an object" mean? posts but still not able to get help because my case is different.
Simple Code
<script>
   var PatientId;
   var DoctorId;

   if(isPatient && @Model.Patient != null) {
        PatientId = @Model.Patient.Id;
        DoctorId = userConnection.User.Id;
   } else if(!isPatient && @Model.Doctor != null) {
        DoctorId = @Model.Doctor.Id; // Right here I get ERROR
        PatientId = userConnection.User.Id;
   }
</script

Error
System.NullReferenceException: Object reference not set to an instance of an object.

In my case either @Model.Patient or @Model.Doctor will be null.
Right now I know that @Model.Doctor is null, but I am already checking its null condition above. How to cater this problem ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Application continue to perform network operation after entering to the background? I was looking into a debug file my application creates while running and saw a strange behavior:
The application uses NSURLConnction to retrieve some data from a server. The connection was started and then the user moved application to the background probable by pressing the home button (application:willResignActive and application:didEnterBackground methods were called).
I could see that the connection was handled in my code after application:didEnterBackground was called. (The connectionDidFinishLoading of NSURLConnection delegate was called after application:didEnterBackground). In the implementation of connectionDidFinishLoading I perform some operations, but at this point application was probable suspended and the code wasn't called.
Then after almost 12 hours user launched application again (it wasn't terminated, but only was in the background) and the code continued running from the same point it stopped, even before application:willEnterForeground and application:didBecomeActive were called).
Does it make scenes?
The part of code running before application entered to the foreground changed my application internal state and cause to strange behavior.
Any ideas how to solve it?

A: after you receive application:didEnterBackground you have about 5 seconds to do the finishing stuff, after which your application is no longer being scheduled on the cpu.
In your case, the best solution is to announce the start of background work via beginBackgroundTaskWithExpirationHandler: and finish the download and related tasks.


text:
Q: Connecting two Ethernet PHY without magnetics? In a (tentative) new design I want to connect two 100 Mbit/s Ethernet PHY similar to LAN8270a, separated by few inches on the same PCB, with same ground plane (but different power supplies). I have the choice of one of my PHY, but the other is embedded in an as-yet-unspecified PCIe to Ethernet IC (perhaps Gigabit but used in 100 Mbit/s mode), and it is critical that this PHY thinks there is a bona fide 100 Mbit/s Ethernet connection.
I could use the following

simulate this circuit – Schematic created using CircuitLab
but I would like to achieve the same without the magnetics, in order to save on cost, purchasing headaches, and if at all possible power consumption.
I can imagine an RC network, perhaps as simple as in this appnote, found thanks to a similar question; or maybe engineered with attenuation and lowpass, but that will not emulate the fact that with real magnetics, when there is a negative pulse on TX1P, there is a positive pulse on TX1M and RX2M. I am uncertain about if that would prevent some PHYs from working normally.
Anything to suggest that one is confident will work for practically any PHY around?

A: You might be interested by these Application Notes about transformerless/magnetic-less ethernet application

*

*Intel AP-438 : http://www.intel.com/content/dam/doc/application-note/8255x-fast-ethernet-controllers-without-magnetics-appl-note.pdf

*TI AN-1519 : http://www.ti.com/lit/an/snla088a/snla088a.pdf
They both have an example of transformerless operation on a PCB, with a capacitor in place of a transformer.
In a case where you control both side of the connector, only one capacitor on the line can be mounted. But if you control only one side you have to put a capacitor two, in case the other side has nothing or has a transformer.
I had to work on a 1000Base-KX backplane connection, and its problem is this standard is not very well known and you can have difficulties to implement it, have information about it, etc.
In my case I needed to have an oscilloscope pattern to observe the signal. After few email to the oscilloscope company and few phone calls I had them understood that I was talking about 1000Base-KX and not 1000Base-CX (Ethernet over Coax).
The 1000Base-KX was "retro-implemented" in the IEEE802.3 when the 10GBase-KX was created. So the 1000Base-KX is a standard derived from 10G and officially become a IEEE standard years after the adoption of the Gigabit standards.
Also 1000Base-KX only need 2 pairs (Full-Duplex) but the operating frequency is around 1Ghz which involves signal integrity issues where 1000Base-T and 100Base-T(X) stays at 125MHz.

A: What you really need is a different variety of PHY, so called "backplane phy". Those are specifically designed to work with capacitive coupling over PCB traces.
The relevant standard is called 802.3ap. Here's a nice overview: ftp://ftp.t10.org/t10/document.05/05-214r1.pdf
Many modern PHYs can be put into a 1000Base-KX mode through a bit of configuration tweaking.
One long running and popular PHY of the above variety, which can be frequently found on all kinds of expansion boards is Marvel 88E1145: http://www.marvell.com/transceivers/assets/Marvell-Alaska-Quad-88E1141-45-GbE.pdf
Many integrated Ethernet controllers also support this mode of operation (Intel as an example): http://www.intel.com/content/dam/doc/application-note/82545-82546-82571-82572-631xesb-632xesb-gbe-controllers-serdes-design-appl-note.pdf

A: The transformers are there to help impedance match to an RJ45 Ethernet line so if you're confident that the impedance match you will be fine even for tens of feet.
Small print
Transformers also protect silicon from line disturbances that might otherwise kill silicon so be aware of this. They also isolate galvanically the two systems and stop earth loops passing currents that can cause poor data quality. Providing you don't need to have a dc level on the connection (that is usually harnessed via a transformer centre-tap) and you have both systems connected thru capacitors it should work. Read the datasheet.

A: Etherent uses various types of line codes to ensure that the transmitted data is DC balanced.  4b/5b is the line code used in 100 Mbit ethernet, and then it is transmitted with MLT-3 encoding.  The 4b/5b code caps the number of ones and zeros you can get in a row.  Then MLT-3 transmits three different voltage levels, -1, 0, and +1.  A transition represents a 1 and no transition represents a zero.  So it doesn't matter if the line is inverted or not as the transitions carry the information, not the levels.  Now, it's possible that some PHY chips will not be able to drive something that's not a transformer, so you may have a problem there depending on how it's connected.  I think that would only be a problem if the ouputs are open collector instead of push-pull.  You should be able to get away with one transformer, though.


text:
Q: (Obvious?) Half-Space Poisson Kernel Estimate In Stein's Singular Integrals and Differentiability Properties of Functions, Theorem 1 (a) of Chapter 8 (pg. 197) he makes the claim without proof that the Poisson Kernel for the half-space $\mathbb{R}^{n+1}_{+}$
$$P_{y}(x)=\frac{c_{n}y}{(|x|^{2}+y^{2})^{(n+1)/2}}$$
majorizes its $t$ translation $P_{y}(x-t)$ with absolute constant $A_{\alpha}$ (depending only on $\alpha$, which we are free to fix) so long as $|t|<\alpha y.$  That is, with $t$ so restricted,
$$P_{y}(x-t)\leq A_{\alpha}P_{y}(x).$$
The setting here is $x\in\mathbb{R}^{n}$ and $y\in\mathbb{R}$.  $c_{n}$ is just a constant depending on the dimension $n$ (the volume of the unit ball I believe).  $x$ is regarded as being in $\partial\mathbb{R}^{n+1}_{+}$ and $y$ the perpendicular component of a point $(x,y)\in\mathbb{R}^{n+1}.$
This does not seem at all obvious to me as he says.  Furthermore, this assertion is markedly similar to my previous (still unanswered) question here Some Scaling Estimate for Heat Kernel (notationally, just change $y$ to $\sqrt{y}$, add an aditional constant $\beta$ for $\beta y$ and then interchange the roles of $y$ and $t$).  I guess I am just having a hard time understanding and proving these estimates and it's causing me some problems with what I'm trying to do.  Any help is appreciated.

So let us cancel $y$ and $c_{n}$ and raise both sides of the inequality to the $(n+1)/2$ power and put $C_{\alpha}=A_{\alpha}^{(n+1)/2}$.  Then we have to show
$$\frac{1}{|x|^{2}+y^{2}-2x\cdot t+|t|^{2}}\leq\frac{C_{\alpha}}{|x|^{2}+y^{2}}$$
when $|t|\leq\alpha y.$  We obviously have to somehow control the $|t|^{2}-2x\cdot t$ term and adjust $C_{\alpha}$ accordingly, but I'm not sure how to do this because of $x$, which is unrestricted.

A: I think the statement should be understood from the perspective of Possion kernel. The classical Possion kernel is given by
$$P_{y}(x)=\frac{y}{x^{2}+y^{2}},u(x+iy)=\frac{1}{\pi}\int^{\infty}_{-\infty}P_{y}(x-t)f(t)dt$$(see the wikipedia article http://en.wikipedia.org/wiki/Poisson_kernel)
In other words at here both $x,y$ are fixed and only $t$ is allowed to changed. Here we have to show
$$\frac{1}{(|x-t|^{2}+y^{2})^{n+1}}\le C\frac{1}{(x^{2}+y^{2})^{n+1}},\forall t, |t|<\alpha y$$
Notice Stein's book has a typo where he wrote $f(z)dx$, which should be $f(z)dz$ instead. Now for fixed $x$, the maximum and minimum for $|x-t|^{2}$ is fixed as well. So the above statement must be true since the left hand side is bounded.

A: For real $x$, $y$, and $t$,
$$
      x^{2}+y^{2} = ((x-t)+t)^{2}+y^{2} = (x-t)^{2}+2(x-t)t+t^{2}+y^{2}.
$$
For real $a$ and $b$, one has $ab \le |ab| \le \frac{1}{2}(a^{2}+b^{2})$. For $\rho > 0$, one also has $2ab \le \rho a^{2}+\frac{1}{\rho}b^{2}$. Hence, if $\alpha > 0$, $y \ge 0$, and $|t| \le \alpha y$,
$$
      x^{2}+y^{2} \le (x-t)^{2}+\alpha(x-t)^{2}+\frac{1}{\alpha}t^{2}+y^{2} \le  (1+\alpha)\{(x-t)^{2}+y^{2})\}.
$$
Finally, in terms of the Poisson kernel $P_{y}(x)=\frac{y}{x^{2}+y^{2}}$ for the upper half-plane,
$$    P_{y}(x-t)=\frac{y}{(x-t)^{2}+y^{2}} \le \frac{A_{\alpha}y}{x^{2}+y^{2}}=A_{\alpha}P_{y}(x),\;\;\; y > 0,\;|t| \le \alpha y,\; x \in\mathbb{R}.
$$
The argument can be modified to work for Poisson kernels on higher-dimensional half spaces.
BTW: This is also related to the heat kernel issue. It is possible to study non-tangential limits as $t \rightarrow 0$ for solutions of the heat equation, or to study non-tangential limits of harmonic functions on a half-space as one approaches the boundary of the half space.
One thing that can be shown is this: if $\phi(x,y)$ is a bounded harmonic function on the upper half-plane where $y > 0$, then $\phi(x,0+)=\lim_{y\downarrow 0}\phi(x,y)$ exists for almost every $x \in \mathbb{R}$, and
$$
               \phi(x,y)=\frac{1}{\pi}\int_{-\infty}^{\infty}\frac{\phi(x,0+)y}{(x-t)^{2}+y^{2}}\,dt =\frac{1}{2\pi i}\int_{-\infty}^{\infty}\phi(x,0+)\left[\frac{1}{t-(x+iy)}-\frac{1}{t-(x-iy)}\right]dt.
$$
The non-tangential limits of $\phi$ also exist, and equal the orthogonal limits.


text:
Q: Соединение Node.Js и React Есть соединение с БД MySQL(PSIH/server/app.js). Соединение работает корректно.

И есть страница входа (PSIH/psiholog/src/pages/Login.js)

Как мне их связать, чтобы реализовать форму входа, которая бы перебирала значения логина и пароля в БД, и при правильном вводе перебрасывалась на страницу PSIH/psiholog/src/pages/Home.js.
import React, { Component } from "react";

export default class Login extends Component{
    render(){

        return (

Welcome!

                            <form className="d-flex flex-column" href="/tests">
                                Логін
                                <input type="text" name="login"/>
                                Пароль
                                <input type="pass" name="pass"/>
                                <button className="btn btn-primary mt-3" type="submit">Отправить</button>
                            </form>

        )
    }
}


text:
Q: Error selecting rows from datatable in jsf 2.2 I have a datatable with a checkbox column to select some rows, when the user is logged everything works fine but when the user is not logged the list with the selected rows are empty after the post, i cant figure it out because this is done automatically by the datatable component, it has nothing to do with the fact that the user is logged or no, maybe it is a bug in jsf 2.2? I'm using the datatable from primefaces 5.
public CompareReportBean() {
    rowsToCompare = List<TabelaEmpresa>)FacesContext.getCurrentInstance().getExternalContext().getRequestMap().get("rowsToCompare");

    WorksheetService ws = new WorksheetService();
    for(TabelaEmpresa t : rowsToCompare) {
        t.setColunas(ws.retrieveColumnsFromTable(t));
    }

    columnKeys = new ColunaTabela[rowsToCompare.size()];
}

When the user is logged rowsToCompare contains the rows selected by the user, and when the user is not logged rowsToCompare is empty, but the code executed is the same in both situations.


text:
Q: Unable to download file from Google Drive using API - node.js I am trying to download a File from google drive using Google SDK API using node.js.
But I am unable to write/save file at server side - node.js
Code:-
var GoogleTokenProvider = require("refresh-token").GoogleTokenProvider,
    async = require('async'),
    fs = require("fs"),
    request = require('request'),
    _accessToken;

var _XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var https = require('https');

const CLIENT_ID = "";
const CLIENT_SECRET = "";
const REFRESH_TOKEN = '';
const ENDPOINT_OF_GDRIVE = 'https://www.googleapis.com/drive/v2';

async.waterfall([
        //-----------------------------
        // Obtain a new access token
        //-----------------------------
        function(callback) {
            var tokenProvider = new GoogleTokenProvider({
                'refresh_token': REFRESH_TOKEN,
                'client_id': CLIENT_ID,
                'client_secret': CLIENT_SECRET
            });
            tokenProvider.getToken(callback);
        },

        //--------------------------------------------
        // Retrieve the children in a specified folder
        //
        // ref: https://developers.google.com/drive/v2/reference/files/children/list
        //-------------------------------------------
        function(accessToken, callback) {
            _accessToken = accessToken;
            request.get({
                'url': ENDPOINT_OF_GDRIVE + '/files?' + "q='root' in parents  and (mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')",
                'qs': {
                    'access_token': accessToken
                }
            }, callback);
        },

        //----------------------------
        // Parse the response
        //----------------------------
        function(response, body, callback) {
            var list = JSON.parse(body);
            if (list.error) {
                return callback(list.error);
            }
            callback(null, list.items[0]);
        },

        //-------------------------------------------
        // Get the file information of the children.
        //
        // ref: https://developers.google.com/drive/v2/reference/files/get
        //-------------------------------------------
        function(children, callback) {

            var xhr = new _XMLHttpRequest();
            xhr.open('GET', children.downloadUrl);
            xhr.setRequestHeader('Authorization', 'Bearer ' + _accessToken);
            xhr.onload = function() {
                console.log("xhr.responseText", xhr.responseText)
                fs.writeFile("download.docx", xhr.responseText)
                callback(xhr.responseText);
            };
            xhr.onerror = function() {
                callback(null);
            };
            xhr.send();
        }
    ],
    function(err, results) {
        if (!err) {
            console.log(results);
        }
    });

I am getting this in console:-
    Content of xhr.responseText is something like that
��▬h��↕E6M��~��3�3∟�9�� � �►��/2�:���♂�4��]�♀I�R���►
$SB6Q���c↔��H�=;+
���►q�3Tdכ��@!T��hEl_�|�I�↨��h(�^:▬�[h̓D♠��f���♠*���ݾ��M→
�1⌂♦"N�↑�o�]�7U$��A6����♠�W��k`�f▬♫��K�Z�^‼�0{<Z�▼�]F�����

                             ���J♥A♀��♣�a�}7�
"���H�w"�♥���☺w♫̤ھ�� �P�^����O֛���;�<♠�aYՠ؛`G�kxm��PY�[��g
Gΰino�/<���<�1��ⳆA$>"f3��\�ȾT��∟I S�������W♥����Y

Please help me to know what is the format of the data I am getting from Drive Api and write it in which format so that I got a complete .docx file
Edit
I am open to use any method other than xmlRequest if it helps me downloading the file(.docx).

A: Complete Working example: Downloading file from GoogleDrive - Node.js API
var GoogleTokenProvider = require("refresh-token").GoogleTokenProvider,
    async = require('async'),
    fs = require("fs"),
    request = require('request'),
    _accessToken;

const CLIENT_ID = "";
const CLIENT_SECRET = "";
const REFRESH_TOKEN = '';
const ENDPOINT_OF_GDRIVE = 'https://www.googleapis.com/drive/v2';

async.waterfall([
        //-----------------------------
        // Obtain a new access token
        //-----------------------------
        function(callback) {
            var tokenProvider = new GoogleTokenProvider({
                'refresh_token': REFRESH_TOKEN,
                'client_id': CLIENT_ID,
                'client_secret': CLIENT_SECRET
            });
            tokenProvider.getToken(callback);
        },

        //--------------------------------------------
        // Retrieve the children in a specified folder
        //
        // ref: https://developers.google.com/drive/v2/reference/files/children/list
        //-------------------------------------------
        function(accessToken, callback) {
            _accessToken = accessToken;
            request.get({
                'url': ENDPOINT_OF_GDRIVE + '/files?' + "q='root' in parents  and (mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document')",
                'qs': {
                    'access_token': accessToken
                }
            }, callback);
        },

        //----------------------------
        // Parse the response
        //----------------------------
        function(response, body, callback) {
            var list = JSON.parse(body);
            if (list.error) {
                return callback(list.error);
            }
            callback(null, list.items);
        },

        //-------------------------------------------
        // Get the file information of the children.
        //
        // ref: https://developers.google.com/drive/v2/reference/files/get
        //-------------------------------------------
        function(children, callback) {

            for(var i=0;i<children.length;i++) {
                var file = fs.createWriteStream(children[i].title);
                // Downnload and write file from google drive
                (function(child) {
                    request.get(
                      { url: child.downloadUrl
                      , encoding: null    // Force Request to return the data as Buffer
                      , headers:
                        { Authorization: 'Bearer ' + _accessToken
                        }
                      }
                    , function done (err, res) {
                        res.pipe(file)
                        // If all is well, the file will be at res.body (buffer)
                        fs.writeFile('./' + child.title, res.body, function (err) {
                            if(!err) {
                                console.log('done')
                            } else {
                                console.log(err)
                            }
                          // Handle err somehow
                          // Do other work necessary to finish the request
                        })
                      }
                    )

                })(children[i])
            }
        }
    ],
    function(err, results) {
        if (!err) {
            console.log(results);
        }
    });

A: I was just having issues with this, I've included an example of how I managed to get this working using the Google API Node.js library: https://gist.github.com/davestevens/6f376f220cc31b4a25cd

A: node-XMLHttpRequest, it seems, does not support binary downloads - see this issue. What you are seeing is the file's binary contents converted into String which, in JavaScript, is an irreversible and destructive process for binary data (which means you cannot convert the string back to buffer and get the same data as the original contents).
Using request, you can download a binary file this way:
var request = require('request')
  , fs = require('fs')

request.get(
  { url: 'your-file-url'
  , encoding: null    // Force Request to return the data as Buffer
  , headers:
    { Authorization: 'Bearer ' + accessTokenHere
    }
  }
, function done (err, res) {
    // If all is well, the file will be at res.body (buffer)
    fs.writeFile('./myfile.docx', res.body, function (err) {
      // Handle err somehow
      // Do other work necessary to finish the request
    })
  }
)

Note: This will buffer the whole file into memory before it can be saved to disk. For small files, this is fine, but for larger files, you might want to look into implementing this as a streamed download. This SO question already answers that, I recommend you have a look.
More information about how to authorize your requests can be found on Google Developers docs.


text:
Q: Silverlight 4 Drag and Drop Treeview Does anyone have an example for any of the following scenarios.
Given, these are all dynamically populated trees.  Not using a Heirarchal data template, but by iterating through object collections manually and appending children at the appropriate level.

*

*Treeview1 has 3 levels, but items can only be reordered within their level.  So, lets say we have Drives, Folders and Files.  Drives can be rearranged in an order, but not put into a Folder.  When navigated down one level in a drive, the individual folders can be reordered, but not dragged between drives.. and same with files, only can be reordered, but not moved to a different folder or drive

*I have 2 treeviews, Treeview1 is the same as #1 above and Treeview2 is like a picklist of available items.  A user can drag an item from Treeview2 to Treeview1, but it can only be placed at Treeview1's File Level.  The dragged item cannot be a child of a file, or placed at the folder level, nor placed at the drive level.  Also, how to handle the Above, On Top, or Below an item.
I have yet to come across these examples.

A: You should make 1 ListBoxDragDropTarget with a list box in it. The listbox has 3 item. Each item contains Listbox DragDropTarget with a list box in it. And every sub level contains an listbox again for all the files. With a little effort you can create your own listboxitem which has a button to open or close it like a treeview. And tada,, you can rearrange the items but no the levels.


text:
Q: Keras LSTM input/output shape I need outputs at every recurrent layer and my setup is as follows:
100 training examples, 3 time steps per example, and 20-d feature vector for each individual element.
x_train: (100,3,20)
y_train: (100,20)
LSTM architecture:
model.add(LSTM(20, input_shape=(3,20), return_sequences=True))
model.compile(loss='mean_absolute_error', optimizer='adam', metrics=['accuracy'])
model.summary()

Training:
history = model.fit(x_train, y_train, epochs=50, validation_data=(x_test, y_test))

Error:
ValueError: Dimensions must be equal, but are 20 and 3 for '{{node Equal}} = Equal[T=DT_FLOAT, incompatible_shape_error=true](IteratorGetNext:1, Cast_1)' with input shapes: [?,20], [?,3].

Please help me with the correct input/output LSTM dimensions.
Thanks

A: LSTM(20, input_shape=(3,20), return_sequences=True) takes as input shape (100,3,20) and returns (100,3,20). Your target output is however encoded as (100,20).
From the dimensions, I assume you want to map each sequence to a non-sequence, i.e. you can do:
LSTM(20, input_shape=(3,20), return_sequences=False)

This will return the final hidden state, i.e. a shape of (100,20) which matches your target output.


text:
Q: Recorrer respuesta laravel con jquery y valir si existe valor dentro quisiera por favor me orientaran sobre la siguiente situación...creo algo estoy haciendo mal.
Estoy en laravel 8
Controlador :
    public function index(){
    $permisos = Permission::all();
    return view('vista.index', compact('permisos'));
}

Mi vista.blade.php :
<script>
$(document).ready(function () {
    jobs = @json($permisos);//Recibo la variable desde laravel
    console.log(jobs);
    console.log(jobs.includes('permiso_modulo_editar"')); //Validar que el valor enviado exista en el array proviente de laravel
});
</script>

La respuesta al mostrar lo que trae la variable $permisos desde el controlador :

La respuesta del "includes('permiso_modulo_editar')" para validar si existe o no dentro :

En resumen, necesito enviar la variable $permisos desde el controlador a mi index.blade.php y en la sección < script> con jquery validar si un valor cualquiera existe en su interior.
Agradecere su ayuda, gracias.

A: Puedes utilizar la función find de js
let permission = jobs.find(job => job.name === 'permiso_modulo_editar');

if(permission) {
    // Existe
}


text:
Q: Eclipse's local history...where are files saved? Can someone explain how Eclipse's local history works?
I accidentally overwrote a file in a project but need to revert to an earlier version.
Is there a chance that Eclipse has the older file cached somewhere?

A: If you have lost a full package structure due to accidental deletion or svn/cvs override, select the project> right click> Restore from local history => select the files.

A: To complete CurtainDog's answer: from eclipse FAQ

Every time you modify a file in Eclipse, a copy of the old contents is kept in the local history. At any time, you can compare or replace a file with any older version from the history.
  Although this is no replacement for a real code repository, it can help you out when you change or delete a file by accident.
  Local history also has an advantage that it wasn't really designed for: The history can also help you out when your workspace has a catastrophic problem or if you get disk errors that corrupt your workspace files.
  As a last resort, you can manually browse the local history folder to find copies of the files you lost, which is a bit like using Google's cache to browse Web pages that no longer exist.
Each file revision is stored in a separate file with a random file name inside the history folder. The path of the history folder inside your workspace is

.metadata/.plugins/org.eclipse.core.resources/.history/

You can use your operating system's search tool to locate the files you are looking for.

Note, if your need to import your local history into a new workspace, you will need both:

*

*.metadata/.plugins/org.eclipse.core.resources/.history

*.metadata/.plugins/org.eclipse.core.resources/.project

to have a functional local history in that new workspace.

A: VonC's answer has all the information you need for finding the location of your code backups. I would simply add that if you are on a Mac or Linux, you can do something like this:
$ cd [WORKSPACE]/.metadata/.plugins/org.eclipse.core.resources/.history/
$ grep -rl "class Foo" . | xargs ls -lt

This will find all the versions of a file that contains a particular string (ie. "class Foo"), and sort them by date/time to easily find the most recent version.

A: Try right-clicking on the file in eclipse, and choose Replace With->Local History.
If there's history available, it'll show up as a list of edit times.
But more importantly, as pointed out in other answers, be sure to put your files in version control! SVN is pretty easy to set up (you don't need a server; it can just use the file system); use it even if you aren't sharing with others.
A tip: whenever you hear yourself say "yes!", check in all of your code. 10 minutes later, you'll be saying "how did I mess that up?"

A: You can use the link http://wiki.eclipse.org/FAQ_Where_is_the_workspace_local_history_stored%3F is very helpfull

A: Open the CVS view and you should see a filter for local history. You should then be able to right-click on the correct version and Get Contents or do a manual compare and merge. I'm not sure what the eclipse defaults are for keeping local history but there is a decent chance you'll be able to get your stuff back if you act quickly.


text:
Q: No object pairs in plist reading data from a server I am trying to read a plist from a server. I know for a fact that the plist is valid since when I go to the URL i get the plist downloaded and the plist editor shows me my array properly. Now when I use the following code I get now array populated. I see the data is in there. In debugger i see that plistData has value however the array petListArray has no data at all. What is wrong?
    - (void)getPetListRequestFinished:(ASIHTTPRequest *)request
    {
        NSData *plistData = [request responseData];
        NSError *error = nil;
        NSPropertyListFormat format = NSPropertyListBinaryFormat_v1_0;
        NSArray *petListArray = (NSArray *)[NSPropertyListSerialization propertyListWithData:plistData
                                                                         options:(NSPropertyListReadOptions)NSPropertyListImmutable format:&format error:(NSError **)error];

    if(error){

        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"GetPetListError"  message:[NSString stringWithFormat:@"getPettListRequestFinished_new deserialization error: error = %@", error]
                                                        delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
        return;
    }
----snip-------

A: You are passing the wrong type of argument for the error: slot of - NSPropertyListSerialization propertyListWithData:options:format:error:. Try:
[NSPropertyListSerialization propertyListWithData: plistData
                             options: (NSPropertyListReadOptions) NSPropertyListImmutable
                             format: &format
                             error: &error]

(edited after checking docs)


text:
Q: SAS differences in outcome between sql and proc means I want to have a weighted average of some variable in a macro variable. My var is zindi&aa and my weight is wprm&aa
I am trying to make sense of two ways of doing it :
one with a proc sql
proc sql noprint;
    select mean(zindi&aa. * wprm&aa.)/sum(wprm&aa.) into :Mean_zindi_aa
    from Panel(where=(annee&ap.<="&nais18" ));
quit;

it yields me an average of 0.77
one with proc means
proc means data=Panel(where=(annee&ap.<="&nais18" ));
    var zindi&ap. ;
    weight wprm&ap ;
    output out=mean_zindi&ap mean=moy≈
run;

and then a data _null_ part
which yields an average of around 20200 that seems to be the correct one
so my question is

*

*what  I am missing with the proc sql so that it does give an absurd result ?

*is there a better way to obtain my macro variable &mean_zindi_aa

A:     proc sql noprint;
    select sum(zindi&aa. * wprm&aa.)/sum(wprm&aa.) into :Mean_zindi_aa
    from Panel(where=(annee&ap.<="&nais18" ));
    quit;

Try this. Looks like you are trying to do a mean on (zindi&aa. * wprm&aa.). If you need the weighted average the above should work. because weighted average =  sum(weight*variable)/sum(weights)

A: Change your PROC SQL to:
proc sql noprint;
    select SUM(zindi&aa. * wprm&aa.)/sum(wprm&aa.) into :Mean_zindi_aa
    from Panel(where=(annee&ap.<="&nais18" ));
quit;

You need to SUM the product, not take the MEAN.


text:
Q: Every compact manifold with fundamental group $ \mathbb{Z} $ is a mapping torus Suppose that $ M $ is the mapping torus of some homeomorphism of a manifold $ F $. Then $ M $ is a fiber bundle with fiber $ F $ and base space $ S^1 $
$$
F \to M \to S^1
$$
So if $ F $ is connected and simply connected then by LES homotopy we have
$$
\pi_1(M) \cong \pi_1(S^1) \cong \mathbb{Z}
$$
Let $ M $ be a compact $ n $ dimensional manifold with fundamental group $ \pi_1(M) \cong \mathbb{Z} $. Is it true that $ M $ must be the mapping torus of a compact connected simply connected $ n-1 $ dimensional manifold?
My thoughts so far:

*

*True for $ n=1 $ because $ S^1 $ is a mapping torus for the point.

*True for $ n=2 $ because there are no compact simply connected 1 manifolds so there are no compact 2 manifolds with fundamental group $ \mathbb{Z} $

*True for $ n=3 $ since the only compact simply connected 2 manifold is the sphere $ S^2 $ and indeed the only 3 manifolds with fundamental group $ \mathbb{Z} $ are the trivial mapping torus $ S^2 \times S^1 $ and the mapping torus of the antipodal map (these are the only two possible mapping tori for $ S^2 $). For example see What closed 3-manifolds have fundamental group $\Bbb Z$?
I expect this already fails for $ n=4 $ and almost certainly fails for generic $ n $. But I figured it couldn't hurt to ask.

A: Let $F$ be a path-connected topological space and $\phi : F \to F$ a homeomorphism. Denote the mapping torus of $\phi$ by $M$ so that we have a fiber bundle $F \to M \to S^1$. Explicitly, $M = F\times[0, 1]/\sim$ where $(x, 0) \sim (\phi(x), 1)$. From the long exact sequence in homotopy, there is a short exact sequence $$0 \to \pi_1(F) \to \pi_1(M) \to \pi_1(S^1) \to 0.$$ The covering space of $M$ corresponding to the image of $\pi_1(F)$ in $\pi_1(M)$ is homeomorphic to $F\times\mathbb{R}$. This follows from the fact that $M$ can be constructed as the quotient of $F\times\mathbb{R}$ by the $\mathbb{Z}$-action generated by $(x, t) \mapsto (\phi(x), t + 1)$. In particular, the universal cover of $M$ is homeomorphic to $\widetilde{F}\times\mathbb{R}$ where $\widetilde{F}$ is the universal cover of $F$.
Suppose now that $F$ is a closed $(n-1)$-manifold, so that $M$ is a closed $n$-manifold. If $\pi_1(M) \cong \mathbb{Z}$, then $\pi_1(F) = 0$ by the short exact sequence above. As suggested by Moishe Kohan, let $N = M \# X$ where $X$ is a closed simply connected $n$-manifold, then $\widetilde{N}$, the universal cover of $N$, is homeomorphic to the connected sum of $\widetilde{F}\times\mathbb{R} = F\times\mathbb{R}$ and countably many copies of $X$. If $H_k(X; \mathbb{Z}) \neq 0$ for some $0 < k < n$, then it follows from Mayer-Vietoris that $H_k(\widetilde{N}; \mathbb{Z}) \cong H_k(\widetilde{F}; \mathbb{Z})\oplus\bigoplus_{i\in\mathbb{Z}}H_k(X)$; in particular, $H_k(\widetilde{N}; \mathbb{Z})$ is not finitely generated. As $\pi_1(N) \cong \pi_1(M) \cong \mathbb{Z}$, if $N$ were a mapping torus, the fiber $F'$ would be a closed simply connected manifold, so $\widetilde{N}$ would be homeomorphic to $\widetilde{F'}\times\mathbb{R} = F'\times\mathbb{R}$ which has finitely generated homology. Therefore $N$ is not a mapping torus. Note, if $H_k(X; \mathbb{Z}) = 0$ for all $0 < k < n$, then $X$ is a simply connected homology sphere and hence homeomorphic to $S^n$, in which case $N$ is homeomorphic to $M$ (which is a mapping torus).
I believe that the hypothesis $\pi_1(M) \cong \mathbb{Z}$ is unnecessary, but the proof above only extends to the case where $\pi_1(M)$ is an extension of $\mathbb{Z}$ by a finite group, i.e. $F$ has finite fundamental group.

A: Just posting this edit as an answer instead since there is nothing else to say here. All credit to Moishe Kohan:
I see. Thanks Moishe Kohan. I guess this is a good general lesson that too much of my intuition about topology is from dimension $ n \leq 3 $ in those dimensions (almost) everything can be determined from fundamental group. In dimension 2 and 1 manifolds are homeomorphic if and only if they have same fundamental group. This is almost true for dimension 3 as well. For example given $ \pi_1 $ for an orientable 3 manifold we can find all the homology and cohomology up to 3. Moreover, in dimensions 3 and under the only compact connected simply connected manifold is the sphere. So we can expect information about the fundamental group to be able to tell us very strong things about a manifold. But in dimension 4 and up there are lots of things other than the sphere that are compact connected simply connected (for example $ K_3 $ surface) and taking connected sum with any of those will give a manifold with same fundamental group but otherwise a totally different topology. So knowing only that a manifold is compact and has $ \pi_1 \cong \mathbb{Z} $ we should not expect to be able to show anything as strong as that it must be a mapping torus (at least not in dimension 4 and up).


text:
Q: Resize TWICImage without losing transparency How to resize a TWICImage without losing transparency? I use the JclGraphics.Resize() method whose parameter is a TBitmap. Transparency is lost in the TBitmap.Assign() method.
In this case, the image is of the type icon. But in another case, it may be a different type of image.
uses
  jclGraphics, ShellApi, UrlMon;

procedure ResizeImageStream(AStream: TMemoryStream; AWidth, AHeight: Integer);
var
  WicImage: TWicImage;
  Bitmap1: TBitmap;
begin
  WicImage := TWicImage.Create;
  try
    WicImage.LoadFromStream(AStream);
    if ((WicImage.Width > 32) or (WicImage.Height > 32)) then begin
      Bitmap1 := TBitmap.Create;
      try
        Bitmap1.Assign(WicImage);
        Bitmap1.Transparent := True;
        Bitmap1.TransparentColor := clBlack;
        Stretch(AWidth, AHeight, rfMitchell, 0, Bitmap1);
        WicImage.Assign(Bitmap1);
        AStream.Clear;
        WicImage.SaveToStream(AStream);
      finally
        FreeAndNil(Bitmap1);
      end;
    end;
  finally
    WicImage.Free;
  end;
end;

procedure ResizeImageFile(AFileNameSrc, AFileNameDsc: String; AWidth, AHeight: Integer);
var
  Stream: TMemoryStream;
begin
  Stream := TMemoryStream.Create;
  try
    Stream.LoadFromFile(AFileNameSrc);
    ResizeImageStream(stream, AWidth, AHeight);
    if FileExists(AFileNameDsc) then
      DeleteFile(AFileNameDsc);
    Stream.SaveToFile(AFileNameDsc);
  finally
    Stream.Free;
  end;
end;

procedure TForm4.FormCreate(Sender: TObject);
begin
  URLDownloadToFile(nil, PChar('https://www.shell.cz/apps/settings/wcm/designs/shell-rio/clientlibs/themes/theme-shell/resources/favicon/favicon.ico'),
    PChar('C:\p\favicon.ico'), 0, nil);
  ResizeImageFile('C:\p\favicon.ico', 'C:\p\favicon_32.ico', 32, 32);
end;

A: The WIC API has its own built-in resizing capabilities, you don't need to convert the TWICImage to a TBitmap at all. For example:
var
  WicImage: TWICImage;
  Scale: IWICBitmapScaler;
  WicBitmap: IWICBitmap;
begin
  WicImage := TWICImage.Create;
  try
    WicImage.LoadFromStream(Stream);

    OleCheck(WicImage.ImagingFactory.CreateBitmapScaler(Scale));
    OleCheck(Scale.Initialize(WicImage.Handle, 32, 32, WICBitmapInterpolationModeFant));
    OleCheck(WicImage.ImagingFactory.CreateBitmapFromSourceRect(Scale, 0, 0, 32, 32, WicBitmap));
    WicImage.Handle := WicBitmap;

    Stream.Clear;
    WicImage.SaveToStream(Stream);
  finally
    WicImage.Free;
  end;
end;


text:
Q: How to tell if a slide is "skipped" in Google Slides with Google Apps Script or API? In Google Slides, it's possible to set a slide to be "skipped" in presentation mode (as described here).
However, the automated page numbering still includes skipped slides (meaning that in presentation mode, if slide 4 is skipped, the slide numbering jumps straight from 3 to 5).
I want to use Google Apps Script to generate my own slide numbers so only non-skipped slides are counted. But I don't know how to check if a slide is marked as "skipped."
Here's what I have in mind:
function genSlideNumbers() {
  var preso = SlidesApp.openById('PRESENTATION_ID');
  var slides = preso.getSlides()
  var slide_num = 1
  for (var i = 0; i < slides.length; i++) {
    slide = slides[i]
    if ( /* ?? slide is "skipped" ?? */ ) {
      slides[i].insertTextBox(slide_num);
      slide_num++;
    }
  }
}

Is it possible?
Edit: Not a duplicate of this question because I'm not asking how to skip a slide; I'm asking if there's any way to tell if a slide is skipped.

A: As of 10/25/2019 there is no API access to the Skip Slide flag in the Slide or Presentation classes. Which means there's no method (using only Apps Script) to determine which slides to skip.
Ideally, there would be  slide.getSkip() and slide.setSkip() methods, but they don't currently exist. You can request them here.

A: Update: There is now a method slide.isSkipped() which determines if the slide is marked as skipped.  (Also slide.setSkipped() to set whether the slide will be skipped.)


text:
Q: Android Studio Firebase createUserWithEmailAndPassword OnComplete is not firing I am just doing a simple sign up for Android Studio, however for some reason the user is successfully created, but the onComplete never runs.
Log.d(TAG, "Before Testing" );
            mAuth.createUserWithEmailAndPassword(mEmail, mPassword)
                    .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
                        @Override
                        public void onComplete(@NonNull Task<AuthResult> task) {
                            Log.d(TAG, "Start Testing"+task.getException() );
                            Toast.makeText(LoginActivity.this, "New Account Is created",
                                    Toast.LENGTH_SHORT).show();
                            // If sign in fails, display a message to the user. If sign in succeeds
                            // the auth state listener will be notified and logic to handle the
                            // signed in user can be handled in the listener.
                            if (!task.isSuccessful()) {
                                Log.d(TAG, "Testing Not Success" + task.getException());
                                task.getException();

                                Log.d(TAG, "Testing Not Success 2" + task.isSuccessful());

                            }else{
                                Log.d(TAG, "Testing is Success" + task.isSuccessful());
                                // startActivity(new Intent(LoginActivity.this, MainMenuActivity.class));
                                // finish();
                            }

                            // ...
                        }
                    });

I would like to know how to check exception for why the onComplete never fired, since I am still very new to programming.
I am sorry if there are any duplicate question.


text:
Q: Controlling particles and height in React web app for mobile devices Currently learning React so apologies!
Im creating a web app in React.js and have successfully imported React-Particles-JS which is currently as:
<Particles
            canvasClassName="example"
            params={{
                "particles": {
                "number": {
                "value": 200
            },
            "size": {
            "value": 3
            }
           },
            "interactivity": {
            "events": {
            "onhover": {
                "enable": true,
                "mode": "repulse"
             }
            }
            }
        }} />

This works fine when viewing on a larger screen, but when viewing on a mobile makes it very cluttered so, what i want to know is how to reduce the value from 200 to something smaller depending on if in a smaller screen, and also increase the height of the Particles  canvas
At the moment it currently looks like this in mobile mode:

Many Thanks!

A: Here's what worked for me:
responsive: [{
          maxWidth: 500,
          options: {
            particles: {
              number: {limit: 50},
            },
          }
        }]

Sorry it's not inline like yours, I did this in a component file.
Hope this helps.


text:
Q: javascript - tooltip when selecting chinese text I would like to display a small tooltip that will embed chinese characters that users  select on a web page. Actually, I just want to be able to enlarge the font.  I have seen this kind of functionality on another website (ramou.net) but I don't think the way he has coded it is the most simple (and it doesn't seem to be very generic).
Any hints are welcome !
Thank you !

A: Found the solution :
   <!DOCTYPE html>

    "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris n多少钱多少钱多少钱多少钱isi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."


text:
Q: How to split core and transitive dependencies in gradle build file? I have 3 projects A, B and C where C is dependent on A and B.
Project A has some core API which changes very frequently (eg: every couple of weeks) and almost all the transitive dependencies needed for Project C which are pretty much constant all the time.
Project B has only core API which changes very rarely (eg: once every 2-3 months).
Project C has some custom implementations which use the core API's from both A and B.
Project C generates a runnable fat/uber/shade jar which is the end product. The problem is, overtime the jar became humongous and it takes atleast couple of hours just to build and publish it. My goal is to bring down this build time by only generating the necessary components as and when needed.
Our current gradle dependencies section looks like:
dependencies {
   implementation 'com:project-A:aaaa'
   implementation 'com:project-B:bbbb'
   implementation 'com:project-C-dependency-1:xxxx'
   implementation 'com:project-C-dependency-2:yyyy'
.
.
.
}

I am then using a Zip task to get all these dependencies included in a single distribution.
My goal is, if possible, to be able to create custom configurations such that I can create 4 seperate distributions - Project A core API, Project A transitive dependencies, Project B core API and Project C API. My issue is how to seperate core API and transitive dependencies from Project A after I am able to resolve it in Project C which should look like following:
`dependencies  {
   projectAcore ('com:project-A:aaaa') {
      transitive = false // This is exactly what I need
   }
   projectATD ('com:project-A:aaaa')  {
      // how to achieve transitiveOnly = true?
   }
   projectBcore ('com:project-B:bbbb')
   projectC .....`

One way I am able to get it to run is downloading everything from project-A and then manually deleting all the core API files. This is cumbersome and not productive.


text:
Q: Is it better to install dotnet SDK on self-hosted Azure DevOps agent, or add the UseDotNet@2 task in the build pipeline? I have configured a self-hosted Linux agent based on Ubuntu 20.04 running in a Docker container.  It reports in to the agent pool and runs correctly.  I'll be running the agents in AWS Fargate.
My question is whether it is considered a best practice to install the dotnet SDK in my Docker image, which will increase the size of the image considerably, or if it is better to leave it out and require build pipelines to install it via the UseDotNet@2 task, which would cause a delay every time a new agent spins up?
Is there a best practice or general guidance, and can anyone cite documentation?
Thanks!

A: I prefer UseDotNet@2 task. UseDotNet@2 task acquire a specific version of .NET Core from the Internet or the tools cache and add it to the PATH. This task can change the version of .NET Core used in subsequent tasks. Even you install dotnet SDK on the agent machine, you would also need use UseDotNet@2 task to change the version of .NET Core. And if you update the sdk on the machine, it may cause pipeline run broken. Although there may some delay when a new agent spins up, it only cause delay on the first run.


text:
Q: how to deploy and access loadbalancer kubernetes service on localhost/local machine using docker desktop k8s cluster? unable to access the service deployed on local k8s cluster created using docker desktop.
#nginxsvc
#service
apiVersion: v1
kind: Service
metadata:
  name: nginxsvc
  labels:
    app: nginx-app
spec:
  selector:
    app: nginx-app
  type: LoadBalancer
  ports:
  - port: 8080 #service port
    targetPort: 8080 #container port
    protocols: TCP

#Deployment
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: nginx-app
  template:
    metadata:
      labels:
        app: nginx-app
    spec:
      containers:
      - name: nginx-controller
        image: nginx:latest
        ports:
        - containerPort: 8080

NAME                 TYPE           CLUSTER-IP      EXTERNAL-IP   PORT(S)          AGE   SELECTOR
service/kubernetes   ClusterIP      10.96.0.1       <none>        443/TCP          15m   <none>
service/nginxsvc     LoadBalancer   10.98.148.173   localhost     8080:32090/TCP   15m   app=nginx-app

tried accessing using localhost:32090

A: Try on the localhost:8080 You have to use the nginxsvc, port
The one you used 32090 is node port with this you have to use the Node-IP:nodeport to access.


text:
Q: Django - Google Places API - Establishment Trying to implement Google Places API, to look for businesses.
I am trying to break down the result in different sections (name,address,city...) to stick it in a form.
Doing a bit of research, I have actually found the ultimate code to copy. However, I am using Django and I am too much of a newbie in coding, to understand how to alter the code to make it work with the framework. (https://jsfiddle.net/geocodezip/ep5aw171/1/)
Here is the code I have:
js file
function initMap(){
  autocomplete = new google.maps.places.Autocomplete(document.getElementById("input"),{
    componentRestrictions: {'country':['uk']},
    fields: ['name','geometry'],
    types:['establishment']
  });

   autocomplete.addListener('place_changed');
}

html

Google Places API Test

        <input id="input" placeholder="*Name API" style="height: 75px; width:1000px">

This bit works. When I type an address, I get the address of the what I am looking for (see screenshot)

Given that I am planning to use a django form to capture the information, I am assuming the html to look like this:

Google Places API Test

        <input id="input" placeholder="*Name API" style="height: 75px; width:1000px">

  <form id="GoogleAPI" method="POST" action="{% url 'google_api_test'%}">
    {% csrf_token %}

   Address
   {{form.name}}
   Address
   {{form.address}}
   ...
  </form>

Looking at the different answers on the topic, there seems to be lot of code to write,so I am expecting anyone to do this here. But I wondering if someone may know a link to a Django tutorial for Google API for businesses (establishment). Found a few online, but they do not cover establishements and the approach appears to be different.
I understand the next step would be to call is to call autocomplete.getPlace() within a function. But all attempts I made proved to unsuccessful.
Would be grateful if anyone had any pointers!


text:
Q: Objective-C delegate or self is morphing classes I have 2 UIViewControllers(A,B). A is set as the delegate for B and then B is presented. The protocol is set up in B's header:
@protocol BDelegate <NSObject>
- (IBAction)finishOrder:(id)sender;

@end

delegate property is declared:
@property (nonatomic, assign) id<BDelegate> delegate;

A sets B.delegate = self;
Then on a button press B calls:
if (self.delegate) {
        [self.delegate finishOrder:nil];
    }

However, on first run lldb gives me:
-[UITextInteractionAssistant finishOrder:]: unrecognized selector sent to instance

second run:
-[NSInvocation delegate]: unrecognized selector sent to instance

third run:
-[__NSCFDictionary delegate]: unrecognized selector sent to instance

forth run:
-[UITextTapRecognizer finishOrder:]: unrecognized selector sent to instance

So... no code changed, but self changed from A to NSInvocation and __NSCFDictionary and the delegate for B (self of A) changed to UITextInteractionAssistant and UITextTapRecognizer... Never seen anything like it. Any ideas? Thanks!

A: You are over-releasing somewhere. Try turning on Zombies, and use Instruments to track down the over-release.


text:
Q: iPhone Docked Playing Through PC, Buzzing I have an iPhone that I fit into an Apple dock. There is an audio cable from dock into the line in on my sound card. My headphones are plugged into the line out.
I get this really quite buzz that is fairly constant, but changes as the iPhone "does stuff".
It's not so bad when the music is playing. But when it stops I get the buzz, so I can't really use my headphones as "noise cancellation."
It doesn't help to change my volume sliders on the PC.
Any ideas?
EDIT
I've been debugging this issue a bit. It actually doesn't matter if the iPhone, Dock, or Line-In are hooked up at all. So I guess its not an iPhone issue.
I don't think it's a GSM signal issue because it happens if the phone is in the other room as well.
Thanks in advance.

A: Putting the iPhone into Airplane Mode should reduce the buzzing slightly. The problem is with the cellular/Wi-Fi signals causing interference with the audio. Unless the specific accessories you use with your iPhone are labelled as "works with iPhone", they're not guaranteed not to produce the buzzing. (For instance, I have a clock radio with a dock connector, and when I connect it, my iPhone offers to turn on Airplane Mode to reduce audio interference).

A: There may be a second problem besides audio interference from wifi and GSM: a ground loop. This is pretty common with audio gear, and a giveaway is the buzz or hum is about 60 hertz. Once you've heard it, you'll recognize it in the future.

A: The buzz is GSM cell phone interference.
When I first got my iPhone my co-workers speakers in the next room would not stop buzzing.  The solution he got new speakers.
MacLife suggests attaching ferrite beads to your cables to prevent interference. http://www.maclife.com/article/iphone_buzz_kill


text:
Q: What happens if I really don't like one of my settlements and refuse to defend it? I'm really not a fan of Tenpines Bluff.  Those two citizens need to suck it up and learn to deal with raiders themselves if they won't move to one of my more well defended settlements.  Their settlement has no defenses and I refuse to build any, so what happens if they get attacked by raiders and I just stand by and laugh instead of rushing to their aid?

A: As discussed here, if you don't defend your settlements the attackers will potentially kill the settlers present at that settlement (assuming the settlers are themselves unable to repel the attackers) and damage certain properties, for example seems that this  defences (guard towers and turrets) and resource generators (crops, water pumps, generators).

A: You could send both of the settlers to another settlement (assuming the rest aren't maxed in population) and then dismantle/turn-off the radio. Then no new settlers will arrive, and the raiders can do what they like w/out any negative consequences for you what-so-ever.


text:
Q: windows phone 7 Background Agent I have one question related with new Mango future. I'v activate background agent. What heppe when I am reboot device? I should activate agent again or not? Thanks a lot.

A: The agent will still be running after a reboot. It will run for 14 days, so at least every 14:th day you have to refresh the scheduling of your background agent.


text:
Q: LNK2028 Managed C++ DLL calling function in another Managed C++ DLL I'm using VS2010 with a managed C++ DLL calling a function in another managed C++ DLL and I'm getting many LNK2028 link errors that look like this.
1>udpPkt.obj : error LNK2028: unresolved token (0A0000AA) "unsigned short __cdecl ComputeCrc16(void const *,unsigned int)" (?ComputeCrc16@@$$FYAGPBXI@Z) referenced in function "public: short __thiscall CPrivateUdpPkt::ComputeCrc(void)const " (?ComputeCrc@CPrivateUdpPkt@@$$FQBEFXZ)

When I use dumpbin /export on the called DLL I see the unresolved function listed as:
7 6 00001040 ?ComputeCrc16@@YAGPBXI@Z = ?ComputeCrc16@@YAGPBXI@Z (  unsigned short __cdecl ComputeCrc16(void const *,unsigned int))

Comparing the functions prototype listed in the dump to the one listed in the error message the expanded prototype seems to match however the mangled names do not.
err ?ComputeCrc16@@$$FYAGPBXI@Z unsigned short __cdecl ComputeCrc16(void const *,unsigned int)
dump?ComputeCrc16@@YAGPBXI@Z    unsigned short __cdecl ComputeCrc16(void const *,unsigned int)

In the LNK2028 link it mentions problems with _cdecl being called with __clrcall but it says this occurs when calling an exported native function, however it doesn't describe how to resolve the issue.  Besides I'm compiling both the called DLL and the calling DLL with /clr so neither of the calling or the called function should be native to my understanding.
The calling code looks like this
unsigned short __declspec(dllimport) ComputeCrc16(const void * i_pData, size_t i_nBytes);

short CPrivateUdpPkt::ComputeCrc() const
{
    const Byte * pByte = reinterpret_cast<const Byte *>(&m_Crc) + sizeof(m_Crc);
    size_t len = &m_aData[DataLen()] - pByte;
    return ComputeCrc16(pByte, len);
}

The called function looks like this:
unsigned short __declspec(dllexport) ComputeCrc16(const void * i_pData, size_t i_unNumBytes)
{
...
}


text:
Q: adding a callback to a for loop I am trying to get jQuery to remove an element after it as run through a cycle of other functions, but following code block executes the remove() before it has run any of the for loop.
function waves(){
    for(i=0;i<=10;i++){
            wave(x);
    };
    $(x).remove();
}

A: Add an if statement into your loop, that then calls your function.
function waves(){
    for(i=0;i<=10;i++){
            wave(x);
            if (i == 10) {
               callback();
            }
    };
}
function callback() {
    $(x).remove();
}


text:
Q: Switching to CloudObject`Private` I shut Mathematica done, then restart it. The image shows all that I do. I have done nothing else. Can anyone explain what is happening to me?

The complete code is:
x[t_] := t^2 + 5;
y[t_] := t^3 + 5;

Manipulate[Plot[fcn[t], {t, -5, 5}],
{{fcn, x, "Graph Type"}, {x -> "Square", y -> "Cubic"}}]

P.S. This is also after contacting Wolfram support who suggested that I uninstall Mathematica, download again, and reinstall.

A: The spurious context change is a bug and can be avoided by turning the Suggestions Bar off.
The predictive interface tries a number of evaluations behind the scenes, each wrapped in TimeConstrained so they don't take too long. Depending on the input, some of these predictions may end up using (and autoloading) other functionality. The context path corruption can happen when this package loading process gets interrupted in the middle.


text:
Q: Getting Unprompted Input in NodeJS I'm trying to get unprompted input from the user in a NodeJS server. The reason is that I want to be able to send strings that can be interpreted as commands while a server is running such as commands to flush the cache.
Now, originally, I used readline as follows:
import * as ReadLine from 'readline';

export default function InitTerminal() {
    const terminal = ReadLine.createInterface({
        input: process.stdin,
        terminal: false
    });

    terminal.on('line', (input) => {
        console.log(input);
        switch(input.toString()) {
            default:
                console.log('Unknown Command');
                break;
        }
    });
}

The issue was that after most inputs, I would get:
rl.on line * input *

Where * input * refers to the string representation of the buffer input from process.stdin. The weird thing is, the on line triggers only occassionaly and typically I will get that line and my listener doesn't trigger. The same thing happens when I don't use ReadLine and just add a listener to process.stdin. Something is triggering node to print out the output above. I'm using node 11.12.0 and ts-node-dev for typescript in development mode.
So what I'm asking is how can I use node to get unprompted input as commands? Either by modifying my original code or any way I haven't thought of.
Kind thanks.

A: The problem was that ts-node-dev plays with the stdin. That means it's hard to get the stdin while using it. What I hade to do was create an npm script called build:dev which compiled my typescript and then ran it. Then I could use the process.stdin without concern.
A way to possible watch changes while doing this is to use nodemon instead of ts-node-dev and just compile the typescript when needed


text:
Q: Как проверить текстовый редактор на строку при типе StringVar()? Есть переменная email = StringVar() которая передает введенный логин, хочу проверить через open file имеется ли введенный логин уже в текстовом редакторе Users.txt,но компилятор пишет, что не может прочитать при типе данных StringVar(), вопрос в том ,что как можно преобразовать переменную email ,чтобы open file смог прочитать ее .. И естественно если там имеется строка ,который ввел пользователь в Entry ,то выдастся предупреждение
email = tk.StringVar()

email_entry = ttk.Entry(signin, textvariable=email)

file = open('C://Users.txt', 'r')
datafile = file.readlines()
for line in datafile:
    if email.get() in line:
      return True

Ошибка компилятора:
datafile = file.readlines()
io.UnsupportedOperation: not readable


text:
Q: Polymer: Why do I need to use npm and bower? I would like to develop a web application with Spring Boot, Spring Web MVC and Thymeleaf. I recently stumbled upon Web Components and Polymer which might be a good addition to Thymeleaf in order to use cool components. As I'm a frontend noob, I ask myself why I need this npm and bower stuff in order to use Polymer.
If I got it right, Web Components and Polymer are just js libraries. Why can't I just include them (maybe by using a cdn) in my html page? I like Thymeleaf as it's possible to view the pages without the need to have a webserver. If I could just include polymer as js library that would still work. I am quite sure that I misunderstand some major concepts, but I can't grab it. Can anyone help me?
Thanks!


text:
Q: Can I pass variables to eval? I am trying to pass a variable to a dynamically declared method like:
eval(def test(name)
 puts name
end
test 'joe')

but it does not work.
Is there a way to do this?

A: If you want to declare a method dynamically then a better way to do that is to use define_method instead of eval, like so
define_method(:test) do |name|
  name
end

test 'joe'
#=> joe

Don't use eval unless it is absolutely necessary and you are 120% sure that it is safe. Even if you are 120% sure that it is safe, still try to look for other options and if you find one then use that instead of eval.

A: eval expects a string. The following should work fine:
eval "def test(name)
  puts name
end
test 'joe'"

A: I am a little confused on what you are trying to do.  If you are trying to define a method with eval that can take a parameter here is the example:
eval "def test(name)
  puts name
end"

test 'joe'

If you want to use eval to define a method that is more dynamic and uses a variable, since as Brian pointed out eval takes a string you would do something like this:
test_name = 'joe'
eval "def test
  puts '#{test_name}'
end"

test


text:
Q: When to start using OSPF We have 4 offices in different countries. They are all connected via VPN to each other (i.e. at least one VPN tunnel from each office to all other three). Each office has between 1 and 4 separate subnets, and each office has an OpenVPN server. Two of the offices have a DMZ (because they host public services) and each office has direct routing to the Internet. Plus there is one "virtual" office, which is physically at the same place as one of the others, but logically completely separate and connected via a VPN tunnel. In total there are 16 subnets and at the moment this is all done with static routes, complete with failover routes. There are 12 main routers involved.
It all works fine, but I am beginning to wonder whether I should look into using OSPF. Everytime I need to add a subnet, I have quite a job on hand to make sure that all the routing tables are updated correctly.
So I was wondering whether anybody could offer advice on when to start using OSPF for this?
EDIT:
If anybody can provide any pointers to a good tutorial or design guide for OSPF areas, I would be greatful.

A: My recommendation would be "several sites ago".
Past 3 or 4 routers, statically routing everything feels like more of a chore than getting a route distribution protocol going.

A: My 2 cents: I'd setup RIP for a small network like that. Heck I'd use it even if there were only two routers. OSPF is definitely more robust and fully capable of what you're doing, but also more complicated.


text:
Q: Write a function that can ignore specific filter parameters in R I want to write a function with several inputs.
Each input adjusts a particular filter parameter in a dplyr pipeline.
I am struggling with how to turn on/off the grep parameter,
that is, I want to have the ability to completely ignore the grep line
My dataframe (df), has three variables (sent, repeat, cases)
Here is my function:
my_filter <- function(df, a, b, c){

df <<- df %>%
          filter(sent != a,
                repeat != b,
                 !grepl("_v", cases))
}

I would like the "c" argument to allow me to ignore the last line in the pipeline !grepl("_v", cases)
how do I set "c" such that it controls the presence/absence of that line?

A: I'd suggest something like this:
my_filter = function(df, a, b, c = TRUE) {
    result = df %>% filter(
      sent != a,
      repeat_col != b
    )
    if(c) result = result %>% filter(!grepl("_v", cases, fixed = TRUE))
    return(result)
}

This handles the conditional as you asked. If you set c to FALSE, the last condition won't be applied. (In other cases, you can also test for if(missing(c)) to check if the c parameter is supplied by the user or not.)
I also don't use global assignment, because you should basically never use it, returning a result lets the result name be chose by the user, instead of picking it for them and potentially overwriting something they already had.
The fixed = TRUE is just for a bit of efficiency since your pattern is an exact match, not a regular expression.

A: Here's another option :
library(dplyr)
my_filter <- function(df, a = FALSE, b = FALSE, c = TRUE){
  df %>%
    filter(Sepal.Width != a,
           Sepal.Length != b,
           c | !grepl("v", Species))
}

dim(iris %>% my_filter)
#> [1] 150   5

dim(iris %>% my_filter(c=FALSE))
#> [1] 50  5


text:
Q: Does extend imply a requires statement for this class? Do I need to require a class if I extend from it or does the classmanger handle that for me?

A: The classmanager will take care of this. You will not need to require this class.


text:
Q: Why does chrome dev tools console show a link for Post 500 error in one website but not another? In test1 web site I can get debugging information with a Post link

In test2 web site, running the same api, I cannot.
I just see

Failed to load resource: the server responded with a status of 500()

A: In web.config
<httpErrors errorMode="DetailedLocalOnly" existingResponse="Auto" />

The docs are here


text:
Q: Stock Price Neural Network Optimization I have seen quite a few people create Neural Networks to predict stock prices, so I decided to try my hand at it. I am using an LSTM network, and have had decent results. But I am worried about overfitting. I have tried to limit this as much as I know how, but I am still not sure if it is an issue in my current network.
'''

Model_Input = Input(shape=(5, 1), name='Model_Input')
x = LSTM(50, name='Model_0')(Model_Input)
x = Dropout(0.5, name='Model_dropout_0')(x)
x = Dense(64, name='Dense_0')(x)
x = Activation('sigmoid', name='Sigmoid_0')(x)
x = Dense(1, name='Dense_1')(x)
x = Dense(1, kernel_initializer='lecun_normal', activation='linear')(x)
Model_Output = Activation('linear', name='Linear_output')(x)

model = Model(inputs=Model_Input, outputs=Model_Output)
adam = optimizers.Adam(lr=0.0005)
model.compile(optimizer=adam, loss='mse')
# Gives the input data a new shape of (1259, 5, 1)
Normalized_Input_Data = np.reshape(Normalized_Input_Data, Normalized_Input_Data.shape + (1,))
# Extract just the closing price from the data (open, high, low, close, and volume are contained)
Normalized_Closing_Price = Normalized_Input_Data[:,3]

# Train neural network
history = model.fit(x=Normalized_Input_Data, y=Normalized_Closing_Price, batch_size=10, epochs=500,
shuffle=True, validation_split=0.25)

'''

The input data is a little over the past 5 years worth of stock data. I only get the data daily. At the time of writing this, I think the network sees 1273 days worth of data instead of 1259. I am using 25% of the data for validation. I figured this would be enough, but it may not be. The below images are for the Nvidia stock.

So over the first 5-6 epochs the loss changes drastically, after it seems to level out and stay pretty consistent. I am not sure if the loss is even enough to worry about, or if there is a way to make it better. Also any changes or suggestions for the network architecture are welcomed.
EDITED
So after changing the training and validation data, changed the model architecture to keep it from overfitting (as much as I could anyway).
'''
    # Concluded that the first dropout layer(s) needed to be more harsh than
    # the later ones
    Model_Input = Input(shape=(5, 1), name='Model_Input')
    x = LSTM(64, name='Model_0')(Model_Input)
    x = Dropout(0.5, name='Model_dropout_0')(x)
    x = Dense(64, name='Dense_0')(x)
    x = Dropout(0.1, name='Model_dropout_1')(x)
    x = Activation('sigmoid', name='Sigmoid_0')(x)
    x = Dense(1, name='Dense_1')(x)
    Model_Output = Activation('linear', name='Linear_output')(x)
    model = Model(inputs=Model_Input, outputs=Model_Output)
    adam = optimizers.Adam(lr=0.0005)
    model.compile(optimizer=adam, loss='mse')
    # Implemented early stopping to keep the epochs from creating overfitting
    Early_Stopping = EarlyStopping(monitor='loss', mode='min', patience=50, verbose=1)
    history = model.fit(x=History_Input_Data, y=History_Closing_Price, batch_size=128, epochs=750, shuffle=False, validation_data=(Validation_Input_Data, Validation_Closing_Price), callbacks=[Early_Stopping])
'''

For those who might need it, I split the input data up before feeding it to the model.
'''
    # Split the dataset up into training and validation datasets
    # Use the first 75% of data to train on (This is the oldest data)
    # Use the last 25% of data to validate on (This is the most current data)
    Length_Of_Data = len(Normalized_Input_Data)
    Validation_Length = int(Length_Of_Data * 0.25)
    History_Length = (Length_Of_Data - Validation_Length)

    # 956 days worth of data for network to train on
    History_Data = Normalized_Input_Data[:History_Length]

    # 318 days worth of data (most current dates) to be validated on
    Validation_Data = Normalized_Input_Data[History_Length:]
'''

Updated graphs for the prices and loss (For the validation dataset).

After about 6 epochs, the model loss seems to even out for both training loss and validation loss. However, this is just for Nvidia's stock. Different stocks give different results. The early stopping was an attempt to try and keep the accuracy similar between multiple stocks.


text:
Q: Recreating list of objects efficiently I am trying to convert a list of objects which has been queried using SQLAlchemy.
The issue that I am having is that the process is taking around 18-20 seconds to loop, process and send the data to the frontdnd. The data is of around 5 million rows which is way too slow to put into production.
Here is an example of what I using.
test = [
   {"id": 5, "date":"2022-01-01 00:00:00"},
   {"id": 5, "date": "2022-01-01 00:00:00"},
   {"id": 5, "date": "2022-01-01 00:00:00"},
   {"id": 5, "date": "2022-01-01 00:00:00"},
]

test_dict = {}

for i in test:
    if i["id"] not in test_dict:
        test_dict[i["id"]] = []
    test_dict[i["id"]].append(i["date"].isoformat)

Expected output should be e.g
[
   {5: [date, date, date, date, date]},
   {6: [date]}
]

I totally understand this is not working code and I am not looking to fix it. I just wrote this on the fly but my main focus is what to do with the for loop to speed the process up.
Thank you everyone for your help.
Thank you everyone for your answers so far.
Providing more info, the data needs to be sent to the frontend which is then rendered on a graph. This data is updated around every minute or so and can also be requested between 2 time ranges. These time ranges are always a minimum of 35 days so the rows returned are always a minimum of 5 million or so. 20 seconds for a graph to load for the end user I would say is too slow. The for loop is the cause of this bottleneck but would be nice to get the for loop down to say 5 seconds at least.
Thank you
Extra info:
Processing database side is unfortunately not an option for this. The data must be converted to the correct format inside the API. For example, concat the data into the correct format or converting to JSON during query isn't an option.

A: If I understood currently you can use pandas dataframes
test = [
   {"id": 5, "date":"2022-01-01 00:00:00"},
   {"id": 5, "date": "2022-02-01 00:00:00"},
   {"id": 5, "date": "2022-03-01 00:00:00"},
   {"id": 5, "date": "2022-04-01 00:00:00"},
   {"id": 6, "date": "2022-05-01 00:00:00"},
]
import pandas as pd

df = pd.DataFrame.from_dict(test)
res = df.groupby("id").agg(list)
print(res)

Output :
                                                                                date
id
5   [2022-01-01 00:00:00, 2022-02-01 00:00:00, 2022-03-01 00:00:00, 2022-04-01 00:00:00]
6                                                                  [2022-05-01 00:00:00]

And if you want it to be as dict you can use res.to_dict()

A: You should probably not send 5 millions objects to the frontend.
Usually we use pagination, filters, and sort elements.
Then if you are really willing to do so, the fastest way would probably be to cache your data, for instance by creating and maintaining a json file on your server that the clients would download.


text:
Q: How to display only specific page via router-view? can only a specific page be viewed via router-view?
App.vue

    <router-view name="login"></router-view>

      <router-view name="register"></router-view>

      <router-view name="home"></router-view>

router.js
export default new Router({
  mode: "history",
  routes: [
    {
      path: "/login",
      name: "login",
      component: () =>
        import(/* webpackChunkName: "Login" */ "./pages/login.vue")
    },
    {
      path: "/register",
      name: "register",
      component: () =>
        import(/* webpackChunkName: "Register" */ "./pages/register.vue")
    },
    {
      path: "/home",
      name: "home",
      component: () =>
        import(/* webpackChunkName: "Home" */ "./pages/home.vue")
    }
  ]
});

I need the router-view to enter only content from one particular page, not all of them. The name attribute does not work.
Is it possible to do this?

A: It's not entirely clear what you are trying to do, but normally, if you have only a single view on the page, the app structure would look more like this:

      <router-view/>

The per view customization would be handled in the individual components themselves, or by some shared outer component if needed.
If you are intending to use multiple views on same page, then you might used named views. But that is not what your example seems to be trying to do.


text:
Q: Swift: how to set the iphone volume programmatically I am trying to create an alarm app and I have noticed that apps like Sleep Cycle will set your volume to max right before the alarm goes off, even if you had the volume at very low.
I have tried using AVAudioPlayer and all I have seen with MPVolumeView is that the user must do it.
Is there any way I can turn it up without the user having to do it?
Thank you for your help.
If I could please get the code in swift

A: You just need to import MediaPlayer. You can do as follow:
import MediaPlayer

And to set the volume to maximum
(MPVolumeView().subviews.filter{NSStringFromClass($0.classForCoder) == "MPVolumeSlider"}.first as? UISlider)?.setValue(1, animated: false)


text: Q: Riemannian submersions and Lagrangian submanifolds Let G be a compact Lie subgroup of $SU(n+1)$, and let $L=G\cdot p$ be a Lagrangian submanifold in $\mathbb{CP}^n$.  If $\Omega$ denotes the $G^{\mathbb C}$ orbit through $p$, I know that $L$ is a deformation retract of $\Omega$ (since the gradient flow of the norm squared of the moment map defines a deformation retract of the appropriate piece of the manifold onto the zero level). Let $\pi$ denote the retraction from $\Omega$ to $L$. Is it already known when $\pi$ is a Riemannian submersion?


text:
Q: Optional Maven properties in profiles I have "web service test" project that I use for testing our web services.  I use maven profiles to generate the client for each web service like so:
<profile>
    <!-- to run: mvn clean cxf-codegen:wsdl2java -e -Dservice=single-sign-on -->
    <id>single-sign-on</id>
    <activation>
        <property>
            <name>service</name>
            <value>single-sign-on</value>
        </property>
    </activation>
    <properties>
        <ws.wsdl>http://example.com:8080/SingleSignOnService?wsdl</ws.wsdl>
        <ws.dir>src/generated/single-sign-on</ws.dir>
        <ws.package>com.example.single_sign_on</ws.package>
    </properties>
</profile>

I use the cxf-codegen-plugin to actually generate the client:
<plugin>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-codegen-plugin</artifactId>
    <version>${cxf.version}</version>
    <configuration>
        <sourceRoot>${ws.dir}</sourceRoot>
        <wsdlOptions>
            <wsdlOption>
                <wsdl>${ws.wsdl}</wsdl>
                <extraargs>
                    <extraarg>-impl</extraarg>
                    <extraarg>-verbose</extraarg>
                    <extraarg>-frontend</extraarg>
                    <extraarg>jaxws21</extraarg>
                    <extraarg>-xjc-npa</extraarg>
                    <extraarg>-p</extraarg>
                    <extraarg>${ws.package}</extraarg>
                </extraargs>
            </wsdlOption>
        </wsdlOptions>
    </configuration>
    <executions>
        <execution>
            <goals>
                <goal>wsdl2java</goal>
            </goals>
        </execution>
    </executions>
    <dependencies>
        <dependency>
            <groupId>xerces</groupId>
            <artifactId>xercesImpl</artifactId>
            <version>2.8.1</version>
        </dependency>
    </dependencies>
    <inherited>true</inherited>
</plugin>

The problem is that I need to specify the package for a few of the web services so their objects don't conflict, but for most of the web services I don't need to.  So basically what I am trying to do is somehow optionally include the
<extraarg>-p</extraarg>
<extraarg>${ws.package}</extraarg>

part based on whether the profile has the <ws.package> property defined or not.  Is this possible?

A: I'm not sure that this can be done out of the box with maven, as it only merges the first level of of the <configuration> element, with any other configuration that you might have in a profile (and thus replacing the whole <wsdlOptions> element).
One solution, but only to make if the current state causes you enough pain, is to write your own version cxf-codegen-plugin where you can pass an extra <myextraargs> configuration at the top level of the <config>. For example
<profile>
    <id>single-sign-on</id>
    <activation>
        <property>
            <name>service</name>
            <value>single-sign-on</value>
        </property>
    </activation>
    <properties>
        <!-- ... -->
        <!-- extra args for your plugin -->
        <my.extra.args>-p ${ws.package}</my.extra.args>
    </properties>
</profile>

-
<!-- generic test configuration>
<plugin>
    <groupId>your.group.id</groupId>
    <artifactId>cxf-codegen-plugin</artifactId>
    <version>${cxf.version}</version>
    <configuration>
        <sourceRoot>${ws.dir}</sourceRoot>
        <myextraargs>${my.extra.args}</myextraargs>
        <wsdlOptions>
            <wsdlOption>
                <wsdl>${ws.wsdl}</wsdl>
                <extraargs>
                    <extraarg>...</extraarg>
                </extraargs>
            </wsdlOption>
        </wsdlOptions>
    </configuration>
    <!-- ... -->
</plugin>

Then your plugin would be responsible for merging the extra args array that the real cfx plugin requires.
edit
After writing the answer, I wonder if the CFX plugin complains if you pass empty <extraarg> elements. If it's ok, then you can define the variables in a profile and some profiles will have an empty value, for example
<!-- profile 1 -->
    <properties>
        <!-- ... -->
        <cfx.extra.property.1>-p</cfx.extra.property.1>
        <cfx.extra.property.2>${ws.package}</cfx.extra.property.2>
    </properties>
<!-- profile 2 -->
    <properties>
        <!-- ... -->
        <cfx.extra.property.1></cfx.extra.property.1>
        <cfx.extra.property.2></cfx.extra.property.2>
    </properties>
<!-- ... -->
                <extraargs>
                    <extraarg>...</extraarg>
                    <extraarg>${cfx.extra.property.1}</extraarg>
                    <extraarg>${cfx.extra.property.2}</extraarg>
                </extraargs>


text:
Q: Prone firing mechanic? So this method has been annoying the crap out of me for the past few weeks. You simply walk around and encounter an enemy. You start firing at them and they quickly go prone, and kill you in a matter of milliseconds. Is there a mechanic to this; why does this work so well? The game I'm pointing at is Black Ops 2, but I noticed this doesn't work in, for example, Battlefield.
What is the actual mechanic of drop shooting in black ops 2? So accuracy after x seconds, accuracy before. A nice answer would be an actual comparison featuring 2 guys both standing, then one start drop shooting and one simply starts shooting. Then a overview of damage dealt and overal accuracy.

A: What you are referring to is sometimes called "drop shooting" or "dolphin diving" (the later one has some forward motion).
People do this because:
1) Shooters typically work like this - you go into crouching or prone position and your aiming reticule gets smaller, therefore you can shoot more accurate.
2) You yourself offer a smaller target. While true that you expose your head, you are still very small and hard to hit.
3) Quickly dive into cover.
Some games try to remedy this "phenomenon" by applying some penalties, like not being able to shoot while the "going prone" animation rolls (Battlefield 3), jumping very dramatically without the ability to shoot (Black Ops, other ones might as well, but don't know), or simply don't support prone (Battlefield Bad Company 2).
EDIT: Reading your comment - I don't know if someone has actually made something like that, but here are some youtube videos. Might contain something satisfying for you


text:
Q: Multiple Keys in KeyBinding? I want to setup hotkeys in my Wpf application.
Using KeyBindings works in the simple case, for example: Ctrl+B, Ctrl+A, etc
<KeyBinding Gesture="Ctrl+B" Command="{Binding Source={StaticResource localCusomCommands}, Path=AddTTRowCommand}" ></KeyBinding>

<KeyBinding Modifiers="Control" Key="B" Command="{Binding Source={StaticResource localCusomCommands}, Path=AddTTRowCommand}" ></KeyBinding>

But if I need hotkeys with multiple keys Ctrl+P+B, Ctrl+A+B, etc
<KeyBinding Modifiers="Control" Key="P,B" Command="{Binding Source={StaticResource localCusomCommands}, Path=AddTTRowCommand}" ></KeyBinding>

Don't work.
<KeyBinding Gesture="Ctrl+B+A" Command="{Binding Source={StaticResource localCusomCommands}, Path=AddTTRowCommand}" ></KeyBinding>

Don't compile. Error   15  Unrecognized ModifierKeys 'B'.
How to achieve this?

A: As i told, there is implementation for overriding the KeyBinding and Gestures for multiple keys. refer the below link. He has overriden the implemetation of InputGesture to achieve this multikeybinding.
http://kent-boogaart.com/blog/multikeygesture


text:
Q: Install XCode 6 on OSX 10.8.5 I have Xcode 4.6 and Xcode 5.1.1 installed on my mac with OS X Mountain Lion (10.8.5)
Now I want to install Xcode 6 and keep Xcode 4.6 and Xcode 5.1.1 installed.
Is this a good idea or would the old Xcode 4.6 and Xcode 5.1.1 interfere with the new version Xcode 6?

A: From the official web site:

Xcode 6 requires a Mac running OS X version 10.9.4 or later or 10.10.

A: Install XCode 6 on OSX 10.8.5 not possible.
For manage all xcode installation, You can install all xcode version in your mac, in application folder rename xcode make retain all xcode version without replace it, but xcode comes with compablility of mac os x version so if you want to install xcode 6 you need to update of mac version 10.9.4 or later. Hope so You can understand.


text:
Q: Blazor app puzzling compiler error message on a new page I have a simple Blazor page but I'm getting some strange error messages.  I cleaned the solution and rebuild the project but the same error pops up.  This is all started when I copied an existing razor page, pasted and renamed it.  So I deleted the copy and did an Add New but still getting four error messages.  One of them is complaining about the @page "/register" which I have no idea why.  Any ideas?  Thanks!

A: The last bind-Value is wrong. You can't bind to .ToString().
bind-* enables two way binding, therefore the bound item needs to be "writable" like a property or a field.


text:
Q: SocketTimeoutException : null while opening New Spring Starter Project SocketTimeoutException : null while opening New Spring Starter Project

JAVA_HOME=C:\Program Files (x86)\Java\jdk1.7.0_40
Path=%JAVA_HOME%\bin;C:\..

A: You have to change the network setting in the STS.
Select Window Tab -> Preferences -> General -> Network Connection and change the setting.

Set Active Provider to manual then edit the host and port details in proxy entries. Apply the setting and click ok.
This worked for me. Hope it works for you

A: You have to change the network setting in the STS.
Select Window Tab -> Preferences -> General -> Network Connection and change the setting.
Set Active Provider to DIRECT

A: Select Window Tab -> Preferences -> General -> Network Connection and change the setting.
Set Active Provider to DIRECT

A: Try to start apache tomcat, after starting tomcat your issue should  be resolve.


text: Q: Large File Processing in WSO2 ESB with headers and trailer I have a big file (say 100K records) with header and trailer. Trailer contains information regarding number of records in this file. is there any way for WSO2 ESB to load this entire file for processing (say reading each row and perform some validation and than sending validated data to external end point) and validate number of records is matching against data present in trailer ?


text:
Q: QueryDSL not generating entities for MySql tables I am trying to use QueryDSL with MySql. To begin with, I'm trying to get Entity classes generated for the tables in my database.
Here is my POM:
    <plugin>
    <groupId>com.querydsl</groupId>
    <artifactId>querydsl-maven-plugin</artifactId>
    <version>4.0.3</version>
    <executions>
      <execution>
        <goals>
          <goal>test-export</goal>
        </goals>
      </execution>
    </executions>
    <configuration>
      <jdbcDriver>${jdbc.driver}</jdbcDriver>
        <jdbcUrl>${jdbc.url}</jdbcUrl>
        <jdbcUser>${jdbc.user}</jdbcUser>
        <jdbcPassword>${jdbc.password}</jdbcPassword>
        <tableNamePattern>.*</tableNamePattern>
      <packageName>app.domain</packageName>
      <targetFolder>${project.basedir}/src/main/java</targetFolder>
      <sourceFolder>${project.basedir}/src/main/java</sourceFolder>
    </configuration>
    <dependencies>
      <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>6.0.3</version>
      </dependency>
    </dependencies>
  </plugin>

Properties:
        <properties>
            <jdbc.user>root</jdbc.user>
            <jdbc.password>root</jdbc.password>
            <jdbc.url>jdbc:mysql://localhost:3306/test</jdbc.url>
            <jdbc.driver>com.mysql.cj.jdbc.Driver</jdbc.driver>
            <querydsl.version>4.0.3</querydsl.version>
        </properties>

However, this is not working. There are no exceptions.
QueryDSL doc: https://github.com/querydsl/querydsl/tree/master/querydsl-sql
Any ideas on what I might be missing here?

A: I was also facing this issue.
This is appearing due to mysql 6.0.2+. Just appended nullNamePatternMatchesAll=true to mysql connection string it helped.
In earlier version default value was set to true. In version 6.0.2+ it is made as false by default.


text:
Q: Alternative to include file or require_once() in php I am new to PHP so don't know if there is any alternative to require_once(). My issue is: currently I am including database configuration file on almost each and every file which needs to connect with database using require_once(). I don't want to include my configuration file on each and every file because it may cause some security risk. Any kind of help would be apriciated. Thanks in advance.

A: You may use the php.ini setting auto_prepend_file to automatically include files when the php process is started.


text:
Q: Are there any limitations regarding the age of a linux distribution which can be used to create a docker base-image? Im wondering if its possible to use very old Linux Distribution like Debian GNU/Linux 3.1 (Sarge) and create a base-image of it to run legacy code not working under "younger" distros.
Only Thing i found about it was somebody successfully using Ubuntu Feisty:  Run old Linux release in a Docker container?
Are there any known limitations?

A: Your host needs to have a minimal version of the Linux kernel, and that version is 3.10
See
Docker minimum kernel version 3.8.13 or 3.10
extract from the previous link
There's also a shell-script to check if your system has the required dependencies in place and to check which features are available;
https://github.com/docker/docker/blob/master/contrib/check-config.sh
So you can use this to check if you will be able to use docker on this host.
From
https://wiki.debian.org/DebianSarge?action=show&redirect=Sarge
I see
kernel : linux 2.4.27 and 2.6.8
So it may not work


text:
Q: Separate HTTP connection results (PHP echo) In my Android application I make a HTTP POST connection:
serverresponse = CustomHttpClient.executeHttpPost(url, postParameters);

All working fine. The url is pointing to a php page on my server. It echos an array of image urls in JSON format like this:
[".\/pictures\/q\/thumbnails\/28052011172.jpg",".\/pictures\/q\/thumbnails\/picca1.jpg",".\/pictures\/q\/thumbnails\/lockscreen_006.jpg"]
What I want to do is also echo the size of directory. That works fine too, but that puts it right after the JSON array, like so:
echo (json_encode($files));
echo (filesize_r($path));

[".\/pictures\/q\/thumbnails\/28052011172.jpg",".\/pictures\/q\/thumbnails\/picca1.jpg",".\/pictures\/q\/thumbnails\/lockscreen_006.jpg"]4223566
4223566 is the number of bytes. In my application I want to split these two values into different strings so I can use them.
In short, I want to separate these two php echos. I don't want to make two separate HTTP connections for both of them.
Sorry if my question isn't clear enough, I sometimes have a hard time explaining stuff in English.

A: Use params in you php so you can select wich action to do

A: Could you not just make one json object which contains the two values your require?
e.g.
$response = array(
    'pictures'=>$files,
    'filesize'=> filesize_r($path)
);
echo json_encode($response);

A: not sure if I understand your question fully, but:
$json['files'] = $files;
$json['size'] = filesize_r($path);

echo json_encode($json);


text:
Q: What is the proper Table publication format for an IEEE Xplore publication? I am finishing to write a scientific paper for an IEEE Xplore (I am not sure if IEEE Xplore and IEEE are the same organization - Publisher by the way will be IEEE) publication and wanted to ask a clarification about where the caption should properly and officially be positioned?
I have a Table so far with the caption on top as below:

Or should the caption should be on the bottom of the table as below? :

Which brings me to a couple more follow-up questions such as:

*

*Does that matter if the table is in half column or if it stretches across the two columns occupying the whole space? Is there any implication with the caption?

*What if I take a picture of a table, say on excel, and put the image of the table in the paper? Does that still count as a Table or as an image?

*Example: I put a caption on the wrong position of the table, say on the bottom like the example above, and the paper is published.
I after realize about the caption erroneous location. Is the paper subjected to a peer review again? Also, does that imply that there should be a review of the paper to properly position the caption in the correct location before being re-published?
Are there any official guidelines anyone can point me to answer those specific questions?
Thank you all for clarifying some of the doubts I have, and I am trying to be proactive and  make sure that everything is in the proper position since the beginning.