text:
Q: prerender.io with staticfile buildpack I'm trying to setup prerender.io with cloud foundry staticfile buildpack (https://github.com/cloudfoundry/staticfile-buildpack), but I can't get it to serve files correctly.
I couldn't find the default nginx.conf that staticfile uses as default. I'm using (https://github.com/cloudfoundry/staticfile-buildpack/blob/master/cf_spec/fixtures/reverse_proxy/nginx.conf) as a reference, but it does not seem to be the right one.
The nginx.conf below is partially working. For some reason, css is being loaded, however they are not being rendered. Just browser default styles are displayed.
A online preview of the server can be accessed at http://cabemcasa-front-staging-dev.mybluemix.net/
worker_processes 1;
daemon off;
error_log <%= ENV["APP_ROOT"] %>/nginx/logs/error.log;
events {
    worker_connections 1024;
}
http {
  log_format cloudfoundry '$http_x_forwarded_for - $http_referer - [$time_local] "$request" $status $body_bytes_sent';
  access_log <%= ENV["APP_ROOT"] %>/nginx/logs/access.log cloudfoundry;
  default_type application/octet-stream;
  sendfile on;
  gzip on;
  tcp_nopush on;
  keepalive_timeout 30;
  server {
    listen <%= ENV["PORT"] %>;
    server_name localhost;
    location / {
      root <%= ENV["APP_ROOT"] %>/public;
      index index.html index.htm Default.htm;
    }

    # location @prerender {
    #         proxy_set_header X-Prerender-Token xxx;

    #         set $prerender 0;
    #         if ($http_user_agent ~* "baiduspider|twitterbot|facebookexternalhit|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator") {
    #             set $prerender 1;
    #         }
    #         if ($args ~ "_escaped_fragment_") {
    #             set $prerender 1;
    #         }
    #         if ($http_user_agent ~ "Prerender") {
    #             set $prerender 0;
    #         }
    #         if ($uri ~ "\.(js|css|xml|less|png|jpg|jpeg|gif|pdf|doc|txt|ico|rss|zip|mp3|rar|exe|wmv|doc|avi|ppt|mpg|mpeg|tif|wav|mov|psd|ai|xls|mp4|m4a|swf|dat|dmg|iso|flv|m4v|torrent)$") {
    #             set $prerender 0;
    #         }

    #         #resolve using Google's DNS server to force DNS resolution and prevent caching of IPs
    #         resolver 8.8.8.8;
    #         if ($prerender = 1) {
    #             #setting prerender as a variable forces DNS resolution since nginx caches IPs and doesnt play well with load balancing
    #             set $prerender "service.prerender.io";
    #             rewrite .* /$scheme://$host$request_uri? break;
    #             proxy_pass http://$prerender;
    #         }
    #         if ($prerender = 0) {
    #             # rewrite .* /index.html break;
    #         }
    #     }
  }
}

A: I have done something similar in another project. Try this:
worker_processes  1;

events {
    worker_connections  1024;
}
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;
    gzip  on;

    server {
        listen      <%= ENV["PORT"] %>;
        root   <%= ENV["APP_ROOT"] %>/public;
        index  index.html;
        server_name  localhost;
        location / {
            try_files $uri @prerender;
        }

        location @prerender {
            proxy_set_header X-Prerender-Token sSfyna56hdgshmXfr24O;

            set $prerender 0;
            if ($http_user_agent ~* "baiduspider|twitterbot|facebookexternalhit|rogerbot|linkedinbot|embedly|quora link preview|showyoubot|outbrain|pinterest|slackbot|vkShare|W3C_Validator") {
                set $prerender 1;
            }
            if ($args ~ "_escaped_fragment_") {
                set $prerender 1;
            }
            if ($http_user_agent ~ "Prerender") {
                set $prerender 0;
            }
            if ($uri ~ "\.(js|css|xml|less|png|jpg|jpeg|gif|pdf|doc|txt|ico|rss|zip|mp3|rar|exe|wmv|doc|avi|ppt|mpg|mpeg|tif|wav|mov|psd|ai|xls|mp4|m4a|swf|dat|dmg|iso|flv|m4v|torrent)$") {
                set $prerender 0;
            }

            resolver 8.8.8.8;
            if ($prerender = 1) {
                set $prerender "service.prerender.io";
                rewrite .* /$scheme://$host$request_uri? break;
                proxy_pass http://$prerender;
            }
            if ($prerender = 0) {
                rewrite .* /index.html break;
            }

        }
    }
}


text:
Q: Added to Rails app on Heroku. How to setup database in local environment? I was recently added to a Rails application via Heroku. I'm able to clone the app to my local machine using:
heroku git:clone -a appname

However, I have issues running local tests and other tasks related to not having a local database. The production environment uses Postgres and the development environment uses sqlite3. What's the best way to get a local database setup?

A: Simply pull the production database from Heroku. Run the following once you have heroku_toolbelt and you have access to the app on Heroku:
heroku pg:pull DATABASE_URL app_development --app app_name_on_heroku_here

This will create a new database locally named "app_development" so rename it to your app. See config/database.yml for your development database name.

A: You will need to setup the databases required for development. This can be done using the built in rake db tasks:
rake db:create
rake db:migrate

This should see your local database created and migrated up to the latest migration.

A: As you have successfully clone rails project from Heroku and your production database is PostgreSQL which is different from your local database SQLite you should update some files from your local project
1. remove or comment "gem pg" and add gem 'sqlite3' and run bundle install
2. Make changes in your database.yml file

default: &default
  adapter: sqlite3
  pool: 5
  timeout: 5000

development:
  <<: *default
  database: db/development.sqlite3

3 run rake db:create
4 run rake db:migrate
5 if you have data in seed file run rake db:seed

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I modify an existing file to add the ability to unlink a specific file from a folder? Thank you StackOverflow experts for looking at my question.
First, It is possible this question has been asked before but my situation is a bit unique. So, please hear me out.
When our users want to edit an existing record, they would also like to have the ability to delete an existing pdf file if one exists before adding a new one.
To display an existing file, I use this code.

         <?php
         // if the BidIDFile is empty,
         if(empty($result["BidIDFile"]))
         {
             //then show file upload field for Bid File
             echo '<input type="file" name="BidIDFile[]" size="50">';
         }
         else
         {
             // Bid file already upload, show checkbox to delete it.
             echo '<input type="checkbox" name="delete[]" value="'.$result["BidIDFile"].'"> (delete)
             '.$result["BidIDFile"].'';
         }

Then to delete this file, I use the following code:
// Connect to SQL Server database
include("connections/Connect.php");

// Connect to SQL Server database
include("connections/Connect.php");

$strsID = isset($_GET["Id"]) ? $_GET["Id"] : null;

if(isset($_POST['delete']))
{
    // whilelisted table columns
    $fileColumnsInTable = array( 'BidIDFile', 'TabSheet', 'SignInSheet', 'XConnect',
                                 'Addend1', 'Addend2','Addend3','Addend4','Addend5', 'Addend6');

    $fileColumns = array();
    foreach ($_POST['delete'] as $fileColumn)
    {
        if(in_array($fileColumn, $fileColumnsInTable))
            $fileColumns[] = $fileColumn;
    }

    // get the file paths for each file to be deleted
    $stmts = "SELECT " . implode(', ', $fileColumns) . " FROM bids WHERE ID = ? ";
    $querys = sqlsrv_query( $conn, $stmts, array($strsID));
    $files = sqlsrv_fetch_array($querys,SQLSRV_FETCH_ROW);

    // loop over the files returned by the query
    foreach ($files as $file )
    {
        //delete file
        unlink($file);
    }

    // now remove the values from the table
    $stmts = "UPDATE bids SET " . impload(' = '', ', $fields) . " WHERE ID = ? ";
    $querys = sqlsrv_query( $conn, $stmts, array($strsID));

This works fine. However, the edit file points to an existing file with an INSERT and UPDATE operation in this one file (great thanks to rasclatt) and I am having problem integrating the two together.
Can someone please help with integrating the two files into one?
Thanks in advance for your assistance.
Here is the INSERT and UPDATE file:
<?php
error_reporting(E_ALL);

class   ProcessBid
    {
        public      $data;
        public      $statement;
        public      $where_vals;

        protected   $keyname;
        protected   $conn;

        public  function __construct($conn = false)
            {
                $this->conn =   $conn;
            }

        public  function SaveData($request = array(),$skip = false,$keyname = 'post')
            {
                $this->keyname              =   $keyname;
                $this->data[$this->keyname] =   $this->FilterRequest($request,$skip);

                return $this;
            }

        public  function FilterRequest($request = array(), $skip = false)
            {
                // See how many post variables are being sent
                if(count($request) > 0) {
                        // Loop through post
                        foreach($request as $key => $value) {
                                // Use the skip
                                if($skip == false || (is_array($skip) && !in_array($key,$skip))) {
                                        // Create insert values
                                        $vals['vals'][]   =   "'".ms_escape_string($value)."'";

                                        // Create insert columns
                                        $vals['cols'][]   =   "".str_replace("txt","",$key)."";

                                        // For good measure, create an update string
                                        $vals['update'][] =   "".str_replace("txt","",$key)."".' = '."'".ms_escape_string($value)."'";

                                        // For modern day binding, you can use this array
                                        $vals['bind']['cols'][]           =   "".$key."";
                                        $vals['bind']['cols_bind'][]      =   ":".$key;
                                        $vals['bind']['vals'][":".$key]   =   $value;
                                        $vals['bind']['update'][]         =   "".$key.' = :'.$key;
                                    }
                            }
                    }

                return (isset($vals))? $vals:false;
            }

        public  function AddFiles($name = 'item')
            {
                // If the files array has been set
                if(isset($_FILES[$name]['name']) && !empty($_FILES[$name]['name'])) {

                        // Remove empties
                        $_FILES[$name]['name']      =   array_filter($_FILES[$name]['name']);
                        $_FILES[$name]['type']      =   array_filter($_FILES[$name]['type']);
                        $_FILES[$name]['size']      =   array_filter($_FILES[$name]['size']);
                        $_FILES[$name]['tmp_name']  =   array_filter($_FILES[$name]['tmp_name']);

                        // we need to differentiate our type array names
                        $use_name   =   ($name == 'item')? 'Addend':$name;
                        // To start at Addendum1, create an $a value of 1

                        $a = 1;
                        if(!empty($_FILES[$name]['tmp_name'])) {

                                 foreach($_FILES[$name]['name'] as $i => $value ) {
                                        $file_name  =   ms_escape_string($_FILES[$name]['name'][$i]);
                                        $file_size  =   $_FILES[$name]['size'][$i];
                                        $file_tmp   =   $_FILES[$name]['tmp_name'][$i];
                                        $file_type  =   $_FILES[$name]['type'][$i];

                                        if(move_uploaded_file($_FILES[$name]['tmp_name'][$i], $this->target.$file_name)) {
                                                // Format the key values for addendum
                                                if($name == 'item')
                                                    $arr[$use_name.$a]      =   $file_name;
                                                // Format the key values for others
                                                else
                                                    $arr[$use_name] =   $file_name;

                                                $sql    =   $this->FilterRequest($arr);

                                                // Auto increment the $a value
                                                $a++;
                                            }
                                    }
                            }
                    }

                if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
                    $this->data[$name]  =   $sql;

                return $this;
            }

        public  function SaveFolder($target = '../uploads/')
            {
                $this->target   =   $target;

                // Makes the folder if not already made.
                if(!is_dir($this->target))
                    mkdir($this->target,0755,true);

                return $this;
            }

        public  function where($array = array())
            {
                $this->where_vals   =   NULL;

                if(is_array($array) && !empty($array)) {
                        foreach($array as $key => $value) {
                                $this->where_vals[] =   $key." = '".ms_escape_string($value)."'";
                            }
                    }

                return $this;
            }

        public  function UpdateQuery()
            {
                $this->data         =   array_filter($this->data);

                if(empty($this->data)) {
                        $this->statement    =   false;
                        return $this;
                    }

                if(isset($this->data) && !empty($this->data)) {

                        foreach($this->data as $name => $arr) {
                                $update[] =   implode(",",$arr['update']);
                            }
                    }

                $vars       =   (isset($update) && is_array($update))? implode(",",$update):"";

                // Check that both columns and values are set
                $this->statement    =   (isset($update) && !empty($update))? "update bids set ".implode(",",$update):false;

                if(isset($this->where_vals) && !empty($this->where_vals)) {
                        $this->statement    .=  " where ".implode(" and ",$this->where_vals);
                    }

                return $this;
            }

        public  function SelectQuery($select = "*",$table = 'bids')
            {
                $stmt               =   (is_array($select) && !empty($select))? implode(",",$select):$select;

                $this->statement    =   "select ".$stmt." from ".$table;

                return $this;
            }

        public  function InsertQuery($table = 'bids')
            {
                $this->data         =   array_filter($this->data);

                if(empty($this->data)) {
                        $this->statement    =   false;
                        return $this;
                    }

                $this->statement    =   "insert into ".$table;

                if(isset($this->data) && !empty($this->data)) {

                        foreach($this->data as $name => $arr) {
                                $insert['cols'][] =   implode(",",$arr['cols']);
                                $insert['vals'][] =   implode(",",$arr['vals']);
                            }
                    }

                $this->statement    .=  '(';
                $this->statement    .=  (isset($insert['cols']) && is_array($insert['cols']))? implode(",",$insert['cols']):"";
                $this->statement    .=  ") VALUES (";
                $this->statement    .=  (isset($insert['vals']) && is_array($insert['vals']))? implode(",",$insert['vals']):"";
                $this->statement    .=  ")";

                return $this;
            }
    }

include("../Connections/Connect.php");
function render_error($settings = array("title"=>"Failed","body"=>"Sorry, your submission failed. Please go back and fill out all required information."))
    { ?>

<?php echo (isset($settings['title']))? $settings['title']:"Error"; ?>

<?php echo (isset($settings['body']))? $settings['body']:"An unknown error occurred."; ?>

<?php
    }

// this function is used to sanitize code against sql injection attack.
function ms_escape_string($data)
    {
        if(!isset($data) || empty($data))
            return "";

        if(is_numeric($data))
            return $data;

        $non_displayables[] =   '/%0[0-8bcef]/';    // url encoded 00-08, 11, 12, 14, 15
        $non_displayables[] =   '/%1[0-9a-f]/';     // url encoded 16-31
        $non_displayables[] =   '/[\x00-\x08]/';    // 00-08
        $non_displayables[] =   '/\x0b/';           // 11
        $non_displayables[] =   '/\x0c/';           // 12
        $non_displayables[] =   '/[\x0e-\x1f]/';    // 14-31

        foreach($non_displayables as $regex)
            $data   =   preg_replace($regex,'',$data);
            $data   =   str_replace("'","''",$data);
        return $data;
    }

    // New bid save engine is required for both sql statement generations
    $BidSet =   new ProcessBid($conn);
    $strId = null;

    if(isset($_POST["Id"]))
    {
        $strId = $_POST["Id"];
        //echo $strId;
    }
    If ($strId == "") {
    //echo "This is an insert statement";
    // This will generate an insert query
    $insert =   $BidSet->SaveData($_POST)
                        ->SaveFolder('../uploads/')
                        ->AddFiles('BidIDFile')
                        ->AddFiles('item')
                        ->AddFiles('SignInSheet')
                        ->AddFiles('TabSheet')
                        ->AddFiles('Xcontract')
                        ->InsertQuery()
                        ->statement;

    // Check that statement is not empty
    if($insert != false) {
            sqlsrv_query($conn,$insert);
            render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to Solicitation screen'));
            $err    =   false;
        }

    //echo '
';
    //print_r($insert);
//  echo '
';
    }
    else
    {
    //echo "This is an update statement";
    // This will generate an update query
    $update =   $BidSet->SaveData($_POST,array("Id"))
                        ->SaveFolder('../uploads/')
                        ->AddFiles('BidIDFile')
                        ->AddFiles('item')
                        ->AddFiles('SignInSheet')
                        ->AddFiles('TabSheet')
                        ->AddFiles('Xcontract')
                        ->where(array("Id"=>$_POST["Id"]))
                        ->UpdateQuery()
                        ->statement;

    //echo '
';
    //print_r($update);
    //echo '
';
    // Check that statement is not empty
    if($update != false) {
            sqlsrv_query($conn,$update);
            render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to admin screen'));
            $err    =   false;
        }
    }
    // This will post an error if the query fails
    if((isset($err) && $err == true) || !isset($err))
        render_error(); ?>


text:
Q: Rails logging from controller upload method I am very new to Rails, and I can't understand how can I log something from a particular controller method. I implemented a simple file upload, with fileutils:
    def file_upload
        require 'fileutils'
        require 'rest_client'
        tmp = params[:file_upload][:my_file].tempfile

        logger.info 'log information with logger'
        puts 'log information with puts'
        p 'log information with p'

        file = File.join("public", params[:file_upload][:my_file].original_filename)
        FileUtils.cp tmp.path, file

        RestClient.post 'http://externalapi', :destination => 'address', :subject => 'subject', :file => file, :api_key => 'apikey'

    end

but from within this method the logging doesn't works. However it does within any other method. I am using Ruby 1.9.3 and Rails 4


text:
Q: How i add javax.media.jai.* package in project? I read the posts and download the cross platform ZIP file which contain jmf.jar file.
But this jar does not contain only javax.media.jai package.
where i get this jar?

A: You could try using maven. Here is the maven repo...
http://mvnrepository.com/artifact/javax.media/jai_core/1.1.3
Or download the source from here
http://www.oracle.com/technetwork/java/current-142188.html


text:
Q: Solr 5.3.1 core missing when restart but still there Every time the server restarts the core is 'missing', but when I go to add it back I get an error about creating a core that already exists. The solr log file says:
"Could not create a new core in /opt/solr-5.3.1/server/webapps/[corename]/as another core is already defined there"
The core.properties file only has one line, it says name=[corename]. This is not a multi-core setup, it's just one core. However, every time the server restarts (including automatically or during a power outage) the core disappears and thus breaks the search on client-side because the core is no longer accessible for it. How can I get the core to persist on start-up? I read elsewhere I should check permissions, but what should I check exactly?
Using Solr 5.3.1 on CentOS 7.
EDIT: OK, so I noticed that the solr user owns all the folders EXCEPT for the webapps, which is owned by the root user. Could this be causing the issue?
EDIT: changed permissions and that does nothing. Core still always disappears on restart and needs to be manually added back via admin console, which throws error message as above.

A: If you have installed Solr from default installation script you should look for core in /var/solr/ location and deleting the dir(If you have no data) manually followed by solr restart. hth.

A: I solved this issue by 1) creating a new core at command line to be placed in the solr home (which was under var/solr), 2) copying over the conf files from the data directory in the old core, and 3) re-indexing.


text:
Q: How to choose fitness function Heuristiclab for classification? I have a classification problem. I want to use Heuristiclab to solve it.
When I tried to see fitness function parameter, there are only two textboxes for (start,end) I don't know what it means? And how can I choose the best fitness for my problem?
Here is the link:http://dev.heuristiclab.com/.
I use labeled dataset from UCI. The task is to use genetic optimization tool for predication.
Thanks


text:
Q: Prevent screen blur in React Native Navigation React Navigation library  supply me the blur event, that trigs when the focused screen is going to be unfocused. Great.
But what if I need to prevent the blur action itself by stopping the user to go away from this screen? The docs only mentions the 'beforeRemove' event, that is something else.
Is there a way to prevent a user to go away from a screen using the screen component logic?

A: Basically, blur event's callback function must navigate to this page


text:
Q: How to select two list items at same time ? To be specific ONLY TWO items not more than that I have a list view like the below image.

Now I want to select Only Any two items from the list view at a time and pass the values of both listview items with Intent to next activity. How can I achieve it.?
If Both items are not selected set validation on it?
AdapterClass
public class LoadAdapter extends BaseAdapter {
    private ArrayList<DataBase> mProductItems;
    private LayoutInflater mLayoutInflater;
    private Context mContext;
    DBHelper mydb;
    DataBase stringItem;
    public LoadAdapter(Context context, ArrayList<DataBase> arrayList){
        mContext = context;
        mProductItems = arrayList;
        mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        Log.e("testtt", String.valueOf(mProductItems.size()));
        return mProductItems.size();

    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        final ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder();
            convertView = mLayoutInflater.inflate(R.layout.load_chart_item, parent, false);
            holder.txtv_name = (TextView) convertView.findViewById(R.id.text);
            holder.nameid = (TextView) convertView.findViewById(R.id.nameid);
            holder.btn_delete = (Button) convertView.findViewById(R.id.btn_delete);
            holder.btn_edit = (Button)convertView.findViewById(R.id.btn_edit);
            holder.location = (TextView)convertView.findViewById(R.id.loc);
            holder.img= (ImageView)convertView.findViewById(R.id.img);
            holder.btn_delete.setTag(position);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder)convertView.getTag();
        }

        mydb = new DBHelper(mContext);

         stringItem = mProductItems.get(position);

        if (stringItem != null) {
            if (holder.txtv_name != null) {

                holder.txtv_name.setText(stringItem.getName());
                holder.nameid.setText(stringItem.getId());
                holder.location.setText(stringItem.getLocation());
                Log.e("saved Location  values",stringItem.getLocation());
            }
        }

 if(selected.get(position))
    {
        //for selected row
        holder.img.setBackgroundResource(R.drawble.myimg)
    }
    else
    {
        // for not selected row

    }

        holder.btn_delete.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                DataBase test = mProductItems.get(position);
                String id =  test.getId();

                mydb.deleteContact(Integer.valueOf(id));
                mProductItems.remove(mProductItems.get(position));
                LoadAdapter.this.notifyDataSetChanged();

                if (mProductItems.size() == 0){
                    mProductItems.clear();
                    LoadAdapter.this.notifyDataSetChanged();
                }

            }
        });

        Log.e("DataBase", String.valueOf(mydb.getAllCotacts()));

        holder.btn_edit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent=new Intent(mContext,UpdateData.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                SharedPreferences preff = PreferenceManager.getDefaultSharedPreferences(mContext);
                SharedPreferences.Editor edi = preff.edit();
                edi.putString("key",String.valueOf(position+1));
                edi.apply();

                mContext.startActivity(intent);
            }
        });

              return convertView;
    }

    public void refresh(ArrayList<DataBase> items)
    {
        this.mProductItems = items;
        notifyDataSetChanged();
    }

    private static class ViewHolder {
        ImageView img;
        TextView txtv_name,nameid,location;
        Button btn_delete,btn_edit;
    }
}

Main Class
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.util.ArrayList;

public class LoadChart extends AppCompatActivity {
    public final static String EXTRA_MESSAGE = "MESSAGE";
    private SwipeListView listView;
    DBHelper mydb;
    Button det;
    LoadAdapter loadAdapter;
    ArrayList<DataBase> array_list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.load_chart);

         mydb = new DBHelper(this);
         array_list = mydb.getAllCotacts();
        Log.e("logging", String.valueOf(array_list));
     //   ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,R.layout.load_chart_item,R.id.text, array_list);

          det = (Button)findViewById(R.id.reli);

        listView = (SwipeListView) findViewById(R.id.listview);
        listView.setAdapter(new LoadAdapter(getApplicationContext(),array_list));

        det.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String str = "";
            str =  relationAdapter.getSelected();
            Toast.makeText(RelationShipChartList.this, str, Toast.LENGTH_SHORT).show();

        }
    });

        listView.setSwipeListViewListener(new BaseSwipeListViewListener() {
            int openItem = -1;
            int lastOpenedItem = -1;
            int lastClosedItem = -1;

            @Override
            public void onOpened(int position, boolean toRight) {
                lastOpenedItem = position;

                int index = position - listView.getFirstVisiblePosition();
                View view = listView.getChildAt(index);
                Button delete = (Button) view.findViewById(R.id.btn_delete);
                Button edit = (Button) view.findViewById(R.id.btn_edit);

               if (!toRight) {

                    delete.setVisibility(View.VISIBLE);
                    edit.setVisibility(View.VISIBLE);

                }

                if (openItem > -1 && lastOpenedItem != lastClosedItem) {
                    listView.closeAnimate(openItem);

                }
                openItem = position;
            }

            @Override
            public void onStartClose(int position, boolean right) {
                Log.d("swipe", String.format("onStartClose %d", position));
                lastClosedItem = position;

            }

            @Override
            public void onClosed(int position, boolean fromRight) {

                int index = position - listView.getFirstVisiblePosition();
                View view = listView.getChildAt(index);
                Button delete = (Button) view.findViewById(R.id.btn_delete);
                Button edit = (Button) view.findViewById(R.id.btn_edit);

                if (!fromRight) {

                    delete.setVisibility(View.INVISIBLE);
                    edit.setVisibility(View.INVISIBLE);

                }

            }

            @Override
            public void onListChanged() {

            }

            @Override
            public void onMove(int position, float x) {

            }

            @Override
            public void onStartOpen(int position, int action, boolean right) {
            }

            @Override
            public void onClickFrontView(int position) {

                int id_To_Search = position;

                DataBase test = array_list.get(position);
                String id =  test.getId();
                String name = test.getName();
                String loc = test.getLocation();
                String dt = test.getDate();
                String time = test.getTime();

                Bundle dataBundle = new Bundle();
                dataBundle.putString("name",name);
                dataBundle.putString("date",dt);
                dataBundle.putString("time",time);
                dataBundle.putString("location",loc);
                dataBundle.putInt("id", Integer.parseInt(id));
                Intent intent = new Intent(getApplicationContext(),LoadedChart.class);
                intent.putExtras(dataBundle);
                startActivity(intent);

            }

            @Override
            public void onClickBackView(int position) {

                Log.e("swipe", String.format("onClickBackView %d", position));
            }

            @Override
            public void onDismiss(int[] reverseSortedPositions) {

            }

        });
    }

    public int convertDpToPixel(float dp) {
        DisplayMetrics metrics = getResources().getDisplayMetrics();
        float px = dp * (metrics.densityDpi / 160f);
        return (int) px;
    }
    @Override
    public void onResume()
    {
        super.onResume();
        Set_Referash_Data();

    }

    public void Set_Referash_Data() {
        array_list.clear();
        mydb = new DBHelper(this);

        ArrayList<DataBase> con = mydb.getAllCotacts();

        for (int i = 0; i < con.size(); i++) {

            String  tidno = con.get(i).getId();
            String name = con.get(i).getName();
            String cons = con.get(i).getCon();
            String loc = con.get(i).getLocation();
            DataBase cnt = new DataBase();
            cnt.setId(tidno);
            cnt.setName(name);
            cnt.setCon(cons);
            cnt.setLocation(loc);
            array_list.add(cnt);

            Log.e(String.valueOf(array_list),"RefreshData");

        }
        mydb.close();

        array_list = mydb.getAllCotacts(); //reload the items from database
        LoadAdapter ld = new LoadAdapter(getApplicationContext(),array_list);
        listView.setAdapter(ld);
        ld.refresh(array_list);
        ld.notifyDataSetChanged();
        Log.e(String.valueOf(array_list),"RefreshData Final");
    }

}

Logcat
05-09 14:47:50.706 29939-29939/com.example.user.humandesignsample E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                Process: com.example.user.humandesignsample, PID: 29939
                                                                                java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.user.humandesignsample.RelationAdapter.getSelected()' on a null object reference
                                                                                at com.example.user.humandesignsample.RelationShipChartList$1.onClick(RelationShipChartList.java:45)
                                                                                at android.view.View.performClick(View.java:5204)
                                                                                at android.view.View$PerformClick.run(View.java:21153)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:148)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

A: I would use Action Mode with MultiChoiceModeListener.
http://developer.android.com/reference/android/widget/AbsListView.MultiChoiceModeListener.html
There is a callback onItemCheckedStateChanged(ActionMode mode, int position, boolean checked).
You can easily get values of already checked list items ListView.getCheckedItemPositions. So you can prevent selection, if you already selected two or even at once pass the values(or ids) of selected ones without any effort.

A: You can simply put a counter on item selection.
Take a variable say for ex.
int count = 0;

Check this variable before marking item as selected/deselected:
if(item.isSelected())
{
   // you need to make is disable
   if(count>0)
   {
      count--;
      // // mark item as deselected
   }
}
else
{
   // make it selected
     if(count<2)
     {
        count++;
        // mark item as selected
     }
}

This will make you select ONLY TWO items at a time.
Modify your adapter like this:
public class LoadAdapter extends BaseAdapter {
private ArrayList<DataBase> mProductItems;
private LayoutInflater mLayoutInflater;
private Context mContext;
DBHelper mydb;
DataBase stringItem;
ArrayList<Boolean> selected = new ArrayList<>();
private int count=0;

public LoadAdapter(Context context, ArrayList<DataBase> arrayList){
    mContext = context;
    mProductItems = arrayList;
    mLayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    for (int i = 0; i < arrayList.size(); i++) {

        selected.add(false);

    }
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
    Log.e("testtt", String.valueOf(mProductItems.size()));
    return mProductItems.size();

}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    // TODO Auto-generated method stub
    final ViewHolder holder;

    if (convertView == null) {
        holder = new ViewHolder();
        convertView = mLayoutInflater.inflate(R.layout.load_chart_item, parent, false);
        holder.txtv_name = (TextView) convertView.findViewById(R.id.text);
        holder.nameid = (TextView) convertView.findViewById(R.id.nameid);
        holder.btn_delete = (Button) convertView.findViewById(R.id.btn_delete);
        holder.btn_edit = (Button)convertView.findViewById(R.id.btn_edit);
        holder.location = (TextView)convertView.findViewById(R.id.loc);
        holder.btn_delete.setTag(position);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder)convertView.getTag();
    }

    mydb = new DBHelper(mContext);

    stringItem = mProductItems.get(position);

    if (stringItem != null) {
        if (holder.txtv_name != null) {

            holder.txtv_name.setText(stringItem.getName());
            holder.nameid.setText(stringItem.getId());
            holder.location.setText(stringItem.getLocation());
            Log.e("saved Location  values",stringItem.getLocation());
        }
    }

    if(selected.get(position))
    {
        //for selected row
        holder.txtv_name.setTextColor(color.red);
    }
    else
    {
        // for not selected row
        holder.txtv_name.setTextColor(color.black);
    }

    holder.txtv_name.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if(holder.txtv_name.getCurrentTextColor()== R.color.black)
            {
                //is not selected
                if(count<2)
                {
                    count++;
                    selected.set(position,true);

                    // mark item as selected
                }
            }
            else
            {
                //is selected
                if(count>0)
                {
                    count--;
                    selected.set(position,false);

                    // // mark item as deselected
                }
            }
            notifyDataSetChanged();
        }
    });

    holder.btn_delete.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            DataBase test = mProductItems.get(position);
            String id =  test.getId();

            mydb.deleteContact(Integer.valueOf(id));
            mProductItems.remove(mProductItems.get(position));
            LoadAdapter.this.notifyDataSetChanged();

            if (mProductItems.size() == 0){
                mProductItems.clear();
                LoadAdapter.this.notifyDataSetChanged();
            }

        }
    });

    Log.e("DataBase", String.valueOf(mydb.getAllCotacts()));

    holder.btn_edit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent=new Intent(mContext,UpdateData.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            SharedPreferences preff = PreferenceManager.getDefaultSharedPreferences(mContext);
            SharedPreferences.Editor edi = preff.edit();
            edi.putString("key",String.valueOf(position+1));
            edi.apply();

            mContext.startActivity(intent);
        }
    });

    return convertView;
}

public void refresh(ArrayList<DataBase> items)
{
    this.mProductItems = items;
    notifyDataSetChanged();
}

private static class ViewHolder {
    TextView txtv_name,nameid,location;
    Button btn_delete,btn_edit;
}}

EDIT 2: For getting selected items from adapter define below method in
  adapter and call it with an adapter object like : adp.getSelected()

public String getSelected() {
    String selectedString = "";
    int num=0;
    for (int i = 0; i < selected.size(); i++) {
        if (selected.get(i)) {
            num++;
            if (num == 1) {
                selectedString = mProductItems.get(i).getName();
            } else {
                selectedString += "," + mProductItems.get(i).getName();
            }
        }
    }
    return selectedString;
}

Answer to issue 2 : If you want to use ImageView instead of text color change. The do the same things as above but replace the TextView + Color with ImageView + Image.
EDIT 3:
You have called the getSelected() method from a Null object. Modify your code like this:
 listView = (SwipeListView) findViewById(R.id.listview);
 loadAdapter = new LoadAdapter(getApplicationContext(),array_list);
    listView.setAdapter(loadAdapter);

    det.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        String str = "";
        str =  loadAdapter.getSelected();
        Toast.makeText(RelationShipChartList.this, str, Toast.LENGTH_SHORT).show();

    }


text:
Q: How to parse CSVs with newline and commas inside a field in Perl? I'm new to Perl. This is a sample csv entry similar to mine.
I would like to parse this, tried briefly Text::CSV, but no luck. The issue here is newline and
commas inside fields. How could I parse this file in Perl? Thanks for the help.
1,A,"Length of x, where x is y"
2,B,"Set A to "10", an invalid state"
3,C,"Solve
A+B and
B+A
"
4,D, Set C to B

A: This code (taken directly from Text::CSV documentation):
#!/usr/bin/perl

use strict;
use Text::CSV;
use Data::Dumper;

my $rows;
my $csv = Text::CSV->new ( { binary => 1 } )  # should set binary attribute.
                 or die "Cannot use CSV: ".Text::CSV->error_diag ();

open my $fh, "<", "test.csv" or die "test.csv: $!";

while ( my $row = $csv->getline( $fh ) ) {
     push @{$rows}, $row;
}

$csv->eof or $csv->error_diag();

close $fh;

# This gets rid of spaces at start and end of string
# as well as newlines within the fields.
for ( 0 .. scalar @{$rows}-1 ) {
    $rows->[$_][2] =~ s/^\s*//;
    $rows->[$_][2] =~ s/\n/ /gms;
}

print Dumper($rows);

Produces the following output:
$VAR1 = [
          [
            '1',
            'A',
            'Length of x, where x is y'
          ],
          [
            '2',
            'B',
            'Set A to "10", an invalid state'
          ],
          [
            '3',
            'C',
            'Solve A+B and B+A '
          ],
          [
            '4',
            'D',
            'Set C to B'
          ]
        ];

Which (I'm guessing) is what you want to achieve.

A: Thanks Everyone who commented, I figured it out. The thing I didn't do was
{ binary => 1, eol => $/ }

Here is the working code:
#!/usr/bin/perl

use 5.010;
use strict;
use warnings;
use Text::CSV;

open(my $Fh, "<", 'datalane_csr.csv');

my $csv = Text::CSV->new ({ binary => 1, eol => $/ });
while (my $row = $csv->getline ($Fh)) {
  say @$row[2];
  }

close(CSV);

Thanks once again. And sorry for the post.
But I have a small issue, the '"' is shown as wierd characters when I print them.


text:
Q: Why does Nginx's proxy_intercept_errors directive require a rewrite to work properly? Following is a sample Nginx server configuration. Without the "magical talisman" location block, proxied error content results in an Nginx 404 page rather than the customized error page being served.
Removing the proxy_intercept_errors directive serves a proper proxied error page with proper http error code headers.
Nonproxied error pages are rendered properly regardless of the presence of the magical talisman.
Any ideas as to what exactly is going on?
server {
    server_name     mydomain.com "";
    listen          80;
    root            /var/www;
    error_page      400 401 402 403 404 500 501 502 503 504 /admin/error_page.htm;
    proxy_intercept_errors on;

    location /proxy/ {
        proxy_read_timeout  60s;
        proxy_set_header    Host $host;
        proxy_pass          http://myservers;
    }

    location /test404/ {
        return 404;
    }

    location /admin/ {    # this line constitute a magical talisman that fixes proxied error interception(???)(!)
        rewrite ^(/admin)(.*)$ /admin$2 break;
    }
}

A: I am sorry this answer kicks in late, bu as of now, with the current v1.8.1 stable version, the configuration you provided should work without any talisman.
If you provided the version which you were experimenting on, it would be an idea to see if a bug has been corrected or if the configuration was flawed.
I suggest you double check your configuration, since you definitely do not need this /admin/ location nor its contained rewrite directive. Take a very special care at removing everything which is not part of this test (and that you do not show) as it might interfere.
As a last resort, you could try this following, successfully tested, configuration snippet, and slowly integrate changes and see at which point results diverge from expectations:
server {
    listen      80;
    listen      [::]:80;
    server_name example.org;

    location /proxy {
        return 418 "Host: $host, Connection: $http_connection";
    }
}

server {
    listen      80;
    listen      [::]:80;
    server_name example.com;

    root /var/ious/files;

    error_page 418 = /error_page.html;
    proxy_intercept_errors on;

    location /proxy {
        proxy_pass http://example.org;
    }
}


text:
Q: Promises vs Async/Await in React All the official documentation and examples I saw so far use Promises for asynchronous executions, for example (from The Road to Learn React book):
class App extends Component {
    //...
    fetchSearchTopStories(searchTerm, page = 0) {
        fetch(`${PATH_SEARCH}?${PARAM_SEARCH}${searchTerm}`)
            .then(result => this.setSearchTopStories(result.data))
            .catch(error => this.setState({ error }));
    }
    //...
}

Why are Promises the preferred way? It there anything to prevent from using async/await in this manner?:
class App extends Component {
    //...
    async fetchSearchTopStories(searchTerm, page = 0) {
        try {
            const result = await fetch(`${PATH_SEARCH}?${PARAM_SEARCH}${searchTerm}`);
            this.setSearchTopStories(result.data);
        } catch (error) {
            this.setState({ error });
        }
    }
    //...
}

A: Javascript's purpose has been, for quite some time already, of being a multi-paradigm language (although it was often classified as a functional one due to its constructions being more easily associated to this specific paradigm). For instance, not that long ago JS's support for the object-oriented programming approach was existent but notoriously hacky, as you would declare a function and give it methods, attributes, etc, which would enable that function to actually work as, and be, a class (although a somewhat strange, anti-intuitive one).
However, javascript has been growing a lot in popularity lately, which notoriously began after the world became conscious of node.js's potential, and, in response to this, the people responsible for ECMAScript (JS's official standard) started to take consistency and de facto multi-paradigm support a lot more seriously, and then ES6 was launched in 2015 aiming to address the hacky, unstandardized constructs so common (and so criticized) in javascript's environment.
With ES6 came a more obvious support for object-orientation (such as the class keyword for example), but, given JS's bad reputation with its multi-paradigm support so far, the ECMAScript committee was clearly trying to compensate. The await keyword is an effect of this attempt, as asynchronous programming in JS has usually been made via the functional approach, chaining one function after another, each executing once the previous function finished its execution (an approach which makes a lot of sense, since things such as requests to external servers cannot have their exact response time reasonably predicted). await offers a possibility of a structured approach to this problem (in a very simplified explanation, structured programming means "one line of code instantly executing after another"), as fetch without await would return an unsolved promise and the code would follow its execution ignoring fetch's actual response, but with the await keyword in place the code will cease to execute until the actual response comes (the external server's data or an error, not a promise).
Therefore, even though they can be considered equivalent, the functional approach has been around for more time and so it is the JS way to do things.

A: While the same results can be achieved with both (promises and async/await), there are still minor differences between them:

*

*Only the promise chain itself is asynchronous <=> The entire async wrapped function is asynchronous

Promises exist longer than async/await style, there are more examples and it works.
I personally prefer the await/async style, because it looks much cleaner and the error handling is better, especially when chaining.
But in the end it does not matter which one you use, both will work.


text:
Q: Probability of choosing 5 out of 60 in ascending order. The title may be a little misleading. Let's say we choose 5 out of 60 balls. We write down the result which are in a form as $k_1,k_2,k_3,k_4,k_5$.

I have to calculate the probability of this happening :

\begin{aligned}k_1<k_2<k_3<k_4<k_5\end{aligned}

Also, the probability of this happening:

\begin{aligned}k_1>\max\{k_2,k_3,k_4,k_5\}\end{aligned}
We do care for the order so the number of the elements in the sample space is : $$\frac{60!}{(60-5)!}$$
I am stuck there. I can't think of anything to do to calculate those two probabilities. I would appreciate it if someone could help me. Thanks in advance!

A: Hints:
Let the balls carry the numbers $1,2,\dots,60$
For the $5$ numbers on the balls that are drawn there are $5!$ orderings with equal probability and exactly one of them is an ascending order.
All $5$ drawn balls have equal chance to be labeled with the largest number.

A: Whatever $5$ (distinct) numbers wind up being chosen, they could have come out in any of $5!=120$ orders.  So the probability they came out in increasing order is $1/120$.

A: Each choice in which $k_1 < \cdots k_5$ corresponds one-to-one to a way to pick five balls from the set of 60. Prove this statement. Then think about how many ways there are to pick 5 balls from 60.
This should be easy. The second one is a little harder, but having thought about the first one in these terms should help. Please write back if you get stuck again.


text:
Q: Tomcat 8.5.9 multiple subdomains I am trying to set up multiple subdomains on Tomcat 8.5.9 but I cannot get the syntax correct in the server.xml to get it to work.  I'm sure it's something I am missing on my end but none of the write ups I have found give the full explanation without also using Apache.  I am not using Apache or NGINX here.  I just want to set up a DEV server with multiple subdomains hosted on the same JVM.
test.foo.com
test1.foo.com
DNS is set up correctly and an nslookup to each URL gives the same public IP address.
The applications are deployed to the "test" and "test1" directories off of "webapps".
The way this is set up the test1.foo.com URL works but the test.foo.com URL is getting 404 errors when I hit it. Errors are being written to the log so it is coming up.
These are my host entries from server.xml:
  <Host name="test.foo.com"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">

    <Context docBase="test" path=""/>

    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="test_access_log" suffix=".txt"
           pattern="%h %l %u %t "%r" %s %b" />

  </Host>

  <Host name="test1.foo.com"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">

    <Context docBase="test1" path=""/>

    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="author_access_log" suffix=".txt"
           pattern="%h %l %u %t "%r" %s %b" />

  </Host>

If anybody can see any errors I'd really appreciate it.

A: (solved in comments)
Set a diferent directory for each virtual host in appBase. The general documentation does not stablish restrictions, but  the specific documentation for virtual host says you can not use the same directory for two virtual hosts

Note that the directory structures under the appBase for each host should not overlap each other.


text:
Q: typescript mapped types with overload functions I want to define a type from a interface where I change the return type to Promise of the callback return value and get the function parameters from the original definition.
// original
SET(key: string, value: string, cb?: Callback<'OK'>): R;

// wanted
SET(key: string, value: string): Promise<'OK'>

My biggest problem is that the Commands interface has a lot of overload functions and the mapped types functionality only keep the last one (overwriting the others):
set(key: string, value: string, cb?: Callback<'OK'>): R;
set(key: string, value: string, flag: string, cb?: Callback<'OK'>): R;
set(key: string, value: string, mode: string, duration: number, cb?: Callback<'OK' | undefined>): R;
set(key: string, value: string, mode: string, duration: number, flag: string, cb?: Callback<'OK' | undefined>): R;
set(key: string, value: string, flag: string, mode: string, duration: number, cb?: Callback<'OK' | undefined>): R;
SET(key: string, value: string, cb?: Callback<'OK'>): R;
SET(key: string, value: string, flag: string, cb?: Callback<'OK'>): R;
SET(key: string, value: string, mode: string, duration: number, cb?: Callback<'OK' | undefined>): R;
SET(key: string, value: string, mode: string, duration: number, flag: string, cb?: Callback<'OK' | undefined>): R;
SET(key: string, value: string, flag: string, mode: string, duration: number, cb?: Callback<'OK' | undefined>): R;

I currently build up a mapped type, which keeps only the last overload version with to much required types. That's currently my main problem. Also the Return value is not that one I want to have and the Parameters still has the cb function in it, but maybe I will find a solutions for this, but I couldn't find a solution to keep all overloaded function.
// current implementation
type PromisedCommands = {
    [X in keyof Commands<boolean>]: (...args: Parameters<Commands<boolean>[X]>) => Promise<ReturnType<Commands<boolean>[X]>>
}

The commands interface has much  more the 100 items, so it isn't an options to write them by my own and keep track of changes.
How could I keep the overload functions or change the parameters of Command functions and the return type to the callback type?


text:
Q: fadeOut element when jquery slideshow is on #1 The site in question: http://notlaura.com/dev/smfa/index-all2.php
I want the 'back to list' button (#to-list) only to appear when the first panel of the Coda Slider is hidden. This works until the first panel is encountered with the arrow navigation. My code is:
    $("#to-list").hide();

    $("li.name,a#nl").click(function(event){
        $("#to-list").fadeIn(900);
    });

    $("#to-list").click(function(event){
        $("#to-list").fadeOut(900);
    });

I tried checking for $('a[href$="#1"]') but the arrow hrefs are only #, so that doesn't work. Also tried a conditional for the URL with window.location, and checking if the panel is hidden, if( $("#list").is(":visible") ) {}
But no success. Any help is greatly appreciated - thanks in advance!

A: You could try window.location.hash
$("li.name,a#nl").click(function(event){
    if(window.location.hash == "#1") {
        $("#to-list").fadeOut(900);
    } else {
        $("#to-list").fadeIn(900);
    }
});


text:
Q: UILabel auto resize and add scroll bar if necessary? I've looked around for an answer here but didn't come along one that really helped me. directing me to a proper answer I may have missed is greatly appreciated too.
I have a label defined in the simplest manner :
    IBOutlet UILabel *eventIDLabel;
    IBOutlet UILabel *eventTitleLabel;
    IBOutlet UILabel *eventDescriptionLabel;

now the description label can vary in content. May have 1 line or multiple lines. I want the label to resize automatically. Now I also want that if more lines than current screen can show, user is enable to scroll down and see the whole content of label.
Very trivial question probably but I am really new and hoping you guys could help.
thanks :D

A: You could use a UITextView. UITextView automatically can be scrolled, when the entered text ist to long.

A: You can use [myLabel sizeToFit]
You can also read more about it here
Also if you know it's going to be relatively long, you can consider using TextView which will provide the text scrolling
Hope I helped


text:
Q: What is the "__.data" in python? When I type
import numpy as np

p = np.array([1.0, 2.0])
print(p.data)
s = p.data
print(s)
print(p)

The output is
<memory at 0x00000253683E8B88>
<memory at 0x00000253683E8B88>
[1. 2.]

What is difference between p and p.data?
In which case we use p or p.data?


text:
Q: $.datepicker.regional['fr'] is undefined? WHen i upgraded jquery and jquery ui versions from 1.3.2 & 1.7.3 to 1.7.1 & 1.8.16 i recieved the error. can sombody help me how to recitfy this.
Jquery-1.7.1.js used
jquery-ui 1.8.16

A: I don't know if you've already succeeded, but I was this error in production with debug=false in webconfig using Bundle Minification. For any reason that I don't know It doesn't do all bundle of the jQuery UI's script. I've separated the Datepicker script in other file javascript and will configure in the bundle config again. I don't know if this is your case,but with me It seems that worked. Your "datepiker" is loaded?


text:
Q: delay in update of a javascript, when returning out of a function I'm new to javascript so be gentle ;)
I wrote a script which (on a webpage) gets a song artist/title and find the albumart on last.fm ..
I use a return to exit (and restart) when the existing track name is the same as there is no need t go through the whole script when it is. I noticed however that often it appears that the script still seems to run through a number of these cycles before picking up on a new entry in the textfile it reads for the names of artist and title. Is there any way to prevent this or can I use a better way to exit or restart the function?
Not sure if I explained this correctly, but I hope you get it.. thanks

var jsnURL = "http://ws.audioscrobbler.com/2.0/?autocorrect=1&method=track.getinfo&api_key=[mykeyisprivate]&format=json&";
var playURL = "./data/nowplaying.txt";
var noImg = "./data/speaker.png";
var albumImage = noImg;
var oldtitle = "none";
var image;

var doMe = function(){
  $(document).ready(function(){

    $.get(playURL, function(sngPlaying){
/*      console.log(sngPlaying); */

      var artist = sngPlaying.split(" - ")[0];
      var title = sngPlaying.split(" - ")[1];

      if ((artist === "not running") || (title === oldtitle)) {
        return;
      };

      oldtitle = title;
/*
      console.log("Artist: "+artist);
      console.log("Title: "+title);
*/
      $.getJSON(jsnURL+"artist="+artist.replace("&","%26")+"&track="+title, function(data){

        try{
          albumImage = data.track.album.image[2]['#text'];
          if (albumImage) {
/*            console.log("Found Album Art: "+albumImage); */
          }
          else {
/*            console.log("Did not Find Album Art, using generic image");  */
            albumImage = noImg;
          };
        }
        catch(err) {
/*          console.log("Something went wrong, using generic image");  */
          albumImage = noImg;
        }

        $("#albumArt").html('');
        $("#trackArtist").html(''+artist+'');
        $("#trackTitle").html(''+title+'');

      });

    });

  });
};

setInterval(doMe, 2000);
@import url(https://fonts.googleapis.com/css?family=PT+Sans+Caption:400,700);

#nwPlayContainer {
  width: 450;
  height: 50;
  position: absolute;
  top: 0;
  left: 0;
  overflow: hidden;
/*background-color: black;
*/font-family: 'PT Sans Caption';
}

#albumArt {
  width: 46px;
  height: 46px;
  padding-left: 2px;
  padding-top: 2px;
  border-radius: 50%;
}

.albumArt {
  border-radius: 50%;
  width:46px;
  height:46px;
  }

#trackArtist {
  width: 398px;
  height: 20px;
  position: absolute;
  text-align: left;
  top: 7px;
  left: 55px;
  color: white;
  font-size: 12px;
  text-shadow:
   -1px -1px 0 #000,
    1px -1px 0 #000,
   -1px  1px 0 #000,
    1px  1px 0 #000;
  }

#trackTitle {
  width: 398px;
  height: 20px;
  position: absolute;
  text-align: left;
  top: 25px;
  left: 55px;
  color: white;
  font-size: 12px;
  text-shadow:
   -1px -1px 0 #000,
    1px -1px 0 #000,
   -1px  1px 0 #000,
    1px  1px 0 #000;
  }


text:
Q: How to make modal in vuejs 3 app with modal content in separate vue file? In @vue/cli 4.5.8 app
I want to make modal looking at example : https://v3.vuejs.org/examples/modal.html
trying to set modal content in separate vue file and failed.
I have file src/views/test2.vue :
<template>

        showModal::{{ showModal }}
;
        <button id="show-modal" @click="showModal = true">Show Modal</button>

        <modal v-if="showModal" @close="showModal = false">

            <template v-slot:header>

custom header

            </template>
        </modal>

</template>

and file with modal defined src/views/Modal.vue:
<transition name="modal">

                    <slot name="header">
                        default header
                    </slot>

                    <slot name="body">
                        default body
                    </slot>

                    <slot name="footer">
                        default footer
                        <button class="modal-default-button" @click="$emit('close')">
                            OK
                        </button>
                    </slot>

</transition>

As result I have page opened without errors, but clicking on button I got error :
runtime-core.esm-bundler.js?5c40:38 [Vue warn]: Component is missing template or render function.
  at <Modal key=0 onClose=fn >
  at <Test2Page onVnodeUnmounted=fn<onVnodeUnmounted> ref=Ref< Proxy {…} > >
  at <RouterView>
  at <App>

Which format is valid?
"core-js": "^3.6.5",
"vue": "^3.0.0",

Thanks!

A: You Modal component should be wrapped by a template tag :
<template>
<transition name="modal">

        ....

</transition>
</template>


text:
Q: how to get specific field of specific document in firestore in flutter I'm new to flutter and I'm trying to get the specific document's fields. I've saved auth id in firestore and using that auth ID in where query I'm trying to access that document and accessing displayName and storing it in userName variable but when i user Database.userName where i want to show this field it displays null on screen.
  class Database {
  static String? userName;

  static void showDisplayName() async {
  var collection = FirebaseFirestore
       .instance
       .collection('Users');

  try {
   var docSnapshot = await collection
      .where("email", isEqualTo:AuthService().currentUser!.uid)
      .snapshots().listen((event) { userName = event
      .docs[0]['displayName'];});
  }on FirebaseException catch (e){
    print(e);
  } catch (error){
    print(error);
  }
 Map<String, dynamic> data = docSnapshot as

 Map<String, dynamic>;

 userName = data['displayName'];
 }
 }

and displaying that username in drawer
  accountName: Text("${Database.userName}")


text:
Q: Autoconversion from number to NULL I am trying to generate a vector of random numbers based on a finite random variable X
With probGen function I generate a variable X, l1 is the first line and l2 is the second one.
And at this point if(sum1 >= U) I recive this error Error in if (sum1 >= U) { : argument is of length zero
This is my code:
probGen=function(n)
{
  v=vector()
  k=sample(1:n,1)
  v=rep(0,k)
  for(i in 1:n)
  {
    aux=sample(1:k,1)
    v[aux]=v[aux]+1
  }
  vfinal=vector()
  klen=0
  for(i in 1:k)
  {
    if(v[i]!=0) klen=klen+1
  }
  for(i in 1:k)
  {
    if(v[i]!=0)
      vfinal=c(vfinal,rep(1/(klen*v[i]),v[i]))
  }
  vfinal=sample(vfinal)
  return (vfinal)
}

n=22
l1=c(1:n)
l2=probGen(n)
l1
l2

simVar=function(l1,l2)
{
  variante=vector()
  U=runif(1,0,1)
  for(i in 1:length(l1))
  {
    sum1=1-1
    for(j in 1:i-1)
    {
      if(i-1>=1)
      {
        sum1=sum1+l2[j]
      }
    }
    sum2=0.0
    for(j in 1:i)
    {
      sum2=sum2+l2[j]
    }

    if(sum1 >= U)
    {
      if(U<sum2)
      {
        variante=c(variante,l1[i])
      }
    }
  }

  return (variante)
}

varR=simVar(l1,l2)
varR

Any idea?
Thanks!

A: The for(j in 1:i-1) near the top of the code for simVar is evaluating as (1:i)-1, resulting in a zero j which produces a NA value of sum1.  Use for(j in 1:(i-1)) instead.


text:
Q: Cleaner way to check if null I have a class that holds a couple of byte arrays, some could be empty some not. And I want to return the first non null array (if there is one) or null if there isn't. But the code just seems so redundant and ugly.
public byte[] getFirstPhoto() {
    if (photo1 != null) {
        return photo1;
    }
    if (photo2 != null) {
        return photo2;
    }
    if (photo3 != null) {
        return photo3;
    }
    if(videoThumbnail != null){
        return videoThumbnail;
    }
    return null;
}

Is there anyway to clean that up, or not really?

A: Yes.  Write a method something like this:
public byte[] firstNonNull(byte[]... arrays) {
    for (byte[] array : arrays) {
        if (array != null)
            return array;
    }
    return null;
}

Then call this function passing in your four arrays in the proper order.


text:
Q: jQuery LayoutCreator Plugin, 2-column layout error I am trying to implement the plugin from the site http://ajaxtown.com but i am getting errors while using it in making a 2 column layout in "px". Can you please help me.
$("#container").layout({
            cols: 2,
            layoutWidth:80px,
            left_col: {'display':true,'width':200,'id':'left_col','_class':'left_col','path':'contents/left.php'},
            content_col: {'width':800,'id':'content_col','_class':'content_col','path':'contents/center.html'},
            header: {'display':true,'id':'header','_class':'','height':'auto','path':'contents/header.html','load_once':true},
            footer: {'display':true,'id':'footer','_class':'','height':'auto','path':'contents/footer.html','load_once':true},
            menu: {'display':true,'id':'menu','_class':'','height':'auto','path':'contents/menu.html','load_once':true},
            colsPadding: 2,
            loadAtOnce: true,
            smartCSS: true,
            unit: 'px',
            preloadImage: 'ajax-loader.gif',
            paddOthers: false

        });

Can you please tell me what is wrong

A: You got an error in the JS:
layoutWidth:80px,

should be either
layoutWidth:"80px",

or
layoutWidth:80,

Im guessing the last one, since you define its pixels in the "unit" setting :)


text:
Q: Using openCV to implement SIFT in image I have tried to implement SIFT with openCV and I have refer to these links link1 and link2. Besides, I have also read the paper about SIFT written by Lowe. I have some problems about the code in link1 and link2.

*

*cv::SiftFeatureDetector detector( 0.05, 5.0 ); cv::SiftDescriptorExtractor extractor( 3.0 );
I can't totally understand the parameter in the above function. If I modify the first function to  cv::SiftFeatureDetector detector( 0.05, 10.0 ); , there is a running time OpenCV Error:Assertion failed < firstOctave>=-1 %% actualNLayers<=nOctaveLayers >.
In addition, I don't realize the parameter in the SiftDescriptorExtractor extractor( ). I know there is a distances ratio in keypoints matching, but the range is [0,1].

*I want to modify the method which I use to match to picture, so I need to extract the descriptor and the dominant orientation of each keypoint. How do I extract extract each keypoint's descriptor and dominant orientation?
Thank you very much for your reply.

A: My advice is that you should use the default parameters of the SIFT at the beginning. Then, if you're not satisfied with the results you can try to refine these parameters.
Ptr<FeatureDetector> detector = new SIFT();;
Ptr<DescriptorExtractor> extractor = new SIFT();

U can find useful information about SIFT parameters in the OpenCV implementation here: http://docs.opencv.org/modules/nonfree/doc/feature_detection.html
To compute the keypoints:
vector<KeyPoint> keypoints;
detector->detect(yourImage, keypoints);

When you compute the keypoints its orientation is automatically calculated and is associated with the parameter 'angle' of each keypoint. Please find more info here: http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_feature_detectors.html
To compute the descriptors of the keypoints:
Mat descriptors;
extractor->compute(yourImage, keypoints, descriptors);

being each row of the Mat descriptors one descriptor.
Please let me know if you have questions!
Hope this helps.

A: *

*cv::SiftFeatureDetector detector( 0.05, 5.0 ), the first param is the constrast threshold. This is the minimum amount of contrast to accept a keypoint. The second param is the edge rejection threshold. If you want to get more features, you should increase the 1st param and/or decrease the 2nd param.

*cv::SiftDescriptorExtractor extractor( 3.0 ), the param is the magnificaiton value, the descriptor size is determined by multiplying the keypoint scale by this value. Using the prefixed param is ok.

For more info: http://docs.opencv.org/2.3/modules/features2d/doc/common_interfaces_of_descriptor_extractors.html


text:
Q: How to find the max,min value for specific season per year of a column in an array in R? I have the following array which I called station:
A1 <- matrix(runif(120),24,5)
A1[1:12,1]<-2012
A1[13:24,1]<-2013
A1[1:12,2]<-(1:12)
A1[13:24,2]<-(1:12)
A1[1:12,3]<-seq(1,24,by=2)
A1[13:24,3]<-seq(1,24,by=2)

A2 <- matrix(runif(120),24,5)
A2[1:12,1]<-2012
A2[13:24,1]<-2013
A2[1:12,2]<-(1:12)
A2[13:24,2]<-(1:12)
A2[1:12,3]<-seq(1,24,by=2)
A2[13:24,3]<-seq(1,24,by=2)

station <- array(NA,c(24,5,2))
station[,,1] <- A1
station[,,2] <- A2
dimnames(station)[[2]]<-c('year','month','day','win_3','win_7')
dimnames(station)[[3]]<-c('station1','station2')
print(station)

I would like to extract max value of win_3 which I called Max_3Days through spring season (i.e, month 3,4 and 5) of each year for each station and specify the corresponding value of day and month (either 3,4 or 5).
The same thing for min value, I want to extract it from win_7 which I called Min_7Days through summer season (i.e, month 6,7 and 8) of each year for each station and specify the corresponding value of month (either 6,7 or 8) and day
I would like to keep the result in array format if it possible.
The result should be like this:
, , 1
                   Year Month day   Max_3Days   Year    Month  Day Min_7Days
  [1,]              2012     3   15      2800     2012      6    1       400
  [2,]              2013     4   2       2730     2013      6    4       100

, , 2
                   Year Month day   Max_3Days   Year    Month  Day Min_7Days
  [1,]              2012     4   15      2800     2012      7    10      250
  [2,]              2013     5   2       2750     2013      7    14      271

I did specify spring and summer season and find the max, min values when I was having only one station as a data frame format, I want to do this for about 70 station in a (matrix) of an array format, and I want to keep the result in an array:
In case of data frame (only one station):
Summer<-station[which(station$month>"5"&station$month<"9"),]
Minima<-ddply(Summer, ~ year, summarise, month=month[which.min(win_7)],day=day[which.min(win_7)], Min_7Days =min(win_7, na.rm = TRUE))

Spring<-station[which(station$month>"2"&station$month<"6"),]
Maxima<-ddply(Spring, ~ year, summarise, month=month[which.max(win_3)],day=day[which.max(win_3)], Max_3Days =max(win_3, na.rm = TRUE))

Any suggestion would be appreciated!!

A: currently i have made them into a list and went ahead.
l = vector('list', 2)
l[[1]] = data.frame(station[,,1])
l[[2]] = data.frame(station[,,2])

spring_end   <- 5
spring_start <- 3
summer_end   <- 8
summer_start <- 6

library(dplyr)
func <- function(df){

  df %>% group_by(year) %>%
         summarise(   Max_3Days    = max(win_3[between(month, spring_start, spring_end)]),
                      Month_spring = month[between(month, spring_start, spring_end)][which.max(win_3[between(month, spring_start, spring_end)])],
                      Min_7Days    = min(win_7[between(month, summer_start, summer_end)]),
                      Month_summer = month[between(month, summer_start, summer_end)][which.min(win_7[between(month, summer_start, summer_end)])])
}

lapply(l, func)

#[[1]]
#   year Max_3Days Month_spring Min_7Days Month_summer
#1  2012 0.6521762            5 0.3547476            6
#2  2013 0.9627131            3 0.1754293            6

#[[2]]
#   year Max_3Days Month_spring  Min_7Days Month_summer
#1  2012 0.6115331            5 0.08505264            6
#2  2013 0.6051239            3 0.10938192            8


text:
Q: How can I tag Azure resources retroactively? I have an azure resource that is running for few days and only Later was tagged. The issue is that the days that the resource was running but did still was not tagged are being shown as "untagged" on Cost Analysis view. On that light I have two questions:

*

*Is there any way so I can tag a resource retroactively by providing a "Start-Date" in which the resource should be tagged?

*If a resource is already deleted, is there any chance that I tag it for cost analisys purposes?
Thanks in advance!


text:
Q: How to process this calculation with Flink I would like to make a real-time filter using Flink.
the idea is to have a value by key stored as accumulator and to calculate a ratio versus the total sum for all keys.
I know it's impossible to share state between keyed operator thus I'm not able to calculate the total value
example :

*

*k1,1

*k2,3

*k1,1

*k2,5

*k3,0

I need to calculate on the stream the following ratio
1/1 , 3/4, 2/5, 8/10, 0 (is always filtered) etc...
Thanks for help

A: Create a custom stateful operator with the following state:
int totalSum;
Map<Key,Ratio> map;

Every event increments the total sum, then update the map according to the event key.
Example:
After 1st event k1,1 your state is:
totalSum 1
map
   k1, 1/1

And you emit the event: k1, 1/1
======
After 2nd event k2,3 your state is:
totalSum 4
map
   k1, 1/1
   k2, 3/4

And you emit the event: k2, 3/4
[.. continue]


text:
Q: Sudo doesn't recognize specific commands I'm currently a student and I must installed Jhipster for a project, the installation seems to work fine but I faced many problems. Indeed, when I want to compile jdl files, I want to do it with a sudo but jhipster is not find only when I used sudo (without it it works)

Furthermore when I tried to launch a Jhipster project I must do ./mnvw or sudo ./mnvw. Here again when I use sudo, a warning spawn with the following message : "Warning: JAVA_HOME environment variable is not set.". This warning is not here when I don't put sudo.
So I would like to know why theses commands doesn't work with sudo, I don't have any troubles with other commands. Thanks in advances for your help, sorry for my english level and all the mistakes I made.

A: Ok, I solved my problem, I don't know if the way I did it is "clean" but I created an alias in my bashrc with the following text :
alias sudo2='sudo -E env "PATH=$PATH"'
Now I use sudo2 to launch Jhipster or mnvw
I know it's not good to answer to ourself but it's for helping if someone face the same problem in the future ;)
Another similar subject with high voted answers : Command not found when using sudo


text:
Q: TCPDF: Prints Extra Blank PDF Page on Firefox only I am viewing pdf files for printing, using TCPDF on CakePHP 2.4.
 All browsers print exactly the same expected results, in addition to Adobe Acrobat reader too. The only exception is FireFox! It adds an additional blank page. I tried all suggested solutions mentioned in other questions here (and there), and none worked.
Here is my code:
    <?php

App::import('Vendor', 'xtcpdf');
header('Content-type: application/pdf');
//see tcpdf_config.php for constants definitions
$pdf = new XTCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', FALSE);
// set margins
$PDF_MARGIN_LEFT = $PDF_MARGIN_TOP = $PDF_MARGIN_RIGHT = $PDF_MARGIN_BOTTOM = 0;
$pdf->SetMargins($PDF_MARGIN_LEFT, $PDF_MARGIN_TOP, $PDF_MARGIN_RIGHT, $PDF_MARGIN_BOTTOM);
$pdf->setPrintHeader(FALSE); //$pdf->SetHeaderMargin(25);
$pdf->setPrintFooter(FALSE); //$pdf->SetFooterMargin(25);
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
$pdf->setFontSubsetting(FALSE);
$pdf->SetAutoPageBreak(TRUE, 0);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
$pdf->addPage('L', 'Letter');
//****************** Completion Image *************************************//
$pdf->Image('/img/completion.png', $x = -10, $y = 34, $w = 240, $h = 30, $type = 'PNG', $link = '', $align = 'C', $resize = TRUE, $dpi = 900, $palign = 'C', $ismask = false, $imgmask = false, $border = 0, $fitbox = TRUE, $hidden = false, $fitonpage = TRUE);

//************************************************** TITLE Body **************************************************//
$pdf->SetFont('times', '', 20);
$title = $information['title'] ;
$pdf->writeHTMLCell($w = 0, $h = 0, $x = 0, $y = 66, $title, $border = 0, $ln = 0, $fill = 0, $reseth = true, $align = 'C', $autopadding = true);

//****************** Description *********************************//
$pdf->SetFont('times', 'I', 16);
    $description = 'bla bla bla bla bla';
    $pdf->writeHTMLCell($w = 0, $h = 0, $x = 0, $y = 93, $description, $border = 0, $ln = 0, $fill = 0, $reseth = true, $align = 'C', $autopadding = TRUE);

//************************** NAME **********************************//
$pdf->SetFont('times', 'B', 24);
$fullName = $information['Student']['first_name'] . ' ' . (!empty($information['Student']['middle_initial']) ? ($information['Student']['middle_initial'] . ' ') : '') . $certificate['Student']['last_name'];
$pdf->writeHTMLCell($w = 0, $h = 0, $x = 0, $y = 127, $fullName, $border = false, $ln = 0, $fill = 0, $reseth = true, $align = 'C', $autopadding = FALSE);

//***************** Line/OFFICE ************************//

$pdf->SetFont('times', 'B', 12);
$office = '__________________________________________________
 Bla Bla Bla
Office of bla bla blat
bla bla bla bla';
$pdf->writeHTMLCell($w = 0, $h = 0, $x = 3, $y = 151, $office, $border = 0, $ln = 10, $fill = 0, $reseth = FALSE, $align = 'C', $autopadding = FALSE);

//******************************* Certificate No. ************************************//
$pdf->SetFont('times', 'B', 10);
$certNo = 'No. ' . $information['Certificate']['certificate_No'];
$pdf->writeHTMLCell($w = 0, $h = 0, $x = 32, $y = 154, $certNo, $border = 0, $ln = 0, $fill = 0, $reseth = FALSE, $align = 'L', $autopadding = false);

//*************************** Date of Issuance ****************************//
$pdf->SetFont('times', '', 10);
$issueDate = 'Date of Issuance: ' . date('F, Y', strtotime($information['Certificate']['award_date']));
$pdf->writeHTMLCell($w = 0, $h = 0, $x = 31, $y = 157, $issueDate, $border = 0, $ln = 0, $fill = 0, $reseth = false, $align = 'L', $autopadding = FALSE);
echo $pdf->Output('PDF' . $information['Certificate']['certificate_number'] . '.pdf', 'I');
$pdf->endPage();

questions I looked at:
Extra blank page with TCPDF
how TCPDF prevent the extra blank page
Firefox prints extra blank page

A: I found no documentation, no articles, no one can explain such weird behavior.
After all, an extra blank paper won't do any harm!


text:
Q: AttributeError query My code:
class Produto:
    def __init__(self,nome,preco):
        self.nome = nome
        self.preco = preco

    def desconto(self,percentual):
        self.preco = self.preco - (self.preco*(percentual/100))

    @property
    def preco(self):
        return self._preco

    @preco.setter
    def preco(self,valor):
        if isinstance(valor,str):
            valor = float(valor.replace('R$',''))
        self._preco = valor

p1 = Produto('camisa', 'R$50')
p1.desconto(20)
print(p1.preco)

Return:

40

This code work 100% , but, if i change this part:
@preco.setter
def preco(self,valor):
    if isinstance(valor,str):
        valor = float(valor.replace('R$',''))
    self._preco = valor

For:
@preco.setter
def preco(self,valor):
    valor = float(valor.replace('R$',''))
    self._preco = valor

I have this error:

AttributeError: 'float' object has no attribute 'replace'

Why?
Another error:
If i change the same part for:
@preco.setter
def preco(self,valor):
    valor = int(50)
    self._preco = valor
p1 = Produto('camisa', 'R$50')
p1.desconto(10)
print(p1.preco)

He Return

50

Why he dont return 45?

A: Well, i make a debug.
In:
self.preco = self.preco - (self.preco*(percentual/100))

Happens a loop, he make a operation, but after this he return for setters and change again the value, for resolve this i change this for:
self._preco = self.preco - (self.preco*(percentual/100))

In the first attempt , a loop happens too, but
if isinstance(valor,str):

make a value change only 1 time .
This resolve both problem.


text:
Q: Android Bluetooth read specific string My android program is now able to receive string like "Test" or "Test 123".
Now, I need to receive a specific strings for incoming data.
In example: ~100 *200 $300.
How can I separate these 3 data by filtering the symbol, such as Textbox1 = "100", Textbox2 = "200" and Textbox3 = "300"?
Please help.
This is my current bluetooth code.
   private byte read()

    {

        byte dataRead = 0;

        try
        {
            dataRead = (byte) inputStream.read();
        }
        catch(IOException readException)
        {
            toastText = "Failed to read from input stream: " + readException.getMessage();
            Toast.makeText(Trial_Blood_Pressure.this, toastText, Toast.LENGTH_SHORT).show();
        }
        return dataRead;
    }

                if (flag)
                {
                    final byte data = read();

                    readMessageHandler.post(new Runnable()
                    {
                        public void run()
                        {
                            String message;

                            if (data != 1){
                                /*  if(txtReceived.getText().toString().equals("ON") || txtReceived.getText().toString().equals("OFF"))
                                {
                                    txtReceived.setText("");
                                }*/
                                message = txtReceived.getText().toString() + (char)data;}

                            else{
                                message = "";}

                            txtReceived.setText(message);
                        }
                    });
                }

A: Use the same separator. I.e.: "100$200$300".
Then you can use String.split() to create a string array which contains the separate values.


text:
Q: threading searching by different numbers Friends, I'm new to python and I would like to do a task that is taking time. I need to search several numbers and scrape some information. I was researching threading to speed up the process.so far i've done it:
from selenium import webdriver
from threading import Thread
from webdriver_manager.chrome import ChromeDriverManager
import pandas as pd

def func(number):
    options = webdriver.ChromeOptions()
    driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
    driver.get(url)
    dados = pd.read_excel("TABLE (TRF).xlsx")
    dados.dropna(inplace=True)
    df = dados['email', 'pass']
    for row in df.itertuples():
        driver.find_element_by_id("84878").send_keys(row[1])
        b = driver.find_element_by_id("serch")
        b.click()
        inf = driver.find_element_by_xpath('//*[@id="barraSuperiorPrincipal"]').text()
        with open(result.txt, "a") as arquivo:
            arquivo.write("%s %s\n" % (str(row[1]), inf))
# ---

url = 'https://www.test.com/'

number_of_threads = 5

#buttons = [False * number_of_threads] # create place
buttons = []

threads = []

for number in range(number_of_threads):
    t = Thread(target=func, args=(number,)) # get number for place in list `buttons`
    t.start()
    threads.append(t)
    buttons.append(False) # create place

for t in threads:
    t.join()

But don't see, I use an excel with all the numbers to look up, how can I make each thread look up a number from the table? in my code all threads are searching for the same number


text:
Q: Database structure for bug reporting database As a personal project to improve my knowledge of php, OOP and PDO i am going to design a bug reporting database like Atlassian Jira, fogbugz etc
I have basic understanding of database structure however i have only ever worked with a single database.
In this simplified scenario lets say we will have the following tables:

*

*Users

*bugs

*project

*issue type

*priority

My first thought was i would need a new database for each company because if i mixed the bugs database with everyones bug it would affect the return of query speeds. That could lead to having lots of databases, since this is a new concept i just want to see if there is a better way to do it.
I assume i will auto generate a new database with the default populated fields for the 5 tables above under a database called something like db_company_56 where 56 is the id of the company.
Could get a bit messy maintaining things with so many databases, i wonder is there a way to store them under a subfolder in phpadmin, from looking around i dont see an obvious way. So is the route i'm taking reasonably ok or is there a better way to do something like this?
If you have further reading material i can search on myself that would be great, i just dont really know what keywords to search for this under.

A: There are a few ways to approach any situation when setting up a database for it, but here's how I'd set it up if I were in your position.  As mentioned in the comments, you're thinking a level higher than you ought to be--unless security is a major issue and you don't want to store different company records in the same database, you should need no more than one database for all the information.
I'm assuming companies will have multiple projects.
What you'd want are, as str mentioned in the comments, multiple tables.  I would create one table for users and their respective data and one table for bugs, with columns for company, project, issue type, priority, any other information you may want (reporting user, etc.), and one more column: an id number relative to company, or more likely, project.  This can't be an AUTO_INCREMENT column but it can still be managed (I'll explain in just a moment).
You can display bugs for a single project in a company by using multiple WHERE conditions, for example:
SELECT * FROM 'bugtable' WHERE company = 'company_name' AND project = 'project_name' ORDER BY bugid ASC

This will display all results from the specified company's specified project.  When adding new bug records, it's easy to assign a new id number.  Assign a variable to a query finding the highest id, for instance:
SELECT 'bugid' FROM 'bugtable' WHERE company = 'company_name' AND project = 'project_name' ORDER BY bugid DESC

Then, increment the id by 1 and use it to submit a new bug record.  In short, all you need to store bug reports is a single table.  Hope this helps a little!


text:
Q: IP address range for BigCommerce hosting? I would like to secure my servers for incoming traffic from BigCommerce.
BigCommerce allows for configuring a 3rd party email server
as well as webhooks. What are the addresses that will be used by these services?

A: We can't guarantee that webhooks will be sent from a specific block of IPs--those addresses can change any time and without notice. But if the purpose is to confirm that incoming webhooks are coming from BigCommerce, you can specify custom headers when creating your webhook. The headers are returned in the webhook payload, so you could set the custom header to a basic auth username/password, and check that at runtime to authenticate the POST.
We do have a list of IPs that I can send you for the SMTP server. Happy to connect by email if your contact info is still the same!


text:
Q: XSL - Value of select with several sub-nodes matching This is my first time working with XSLT files. I have to change a report using a XSL file and I have the following problem:

*

*I have 3 variables which have to match to identify my right XML tag

*One of these variable is defined in a sub-sub-tag

*My result is located in the first sub-tag

To choose the right attribute, I use the following XSL code:
<xsl:for-each select="MSMResults/MSMVarContribs/Contrib">
  <xsl:variable name="PrtAsmType"><xsl:value-of select="@PrtAsmType"/></xsl:variable>
  <xsl:variable name="CadName"><xsl:value-of select="@PrtAsmCadName"/></xsl:variable>
  <xsl:variable name="ContribType"><xsl:value-of select="@Type"/></xsl:variable>
  <xsl:variable name="ID"><xsl:value-of select="@ID"/></xsl:variable>
  <xsl:value-of select="/CETOLReport/PrtAsm[@Type=$PrtAsmType and @CadName=$CadName and /Feature/SizeDimension/Variable/@ID=$ID]//SizeDimension/@Note"/>

This is the XML file (shortened):
<CETOLReport>
<PrtAsm Type="PART" CadName="PRT0001" Name="PRT0001">
  <VariationRule>
  <Alerts Count="0"/>
  <Feature>
  ...
  </Feature>
  ...
  <Feature Note="">
     <Alerts Count="0"/>
     <SizeDimension Note="PRT001
dim.# 01">
        <Tolerance Lower="0.1" Upper="0.2"/>
        <VariationRule ControlSkew="TRUE"/>
        ...
        <Variable Note="" Nominal="9" ID="12">
           <Distribution Mean="9.149999999999999"/>
           <Alerts Count="0"/>
        </Variable>
     </SizeDimension>
     <Dimension>
     ...
     </Dimension>
     <Dimension>
     ...
     </Dimension>
  </Feature>
  <Feature>
  ...
  </Feature>
</PrtAsm>
</CETOLReport>

Summed up:
I have to match

*

*the attribute Type in <PrtAsm>

*the attribute CadName in <PrtAsm>

*the attribute ID in <PrtAsm/Feature/SizeDimension/Variable>
and as an output I want

*

*the attribute Note in <PrtAsm/Feature/SizeDimension>
What do I have to change in
<xsl:value-of select="/CETOLReport/PrtAsm[@Type=$PrtAsmType and @CadName=$CadName and /Feature/SizeDimension/Variable/@ID=$ID]//SizeDimension/@Note"/> to get the right answer?

A: I would try:
<xsl:value-of select="/CETOLReport/PrtAsm[@Type=$PrtAsmType and @CadName=$CadName and Feature/SizeDimension/Variable/@ID=$ID]/Feature/SizeDimension[1]/@Note"/>

A: Try this....
<xsl:value-of select="/CETOLReport
                      /PrtAsm[@Type=$PrtAsmType and @CadName=$CadName]
                      /Feature/SizeDimension[Variable/@ID=$ID]/@Note"/>


text:
Q: Multiple behavior spaces I have a simulation with no global values. Instead the two things that are changed between experiments are the breeds being used, and the number of ticks in the setup (how many turns before the behavior space starts recording results)
Currently I'm duplicating each behaviour space and making the minor changes, is there a better way to do this so that I can program all the behavior spaces runs at once?

A: There are many different ways to do this, but since you don't give us a lot of information about what you're trying to do, I'm going to propose something very general. You should be able to adapt it to your needs.
Here is a simplistic model with two breeds (alphas and betas):
breed [ alphas alpha ]
breed [ betas beta ]

globals [
  experiment-id ; this could be a chooser in your interface
  breed-to-use
  num-steps-after-setup
]

to setup
  clear-all
  ifelse experiment-id = 0 [
    set breed-to-use alphas
    set num-steps-after-setup 25
  ] [
    set breed-to-use betas
    set num-steps-after-setup 50
  ]
  create-turtles 10 [
    set breed breed-to-use
  ]
  reset-ticks
  repeat num-steps-after-setup [ some-step-procedure-that-does-not-tick ]
end

You can make experiment-id vary in your BehaviorSpace experiment definition:
["experiment-id" 0 1]

The ifelse experiment-id = 0 statement in setup takes care of setting the other parameters according to which experiment you're running.

By the way, having a procedure run at the end of setup to delay the recording of steps by BehaviorSpace is probably not a good idea, but it's hard to suggest an alternative without knowing why you want to do that.


text:
Q: The value is not assigned to label in vb.net The value is not assigned to lbl5
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim cc As String
    Dim an As String
    Dim da As Double
    Dim intam, tab As Double

    an = Val(txtan.Text)
    da = Val(txtxda.Text)
    cc = Val(txtcc.Text)

    If Val(txtan.Text) = "k" Then
        lbl5.Text = "hhhhhhhhhhhhhhh"
        intam = da * 0.05
    ElseIf an = "wanitha" Then
        intam = da * 0.06
    ElseIf an = "upahara" Then
        intam = da * 0.07

    End If

    tab = (da) + intam

End Sub

A: From MSDN

The Val function returns the numbers contained in a string as a
  numeric value of appropriate type. The Val function stops reading the
  string at the first character it cannot recognize as part of a number

How can it be possible that this condition is true?
If Val(txtan.Text) = "k" Then

You should check with
If txtan.Text = "k" Then

also this is not quite right:
an = Val(txtan.Text)

should be
an = txtan.Text

A: put a breakpoint in the line:
line If Val(txtan.Text) = "k" Then

and check if the comming value is really "k"
You also dont need to use Val(txtan.Text), txttan.Text is enough
Please be more specific in your next questions