text:
Q: select into outfile not working with hibernate I am trying to execute de following code in Hibernate to create a .csv file from a mySQL database. :
String sql =
"SELECT * INTO OUTFILE 'table.csv' FIELDS TERMINATED BY ','" +
" OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\\n' " +
"FROM match INNER JOIN totala ON match_code= match";

The .csv file is created correctly but then I get the following error:
Exception monitoring the input folder org.hibernate.exception.GenericJDBCException: could not execute query
    at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:140)
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:128)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.loader.Loader.doList(Loader.java:2452)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2192)
    at org.hibernate.loader.Loader.list(Loader.java:2187)
    at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:316)
    at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1832)
    at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165)
    at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:179)
    at com.salebuild.dao.hibernate.CorporateTitleDAOImpl.dumpTitleCompanyCSV(CorporateTitleDAOImpl.java:49)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:198)
    at $Proxy128.dumpTitleCompanyCSV(Unknown Source)
    at com.salebuild.service.CorporateTitleServiceImpl.dumpTitleCompanyCSV(CorporateTitleServiceImpl.java:53)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
    at $Proxy159.dumpTitleCompanyCSV(Unknown Source)
    at com.salebuild.service.collector.ContactScraperMonitorInputFolder.addNewFile(ContactScraperMonitorInputFolder.java:61)
    at com.salebuild.service.collector.ContactScraperMonitorInputFolder.run(ContactScraperMonitorInputFolder.java:37)
    at java.lang.Thread.run(Thread.java:619)
Caused by: java.sql.SQLException: ResultSet is from UPDATE. No Data.
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
    at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:7021)
    at com.mchange.v2.c3p0.impl.NewProxyResultSet.next(NewProxyResultSet.java:2859)
    at org.hibernate.loader.Loader.doQuery(Loader.java:741)
    at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:270)
    at org.hibernate.loader.Loader.doList(Loader.java:2449)
    ... 29 more

Some googling suggested that it may be because query is not returning any result so I get "java.sql.SQLException: ResultSet is from UPDATE. No Data". But how do I get over this exception.I dont want my code to break.
I am running the query like:
public void dumpTitleCompanyCSV(String titleId,String titleName, String dumpFolder) {
        Session session = getSession();
        String hql = "SELECT "+titleId+" ,id, \""+titleName+"\", name " +
                    "FROM company INTO OUTFILE 'd:/contact/input/file.csv' " +
                    "FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\\n'";
        logger.debug("jeets The query is \n "+hql);
        Query query  = session.createSQLQuery(hql);
         query.list();
    }

A: Use executeUpdate() method to run queries that doesn't return any results.
In your case since the results will be dumped to a external file there will be no result set. Note that this is different than a query that may return empty results due to the criteria not being met.
EDIT :
Since that also seem to be failing I think you may need to try using pure JDBC.
Do something like below
session.doWork(new Work() {
    @Override
    public void execute(Connection con) throws SQLException {
        //run your query natively here
    }
});


text:
Q: Is $P( (A\cap B)\cap C)$ equal to $P(A\cap C) P(B\cap C)$? Is $P( (A\cap B)\cap C)$ equal to $P(A\cap C) P(B\cap C)$? In a proof I doubtfully used this equation. Is it correct? But I am not sure about it. Can somebody confirm its validity? If possible, can somebody prove it please?

A: The answer is no. The statements like this are rarely true. Say, set $C = \Omega$ and let $A$, $B$ have positive probabilities with $A\cap B = \varnothing$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: iPhone-Android texting compatibility Text messages from my iPhone to my friend's Android phone do not stay in the 160 characters as sent. Sometimes they appear as two or three separate texts when they are received.

A: This is normal functionality and has been present on the original iPhone OS on the very first iPhone back in 2007.
What you are seeing is that the iPhone is allowing you to send messages that are longer than the SMS limit, and when you do that it automatically splits the message into the number of SMS messages required to send your message.
If your recipient has an iPhone, they just see the original un-split message as the iPhone puts it back together for the recipient.  Other devices, such as your friend's Android device, just show the discrete SMS messages in the order they were sent.

A: The problem is someone refusing to support Concatenated SMS, as @Andrew Ferrier noted. in a comment on Stu's answer.  The spec makes for very dense, acronym-rich reading.
However, there's a section that's relatively readable, which reads:

3.8.3       Text       concatenation
  If the concatenation mechanism described in subclause 9.2.3.24.1 is not supported by the transmitting or receiving
  entity, the following textual concatenation mechanism may be used. The first message is ended with a + sign, and each
  subsequent message start and end with + signs until the final message which starts with a + sign but does not end with a
  + sign.

 <message1>+
 +<message2>+
 +<message3>

Any header fields placed on the front of an MO or MT message are not added to the second and subsequent messages.
  This provides a simple mechanism which is completely backward compatible.  There is no indication of the number of
  messages and should a message be lost by the system or arrive out of sequence then the original message cannot be
  reconstructed.  Therefore, wherever possible the concatenation mechanism specified in sub clause 9.2.3.24.1 should be
  used instead.

Since the '+' characters would be apparent if the receiver didn't support the simple coding but the sender did, it's clear that this simple mechanism is not supported by Apple.
I gave up/lost interest in deciphering the spec before figuring out who supports or doesn't support 9.2.3.24.1 but it doesn't matter too much to me; the blame falls on Apple for not supporting the simple fallback scheme.


text:
Q: Laravel Queue with Supervisor not working with Multiple Websites When adding a single website running a Laravel Queue to Supervisor, delayed jobs are processed as they should.
When I add another website to Supervisor, delayed jobs are not processed for any of the websites/queues.
I have tried rereading, reloading, and restarting the service.  The supervisord.log shows all the processes running, but jobs are not being triggered.
If I stop all but 1 worker, the queue works.
Laravel 5.7
Supervisord 3.3.1
redis-cli 3.2.6
Debian/Nginx
sudo nano /etc/supervisor/conf.d/website-a-worker.conf

[program:website-a-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/website.a/artisan queue:work redis --sleep=3 --tries=3
autostart=true
autorestart=true
#user=laravel
numprocs=8
autostart=true
autorestart=true
stdout_logfile=/var/www/website.a/storage/logs/worker.log
stderr_logfile=/var/www/website.a/storage/logs/worker.err.log

sudo nano /etc/supervisor/conf.d/website-b-worker.conf

[program:website-b-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/website.b/artisan queue:work redis --sleep=3 --tries=3
autostart=true
autorestart=true
#user=laravel
numprocs=8
autostart=true
autorestart=true
stdout_logfile=/var/www/website.b/storage/logs/worker.log
stderr_logfile=/var/www/website.b/storage/logs/worker.err.log

sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start website-a-worker:*
sudo supervisorctl start website-b-worker:*

// config/queue.php
...
'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
            'queue' => 'default',
            'retry_after' => 600,
            'block_for' => null,
        ],
...

<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class SomeJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function handle()
    {
       \Log::info('This only gets triggered if 1 supervisor worker is running.');
    }
}

> sudo service supervisor restart
> cd /var/www/website.a
> php artisan tinker

>>> App\Jobs\SomeJob::dispatch()->delay(1);
# Job does not get triggered
>>> exit

The job never gets triggered.
However, if I stop supervisor for website.b, website.a will process jobs.
> sudo supervisorctl stop website-b-worker:*
website-b-worker:website-b-worker_02: stopped
website-b-worker:website-b-worker_03: stopped
website-b-worker:website-b-worker_00: stopped
website-b-worker:website-b-worker_01: stopped
website-b-worker:website-b-worker_06: stopped
website-b-worker:website-b-worker_07: stopped
website-b-worker:website-b-worker_04: stopped
website-b-worker:website-b-worker_05: stopped

> php artisan tinker

>>> App\Jobs\SomeJob::dispatch()->delay(1);
# Job gets triggered!

How can I run multiple workers (at least 1 for each website)?

A: I've used Supervisor with Laravel and Redis but only for 1 website at a time. However I did some research and I found that you can specify the name of the Queue process in Laravel https://laravel.com/docs/5.8/queues#connections-vs-queues .
A Laravel Job has a setter method onQueue() to specificy name to a queue. laravel docs example :
Job::dispatch()->onQueue('emails');

But in your code SomeJob you can call it directly with $this->onQueue('queue_name'); your code can be like :
<?php
namespace App\Jobs;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;

class SomeJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function handle()
    {
        // on website a
        $this->onQueue('websiteAQueue');
        \Log::info('This only gets triggered if 1 supervisor worker is running.');
    }
}

And in Supervisor process for Website A, specify the queue parameter to be websiteAQueue :
[program:website-a-worker]
process_name=%(program_name)s_%(process_num)02d
command=php /var/www/website.a/artisan queue:work redis --queue=WebsiteAQueue --sleep=3 --tries=3
autostart=true
autorestart=true
#user=laravel
numprocs=8
autostart=true
autorestart=true
stdout_logfile=/var/www/website.a/storage/logs/worker.log
stderr_logfile=/var/www/website.a/storage/logs/worker.err.log

This way when Laravel is sending the Job, it will send it to that specified Queue and not the default one it found.
EDIT------------------------
Or better, you can use a different queue name for each Website config :
// Website A : config/queue.php
...
'redis' => [
            'driver' => 'redis',
            'connection' => 'default',
            'queue' => 'websiteAQueue',
            'retry_after' => 600,
            'block_for' => null,
        ],
...

This way all the queues are sent to websiteAQueue automatically, so you don't have to use $this->onQueue() on each Job.


text:
Q: How to not use by part to evaluate the following integration problem?
Evaluate$$\int^1_02x^2\sqrt{x^2+4}dx$$without integration by parts.

This is a problem from my calculus homework. I've tried to sub. $x=2\tan u$, and it became $$32\int^{\arctan\frac{1}{2}}_0\tan^2 u\sec^3 u$$ Which needs by parts.
Can anyone help me?

A: Hint
$$\tan^2u\sec^3u=\dfrac{\sin^2u}{\cos^5u}=\dfrac{\sin^2u}{\cos^6u}\cdot\cos u$$
As the exponent of cosine is odd, set $\sin u=y$
Then http://mathworld.wolfram.com/PartialFractionDecomposition.html

A: $$\dfrac{d(\tan^mx\sec^nx)}{dx}=n\tan^{m+1}x\sec^{n+1}x+m\tan^{m-1}x\sec^{n+2}x$$
Integrate both sides with respect to $x$
Set $n+1=3,m+1=2$
Now $$\int\sec^{2r}x\ dx=\int(1+\tan^2x)^{n-1}\sec^2x\ dx=?$$


text:
Q: Microsoft Cognitive Services custom vision - use without prediction API I'm currently looking to use Microsoft Cognitive Service custom vision. It comes with a prediction API which you can use to fetch the predicted results. Is it possible to use Custom Vision without using this prediction API? With that, I mean just export the model to Tensorflow and build my own API which fetches the results directly from Tensorflow.
It seems like I can export the model for mobile usage or to run it in a Docker container. However it seems like the prediction API is wired into that Docker container.

A: Custom Vision Service only exports compact domains. Classifiers built with a compact domain may be slightly less accurate than a standard domain with the same amount of training data.After you have exported your TensorFlow model from the Custom Vision Service, this quickstart will show you how to use this model locally to classify images.
For object detection exports there is code to load and run the object detection model in the zip file downloaded. Along with the the export model you will find Python code to exercise the model.


text:
Q: Recognizing characters with accent marks I have written code to recognize some words, but I get errors in the recognition of some characters with accent marks. Is there any solution?
i = Import["http://i.stack.imgur.com/f3U9N.jpg"]
TextRecognize[i, "SegmentationMode" -> 6]

0perag5es
Construg5es
Tftulo
Médulo

A: Add Language -> "Portuguese".
i = Import["http://i.stack.imgur.com/f3U9N.jpg"]
TextRecognize[i, "SegmentationMode" -> 6, Language -> "Portuguese"]


text:
Q: Given the pdf $f(y\mid\theta) = \theta y^{\theta - 1}1_{0Let $Y_1, \ldots, Y_n$ be a random sample from the pdf $$f(y\mid\theta) = \theta y^{\theta - 1}, 0 < y < 1, \theta > 0 .$$
show that $$E\left(\frac{1}{2\theta\sum_{i = 1}^n W_i}\right) = \frac{1}{2(n-1)}$$
I have showed that $\sum_{i = 1}^n -\ln(Y_i)$ is sufficient for $\theta$, and if $W_i = -\ln(Y_i)$, I have showed that $W_i$ has an exponential distribution with mean $1/\theta$. I have also showed that $2\theta \sum_{i=1}^n W_i $ has a $\chi^2$ distribution with $2n$ degrees of freedom.
I am wondering how to show it?

A: If you know that the chi-square distribution with $k$ degrees of freedom is $$f(x)\,dx=\frac{1}{\Gamma\left(\frac k 2\right)}\left(\frac x 2\right)^{k/2-1} e^{-x/2}\,\frac{dx}{2}\text{ for }x>0,$$ then it's just evaluating an integral:
\begin{align}
\int_0^\infty \frac 1 x f(x)\,dx & =
\int_0^\infty \frac 1 x \frac{1}{\Gamma\left(\frac k 2\right)}\left(\frac x 2\right)^{k/2-1} e^{-x/2}\,\frac{dx}{2} \\[12pt]
& = \frac{1}{\Gamma(k/2)}\cdot\frac 1 2 \int_0^\infty \left(\frac x 2\right)^{k/2-2} e^{-x/2} \,\frac{dx}{2} \\[12pt]
& = \frac{1}{\Gamma(k/2)}\cdot\frac 1 2 \int_0^\infty u^{k/2-2} e^{-u}\,du \\[12pt]
& = \frac{1}{\Gamma(k/2)}\cdot\frac 1 2 \cdot \Gamma\left( \frac k 2 - 1 \right) \\[12pt]
& = \frac{1}{\frac k 2 - 1} \cdot\frac 1 2 = \frac{1}{k-2}.
\end{align}


text:
Q: Vue js + Flask + AWS Cognito authentication I am learning Vue JS, and understood Vue JS <-> AWS Cognito Auth mechanism and then Vue JS <-> Flask integration.
Now I would like to understand how can I authenticate a user using AWS Cognito using Vue JS as frontend and once authenticated, how can I securely call Flask Backend api's?
How does Flask verify authentication data (like JWT Token provided by AWS Cognito to Vue) provided by Vue JS to respond to API calls?

A: Use AWS API Gateway in front of your Flask app, the API gateway can authorize the JWT token and pass your request to Flask
https://docs.aws.amazon.com/apigateway/latest/developerguide/apigateway-enable-cognito-user-pool.html


text:
Q: Unwanted output audio looping through input I have a fresh Xubuntu install and I'm trying to configure the sound,
I've got a Creative Xfi Titanium series sound card
At the moment when I'm talking online in Mumble/Skype/Teamspeak etc..
my output audio is passed out as well as my input, i.e. if I was listening to music the people listening to me would also hear the music (not through my microphone, wearing a headset) and it will completely down out my voice.
Sound Input

As you can see I've disabled the monitor which I initially thought was the problem
All my searches for trying to solve this just turn up people wanting to hear their microphone through their speakers and not about a sound loop going the other way.

A: Pulse Audio GUI is not able to manage physical inputs and outputs. So you should try with  alsamixer and one of its GUI (ex: gnome-alsamixer). This way, you can manage the physical i/o of your sound card.
sudo apt-get install alsamixer gnome-alsamixer

Using alsamixer (in terminal) go to input (F4) and turn down the PCM volume level to 0
Note: To stop hearing your own microphone in your headset/speakers turn down the microphone level to 0 on Output (F3)


text:
Q: Django Meta Class - Apply Ordering to user's model field I am new to Django 1.9, I have an models.py :
class MyProfile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    Role = ArrayField(models.CharField(max_length=1000), blank=True,null=True)
    ContactNumber = models.CharField(max_length=100)

    class Meta:
        ordering = ('date_joined',)

Here I want to order table using date_joined which is field of User model.
When I am trying to run python manage.py makemigrations it gives me error as follows:
SystemCheckError: System check identified some issues:

ERRORS:
projectmanagement.UniservedTeam: (models.E015) 'ordering' refers to the non-existent field 'date_joined'.

How do i achieve this?

A: To set ordering on generic api views:
http://www.django-rest-framework.org/api-guide/filtering/#orderingfilter
use: ordering = ('user__date_joined', )
EDIT:
you can specify ordering on meta class like this:
class Meta:
    ordering = ('user__date_joined', )


text:
Q: Uploading images via azure storage I am trying to upload images to blob storage via azure functions. Kind of struggling to get it working.
var data = new FormData();
        xhr = new XMLHttpRequest();
        data.append('file', file);
        data.append('name', file.name);

        xhr.open('POST', 'https://[blobstorage]/api/upload/foo', true);
        xhr.setRequestHeader('Content-type', 'multipart/form-data;');
        xhr.send(data);

The POST gets triggered in azure functions:
if (context.req.method === 'POST') {
        fs.readFile(context.req.rawBody, function (err, data) {
            context.log('data', data);
            blobService.createBlockBlobFromText(containerName, blob, data, {contentSettings: {contentType: 'image/png'}}, function(){
                context.done();
            });
        });
    }

This adds a file to blob storage but it isnt the image unfortunatly.

A: I believe context.log('data', data); showsundefined in the logs. That's why you are getting zero size file. Unfortunately multipart parsing is not part of Azure Functions functionality. You can find more details here:
How to parse Multi-part form data in an Azure Function App with HTTP Trigger? (NodeJS)


text:
Q: How to make an AngularJS directive to change the src attribute of an image? I want to create a angular directive for my image tags that changes the image src to a random image in a collection or through a call to a service. The change should should happen after 5 seconds or as an input to the directive. Is this possible and could someone help me starting?
I will also add animations to this but, thats for later.....
As a newbie to AngularJS any help or directions would be appreciated.
Thanks.

A: When one writes an img tag source like this:
<img ng-src='{{imagesrc}}' />

The image source attribute gets bound to the variable imagesrc, which you can then change in JS, such as by using $timeout:
var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $timeout) {
  $scope.name = 'World';
  $scope.imagesrc = "http://www.steff.qc.ca/main/wp-content/uploads/2010/03/phoenix.gif";
  $timeout(function() {
    $scope.imagesrc = "http://im2-tub-ru.yandex.net/i?id=3fb6126a9a8ea667700f698b774e34d3-90-144&n=21";
  }, 1000);
});

See full plunkr here:
http://plnkr.co/edit/q7dI6N6skuGlhfQTqyQT?p=preview

A: You can write a directive, and in the link function write something like this:
function link(scope, element, attrs) {
    var format,
        timeoutVal;

    function updateAttrs(value) {
      element.attr('src', value));
    }

    element.on('click', function() {
      updateAttrs(value);
    });
  }

Somwhere in the link you can use angular $timeout.
This code snippet does not work but it could give you some some idea of the mechanism.
Another way is to use ng-mouseover and create in the parent controller a function, which will change attrs of the element.


text:
Q: getimagesize does not work with images that contain latin/special chars When I try to get image size like this
$size=getimagesize(realpath('http://www.index.hr/images2/ivandžaferovic-fejs.jpg'));

It says:

Warning:
  getimagesize(http://www.index.hr/images2/ivandžaferovic-fejs.jpg)
  [function.getimagesize]: failed to open stream: HTTP request failed!
  HTTP/1.0 400 Bad request in
  test.php on line 4
  -bool(false)

It is because of "ž" character inside picture. without it, functions does work. What to do about it

A: It works if you urlencode the filename:
$size = getimagesize('http://www.index.hr/images2/'.urlencode('ivandžaferovic-fejs.jpg'));

print_r($size);

More dynamic example with pathinfo:
$url = pathinfo('http://www.index.hr/images2/ivandžaferovic-fejs.jpg');
$size = getimagesize($url['dirname'].'/'.urlencode($url['basename']));
print_r($size);

Another example with parse_url:
$urlArray = parse_url('http://www.portal.com/ResourceManager/GetImage.aspx?imgId=619389&fmtId=99');

$url = ($urlArray['scheme'].'://'.$urlArray['host'].str_replace('%2F', '/', urlencode($urlArray['path'])));
$url .= isset($urlArray['query']) ? '?'.$urlArray['query'] : '';

$size = getimagesize($url);
print_r($size);

It should work in most of the cases. The scheme (http, https etc.) must be given, else parse_url will not include a host but only a path array key. So to build a general and flawless solution you'll have to spend more time (write more code) on parsing the url.


text:
Q: Angular2 Output Eventemitter is only working on Plunkr but not working when using local copy I've been trying this angular2 sample Component Interaction using plunkr and it is working fine, but if i use visual studio 2015/Code and download all package(node_modules) somehow is not working properly, i have attached the sample local copy that the first "Agree/disagree" emit is not working only the 2nd/3rd is working.
Here is my code copy: SampleApplication
Hope someone can help me on this thanks.

A: Sorry folks, already figured it out what is the problem.
it's my module declaration and i should remove the votercomponent in the bootstrap
@NgModule({
    imports: [BrowserModule],
    declarations: [VoteTakerComponent, VoterComponent],
    bootstrap: [VoteTakerComponent, VoterComponent]
})

export class AppModule { }


text:
Q: Exported Database Dumpfile Incorrect I'm trying to create a page with a button when clicked will download the database named sampledb.
Here's my backup.php
<?php
ob_start();

$username = "root";
$password = "";
$hostname = "localhost";
$dbname   = "sampledb";

$command = "C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysqldump --add-drop-table --host=" . $hostname . "--user=". $username ." --password=". $password." ".$dbname;
system($command);

$dump = ob_get_contents();
ob_end_clean();

// send dump file to the output
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=sqlfile.sql');
readfile('sqlfile.sql');
flush();
echo $dump;
exit();
?>

The export was successful. However, when I checked the downloaded file (sqlfile.sql) in the downloads folder, its file size is only 2kB. I tried exporting the sampledb using phpMyAdmin and found out the actual file size is 9kB.
Moreover, when I tried importing the sqlfile.sql through phpMyAdmin, I got an error message. It says Warning: readfile(sqlfile.sql).
Something is wrong with my export code. Any suggestions?
UPDATE 20131205
I tried appending > sqlfile.sql to this part of my code.
$command = "C:\\wamp\\bin\\mysql\\mysql5.5.24\\bin\\mysqldump. --add-drop-table --host=" . $hostname . "--user=". $username ." --password=". $password." ".$dbname;
File size is still incorrect. I cannot upload the downloaded file to phpMyAdmin.
END UPDATE

A: mysqldump needs to be dumped into a file, otherwise it just returns the results as text.
Usually this is done by redirecting into a file:
mysqldump --... > dump.sql


text:
Q: About csc.exe, is it necessary to learn? I am an intermediate programmer and these days I've been analyzing the CLR, my question is what is the need to learn all the commands of c# command line! It's so boring.
is it necessary?

A: You might find, as I did, that sometimes it's just easier to start up Notepad (or your favorite text editor) to create a simple C# program.  Then use the command line tool to compile it quickly, without having to go to the trouble of starting Visual Studio, building a project, etc.  It's a whole lot easier and faster to just type:
csc /t:exe MyProgram.cs
Knowledge is rarely useless. Some of the things you consider 'boring' turn out to be the most important and eventually the most interesting.
In the case of the .NET command line tools, I would suggest learning about them--what tools exist, what they do, and how to operate them--but I wouldn't say that you need to become a command line guru.

A: It depends a lot on how you plan to use C#. If you're building things only from Visual Studio or another IDE, it's probably less of a priority. However, if you'll be building C# projects using other tools (ant, for example), you should familiarize yourself with it.

A: If you have a tool like Visual Studio, you can most probably get away without learning command line compilation. However, knowing them would be of advantage in situations when you don't have advance IDE.
This goes for every language and not just c#.


text:
Q: How to find out if the input number is balanced? According to my lecturer a balanced number is balanced if the sum of its divisors is equal to it self. for example: 6 is a balanced number because 1+2+3=6
These are my very first homework so i am struggeling.
#include <iostream>
using namespace std;

int main() {
    int num = 0;
    int sum = 0;
    cout << "Enter a number" << endl;
    cin >> num;
    if (num % (num-1) == 0 ){

    for(int i =1; sum == 0; i++) {
        sum += (num - i);

    }

    if (sum == num) {
        cout << "Great Success" << endl;
        }
    else {
        cout << "Wrong number" << endl;
    }

    }

}

A: Do the maths first. Often code being a bit messy is just a consequence of not preparing yourself good enough to write the code. Dont start writing code before you know what you want to write. Frankly, from your code one can see that it is something related to num-1 dividing num, but otherwise it is not clear how it is supposed to solve the problem. And its intendation makes it quite hard to read, so lets forget about the code and start from scratch...
y is a divisor of x exactly if x % y == 0. The biggest possible divisor of x is x/2. To get all divisors we can simply check every number from 2 up to x/2 (1 is always considered a divisor, hence no need to check).
Only now we can write some code:
int x;
std::cin >> x;
int sum = 1;
for (int y = 2; y <= x/2; ++y){
    if ( check_if_y_is_divisor) { sum += y; }
}
bool is_balanced = sum == x;

I left a tiny hole in the code that you have to fill (I just dont like to give away the full solution when it is homework).


text:
Q: Opening 2 WebCams From The Same USB Cable So i got this cool double WebCam that connect to the mac from a single usb cable.
i can see that my mac recognized the cameras as i connect it. i write a little program from XCODE that stream cam video to QTCaptureView in to two QTCaptureViews left and right
                 [ left cam view ]    [ right cam view ]

before i post some code i would like to tell that if i choose one of the cams to be streamed and the face time camera also (for example it could be any other cam instead of the cam that connected to the same port) i get both streamed at the same time.
but if i choose both camera to be projected only one will work.
it could be something that is impossible on the hardware level?
i would really like to hear some ideas.

A: A simple solution is to use "Video Capture Sources" filter from GraphEdit where you should see two capture ports that can be rendered simultaneously.
A more advanced solution is to use OpenCV as follows:
Mat Lframe,Rframe;

For multi-head camera, use:
VideoCapture cap(0); // open the default camera
if(cap.grab())
    cap.retrieve(Lframe,0); cap.retrieve(Rframe,1);// get a new frame

For two stereo cameras:
VideoCapture capL(0),capR(1);
capL.grab();capR.grab();
capL.retrieve(Lframe); capR.retrieve(Rframe);// get a new frame

See VideoCapture for more details.


text:
Q: Croatian letters in Java Program I need help your help on croatian letters in my program. On the website (play framework) you can put in names. The name will be saved and a PDF file will be created (with iText) where the string the user typed in is shown. I want to use the font lucida bright. The problem is that there are non-german letters in the names that are not shown. I also tried to convert it into unicode (/u----) but it also doesn't work. I tried to use utf-8 like this in the iText doc:
String name = new String(e.getName().getBytes("UTF-8"));
// e is the object where the name and some other infos are saved

and in the html where the user can type in the name
<meta name="language" content="cr">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

but it doesn't work completely.
In lucida bright (font) are only Š and š correctly shown and in times new roman Š, Ž, š and ž. How can I solve this problem?

A: If you want to use a font in iText's PDF generation then you have to add it
As in
Font font = FontFactory.getFont("Times-Roman");
document.add(new Paragraph("Times-Roman", font));

For more information see iText


text:
Q: How to get the state of the cursor? I was wondering if there was any way in Python 3.8 to read the cursor type like how win32gui could do with win32gui.GetCursorInfo(), Finding the id of the cursor. Below is what I mean by cursor state:

A: Please find the code below.
reference:
https://www.iditect.com/how-to/10284849.html, but I modified it a little bit:
from win32con import IDC_APPSTARTING, IDC_ARROW, IDC_CROSS, IDC_HAND, \
IDC_HELP, IDC_IBEAM, IDC_ICON, IDC_NO, IDC_SIZE, IDC_SIZEALL, \
IDC_SIZENESW, IDC_SIZENS, IDC_SIZENWSE, IDC_SIZEWE, IDC_UPARROW, IDC_WAIT

from win32gui import LoadCursor, GetCursorInfo

def get_current_cursor():
    curr_cursor_handle = GetCursorInfo()[1]
    return Cursor.from_handle(curr_cursor_handle)

class Cursor(object):
    @classmethod
    def from_handle(cls, handle):
        for cursor in DEFAULT_CURSORS:
            if cursor[1].handle == handle:
                return cursor[0] #DEFAULT_CURSORS.index(cursor) , Cursor.__init__
        return cls(handle=handle)

    def __init__(self, cursor_type=None, handle=None):
        if handle is None:
            handle = LoadCursor(0, cursor_type)
        self.type = cursor_type
        self.handle = handle

DEFAULT_CURSORS = (('APPSTARTING',Cursor(IDC_APPSTARTING)), ('ARROW',Cursor(IDC_ARROW)), ('CROSS',Cursor(IDC_CROSS)), ('HAND',Cursor(IDC_HAND)), \
       ('HELP',Cursor(IDC_HELP)), ('IBEAM',Cursor(IDC_IBEAM)), ('ICON',Cursor(IDC_ICON)), ('NO',Cursor(IDC_NO)), ('SIZE',Cursor(IDC_SIZE)),\
       ('SIZEALL', Cursor(IDC_SIZEALL)),('SIZENESW', Cursor(IDC_SIZENESW)), ('SIZENS',Cursor(IDC_SIZENS)), ('SIZENWSE',Cursor(IDC_SIZENWSE)),\
        ('SIZEWE', Cursor(IDC_SIZEWE)), ('UPARROW', Cursor(IDC_UPARROW)), ('WAIT',Cursor(IDC_WAIT)))

while(True):
    print(get_current_cursor())

A: I've made some improvements to be more streamlined
from win32con import IDC_APPSTARTING, IDC_ARROW, IDC_CROSS, IDC_HAND, \
IDC_HELP, IDC_IBEAM, IDC_ICON, IDC_NO, IDC_SIZE, IDC_SIZEALL, \
IDC_SIZENESW, IDC_SIZENS, IDC_SIZENWSE, IDC_SIZEWE, IDC_UPARROW, IDC_WAIT

from win32gui import LoadCursor, GetCursorInfo

DEFAULT_CURSORS = {
    LoadCursor(0, IDC_APPSTARTING): 'appStarting',
    LoadCursor(0, IDC_ARROW): 'Arrow', LoadCursor(0, IDC_CROSS): 'Cross',
    LoadCursor(0, IDC_HAND): 'Hand', LoadCursor(0, IDC_HELP): 'Help',
    LoadCursor(0, IDC_IBEAM): 'IBeam', LoadCursor(0, IDC_ICON): 'ICon',
    LoadCursor(0, IDC_NO): 'No', LoadCursor(0, IDC_SIZE): 'Size',
    LoadCursor(0, IDC_SIZEALL): 'sizeAll',
    LoadCursor(0, IDC_SIZENESW): 'sizeNesw',
    LoadCursor(0, IDC_SIZENS): 'sizeNs',
    LoadCursor(0, IDC_SIZENWSE): 'sizeNwse',
    LoadCursor(0, IDC_SIZEWE): 'sizeWe',
    LoadCursor(0, IDC_UPARROW): 'upArrow',
    LoadCursor(0, IDC_WAIT): 'Wait',
}

def get_current_cursor():
    curr_cursor_handle = GetCursorInfo()[1]
    res = DEFAULT_CURSORS.get(curr_cursor_handle, 'None')
    return res

if __name__ == '__main__':
    while True:
        get_current_cursor()


text:
Q: Can't send e-mail using fake sendmail in wamp I have been doing this for hours and can't get it to work, many comments in the tutorial said it works like a charm but I can't really make this work.
I have done all the steps here http://blog.techwheels.net/send-email-from-localhost-wamp-server-using-sendmail/ and read all the comments with problems other users encountered and also used the solutions replied.
What I see on the apache error log is this
[Tue Nov 27 05:19:47 2012] [notice] Parent: Created child process 4120
[Tue Nov 27 05:19:47 2012] [warn] Init: Session Cache is not configured [hint: SSLSessionCache]
[Tue Nov 27 05:19:48 2012] [notice] Child 4120: Child process is running
[Tue Nov 27 05:19:48 2012] [notice] Child 4120: Acquired the start mutex.
[Tue Nov 27 05:19:48 2012] [notice] Child 4120: Starting 64 worker threads.
[Tue Nov 27 05:19:48 2012] [notice] Child 4120: Starting thread to listen on port 80.
[Tue Nov 27 05:19:48 2012] [notice] Child 4120: Starting thread to listen on port 80.

I also have tried it on my other computer and it has the same error log. I have disabled my firewall and also critically followed the steps on the tutorial.

A: Sorry for the previous answer. Thanks everyone for your suggestions to improve my answer. Here is my answer: The phpmailer has a file called class.phpmailer.php. Then in the function smtpmailer($to, $from, $from_name, $subject, $body) the code goes as follows:
global $error;
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPDebug = 0;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = 'gmailusername';
$mail->Password = 'gmailpassword';
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
    $mail->IsHTML(True);
    $mail->Body=$body;
//$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send()) {
    $error = 'Mail error: '.$mail->ErrorInfo;
    return false;
} else {
    $error = 'Message sent!';
    return true;
}

Then just call the function where ever you want as:
smtpmailer($to, $from, $headers, $subject, $message);
Oh and prior to this make sure php_openssl extension is enabled.
I hope this answer of mine was helpful. :)


text:
Q: Proofs about functions that depend on the ordering of their alternatives Having quite some experience in Haskell, I just recently started to use Idris for theorem proving. This is a minimal example that illustrates a problem I encountered when trying to prove rather simple statements.
Consider we have a total function test:
total test : Integer -> Integer
test 1 = 1
test n = n

Of course we see that the function could be simplified to test n = n, but let's prove it. I am simply going over all the cases:
total lemma_test : (n : Integer) -> test n = n
lemma_test 1 = Refl
lemma_test n = Refl

But, this doesn't type-check:
Type mismatch between
        n = n (Type of Refl) and
        test n = n (Expected type)

Specifically:
        Type mismatch between
                n
        and
                test n

So, the problem seems to be that Idris cannot infer for the second case of lemma_test that n is not equal to 1 and that also the second case of test must be applied.
We can, of course, try to explicitly list ALL the cases, which can be cumbersome, or impossible, as in the case for Integers:
total lemma_test : (n : Integer) -> test n = n
lemma_test 1 = Refl
lemma_test 2 = Refl
lemma_test 3 = Refl
...

Is there a way to prove statements like this for functions that are not defined over a finite set of data constructors but instead depend on the fact that pattern-matching works from top to bottom, like test in this example?
Maybe there is a rather simple solution that I just fail to see, considering that functions like this occur quite often.

A: As others have said, Integer is primitive, and not an inductively defined Idris type, therefore we can't do exhaustive pattern matching on it. More specifically, the issue is that in Idris (and actually in state-of-the-art Agda too!) we can't really prove things about "default" pattern matches, because they don't carry information about all the previous patterns that failed to match. In our case, test n = 1 doesn't give us evidence that n is not equal to 1.
The usual solution is to use decidable equality (Boolean equality could be good too) instead of fall-through:
import Prelude

%default total

test : Integer -> Integer
test n with (decEq n 1)
  test n | Yes p = 1
  test n | No  p = n

lemma_test : (n : Integer) -> (test n) = n
lemma_test n with (decEq n 1)
 lemma_test _ | (Yes Refl)  = Refl
 lemma_test n | (No contra) = Refl

Here, the No result carries explicit evidence about the failed match.

A: I'm not sure how Integer is defined, or how to do induction on it, etc., so this is not a full answer to your question; but maybe the Nat version is also going to be informative for you? (also, maybe you actually meant Nat, since in your second example you only enumerate the positive naturals?)
If you change test to use Nats:
total test : Nat -> Nat
test (S Z) = 1
test n = n

then you can do exhaustive pattern matching in lemma_test:
total lemma_test : (n : Nat) -> test n = n
lemma_test (S Z) = Refl
lemma_test Z = Refl
lemma_test (S (S k)) = Refl

A: Integer isn't defined in Idris, but rather defers to GMP bigints. It's effectively opaque to Idris, and apparently not something you can reason about cases of at compile time in this way. With something like Nat, which is defined inductively, you can talk about proofs in the form of a base case and a recursive case.
That type error about n not being test n is telling you that Idris can't reduce the expression test n. I'm not sure that's how it's supposed to behave - obviously it's a total function, and it's supposed to reduce total functions afaik. Maybe that's related to the opacity of Integer to Idris?
You can test out the reduction at the repl, by introducing the free variable as a labmda param. E.g. \n => test n just echoes back \n => test n : Integer -> Integer (with nothing changed), however, if you remove the test 1 = 1 case from your definition and try again, it echoes back \n => n : Integer -> Integer - it's reduced test n to n. And then your proof would work as-is.


text:
Q: Сохранение данных при вводе в TextField которая находиться в ячейке таблицы У меня есть таблица с 50 ячейками и в каждой есть TextField.
Как при редактировании ячейке сразу обновить данные в массиве для отображения таблицы? Чтобы при прокрутке данные они не пропали?


text:
Q: Does Windows 7 support multiple mouse drivers being installed? I use a laptop for work that plugs into a docking station to which my Logitec G5 mouse is connected.  I often take my laptop home where I will connect my Logitech G500.  To my understanding, these two mice use the same drivers, so there shouldn't be any conflicts.  However, I am thinking of buying a non-Logitech mouse for work.  I'd like to know that the non-Logitech drivers will work for the non-Logitech mouse while my Logitech drivers will work for my G500 when I take my laptop home.

A: You can install an unlimited amount of drivers (mouse or otherwise). In reality though, nearly all mice use the same standard mouse driver provided by Microsoft.


text:
Q: Question about flags in synthenic geometry The book is "Projective Geometry: From Foundations to Applications" by Albrecht Beutelspacher and Ute Rosenbaum.
On page 3, the definiation of a flag is stated:
Definition. Let $\textbf{G} = (\Omega,I)$ be a geometry. A flag of $\textbf{G}$ is a set of elements of $\Omega$ that are mutually incident. A flag $\mathscr{F}$ is called maximal if there is no element $x \in \Omega \setminus \mathscr{F}$ such that $\mathscr{F} \cup \{ x\}$ is also a flag.
Then in example a.
Let $Q$ be a point, $g$ be a line, and $\pi$ be a plane of 3-dimensional Euclidean space with $Q \in g$ and $g \subseteq \pi$. Then the following are flags:
$\{ Q \},\, \{ g \},\, \{\pi\}$;
$\{Q,g\},  \{Q,\pi\},\{g,\pi\}$;
$\{Q,g,\pi \}$.
Note before in the text it states: Two elements of the geometry $\textbf{G}$ that are related by $I$ are called incident.
I understand the last two flags listed; however, the first listing of $\{ Q \},\, \{ g \},\, \{\pi\}$  is where I have some troubles.
First, lets label the three flags as $A,B,C$ respective to the order listed.
Now, I get that $C$ is the maximal flag. I understand that any three elements of the set $C$ are incident with each other, and all three elements are in $I$.
I see how $B$ is also a flag, but not a maximal flag.  Each set has two elements.
Now for $A$  I get a bit confused.  Now the book states that it takes TWO elements for "incident".  How can $A$ be a flag?  How come mutual incident doesn't requre two elements but to have the propertiy of incident it does require two elements?


text:
Q: Many to many in mongodb using spring configuration(annotation preffered) I'm modeling a schema. As I'm new to Mongo DB I've no idea on how to model a nosql db.
Structuring a relational type db and using mongo on top of it does not allow me to use many to many mapping.
Using Spring-data does provide support for one to many using @DBRef on top of the List<?>. But many to many is something I want.
Any help will be deeply appreciated. Kindly prefer using code to explain. Or a demo structure to illustrate. Thanks in advance.

A: There are several ways to implement many-to-many in MongoDB.
I think the simplest is the following:
Many-To-Many Relational scenario:

After de-normalization:

And your Spring Data code should look something like this:
public class Category {

    @Id
    private ObjectId id;

    private String category_name;

    @DbRef
    private List<Product> products_ids;

    // ... getters and setters ...

}

public class Product {

    @Id
    private ObjectId id;

    private String product_name;

    @DbRef
    private List<Category> categories_ids;

    // ... getters and setters ...

}

A:
 @marianomdq:
  And your Spring Data code should look something like this: ...

When I tried this out, there is no problems, what so ever, to save the entities to the database. My problem is loading them again. That seems to cause the (in this example) load of a Category to fall into an infinite loop Category -> Product -> Category -> Produ..... Until a StackOverflowException is thrown.
java.lang.StackOverflowError: null
    at java.lang.reflect.Constructor.newInstance(Constructor.java:416) ~[na:1.8.0_77]
    at java.lang.Class.newInstance(Class.java:442) ~[na:1.8.0_77]
    at com.mongodb.DBCollectionObjectFactory.getInstance(DBCollectionObjectFactory.java:51) ~[mongodb-driver-3.2.2.jar:na]
    at com.mongodb.DBObjectCodec.readDocument(DBObjectCodec.java:340) ~[mongodb-driver-3.2.2.jar:na]
    at com.mongodb.DBObjectCodec.decode(DBObjectCodec.java:136) ~[mongodb-driver-3.2.2.jar:na]
    at com.mongodb.DBObjectCodec.decode(DBObjectCodec.java:61) ~[mongodb-driver-3.2.2.jar:na]
    ........

Complete stacktrace is super big.
Solution: Lazy loading of database references!
Simply set the lazy flag of the DBRef annotation to true, this will make the loading references lazy. Which means that the circular references will not all be loaded at once.
@DBRef(lazy = true)
The research to actually get to this solution was cumbersome. Therefore I wanted to share this information.


text:
Q: How to attach a file to a vcalendar event? I am trying to attach a file to a calendar event invite generated using Java. I want to attach a blob object as an attachment,but I unable to attach even a basic file.
I tried using the ATTACH tag in the calendar event template as follows:
"ATTACH;FMTTYPE=image/jpeg:http://farm1.static.flickr.com/183/411545406_c73ca4e613_t.jpg"
But it doesn't work. Am I missing something?
Thanks,
Tanvi


text:
Q: CMake and Visual studio 2015 - The C compiler cl.exe is not able to compile a simple test program I am trying to compile my programme using microsoft visual studio 2015 combine with cmake on Qt creator and I get this error that I really do not know how to solve.
Running "C:\Program Files\CMake\bin\cmake.exe C:/Users/SEVLH/Documents/sodis"-GCodeBlocks - NMake Makefiles" "-DCMAKE_CXX_COMPILER:STRING=C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe" "-DCMAKE_C_COMPILER:STRING=C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe" "-DCMAKE_PREFIX_PATH:STRING=C:/Qt/Qt5.8.0/5.8/msvc2015_64" "-DQT_QMAKE_EXECUTABLE:STRING=C:/Qt/Qt5.8.0/5.8/msvc2015_64/bin/qmake.exe"" in C:\Users\SEVLH\AppData\Local\Temp\qtc-cmake-Yu2EZw.
-- The C compiler identification is unknown
-- The CXX compiler identification is unknown
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe
-- Check for working C compiler: C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe -- broken
CMake Error at C:/Program Files/CMake/share/cmake-3.8/Modules/CMakeTestCCompiler.cmake:51 (message):
The C compiler "C:/Program Files (x86)/Microsoft Visual Studio 14.0/VC/bin/amd64/cl.exe" is not able to compile a simple test program.

It fails with the following output:

Change Dir: C:/Users/SEVLH/AppData/Local/Temp/qtc-cmake-Yu2EZw/CMakeFiles/CMakeTmp

Run Build Command:"nmake" "/NOLOGO" "cmTC_eda15\fast"

"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\amd64\nmake.exe" -f CMakeFiles\cmTC_eda15.dir\build.make
/nologo -L CMakeFiles\cmTC_eda15.dir\build

Building C object CMakeFiles/cmTC_eda15.dir/testCCompiler.c.obj

C:\PROGRA~2\MICROS~1.0\VC\bin\amd64\cl.exe -o
CMakeFiles\cmTC_eda15.dir\testCCompiler.c.obj -c
C:\Users\SEVLH\AppData\Local\Temp\qtc-cmake-Yu2EZw\CMakeFiles\CMakeTmp\testCCompiler.c

NMAKE : fatal error U1045: spawn failed : Invalid argument

 Stop.

NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\amd64\nmake.exe"' : return code '0x2'

 Stop.

CMake will not be able to correctly generate this project.
Call Stack (most recent call first):
CMakeLists.txt:3 (project)

A: I solve it adding jom.exe to the path

A: I solved this problem for Visual Studio 2019 and QT 5.14.1 (Qt creator 4.11.0) by changing CMake generator in Tools > Options > Kits to Ninja.


text:
Q: How to send an Ajax request to Laravel 5.0 framework? I've tried to fix this all morning and I can't seem to find any working method online.
I'm trying to do a simple ajax request to my Laravel controller and get the data it sends. I've simplified it to the maximum and I still get ERROR 500 with data "undefined".
It seems that every examples onlines are about Laravel 4.0, I'm not sure if they changed something or not but none seem to work. I also tried changing the route to "any" and it works on the direct access but not with the ajax request.
Thanks.
Controller :
<?php namespace App\Http\Controllers;
use Session, DB, Request;
class AjaxController extends Controller {

    public function question()
    {
        print_r("Made It");
        die();
    }
}

Route :
Route::post('/ajax/question', 'AjaxController@question');

Javascript :
$.ajax({
    url: "/ajax/question",
    method: 'POST',
    data:  { 'answered': '1' },
    processData: false,
    contentType: false,
    cache: false,
    success: function(data) {
        console.log(data);
        console.log("success");
    },
    error: function(data) {
        console.log(data);
        console.log("error");
    }
});

console.log(data) gives the following :
readyState

    4
responseText

    ""
status

    500
statusText

    "Internal Server Error"
abort

    function(e)
always

    function()
complete

    function()
done

    function()
error

    function()
fail

    function()
getAllResponseHeaders

    function()
getResponseHeader

    function(e)
overrideMimeType

    function(e)
pipe

    function()
progress

    function()
promise

    function(e)
setRequestHeader

    function(e, t)
state

    function()
statusCode

    function(e)
success

    function()
then

    function()

EDIT :
If I change the request to GET it works properly. (Set route to any)

A: If you look in your browser console at the response, chances are you're hitting the CSRF middleware. You need to post _token with the current value for the user's csrf_token().
We include this in our page layouts in order to automatically add it to all AJAX requests via a header (which Laravel understands):
<script>
$(function() {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': {!! json_encode(csrf_token()) !!};,
        }
    });
});
</script>

See https://github.com/laravel/framework/blob/8687d42c6674e47efc093b5092ea217b62ba293a/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php#L55 for details on how that works.

A: $.ajax({

    type: "POST",

    URL: "test/",

    data: {

        id: $(this).val(), // < note use of 'this' here

        access_token: $("#access_token").val()
    },

    success: function(result) {

        alert('YES');
    },
    error: function(result) {

        alert('Some Thing went wrong');

    }

});


text:
Q: Bluetooth communication in Android Cant get the message I am trying to make a link (bluetooth) between my arduino and android. i want to recieve the data from the arduino. The ListenInput thread does get started but nothing more
Here is my code
package com.codeyard.teleprompter;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

public class bleutoothrevivedeletenow extends AppCompatActivity {
    static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    String address = null;
    BluetoothAdapter myBluetooth = null;
    BluetoothSocket btSocket = null;
    Button StartConnection;
    Button Disconnect;
    Button Recieve;
    TextView incomingData;
    InputStream mmInStream = null;
    String incomingMessage;
    StringBuilder messages;
    Thread ListenInput = new Thread() {
        @Override
        public void run() {
            try {

                mmInStream = btSocket.getInputStream();
                byte[] buffer = new byte[1024];
                int bytes;
                Toast.makeText(getApplicationContext(), "Thread started///", Toast.LENGTH_LONG).show();
                while (true) {
                    // Read from the InputStream
                    try {
                        if (mmInStream == null) {
                            Log.e("", "InputStream is null");
                        }
                        bytes = mmInStream.read(buffer);
                        incomingMessage = new String(buffer, 0, bytes);
                        messages.append(incomingMessage);
                        Toast.makeText(getApplicationContext(), "incoming message", Toast.LENGTH_LONG).show();
                        Toast.makeText(bleutoothrevivedeletenow.this, incomingMessage, Toast.LENGTH_LONG).show();
                        //TODO Remove this

                    } catch (Exception e) {
                        Toast.makeText(bleutoothrevivedeletenow.this, "128", Toast.LENGTH_SHORT).show();

                    }
                }
            } catch (Exception e) {
                Toast.makeText(bleutoothrevivedeletenow.this, "133", Toast.LENGTH_SHORT).show();
            }

        }
    };
    private boolean isBtConnected = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bleutoothrevivedeletenow);
        messages = new StringBuilder();
        SharedPreferences sharedPreferences;
        sharedPreferences = PreferenceManager.getDefaultSharedPreferences(bleutoothrevivedeletenow.this);
        address = sharedPreferences.getString("ADDRESS", "");
        StartConnection =  findViewById(R.id.button5);
        Disconnect =  findViewById(R.id.button6);
        incomingData = findViewById(R.id.textView);
        Recieve =  findViewById(R.id.button7);

        StartConnection.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                new ConnectBT().execute();

            }
        });
        Disconnect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (btSocket != null) //If the btSocket is busy
                {
                    try {
                        btSocket.close(); //close connection
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                finish();
            }
        });
        Recieve.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ListenInput.start();
                final Handler handler = new Handler();
                Runnable runnable = new Runnable() {
                    @Override
                    public void run() {
                        incomingData.setText(messages);
                        handler.postDelayed(this, 2000);

                    }
                };
                runnable.run();
            }
        });

    }

    private class ConnectBT extends AsyncTask<Void, Void, Void>  // UI thread
    {
        private boolean ConnectSuccess = true; //if it's here, it's almost connected

        @Override
        protected void onPreExecute() {
            Toast.makeText(getApplicationContext(), "Connecting....", Toast.LENGTH_LONG).show();
        }

        @Override
        protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
        {
            try {
                if (btSocket == null || !isBtConnected) {
                    ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH}, 1);
                    ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH_ADMIN}, 1);
                    ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH_PRIVILEGED}, 1);

                    myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device

                    BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);

                    //connects to the device's address and checks if it's available
                    btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
                    BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
                    btSocket.connect();//start connection
                }
            } catch (IOException e) {
                ConnectSuccess = false;//if the try failed, you can check the exception here
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
        {
            super.onPostExecute(result);

            if (!ConnectSuccess) {
                Toast.makeText(getApplicationContext(), "Connection Failed", Toast.LENGTH_SHORT).show();
                finish();
            } else {
                Toast.makeText(getApplicationContext(), "Connection Successful", Toast.LENGTH_SHORT).show();
                isBtConnected = true;
            }

        }

    }
}

P.S. i have provided the entire code. this code is actually of this github repo:
https://github.com/IamMayankThakur/android-arduino-using-bluetooth
The code first genereated a IllegalThreadException but after debugging i edited the code and now it doesn't crash but still no incoming data


text:
Q: HttpUrlConnection POST request not working....How to solve this? HttpUrlConnection POST request not working. Tell me if there is any other way to make POST request in android.Tell me if there is any other way to make POST request in android.Tell me if there is any other way to make POST request in android.
 public final String apiCall(String pUrl) {
    if( ! isInternetAvailable() )
        return "NO_INTERNET";

    try {
        URL lUrl = new URL(pUrl.replace(" ", "%20"));
        Log.i("url", String.valueOf(lUrl));

       String url = pUrl;

        Log.i("dom", url.substring(0, (url.indexOf('?') - 1)));
        Log.i("para", url.substring((url.indexOf('?') + 1), url.length()) );

        URL obj = new URL(url.substring(0,(url.indexOf('?')-1)));
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", "GYUserAgentAndroid");
        con.setRequestProperty("Content-Type", "application/json");

        String urlParameters = url.substring((url.indexOf('?')+1), url.length());
        Log.i("urlParameters", urlParameters.toString());

        // Send post request
        con.setDoInput(true); // true if we want to read server's response
        con.setDoOutput(true); // false indicates this is a GET request
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        Log.i("res",response.toString());
        return response.toString();

    }catch (Exception e) {
        Log.i("secondEx",e.toString());
        return "ERROR";
    }

}

A: Try this
InputStream inputStream;
HttpURLConnection urlConnection;
byte[] outputBytes;

public class WebServiceAsyncTask extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... params) {

        try {
            URL url = new URL(Url);
            urlConnection = (HttpURLConnection) url.openConnection();
            outputBytes = query.getBytes("UTF-8");
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoOutput(true);
            urlConnection.setConnectTimeout(15000);
            urlConnection.connect();

            OutputStream os = urlConnection.getOutputStream();
            os.write(outputBytes);
            os.flush();
            os.close();

            inputStream = new BufferedInputStream(urlConnection.getInputStream());
            ResponseData = convertStreamToString(inputStream);

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();

        }
        return ResponseData;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

    }

    public String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append((line + "\n"));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}

Pass your parameters in json string format like this
JSONObject() params = new JSONObject();
params.put("key","your parameter");
params.put("key","your parameter");

query=params.toString();

Check this link for reference

A: Another way to perform requests is Retrofit
You can find a good tutorial here


text:
Q: Gradle: is it possible to publish to Gradle's own local cache? I know that I can use the maven plugin coupled with mavenLocal() to install an artifact and use it locally.
However investigating this a bit further, I notice that this means the artifacts are installed to Mavens's standard ~/.m2, but at the same time Gradle's own cache lives under ~/.gradle/caches in a different format.
This seems wasteful to me, a) working with two local caches, and b) having to add mavenLocal() to all projects. I was wondering if there is a way to publish an artifact to Gradle's ~/.gradle/caches ?

A: Note that the local Maven repository is not (really) a cache, and that the Gradle cache is not a repository. Gradle uses its cache only to cache remote artifacts, it should not copy artifacts retrieved from local Maven repositories there. In turn, you cannot publish artifacts to the Gradle cache.
So the approach to publish to and use mavenLocal() should not be as wasteful as you think. Also, you do not have to add mavenLocal() to all projects of a multi-project separately. You can simply use something like allprojects { repositories { mavenLocal() } } in your root project. Or if you want mavenLocal() in all your independent Gradle projects you could even try adding it to ~/.gradle/init.gradle.

A: Here is an example with code.
As it's not possible to publish into Gradle. The workaround is to publish into the maven and use it in Gradle.
Step 1 publish the code to local maven repository /users/jay/.m2/repository/
Step2 - Use the local maven repo code in another project.
Step #1 (Publish to local maven repo)
apply plugin: 'maven-publish'

publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java
        }
    }
}

Step #2 (Use the local maven repo in your gradle project)
repositories {

    // ..... Other repositories

    mavenLocal()
}

dependencies {
    compile 'com.jai:myapp:1.0.0'
}


text:
Q: Which filter fires upon setting a featured image When I am creating/editing a post and set the featured image, I'd like to display a message to the screen if the file dimensions or size are below a certain threshold.  But I want the featured image to still be set.
The message is simply a reminder to myself if I have set a featured image that doesn't meet certain criteria. I need to do this BEFORE saving the post, ideally right after I set the featured image.
I couldn't determine which add_filter I would use in my child functions.php to display a message at this point.
I found this example ( https://developer.wordpress.org/reference/hooks/admin_post_thumbnail_html/#user-contributed-notes ) but couldn't get it to work.
Do you have a recommendation?
UPDATE:  It turns out that admin_post_thumbnail_html filter no longer works in WordPress > 5.0 : https://core.trac.wordpress.org/ticket/45688    And doing something comparable since 5.0 seems convoluted/requires javascript:  https://github.com/danielbachhuber/gutenberg-migration-guide/blob/master/filter-admin-post-thumbnail-html.md

A: A nearly identical use case for your question is found in the WordPress documentation for the filter admin_post_thumbnail_html.
A filter hooked to this will receive the HTML for the admin screen as $content.  Modify and return this markup as you wish.
function filter_featured_image_admin_text( $content, $post_id, $thumbnail_id ){
    $help_text = '<p>' . __( 'Please use an image that is 1170 pixels wide x 658 pixels tall.', 'my_domain' ) . '</p>';
return $help_text . $content;
}

add_filter( 'admin_post_thumbnail_html', 'filter_featured_image_admin_text', 10, 3 );

Full details here:
https://developer.wordpress.org/reference/hooks/admin_post_thumbnail_html/


text:
Q: Jax-rs returning response before db operations I am using Rest Services with Jersey (Java EE 6)
When Client send a request to server, after some operations server send a response to client,
Unfortunately, I take too times which affect client in bad ways, so I am trying to send response to client from server before DB operations, but I could not design it. Is there any way to do DB operations after sending response. Actually my aim is that server returns response without waiting DB updates.
thanks

A: You could probably call an @Asynchronous EJB for the Database updates (http://docs.oracle.com/javaee/6/tutorial/doc/gkkqg.html), but then you'd have to handle the case where the DB updates failed.
You could return a temporary location to the client and so that it can send subsequent requests to get the status of the DB operations (success/in progress/failed).

A: Have a look at https://jersey.java.net/documentation/latest/async.html. The AsyncResponse can be used.


text:
Q: Why do other people get a 404 on my website? (Using PHP on it) So I have access to a hosting on a /www folder on my school's domain name, the problem is that only people on the school's network are able to reach that folder (which shouldn't happening, unless they have it restricted to VPN access only).
If that's the case, how would I go about modifying my .htaccess file to let outsiders access m y site or disable the VPN requirement? I remember fiddling with my htaccess file, that may have broke it but I dunno what happened. . . Any suggestions?

A: Unless the restriction was originally in the .htaccess file, you will not be able to add outside access directly.
Requiring VPN access is something that is done on a network-level (not a folder or user level, which is what you are trying to do).  This means you would have to ask the administrator to do this for you.  I doubt you'll have access to modifying any firewall, proxy, or routing tables the school has set in place.  Also, doing so may be illegal.
For a quick work-around, if you have access to a public folder, you can try adding symlink to your www directory.  This is unlikely to work as (a) I doubt you have access to a public directory, and (b) schools usually disable FollowSymLinks in Apache


text:
Q: Update VirtualBox without losing Guest .vdi Files I have VirtualBox "Version 5.1.4 r110228 (Qt5.5.1)" installed on a MacBook Air macOS Sierra version 10.12. Now I got an update message: http://download.virtualbox.org/virtualbox/5.1.6/VirtualBox-5.1.6-110634-OSX.dmg
But how can I update my VirtualBox version from 5.1.4 to 5.1.6? Obviously without losing my guests installations CentOS 7 64 and Windows 10 Enterprise.
Do I need to remove VirtualBox 5.1.4? And what happens with my Guest VDI installations?

A: Shut down all VMs and quit VirtualBox. Open VirtualBox-5.1.6-110634-OSX.dmg and double-click the installer in the mounted image. The installer will overwrite the old VirtualBox.app and some other files.
The VMs will be kept in place and won't be modified.
Later download the latest Extension Pack 5.1.6-110634 and install it in the existing VMs if necessary/possible.


text:
Q: Unsupervised gen_server doesn't call terminate when it receives exit signal gen_server documentation on Module:terminate callback says:

Even if the gen_server process is not part of a supervision tree, this
  function is called if it receives an 'EXIT' message from its parent.
  Reason is the same as in the 'EXIT' message.

Here is my handle_info and terminate function:
handle_info(UnknownMessage, State) ->
    io:format("Got unknown message: ~p~n", [UnknownMessage]),
    {noreply, State}.

terminate(Reason, State) ->
    io:format("Terminating with reason: ~p~n", [Reason]).

I start this server using gen_server:start. I assume when I call erlang:exit(Pid, fuckoff), it should call terminate callback function. But it shows:
Got unknown message: {'EXIT',<0.33.0>,fuckoff}

Which means it is calling handle_info. But when I call gen_server:stop, everything works as mentioned in documentation. I'm calling my gen_server from shell. Would you please clarify this?
[UPDATE]
Here is source code of decode_msg function inside gen_server. If it receives any 'EXIT' message it should call terminate function:
decode_msg(Msg, Parent, Name, State, Mod, Time, Debug, Hib) ->
    case Msg of
    {system, From, Req} ->
        sys:handle_system_msg(Req, From, Parent, ?MODULE, Debug,
                  [Name, State, Mod, Time], Hib);
    {'EXIT', Parent, Reason} ->
        terminate(Reason, Name, Msg, Mod, State, Debug);
    _Msg when Debug =:= [] ->
        handle_msg(Msg, Parent, Name, State, Mod);
    _Msg ->
        Debug1 = sys:handle_debug(Debug, fun print_event/3,
                      Name, {in, Msg}),
        handle_msg(Msg, Parent, Name, State, Mod, Debug1)
end.

In my case it doesn't call terminate function.
[UPDATE]
When I start gen_server using gen_server:start_link(), sending an exit signal using erlang:exit(Pid, Reason) will result in calling terminate call back function which is an expected behaviour. It seems there is a difference in interpreting an exit signal whether a process is linked to its parent or not.

A: Short answer:
If you call the exit/2 function from inside the gen_server actor, it behaves as expected based on the documentation and the terminate/2 callback will be called.
Long answer:
When you send the exit message from the shell, the Parent value of exit tuple is set to the shell process id, on the other hand when you start the gen_server process form shell its Parent value is set to its own process id, not the shell process id, therefore when it gets the exit message it doesn't match the second clause of the receive block in decode_msg/8 function so the terminate/6 function is not called and finally the next clause is matched which is calling handle_msg/5 function.
Recommendation:
For getting the terminate/3 callback called even by sending an exit message to the gen_server process, you can trap the exit message in handle_info/2 and then return with stop tuple as follows:
init([]) ->
    process_flag(trap_exit, true),
    {ok, #state{}}.

handle_info({'EXIT', _From, Reason}, State) ->
    io:format("Got exit message: ~p~n", []),
    {stop, Reason, State}.

terminate(Reason, State) ->
    io:format("Terminating with reason: ~p~n", [Reason]),
    %% do cleanup ...
    ok.

A: When you start your gen_server, its a simple process, so, erlang:exit/1 or erlang:exit/2 work as expected.

*

*If Pid is not trapping exits, Pid itself exits with exit reason Reason.

*If Pid is trapping exits, the exit signal is transformed into a message {'EXIT', From, Reason} and delivered to the message queue of Pid.

So, currently your code trap 'EXIT' signal because this one is send like any other message into the mailbox and match handle_info/2 wildcard pattern.
If you want more information about that, you can read gen_server source code and see how it works. You can also find your problem described in this code.


text:
Q: How to append two dataframe by overwriting the existing rows I have a dataframe say df. I have extracted a sample 5% rows from df and created a new dataframe df1 to do few manipulations in the dataset. Now I need to append df1 to df and overwrite the existing rows of df1 as it is a subset of df.
I tried to extract the rows that are not present in df using
    df2 <- subset(df, !(rownames(df) %in% rownames(df1[])))

But this didnt work.
Can anyone help please.

A: Save the filter and re-use it like so
set.seed(357)
xy <- data.frame(col1 = letters[1:5], col2 = runif(5))

  col1       col2
1    a 0.10728121
2    b 0.05504568
3    c 0.27987766
4    d 0.22486212
5    e 0.65348521

your.condition <- xy$col1 %in% c("c", "d")
newxy1 <- xy[your.condition, ]
newxy1$col2 <- 1:2

xy[your.condition, "col2"] <- newxy1$col2
xy

  col1       col2
1    a 0.10728121
2    b 0.05504568
3    c 1.00000000
4    d 2.00000000
5    e 0.65348521

A: You should always try to make a reproducible example so that it is easy for others to help you
I have tried to do that with the help of mtcars dataset
#Copied mtcars data into df
df = mtcars
# sample 5 rows from df
df1 = df[sample(1:nrow(df), 5), ]
# did few manipulations in the dataset
df1 = df1 * 2
# overwrite the existing rows of df1 as it is a subset of df
df[rownames(df1), ] <- df1


text:
Q: append values to a empty list in a column Consider the below dataframe, column c will always have an empty list in it. I need to compute few things and add it to the list, for example append values of column a and b to the empty list of column c
Given df

Expected output:

A: Let's try
df["Mark list"] = df.filter(regex='Mark\d+').agg(list, axis=1)

A: You'll want to use pandas.DataFrame.apply for this.
something like:
df["Mark list"] = df.apply(lambda row: [row["Mark1"], row["Mark2"]], axis=1)

A: You could convert the columns you want to append into lists (using a custom function and apply) and then simply add them to the list column. This will work for columns calculated on the fly as well.
import pandas as pd

df_vals = {"mark1": [23, 34, 45], "mark2": [45, 34, 12], "mark_list": [[] for i in range(3)]}

to_list = lambda x: [x]
df = pd.DataFrame(df_vals)
df["mark_list"] += df["mark1"].apply(to_list)
df["mark_list"] += df["mark2"].apply(to_list)
df["mark_list"] += (df["mark2"] + df["mark1"]).apply(to_list)  # works for columns created on-the-fly
df

Output:
   mark1  mark2     mark_list
0     23     45  [23, 45, 68]
1     34     34  [34, 34, 68]
2     45     12  [45, 12, 57]


text:
Q: Spark Java- reading gzip files from S3 ,mapToPair - takes a while to complete I am reading .gz files from s3 file 1(5GB) file2(1GB). The job takes a around and hour and when completed the driver node status is shown as running.
while reading the file with the below code
sc.textfile(".gz").mapToPair(..mapping to an object)

The above takes about an hour.
sc.textfile(".gz").repartition(500).mapToPair(..mapping to an object) and
sc.textfile(".gz").repartition(500).mapToPair(..mapping to an object).partitionByKey((new HashPartitioner(500))

The above takes the same amount of time.
I do a spark submit with below
--driver-memory  10G --num-executors 17 --executor-cores 5 --executor-memory 19G

What am I missing here?


text:
Q: Keras validation loss from model.fit() not expected On training my network using model.fit() in Keras with loss='mean_squared_error' in model.compile():
model.compile(loss='mean_squared_error', optimizer=optimizers.Adam(decay=0.00001), metrics=['accuracy'])
hist=model.fit(X, Y, epochs=200, batch_size=2000,  verbose=2, shuffle="batch", validation_data=(Xval,Yval))

I get this at the end:

Epoch 200/200 23s - loss: 1.2060 - acc: 0.5168 - val_loss: 1.5213 -
  val_acc: 0.5294

Now if I manually check the loss on the validation set by
pre=model.predict(Xval)
print(np.mean(np.square(pre-Yval)))

I get 1.4587 and not 1.5213.
Why are they different? Why am I not getting 1.5213 as calculated by model.fit()? Am I missing something here? Doesn't model.fit() go through the entire validation set?

A: After analyzing this situation I think I know why you could be experiencing this. Judging by the output you get on your epoch 200, we can see that your model metrics at that moment were:

loss: 1.2060 - acc: 0.5168 - val_loss: 1.5213 - val_acc: 0.5294

This means that on that last epoch, the feed-forward model you are training obtained a loss of 1.2060 (and a validation one of 1.5213).
However, the training algorithm still has to back-propagate that final loss to update your model weights. Only after iterating over inputs, then calculating metrics, and finally back-propagate weights, is that an epoch is considered to "end". The same process continues for any additional epochs.
That is why you get different losses when you evaluate after that final epoch, as your model changed a bit after that last back-propagation updated your model, learning a bit more than on the previous step. This would also explain why you obtained a lower loss value after epoch 200, as your model had one more epoch of successful training.

A: There could be two reasons for it:

*

*Output of your network is a vector while mse assumes that the output and target outputs are scalers. It would still work with vectors but the values are not reliable.

*You used a batch_size of 2000 during training while during prediction, the batch_size is 1. Try model.predict(Xval,batch_size=256). This will make sure that the conditions for the two are the same.


text:
Q: Geoprocessing a mapservice? I'm working on an application where a desired functionality is for users to start with the big picture (i.e. a single map layer), and gradually add more and more conditions to display only the area that satisfies all of them (i.e. the intersection of all the selected layers). I've been able to do this with Javascript on the client, but this has some performance issues and ideally I'd like to process this on the server.
The data I'm working with has already been prepared as polygonal layer or raster layer mapservices. Can I pull data directly from these services for processing?

A: I assume you want to use a geoprocessing service in your web app along with your map service. I give the Creating GP Services presentation at the ESRI UC, and show a demo of this. This is what I'd consider the least likely scenario in terms of GP services consuming data, thus it's not well documented. That said, you can use a geoprocessing service to work with a feature service. The feature service will stream the features over to the GP service for it to use. This requires some specific setup in both the tool and your javascript app.
First, your tool will need take a string as input. This string will represent the URL to a feature service with the query params.
For example, this would be the start code to your tool:
inFS = arcpy.GetParameterAsText(0)

featureset = arcpy.FeatureSet()
featureset.load(fs)

cnt = arcpy.GetCount_management(featureset)  #Or whatever tool/workflow

The web app would pass a URL like: (note the query here is 1=1 and f=json is critical.)
http://server:6080/arcgis/rest/services/fs1/FeatureServer/0/query?where=1%3D1&returnGeometry=true&returnIdsOnly=false&returnCountOnly=false&f=json

The last part is the web app itself. With the parameter named "inputFS" inside the tool itself, this is the code used in JS:
vals = "url to fs ...JS code sets this"
gp = new Geoprocessor(gpServiceUrl);
var params = {
    "inputFS" : vals
     };
console.log(params);
gp.submitJob(params,gpJobComplete,gpJobStatus,gpJobFailed);

In terms of a RASTER layer...there is a tool you'd need to use the Make Image Service Layer tool, but note that this tool only works off an ImageService, not a map service with a raster. The input parameter would again be a string (the URL itself).
As you work through this, keep in mind that the map/feature service and the GP service really have nothing to do with one another. Yes you want them to consume the same underlying data. But each service by itself has no knowledge of the other. Its the web app which glues these 2 services together by passing the URL as long as the GP service is setup properly to consume it.


text:
Q: Regex find comment word and replace comment1 I am looking for a regular expression  that would allow me to find and replace all instances with id="comment"  with adding incremental number.  Like id="comment1", id="comment2" and so on.  I have about 400+ instances in an HTML document.
Should I use notepad++?   What is the easiest way to do this?
Any help would be appreciated.  Thanks in advance

A: I'm not sure what might be the easiest way, but I highly doubt that'd be any regular expression.
Maybe, with a for loop we could do that. For instance, it would look something like this in PHP:
<?php

$str = file_get_contents('path/to/html/file/filename.html');
$arr = preg_split('/id="comment"/', $str);

foreach ($arr as $key => $value) {
    $count = $key + 1;
    if ($key == sizeof($arr) - 1) {
        $new_str .= $value;
    } else {
        $new_str .= $value . ' id="comment' . $count . '"';
    }
}

$str = file_put_contents('path/to/html/file/filename_modified.html', $new_str);


text:
Q: Creating a dynamic controller in codeigniter? Consider this scenario::-
 When i upload a view file in admin,A new menu is created in user side i.e dynamic creation of menus..
Ex: when admin upload a help view file, a help menu should appear in user side..is that
possible,the controller for help should be created dynamically.

A: Sure, PyroCMS does this. Take a look at the module management code, specifically details.php. You'll need to do some of the development yourself for this but my code will demonstrate how I've done it.
http://github.com/pyrocms/pyrocms

A: I got something like this working a while back pretty easily..
Take a look at the simple example of how I did this... It was for a Help Site.
The Model

<?php

class Template_model extends Model {

    function Template_model()
    {
        parent::Model();
    }

    function load_pages()
    {
        $data = array();
        $this->db->where('status',0);
        $this->db->order_by('sort', 'ASC');
        //$this->db->get('pages');
        $query = $this->db->get('pages');
        if ($query->num_rows() > 0){
            foreach ($query->result_array() as $row){
                $data[] = array(
                    "name" => $row['name'],
                    "url" => $row['url']
                );
            }
         }

        $query->free_result();
        return $data;
    }

}

The controller

<?php

class View extends Controller {

    function View()
    {
        parent::Controller();
    }

    function index()
    {
        redirect('view/topic/orders');
        //echo "oops";
    }

    function topic()
    {
        $page = $this->uri->segment(3);

        //get the page id
        $this->load->model('view_model');
        $id = $this->view_model->get_page_id_by_url($page);
        $id = $id['id'];

        //get the page title
        $data['title'] = $this->view_model->get_page_title($id);

        //load the post by page id
        $data['posts'] = $this->view_model->get_page_posts($id);

        //load the header
        $this->load->model('template_model');
        $data['pages'] = $this->template_model->load_pages();

        //load the view
        $data['main_content'] = 'view/page';
        $this->load->view('includes/template', $data);

    }

    function article()
    {
        $url = $this->uri->segment(3);

        //get the post by url
        $this->load->model('view_model');
        $data['post'] = $this->view_model->get_post_by_url($url);
        $id = $data['post']['page_id'];
        //print_r($data['post']);

        //get the page title
        $data['title'] = $this->view_model->get_page_title($id);

        //load the post by page id
        $data['posts'] = $this->view_model->get_page_posts($id);

        //load the header
        $this->load->model('template_model');
        $data['pages'] = $this->template_model->load_pages();

        //load the view
        $data['main_content'] = 'view/article';
        $this->load->view('includes/template', $data);
    }

}

/* End of file view.php */
/* Location: ./system/application/controllers/view.php */

and the view..

                <?php
                if(!empty($pages))
                {
                    foreach($pages as $page)
                    {
                        ?>

                            <li <?php if($on_page == $page['url']) { echo 'class="selected"'; }?>><a href="<?php echo base_url().'view/topic/'.$page['url'];?>"><?php echo $page['name'];?>

                        <?

                    }
                }?>

<li <?php if($on_page == 'admin') { echo 'class="selected"'; }?>><a href="<?php echo base_url();?>admin">Admin

<li <?php if($on_page == 'logout') { echo 'class="selected"'; }?>><a href="<?php echo base_url();?>logout">Logout

A: You should just route the links to a specific controller that handles menus


text:
Q: node.js + express.js: session handling with mongodb/mongoose Right now i'm storing my session data in the "memory store" which comes bundled with connect(express). But I want/have to change this for production.
The application is using mongodb and I installed mongoose to handle all db-communications.
e.g. Connect to the DB after initializing my app:
var mongo = require('mongoose');
mongo.connect('mongodb://localhost/myDb');
mongo.connection.on('open', function () {
  app.listen(3000);
}

I found the connect-mongodb module, but I don't know how to implement it using mongoose, or if it's actually possible?
I need to add something like this:
var mongoStore = require('connect-mongodb');
// ...
app.use(express.session({
  secret: 'topsecret',
  maxAge: new Date(Date.now() + 3600000),
  store: new mongoStore({ db: 'myDb' })
}));

or do I have to define my db connection a second time using the mongodb-module directly?

A: It looks like you could do this to setup connect-mongodb assuming your mongoose connection code above is run earlier:
app.use(express.session({
  secret: 'topsecret',
  maxAge: new Date(Date.now() + 3600000),
  store: new mongoStore({ db: mongoose.connections[0].db })
}));

A: in the end i'm using a bit of every answer that was given before:

*

*i switched from connect-mongodb to connect-mongo module

*i'm using a general conf object to store my configuration data

*there are two db connections because it's easier to handle for me (maybe changed later on, if/when a new version of mongoose/express comes out)

requirements:
var express = require('express'),
    MongoStore = require('connect-mongo')(express),
    mongo = require('mongoose');

conf object:
var conf = {
  db: {
    db: 'myDb',
    host: '192.168.1.111',
    port: 6646,  // optional, default: 27017
    username: 'admin', // optional
    password: 'secret', // optional
    collection: 'mySessions' // optional, default: sessions
  },
  secret: '076ee61d63aa10a125ea872411e433b9'
};

then i can configure it like this:
app.configure(function(){
  // ...
  app.use(express.cookieParser());
  app.use(express.session({
    secret: conf.secret,
    maxAge: new Date(Date.now() + 3600000),
    store: new MongoStore(conf.db)
  }));
  // important that this comes after session management
  app.use(app.router);
  // ...
});

and finally connect to mongodb a second time using mongoose:
var dbUrl = 'mongodb://';
dbUrl += conf.db.username + ':' + conf.db.password + '@';
dbUrl += conf.db.host + ':' + conf.db.port;
dbUrl += '/' + conf.db.db;
mongo.connect(dbUrl);
mongo.connection.on('open', function () {
  app.listen(3000);
});

A: So connect-mongodb does not use Mongoose, it uses the node-mongodb-native driver (i.e.: npm install mongodb). Mongoose also depends on this driver, so it should be present.
Looking at the code directly, you have to provide your DB connection information as a MongoStore object:
store: new mongoStore({ host: 'session_server', port: 27017, db: 'seesion', collection: 'sessions' })

Typically for this, you'll want to have some "config" object or variable that can be dynamically loaded (dev vs test vs prod). Then you pull the host/port/db/auth off of that config object.

A: For express 4x:
var express = require('express'),
    session = require('express-session'),
    MongoStore = require('connect-mongo')(session),
    mongo = require('mongoose');

var conf = {
  db: {
    db: 'myDb',
    host: '192.168.1.111',
    port: 6646,  // optional, default: 27017
    username: 'admin', // optional
    password: 'secret', // optional
    collection: 'mySessions' // optional, default: sessions
  },
  secret: '076ee61d63aa10a125ea872411e433b9'
};

app.configure(function(){
  app.use(express.cookieParser());
  app.use(session({
    secret: conf.secret,
    maxAge: new Date(Date.now() + 3600000),
    store: new MongoStore(conf.db)
  }));
});

var dbUrl = 'mongodb://';
dbUrl += conf.db.username + ':' + conf.db.password + '@';
dbUrl += conf.db.host + ':' + conf.db.port;
dbUrl += '/' + conf.db.db;
mongo.connect(dbUrl);
mongo.connection.on('open', function () {
  app.listen(3000);
});

session has been moved to it's own module, so you need to require it and use session when configuring the MongoStore.

A: Please include
app.use(express.cookieParser());

directly before
app.use(express.session({

Otherwise throws error as below,

TypeError: Cannot read property 'connect.sid' of undefined

A: You can pass in an object of connection details (host, username, password, etc.).
You can also pass in a connection url like mongodb://user:pass@host.com/db_name.
Both those methods will automatically start a new connection, regardless of whether or not you already have or will start a mongoose connection.
In the latest code, you can pass in a handle to an existing connection, an instance of mongodb.Db. With mongoose, this would be mongoose.connection.db. However, this code isn't in an actual release, and when I tried it, it didn't work. Probably not ready to be used yet (or untested).
I'm sure if you wait for the next release, you'll be able to pass in an existing mongoose connection. In the mean time you'll just need to accept having two connections, one from mongoose and one from connect-mongodb.
I got the connection info from https://github.com/tedeh/connect-mongodb and I got the handle information from viewing the source (relevant commit).

A: I just stumble across mongoose-session
Very lightweight and worked seamlessly for me. From github...
Installation
npm install mongoose-session

Use
var express = require('express');

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/db');

var app = express();

app.use(require('express-session')({
    key: 'session',
    secret: 'SUPER SECRET SECRET',
    store: require('mongoose-session')(mongoose)
}));


text:
Q: how to wrap text around an image in flash (actionscript 3) Hi I'm trying to set up a textfield which will wrap around an image using flash as3. Anyone have any pointers on how to accomplish that?

A: Thats what you are looking for: http://partlyhuman.com/lab/textwrapping/
Get it here: http://dispatchevent.org/roger/dynamic-text-wrapping-in-actionscript-3/


text:
Q: resource not found python textblob Resource u'tokenizers/punkt/english.pickle' not found The link below shows a similar issue except that his was solved downloading the packages and I already downloaded the packages...
Resource u'tokenizers/punkt/english.pickle' not found
But The weird thing is that I am able to run this on the terminal with no errors, but I have a js file doing a ajax call to this .py file and when it tries to execute it. It returns that error.. but Im not sure why
Errors more
Resource u'tokenizers/punkt/english.pickle' not found.  Please
    use the NLTK Downloader to obtain the resource:  >>>
    nltk.download()
    Searched in:
    - '/var/www/nltk_data'
    - '/usr/share/nltk_data'
    - '/usr/local/share/nltk_data'
    - '/usr/lib/nltk_data'
    - '/usr/local/lib/nltk_data'
    - u'

Traceback (most recent call last):
  File "/var/www/CSCE-470-Anime-Recommender/py/app.py", line 40, in <module>
    cl = NaiveBayesClassifier(Functions.classify(UserData))
  File "/usr/local/lib/python2.7/dist-packages/textblob/classifiers.py", line 192, in __init__
    self.train_features = [(self.extract_features(d), c) for d, c in self.train_set]
  File "/usr/local/lib/python2.7/dist-packages/textblob/classifiers.py", line 169, in extract_features
    return self.feature_extractor(text, self.train_set)
  File "/usr/local/lib/python2.7/dist-packages/textblob/classifiers.py", line 81, in basic_extractor
    word_features = _get_words_from_dataset(train_set)
  File "/usr/local/lib/python2.7/dist-packages/textblob/classifiers.py", line 63, in _get_words_from_dataset
    return set(all_words)
  File "/usr/local/lib/python2.7/dist-packages/textblob/classifiers.py", line 62, in <genexpr>
    all_words = chain.from_iterable(tokenize(words) for words, _ in dataset)
  File "/usr/local/lib/python2.7/dist-packages/textblob/classifiers.py", line 59, in tokenize
    return word_tokenize(words, include_punc=False)
  File "/usr/local/lib/python2.7/dist-packages/textblob/tokenizers.py", line 72, in word_tokenize
    for sentence in sent_tokenize(text))
  File "/usr/local/lib/python2.7/dist-packages/textblob/base.py", line 64, in itokenize
    return (t for t in self.tokenize(text, *args, **kwargs))
  File "/usr/local/lib/python2.7/dist-packages/textblob/decorators.py", line 38, in decorated
    raise MissingCorpusError()
MissingCorpusError:
Looks like you are missing some required data for this feature.

To download the necessary data, simply run

    python -m textblob.download_corpora

or use the NLTK downloader to download the missing data: http://nltk.org/data.html
If this doesn't fix the problem, file an issue at https://github.com/sloria/TextBlob/issues.

A: I moved the files into one of the directory's stated and had to change the permissions on one of the files I was including.


text:
Q: how to convert string that contains Base64 code of a image to Byte? i'm trying to save image in mongoose and my client convert that image to Base64 string and send it to server and i want to save that string to byte
because that string size is larger than image and i want to improve my performance
this is my Heroes collection
var mongoose = require('mongoose');
var Heroes = mongoose.model('Heroes',{
    Name:{
        type: String,
        required: true,
        trim: true
    },
    Heroes_Image:{
        type: String,
        required: true
    }
});

module.exports = {Heroes};

and this is my server side:
var {mongoose} = require('./db/mongoose');
var {Heroes} = require('./models/Heroes');
var net = require('net');
var db = mongoose.connection;
var clients = [];
net.createServer(function (socket) {
    // Identify this client
    socket.name = socket.remotePort

    // Put this new client in the list
    clients.push(socket);

    console.log(socket.name + " joined the chat");

    socket.on('data', function (data) {
        var j = JSON.parse(data);
        db.collection('Heroes').insertOne({
            Name: j.Name,
            Heroes_Image: j.Heroes_Image
        });// here save Base64 string of client image and it waste memory
    })
});

A: You could use Blob to save it as a file.


text:
Q: taking abspath from os module I have created symbolic links for bin and config directories to deployment folder as below:
/opt/app/bin -> /opt/deployments/v1/bin
/opt/app/config -> /opt/deployments/v1/config

I have a Python file as /opt/app/bin/pullfiles.py. I have tried with below code to take abspath of pullfiles.py file:
import os
working_dir = f'{os.path.split(os.path.dirname(os.path.realpath(__file__)))[0]}

It gives me below result:
/opt/deployments/v1

but I need actual result:
/opt/app