text:
Q: Mongoengine Django Rest Framework - Serializer Error - ReferenceField is not JSON serializable Everything works great until the ObjectID value of the ReferenceField no longer points to a valid document. Then The ObjectID is left as the value, and json doesn't know how to serialize this.
How do I deal with invalid ReferenceFields?
E.g.
class Food(Document):
    name = StringField()
    owner = ReferenceField("Person")

class Person(Document):
    first_name = StringField()
    last_name = StringField()
    ...

p = Person(...)
apple = Food(name="apple", owner=p)
p.delete() # might be the wrong method, but you get the idea

At this point, attempting to fetch a list of foods via the REST API will fail with the is not JSON serializable error, since apple.owner no longer points to an owner that exists.

A: Since you are using DRF with mongoengine, you must be using django-rest-framework-mongoengine.
Apparenly, its a bug in django-rest-framework-mongoengine. Check this open issue on Github which was reported recently regarding the same.
https://github.com/umutbozkurt/django-rest-framework-mongoengine/issues/91
One way is to write your own JSONEncoder for this. This link might help.
Another option is to use the json_util library of Pymongo. They provide explicit BSON conversion to and from json.
As per json-util docs:

This module provides two helper methods dumps and loads that wrap the
  native json methods and provide explicit BSON conversion to and from
  json. This allows for specialized encoding and decoding of BSON
  documents into Mongo Extended JSON's Strict mode. This lets you encode
  / decode BSON documents to JSON even when they use special BSON types.


text:
Q: PayPal SOAP API - Version is not supported I use .Net, and Visual Studio 2010.
I downloaded the WSDLs and corrected the maxOccurs error, and adding the WSDL as a Web Reference works just fine.
The problem occurs when I call SetExpressCheckout. The error simply says, Version is not supported. I have checked the version of the WSDL, which is 76.0 - and should be correct AFAIK.
The Web Service endpoint being used is this: https://api.sandbox.paypal.com/2.0/
Is there anywhere I need to specify the version, or is the service endpoint being used wrong?

A: If anyone has the same problem, you need to specify the version:
PayPalAPIAASoapBinding api = new PayPalAPIAASoapBinding();

// Service Provider's API Credentials
api.RequesterCredentials = new CustomSecurityHeaderType();
api.RequesterCredentials.Credentials = new UserIdPasswordType();
api.RequesterCredentials.Credentials.Username = this.Username;
api.RequesterCredentials.Credentials.Password = this.Password;
api.RequesterCredentials.Credentials.Signature = this.ApiSignature;

// The merchant's PayPal e-mail address (3rd party authentication)
api.RequesterCredentials.Credentials.Subject = this.CustomerId;

SetExpressCheckoutReq req = new SetExpressCheckoutReq();
req.SetExpressCheckoutRequest = new SetExpressCheckoutRequestType();
req.SetExpressCheckoutRequest.SetExpressCheckoutRequestDetails = new SetExpressCheckoutRequestDetailsType();
req.SetExpressCheckoutRequest.Version = "74.0";

Right now the Sandbox runs in v 74.0, and production in 76.0. PayPal doesn't always run same versions across their environments.

redpajama_set_name: RedPajamaStackExchange


text:
Q: wpf automatic event generation stub Why visual studio generates event method with number postfix, Ex: instead generating Click event of a button as button_Click, it generates button_Click_1 where there is no click event present.

A: Well am quite certain you have a stale button_Click somewhere.. find it and remove it


text:
Q: SQL NOW() in long running query Say I have long running update query
update some_table
set modification_time = now()
where (something incredibly complex);

What will be values of modification_time in some_table? Will they be same or different (say, it took 2 days for query to execute).
And if they will be different, how do I write this query so that they all are same?

A: They will all be the same, since NOW() is locked in at the time of query start.
Is this too short as an answer?
Okay, more info MySQL reference for NOW()

NOW() returns a constant time that indicates the time at which the statement began to execute. (Within a stored function or trigger, NOW() returns the time at which the function or triggering statement began to execute.) This differs from the behavior for SYSDATE(), which returns the exact time at which it executes.

It is actually more interesting to read the manual entry for SYSDATE() however, which contains this snippet
mysql> SELECT NOW(), SLEEP(2), NOW();
+---------------------+----------+---------------------+
| NOW()               | SLEEP(2) | NOW()               |
+---------------------+----------+---------------------+
| 2006-04-12 13:47:36 |        0 | 2006-04-12 13:47:36 |
+---------------------+----------+---------------------+

mysql> SELECT SYSDATE(), SLEEP(2), SYSDATE();
+---------------------+----------+---------------------+
| SYSDATE()           | SLEEP(2) | SYSDATE()           |
+---------------------+----------+---------------------+
| 2006-04-12 13:47:44 |        0 | 2006-04-12 13:47:46 |
+---------------------+----------+---------------------+

What's so interesting you ask.. notice that you can SLEEP in a query??  Consider this query (the sub-query just emulates a 3-record table)
select *, now(), sleep(2), sysdate()
from (select 1 N union all select 2 union all select 3) M

You get:
N   now()           sleep(2)  sysdate()
1   2011-04-02 23:55:27   0   2011-04-02 23:55:29
2   2011-04-02 23:55:27   0   2011-04-02 23:55:31
3   2011-04-02 23:55:27   0   2011-04-02 23:55:33


text:
Q: Lazy `SignalProducer` that fetches more data asynchronously when all data has been consumed Let's imagine that we can fetch a fixed number of messages asynchronously (one request, containing N elements)
func fetchMessages(max: UInt, from: Offset) ->  SignalProducer<Message,NoError>

Now, I'd like to turn this into an unbounded SignalProducer that will lazily call fetchMessages when the previous stream completes.
func stream(from: Offset) -> SignalProducer<Message, NoError> {
    // challenge is to implement this function
}

An initial idea that could work, but that would still require pre-computing all the ranges would be to genericize the following code
func lazyFetchFrom(from: Offset) -> SignalProducer<Message,NoError> {
        return SignalProducer<Message,NoError> { (observer, disposable) in
            fetchMessages(from).start(observer)
        }
    }

    let lazyStream =
        fetchMessages(1000, from)
            .concat(lazyFetchFrom(from + 1000))
            .concat(lazyFetchFrom(from + 2000))
            .... // could probably be done generically using a flatMap

Now, I'd like to go one step further and evaluate the next call to lazyFetchFrom once the previous values have been consumed. Is that possible?
Thanks
PS: to be clear, my main concern is to provide some sort of backpressure so that the producer doesn't produce too quickly compared to the consumer
Edit: here is my latest attempt at implementing some backpressure. However, when we observeOn the signal, the backpressure disappears, and everything is queued in memory

A: - (RACSignal *)allContentFromId:(NSInteger)contentId afterDate:(NSDate *)date fetchSize:(NSInteger)fetchSize {
    RACSignal *signalNextPagination = [self nextPaginationAllContentFromId:contentId afterDate:date fetchSize:fetchSize];

    //in signalNextPagination will be send next fetch size data and send complete only after downloaded all data
    //so we used aggregate

    return [signalNextPagination aggregateWithStart:@[] reduce:^id(NSArray *before, NSArray *next) {
        return [before arrayByAddingObjectsFromArray:next];
    }];
}

- (RACSignal *)nextPaginationAllContentFromId:(NSInteger)contentId afterDate:(NSDate *)date fetchSize:(NSInteger)fetchSize {

    //command will be send one fetch request
    //after recv data in command need try size fetch
    //if size eq fetch size, so need repeat command with new offset

    RACCommand *command = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSDate *date) {
        return [self requestContentFromId:contentId afterDate:date limit:fetchSize];
    }];
    command.allowsConcurrentExecution = YES;

    RACSignal *download = [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [[command.executionSignals flattenMap:^RACStream *(id value) {
            return value;
        }] subscribeNext:^(NSArray *datas) {
            [subscriber sendNext:datas];
            if ([datas count] == fetchSize) {
                NSDate *date = [[datas firstObject] pubDate];
                [command execute:date];
            } else {
                [subscriber sendCompleted];
            }
        } error:^(NSError *error) {
            [subscriber sendError:error];
            [subscriber sendCompleted];
        }];

        [command execute:date];
        return nil;
    }];

    return download;
}


text:
Q: How to stop file being inserted into server
Possible Duplicate:
files get uploaded just before they get cancelled

I have a situation when it comes to cancelling a file upload. What is suppose to happen is that if the user clicks on the "Cancel" button, then it will go to script below and remove the file from the server and delete the file's records from the database:
cancelaudio.php
<?php
session_start();
 // connect to the database
 include('connect.php');

  /* check connection */
  if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    die();
  }

  unlink("AudioFiles/" . $_SESSION['AudioFile']);  //undefined notice

$delete = $mysqli->prepare('DELETE FROM Audio WHERE AudioId = ?');
$delete->bind_param("i",$_SESSION['lastAudioID']);
$delete->execute();

$deleteaud = $mysqli->prepare('DELETE FROM Audio_Question WHERE AudioId = ?');
$deleteaud->bind_param("i",$_SESSION['lastAudioID']);
$deleteaud->execute();

?>

Now this is the situation I am having:
If I clean my cookies, it means obviously I have no files stored my $_SESSION variable. Now if I try to upload a file (first file) but then cancel it, then I get an undefined index notice for "AudioFile". This is fair as obviously I have no file stored in that $_SESSION variable. But the problem is that it does not perfrom the unlink() and DELETE statement in the code above so it will display the record of the file and still uploads it.
So what is happening is that until I have one file in the server and a file stored in the $_SESSION['AudioFile'], it would not remove the file from the server and and it would delete the record from the database.
So what my question is that what do I need to do so that if there is no file in the $_SESSION['AudioFile'] and the user uploads and then cancels a file, how can I stop it from inserting the file into the server and inserting the database record?
Below is the code where it uploads the files and inserts the data into the database:
audioupload.php
<?php

session_start();

ini_set('display_errors',1);
error_reporting(E_ALL);
// connect to the database
include('connect.php');

/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}

$result = 0;

if( file_exists("AudioFiles/".$_FILES['fileAudio']['name'])) {
$parts = explode(".",$_FILES['fileAudio']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;

while( file_exists("AudioFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileAudio']['name'] = $base."_".$n.".".$ext;

move_uploaded_file($_FILES["fileAudio"]["tmp_name"],
"AudioFiles/" . $_FILES["fileAudio"]["name"]);
$result = 1;

}
else
{
move_uploaded_file($_FILES["fileAudio"]["tmp_name"],
"AudioFiles/" . $_FILES["fileAudio"]["name"]);
$result = 1;
}

$audiosql = "INSERT INTO Audio (AudioFile)
VALUES (?)";

if (!$insert = $mysqli->prepare($audiosql)) {
// Handle errors with prepare operation here
}

//Dont pass data directly to bind_param store it in a variable
$insert->bind_param("s",$aud);

//Assign the variable
$aud = 'AudioFiles/'.$_FILES['fileAudio']['name'];

$insert->execute();

if ($insert->errno) {
// Handle query error here
}

$insert->close();

$lastAudioID = $mysqli->insert_id;

$_SESSION['lastAudioID'] = $lastAudioID;
$_SESSION['AudioFile'] = $_FILES["fileAudio"]["name"];

$audioquestionsql = "INSERT INTO Audio_Question (AudioId, QuestionId)
VALUES (?, ?)";

if (!$insertaudioquestion = $mysqli->prepare($audioquestionsql)) {
// Handle errors with prepare operation here
echo "Prepare statement err audioquestion";
}

$qnum = (int)$_POST['numaudio'];

$insertaudioquestion->bind_param("iii",$lastAudioID, $qnum);

$insertaudioquestion->execute();

if ($insertaudioquestion->errno) {
// Handle query error here
}

$insertaudioquestion->close();

?>

Below is the HTML form for the file input:
<form action='audioupload.php' method='post' enctype='multipart/form-data' target='upload_target_audio' onsubmit='return audioClickHandler(this);' class='audiouploadform' >

Audio File: <input name='fileAudio' type='file' class='fileAudio' />

<input type='submit' name='submitAudioBtn' class='sbtnaudio' value='Upload' />

<input type='hidden' class='numaudio' name='numaudio' value='" + GetFormAudioCount() + "' />

<input type='reset' name='audioCancel' class='audioCancel' value='Cancel' />

</form>

Finally below is the jquery function where if the user clicks on the "Cancel" button while the file is uploading, it will simply change the iframe source to "cancelaudio.php":
function startAudioUpload(audiouploadform){
$(audiouploadform).find('.audiof1_upload_process').css('visibility','visible');
$(audiouploadform).find('.audiof1_upload_form').css('visibility','hidden');
sourceAudioForm = audiouploadform;

$(audiouploadform).find(".audioCancel").on("click", function(event) {
$('.upload_target_audio').get(0).contentwindow
$("iframe[name='upload_target_audio']").attr("src", "cancelaudio.php");
return stopAudioUpload();
});

return true;
}

A: To get rid of your undefined index stuff, plus make your script a lot more robust, you SHOULD add error checking. Even a simple
if ($_FILES['fileAudio']['error'] === UPLOAD_ERR_OK) {
   ... successful upload ...
}

would reduce a lot of your problems. Right now your code simply assumes a successful upload, without even bothering to check if an upload was event attempted.
The various error codes for failure are defined here: http://php.net/manual/en/features.file-upload.errors.php


text:
Q: I have an error when I try to Build a signed APK
When I need to build the app, Android Studio gives me the error
I tried to build the app without the icon and it worked successfully
I tried to change the icon and it didn't work

A: The mipmap is been giving me a lot issues as well sometimes it works sometimes it doesn't. The way I get around it is place the icon using drawable/icon instead of using mipmap. It will place the icon correctly.
You can try to use mipmap but I notice that referencing your icon in drawable is a small work around.
Also if you have a simple icon, remove the background and then add it to the drawable folder then create the image asset. That is how I use mipmap. I noticed that if my icon is custom and has a background it seems to not work right.
Option one: reference the icon directly with the png in drawable. But leave the round mipmap icon style.
Option two: remove the background from the icon. I use an online background remover as long as there is no white in the icon because it will remove that part of the icon. Then add the icon to the drawable and add image asset as normal.
The reason why it throws this error. Is even though you have it in Android Studio for some reason it doesn't build in the file structure. You can also check the file structure in the computer and see the image is not there. Hence the reason for the error.


text:
Q: Rclone Failed to sync: googleapi: Error 403: We're sorry, but this service is not available in your location, forbidden I want to backup my files into google drive using rclone by this command:
sudo rclone sync  "/media/so/ACAC8B5FAC8B2346/Company Informations/مدارک شرکت GSH/اداری (copy)"  gsh:Company_Informations/office_files  --checkers 3  --log-file /home/so/Desktop/trash/rclone_sync.log -v --transfers 3

So i get this error:
Failed to sync: googleapi: Error 403: We're sorry, but this service is not available in your location, forbidden

So entire log file is this kind:
2019/12/30 21:16:04 Failed to create file system for "gsh_email:drive": drive: failed when making oauth client: error opening service account credentials file: open ss: no such file or directory
2019/12/30 21:52:45 ERROR : : error reading destination directory: googleapi: Error 403: We're sorry, but this service is not available in your location, forbidden
2019/12/30 21:52:45 INFO  : GCS bucket Company_Informations path office_files: Waiting for checks to finish
2019/12/30 21:52:45 INFO  : GCS bucket Company_Informations path office_files: Waiting for transfers to finish
2019/12/30 21:52:45 ERROR : GCS bucket Company_Informations path office_files: not deleting files as there were IO errors
2019/12/30 21:52:45 ERROR : GCS bucket Company_Informations path office_files: not deleting directories as there were IO errors
2019/12/30 21:52:45 ERROR : Attempt 1/3 failed with 1 errors and: googleapi: Error 403: We're sorry, but this service is not available in your location, forbidden
2019/12/30 21:52:45 ERROR : : error reading destination directory: googleapi: Error 403: We're sorry, but this service is not available in your location, forbidden
2019/12/30 21:52:45 INFO  : GCS bucket Company_Informations path office_files: Waiting for checks to finish
2019/12/30 21:52:45 INFO  : GCS bucket Company_Informations path office_files: Waiting for transfers to finish
2019/12/30 21:52:45 ERROR : GCS bucket Company_Informations path office_files: not deleting files as there were IO errors
2019/12/30 21:52:45 ERROR : GCS bucket Company_Informations path office_files: not deleting directories as there were IO errors
2019/12/30 21:52:45 ERROR : Attempt 2/3 failed with 1 errors and: googleapi: Error 403: We're sorry, but this service is not available in your location, forbidden
2019/12/30 21:52:46 ERROR : : error reading destination directory: googleapi: Error 403: We're sorry, but this service is not available in your location, forbidden
2019/12/30 21:52:46 INFO  : GCS bucket Company_Informations path office_files: Waiting for checks to finish
2019/12/30 21:52:46 INFO  : GCS bucket Company_Informations path office_files: Waiting for transfers to finish
2019/12/30 21:52:46 ERROR : GCS bucket Company_Informations path office_files: not deleting files as there were IO errors
2019/12/30 21:52:46 ERROR : GCS bucket Company_Informations path office_files: not deleting directories as there were IO errors
2019/12/30 21:52:46 ERROR : Attempt 3/3 failed with 1 errors and: googleapi: Error 403: We're sorry, but this service is not available in your location, forbidden
2019/12/30 21:52:46 Failed to sync: googleapi: Error 403: We're sorry, but this service is not available in your location, forbidden

So what is your recommendation to solve this problem?

A: 403 with that message indicates Google does not offer this service to your country or location.
Given the geolocation from your VPN question placing you in Iran, this is likely due to sanctions in place on your country and Google is abiding by the law of those sanctions and disallowing Iraq access to this service.  Unfortunately, this is Google's decision and there is nothing we can really do to assist you in this matter other than suggest you use a VPN (which may or may not also forbid Iraq from connecting)


text:
Q: Dynamics CRM 2016 tracking emails correctly but Outlook showing as not tracked. We're using Microsoft Dynamics CRM 2016 with Outlook (Office 365). All very new so we have the latest versions of each. Users track emails from Outlook using the 'Set Regarding' function. The tracking is working fine, with 1 major exception. When someone replies to a tracked email, the reply is tracked correctly in CRM, however in the Outlook client there is nothing to show the email is tracked. I.e. normally you would expect to see the little CRM icon (green and blue people), and also a CRM at the footer of the email with details about the tracking. Instead it just looks like a normal email, notwithstanding that it is indeed tracked in CRM. The original tracked email shows correctly (with the green and blue icon and the CRM footer). It's just the replies that are not appearing correctly.
Any help would be very appreciated.

A: Unfortunately, there are two tracking methods for Dynamics CRM: automatic tracking and manual tracking.
When an email is tracked by the automatic tracking, the UI in CRM for Outlook (Outlook add-in) will not reflect that.
We are planning to improve this when using the new CRM App for Outlook (office app).
Ben


text:
Q: Django-Access dynamically created model I was working on a Django app which requires creating tables dynamically.
def dcreatedb(request):
    dbname = request.GET['dbname']
    attrs = {
        'name': models.CharField(max_length=20),
        '__module__': 'data.models'
    }
    model = type(dbname, (models.Model,), attrs)
    with connection.schema_editor() as schema_editor:
        schema_editor.create_model(model)
    return HttpResponse('done')

The above dcreatedb view creates a model dynamically. But I need to access the same model in some other view but the model is not in the models.py file in the app and created dynamically by the dcreatedb view.
def dinsertdb(request):
    dbname = request.GET['dbname']
    # access the dbname model and do some work
    return HttpResponse('work done')

for instance let us suppose a model named books is created by the dcreatedb view dynamically, and now I want to access the same model in the dinsertdb view.(Both the dcreatedb model and the dinsertdb models are in the same views.py file under the same app.)
How can this be done?
Thanks


text:
Q: Docker executor in Gitlab Runner resolves database to localhost instead of alias, via Symfony's Doctrine I have a symfony project with the following .gitlab-ci.yml file:
test:
    image: registry.gitlab.com/MYIMAGEURL:latest

    variables:
        # POSTGRES - Use the values from the .env.test file.
        POSTGRES_DB: db
        POSTGRES_USER: postgres
        POSTGRES_PASSWORD: asdfasdf

        # MISC
        APP_ENV: test

    services:
        -   name: postgres:10
            # "postgresql" is what we use in the .env.test file
            alias: postgresql

    before_script:
        - cd my-project

    script:
        - cp .env.test .env
        - composer install

Symfony's cache:clear --env=test fails when doctrine tries to make a connection:
SQLSTATE[08006] [7] could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?
  could not connect to server: Address not available
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?

My .env.test file has the following URL:
DATABASE_URL=pgsql://postgres:asdfasdf@postgresql:5432/db

So I know it should be looking for the postgresql host.
I further confirmed the doctrine config using php bin/console debug:config doctrine, and the defined default connection URL is: url: '%env(resolve:DATABASE_URL)%'. I also set and confirmed that the cache:clear command is being run in the test environment. Why is resolve:DATABASE_URL resolving to localhost?
I don't know what else to try. It always connects to localhost rather than postgresql. What else should I try?
EDIT: Additionally, I followed the guide on testing a job locally using manual service links and everything runs fine.

A: The issue was the APP_ENV: test config variable. The bin/console file had code in it that checked if this env variable is set, and only if NOT set would it load the .env files. After removing this variable dotenv loaded the .env files as desired.


text:
Q: Receiving D2C messages from an IoT Hub in browser I am working on a simple dashboard for showing IoT data in a browser.
So far, I was using the Paho MQTT client library and a public MQTT broker to receive data. However, I'd like to use the Azure IoT Hub from now on.
The data I'm sending is just simple temperature and humidity values.
I already found out that I can't connect to the IoT Hub via MQTT. So my question is:
Is there a possibility to connect (eg. using javascript) directly to IoT Hub and read the data?
If not, what's my best option?
I thought about saving the messages to an SQL Database and reading from that, but that seems quite complicated for what should be a simple IoT use case (showing real-time data)
Thank you in advance!

A: You can connect to IoT Hub via MQTT.  Please take a look at this documentation for detail.  We also have a Node.js SDK for connecting to IoT Hub if you don't want to deal with MQTT directly.  I know you are working on your own dashboard, but have you looked at Azure IoT Solutions Accelerator?  It's completely open source and you can modify it as you want.


text:
Q: How to edit a command autocomplete template in Overleaf? In Overleaf, commands such as \begin{figure} and \begin{table} will automatically add a template after using the auto-complete option, such as:
\begin{table}[]
    \centering
    \begin{tabular}{c|c}
         &  \\
         &
    \end{tabular}
    \caption{Caption}
    \label{tab:my_label}
\end{table}

My question is if it is possible to change these templates?
For example, I want to use \begin{tabularx} instead, and put the \caption above the table.


text:
Q: How to use a custom tcp encoder/decoder in spring xd Documentation shows how to use a small set of tcp decoders/ encoders (CR,LF, a few others )
I've got payloads separated by 2 bytes  0x1C 0x0D.
What's the easiest way to specify this in the stream definition ?
Or will I have to create a custom source/sink as shown here?
http://docs.spring.io/spring-xd/docs/0.1.x-SNAPSHOT/reference/html/creating-a-sink-module.html

A: Decoders are used in sources, not sinks; sinks use encoders.
Yes, you need to customize the source/sink.
Please use a newer version of XD than 0.1.x; the current release is 1.2.0.
See the Spring Integration documentation about creating custom encoders/decoders (usually based on the AbstractByteArraySerializer).


text:
Q: The Viewmodel is not destroyed even when the oncleared is called there is a Nested graph inside them two fragments (A,B) with 3 viewmodels
1 sharedviewmodel and 2 individual
the individual viewmodel is not getting destroyed even when the   findNavController().popBackStack()
is called which inturn calls onCleared  of viewmodel
this is initialization inside one of the fragment
B'sVm =
ViewModelProvider(this).get(B'sViewModel::class.java)
There is a recyclerview inside the B's fragment which take the list from viewmodel(through binding) (after network call) then called findNavController().popBackStack() to go to A's Fragment(the onCleared of viewmodel is called ) Then navigated to Fragment B . the previous list is still there .
Fragment A->Fragment B(list the data) -> Fragemnt A-> Fragment B(previous list still there )


text:
Q: Using a loop in a CUDA graph I have kernel A, B, and C which need to be executed sequentially.
A->B->C
They are executed in a while loop until some condition will be met.
while(predicate) {
    A->B->C
}

The while loop may be executed from 3 to 2000 times - information about a fact that a loop should stopped is produced by kernel C.
As the execution is related to multiple invocations of relatively  small kernels CUDA Graph sounds like a good idea. However, CUDA graph implementation I have seen are all linear  or tree-like without loops.
Generally, if the loop is not possible, the long chain of kernels of the length 2000 with possibility of early stop invoked from kernel C would be also OK. However, is it possible to stop the graph execution in some position by the call from inside of the kernel?

A: CUDA graphs have no conditionals. A vertex of the graph is visited/executed when its predecessors are complete, and that's that. So, fundamentally, you cannot do this with a CUDA graph.
What can you do?

*

*Have a smaller graph for the loop iteration, and repeatedly schedule it.

*Have A, B and C start their execution by checking the loop predicate - and skip all work if it holds. With that being the case, you can schedule many instances of A->B->C->A->B->C etc - which, starting at some point, will  do nothing.

*Don't rely on the CUDA graphs API. It's not a general-purpose parallel execution mechanism. :-(


text:
Q: multiline random text using js I'm trying to make a random text generator that makes more than one line but it always goes on the same line on the HTML page (I have tried \n already and it doesn't work).
I tested it on chrome, but can I get some help please if its possible to even do.
Here the code I used: (live demo)
function rtg(maxChar, maxLines) {
var ranChar = "";
var count;
var alphabet = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,r,s,t,u,v,w,x,y,z,1,2,3,4,56,7,8,9,0".split(",");

for (var i = 0; i < maxLines; i++) {
     var rand = null;
     for (var x = 0; x < maxChar; x++) {
         count++;
         rand = Math.floor(Math.random() * alphabet.length);
         ranChar += alphabet[rand];
         if (maxChar == count) {
          //this part i need help with
             ranChar += '\n'
             count = 0;
         }
      }
   }
}

A: \n is not recognised in HTML unless you use the css property white-space: pre-line (or put your text inside of a
Your Text Here
 tag. Another way (probably preferable) would be to add '
' instead of '\n' when you want to go to the next line

A: You can add a new line in a string with "\n"

A: There are some unnecessary variables here, so I've simplified your code a bit. i and x are your counts, so you don't really need a count variable. You should also use
 instead of \n if you're putting it in the HTML of the page.

function rtg(maxChar, maxLines) {
  var lines = "";
  for(var i = 0; i < maxLines; i++) {
    if(i > 0) lines += "
";
    for (var x = 0; x < maxChar; x++) lines += rando("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnoprstuvwxyz1234567890");
  }
  return lines;
}

window.addEventListener("load", function(){
  document.getElementById("result").innerHTML = rtg(12, 5);
});

This code uses randojs.com to simplify randomness, so if you want to use this code, just make sure you have this in the head tag of your html document:

In response to your comment:
if you want to link up your own external js file, you can make two files in the same directory: 1 html file, and 1 js file named "script.js". in the HTML file, use this as your HTML code:

in the script.js file, use this:
function rtg(maxChar, maxLines) {
  var lines = "";
  for(var i = 0; i < maxLines; i++) {
    if(i > 0) lines += "
";
    for (var x = 0; x < maxChar; x++) lines += rando("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnoprstuvwxyz1234567890");
  }
  return lines;
}

window.addEventListener("load", function(){
  document.getElementById("result").innerHTML = rtg(12, 5);
});

This has been tested and is working properly.


text:
Q: Altering trained images to train neural network I am currently trying to make a program to differentiate rotten oranges and edible oranges solely based on their external appearance. To do this, I am planning on using a Convolutional Neural Network to train with rotten oranges and normal oranges. After some searching I could only find one database of approx. 150 rotten oranges and 150 normal oranges on a black background (http://www.cofilab.com/downloads/). Obviously, a machine learning model will need at least few thousand oranges to achieve an accuracy above 90 or so percent. However, can I alter these 150 oranges in some way to produce more photos of oranges? By alter, I mean adding different shades of orange on the citrus fruit to make a "different orange." Would this be an effective method of training a neural network?

A: Data augmentation is what you are looking for. In you case you can do different things:

*

*Apply filters to get slightly different image, as has been said you can use gaussian blur.

*Cut the orange and put it in different backgrounds.

*Scale the oranges with different scales factors.

*Rotate the images.

*create synthetic rotten oranges.

*Mix all different combinations of the previous mentioned. With this kind of augmentation you can easily create thousand of different oranges.
I did something like that with a dataset of 12.000 images and I can create 630.000 samples

A: That is indeed a good way to increase your data set. You can, for example, apply Gaussian blur to the images. They will become blurred, but different from the original. You can invert the images too. Or, in last case, look for new images and apply the cited techniques.

A: It is a very good way to increase the number of date you have. What you'll do depends on your data. For example, if you are training on data obtained from a sensor, you may want to add some noise to the training data so that you can increase your dataset. After all, you can expect some noise coming from the sensor later on.
Assuming that you will train it on images, here is a very good github repository that provides means to use those techniques. This python library helps you with augmenting images for your machine learning projects. It converts a set of input images into a new, much larger set of slightly altered images.
Link: https://github.com/aleju/imgaug
Features:

*

*Most standard augmentation techniques available.

*Techniques can be applied to both images and keypoints/landmarks on
images. Define your augmentation sequence once at the start of the
experiment, then apply it many times.

*Define flexible stochastic ranges for each augmentation, e.g. "rotate
each image by a value between -45 and 45 degrees" or "rotate each
image by a value sampled from the normal distribution N(0, 5.0)".

*Easily convert all stochastic ranges to deterministic values to
augment different batches of images in the exactly identical way
(e.g. images and their heatmaps).

A: Data augmentation is really good way to boost training set but still not enough to train a deep network end to end on its own given the possibility that it will overfit. You should look at domain adaptation where you take a pretrained model like inception which is trained on imagenet dataset and finetune it for your problem. Since you have to learn only parameters required to classify your use case, it is possible to achieve good accuracies with relatively less training data available. I have hosted a demo of classification with this technique here. Try it out with your dataset and see if it helps. The demo takes care of pretrained model as well as data augmentation for dataset that you will upload.


text:
Q: How to use ruby 2.7 on my Ruby on Rails applications I updating my applications that are running in AWS OpsWorks so I need to use Ruby 2.7, but the newest version showing is 2.6.
Can I force my stack to use 2.7 version?

A: According to this page: https://docs.aws.amazon.com/opsworks/latest/userguide/workingcookbook-ruby.html
Version 2.7 is not yet available for OpsWorks.


text:
Q: States pointing to the new contract version still tries to deserialise old contract? I have a scenario where I have upgraded my obligations from V1 to V2 and pointed to the correct V2 contracts successfully. Next I tried to do an SettleObligation on these upgraded V2 states. When the transaction is formed and sent out in CollectSignatureFlow, there's a java.lang.NoSuchMethodError found on my isGreaterThan method which is called in the verifySettle command in the contract.
This particular function initially exist on the package "com.example.base" in a file BaseHelper.kt, along the way, in V2, we migrated the function to another file MathHelper.kt, this move did not cause any unresolved references because the package is the same.
Would like to understand:

*

*Does the contract reference the function location by file name instead of package name? and it's unchangeable once you compile the contract-v1.jar?

*Why do V2 states still try to deserialise V1 contracts? Is this being done via walking the chain somehow?

Stack trace below

[WARN ] 2018-11-13T00:05:12,777Z [Node thread-1] flow.[cd538d42-1715-4ed3-bde6-38eca94ef79f].run - Flow ended due to receiving exception {}
net.corda.core.contracts.TransactionVerificationException$ContractRejection: Contract verification failed: com.example.base.BaseHelperKt.isGreaterThan(Ljava/math/BigDecimal;Ljava/math/BigDecimal;)Z,
contract: com.example.contracts.ObligationContractV1, transaction: 8B8780A16D330A93A361F747B77C227442BD310C9DAAA561376DED69F580C794
        at net.corda.node.services.statemachine.FlowStateMachineImpl.erroredEnd(FlowStateMachineImpl.kt:497) ~[corda-node-3.2.1847-corda.jar:?]
        at net.corda.node.services.statemachine.FlowStateMachineImpl.confirmNoError(FlowStateMachineImpl.kt:481) ~[corda-node-3.2.1847-corda.jar:?]
        at net.corda.node.services.statemachine.FlowStateMachineImpl.waitForMessage(FlowStateMachineImpl.kt:444) ~[corda-node-3.2.1847-corda.jar:?]
        at net.corda.node.services.statemachine.FlowStateMachineImpl.receiveInternal(FlowStateMachineImpl.kt:376) ~[corda-node-3.2.1847-corda.jar:?]
        at net.corda.node.services.statemachine.FlowStateMachineImpl.receive(FlowStateMachineImpl.kt:229) ~[corda-node-3.2.1847-corda.jar:?]
        at net.corda.node.services.statemachine.FlowSessionImpl.receive(FlowSessionImpl.kt:44) ~[corda-node-3.2.1847-corda.jar:?]
        at net.corda.node.services.statemachine.FlowSessionImpl.receive(FlowSessionImpl.kt:48) ~[corda-node-3.2.1847-corda.jar:?]
        at net.corda.core.flows.CollectSignatureFlow.call(CollectSignaturesFlow.kt:290) ~[corda-core-3.2.1847-corda.jar:?]
        at net.corda.core.flows.CollectSignatureFlow.call(CollectSignaturesFlow.kt:135) ~[corda-core-3.2.1847-corda.jar:?]
        at net.corda.core.flows.FlowLogic.subFlow(FlowLogic.kt:290) ~[corda-core-3.2.1847-corda.jar:?]
        at net.corda.core.flows.CollectSignaturesFlow.call(CollectSignaturesFlow.kt:114) ~[corda-core-3.2.1847-corda.jar:?]
        at net.corda.core.flows.CollectSignaturesFlow.call(CollectSignaturesFlow.kt:64) ~[corda-core-3.2.1847-corda.jar:?]
        at net.corda.core.flows.FlowLogic.subFlow(FlowLogic.kt:290) ~[corda-core-3.2.1847-corda.jar:?]
        at com.example.flows.flows.SettleObligation$Initiator.collectSignature(SettleObligation.kt:178) ~[obligation-1.0.jar:?]
        at com.example.flows.flows.SettleObligation$Initiator.call(SettleObligation.kt:87) ~[obligation-1.0.jar:?]
        at com.example.flows.flows.SettleObligation$Initiator.call(SettleObligation.kt:51) ~[obligation-1.0.jar:?]
        at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:96) [corda-node-3.2.1847-corda.jar:?]
        at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:44) [corda-node-3.2.1847-corda.jar:?]
        at co.paralleluniverse.fibers.Fiber.run1(Fiber.java:1092) [quasar-core-0.7.9-jdk8.jar:0.7.9]
        at co.paralleluniverse.fibers.Fiber.exec(Fiber.java:788) [quasar-core-0.7.9-jdk8.jar:0.7.9]
        at co.paralleluniverse.fibers.RunnableFiberTask.doExec(RunnableFiberTask.java:100) [quasar-core-0.7.9-jdk8.jar:0.7.9]
        at co.paralleluniverse.fibers.RunnableFiberTask.run(RunnableFiberTask.java:91) [quasar-core-0.7.9-jdk8.jar:0.7.9]
        at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) [?:1.8.0_181]
        at java.util.concurrent.FutureTask.run(FutureTask.java:266) [?:1.8.0_181]
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180) [?:1.8.0_181]
        at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293) [?:1.8.0_181]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) [?:1.8.0_181]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) [?:1.8.0_181]
        at net.corda.node.utilities.AffinityExecutor$ServiceAffinityExecutor$1$thread$1.run(AffinityExecutor.kt:62) [corda-node-3.2.1847-corda.jar:?]
Caused by: net.corda.core.CordaRuntimeException: java.lang.NoSuchMethodError: com.example.base.BaseHelperKt.isGreaterThan(Ljava/math/BigDecimal;Ljava/math/BigDecimal;)Z
[INFO ] 2018-11-13T00:05:12,807Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Previous node was identical to incoming one - doing nothing {}
[INFO ] 2018-11-13T00:05:12,807Z [RxIoScheduler-2] network.PersistentNetworkMapCache.addNode - Done adding node with info: NodeInfo

A: In Kotlin, each file is compiled to a JVM-level class. A file named Foobar.kt will become a class named FoobarKt.
When you move a top level function from one file to another, therefore, the name of the file is baked into the compiled code and such a change is not binary compatible even though it's source compatible.
Unfortunately this is one of the hidden complexities of all software development - the way the source compiler resolves symbol scopes isn't always identical to the way the runtime linker does. It happens in every language and runtime, although there are ways for the JetBrains guys to fix it in the very long run, if they choose to do so. Sorry. You'll have to move the function back, or provide an alias (look at the @JvmName annotation).

A: The resolveTransactionFlow.kt (when walking down the chain) will loop in sequence to fetch the Tx while verifying it. In that case one would need all the old contract codes (as a cordapp) to be present, else you won't be able to resolve the provenance of the chain.
val result = topologicalSort(newTxns)
    result.forEach {
        // For each transaction, verify it and insert it into the database. As we are iterating over them in a
        // depth-first order, we should not encounter any verification failures due to missing data. If we fail
        // half way through, it's no big deal, although it might result in us attempting to re-download data
        // redundantly next time we attempt verification.
        it.verify(serviceHub)
        serviceHub.recordTransactions(StatesToRecord.NONE, listOf(it))
    }


text:
Q: Why is string to date and back to string resulting in two different strings? My input string is:
"2016-06-13T14:20:09.866Z"

My output string is:
"2016-06-13T10:20:09.866-04"

Why are they different and how can I make it output in the same format as the input?
I convert from string to date:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.ENGLISH);
dateFormat.parse((String) date));

In a unit test, I convert the parsed date back into a string:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.ENGLISH);
dateFormat.format(date);

A: The two dates are the same - only the format differs (one is 2pm UTC the other is 10am with an offset of -4 hours = 2pm UTC too).
So I suppose that what you want is to have the second string in UTC time zone too. In that case you can simply set the timezone of the second DateFormat:
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.ENGLISH);
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

A:
Why are they different and how can I make it output in the same format
as the input?

Both of them not only represent the same moment but are also in the same format, ISO 8601.
2016-06-13T14:20:09.866Z represents a date-time in UTC. The Z in it is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours).
2016-06-13T10:20:09.866-04 or 2016-06-13T10:20:09.866-04:00 represents a date-time at a timezone offset of -04:00 hours i.e. this moment can be represented as 2016-06-13T14:20:09.866+00:00 or 2016-06-13T14:20:09.866Z in UTC.
Note that the legacy date-time API (java.util date-time types and their formatting type, SimpleDateFormat) is outdated and error-prone. It is recommended to stop using it completely and switch to java.time, the modern date-time API*.
Demo using the modern API:
import java.time.OffsetDateTime;
import java.time.ZoneOffset;

public class Main {
    public static void main(String[] args) {
        OffsetDateTime odtWithMinusFourHoursOffset = OffsetDateTime.parse("2016-06-13T10:20:09.866-04");
        System.out.println(odtWithMinusFourHoursOffset);

        OffsetDateTime odtWithSameMomentInUtc = odtWithMinusFourHoursOffset.withOffsetSameInstant(ZoneOffset.UTC);
        System.out.println(odtWithSameMomentInUtc);
    }
}

Output:
2016-06-13T10:20:09.866-04:00
2016-06-13T14:20:09.866Z

Did you notice, we did not use DateTimeFormatter here?
The modern date-time API is based on ISO 8601 and does not require using a DateTimeFormatter object explicitly as long as the date-time string conforms to the ISO 8601 standards.
Learn more about the the modern date-time API* from Trail: Date Time.

* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.


text:
Q: Getting bibliography in the main file I am submitting a journal paper and if I'm not mistaken I suspect they expect all manuscript in the same file, including references. A minimal example is:
\documentclass[preprint,12pt]{elsarticle}

\begin{document}

\cite{turing_checking_1949}

\bibliographystyle{plain}
\bibliography{references}

\end{document}

The question is how can I omit line \bibliography{references}, paste the contents of references.bib  in the main file and still get the same bibliography result.


text:
Q: (ruby on rails)After an server data update, how to load/display a specific div from a partial in the quickest way with jquery/ajax? for clarity purposes I will display all the relevant code files to give the question contest/clarity. I am editing specific divs in a partial with a form and want to display the newly updated div only.
I have this div on the page Scoreboard#show:

    <%= render 'schedules/schedules' %>

The partial _schedules.html.erb( with @schedules= @scoreboard.schedules.paginate(page: params[:page], per_page: 10))
 <% @schedules.each do |schedule| %>
      <div class ="schedule-list" id="schedule_<%=schedule.id%>">

           #various divs here
           e.g
 <%=schedule.detail %>

             <%= link_to "Edit", edit_scoreboard_schedule_path(@scoreboard, schedule), remote: true, class: " sched-edit btn btn-primary" %>

             <%= link_to "Del", [@scoreboard, schedule], remote: true, method: :delete, class: " sched-delete btn btn-primary" %>

    <% end %>

<%= will_paginate @schedules %>

On the click of the edit button, the below file(edit.js.erb) is fired:
$("#schedule_<%=@schedule.id%>").hide(); #the div being edited is hidden
$("#schedule_<%=@schedule.id%>").after("<%= j render 'scheduleedit'%>"); #this renders the edit form where the div used to be

Now, what upon submitting the edit form, I want to hide the edit form and then bring back the div(schedule_<%=schedule.id%>) with the  new data. If I use .html() to reload the whole .all-schedules div in the past, it resets the pagination index and also since the pagination is ajax, it stops working as a result of .html(). My goal is to only affect the specific
#schedule_<%=schedule.id%> div and insert it where it was previous and stay on the page of pagination that the div was on.
So far, this is what the update.js.erb file looks like:
$("#edit_schedule_<%=@schedule.id%>").hide(); #this successfully hides the edit form

#code needed here to re-render the `#schedule_<%=schedule.id%>` div
#without affecting the ajax pagination and staying on the same page in the pagination index

I would prefer to use .html() for this as it is faster than .load(). I don't know if there's any other other methods out there to make this just as quick as .html(). Thanks in advance.

A: You may consider moving out the content of one schedule into a partial.
schedules/_schedule.html.erb
<div class="schedule-list" id="schedule_<%=schedule.id%>">
   # your content

Render collection view schedules from parent view:

  <%= render @schedules %>

At this point you could easily render the only the schedule you need to reload:
update.js.erb
$("#schedule_<%=@schedule.id%>").html("<%= j render('schedules', schedule: @schedule) %>")

Give it a try bro ;)


text:
Q: How to reconnect in php adodb after exceptions: Mysql server gone away or Lost connection to MySQL server during query I have problem in one of my cron jobs, sometimes I get error like: MySQL server gone away and sometimes  Lost connection to MySQL server during query. On random query's.  I using ADODB, and connecting to database with function:
function connectDatabase()
{
   $this->database = NewADOConnection(DSN);
   $this->database->SetFetchMode(ADODB_FETCH_ASSOC);
}

and in cron job I doing something like that:
    while($arrRow = $result->fetchRow()){
        try {
            /*
            Some MySQL query's (~10 query's)
            */
        } catch(Exception $e){
            print $e->getMessage();
            print "\n";
            print $e->getTraceAsString();
            $this->connectDatabase();
        }
    }

In this loop I try to update records one by one, with real simple and quick query's. But in example yesterday I catch this error:
mysql error: [2013: Lost connection to MySQL server during query] in EXECUTE("UPDATE item
            SET
                item.price = 10.00,
                WHERE item.item_id = 145383")

#0 ../public_html/includes/adodb/adodb.inc.php(879): adodb_throw('mysql', 'EXECUTE', 2013, 'Lost connection...', 'UPDATE item ...', false, Object(ADODB_mysql))
#1 ../public_html/includes/adodb/adodb.inc.php(854): ADOConnection->_Execute('UPDATE item ...', false)
#2 ../public_html/class/Updater.class.php(208): ADOConnection->Execute('UPDATE item ...')
#3 ../public_html/class/Updater.class.php(74): Updater->updatePrice('145383', Array, 0)
#4 ../public_html/pricejob.php(14): Updater->start()

And in catch block I want to try reconnect to database but I got same error:
#5 {main}PHP Fatal error:  Uncaught exception 'ADODB_Exception' with message 'mysql error: [2006: MySQL server has gone away] in CONNECT(..., '...', '****', ...)
' in .../public_html/includes/adodb/adodb-exceptions.inc.php:76
Stack trace:
#0 .../public_html/includes/adodb/adodb.inc.php(426): adodb_throw('mysql', 'CONNECT', 2006, 'MySQL server ha...', '...', '...', Object(ADODB_mysql))
#1 .../public_html/includes/adodb/adodb.inc.php(3770): ADOConnection->Connect('...', '...', '...', '...')
#2 .../public_html/includes/adodb/adodb.inc.php(3653): ADONewConnection('mysql://...')
#3 .../public_html/class/Database.php(64): NewADOConnection('mysql://...')
#4 .../public_html/class/Updater.class.php(82): Database->connectDatabase()
#5 .../public_html/pricejob.php(14): Updater->start()
#6 {main}
  thrown in .../public_html/includes/adodb/adodb-exceptions.inc.php on line 76

I know just one that I got this exception when I need to cycle > 25k rows in loop. How to handle this for me? how to bring back the server at that errors?

A: mysql_connect doesn't work second time
mysql_connect doesn't care if the connection has disconnected or timed-out it will never connect a second time unless you call it with the parameter new_link with the value true.
mysql_connect($server,$username,$password,true);


text:
Q: RESTfull Webservice with Jersey and jQuery get strange response I try to build a RESTfull Webservice.
On the frontend I use jQuery to get the data.
On the backend I am trying it with the example from www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/
Calling 127.0.0.1:8080/restEx/rest/json/get from the browser I get the answer as expected:
{"title":"Enter Sandman","singer":"Metallica"}

But when I try to get these data with $.get(), I get no answer.
Looking in Firebug tells me, that I don't get data.
I also tried it with
return Response.ok("{status: 'success'}").header("Access-Control-Allow-Origin", "*").build();

as I found as a solution in another question
In Firebug now I  see the data, but still jQuery doesn't executes the success function. I still only see the fail-function.
So what I am doing wrong? How can I make this stuff working?
I am using jQuery 2.0.2, Jersey 1.8 (I tried it with Jersey 2 from jersey.java.net/documentation/latest/getting-started.html#running-project with same result) and the project is deployed on Tomcat 7.
index.html
<!DOCTYPE html>

    <title></title>

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mkyong.common</groupId>
    <artifactId>RESTfulExample</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>RESTfulExample Maven Webapp</name>
    <url>http://maven.apache.org</url>

    <repositories>
        <repository>
            <id>maven2-repository.java.net</id>
            <name>Java.net Repository for Maven</name>
            <url>http://download.java.net/maven/2/</url>
            <layout>default</layout>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.8.2</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-server</artifactId>
            <version>1.8</version>
        </dependency>

        <dependency>
            <groupId>com.sun.jersey</groupId>
            <artifactId>jersey-json</artifactId>
            <version>1.8</version>
        </dependency>

    </dependencies>

    <build>
        <finalName>restEx</finalName>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

web.xml
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Restful Web Application</display-name>

    <servlet>
        <servlet-name>jersey-serlvet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>com.sun.jersey.config.property.packages</param-name>
            <param-value>com.mkyong.rest</param-value>
        </init-param>
        <init-param>
            <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
            <param-value>true</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>jersey-serlvet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

JSONService.java
package com.mkyong.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.mkyong.Track;

@Path("/json")
public class JSONService {

    @GET
    @Path("/get")
    @Produces(MediaType.APPLICATION_JSON)
    public Track getTrackInJSON() {

        Track track = new Track();
        track.setTitle("Enter Sandman");
        track.setSinger("Metallica");

        return track;

    }

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createTrackInJSON(Track track) {

        String result = "Track saved : " + track;
        return Response.status(201).entity(result).build();

    }

    @GET @Path("/test") @Produces(MediaType.APPLICATION_JSON)
    public JSONObject test() throws JSONException{
        return new JSONObject("{status:'success'}");
    }
}

Track.java
package com.mkyong;

public class Track {

    String title;
    String singer;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSinger() {
        return singer;
    }

    public void setSinger(String singer) {
        this.singer = singer;
    }

    @Override
    public String toString() {
        return "Track [title=" + title + ", singer=" + singer + "]";
    }

}

A: Wrong URL, change http://127.0.0.1:8080/restEx/rest/json/test to http://127.0.0.1:8080/restEx/rest/json/get:
<!DOCTYPE html>

    <title></title>

A: Thanks to the link from Marcos Zolnoswski I was able to solve my Problem.
With the inforamtion provided there, I was able to find http://blog.usul.org/cors-compliant-rest-api-with-jersey-and-containerresponsefilter/ where a solution is described how to add the missing header to all requests.
As init-Parameter to my Jersey Servlet:
<init-param>
    <param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
    <param-value>your.package.ResponseCorsFilter</param-value>
</init-param>

ResponseCorsFilter.java
package yoiur.package.security;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;

import com.sun.jersey.spi.container.ContainerRequest;
import com.sun.jersey.spi.container.ContainerResponse;
import com.sun.jersey.spi.container.ContainerResponseFilter;

public class ResponseCorsFilter implements ContainerResponseFilter {

    @Override
    public ContainerResponse filter(ContainerRequest req, ContainerResponse contResp) {

        ResponseBuilder resp = Response.fromResponse(contResp.getResponse());
        resp.header("Access-Control-Allow-Origin", "*")
                .header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");

        String reqHead = req.getHeaderValue("Access-Control-Request-Headers");

        if(null != reqHead && !reqHead.equals("")){
            resp.header("Access-Control-Allow-Headers", reqHead);
        }

        contResp.setResponse(resp.build());
            return contResp;
    }

}


text:
Q: How to mock the springcontext? private ServiceImpl() {
    // TODO Auto-generated constructor stub

    reMgr = (ReManager) SpringContext.getBean("reManager");

I want to mock this method , this is a private constructor which is initializing the springContext. I am setting the beanfactory through my powermockito test case using beans.xml where I have specified the bean and its classname. Still this method is failing to get the instance of reManager .

A: Forgive me if I'm misunderstanding something but if you are using PowerMockito can't you do something along the lines of:
@RunWith(PowerMockRunner.class)
@PrepareForTest(SpringContext.class)
public FooTest {
    @Test
    public void foo() {
        final ReManager manager = Mockito.mock(ReManager.class);

        PowerMockito.mockStatic(SpringContext.class);
        Mockito.when(SpringContext.getBean("reManager")).thenReturn(manager);

        ... etc...
    }
}

See more information here on how to verify static behaviour.
Alternatively... I would change the design so your dependencies are passed to the class under test, e.g.:
@Test
public void foo() {
    final ReManager manager = Mockito.mock(ReManager.class);
    final ServiceImpl service = new ServiceImpl(manager);

    ... etc...
}

Then there is no need for PowerMock, your testing becomes easier and there's less coupling between classes.

A: If what you wanna do is creating an instance of a Spring bean in one of your tests you don't need to use powermockito for that. You could do something like this
@ContextConfiguration(locations = "/beans.xml")
public class YourTestJUnit4ContextTest extends  AbstractJUnit4SpringContextTests {

private ReManager reManager;

@Before
public void init() {
    reManager= (ReManager) applicationContext.getBean("reManager");
}

@Test
public void testReManager() {
    // Write here the code for what you wnat to test
}

}
beans.xml is the file where you define your application context. The best link I can think right know is this
Spring Testing Support


text:
Q: if a='4*6' why int(a) not = 24 is there any way to do it I'm trying to multiply all members of list
i = [6,7]

print(int(str(i).replace(',', '*').replace('[', '').replace(']', '')))

I expect the output 42 but error is

invalid literal for int() with base 10: '6*7'

A: int can't cast the value '6* 7'
You can try this with eval.
The eval() method parses the expression passed to this method and runs python expression (code) within the program.
This will work
print(eval(str(i).replace(',', '*').replace('[', '').replace(']', '')))

A: I am not even sure why are you converting a list i into a string, and then doing the replace and eval.
A much cleaner way to do it will be to use functools.reduce which will apply multiplication operator between all elements in the list, this way you can multiply arbitrary long list of integers, the function we use here is operator.mul, which stands for multiplication, a*b
In [48]: import operator
    ...: from functools import reduce

In [49]: reduce(operator.mul, [6,7])
Out[49]: 42

In [50]: reduce(operator.mul, [6,7,8,9,10])
Out[50]: 30240

In [51]: operator.mul(6,7)
Out[51]: 42

A: One of the easiest way to multiply a list is using reduce from functools. Here is the code:
from functools import reduce
multiplied_list = reduce(lambda x, y: x*y, [6,7])
print(multiplied_list)

Hope it helps :)


text:
Q: PHPUnit does not run its tests I am following the examples in the PHPUnit manual. See the two Test files below. I am running the tests in Eclipse PDT with PTI installed. I see the following problems:

*

*When running DependencyFailureTest, it does not recognize it as being a test. Is does not run anything.

*When running MultipleDependenciesTest, it is running and mentions that all three test cases pass, as it should. However, if I then change the expected outcome in the function testConsumer into array('first', 'third'), it still mentions that all test cases pass, although one of them should clearly fail. Also, when I change one of the assertions into $this->assertTrue(FALSE);, I expect a failed and a skipped test case, but again all test cases pass.

Has anyone experienced something similar, and solved this?
DependencyFailureTest
<?php
class DependencyFailureTest extends PHPUnit_Framework_TestCase
{
    public function testOne()
    {
        $this->assertTrue(FALSE);
    }

    /**
     * @depends testOne
     */
    public function testTwo()
    {
    }
}
?>

MultipleDependenciesTest
<?php
class MultipleDependenciesTest extends PHPUnit_Framework_TestCase
{
    public function testProducerFirst()
    {
        $this->assertTrue(true);
        return 'first';
    }

    public function testProducerSecond()
    {
        $this->assertTrue(true);
        return 'second';
    }

    /**
     * @depends testProducerFirst
     * @depends testProducerSecond
     */
    public function testConsumer()
    {
        $this->assertEquals(
            array('first', 'second'),
            func_get_args()
        );
    }
}
?>

A: I don't have a good answer yet, only some black magic voodoo. I noticed that for running it in the command line, I need to include the class under test.
<?php

require_once ('path/to/Car.php')

class CarTest extends PHPUnit_Framework_TestCase {
...

For running it in PTI, I mention the file in the Bootstrap file in the PHPUnit preferences. Therefore, this reuire_once statement is not necessary. But worse however, this require_once statement causes the test not to run!
Something strange that I noticed is that at one time, my tests were not running, even without the require_once statement. In the PHPUnit preferences, I had the option Do not check for equal namespaces while searching for php/test case classes enabled. I disabled it, and it worked. I enabled it again, and it still worked.

A: Phpunit doesnot show any thing (run 0/0)

Console Error:
Fatal error: Declaration of PHPUnitLogger::addFailure(Test $test, AssertionFailedError $e, $time): void must be compatible with PHPUnit\Framework\TestListener::addFailure(PHPUnit\Framework\Test
$test, PHPUnit\Framework\AssertionFailedError $e, float $time): void in
C:\Users\xxx\AppData\Local\Temp\phpunit_printer\PHPUnitLogger.php(415): eval()'d code on line 1

TestCase

<?php
namespace PHPUnit\Framework;

use Facebook\WebDriver\WebDriverBy;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;

class SeleniumTest extends \PHPUnit_Framework_TestCase
{

    protected $webDriver;

    public function setUp()
    {
        // system . property_exists("Facebook\WebDriver\Firefox\FirefoxDriver", "C:\rc\geckodriver\geckodriver");
        // System . set("Webdriver.gecko.driver", "C:\rc\geckodriver\geckodriver");
        $this->webDriver = RemoteWebDriver::create('http://localhost:4444/wd/hub', DesiredCapabilities::firefox());
        $this->webDriver->manage()
            ->window()
            ->maximize();
        $this->webDriver->get('http://localhost/farmer/login');
        // $this->webDriver->get("www.gmail.com");
    }

    public function testLoginPass()
    {
        $this->webDriver->get('http://localhost/farmer/login');
        $this->webDriver->findElement(WebDriverBy::name('username'))->sendKeys(' correct');
        $this->webDriver->findElement(WebDriverBy::id('password'))->sendKeys('password');
        $this->webDriver->findElement(WebDriverBy::name('btn-login'))->click();
        $content = $this->webDriver->findElement(WebDriverBy::tagName('body'))->getText();
        $this->assertContains('Dashboard', $content);
    }

    public function testLoginFail()
    {
        $this->webDriver->get('http://localhost/farmer/login');
        $this->webDriver->findElement(WebDriverBy::name('mobile'))->sendKeys("800000000000");
        $this->webDriver->findElement(WebDriverBy::id('password'))->sendKeys("8000000000");
        $this->webDriver->findElement(WebDriverBy::name('btn-login'))->click();
        $content = $this->webDriver->findElement(WebDriverBy::className('help-block'))->getText();
        $this->assertContains('Your Credential Doesnot Match.Please Try Again !!', $content);
    }

    public function tearDown()
    {
        $this->webDriver->quit();
    }
}

?>

While MakeGood is working Properly in Eclipse (Everything is OK)
MAKEGOOD result


text:
Q: How do I update state values using Formik and setFieldValue I am trying to write a simple profile page where the user can change their photo, name, username and bio. The fields name, username and bio I keep inside in formik form, because I need to perform some validations on them. Inside the <Formik> form I have a button submit which is the following:
<TouchableOpacity
                onPress={handleSubmit} //the important part!!!
                title="UPDATE PROFILE"
                disabled={!isValid}
                style={isValid ? styles.buttonStyle : styles.buttonStyleInvalid}
              >
                <Text style={styles.textStyle}>UPDATE PROFILE </Text>
              </TouchableOpacity>

My handleSubmit method is outside my <Formik> form. It needs to check if the username is taken. I dont want to do such calls to the db every time the user touches the username field, I want to check it only on submit. Here is my method:
const submitHandler = async () => {
    //my formik values have been set up correctly
    console.log("checking formik values: ", formRef.current.values);
    //username is part of my state; so I want to update it with the values from the form
    setUsername(formRef.current.values.username.trim());
     //username is with the old value
     console.log("checking if username has been updated: ", username);
    //yet here, when I check the value of the username it is the old value, and the state hasnt been updated
    // so I dont even go inside this if case, because my state hasn't been updated
    if (username !== props.currentUser.username) {
      //do some checks not important
    }
  };

Here is my state:
const [username, setUsername] = useState(props.currentUser.username);
const [name, setName] = useState(props.currentUser.name);
const [bio, setBio] = useState(props.currentUser.bio);

Here is my Formik (I am not including name and bio because it is similar):
<Formik
        validationSchema={loginValidationSchema}
        initialValues={{ name: name, username: username }}
        onSubmit={(values, formikActions) => {
          submitHandler();
        }}
        innerRef={formRef}
      >
        {({
          handleChange,
          handleBlur,
          handleSubmit,
          values,
          errors,
          touched,
          isValid,
          setFieldValue,
          setFieldTouched,
        }) => {
          return (
            <>
              <TextInput
                value={username}
                style={styles.textInputStyle}
                name="username"
                keyboardType="twitter"
                placeholder="Username"
                onChangeText={(val) => {
                  setFieldValue(
                    "username",
                    val
                      .normalize("NFD")
                      .replace(/[\u0300-\u036f]/g, "")
                      .replace(/\s+/g, "_")
                      .replace(/[^a-z0-9_]/gi, "")
                  );
                  setFieldTouched("username", true, false);
                  setUsernameError(null);
                }}
                onBlur={handleBlur("username")}
                value={values.username}
                autoCapitalize="none"
              />
              {errors.username && touched.username && (
                <Text style={styles.error}>{errors.username}</Text>
              )}
              {usernameError ? (
                <Text style={styles.error}>{usernameError}</Text>
              ) : null}
              <TouchableOpacity
                onPress={handleSubmit}
                title="UPDATE PROFILE"
                disabled={!isValid}
                style={isValid ? styles.buttonStyle : styles.buttonStyleInvalid}
              >
                <Text style={styles.textStyle}>UPDATE PROFILE </Text>
              </TouchableOpacity>
            </>
          );
        }}
      </Formik>

My question: How do I set my username correctly, so that my handleSubmit method performs the checks correctly? I tried updating it using setUsername(formRef.current.values.username.trim()); obviously, it doesnt work, so Im guessing I should call it from onChangeText method? But then I am not using properly setFieldValue I guess?


text:
Q: Java Relative Path Issue I am facing an issue while trying to resolve a file path using relative paths in Java. I am not sure where I am failing at. Could you please help me out? Thanks!
@Test
public void testObjectNotNull() throws Exception{
    FileReader fileReader = new FileReader(getClass().getResource("./JavaPractice/resources/tests/codeeval/fileReaderTest.txt").toString());
    assertNotNull(fileReader);
}

Exception:
java.lang.NullPointerException
    at components.com.codeeval.FileReader.FileReaderTest.testObjectNotNull(FileReaderTest.java:13)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)

Directory Structure:
JavaPractice
--resources.tests.codeeval.fileReaderTest.txt (File that I am trying to access)
--tests.components.com.codeeval.FileReader.FileReaderTest.java (junit which is trying to access the above file)

A: Your issue is because  this
getClass().getResource("./JavaPractice/resources/tests/codeeval/fileReaderTest.txt")
is null. You are reading from the classpath and not a relative path per-se SO
Change your code to
getClass().getResource("tests/codeeval/fileReaderTest.txt") and ensure that the resources folder is on your classpath. Also read up on loading from classpath

A: Resources are not files. They are typically JAR file entries. You should use the resource API of Class or ClassLoader. That can return you an InputStream.

A: try this
InputStream in = Your_Class.class.getClassLoader().getResourceAsStream("resources/tests/codeeval/abc.txt");

 assertNotNull(in);
 Reader fr = new InputStreamReader(in, "utf-8");


text:
Q: mysql convert string to int not working(with pdo) I want to convert memberID from string to int first then do other operation in mysql but it seems that only num 3 sql work,how can i fix it?
otherwise,I have a question that why I input memberID by php int type but mysql insert it as string?
select hasGivePoint from posts where postID=:postID and json_search(hasGivePoint,'one',(convert(:memberID ,signed))) is not null;

update
posts
set
$pointName=$pointName-1,hasGivePoint=JSON_REMOVE(hasGivePoint,replace(json_search(hasGivePoint,'one',
convert(:memberID ,signed)),'\"',''))
WHERE postID=:postID;
";

update posts set $pointName=$pointName+1,hasGivePoint=JSON_ARRAY_APPEND(hasGivePoint,'$',convert(:memberID ,signed)) where postID=:postID;


text:
Q: django search returns a blank page I have designed my search box in my django app but the search only returns the extended html page, not the search results.
#View
class SearchListProject(ListView):
paginate_by = 4
template_name = 'website/search_project.html'

def get_queryset(self):
    search_project = self.request.GET.get('q')
    return Project.objects.filter(description__icontains=search_project)

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    context['search_project'] = self.request.GET.get('q')
    return context

#url
    path('search_project/', SearchListProject.as_view(), name='search_project'),
path('search_project/page/<int:page>', SearchListProject.as_view(), name='search_project')

#html
{% extends 'website/project_list.html' %}

Search: {{ search_project }}

{% block previous_page_url %}
    {% url 'website:search_project' page_obj.previous_page_number %}?q={{ search_project }}
{% endblock %}
{% block next_page_url %}
    {% url 'website:search_project' page_obj.next_page_number%}?q={{ search_project }}
{% endblock %}

#my form
                <form action="{% url 'website:search_project' %}">
              <input type="text" name="q">
              <button type="submit"></button>
            </form>


text:
Q: Setting up Pycharm to aid in learning python itself. Can Pycharm be configured to help learn python itself? I have pycharm setup right now and I'm trying to see its possible to set it up to help me learn more about the language. For example, and this is a simple example, lets say I created an empty list:
list = []
If I highlight over [] or control-click on it, pycharm tells me nothing about lists or anything about the brackets. Is it possible to set it up so that I can get to the official python documentation that talks about lists or anything that indicates its a list in the first place? I see that the official python documentation is not added to Pycharm's default external documents under Pycharms settings. If I add it, how to I pull it up for objects, sequence types, methods and all the other things that makes python tick? Pycharm is an awesome IDE and I have to believe its possible to set it up so the language itself it easier to learn when working in it.

A: At this time PyCharm is only able to provide help for library functions; it doesn't have any features for providing help on language features such as list literals.


text:
Q: Twitter button count not work, it always displays 0 Script :

code :
<?php
      $variable = 'ID)).'" data-counturl="'.urlencode(get_permalink($post->ID)).'" data-count="horizontal" class="twitter-share-button" >Tweet';
?>

It tweets successfully but in my site page icon not count the number of tweet, it remains same value 0.
solution accepted,
Thanks in Advance.

A: I find out this questions answer from here,
twitter button


text:
Q: java.net.SocketException: Connection reset when i run from android studio, but works in eclipse I'm getting the below exception when I run TestUtil class from android studio. But if I run it from eclipse it works fine.

java.net.SocketException: Connection reset    at
  java.net.SocketInputStream.read(SocketInputStream.java:189)   at
  java.net.SocketInputStream.read(SocketInputStream.java:121)   at
  sun.security.ssl.InputRecord.readFully(InputRecord.java:442)  at
  sun.security.ssl.InputRecord.read(InputRecord.java:480)   at
  sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:927)     at
  sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1312)
    at
  sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1339)
    at
  sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1323)
    at
  sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:515)
    at
  sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
    at
  sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1299)
    at
  sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
    at com.XYZ.android.cmpi.util.RestUtil.get(RestUtil.java:36)
      at com.XYZ.android.cmpi.tests.TestUtil.main(TestUtil.java:15)

public class TestUtil {

    public static void main(String[] args) throws MalformedURLException {
        String response = RestUtil.get(new URL(RestUtil.getURL()));
        print(response);
    }

    public static void print(Object o) {
        out.print(o);
    }
}

//
  public class RestUtil {

        public final static String USER_AGENT = "Mozilla/5.0";

        public static String get(URL url) {
            StringBuilder sb = new StringBuilder();
            HttpURLConnection connection = null;
            try {
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");

                BufferedReader br = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }

                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                connection.disconnect();
            }
            return sb.toString();
        }

        public static String getURL() {
            // returns URL
        }
    }

I'm not sure why I'm getting this exception when I run from android studio, but not from Eclipse.


text:
Q: Create n files with random number value in loop batch how can I generate n files which includes random number using batch?
I have:
@echo off
set /p howManyFiles=How many files to generate:
FOR /L %%i IN (1, 1, %howManyFiles%) DO (
    set /a num=%random% %%100 +1
    echo !num! >"C:\xxx\file.txt"
)
pause

but it generates only 1 file.

A: Two problems with your code.
1) You are using the correct syntax for variables that require delayed expansion but you do not have delayed expansion enabled.
2) If you want to create multiple files then use the for variable with the file name.
@echo off
setlocal enabledelayedexpansion
set /p howManyFiles=How many files to generate:
FOR /L %%i IN (1, 1, %howManyFiles%) DO (
    set /a num=!random! %% 100 + 1
    echo !num! >"C:\xxx\file%%i.txt"
)
pause


text:
Q: Boost::spirit::karma: duplicate doesn't work within repeat or kleene star? Here's a piece of very simple code that uses boost::spirit::karma to produce formatted output in the graphviz dot language:
#include <iostream>
#include <iterator>
#include <vector>
#include <boost/spirit/include/karma.hpp>
using namespace std;

int main() {
    vector<int> v{0,1,2,3};
    unsigned count = 17;
    {
        namespace karma = boost::spirit::karma;
        karma::generate(ostream_iterator<char>(cout), *(karma::duplicate['c' << karma::int_ << '_' << karma::lit(count) << "[xlabel=" << karma::int_ << "];\n"]), v);
    }

    return 0;
}

I would expect this to produce:
c0_17[xlabel=0];
c1_17[xlabel=1];
c2_17[xlabel=2];
c3_17[xlabel=3];

Instead, it produced:
c0_17[xlabel=1];
c2_17[xlabel=3];

Which means the duplicate[] directive is not effective at all within a kleene star. I've also tried the repeat[] directive but that does not work as well.
What am I doing wrong? I'm using boost version 1.53.0. I've compiled the code with g++ 4.7 and clang++ 3.2, both produced the same results.

A: #include <iostream>
#include <iterator>
#include <vector>
#include <boost/spirit/include/karma.hpp>
using namespace std;

int main() {
    vector<int> v{0,1,2,3};
    unsigned count = 17;
    {
        namespace karma = boost::spirit::karma;
        //karma::rule<ostream_iterator<char>, int()> xlabel = karma::duplicate['c' << karma::int_ << '_' << karma::lit(count) << "[xlabel=" << karma::int_ << "];\n"];
        //karma::generate(ostream_iterator<char>(cout), *xlabel, v);
        karma::generate(ostream_iterator<char>(cout), *karma::attr_cast<int>(karma::duplicate['c' << karma::int_ << '_' << karma::lit(count) << "[xlabel=" << karma::int_ << "];\n"]), v);
    }

    return 0;
}


text:
Q: Recover data of dropped tables without backup I did a blunder in my client database. I have dropped all tables and created new tables with same name in client database. I lost all client data. I don't have any backup of client DB. Can you please let me know if I can recover data of old tables.

A: Few options .All untested  and i am not sure,how consistent the database will be
1.RedGate Provides a tool called SQL Log Rescue..It claims to do View and recover deleted and modified data
2.Volume Shadow Copy service
some reference of what this means :(emphasis mine)

This service allows Windows to take automatic or manual backups, or snapshots, of the current state of the files on a particular volume (drive letter). The important part of this process is that these backups can be taken of files even if they are open. Therefore, this provides a mechanism that backup programs and Windows can use to retain a reliable history of a computer's files

Below is a step by step tutorial on how to do this
https://www.bleepingcomputer.com/tutorials/how-to-recover-files-and-folders-using-shadow-volume-copies/


text:
Q: Visual Studio 2010 syntax highlighting for JsRender Is there any way to get HTML syntax highlighting working for JsRender templates (as part of an aspx file) in Visual Studio 2010?
My aspx files typically look like this:
<%@ Page Title="Home Page" Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Test._Default" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

A: There is no support for JsRender syntax highlighting in VS 2010, but if you have VS 2012, there is a a Web Essentials plugin which adds syntax highlighting within script blocks (of type other than text/javascript). It also provides hightlighting on {{foo }} tags.
In a future release it will likely be built in...
The Web Essentials plugin download is here
Update: VS 2012 and VS 2013 now include syntax highlighting for JsRender tempates.


text:
Q: Transparency in animator control I'm writing a user control for animation.
Its uses an internal ImageList to store the animation images and paint one after the other in a loop.
This is the whole code:
public partial class Animator : UserControl
{
    public event EventHandler OnLoopElapsed = delegate { };
    private ImageList imageList = new ImageList();
    private Timer timer;
    private bool looping = true;
    private int index;
    private Image newImage;
    private Image oldImage;

    public Animator()
    {
        InitializeComponent();

        base.DoubleBuffered = true;

        timer = new Timer();
        timer.Tick += timer_Tick;
        timer.Interval = 50;
    }

    public bool Animate
    {
        get { return timer.Enabled; }
        set
        {
            index = 0;
            timer.Enabled = value;
        }
    }

    public int CurrentIndex
    {
        get { return index; }
        set { index = value; }
    }

    public ImageList ImageList
    {
        set
        {
            imageList = value;
            Invalidate();
            index = 0;
        }

        get { return imageList; }
    }

    public bool Looping
    {
        get { return looping; }
        set { looping = value; }
    }

    public int Interval
    {
        get { return timer.Interval; }
        set { timer.Interval = value; }
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        if (imageList.Images.Count == 0)
            return;

        Invalidate(true);
        index++;

        if (index >= imageList.Images.Count)
        {
            if (looping)
                index = 0;
            else
                timer.Stop();

            OnLoopElapsed(this, EventArgs.Empty);
        }
    }

    protected override void OnPaintBackground(PaintEventArgs e)
    {
        if (oldImage != null)
            e.Graphics.DrawImage(oldImage, ClientRectangle);
        else
            e.Graphics.Clear(BackColor);
    }

    protected override void OnPaint(PaintEventArgs e)
    {
        Graphics g = e.Graphics;

        if (imageList.Images.Count > 0)
        {
            newImage = imageList.Images[index];
            g.DrawImage(newImage, ClientRectangle);
            oldImage = newImage;
        }
        else
        {
            e.Graphics.Clear(BackColor);
        }
    }
}

The animation seems very nice and smooth,
but the problem is that its surrounding rectangle is painted black.
What am I missing here?
I've seen very smooth transparent animation done here in WPF,
I've placed some label behind it and they are seen thru the rotating wheel as I hoped.
But I don't know WPF well enough to build such a control in WPF.
Any idea or WPF sample code will be appreciated.

A: This was solved by removing this line from the constructor:
base.DoubleBuffered = true;

Now the control is fully transparent, even while changing its images.


text:
Q: How does Gitlab CI determine if a PHPUnit test pass or fails? I have this basic .gitlab-ci.yml file.
image: php:7.2

before_script:
  # install git
  - apt-get update -yqq
  - apt-get install git -yqq
  # Install composer
  - curl -sS https://getcomposer.org/installer | php
  # Install all project dependencies
  - php composer.phar install

tests:
  script:
    - vendor/bin/phpunit tests

This works just fine, it alerts me if unit tests fail or pass.
My question is how exactly does Gitlab CI know this? Do they parse the output of PHPUnit and see if the string FAILURES! exist?

A: The gitlab-ci only checks the exit codes of processes running inside it. If a process exits with another status code than 0 then the pipeline stops and declares failure. That's how the CI pipelines works overall, not only gitlab but Jenkins, etc. too.


text:
Q: JPA ManyToOne relations from different entities to the same entity I have different entities in my model and more than one needs an Address, is there any way to do this without having tables with duplicate information?
E.g. a model that has a User and an EnglishClass entity, both need an Address with same data, as city, country, state, etc.
Is there a way to have this Address information only in one place (without having  AddressUser and AddressEncglisClass entity) and without having an Address table that has both User and EnglishClass objects? I want to avoid this to avoid having null values.


text:
Q: JS remove leading zeros In JavaScript, I want to remove the decimal place & the following zeros.
For example, my original number: "0.00558", I want to be left with "558".
Is this possible? (I'm also using AngularJS if that has a method for this).

A: you can do that by a simple regex replace.
var number = "0.00558";
number = number.replace(/^[0\.]+/, "");
console.log(number);//number is now "558"

A: Remove the decimal point:
el.value.replace(/[^\d]/g,'');

or
el.value.replace(/\./g,'');

Then get the integer value:
var el.value = parseInt(el.value);

While I have always gone with the default radix being 10, @aduch makes a good point.  And MDN concurs.
The safer way is:
var el.value = parseInt(el.value,10);

From MDN:
    If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed.
    If the input string begins with "0", radix is eight (octal) or 10 (decimal).  Exactly which radix is chosen is implementation-dependent.  ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet.  For this reason always specify a radix when using parseInt.
    If the input string begins with any other value, the radix is 10 (decimal).


text:
Q: A geometry problem (length of side of a quadrilateral) This problem showed up on my tab and I have tried few approaches, but they don't span out. So this is the figure,
In this figure we have find the distance BC, in terms of AD, AB and $\theta$ only.
Any pointers would be helpful.
P.S: In one of my methods I drew diagonals and used cosine rule, then cross-substituted the equations.

A: HINT:

*

*Join BD.

*$\angle BDA=\angle CBD-\theta$ (that's the best I could explain which angle I'm talking about) as Alternate Angles wrt a transversal (here, BD) are equal.

*$\angle BDA=\angle CBD-\theta=\tan^{-1}\left(\dfrac{BA}{AD}\right)$.

*$\triangle CBD$ is a right triangle.

*$\cos\angle CBD=\cos\left(\tan^{-1}\left(\dfrac{BA}{AD}\right)+\theta\right)=\dfrac{BC}{BD}=\dfrac{BC}{\sqrt{AB^2+AD^2}}$.

*$BC=\sqrt{AB^2+AD^2}\cdot\cos\left(\tan^{-1}\left(\dfrac{BA}{AD}\right)+\theta\right)$.

A: Drop a perpendicular from $A$ to $CD.$ Call the intersection point $E.$
Drop a perpendicular from $B$ to $AE.$ Call the intersection point $F.$
You now have partitioned the original figure into two right triangles and a rectangle, as shown below:

(The rectangle doesn't look very rectangular, but that's mainly because of the not-to-scale right angle at $C.$)
You should now be able to find all the lengths you need as quite simple expressions involving $AB,$ $AD,$ and trigonometric functions of $\theta.$


text:
Q: "Will" or "going to" or both, which one is correct (or more natural) in these specific phrases? Are the following phrases correct?
If both "will" and "going to" could be used, which one is more natural?

*

*It's raining. Don't go out. You'll get wet / You are going to get wet

To me both sound fine, but shouldn't "going to" be the more natural one?! Because it's 'something that is going to happen'

*The future situation is uncertain. What do you think it will happen? / What do you think it is going to happen?

Here "will" sounds better, but I think I heard also the phrases: "I tell you what it is going to happen" or "Oh my God, what's going to happen to our jobs now?"

3.A. Joe: Oh, I've just realised I haven't got any money. Ann: Well don't worry I'll lend you some.

But let's say Ann says:

3.B. hmmm... (she thinks for a while, then she decides to lend him some money) ok listen Jim, I'm going to lend you some money for tonight.

Is this one correct too?

*We are going to leave at about 9 o'clock then. / We'll leave at about 9 o'clock then.

I'm clueless about which one is the right one.

A:
1.It's raining. Don't go out. You'll get wet / You are going to get wet

Both mean the same thing. In this example, You will = You're going to.
As to which is more natural, this is a matter of opinion. To me, the more natural is the conversational, and the conversational uses the fewest syllables. Ergo, "you'll get wet."

2.The future situation is uncertain. What do you think it will happen? / What do you think it is going to happen?

For starters, the it does not belong in either sentence as written. By removing the it, both become good English. However, in terms of which is more natural, I would chose the conversational, "What do you thing happens?"
If you are stuck using one of the two sentences, they need to be rewritten as:

*

*What do you think will happen?

*What do you think is going to happen?

Knowing my Law of Least Syllables, I prefer sentence one.

3.A. Joe: Oh, I've just realised I haven't got any money. Ann: Well don't worry I'll lend you some.
3.B. hmmm... (she thinks for a while, then she decides to lend him some money) ok listen Jim, I'm going to lend you some money for
  tonight.

British English, but no Oxford comma? Come on, mate, snap to it, then :)
Sentence 3-A is, of course, the conversational route, but it needs a spot of tidying up: "Well, don't worry; I'll lend you some."
The sentence proper is, "I'll lend you some," with the "well" being emotive and "don't worry" being parenthetic. The semi-colon acts as the Coordinating Conjunction and.
The for tonight bit in sentence two could imply that it must be paid back by morning, which is not very friendly like. Otherwise, it is redundant.

4.We are going to leave at about 9 o'clock then. / We'll leave at about 9 o'clock then.

These are the same, with sentence two being more conversational. You can say the same thing in even less words with, "We'll leave around nine, then."
Cheers.

A: Both mean pretty much the same thing. One could argue over subtle differences in connotation, but I don't think there's any clear, widely-recognized difference.
BTW Your second example should be "What do you think will happen? / What do you think is going to happen?" The "it" doesn't belong, because the clause already has a subject: "what". We say, "What will happen?"  NOT "What it will happen?" Similarly for more complex sentences.


text:
Q: Passing Node.JS run params via Travis CI API I'm trying to setup a nice and customizable testing environment for my company using TestRail + Travis CI + a Selenium-based testing app. I want to be able to use the Travis CI Api v3 to trigger the Node.JS app to run. Ideally I'd be able to specify an email / password in the API request that the Node app will use to do all the tests with. I'm going to use TestRail's UI Script to trigger the Travis CI Api with the correct params.
Currently I have lots of scripts in the package.json file that runs the tests in certain environments. The conf.js file parses these params and sets up the application accordingly.
"test:susa:prod:b2c": "node node_modules/protractor/bin/protractor ./conf.js --disableChecks=flag --params.region=susa --params.run=prod  --params.app=b2c --params.conf=headlesschrome",
"test:susa:qa:admin": "node node_modules/protractor/bin/protractor ./conf.js --disableChecks=flag --params.region=susa --params.run=qa --params.app=corp --params.conf=headlesschrome",
"test:susa:prod:corp": "node node_modules/protractor/bin/protractor ./conf.js --disableChecks=flag --params.region=susa --params.run=prod --params.app=admin --params.conf=headlesschrome"

It would be really nice if I could also pass these params in via the Travis CI Api also.

A: Never worked in Travis but I can imagine it's same as Jenkins.
So what I'd do in Jenkins from bottom to top:

*

*make sure protractor can accept parameters (any: email, password, env, userrole if needed). One way is what you're doing with --params.var flag. Limitation though, you can't make config file configurable, since variables become available when the browser launches. Another way is https://stackoverflow.com/a/66128729/9150146 Limitation, the approach is different to set an environment variable in different OS

*set up a configurable job in CI tool. This job needs to have parameter inputs - dropdowns, text fields, check box - whatever is applicable. The job would pass these parameters to protractor and eventually shell script would run node process. For example:
protractor config.js --params.user="${USERNAME}" --params.password="${PASSWORD}"

*

*when the job is setup, you can send an API request to trigger a build (test execution). The requests URL would have all parameters specified. Example here https://stackoverflow.com/a/20360774/9150146
Essentially what you want to do is several tasks (layers) and you just need to properly identify them and then solve one by one


text:
Q: How to parse or read CSV separated comma ignoring empty and selected value using C#? I got some issue in parsing or reading the CSV. I want to achieve to pick the selected value in CSV file because it doesn't have a header. Then I want to store the selected item into the database.
Example Data:
Row 1: "","",John,"",28,"","",
Row 2: "",Doe,"","USA",
Row 3: Devoper,"","","ABC Company",
Row 4: "","",10,000,"2 Years",
Row 5: "C#","LINQ","ASP.NET MVC",

I want to select like this:
Row 1: John,28
Row 2: Doe, USA
Row 3: Developer, ABC Company
Row 4: 10,000, 2 Years
Row 5: C#, LINQ, ASP.NET MVC

We assume class structured is like this:
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Address { get; set; }
public string Position { get; set; }
public double Salary { get; set; }
public string YearWorked { get; set; }
public string Skills { get; set; }

A: LINQ is a wonderfull quick tool. But like all quick tools, it has limits. I generally consider parsing CSV to be way beyond those limits.
You should be using a proper CSV parser. There is just to many special cases (like Multiline fields, escaped commas) for LINQ to ever realiably deal with. And even if you could, the performance and memory usage would still be bad.
Here is a CSV Parser I often link. Could it be the droid you are looking for?
http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader