text:
Q: Migrating to numpy api 1.7 I have this code (main function in my c++ python module):
static PyObject* FMM(PyObject* self, PyObject* args)
{
    PyObject *model_obj;
    PyObject *time_obj;
    PyObject *accepted_obj;
    PyObject *lat_obj;
    PyObject *lon_obj;
    PyObject *h_obj;
    int N;

    if (!PyArg_ParseTuple(args, "OOOOOOi", &model_obj, &time_obj, &accepted_obj, &lat_obj, &lon_obj, &h_obj, &N))
    {
        Py_INCREF(Py_None);
        return Py_None;
    }

    PyObject *model = PyArray_FROM_OTF(model_obj, NPY_FLOAT, NPY_INOUT_ARRAY);
    PyObject *time = PyArray_FROM_OTF(time_obj, NPY_FLOAT, NPY_INOUT_ARRAY);
    PyObject *accepted = PyArray_FROM_OTF(accepted_obj, NPY_BOOL, NPY_INOUT_ARRAY);
    PyObject *lat = PyArray_FROM_OTF(lon_obj, NPY_DOUBLE, NPY_INOUT_ARRAY);
    PyObject *lon = PyArray_FROM_OTF(lon_obj, NPY_DOUBLE, NPY_INOUT_ARRAY);
    PyObject *h = PyArray_FROM_OTF(h_obj, NPY_DOUBLE, NPY_INOUT_ARRAY);

    float *MODEL    = static_cast<float *>(PyArray_DATA(model));
    float *TIME     = static_cast<float *>(PyArray_DATA(time));
    bool *ACCEPTED  = static_cast<bool *>(PyArray_DATA(accepted));
    double *LAT     = static_cast<double *>(PyArray_DATA(lat));
    double *LON     = static_cast<double *>(PyArray_DATA(lon));
    double *H       = static_cast<double *>(PyArray_DATA(h));
    _FMM(MODEL, TIME, ACCEPTED, LAT, LON, H, N);

    Py_INCREF(Py_None);
    return Py_None;
}

I have been getting warning
#warning "Using deprecated NumPy API,

I'd like to migrate to numpy api 1.7:
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION

How should I modify my function to replicate result in new version of c-api? Can you direct me to any example?

A: Well, that was easy:
static PyObject* FMM(PyObject* self, PyObject* args)
{
    PyArrayObject *model_obj;
    PyArrayObject *time_obj;
    PyArrayObject *accepted_obj;
    PyArrayObject *lat_obj;
    PyArrayObject *lon_obj;
    PyArrayObject *h_obj;
    int N;

    if (!PyArg_ParseTuple(args, "OOOOOOi", &model_obj, &time_obj, &accepted_obj, &lat_obj, &lon_obj, &h_obj, &N))
    {
        Py_INCREF(Py_None);
        return Py_None;
    }

    //PyObject *model = PyArray_FROM_OTF(model_obj, NPY_FLOAT, NPY_INOUT_ARRAY);
    //PyObject *time = PyArray_FROM_OTF(time_obj, NPY_FLOAT, NPY_INOUT_ARRAY);
    //PyObject *accepted = PyArray_FROM_OTF(accepted_obj, NPY_BOOL, NPY_INOUT_ARRAY);
    //PyObject *lat = PyArray_FROM_OTF(lon_obj, NPY_DOUBLE, NPY_INOUT_ARRAY);
    //PyObject *lon = PyArray_FROM_OTF(lon_obj, NPY_DOUBLE, NPY_INOUT_ARRAY);
    //PyObject *h = PyArray_FROM_OTF(h_obj, NPY_DOUBLE, NPY_INOUT_ARRAY);

    float *MODEL    = static_cast<float *>(PyArray_DATA(model_obj));
    float *TIME     = static_cast<float *>(PyArray_DATA(time_obj));
    bool *ACCEPTED  = static_cast<bool *>(PyArray_DATA(accepted_obj));
    double *LAT     = static_cast<double *>(PyArray_DATA(lat_obj));
    double *LON     = static_cast<double *>(PyArray_DATA(lon_obj));
    double *H       = static_cast<double *>(PyArray_DATA(h_obj));
    _FMM(MODEL, TIME, ACCEPTED, LAT, LON, H, N);

    Py_INCREF(Py_None);
    return Py_None;
}


text:
Q: Fedora 21 shutdown and reboot error Recently I have been using Fedora 21 and I have an issue where sometimes I shut down and reboot and the system just hangs at the fedora logo and never actually boots. I noticed the issue after installing steam as I had an issue with the execheap preventing me from running games with intel drivers. To fix this I used sudo su -c "setsebool -P allow_execheap 1" I didn't want to disable selinux completely as I had read it wasn't a good idea.
I noticed this shutdown error only after using that but it isn't consistent and only happens at certain times. Is this something that could cause the issue that forces me to boot twice or is this just a coincidence. If it is the cause, is there a fix other than just changing the value back whenever I exit steam?

A: I had the same-similar problem with fedora-21 on my desktop.  In my case, I had activated automaticlogin (/etc/gdm/custom.conf) and then I would have to boot twice almost every time - it would hang at the same point, the F/infinity logo the first time.  I used the command "journalctl -b"
to see boot errors and noticed that "keyring" was mentioned several times.
I used seahorse to change the keyring's password entirely: changed to a blank, no password, (null).  (seahorse: under Passwords on Login right click and select Change Password {by default it is your user password})  That fixed it for me.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Migrate Hypersonic DB to MySQL/MariaDB I run an OpenKM instance and I'm running out of HDD, so I want to migrate to a MariaDB Cluster.
Is there any way to migrate a 30Gb+ Hypersonic DB to MariaDB?

A: The latest MySQL Workbench tool comes with a migration feature, take a look here https://www.mysql.com/products/workbench/migrate/


text:
Q: Are $((0,1]\cap\mathbb Q)\times\mathbb Q$ and $\mathbb Q \times([0,1)\cap\mathbb Q)$ order isomorphic? The ordering here isn't specified but I assume it's lexicographic.
I think the answer is yes. My reasoning is the following:
Neither sets have a least or a greatest element  because the second component can always be increased or decreased indefinitely.
Both sets are countable as a product of two countable sets. Both sets are dense (it might be a bit tricky to prove this, but it seems relatively simple).
Therefore, both sets are order isomorphic to $\mathbb Q$, so they are order isomorphic to each other.
Does this make sense?

A: If the intended ordering is lexicographic, your argument is correct. In a general order-theoretic context, however, there is at least one other reasonable possibility: the question might be about the product partial order in which $\langle p_0,q_0\rangle\le\langle p_1,q_1\rangle$ iff $p_0\le p_1$ and $q_0\le q_1$. In that case they are not order-isomorphic: if $\uparrow\!\!\langle p,q\rangle=\{\langle r,s\rangle:p\le r\text{ and }q\le s\}$, then in the first set $\uparrow\!\!\langle 1,q\rangle$ is linearly ordered for every $q\in\Bbb Q$, while in the second set no $\uparrow\!\!\langle p,q\rangle$ is linearly ordered.


text:
Q: how to create Codeigniter route that doesn't override the other controller routes? I've got a lot controller in my Codeigniter apps, ex: Signup, Profile, Main, etc..
Now I want to build "User" controller.
what I want:

*

*if people goes to url: example.com/signup, I want use default route to "Signup" Controller

*if people goes to url: example.com/bobby.ariffin, I want to reroute this to "User" Controller because the url not handled by any Controller in my apps.

I had create this in my config/routes.php:
$route['(:any)'] = "user";

but it's override all the route in my apps to "User" Controller.
Is there any simple route for Codeigniter that doesn't override the other controller routes?
Update---
I've got simple regex for this problem, from: Daniel Errante's Blog
$route['^(?!ezstore|ezsell|login).*'] = "home/$0″;

where ezstore, ezsell, and login are the name of controller in Your Apps.

A: You can also use a foreach statement for this. That way you can keep your controllers in a nice neat list.
$controller_list = array('auth','dashboard','login','50_other_controllers');

foreach($controller_list as $controller_name)
{
    $route[$controller_item] = $controller_name;
}

$route['(:any)'] = "user/display/$1";

A: You're going to have to explicitly define all of those routes. Otherwise you will always end up at the "user_controller".
$route['signup'] = "signup";
$route['(:any)'] = "user/display/$1";

or something similar. They are ran in order, so what ever is defined first, is going to happen first. So if you catch (:any), you're going to send ANYTHING to that controller.
Also keep in mind that you can use regular expressions, so if you know there is always going to be a '.' in there, you could test for that.


text:
Q: ruby packing variables and monkey patching Okay so this is the code:
    class Board
      attr_reader :size

      def initialize n
        @grid = Array.new(n) {Array.new(n,:N)}
        @size = n * n
      end

      def [] position
        row, col = position
        @grid[row][col]
      end

      def []= position, val
        row, col = position
        @grid[row][col] = val
      end

      def num_ships
        @grid.flatten.count(:S)
      end

      def attack position
        if self[position] == :S
            self[position] = :H
            puts "you sunk my battleship"
            return true
        else
            self[position] = :X
            return false
        end
      end

      def place_random_ships
        max_ships = @size * 0.25

        while self.num_ships < max_ships
            row = rand(0...@grid.length)
            col = rand(0...@grid.length)
            position = [row,col]
            self[position] = :S
        end
      end

    end

But,
def place_random_ships
        max_ships = @size * 0.25

        while self.num_ships < max_ships
            row = rand(0...@grid.length)
            col = rand(0...@grid.length)
            position = [row,col]
            self[position] = :S
        end
      end

this works, and does what it's suppose to, but when I avoid packing [row,col] and add it directly it does not work.
def place_random_ships
        max_ships = @size * 0.25

        while self.num_ships < max_ships
            row = rand(0...@grid.length)
            col = rand(0...@grid.length)

            self[row,col] = :S
        end
      end

I'm still new to programming, so please try to explain the issue to where I can understand it, or tell me the problem, so I can google it to get a better understanding please.

A: The issue is that you defined []= to take 2 argument,  and array and a value.
def []= position, val
    row, col = position
    @grid[row][col] = val
end

With your current implementation you would need to call it like this
foo[[row,col]] = :S
What you might want to to is define []= like this:
def []= row, col, val
  @grid[row][col] = val
end

then when you want to pass the array position you can use the array spread operator.  With this implementation both of these calls will work.
position = [1,2]

foo[1,2] = :S
foo[*position] = :S

if you do that you probably would want to define [] the same way.
def [] row,col
  @grid[row][col]
end


text:
Q: After Render Event on CompositeView with Backbone.Marionette I have a Marionette CompositeView with a search panel and the collection of result data.
I would like to call a function when:

*

*the search panel is rendered.

*the collection is not rendered yet.

*this function should not be called when the collection is rendered.

I did it in this way: (but "afterRender" function get called twice)
// VIEW
App.MyComposite.View = Backbone.Marionette.CompositeView.extend({
    // TEMPLATE
    template: Handlebars.compile(templates.find('#composite-template').html()),
    // ITEM VIEW
    itemView: App.Item.View,
    // ITEM VIEW CONTAINER
    itemViewContainer: '#collection-block',

    //INITIALIZE
    initialize: function() {
        this.bindTo(this,'render',this.afterRender);
    },

    afterRender: function () {
        //THIS IS EXECUTED TWICE...
    }

});

How can i do this?
==========================EDIT==================================
I solved it in this way, if you have an observation please let me know.
// VIEW
App.MyComposite.View = Backbone.Marionette.CompositeView.extend({

    //INITIALIZE
    initialize: function() {
        //this.bindTo(this,'render',this.afterRender);
        this.firstRender = true;
    },

    onRender: function () {
        if (firstRender) {
            //DO STUFF HERE..............
            this.firstRender = false;

        }
    }

});

A: Just use onShow function
Backbone.Marionette.ItemView.extend({
  onShow: function(){
    // react to when a view has been shown
  }
});

http://marionettejs.com/docs/marionette.view.html#view-onshow

A: Marionette provides an onRender method built in to all of it's views, so you can get rid of the this.bindTo(this, 'render', this.afterRender) call:

// VIEW
App.MyComposite.View = Backbone.Marionette.CompositeView.extend({
    // TEMPLATE
    template: Handlebars.compile(templates.find('#composite-template').html()),
    // ITEM VIEW
    itemView: App.Item.View,
    // ITEM VIEW CONTAINER
    itemViewContainer: '#collection-block',

    //INITIALIZE
    initialize: function() {
        // this.bindTo(this,'render',this.afterRender); // <-- not needed
    },

    onRender: function () {
        // do stuff after it renders, here
    }

});

But to get it to not do the work when the collection is not rendered, you'll have to add logic to the onRender method that checks whether or not the collection was rendered.
This largely depends on what you're trying to do with the rendering when no items are rendered from the collection.
For example... if you want to render a "No Items Found" message, you can use the built in emptyView configuration for the composite view.

NoItemsFoundView = ItemView.extend({
  // ...
});

CompositeView.extend({

  emptyView: NoItemsFoundView

});

But if you have some special code that needs to be run and do certain things that aren't covered by this option, then you'll have to put in some logic of your own.

CompositeView.extend({

  onRender: function(){
    if (this.collection && this.collection.length === 0) {
      // do stuff here because the collection was not rendered
    }
  }

});


text:
Q: NSURLConnection sendSynchronousRequest data parsing crash I am using sendSynchronousRequest and receiving data from a web server but the app is crashing while I am trying to parse the received data?
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"data received from url: %@", data);
xmlParser = [[NSXMLParser alloc] initWithData: data];
[xmlParser setDelegate: self];
[xmlParser setShouldResolveExternalEntities:YES];
[xmlParser parse];
[xmlParser release];

But after [xmlParser parse]; the app crashes. I am getting the following:
2011-03-01 09:36:31.735 MasterApp[228:207] -[NSCFString bytes]: unrecognized selector sent to instance 0x5f6b000
2011-03-01 09:36:31.738 MasterApp[228:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSCFString bytes]: unrecognized selector sent to instance 0x5f6b000'
*** Call stack at first throw:
(
    0   CoreFoundation                      0x0252eb99 __exceptionPreprocess + 185
    1   libobjc.A.dylib                     0x0267e40e objc_exception_throw + 47
    2   CoreFoundation                      0x025306ab -[NSObject(NSObject)   doesNotRecognizeSelector:] + 187
    3   CoreFoundation                      0x024a02b6 ___forwarding___ + 966
    4   CoreFoundation                      0x0249fe72 _CF_forwarding_prep_0 + 50
    5   Foundation                          0x00114afc -[NSXMLParser parse] + 147
    6   MasterApp                           0x0000c731 -[identifierList getUrl] + 994
    7   MasterApp                           0x0000c306 -[identifierList   actionSheet:clickedButtonAtIndex:] + 56
    8   UIKit                               0x0077047d -[UIActionSheet(Private)   _buttonClicked:] + 258
    9   UIKit                               0x002dc7f8 -[UIApplication   sendAction:to:from:forEvent:] + 119
    10  UIKit                               0x00367de0 -[UIControl sendAction:to:forEvent:] + 67
    11  UIKit                               0x0036a262 -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 527
    12  UIKit                               0x00368e0f -[UIControl touchesEnded:withEvent:] + 458
    13  UIKit                               0x003003d0 -[UIWindow _sendTouchesForEvent:] + 567
    14  UIKit                               0x002e1cb4 -[UIApplication sendEvent:] + 447
    15  UIKit                               0x002e69bf _UIApplicationHandleEvent + 7672
    16  GraphicsServices                    0x02d8a822 PurpleEventCallback + 1550
    17  CoreFoundation                      0x0250fff4 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 52
    18  CoreFoundation                      0x02470807 __CFRunLoopDoSource1 + 215
    19  CoreFoundation                      0x0246da93 __CFRunLoopRun + 979
    20  CoreFoundation                      0x0246d350 CFRunLoopRunSpecific + 208
    21  CoreFoundation                      0x0246d271 CFRunLoopRunInMode + 97
    22  GraphicsServices                    0x02d8900c GSEventRunModal + 217
    23  GraphicsServices                    0x02d890d1 GSEventRun + 115
    24  UIKit                               0x002eaaf2 UIApplicationMain + 1160
    25  MasterApp                           0x00001dbc main + 102
    26  MasterApp                           0x00001d4d start + 53
)
terminate called after throwing an instance of 'NSException'
Program received signal:  "SIGABRT".

Thank you in advance

A: You need to set up the parser based on the format of the data you recieve.  To get started, Look at the NSXMLParser documentation and the NSXMLParserDelegate documentation.  From those pages you can find helpful sample code, SeismicXML and LazyTableImages.


text:
Q: How does sites like mint.com and sigfig.com (etc.) secure credential information I'm looking for detailed insight into how does sites like mint.com and sigfig.com (etc.) secure credential information.  Millions of people trust not just their login information to the primary site, but also their FINANCIAL sites, and not just one but often MANY financial sites.
This is a question at the architecture level.  The sites obviously employ penetration testing, active monitoring etc.  And they must be doing strong encryption such as:
https://crackstation.net/hashing-security.htm
If a small business/web site wanted to be as secure as possible storing this information, how would they go about it?

A: So you want to store user's passwords to external sites securely...
You can't use hashing here, because you need to know the plaintext value and send it to the external site to login.
Ideally you'd use something like OAUTH here instead, but not every site supports OAUTH.
Here's what I would do:
Encrypt the external.com credentials with a key derived from my password for you.com (I need to be logged in to you.com for you to grab data from external.com)

*

*I create an account with you.com with a username and password and login

*You hash my you.com password and store in the db

*Each time I login, you generate a key derived from my plaintext password, which you keep in server-side session while I'm logged in

*I add credentials for external.com

*You encrypt these credentials with my you.com key and store in the db

*You decrypt my external.com credentials with my you.com key and then login to external.com on my behalf

An even better approach would be to add a second server that only stores the external credentials and connects to the external sites and returns authentication details (like a session cookie).


text:
Q: Rails 5: nested resources undefined method _path I have three tables: users, observative_sessions and observations.
In each respective model there's
users.rb
has_many :observative_sessions, dependent: :destroy
has_many :observations, through: :observative_sessions, dependent: :destroy

observative_sessions.rb
belongs_to :user
has_many :observations, dependent: :destroy

observations.rb
belongs_to :observative_session
belongs_to :user

In routes.rb I nested observations in observative_sessions
resources :observative_sessions do
  resources :observations
end

I show the list of possible observations for each observative_session so I created the partial (observations/_index.html.erb) to render in the show page of observative session.
<%= render 'observations/index' %>

and a button to create new observations
<button type="button" class="btn btn-primary btn-sm" data-toggle="modal" data-target="#new-observation-modal">Create</button>

observative_sessions_controller.rb
def show
   @q = Observation.ransack([:observative_session])
   @observations = @s.result.order(params[:order]).paginate(page: params[:page]) if params[:q].present?
   @observations = @s.result.order(params[:order]).paginate(page: params[:page]) unless params[:q].present?
   @observation = Observation.new
end

Now I have a problem, when I try to create a new observation the button calls the new_modal which renders the form
<%= render 'observations/form' %>

observations/_form.html.erb
<%= bootstrap_form_for ([@observative_session, @observation]) do |f| %>

And here I get the error Undefined method 'observations_path'
This is how I defined the creation method in observations_controller.rb
def create
  @observation = Observation.new(observation_params)

respond_to do |format|
  if @observation.save
    format.html { redirect_to [@observative_session, @observation], notice: 'Observation was successfully created.' }
    format.json { render :show, status: :created, location: @observation }
  else
    format.html { render :new }
    format.json { render json: @observation.errors, status: :unprocessable_entity }
  end
end

end
Thank you so much for any help.

A: My bad the error was on new.html.erb I passed
<%= render 'form', observation: @observation %>

instead of
<%= render 'form', observation: ([@observative_session, @observation]) %>

and in observations_controller.rb I had to add
    @observative_session = ObservativeSession.find(params[:observative_session_id])
    @observation = @observative_session.observations.build(observation_params)

By the way before I was trying to use thinking of passing the id of the session
ObservativeSession.find(params[:id])

instead it should be
ObservativeSession.find(params[:observative_session_id])


text:
Q: Steam saying I am missing "libc.so.6", even though it is in my libraries folder I a question like this has been asked before, but none of the solutions I found have worked, and I think my problem is different, because it's more like Steam not detecting the library. Exact error message:

You are missing the following 32-bit libraries, and Steam may not run: libc.so.6

When I try run sudo apt-get install libc6:i386, it returns this:
Reading package lists... Done
Building dependency tree
Reading state information... Done
libc6:i386 is already the newest version (2.23-0ubuntu3).
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
 gcc-5-multilib : Depends: libc6-dev-i386 (>= 2.11) but it is not going to be installed
 libc6-dev-x32 : Depends: libc6-dev-i386 (= 2.23-0ubuntu3) but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

I have tried apt-get -f install, which returns this error:
dpkg: error processing archive /var/cache/apt/archives/libc6-dev-i386_2.23-0ubuntu3_amd64.deb (--unpack):
 trying to overwrite '/usr/include/bits', which is also in package libc6-dev-amd64:i386 2.23-0ubuntu3
Errors were encountered while processing:
 /var/cache/apt/archives/libc6-dev-i386_2.23-0ubuntu3_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

It looks like my problem is that the file is there, but for some reason it is not detected by Steam.


text:
Q: Web2py Email Authentication I Have set Web2py to send email verification on registration and not to allow log on until verified with the following settings:
mail=auth.settings.mailer

mail.settings.server = 'smtp.gmail.com:587'
mail.settings.sender = 'my_email_address@gmail.com'
mail.settings.tls=True
mail.settings.login = 'my_email_address@gmail.com:my_gmail_password'

auth.settings.registration_requires_verification = True
auth.settings.registration_requires_approval = False
auth.settings.login_after_registration = False

Email is being sent for password reset but not for registration. It also is allowing logon.
i am not sure why?
Here is my register form code:
def register():

    form = SQLFORM(db.auth_user)
    form.element('table').insert(-1,(T('Please confirm that you are not a machine :'),Recaptcha(request, PUBLIC_KEY, PRIVATE_KEY, options="theme:'white'"),''))
    if form.process(onvalidation=lola).accepted:
        session.flash = 'record inserted'
        make_thumb(db.auth_user, form.vars.id,(250,250))
        redirect(URL('login'))
    return dict(form=form)

A: If you want some of the extra registration features, such as email verification, you'll need to use the built-in auth.register() function:
def register():
    return dict(form=auth.register())

If you need to run callback functions on validation and on form acceptance, you can specify them using auth.settings.register_onvalidation and auth.settings.register_onaccept.


text:
Q: Why I cannot filter on this condition on reading xml and filter I have a sample code
import org.apache.spark.sql.Row
import scala.xml._

object reading_xml {
  def main(args: Array[String]): Unit = {
    //I have 42 Millions of records
    val records = List(
      "<root><c1>v1</c1><c2>v2</c2><c3>v3</c3><c4>v4</c4><c5>20181104</c5></root>",
      "<root><c1>v1</c1><c2>v2</c2><c3>v3</c3><c4>v4</c4><c5>20181102</c5></root>",
      "<root><c1>v1</c1><c2>v2</c2><c3>v3</c3><c4>v4</c4><c5>20181102</c5></root>",
      "<root><c1>v1</c1><c2>v2</c2><c3>v3</c3><c4>v4</c4><c5>20181106</c5><c6>v6</c6></root>"
    )
    import org.apache.spark.sql.SparkSession
    val spark = SparkSession.builder().master("local").getOrCreate()
    import spark.implicits._
    val df = records.toDF()
    df.show()
    val rdd = df.rdd.map(line => Row.fromSeq(
      "BNK"
    :: scala.xml.XML.loadString("<?xml version='1.0' encoding='utf-8'?>" + line(0)).child
      .filter(elem =>
        elem.label == "c1"
        || elem.label == "c2"
        || elem.label == "c3"
        || (elem.label == "c5" && elem.text =="20181106")
      ).map(elem =>  elem.label+"@"+elem.text).toList)
    )
    rdd.take(100).foreach(println)

Actual output:
[BNK,c1@v1,c2@v2,c3@v3]
[BNK,c1@v1,c2@v2,c3@v3]
[BNK,c1@v1,c2@v2,c3@v3]
[BNK,c1@v1,c2@v2,c3@v3,c5@20181106]

What I am expecting is to get only one row as result.
[BNK,c1@v1,c2@v2,c3@v3,c5@20181106]

What is wrong with my condition or any i missed understand about scala_xml, and how to get expected result?

A: Depending on what are you trying to do. If you are looking for if any one of the tags c1, c2, c3, c5 has a value of 20181106 then you might want to do this.
    (elem.label == "c1" || elem.label == "c2" || elem.label == "c3" || elem.label == "c5")
    && elem.text =="20181106"

A: Your outer map expects 4 records and it is returning 4 records as expected. You might want to add filter at the end.
val rdd = df.rdd.map(line => Row.fromSeq(
      "BNK"
    :: scala.xml.XML.loadString("<?xml version='1.0' encoding='utf-8'?>" + line(0)).child
      .filter(elem =>
        elem.label == "c1"
        || elem.label == "c2"
        || elem.label == "c3"
        || (elem.label == "c5" && elem.text =="20181106")
      ).map(elem =>  elem.label+"@"+elem.text).toList)
    ).filter(line => line.mkString.contains("c1") && line.mkString.contains("c2") &&
      line.mkString.contains("c3")&& line.mkString.contains("c5") && line.mkString.contains("20181106"))

rdd.take(100).foreach(println)

Op:
[BNK,c1@v1,c2@v2,c3@v3,c5@20181106]

A: XML can be parsed, then required nodes left, and then node with required value left:
val rdd = df.rdd.map(line => scala.xml.XML.loadString("<?xml version='1.0' encoding='utf-8'?>" + line(0)).child)
  // left only required nodes
  .map(nodeList => nodeList.filter(elem => Seq("c1", "c2", "c3", "c5").contains(elem.label)))
  // find element where "c5" == "20181106"
  .filter(nodeList => nodeList.find(elem => elem.label == "c5" && elem.text == "20181106").isDefined)
  .map(s => Row.fromSeq("BNK" :: s.map(elem => elem.label + "@" + elem.text).toList))


text:
Q: Change  ID with Javascript from within ContentPage I'm looking to do a short term hack on a site.  The site is a ASP.NET site with a master page.  The body tag is in the master page.   I'd like to specify which ID should be in the body tag from within various content pages.  What I don't know is if you can have this type of access to the body tag when your JS is within the body tag.  For various reasons, I'd like to try to accomplish this in JS, not .NET.
Any tips?
Rephrasing for clarity:
I would like to use JavaScript to specify a body ID from within the body tag of a site. For example:
<body id="MyID">

JS to change MyID to another name

</body>

A: Put this in the Page_Load of any ContentPage...
string JS = "document.body.id = 'WhateverID';";
ClientScript.RegisterStartupScript(this.GetType(), "BodyID", JS, true);


text:
Q: Intersection of two points in Ruby I want to find intersection of two points in Ruby. What type of checks should be there so that the function works for all cases.
Pseudocode code is
intersection(range1, range2)

*

*notCommonR1 = part of range1 which is not common

*common = common part between both ranges

*notCommonR2 = part of range2 which is not common
For example
intersection([0, 3], [2, 4]) == {
:range1 => [[0, 2]],
:both => [2, 3],
:range2 => [[3, 4]]
}

A: This is fairly straightforward; there aren't really any special checks to make here; the only special case is if there is no common part between the ranges.
def intersection(a, b)
  # Sort so that a1 < a2, b1 < b2, a1 < b1
  a, b = [a.sort, b.sort].sort
  a1, a2 = a
  b1, b2 = b

  if a2 > b2
    {range1: [[a1, b1], [b2, a2]], both: [[b1, b2]], range2: []}
  elsif a2 >= b1
    {range1: [[a1, b1]], both: [[b1, a2]], range2: [[a2, b2]]}
  else
    {range1: [[a1, a2]], both: [], range2: [[b1, b2]]}
  end
end

Depending on how you use both, nil as a value may not be ideal; use whatever indicates no common range.

A: def intersection((x1, x2), (x3, x4))
  h = {}
  e1, e2 = x1..x2, x3..x4
  [x1, x2, x3, x4].sort.each_cons(2) do |x5, x6|
    key =
    case [e1, e2].select{|e| e.include?(x5..x6)}
    when [e1] then :range1
    when [e2] then :range2
    when [e1, e2] then :both
    end
    h[key] ||= []
    h[key].push([x5, x6])
  end
  h
end


text:
Q: Triangle angle bisector and midpoints related question The question is :-

The bisector of each angle of a triangle intersects the opposite side at a point equidistant from the midpoints of other sides of the triangle. Find all such triangles.

According to the question in $\Delta ABC$ I marked the midpoints as $A',B',C'.$ therefore let the bisector from $A$ be $AX$ hence
 $C'X =B'X$ therefore we need to find in which triangle does that happen.But I am confused how to move further to find which type of triangle is that.
Please help out to solve this question .It is an olympiad book question.

A: Let $AB=2c$, $BC=2a$ and $AC=2b$ be the sides of a triangle, $D$ and $E$ the midpoints of $BC$ and $AC$. Point $M$ on side $AB$, equidistant from $D$ and $E$, lies on the perpendicular bisector of $DE$, hence $HM={1\over2}DE={1\over2}c$. Moreover:
$$
BH=a\cos(\angle ABC)={a^2+c^2-b^2\over2c}={c\over2}+{a^2-b^2\over2c}
$$
and
$$
BM=BH+HM={c}+{a^2-b^2\over2c},\quad AM=2c-BM={c}-{a^2-b^2\over2c}.
$$
Point $M$ lies on the bisector of $\angle C$ if $BM:AM=BC:AC$, that is if:
$$
(a-b)\big(2c^2-(a+b)^2\big)=0.
$$
This is satisfied if either $a=b$ (isosceles triangle) or $(a+b)^2=2c^2$. Analogous equations hold for the other sides of the triangle.
If the triangle we are looking for is not isosceles, its sides must then satisfy the system
$$
\cases{
(a+b)^2=2c^2\\
(b+c)^2=2a^2\\
(c+a)^2=2b^2\\
}
$$
which has no positive solution, because summing up the three equation one gets
$2ab+2bc+2ac=0$.
If the triangle is isosceles but not equilateral (e.g. $a=b\ne c$), the second and third equation coalesce into $(a+c)^2=2a^2$, which gives a solution:
$$
{a\over c}=1+\sqrt2.
$$
Finally, we also have the trivial solution $a=b=c$.


text:
Q: Extract some IPA from iPhone to USB Memory without jailbroken/download from App Store without iOS Device How can I copy an IPA (iOS App Store Package) from my iPhone to a USB memory, using Linux, macOS, or Windows OS?
Alternatively, How to download IPA directly to my Laptop from App Store without iOS Device?

A: Apple stopped supporting local backup of iOS apps in iTunes several versions ago. However there are apps available that will back up your iOS device including the apps.
I got iMazing in a Mac app bundle a while back and found it works as advertised and is well supported from the developer. It will back up your iOS device including the apps on it and store it locally on your Mac.
No relation to or interest in iMazing, just a happy customer. There are other apps that do similar things as well.


text:
Q: Error in namespaces I have recently created an .edmx file in my ASP .NET MVC4 application, and later on i have added a stored procedure and so I did a function import using Entity Framework 4.0.0.0 , but eventually an error pops out as

The type or namespaces Core does not exist in the namespace System.Data.Entity

The same setup is been executed on my colleague's system, but the same error doesn't occur at his system.

A: If you are using EF 6 you have to include namespace System.Data.Entity.Core.
See here a similar question on forums.asp.net
HERE is System.Data.Entity.Core documentation.


text:
Q: Decreasing hunger variable overtime using java im an experienced python coder who's getting for the first time into java, i'm trying to code a text-based adventure game. I want the game to have a hunger variable set to 100 that decreases by 5 every 15 seconds. I tried doing a while loop but it didn't go well. I've done a lot of search online but I didn't found any answer.
This is what i tried
package game;
public class game {
    int hunger = 100;
    int hungerDecreaser = 5;
    while (true) {
        Thread.Sleep(15000);
        hunger - hungerDecreaser;
    }
}

A: You have to catch the InterruptedException that Thread.sleep() will throw. hunger - hungerDecreaser should also be changed to hunger -= hungerDecreaser.
Below is an example of how you can have concurrency.
Main.java file:
public class Main {
    public static void main(String[] args) {
        //create hunger handler
        Runnable hunger = new Hunger();
        //create hunger thread
        Thread thread = new Thread(hunger);
        //start thread
        thread.start();

        //rest of game
        System.out.println("This code will run at the same time as the hunger thread.");
    }
}

Hunger.java file:
public class Hunger implements Runnable{
    int hunger;
    int hungerDecreaser;

    Hunger() {
        hunger = 100;
        hungerDecreaser = 5;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(15000); // throws InterruptedException
            } catch (InterruptedException e) { // Exception must be caught or else code will not compile
                Thread.currentThread().interrupt();
            }
            hunger -= hungerDecreaser;
            System.out.println("The hunger has decreased to: " + hunger);
        }
    }
}


text:
Q: Nodejs Cassandra Client [node-cassandra-client] I tried connecting to my cassandra cluster [version 1.0.6] via nodejs using node-cassandra-client
This is my sample script
var Connection = require('cassandra-client').Connection;
var con = new Connection({host:'x.x.x.x', port:9160, keyspace:'Stats', timeout:10000});
console.log(con);
con.execute('UPDATE TestCF ?=? WHERE key=?', ['cola', '1', '20120132'], function(err) {
    if (err) {
        console.log("Failed");
    } else {
        console.log("success");
    }
});

On executing the script
    The "sys" module is now called "util". It should have a similar interface.
    node-cassandra-client.driver: connecting x.x.x.x:9160 {}
    { validators: {},
      client: null,
      connectionInfo:
       { host: 'x.x.x.x',
         port: 9160,
         keyspace: 'Stats',
         timeout: 10000 },
      timeout: 10000 }

    node.js:201
            throw e; // process.nextTick error, or 'error' event on first tick
                  ^
    TypeError: Cannot call method 'execute_cql_query' of null
        at [object Object].execute (/home/tamil/workspace/TestProjects/node-cass/node_modules/cassandra-client/lib/driver.js:367:17)
        at Object.<anonymous> (/home/tamil/workspace/TestProjects/node-cass/index.js:5:5)
        at Module._compile (module.js:432:26)
        at Object..js (module.js:450:10)
        at Module.load (module.js:351:31)
        at Function._load (module.js:310:12)
        at Array.0 (module.js:470:10)
        at EventEmitter._tickCallback (node.js:192:40)

My nodetool stats
Address         DC          Rack        Status State   Load            Owns    Token
x.x.x.x         datacenter1 rack1       Up     Normal  1.03 MB         100.00% 0

What would be the error reason? and Need some help to fix this

A: Looks like some kind of problem with the node.js thrift driver. I've had more luck with Helenus.

A: the client inside your connection is null.  You need to connect() first.  Here's an example (ignores all errors):
var con = new Connection({host:'x.x.x.x', port:9160, keyspace:'Stats', timeout:10000});
con.connect(function(err) {
  assert.ifError(err);
  con.execute('SELECT COUNT(*) FROM TestCF', [], function(err, rows) {
    con.close(function(err) {
      // you're done now.
    });
  });
});

I recommend using async to handle the ordering of connct, query, close, etc.


text:
Q: No mapping found for HTTP request with URI in spring? I am new to Spring. I am stuck in one problem although I have looked this in various sites and followed the question that are here with this topic but still I am not able to find a solution.
I'm getting this error
No mapping found for HTTP request with URI [/ReadingsMVC/] in DispatcherServlet with name 'spring'
My web.xml is-
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>Spring3MVC</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>spring</servlet-name>
       <url-pattern>*.do</url-pattern>
    </servlet-mapping>
</web-app>

My Spring-Servlet is-
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan
        base-package="com.abc.reading.controller"/>

    <bean id="viewResolver"
        class="/WEB-INF/jsp/.*jsp">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
      </bean>
   </beans>

My Java Rest Controller code is
package com.lucidtechsol.reading.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.abc.reading.exception.InvalidRangeException;
import com.abc.reading.exception.NegativeNumberException;
import com.abc.reading.utilities.RandomNumberGenerator;

@RestController
public class ReadingController {

    @RequestMapping("/reading")
    public String getReading() throws NegativeNumberException, InvalidRangeException {

       return  new Integer(new RandomNumberGenerator().generateRandomNumber(100, -50)).toString();

        }
}

My TestRandomNumberGenerator is
package com.abc.testcase;

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.abc.reading.exception.InvalidRangeException;
import com.abc.reading.exception.NegativeNumberException;
import com.abc.reading.utilities.RandomNumberGenerator;

public class TestRandomNumberGenerator {
    int upper;
    int lower;
    RandomNumberGenerator generator;

    /**
     * @throws java.lang.Exception
     */
    @Before
    public void setUp() throws Exception {
        generator = new RandomNumberGenerator();
    }

    /**
     * @throws java.lang.Exception
     */
    @After
    public void tearDown() throws Exception {
        generator = null;
    }

    @Test
    public void testPositive() {
        upper = 10;
        lower = 5;
        try {
            assertTrue(upper >= generator.generateRandomNumber(lower, upper));
        } catch (NegativeNumberException | InvalidRangeException e) {
            e.printStackTrace();
        }
    }

    @Test(expected = NegativeNumberException.class)
    public void testNegativeNumberException() throws NegativeNumberException,
            InvalidRangeException {
        upper = 10;
        lower = -5;
        generator.generateRandomNumber(lower, upper);
    }
    @Test(expected = InvalidRangeException.class)
    public void testInvalidRangeException() throws NegativeNumberException,
            InvalidRangeException {
        upper = 30;
        lower = 10;
        generator.generateRandomNumber(lower, upper);
    }
}

My exception java file are-
InvalidException
/**
 *
 */
package com.abc.reading.exception;

/**
 * @author kuppusamys
 *
 */
public class InvalidRangeException extends Exception {
    /**
     *
     */
    private static final long serialVersionUID = 4348179544370409821L;

    public InvalidRangeException() {
        super();
    }

    public InvalidRangeException(String message) {
        super(message);
    }
}

NegativeException
/**
 *
 */
package com.abv.reading.exception;

/**
 * @author kuppusamys
 *
 */
public class NegativeNumberException extends Exception {
    /**
     *
     */
    private static final long serialVersionUID = -7903564384519771246L;

    public NegativeNumberException() {
        super();
    }

    public NegativeNumberException(String message) {
        super(message);
    }
}

RandomNumberGenerator is
import java.util.Random;

import com.abc.reading.exception.InvalidRangeException;
import com.abc.reading.exception.NegativeNumberException;

public class RandomNumberGenerator {
    public int generateRandomNumber(int upper, int lower) throws NegativeNumberException, InvalidRangeException {
        if (lower < 0) {
            throw new NegativeNumberException(
                    "Lower bound of range is negative -->" + lower);
        }
        if (upper < 0) {
            throw new NegativeNumberException(
                    "Upper bound of range is negative -->" + upper);
        }
        if (upper < lower) {
            throw new InvalidRangeException("Upper bound of range -->" + upper
                    + " is smaller than lower bound of range -->" + lower);
        }

        return lower + new Random().nextInt(upper - lower);
    }
}

My .jsp file is- Hello
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>spring mvc</title>
</head>
<body>
${message}
</body>
</html>

I am not understanding what I am doing wrong. Please help me!
if you don't understanding please comment

A: Try with http://localhost:8080/reading
web.xml
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <display-name>Spring Web MVC Application</display-name>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

     <bean class="com.abc.reading.controller.ReadingController" />

     <bean id="viewResolver"
                  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       <property name="prefix">
            <value>/WEB-INF/pages/</value>
       </property>
       <property name="suffix">
            <value>.jsp</value>
       </property>
     </bean>

</beans>


text:
Q: stacked and stationary objects Say two boxes are stacked on top of each other, resting on the ground. Box A is on the bottom and box B is on top. Is the force the ground exerts on box A greater than the force box A exerts on box B?
I think that yes, because the force the ground exerts upon A is equal to A + B, but the force A exerts on B is only equal to B. Is that right?

A: Yes,
Let's break it down.
Forces acting on box B:
Gravity = $-m_Bg$
Normal force from box A pushing up on box B = $m_Bg$
We know these must be opposite and equal since the net force on B is 0 (because there is no net acceleration if it is stationary.)
Forces acting on Box A:
Gravity = $-m_Ag$
Box B pushing on Box A = $-m_Bg$
Thus, the force the ground exerts on box A must balance these two forces if box A is to be stationary (no net force).  Therefore,
Normal force from ground on box A = $g(m_A + m_B)$
Therefore it is clear that the ground exerts more force on box A than box A exerts on box B.


text:
Q: Make dummy target that checks the age of an existing file? I'm using make to control the data flow in a statistical analysis. If have my raw data in a directory ./data/raw_data_files, and I've got a data manipulation script that creates cleaned data cache at ./cache/clean_data. The make rule is something like:
cache/clean_data:
  scripts/clean_data

I do not want to touch the data in ./data/, either with make, or any of my data munging scripts. Is there any way in make to create a dependency for the cache/clean_data that just checks whether specific files in ./data/ are newer than last time make ran?

A: If clean_data is a single file, just let it depend on all data files:
cache/clean_data: data/*
    scripts/clean_data

If it is a directory containing multiple cleaned files, the easiest way is to write a stamp file and have that depend on your data files:
cache/clean_data-stamp: data/*
    scripts/clean_data
    touch cache/clean_data-stamp

Note that this regenerates all clean_data files if one data file changes. A more elaborate approach is possible if you have a 1-to-1 mapping between data and cleaned files. The GNU Make Manual has a decent example of this. Here is an adaptation:
 DATAFILES:= $(wildcard data/*)
 CACHEFILES:= $(patsubst data/%,cache/clean_data/%,$(DATAFILES))

 cache/clean_data/% : data/%
         scripts/clean_data --input $< --output $@

 all: $(CACHEFILES)

Here, we use wildcard to get a list of all files under data. Then we replace the data path with the cache path using patsubst. We tell make how to generate cache files via a static pattern rule, and finally, we define a target all which generates all the required cache files.
Of course you can also list your CACHEFILES explicitly in the Makefile (CACHEFILES:= cache/clean_data/a cache/clean_data/b), but it is typically more convenient to let make handle that automatically, if possible.
Notice that this complex example probably only works with GNU Make, not in Windows' nmake. For further info, consult the GNU Make Manual, it is a great resource for all your Makefile needs.


text:
Q: PHP dynamically get the data from a sub array I have a question.
Have a script that renames array keys.
Now I want to do this in a sub level array if needed.
Current situation
The current code I have that works is :
    ///######## IF THE ORIGINAL KEY HAS BEEN SET
    if(isset($this->PreparedData[$key]) === true){
        ///######## ADD THE DATA TO THE PREPARED DATA VARIABLE
        $this->PreparedData[$value] = $this->PreparedData[$key];
        ///######## UNSET THE ORIGINAL KEY
        unset($this->PreparedData[$key]);
    }

But I want the code to be able to set the following dynamically:
    ///######## IF THE ORIGINAL KEY HAS BEEN SET
    if(isset($this->PreparedData[$subKey1][$key]) === true){
        ///######## ADD THE DATA TO THE PREPARED DATA VARIABLE
        $this->PreparedData[$subKey1][$value] =$this->PreparedData[$subKey1][$key];
        ///######## UNSET THE ORIGINAL KEY
        unset($this->PreparedData[$subKey1][$key]);
    }

Question
But I want to do this dynamically:
So it could be:
$this->PreparedData[$subKey1][$key]

But also:
$this->PreparedData[$subKey1][$subKey2][$key]

But also:
$this->PreparedData[$subKey1][$subKey2][$subKey3][$key]

And this at the hand of an array
Desired situation
So I could set:
MethodName('wheels', array('car', 'mustang'));

That would mean :
$this->PreparedData['car']['mustang']['wheels']

The only question I have.. Is... how to do just this?
Because I also want to be able to call:
MethodName('wheels');

Meaning:
$this->PreparedData['wheels']

Thank you!!
The solution is (by splash58):
function MethodName($key, $path = array()) {
   global $array;

   $p = &$array;                 // point to array
   foreach($path as $step)       // walk trough path to needed level
      $p = &$p[$step];
   return  $p[$key];             //take value
}

$array = array(                  // test array
  'wheels'=> 'wheels1',
  'car' => array(
      'mustang'  => array(
          'wheels'=> 'wheels2')));

echo MethodName('wheels', array('car', 'mustang')) . "\n";    // wheels2
echo MethodName('wheels');                                    // wheels1

A: Move this into your enviroment
function MethodName($key, $path = array()) {
   global $array;

   $p = &$array;                 // point to array
   foreach($path as $step)       // walk trough path to needed level
      $p = &$p[$step];
   return  $p[$key];             //take value
}

$array = array(                  // test array
  'wheels'=> 'wheels1',
  'car' => array(
      'mustang'  => array(
          'wheels'=> 'wheels2')));

echo MethodName('wheels', array('car', 'mustang')) . "\n";    // wheels2
echo MethodName('wheels');                                    // wheels1

A: When you declare the method, just let it have a default value for the array parameter. Do something like this:
function MethodName($valToInsert, $array = array())
{
    $arr1 = array();
    foreach($array as $key=>$value)
    {
        $arr1 = arr1[$value];
    }
    $final_array = $arr1[$valToInsert];
    return $final_array;
}

A: For this problem I use the following function:
function traverse($array, $path){
    foreach ($path as $key) {
        if(isset($array[$key]))
            $array = &$array[$key];
        else return null;
    }
    return $array;
}

Using it is very simple:
$array = array(                  // test array
    'wheels'=> 'wheels1',
    'car'   => array(
        'mustang'  => array(
            'wheels'=> 'wheels2')
        )
);

traverse($array, array('car', 'mustang', 'wheels')); // will return 'wheels' if path exists 'null' if not

I personally use it like this:
$array = array(                  // test array
    'wheels'=> 'wheels1',
    'car'   => array(
        'mustang'  => array(
            'wheels'=> 'wheels2')
        )
);

traverse($array, 'car.mustang.wheels');

function traverse($array, $path){
    if(!is_array($path))
        $path = explode(".", $path);
    foreach ($path as $key) {
        if(isset($array[$key]))
            $array = &$array[$key];
        else return null;
    }
    return $array;
}


text:
Q: Android button has setOnTouchListener called on it but does not override performClick When I try to add onTouchListner() to a button, it gets me the

Button has setOnTouchListener called on it but does not override
  performClick

warning. Does anyone know how to fix it?

btnleftclick.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return false;
    }
});

Error:

Custom view has setOnTouchListener called on it but does not override
  performClick If a View that overrides onTouchEvent or uses an
  OnTouchListener does not also implement performClick and call it when
  clicks are detected, the View may not handle accessibility actions
  properly. Logic handling the click actions should ideally be placed in
  View#performClick as some accessibility services invoke performClick
  when a click action should occur.

A: This warning comes up because Android wants to remind you to think about the blind or visually impaired people who may be using your app. I suggest you watch this video for a quick overview about what that is like.
The standard UI views (like Button, TextView, etc.) are all set up to provide blind users with appropriate feedback through Accessibility services. When you try to handle touch events yourself, you are in danger of forgetting to provide that feedback. This is what the warning is for.
Option 1: Create a custom view
Handling touch events is normally something that is done in a custom view. Don't dismiss this option too quickly. It's not really that difficult. Here is a full example of a TextView that is overridden to handle touch events:
public class CustomTextView extends AppCompatTextView {

    public CustomTextView(Context context) {
        super(context);
    }

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                return true;

            case MotionEvent.ACTION_UP:
                performClick();
                return true;
        }
        return false;
    }

    // Because we call this from onTouchEvent, this code will be executed for both
    // normal touch events and for when the system calls this using Accessibility
    @Override
    public boolean performClick() {
        super.performClick();
        doSomething();
        return true;
    }

    private void doSomething() {
        Toast.makeText(getContext(), "did something", Toast.LENGTH_SHORT).show();
    }
}

Then you would just use it like this:
<com.example.myapp.CustomTextView
    android:id="@+id/textview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="20dp"
    android:text="Click me to do something"/>

See my other answer for more details about making a custom view.
Option 2: Silencing the warning
Other times it might be better to just silence the warning. For example, I'm not sure what it is you want to do with a Button that you need touch events for. If you were to make a custom button and called performClick() in onTouchEvent like I did above for the custom TextView, then it would get called twice every time because Button already calls performClick().
Here are a couple reasons you might want to just silence the warning:

*

*The work you are performing with your touch event is only visual. It doesn't affect the actual working of your app.

*You are cold-hearted and don't care about making the world a better place for blind people.

*You are too lazy to copy and paste the code I gave you in Option 1 above.

Add the following line to the beginning of the method to suppress the warning:
@SuppressLint("ClickableViewAccessibility")

For example:
@SuppressLint("ClickableViewAccessibility")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button myButton = findViewById(R.id.my_button);
    myButton.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            return false;
        }
    });
}

A: Solution:

*

*Create a class that extends Button or whatever view you are using and override performClick()
class TouchableButton extends Button {

    @Override
    public boolean performClick() {
        // do what you want
        return true;
    }
}

*Now use this TouchableButton in xml and/or code and the warning will be gone!

A: Have you tried adding :
view.performClick()

or adding suppresslint annotation :
@SuppressLint("ClickableViewAccessibility")

?

A:
Custom view controls may require non-standard touch event behavior.
  For example, a custom control may use the onTouchEvent(MotionEvent)
  listener method to detect the ACTION_DOWN and ACTION_UP events and
  trigger a special click event. In order to maintain compatibility with
  accessibility services, the code that handles this custom click event
  must do the following:
Generate an appropriate AccessibilityEvent for the interpreted click
  action. Enable accessibility services to perform the custom click
  action for users who are not able to use a touch screen. To handle
  these requirements in an efficient way, your code should override the
  performClick() method, which must call the super implementation of
  this method and then execute whatever actions are required by the
  click event. When the custom click action is detected, that code
  should then call your performClick() method.

https://developer.android.com/guide/topics/ui/accessibility/custom-views#custom-touch-events

A: At the point in the overridden OnTouchListener, where you interprete the MotionEvent as a click, call view.performClick(); (this will call onClick()).
It is to give the user feedback, e.g. in the form of a click sound.

A: you can suppress a warning
@SuppressLint("ClickableViewAccessibility")

or call performClick()
[Example]


text:
Q: Mapping to columnA **or** columnB with Doctrine I have a User Entity and a Relationship Entity. (The Relationship Entity is for identifying social relationships. facebook friends, twitter follower...etc)
Here is my relationship class to better understand it:
 /**
 * Describes a relationship between two users in the direction of user1 to user2. (i.e. user1 is 'friends' with user2)
 * This relationship may be mutual
 * @package AppBundle\Entity
 */
class Relationship {
    protected $id;
    protected $user1;
    protected $user2;
    protected $source;
    protected $type;
    protected $mutual;

    /**
     * @param string $source The source of the relationship information (facebook, twitter...etc.)
     * @param string $type The type of relationship. (source specific) e.g. friends, follower
     * @param int $user1 The user id
     * @param int $user2 The user id
     * @param bool $mutual If set to true than the reverse relationship is true (i.e. user2 is 'friends' with user1 as well)
     * This may seem obvious for facebook friends but the twitter follower relationship is not always mutual
     */
    function __construct($user1,$user2,$source,$type,$mutual)
    {
        $this->user1 = $user1;
        $this->user2 = $user2;
        $this->source = $source;
        $this->type = $type;
        $this->mutual = $mutual;

    }

The trouble I am having is mapping the User Entity to the Relationship entity.
A specific instance of a User might be user1 or user2 in the Relationship.
I can't map specifically to the Relationship Entity's user1 column because it might be user2
I was trying to avoid duplicate entries in the Relationships table by having one entry define the relationship bidirectionally (accomplished with the $mutual property).
Is there a way to map this in Doctrine such that the User would have access to their Relationships (e.g. User->getRelationships) regardless of whether they are user1 or user2?

A: Honestly speaking "I don't know" :(
But the reason I am replying here is to bring a point. User1 and User2 both are instance of user. So, The problem here is that a user entity is acting as two different character. A user is referencing another user, I mean a User's primary key is users foreign key(self referencing). I personally faced this problem while making a social application. One user is a friend of another user. A user have a friend at the same time a user is a friend. I solved that problem by duplicating the row that you don't want to. By the way, I am also waiting for any batter solution. Best of luck


text:
Q: Extracting a date from webpage using selenium webdriver For one of my projects, i am trying to run a looped script (for and while) which would run until a particular predefined date value is reached.
My code is aimed at extracting the flight data of an aircraft between two specified dates. My source of information is the publicly available flight tracker, <flightradar24.com>, for which i also have a business subscription.
For example - https://www.flightradar24.com/data/aircraft/d-abyt
When trying to collect a list of flights from the page, i want to be able to read a date and stop the loop if it is over the specified date.
The html source looks like the following:

In this case the 22 Mar 2020 is what I want to read and use to compare.
So far I've tried the following to try and extract the date.
element = driver.find_element_by_class_name('w40 hidden-xs hidden-sm')

print(driver.find_element_by_xpath("//time[@class='hidden-xs hidden-sm']").text)

print(driver.find_element_by_xpath("//time[@class='w40 hidden-xs hidden-sm']").get_attribute("data-time-format"))

and
element = driverfox.find_element_by_xpath('// time[ @class ="data-time-format"] / @ datetime'.__getattribute__("data-time-format"))

Thank you in advance for your advice !!

Error when executing Debanjan's CSS suggestion.

A: Use the following to print out the element's text.
print(driver.find_element_by_css_selector('td.hidden-xs.hidden-sm').text)

Also induce webdriver waits
elem=WebDriverWait(driver, 10).until(EC.presence_of_element_located(((By.CSS_SELECTOR, "td.hidden-xs.hidden-sm"))).text
print(elem)

Import
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

A: To print the date i.e. 22 Mar 2020 you need to induce WebDriverWait for the visibility_of_element_located() and you can use either of the following Locator Strategies:

*

*Using CSS_SELECTOR and text attribute:
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "tr.data-row[data-timestamp] td[data-timestamp][data-time-format='DD MMM YYYY']"))).text)

*Using XPATH and get_attribute():
print(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//tr[@class='data-row']//td[@data-timestamp and @data-time-format='DD MMM YYYY']"))).get_attribute("innerHTML"))

*Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

A: The problem is you're tryng to match with multiple class names. Xpath isn't great with this. Css selectors are which is why this works well:
driver.find_element_by_css_selector('td.hidden-xs.hidden-sm')

But you could also accomplish this with xpath such as:
driver.find_element_by_xpath("//td[contains(@class,'hidden-xs') and contains(@class, 'hidden-sm')]")
And, as always it's best to introduce a wait before locating an element:
element = WebDriverWait(driver, 10).until(
        EC.visibility_of_element_located((By.XPATH, "//td[contains(@class,'hidden-xs') and contains(@class, 'hidden-sm')]"))
    )


text:
Q: Double Scrollbars in Tkinter Python I cannot get x and y scrollbars to work in Tkinter with Python, although I have followed multiple examples:

*

*How to add 2 scrollbars with tkinter in python 3.4

*Adding a scrollbar to a group of widgets in tkinter

*How to make a proper double scrollbar frame in tkinter

*Vertical and Horizontal Scrollbars on Tkinter Widget

*Scrolling a Canvas widget horizontally and vertically
The scrollbars appear, but do not activate when the window is smaller than the frame. How can I get this to work (see image below)?

Below is the minimal code that is producing my problem (Python 3.7)
import tkinter as tk
from tkinter import ttk

big_font = ("Arial", 50)

class DoubleScrollbarFrame(ttk.Frame):

    def __init__(self,
                 parent,
                 *args,
                 **kwargs):
        self.parent = parent

        super().__init__(self.parent,
                         *args,
                         **kwargs)

        #Set widgets to fill main window such that they are
        #all the same size
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        self.create_widgets()
        self.position_widgets()

    def create_widgets(self):
        self.canvas = tk.Canvas(self)
        self.frame = ttk.Frame(self.canvas)
        self.scroll_x = ttk.Scrollbar(self,
                                      orient = tk.HORIZONTAL,
                                      command = self.canvas.xview)
        self.scroll_y = ttk.Scrollbar(self,
                                      orient = tk.VERTICAL,
                                      command = self.canvas.yview)
        self.canvas.config(xscrollcommand = self.scroll_x.set,
                           yscrollcommand = self.scroll_y.set)
        self.canvas.create_window((0,0),
                                  window = self.frame,
                                  anchor = 'nw')
        self.frame.bind('<Configure>',
                        self.set_scrollregion)
        self.sizegrip = ttk.Sizegrip(self)

        #Test
        self.test1 = tk.Label(self.frame,
                              text = 'Test 1',
                              font = big_font)
        self.test2 = tk.Label(self.frame,
                              text = 'Test 2',
                              font = big_font)
        self.test3 = tk.Label(self.frame,
                              text = 'Test 3',
                              font = big_font)

    def position_widgets(self,
                         **kwargs):
        self.test1.grid(row = 0,
                        column = 0,
                        sticky = 'w')
        self.test2.grid(row = 1,
                        column = 0,
                        sticky = 'w')
        self.test3.grid(row = 2,
                        column = 0,
                        sticky = 'w')

        self.scroll_x.grid(row = 1,
                           column = 0,
                           sticky = 'ew')

        self.scroll_y.grid(row = 0,
                           column = 1,
                           sticky = 'ns')

        self.canvas.grid(row = 0,
                         column = 0,
                         sticky = 'nsew')

        self.frame.grid(row = 0,
                        column = 0,
                        sticky = 'nsew')

        self.sizegrip.grid(row = 1,
                           column = 1,
                           sticky = 'se')

    def set_scrollregion(self,
                         event):
        print('Frame Dimensions: {} x {}'.format(self.frame.winfo_width(),
                                                 self.frame.winfo_height()))
        print('Canvas Dimensions: {} x {}'.format(self.canvas.winfo_width(),
                                                  self.canvas.winfo_height()))
        self.canvas.configure(scrollregion = self.canvas.bbox('all'))

class MainApp(tk.Tk):

    def __init__(self,
                 *args,
                 **kwargs):

        super().__init__(*args,
                         **kwargs)

        #Set widgets to fill main window such that they are
        #all the same size
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        self.create_widgets()
        self.position_widgets()

    def create_widgets(self):
        self.frame = DoubleScrollbarFrame(self)

    def position_widgets(self):
        self.frame.grid(row = 0,
                        column = 0,
                        sticky = 'nsew')

    def exit(self):
        self.destroy()

if __name__ == '__main__':

    #Create GUI
    root = MainApp()

    #Run program
    root.mainloop()

A: The problem is in these lines of code inside DoubleScrollbarFrame.position_widgets:
self.frame.grid(row = 0,
                column = 0,
                sticky = 'nsew')

This removes control of the widget from the canvas and gives control to grid. It is no longer a canvas object, so self.canvas.bbox("all") is returning (0, 0, 1, 1). If the scrollregion is set incorrectly, the scrollbars don't know how much to scroll.
The solution is simple: don't call grid on self.frame.


text:
Q: Replacing a battery pack with a mismatched DC source I have a PCB which is nominally powered by a custom battery pack.  Specifically, this battery pack:

So five cells connected in series, at 3.6V each, which I assume means that the nominal output voltage is 18V.
Speaking generally, would it be possible to do away with the battery pack and replace it with a mains-driven DC power supply?  And assuming so, what would happen if a slightly mismatched power-supply is used (for instance, one that provides a 19V output, or one that provides a 15V output)?
Could the PCB generally be expected to function, or does the input voltage from the power supply need to exactly match the 18V provided by the battery pack?

A: A battery doesn't operate as a constant-voltage source at the nominal output voltage, the voltage will be within some usable range.  In your case the cells pictured are lithium thionyl-chloride cells made by Saft, which are NOT rechargeable.  This simplifies things a great deal as there won't be circuitry on the board to deal with battery charging.  The photo shows only two wires going to the battery pack, so there aren't extra wires for e.g. authentication against counterfeit packs.  It appears to be simple plus and minus.
The cell data sheet claims an open-circuit voltage (when new at 20C temperature) of 3.67V and nominal voltage of 3.6V.  This chemistry has a very flat voltage profile at 20C compared to some other chemistries, so it will spend most of the time around 3.6V and fall steeply as it gets close to full discharge.  At other temperatures it may operate at a somewhat different voltage.  In the data sheet they discharge to 2.0V for the discharge curves, so it's safe to assume the cell is considered dead below that voltage and should not be discharged further.
It should be a reasonable assumption that your circuit board will run from any applied voltage between 2.0V-3.67V per cell, multiplied by 5 cells gives 10.0V-18.35V.  It's possible the board doesn't run as low as 2.0V per cell, since there isn't much energy in the cells below a somewhat higher voltage, unless operating at high or low temperature which changes the voltage profile.  The safest guess would be to power the board from 5 x 3.6V = 18.0V, but it would probably work at least over the range down to 5 x 3.0V and possibly down to 5 x 2.0V.
I wouldn't be surprised if the board could operate from an even lower voltage, since the battery may simply run into switching  or linear regulator(s), which might only need to have enough headroom above the output voltage to keep running properly.  If the board has a regulator creating a 12VDC power rail then the minimum input would be at least 0.5V or even 1.5V above that.  If the power rails on the board are all 5.0V or 3.3V then it might power up from an input as low as 6.0V.  If you measure across any large bulk capacitors that appear to be on power rails it would tell you what those rail voltages are.  Looking up the voltage regulator IC(s) would also tell you something, if you can read them.
For safety of yourself and the board, you should add a fast-blow fuse in line with the V+ wire, so if something goes wrong the power supply doesn't keep frying the board.  Measure current into the board to be sure it's about the same as current from a battery.  Measure the output of your power adapter before applying it to the board to be sure it's really the voltage you think it is.  If using a big wall wart rather than a regulated wall adapter or bench supply, the voltage won't be exactly what it says on the outside except at a certain load current.
More information from the manufacturer's website:
http://www.saftbatteries.com/battery-search/ls-lsh

A: Assuming you have a constant voltage source, the circuit will draw as much current as needed.
If you increase the voltage, it will draw more current. But when it comes to 1 volt increase of a 18 V supply, the current wouldn't be enough higher to produce permanent damage. It will increase power dissipation. But that can't be said sure without knowing the actual circuit.
If you decrease the voltage, it may work because it is a circuit designed for batteries. The voltage of batteries decreases over time. So 15 V wouldn't do any harm to try with.


text:
Q: Automatically put content in for read in bash Hi  I have a little bash script and before i used to type the content in a bit like answering a question, but what i would like to do is just run the bash script and instead of answering the question it would just put the answer automatically in.
    echo "
Please type in your name "

echo $name > /root/details/name.info
echo "
Your name is $name ! "

echo "
    What is your age "
    read age
    echo $age > /root/details/age.info

echo "
This server will carry out a complete maintenance routine daily
Enter the time at which this routine should happen :
Example : Eleven o'clock is 23 , midnight is 00 , three in the morning is 03 ...
Based on the example , enter the time of maintenance with a decimal number 00-23
Please note: ( 00/23 )"

echo $HorMan>

echo "
    Please enter  your username e.g. admin"
    read username
    echo $username > /root/details/username.info

In the above code Name and Age would be different on each script run but Server maintenance and Username would be the same on every script run.

A: Put the answers to the questions in a text file, one answer per line, in the correct order.
Then run your script:
$ ./script.sh <answers.txt

EDIT: After updated question.
If some of the input to the script is static, either don't read them in the script at all (replace with static data), or have a second script that fills in those values:
$ ./answerscript.sh <answers.txt | ./script.sh

The answers.txt contains names and ages on alternating lines, while the answerscript.sh does the following:
#!/bin/sh

IFS=
while read name; do
  echo $name
  read age
  echo $age
  echo 23
  echo enoch
done

(23 and enoch is the time and the username that is static).
BTW, your script, as it is written now, won't read the name nor the time.


text:
Q: Alternative zend core function in laravel I want to call the "getlist-options" template with the controller.
In the zend-framework, I was able to do this with
$this->action()
What an alternative function is in laravel. And does it just exist?

A: Just to mark this question as answered (I recommend reading the Laravel Docs)
Here's the equivalent in Laravel to return an html template named getlist-options.blade.php
return view('layouts.getlist-options');

Assuming the template file is in the resources/views/layouts directory


text:
Q: C++ mathematical comparison using function return value not working Consider the following code:
   char foo[32] = "123456";
   printf("strlen(foo) = %d\n", strlen(foo));
   if ((5 - strlen(foo)) > 0)
   {
      //This statement prints because the comparison above returns true, why?
      printf("String must be less than 5 characters, test 1\n");
   }

   int tmp;
   if ((tmp = 5-strlen(foo)) > 0)
   {
      //This statement does not print and makes since
      printf("String must be less than 5 characters, test 2\n");
   }

As the comments indicate, I do not understand why a temporary variable is needed to store the result of the mathematical calculation before comparisons to another value work.

A: The reason why you get a true there is because the result of the subtraction is unsigned. This, in turn, is because size_t, the return type of strlen(), is unsigned, and it's large enough that int got converted to its type rather than the other way around.
When you assign the result of the subtraction to a signed int variable tmp, you make the result signed again, so the comparison works as expected.
In general, you should be very careful with subtraction of unsigned values if you suspect that the result might become negative. If you are not 100% sure, use a signed type, or avoid subtractions in the first place. For example, a legitimate replacement for your condition above would be
if (strlen(foo) <= 5)
    ...


text:
Q: Check manually a JMenuItem in a JPopUpMenu? I have a JPopUpMenu with several JCheckBoxMenuItem's on it.

Actually what I would like to do is basicly to select an item of the JPopUpMenu with a specific index.
For exemple,  a method like myPopUpMenu.setSelected(2), which would select "Algérie" in my JPopUpMenu.
The problem is that I don't know any method which would allow me to check an item manually...
Here's the code of my JPopUpMenu :
MainVue.java:
public class MainVue extends JFrame implements ActionListener {

 private static final JScrollPopupMenu menuProduit = new JScrollPopupMenu();
 private static final JScrollPopupMenu menuPays = new JScrollPopupMenu();
 private static List<String> listeFiltres = new ArrayList<String>();
 private String listeDeFiltres;
 private String[] tableauFiltrePermanent;
 private String listeFiltrePermanent;

 private String[] tableauPays = { "Autres", "Afrique du sud", "Algérie", "Allemagne", "Arabie Saoudite", "Argentine",
        "Australie", "Bangladesh", "Belgique", "Brésil", "Bulgarie", "Canada", "Chine", "Corée du sud", "Egypte",
        "Emirats-Arabes Unis", "Espagne", "Etats-Unis", "Ethiopie", "Europe", "France", "Hongrie", "Inde",
        "Indonésie", "Irak", "Iran", "Israél", "Italie", "Japon", "Jordanie", "Kazakhstan", "Koweit", "Liban",
        "Libye", "Malaisie", "Maroc", "Mexique", "Monde", "Oman", "Pakistan", "Pays-Bas", "Philippines", "Poligne",
        "Portugal", "Qatar", "République tchéque", "Roumanie", "Russie", "Taïwan", "Tunisie", "Turquie",
        "Ukraine" };
 private String[] tableauProduit = { "Blé", "Colza", "Mais", "Orge", "Orge de Brasserie", "Palme", "Soja",
        "Tournesol", "Tourteaux De Colza", "Tourteaux de Soja", "Huile de Soja", "Huile De Colza" };

 private List<JCheckBoxMenuItem> listJCBProduit = new ArrayList<JCheckBoxMenuItem>();
 private List<JCheckBoxMenuItem> listJCBPays = new ArrayList<JCheckBoxMenuItem>();
 public static PropertiesConfiguration prop;

 public MainVue(Modele modele, Controleur controleur) throws ClassNotFoundException, SQLException, IOException {

  prop = new PropertiesConfiguration("config.properties");

  for (int i = 0; i < tableauProduit.length; i++) {
        listJCBProduit.add(new JCheckBoxMenuItem(tableauProduit[i]));
    }

    for (int j = 0; j < listJCBProduit.size(); j++) {
        JCheckBoxMenuItem produitActuel = listJCBProduit.get(j);
        menuProduit.add(produitActuel);
        produitActuel.addActionListener(new OpenAction(menuProduit, boutonProduit));

    }

    for (int i = 0; i < tableauPays.length; i++) {
        listJCBPays.add(new JCheckBoxMenuItem(tableauPays[i]));
    }

    for (int j = 0; j < listJCBPays.size(); j++) {
        JCheckBoxMenuItem paysActuel = listJCBPays.get(j);
        menuPays.add(paysActuel);
        paysActuel.addActionListener(new OpenAction(menuPays, boutonPays));
    }
    listeDeFiltres = "";

        for (int p = 0; p < listeFiltres.size(); p++) {
            String filtreActuel = listeFiltres.get(p);
            if (listeDeFiltres == "") {
                listeDeFiltres += filtreActuel;
            } else {
                listeDeFiltres += "," + filtreActuel;
            }

            }
  prop.setProperty("listeFiltres", listeDeFiltres);
 }
}

Here's the JScrollPopUpMenu component :
JScrollPopUpMenu.java:
package fr.views;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.swing.JPopupMenu;
import javax.swing.JScrollBar;

public class JScrollPopupMenu extends JPopupMenu {
protected int maximumVisibleRows = 10;

public JScrollPopupMenu() {
    this(null);
}

public JScrollPopupMenu(String label) {
    super(label);
    setLayout(new ScrollPopupMenuLayout());

    super.add(getScrollBar());
    addMouseWheelListener(new MouseWheelListener() {
        @Override public void mouseWheelMoved(MouseWheelEvent event) {
            JScrollBar scrollBar = getScrollBar();
            int amount = (event.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL)
                         ? event.getUnitsToScroll() * scrollBar.getUnitIncrement()
                         : (event.getWheelRotation() < 0 ? -1 : 1) * scrollBar.getBlockIncrement();

            scrollBar.setValue(scrollBar.getValue() + amount);
            event.consume();
        }
    });
}

private JScrollBar popupScrollBar;
protected JScrollBar getScrollBar() {
    if(popupScrollBar == null) {
        popupScrollBar = new JScrollBar(JScrollBar.VERTICAL);
        popupScrollBar.addAdjustmentListener(new AdjustmentListener() {
            @Override public void adjustmentValueChanged(AdjustmentEvent e) {
                doLayout();
                repaint();
            }
        });

        popupScrollBar.setVisible(false);
    }

    return popupScrollBar;
}

public int getMaximumVisibleRows() {
    return maximumVisibleRows;
}

public void setMaximumVisibleRows(int maximumVisibleRows) {
    this.maximumVisibleRows = maximumVisibleRows;
}

public void paintChildren(Graphics g){
    Insets insets = getInsets();
    g.clipRect(insets.left, insets.top, getWidth(), getHeight() - insets.top - insets.bottom);
    super.paintChildren(g);
}

protected void addImpl(Component comp, Object constraints, int index) {
    super.addImpl(comp, constraints, index);

    if(maximumVisibleRows < getComponentCount()-1) {
        getScrollBar().setVisible(true);
    }
}

public void remove(int index) {
    // can't remove the scrollbar
    ++index;

    super.remove(index);

    if(maximumVisibleRows >= getComponentCount()-1) {
        getScrollBar().setVisible(false);
    }
}

public void show(Component invoker, int x, int y){
    JScrollBar scrollBar = getScrollBar();
    if(scrollBar.isVisible()){
        int extent = 0;
        int max = 0;
        int i = 0;
        int unit = -1;
        int width = 0;
        for(Component comp : getComponents()) {
            if(!(comp instanceof JScrollBar)) {
                Dimension preferredSize = comp.getPreferredSize();
                width = Math.max(width, preferredSize.width);
                if(unit < 0){
                    unit = preferredSize.height;
                }
                if(i++ < maximumVisibleRows) {
                    extent += preferredSize.height;
                }
                max += preferredSize.height;
            }
        }

        Insets insets = getInsets();
        int widthMargin = insets.left + insets.right;
        int heightMargin = insets.top + insets.bottom;
        scrollBar.setUnitIncrement(unit);
        scrollBar.setBlockIncrement(extent);
        scrollBar.setValues(0, heightMargin + extent, 0, heightMargin + max);

        width += scrollBar.getPreferredSize().width + widthMargin;
        int height = heightMargin + extent;

        setPopupSize(new Dimension(width, height));
    }

    super.show(invoker, x, y);
}

protected static class ScrollPopupMenuLayout implements LayoutManager{
    @Override public void addLayoutComponent(String name, Component comp) {}
    @Override public void removeLayoutComponent(Component comp) {}

    @Override public Dimension preferredLayoutSize(Container parent) {
        int visibleAmount = Integer.MAX_VALUE;
        Dimension dim = new Dimension();
        for(Component comp :parent.getComponents()){
            if(comp.isVisible()) {
                if(comp instanceof JScrollBar){
                    JScrollBar scrollBar = (JScrollBar) comp;
                    visibleAmount = scrollBar.getVisibleAmount();
                }
                else {
                    Dimension pref = comp.getPreferredSize();
                    dim.width = Math.max(dim.width, pref.width);
                    dim.height += pref.height;
                }
            }
        }

        Insets insets = parent.getInsets();
        dim.height = Math.min(dim.height + insets.top + insets.bottom, visibleAmount);

        return dim;
    }

    @Override public Dimension minimumLayoutSize(Container parent) {
        int visibleAmount = Integer.MAX_VALUE;
        Dimension dim = new Dimension();
        for(Component comp : parent.getComponents()) {
            if(comp.isVisible()){
                if(comp instanceof JScrollBar) {
                    JScrollBar scrollBar = (JScrollBar) comp;
                    visibleAmount = scrollBar.getVisibleAmount();
                }
                else {
                    Dimension min = comp.getMinimumSize();
                    dim.width = Math.max(dim.width, min.width);
                    dim.height += min.height;
                }
            }
        }

        Insets insets = parent.getInsets();
        dim.height = Math.min(dim.height + insets.top + insets.bottom, visibleAmount);

        return dim;
    }

    @Override public void layoutContainer(Container parent) {
        Insets insets = parent.getInsets();

        int width = parent.getWidth() - insets.left - insets.right;
        int height = parent.getHeight() - insets.top - insets.bottom;

        int x = insets.left;
        int y = insets.top;
        int position = 0;

        for(Component comp : parent.getComponents()) {
            if((comp instanceof JScrollBar) && comp.isVisible()) {
                JScrollBar scrollBar = (JScrollBar) comp;
                Dimension dim = scrollBar.getPreferredSize();
                scrollBar.setBounds(x + width-dim.width, y, dim.width, height);
                width -= dim.width;
                position = scrollBar.getValue();
            }
        }

        y -= position;
        for(Component comp : parent.getComponents()) {
            if(!(comp instanceof JScrollBar) && comp.isVisible()) {
                Dimension pref = comp.getPreferredSize();
                comp.setBounds(x, y, width, pref.height);
                y += pref.height;
            }
        }
    }
}
}

Thanks in advance for any help !

A: The index which you get from getIndex() method use as follows. You are adding ScrollBar in your JScrollPopupMenu at 0 index. So to remove casting error update your code as follow.
int index = getIndex("name");
      ((JCheckBoxMenuItem)menuProduit.getComponentAtIndex(index+1)).setState(true);


text:
Q: Minicart Problem in Custom Module in Magento 2 I am working on Quick Order Custom Module, for this I have shown the all products in to one page. So that the customer will add the multiple product to cart at a time. Here Products are adding to cart and showing messages in my form, but minicart is not showing. For this I have written below code.
quickorder.phtml
<?php

$list = $block->getProducts();

$cart_items = $block->getCartItems();

?>

Quick Order Instructions

The Quick Order page is designed to simplify the ordering process.
            All products are listed in the table below. A search feature has been provided to help find the desired product(s).
            In addition, the table headers are sortable on devices with a screen width greater than 550px.

How to use the Quick Order Page

Find the desired product(s), using the search feature if needed.

Enter the amount into QTY box and press enter or select the ADD TO CART button.

View the cart to place your order -or- continue shopping on the page.

*Best Price is calculated on largest quantity discount.

<?php

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->create('\Magento\Store\Model\StoreManagerInterface');
$baseURL_l = $social_image_url = $storeManager->getStore()->getBaseUrl();

$fav = "";
$sk = "";
$name = "";
$price = "";
$qty = "";
$cart = "";

if(count($list) > 0 ){
    /*$table = "";*/
    foreach($list as $items){

        $product_obj = $objectManager->create('Magento\Catalog\Model\Product')->load($items->getId());

        $sku = $product_obj->getSKU();
        $url = $baseURL_l . $sku;

        $fav .= "
";
        $fav .= "&nbsp";
        $fav .= "
";

        $sk .= "
";
        $sk .= "";
        $sk .= $sku;
        $sk .= "";
        $sk .= "
";

        $name .= "
";
        $name .= $product_obj->getName();
        $name .= "
";

        $price_for = number_format($product_obj->getPrice(), 2, '.', '');

        $price .= "
";
        $price .= $price_for;
        $price .= "
";

        $qty .= "
";
        //$qty .= "<input type='text' style='text-align:center;padding-right:1px;padding-left:1px;width:40px;height: 20px;' maxLength='3' id='Quantity_$sku' name='Quantity' value=''>";
        $qty .= "<input type='number' maxLength='3' name='qty_$sku' id='qty' title='Qty' value='' class='input-text qty' style='text-align:center;padding-right:1px;padding-left:1px;width:40px;height: 20px;'/>";
        $qty .= "
";

        $cart .= "
";
        $cart .= "&nbsp";
        $cart .= "
";

    }
}

if(count($list) >0 ){
    $div = "";
    $div .= "
";
    $div .= "
";
    $div .= "
Favorites
";
    $div .= $fav;
    $div .= "
";
    $div .= "
";
    $div .= "
SKU
";
    $div .= $sk;
    $div .= "
";
    $div .= "
";
    $div .= "
Product Name
";
    $div .= $name;
    $div .= "
";
    $div .= "
";
    $div .= "
Best Price
";
    $div .= $price;
    $div .= "
";
    $div .= "
";
    $div .= "
Qty
";
    $div .= $qty;
    $div .= "
";
    $div .= "
";
    $div .= "
In Cart
";
    $div .= $cart;
    $div .= "
";

    $div .= "
";

   ?>

<form data-role="tocart-form" method="post" action="<?php /* @escapeNotVerified */ echo $baseURL_l . 'quickorder/index/add'; ?>">

        <input type="submit" onclick="<?php /* @escapeNotVerified */ echo $baseURL_l . 'quickorder/index/add'; ?>" name="insert" value="Add to Cart" class="btn" />
        <button type="submit"
                title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>"
                class="btn">
        </button>

        <input type='text' style='text-align:center;padding-right:1px;padding-left:1px;width:350px;height: 30px;' id='search' name='search' value=''>
        <input type="submit" name="insert" value="Product Search" class="btn" onclick="<?php /* @escapeNotVerified */ echo $baseURL_l . 'quickorder/index/search'; ?>"/>

    <?php echo $div; ?>

        <input type="submit" name="insert" value="Add to Cart" class="btn" onclick="<?php /* @escapeNotVerified */ echo $baseURL_l . 'quickorder/index/add'; ?>"/>

</form>
    <?php
}else{
    $div = "";
    $div .= "
";
    $div .= "
";
    $div .= "
Favorites
";
    $div .= "
No Records Found!
";
    $div .= "
";
    $div .= "
";
    $div .= "
SKU
";
    $div .= "
!
";
    $div .= "
";
    $div .= "
";
    $div .= "
Product Name
";
    $div .= "
!
";
    $div .= "
";
    $div .= "
";
    $div .= "
Best Price
";
    $div .= "
!
";
    $div .= "
";
    $div .= "
";
    $div .= "
Qty
";
    $div .= "
!
";
    $div .= "
";
    $div .= "
";
    $div .= "
In Cart
";
    $div .= "
!
";
    $div .= "
";
    $div .= "
";

    echo $div;

}

?>

Add.php controller
/**
     * Add product to shopping cart action
     *
     * @return \Magento\Framework\Controller\Result\Redirect
     * @SuppressWarnings(PHPMD.CyclomaticComplexity)
     */
    public function execute()
    {

        /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
        $resultRedirect = $this->resultRedirectFactory->create();

        $request = $this->getRequest()->getParams();
        try {

            $sku_list = [];

            foreach($request as $k => $v){
                if (strpos($k, 'qty_') !== false) {
                    $sku = explode('_',$k);
                    if($v !="" || $v !=0)
                        $sku_list[$sku[1]] = $v;
                }
            }

            $product = $this->_productFactory->create();

            foreach($sku_list as $k => $v){

                $data = $product->loadByAttribute('sku',$k);
                $product = $this->_initProduct1($data->getId());

                /**
                 * Check product availability
                 */
                if (!$product) {
                    return $this->goBack();
                }

                $requests = array('product' => $product->getId(),'qty' => $v);
                $_product = $this->productRepository->getById($product->getId());
                $qty = $v;

                if($_product->getTypeId() == "bundle"){

                    //
                    $productTypeInstance = $product->getTypeInstance();
                    $requiredChildrenIds = $productTypeInstance->getChildrenIds($_product->getId(), true);

                    $par = array('product' => $product->getId(),
                        "bundle_options" => array(),
                        'qty' => $v);
                    $magento = [];
                    foreach($requiredChildrenIds as $child){
                        $i =0;
                        foreach($child as $k => $v){
                            $i++;
                            $prod = $this->productRepository->getById($v);
                            $isSaleable = $prod->isSalable();
                            if($isSaleable){
                                $magento[$v] = "$i";
                            }else{
                                $message = __('No stock for this Item',$_product->getName());
                                $this->messageManager->addErrorMessage($message);
                                return $this->goBack(null, $product);
                            }
                        }

                    }
                    $par = array(
                        'product' => $product->getId(),
                        'bundle_options' => array(  1 => $magento),
                        'qty' => $qty
                    );

                    $this->cart->addProduct($_product,$par);

                }else{
                    $this->cart->addProduct($_product,$requests);
                }

                $message = __('You added %1 to your shopping cart.',$product->getName());
                $this->messageManager->addSuccessMessage($message);

            }

            $this->cart->save();

            return $resultRedirect->setPath('quickorder/index/index');

        }  catch (\Exception $e) {
            $this->messageManager->addException($e, __('We can\'t add this item to your shopping cart right now.'));
            $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e);
            return $this->goBack();
        }
    }

After adding product to shopping cart showing success message see below pic.
and not showing the red icon in minicart see above pic. When I navigate browser to cart page showing products in cart page. But I con is not showing.
Any suggestings or help?

A: Finally I solved my self by adding below code.
add section.xml to etc/frontend
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Customer:etc/sections.xsd">
    <action name="[frontName]/[ActionPath]/[ActionName]">

    </action>
</config>


text:
Q: Simplification of a series I have a series in the following form:
\begin{equation}
\sum_{k=1}^{n} A\exp(\mu t(k-1)+\sigma \sqrt{t(k-1)})
\end{equation}
I would like to know if I can convert this equation with something such as a geometric series, given that I see some similarities to that:$\sum _{k=1}^{n}ar^{k-1}={\frac {a(1-r^{n})}{1-r}}$, I might be completly wrong of course.

A: *

*$\exp(\mu kt) \ne \exp(\mu t) \exp(k-1)$

*Your $C$ depends on $k$. So your series has nothing to do with a geometric series.

A: Unfortunately almost all series are not simplifiable. But if you are doing applied math in finance, you could use a lot of approximation methods and numerical methods to acquire desired results. However, in order to determine which approximation methods is legit, one must know the background of your questions, so one will not omit important details while doing simplification.