text:
Q: UnmarshalException: unexpected element (uri:"http://www.namespace.com/RTS", local:"container") I am trying to map my xml to java classes.
Xml comes from a third-party service. The structure is the same, but there may be a different prefix or namespace. XML:
<?xml version="1.0" encoding="UTF-8"?>
<xdms:container xmlns:xdms="http://www.namespace.com/RTS" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xdms:uid="FHGHDFGDFJKGDFHG" xdms:version="3.2">
    <xdms:requisites>
        <xdms:documentKind>letter</xdms:documentKind>
        <xdms:classification>main</xdms:classification>
        <xdms:annotation>unknown</xdms:annotation>
    </xdms:requisites>
</>

My classes:
@XmlRootElement(name = "container")
@XmlAccessorType(XmlAccessType.FIELD)
public class Container {
    private static final long serialVersionUID = 1L;

    @XmlElement(name = "requisites")
    private Requisites requisites;

    public Container() {
        super();
    }

    @Override
    public String toString() {
        return "Container{" +
                "requisites=" + requisites +
                '}';
    }
}

@XmlRootElement(name = "requisites")
@XmlAccessorType(XmlAccessType.FIELD)
public class Requisites implements Serializable {
    private static final long serialVersionUID = 1L;

    private String documentKind;
    private String classification;
    private String annotation;

    public Requisites() {
        super();
    }

    @Override
    public String toString() {
        return "Requisites{" +
                "documentKind='" + documentKind + '\'' +
                ", classfication='" + classification + '\'' +
                ", annotation='" + annotation + '\'' +
                '}';
    }
}

and the main class in which I run parsing:
    JAXBContext jaxbContext;
    File xmlFile = new File("test.xml");
    try
    {
        jaxbContext = JAXBContext.newInstance(Container.class);
        Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
        Container cont = (Container) jaxbUnmarshaller.unmarshal(xmlFile);

        System.out.println(cont);
    }
    catch (JAXBException e)
    {
        e.printStackTrace();
    }

And I get the error:

javax.xml.bind.UnmarshalException: unexpected element
  (uri:"http://www.namespace.com/RTS", local:"container"). Expected
  elements are <{}container>,<{}requisites>     at
  com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:726)
    at
  com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:247)
    at
  com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:242)
    at
  com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:109)
    at
  com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1131)
    at
  com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:556)
    at
  com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:538)
    at
  com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:153)
    at
  com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:509)
    at
  com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:374)
    at
  com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:613)
    at
  com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3132)
    at
  com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:852)

UPD:
I added nameSpace, the error is gone. But the fields of my objects are not filled with information. They are empty, although in xml they are filled with information

Container{requisites=Requisites{documentKind='null',
  classfication='null', annotation='null'}}

A: You don't specify the namespace in your jaxb class
Something like that:
@XmlRootElement(name = "container", namespace = "http://www.namespace.com/RTS")
@XmlAccessorType(XmlAccessType.FIELD)
public class Container {

    @XmlElement(name = "requisites", namespace="http://www.namespace.com/RTS")
    private Requisites requisites;

}

you might need to add namespace to every element in Requisites as well.
@XmlRootElement(name = "requisites")
@XmlAccessorType(XmlAccessType.FIELD)
public class Requisites implements Serializable {
    private static final long serialVersionUID = 1L;

    @XmlElement(name = "documentKind", namespace="http://www.namespace.com/RTS")
    private String documentKind;
    @XmlElement(name = "classification", namespace="http://www.namespace.com/RTS")
    private String classification;
    @XmlElement(name = "annotation", namespace="http://www.namespace.com/RTS")
    private String annotation;

A: Use the namespace attribute in the @XmlRootElement as follows:
@XmlRootElement(name="container", namespace="http://www.namespace.com/RTS")

In case, if it still throws the same error, you also have to specify the namespace attribute in your @XmlElement:
@XmlElement(name="requisites", namespace="http://www.namespace.com/RTS")

Your each attribute inside the Requisites tag should also contain the namespace within its @XmlElement annotation.


text:
Q: Access cursor columns dynamically by index similar to array I have this js code that I need to convert into PL SQL. Below I've also included my own version of PL SQL conversion of this code but it has some errors. Any help on this is greatly appreciated. Thanks
Original JavaScript Code
for (var i=2; i<nsArray.length; i++) {
     if (weight<nsArray[i]) {

      whLowerLimit = nsArray[i-1];
      whUpperLimit = nsArray[i];

         }
       }

This is what I have done so far
Create Procedure

V_CUR_NSLOOKUP SYS_REFCURSOR;
V_NSLOOKUP MRWTHTPCT%ROWTYPE;

V_HEIGHT number;
V_WHLOWERLIMIT number;
V_WHUPPERLIMIT number;

Begin

    FOR I IN 3..V_NSLOOKUP.COUNT
       LOOP
           IF V_WEIGHT < V_NSLOOKUP.(COLUMN_NAME) THEN
              V_WHLOWERLIMIT := V_NSLOOKUP(COLUMN_NAME - 1);
              V_WHUPPERLIMIT := V_NSLOOKUP(COLUMN_NAME);

      END IF
     END LOOP;
END

A: The only way I can think of doing that is storing the column names in a separate array. You can get the column names of a table through the all_tab_columns view:
DECLARE
  TYPE columns_names IS TABLE OF VARCHAR2(50);
  v_columns columns_names;
BEGIN
  SELECT column_name
  BULK COLLECT INTO v_columns
  FROM all_tab_columns
  WHERE table_name = 'TABLE_NAME';

  -- Do your stuff...

END;

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ Heap and Stack Memory ( memory managment ) So currently I've been working with pointers and now I know how to use them and where are they going in the money, but there is still one question that keeps bothering me. Why do I want some things in Heap and some in Stack ?
When we are declaring a pointer the variable and the address stays in the stack, but the specific pointer address POINTS to the value. Okay, but why do I want to do that ? Why shouldn't I just declare a normal variable ? What's the point and when do I have to use dynamic memory allocation ?

A: Heap memory 'lives' until you call delete (or delete[]), stack memory only lives until you exit the scope in which it is declared. That's the difference.

A: Well, it all depends on you and your application.
Use of Stack
You would use the stack if you know exactly how much data you need to allocate before compile time and it is not too big.
Use of Heap:
You would use the heap if you don't know exactly how much data you will need at run time or if you need to allocate a lot of data.
you can also refer below link more detail

What and where are the stack and heap?


text:
Q: how to do temporary tables in Linq to Entity Framework Our application queries the database primarily using Linq queries backed by Entity Framework but we sometimes call legacy stored procedures.  Sometimes we want to replace an existing stored procedure with a Linq / Entity Framework query.  Is this possible to do even if the stored procedure uses temporary tables?  If so, how?

A: Honestly, why force a square peg into a round hole? Entity Framework supports calling stored procedures for a reason; because Entity Framework cannot address every use case that the database itself can support.
I would just use the right tool for the job (which in some of these cases appears to be stored procedures) and not worry about trying to create a faux "pure" architecture by forcing everything into Entity Framework.

A: Entity Framework doesn't support temporary tables in this manner.  The "temporary" table would have to be defined as a permanent one in the database, perhaps named with a tmp prefix.  You could then remove and add records in the usual way using Entity Framework.


text:
Q: Rails 3 validate URL or IP address I'm searching for a way to validate a field for correct URL or IP address in a rails model. I've played a little bit with validates :url, :format => URI::regexp(%w(http https)), and other URL validations. But how do I get the field validated with either an URL or an IP address? Maybe there is a gem for that.
thx!

A: Not sure if there are such gems, but custom validations can be implemented relatively simple (with ipaddress gem in the Gemfile). Try something like
require 'uri'
validate :valid_url_or_ip
...
private
def valid_url_or_ip
  unless valid_url?(url) || IPAddress.valid?(url)
    errors.add(:url, "Not an URL or IP address")
  end
end

def valid_url?
  uri = URI.parse(url)
  uri.kind_of?(URI::HTTP) || uri.kind_of?(URI::HTTPS)
rescue URI::InvalidURIError
  false
end


text:
Q: drop down menu on image button on action bar what i have is an action bar .. and i have only logo in it and an image button and i want when i press on the button a spinner with a three values will appear and each one of them open a new activity , here is my code :
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    android.app.ActionBar mActionBar = getActionBar();
    mActionBar.setDisplayShowHomeEnabled(false);
    mActionBar.setDisplayShowTitleEnabled(false);
    LayoutInflater mInflater = LayoutInflater.from(this);

    View mCustomView = mInflater.inflate(R.layout.custom_actionbar, null);
    TextView mTitleTextView = (TextView) mCustomView.findViewById(R.id.title_text);
    mTitleTextView.setText("My Own Title");

    ImageButton imageButton = (ImageButton) mCustomView
            .findViewById(R.id.imageButton);
    imageButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View view) {
     // i want the spinner to be add here
        }
    });

    mActionBar.setCustomView(mCustomView);
    mActionBar.setDisplayShowCustomEnabled(true);
}

@Override
public boolean onNavigationItemSelected(int arg0, long arg1) {
    // TODO Auto-generated method stub
    return false;
}

A: ublic class MainActivity extends Activity{
...
...
/**
 * On selecting action bar icons
 * */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Take appropriate action for each action item click
    switch (item.getItemId()) {
    case R.id.action_search:
        // search action
        return true;
    case R.id.action_location_found:
        // location found
        LocationFound();
        return true;
    case R.id.action_refresh:
        // refresh
        return true;
    case R.id.action_help:
        // help action
        return true;
    case R.id.action_check_updates:
        // check for updates action
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

/**
 * Launching new activity
 * */
private void LocationFound() {
    Intent i = new Intent(MainActivity.this, LocationFound.class);
    startActivity(i);
}

}
Try This code :
For better understanding go through following link
http://www.androidhive.info/2013/11/android-working-with-action-bar/


text:
Q: Remove query results with having I have an SQL query like the following:
select aaa,
 count(condition_1),
 count(condition_2),
 count(condition_3)
from DB
where ...
group by 1,
order by 1

The above will return four columns. Is it possible with a having statement to suppress some of the fields in the results but return all the rows that the original script would produce.
Thanks in advance for your help

A: if you are trying to "suppress" field values (and i assume that you're really looking to return 0 in that case, since the fields aren't going away as long as they're in the select) based on some criteria but return all rows, you could try the following:
select aaa,
case when count(condition_1) > 1 then count(condition_1) else 0 end as count_1,
case when count(condition_2) > 1 then count(condition_2) else 0 end as count_2,
case when count(condition_3) > 1 then count(condition_3) else 0 end as count_3
from DB
where ...
group by 1,
order by 1

obviously modify the case statements to reflect the values you wish to return, with all others being 0

A: I am not exactly sure what you mean but, from my understanding you are trying to group your results based on a single column's count. If that's right, then the code you need would be along the lines of
select aaa,
 count(condition_1) as count_1,
 count(condition_2) as count_2,
 count(condition_3) as count_3
from DB
where ...
group by 1,
order by 1
having count_1 > 1

A: No, you can't suppress columns (fields) and keep all the rows.
Any filtering (WHERE, HAVING etc) will apply only to rows.
You could do this
select
    aaa,
    case
        when somecondition then count(condition_1)
        when somecondition then count(condition_2)
    end as thecount,
    case
        when somecondition then '1'
        when somecondition then '2'
    end as thecountofwhat

from mytable
where ...
group by aaa,
order by aaa

Note: don't use ordinals in GROUP BY or ORDER BY. Bad practice. And only MySQL allows such nonsense in the GROUP BY.


text:
Q: couchdb on ssl runs with error I can see couch db running on port 5984 and 6984 using
sudo lsof -i :5984

and
sudo lsof -i :6984

However, when I access it through the browser, I get the error shared at bottom of post. I will need to access this through pouch db running from an application running on SSL.
In local.ini, I have this:
[ssl]
cert_file = /home/ec2-user/api_aonesalons_com.crt
key_file = /home/ec2-user/myserver.key

error when accessed on https.
[error] [<0.392.0>] {error_report,<0.62.0>,
                                  {<0.392.0>,std_error,
                                   [83,83,76,58,32,"1112",58,32,"error",58,
                                    "[]",32,"/home/ec2-user/myserver.key",
                                    "\n",32,32,
                                    [91,
                                     [[123,
                                       ["ssl_connection",44,
                                        "init_private_key",44,"5"],
                                       125],
                                      44,10,"   ",
                                      [123,
                                       ["ssl_connection",44,"ssl_init",44,"2"],
                                       125],
                                      44,10,"   ",
                                      [123,
                                       ["ssl_connection",44,"init",44,"1"],
                                       125],
                                      44,10,"   ",
                                      [123,
                                       ["gen_fsm",44,"init_it",44,"6"],
                                       125],
                                      44,10,"   ",
                                      [123,
                                       ["proc_lib",44,"init_p_do_apply",44,
                                        "3"],
                                       125]],
                                     93],
                                    "\n"]}}

=ERROR REPORT==== 8-Feb-2018::15:40:11 ===
SSL: 1112: error:[] /home/ec2-user/myserver.key
  [{ssl_connection,init_private_key,5},
   {ssl_connection,ssl_init,2},
   {ssl_connection,init,1},
   {gen_fsm,init_it,6},
   {proc_lib,init_p_do_apply,3}]

[error] [<0.392.0>] {error_report,<0.62.0>,
                        {<0.392.0>,crash_report,
                         [[{initial_call,
                               {ssl_connection,init,['Argument__1']}},
                           {pid,<0.392.0>},
                           {registered_name,[]},
                           {error_info,
                               {exit,ekeyfile,
                                   [{gen_fsm,init_it,6},
                                    {proc_lib,init_p_do_apply,3}]}},
                           {ancestors,[ssl_connection_sup,ssl_sup,<0.63.0>]},
                           {messages,[]},
                           {links,[<0.67.0>]},
                           {dictionary,[]},
                           {trap_exit,false},
                           {status,running},
                           {heap_size,1597},
                           {stack_size,24},
                           {reductions,1169}],
                          []]}}

=CRASH REPORT==== 8-Feb-2018::15:40:11 ===
  crasher:
    initial call: ssl_connection:init/1
    pid: <0.392.0>
    registered_name: []
    exception exit: ekeyfile
      in function  gen_fsm:init_it/6
    ancestors: [ssl_connection_sup,ssl_sup,<0.63.0>]
    messages: []
    links: [<0.67.0>]
    dictionary: []
    trap_exit: false
    status: running
    heap_size: 1597
    stack_size: 24
    reductions: 1169
  neighbours:
[error] [<0.67.0>] {error_report,<0.62.0>,
                       {<0.67.0>,supervisor_report,
                        [{supervisor,{local,ssl_connection_sup}},
                         {errorContext,child_terminated},
                         {reason,ekeyfile},
                         {offender,
                             [{pid,<0.392.0>},
                              {name,undefined},
                              {mfargs,{ssl_connection,start_link,undefined}},
                              {restart_type,temporary},
                              {shutdown,4000},
                              {child_type,worker}]}]}}

=SUPERVISOR REPORT==== 8-Feb-2018::15:40:11 ===
     Supervisor: {local,ssl_connection_sup}
     Context:    child_terminated
     Reason:     ekeyfile
     Offender:   [{pid,<0.392.0>},
                  {name,undefined},
                  {mfargs,{ssl_connection,start_link,undefined}},
                  {restart_type,temporary},
                  {shutdown,4000},
                  {child_type,worker}]

[error] [<0.180.0>] {error_report,<0.31.0>,
                                  {<0.180.0>,std_error,
                                   [{application,mochiweb},
                                    "Accept failed error",
                                    "{error,ekeyfile}"]}}

=ERROR REPORT==== 8-Feb-2018::15:40:11 ===
    application: mochiweb
    "Accept failed error"
    "{error,ekeyfile}"
[error] [<0.180.0>] {error_report,<0.31.0>,
                        {<0.180.0>,crash_report,
                         [[{initial_call,
                               {mochiweb_acceptor,init,
                                   ['Argument__1','Argument__2',
                                    'Argument__3']}},
                           {pid,<0.180.0>},
                           {registered_name,[]},
                           {error_info,
                               {exit,
                                   {error,accept_failed},
                                   [{mochiweb_acceptor,init,3},
                                    {proc_lib,init_p_do_apply,3}]}},
                           {ancestors,
                               [https,couch_secondary_services,
                                couch_server_sup,<0.32.0>]},
                           {messages,[]},
                           {links,[<0.146.0>,#Port<0.3466>]},
                           {dictionary,[]},
                           {trap_exit,false},
                           {status,running},
                           {heap_size,987},
                           {stack_size,24},
                           {reductions,18123}],
                          []]}}

=CRASH REPORT==== 8-Feb-2018::15:40:11 ===
  crasher:
    initial call: mochiweb_acceptor:init/3
    pid: <0.180.0>
    registered_name: []
    exception exit: {error,accept_failed}
      in function  mochiweb_acceptor:init/3
    ancestors: [https,couch_secondary_services,couch_server_sup,<0.32.0>]
    messages: []
    links: [<0.146.0>,#Port<0.3466>]
    dictionary: []
    trap_exit: false
    status: running
    heap_size: 987
    stack_size: 24
    reductions: 18123
  neighbours:
[error] [<0.146.0>] {error_report,<0.31.0>,
                        {<0.146.0>,std_error,
                         {mochiweb_socket_server,297,
                             {acceptor_error,{error,accept_failed}}}}}

=ERROR REPORT==== 8-Feb-2018::15:40:11 ===
{mochiweb_socket_server,297,{acceptor_error,{error,accept_failed}}}

SSL certificate used here works just fine with apache so should not really be a problem.
I am facing this issue same as described here
https://groups.google.com/forum/#!topic/couchdb-user-archive/Jlqfj-8a_sM


text:
Q: PHP: How to use preg_match() here? I  have two strings like
stdClass Object ( [id] => 10303 )

and
 stdClass Object ( [error] => not found )

How do I catch id and error via preg_match() the function? I've used this code but it didn't help:
$file = 'stdClass Object ( [id] => 10303 )';
preg_match('/\[id\] \=\> ([0-9]+)/', $file, $mfc);
var_dump($mfc);

A: Id
preg_match('/\[id\][\s]*\=\>[\s]*([0-9]+)/', $file, $mfc);

Error Text
preg_match('/\[error\][\s]*\=\>[\s]*(.*?)\?/', $file, $mfc);

The main change to your regex is to take into account any unprecedented whitespace characters present.

A: For error you can use this!
preg_match('/\[error\][\s]*\=\>[\s]*(.*?)\?/', $file, $mfc);
var_dump($mfc);

And for ID
$syntax = '/\[id\][\s]*\=\>[\s]*([0-9]+)/';
preg_match($syntax, $file, $mfc);
var_dump($mfc);


text:
Q: iPhone wi-fi speeds significantly slower than Mac? Both my iMac and iPhone are on the same wireless router (Airport Extreme).
But my iMac is pulling 50Mbps down while my iPhone 4 is maxing out around 20Mbps.
What could be the reason for that?

A: The processor and hardware architecture of the iPhone (and mobile devices in general) cannot handle the processing required to download data nearly as fast as your iMac. This combined with a million other variables, including the fact that the antenna in the iPhone is much smaller and could receive a weaker signal even though it is the same distance from the transmitter as the iMac, are among many reasons the transfer speeds are slower on your iPhone.
In short, there is a processing bottleneck somewhere in the architecture of the iPhone that is not present in the iMac for transferring that amount of data.

A: I reckon it is because you need to squeeze the receiver in a much smaller space. Because the receiver is smaller, you have to limit what you implement. It's probably the best they can do for that size, without making it to expensive.


text:
Q: Custom geometry for page with floats I have a special page for floats (i.e., with [p]).
In my real code it is a longtable in a table. Because of space issues I want to change the margins of the page with that float. How do I set a new geometry only for the float pages?
This is not a duplicate of the linked question as that solution does not work in the case of a float page.
An MWE with a \hrule to indicate the margins of the float page:
\documentclass[a4paper]{article}
\usepackage{geometry}
\usepackage{lipsum}
\begin{document}
\lipsum[1]
\begin{figure}[p]
    \hrule
    \caption{A horizontal rule.}
\end{figure}
\end{document}

A: You do not need to change the page geometry (most likely) it is much simpler and usually sufficient just to allow the content of the float to bleed in to the margins, here by 1cm either side.
\documentclass[a4paper]{article}

\usepackage{lipsum}
\begin{document}
\lipsum[1]
\begin{figure}[p]
\hspace*{-1cm}%
\begin{minipage}{\dimexpr\textwidth+2cm}
    \hrule
    \caption{A horizontal rule.}
\end{minipage}%
\hspace*{-1cm}
\end{figure}
\end{document}


text:
Q: Pyttx3 Vosk | Голосовой Асcистент python Всем привет, я уже делал голосового ассистента, но у него был 1 минус... приходилось ждать пока программа скажет говорите. Я хотел бы чтобы программа постоянно ждала определённого слова. и когда оно было сказано, она начинала запись. Т.е. как обращение. Как осуществить подобный способ работы голосового ассистента.
Как создать голосовую модель для pyttsx3?
Я перелистал очень много источников интернета. На разных языках, как мне создать свою голосовую модель?
Как создать свою модель для распознания речи Vosk?
Как указать путь к уже существующей модели pyttsx3 и использовать именно её?


text:
Q: Gridview related problem in asp.net How can I enter data from textbox to gridview on the buttonclick event

A: A gridview is more commonly used for databinding to a source of table-like data. If you're just moving text from textboxes to grid/table, you might be better off using a regular table with empty asp labels in the cells. On postback, you can:
lblCell11.Text = txtBox1.Text;


text:
Q: Starting an application located in an Alternate Data Stream On Windows 7, starting a program located in an Alternate Data Stream (e.g. start c:\temp\application.exe:hiddenProgram.exe) does not work anymore!
Using Process Monitor, I see that the access result is OK, but somehow, the OS is blocking access to this file. On Vista and earlier versions, this method used to work.

Does anyone knows how to start it using windows 7 ?

A: Do what Marc Russinovich does with the Sysinternals tools: store additional executables as resources in the main EXE and unpack them when needed.
There is an additional advantage over ADS: portability. ADS do not survive being stored on FAT formatted volumes, for example.
This technique can indeed be helpful if you want to distribute single EXEs that unpack required device drivers or other helper tools when needed (-> Sysinternals).


text:
Q: Is the property accessor/mutator (getter/setter) the right place to enforce acceptable ranges? In an app where a port number is set, I want to restrict the values assignable to the port number to those between 49152 and 65535 (inclusive).
I wrote some test methods that test that anything outside of this range causes the test to fail. They do fail (as expected, as the code does not yet take that into account).
So my question is: what is the best place to put the code that forces an invalid value to a valid value - here:
public int Port
{
    get
    {
        return port;
    }
    set
    {
        port = value;
    }
}

such as:
public int Port
{
  get
  {
      return port;
   }
   set
   {
       if ((value < 49152) || (value > 65535))
       {
          value = 55555;
       }
       port = value;
    }
}

...or somewhere else?

A: This is one of the biggest benefits to having wrapper methods around the fields and not exposing them directly. So I would say most definitely, yes.

A:
what is the best place to put the code that forces an invalid value to a valid value?

The best place for that is nowhere. Forcing an invalid value to a random valid value is hiding a bug in the caller. The caller can know ahead of time whether the value they are attempting to set is valid or not, so crash them if they do it wrong. Throw an exception, don't ignore the bug and make a guess as to what they meant.

A: You can put validation logic in your setter, but you should probably let somebody know if the validation fails.
ie:
private static int minimumPortNumber = 49152;
private static int maximumPortNumber = 65535;

public int Port
{
  get
  {
      return port;
   }
   set
   {
       if ((value < minimumPortNumber) || (value > maximumPortNumber))
       {
           throw new ArgumentOutOfRangeException("port", string.Format("The port number is out of range. It must be between {0} and {1}", minimumPortNumber, maximumPortNumber));
       }
       port = value;
    }
}


text:
Q: rendering a bootstrap modal using partial view and ajax call make all fields not editable(event the modal himself) here is the bootstrap modalI Have successfully rendered a partial view containing a bootstrap modal in a view .
the problem is when i show the modal all the content are not editable any more  even the content of the modal .
//View
[@section Scripts{

}

//partial view
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

                    <button type="button" class="close" data-dismiss="modal">×</button>

تعديل الدور

                    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                    @Html.HiddenFor(model => model.ID)

                        @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                            @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

                            <input type="submit" value="Save" class="btn btn-default" />

                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

}][1]


text:
Q: How do I call async methods in lambda expression? I want to order array by method:
MyList.OrderBy(p=>CalcValue(p))

I want that the calculation will execute async.
I'm using .net 4 so I can't declare the methods as async.
If I would create some kind of code that first will calculate the values, store them and only than sort it by lambda expression but how can I do it directly inside of the lambda expression?
Is it possible?

A: Not very clear from your question what exactly you want.
This may help you, it will first calculate all the values and then will sort it with it, although your term aync is unclear to me for this context.
MyList.Select(p=>new {p,CalcValue = CalcValue(p)})
       .OrderBy(x=>x.CalcValue)
       .Select(x=>x.p);


text:
Q: How should i go about developing chrome extension like this A extension that takes a photo and make it into webcam stream. So if i have website requesting access to webcam then this would show up as possible webcam to share with.
I know javascript and a bit of chrome extension api. But i don't know how to go about this.

A: There is no Chrome extension API that will allow you to create a webcam that will show up in other applications.


text:
Q: Visual Studio Online - Shared Projects I have added a new solution to VSO and would like to reference a project already belonging to a different solution.
As an example I have a solution that contains common/core framework code.
I then want to be able to create new solutions that reference this common code.
Does anybody know the best way to achieve this? or if it is possible?

A: I don't think there is a way for you to add reference to project (source code) in another solution, because, you can only add reference to project that in the same solution.
You can, however, first compile the common framework code to generate the common.dll, for example. Then add reference to the common.dll in the new solution. If the common framework code is stable that doesn't change, you can just put the common.dll into source control, with this way to be sure that the referenced dll file can be found when build in VSO.

A: You can do it but it is extremely bad practice and often leads to issues.
You can simply add any Project inside of the same source control repository to any solution. Having the code under the solution will make it flow better and cause less issues. (However this is high on my list of silly things customers do that I have to undo)
The real solution however is to have a solution for your shared , and package it as a Nuget package, then publish it to a local (myget is best) repository. You can then add that Nuget package to as many projects as you like.


text:
Q: XBAP childWindow control available similar to Silverlight 3 ChildWindow? The Silverlight 3 toolkit has a ChildWindow control for model popup like functionality.  This is great.  Anyone aware of a similar control that can be utilized via XBAP?
http://silverlight.codeplex.com/wikipage?title=Silverlight%20Toolkit%20Overview%20Part%204&referringTitle=Silverlight%20Toolkit%20Overview%20Part%203
The assumption is maybe someone ported the functionality back to WCF/XBAP?
Trying to find a solution without going to 3rd party purchased controls (against current company policy).

A: Don't know that you'll get this to work without FullTrust (FullTrust XBAPs are a PITA until .NET 4). Here's a psuedo-workaround though- not as nice as SL ChildWindow, but it gets you basic popup functionality.

A: In theory couldn't you rebuild the ChildWindow source and massage it a little to work on WPF? Most of the controls are WPF compatible, so it would make sense to build ChildWindow for XBAPs.


text:
Q: Convenient way to download MCD19A2 product using R I want to download MODIS MCDA219 product. I have been downloading manually from

*

*https://ladsweb.modaps.eosdis.nasa.gov/

*and https://earthdata.nasa.gov .

As a new to R user, recently I have learn downloading this product using R with help of Download MODIS/MCD19A2 AOD product with R .
Problem is, the daily product are creating too much folder. For example if I try to download January month of 2018, then it will create folder for each day. So for January month, 31 hdf format files are in 31 folders each. How can I download MCD19A2 product by month and the HDF file?
I will need more than 50,000 dataset and I was looking for more convenient way to download the product using R

A: You can use:
install.packages("MODIStsp")
library(MODIStsp)
MODIStsp()

It's a good GUI to download and process MODIS data.

A: the library rts might help be of your help. It contains almost all MODIS products and allows you to download, mosaic and reproject MODIS data all within the download command. You can have a unique GeoTIFF for each date as an output, which might reduce the number of file you have to store. Try
install.packages('rts')
library(rts)
modisProducts() # this shows all products available with this library

to make sure the product you need is available (very likely). The download process is not as straightforward, as it requires authenticating with NASA which in turn requires previous authentication. This process is described in detail here and here.


text:
Q: Managing media using the Android MediaStore I manage media (images, sound) of my app directly, reading and saving to the SD card. Should I be using the MediaStore instead? I'm not quite sure what the MediaStore is for, and the javadoc is not very helpful.
When should an app use the MediaStore? A brief overview of the pros and cons of the MediaStore will be much appreciated.

A: As an avid android user.
I think MediaStore is the "Public Link" between the internal Android Media Scanner Application (You can manually invoke it through Spare Parts) and 3rd party applications, like yours.
I'm guessing MediaStore is this "public link" based on its android.provider packaging.
As providers in android, is how applications provide information to other applications
If MediaStore is a ContentProvider, reading information populated by MediaScanner.
Then MediaStore is for User media, such as music, video, pictures etc.
For ringtones, notifications; I think you are supposed to use android.media.RingtoneManager
Also don't hardcode the path "/sdcard/" There is an api call to get it, Environment.getExternalStorageDirectory()
http://twitter.com/cyanogen/status/13980762583
====
The pro is that Media Scanner runs every time you mount the removable storage to the phone, and it also scans the internal memory (if it has any like the HTC EVO & incredible)

A: I am no expert in this but as far as my common sense goes, well its the easy way to search for certain types of files.
If your app has a library of sorts, then using MediaStore instead of searching all by yourself is more useful, faster and less power consuming. Also you can be assured that those are all the files present in the system.
I hope this helps.


text:
Q: System too slow after minikube . (4gb ram + core i3 ) I have a core i3 processor 7th generation and 4gb ram in my system. I installed virtual box and then ran .. minikube start on my shell.
As the minikube starts, the system is heavily slowed down. It hangs at the drop of hat. I am learning kubernetes and want to make use of yaml files to deploy and learn which I can't in playground .
And as I delete minikube , system comes back to life.
So, I have two questions. Is the issue with RAM or with core i3 ? The prerequisites for minikube is 2 CPUs . Does that mean minikube alone will have two CPUs for itself and host will not have any?
Whats causing the issue?
Second one, is there any other way i can learn k8 without minikube? playground doesn't provide way for adding yaml file

A: This is probably not enough memory so the machine starts paging/swapping. Not enough cpu is a problem, too, of course.
If you are using Windows try stopping all programs and docker desktop when using minikube. (minikube uses 2gb ram by default)
Try upgrading to at least 8gb ram when working with virtual maschine. (minikube and docker desktop both create VMs for the linux environment.)
If you are using a linux machine use the docker driver for minikube.


text:
Q: Simple quadrupole moment I have a very simple problem: There is a charge $-q$ at $(0, 0, d)$ and $(0, 0, -d)$ as well a charge $2q$ at $(0, 0, 0)$. I have to calculate the quadrupole moment using spherical coordinates. I use $x=\cos(\phi)$.
The formula I build up is this:
$$ q_{2,m} = \frac{(2-m)!}{(2+m)!} \frac{(-1)^{m+1}}8 \int_{-1}^1 \mathrm dx \, \left(1-x^2\right)^{m/2}  \frac{\mathrm d^{2+m}}{\mathrm dx^{2+m}} \left(x^2-1\right)^2 $$ $$\times\int_0^{2\pi} \mathrm d \phi \, \mathrm e^{\mathrm im \phi} \int_0^\infty \mathrm dr \, r^2 \rho(r, x, \phi).$$
Is this even correct?
Then I tried to figure out what the $\rho$ has to be, this is what I currently believe to be correct:
$$ \rho(r, x, \phi) = q \delta(\phi) \left[2 \delta(r) \delta(x-1) - \delta(r-d) \delta(x-1) - \delta(r-d) \delta(x+1)\right].$$
So now I would just need to calculate the integrals, right? The problem for positive $m$ would be that $\int \mathrm dx \, \delta(x-1) \left(1-x^2\right)^{m/2}$ would be zero. And $\int \mathrm dr \, r^2 \delta(r)$ would also be zero. So the $q_{2,1}$ and $q_{2,2}$ are zero.
I previously used the following charge density (although there was a negative radius):
$$ \rho(r, x, \phi) = q \delta(x) \delta(\phi) \left[2\delta(r) - \delta(d-r) - \delta(d+r)\right].$$
And I got:
$$
q_{2,-2} = 3! q d^2
,\quad
q_{2,-1} = 0
,\quad
q_{2,0} = -q d^2
,\quad
q_{2,1} = 0
,\quad
q_{2,2} = \frac 14 qd^2.
$$
In one of the books, it says that only the $Q_{3,3}$ element of the tensor would be non-zero.
So how can I obtain the correct answer here?

A: I would say the quickest route would be to use the multipole expansion for the potentials of the different charges and then add those up. Thus you'd use
$$
\frac{1}{|\mathbf{r}-\mathbf{r}'|}=\sum_{l=0}^\infty\sum_{m=-l}^l\frac{ 4\pi}{2l+1} \frac{r'^l}{r^{l+1}}Y_{lm}^\ast(\theta',\phi')Y_{lm}(\theta,\phi),
$$
valid for $r>r'$ (see Jackson, 2nd ed., p.111, eq 3.70). To implement this, take $\mathbf{r}'=(0,0,\pm d)$, so that $\theta'=0,\pi$ and $\phi'$ is irrelevant. Then $Y_{lm}^\ast(\theta',\phi')$ is zero unless $m=0$, so you have
$$
Y_{lm}^\ast(\theta',\phi')=\delta_{m,0}N_{lm}P_l(\cos\theta)=\delta_{m,0}\sqrt{\frac{2l+1}{4\pi}}P_l(\pm1)=\delta_{m,0}\sqrt{\frac{2l+1}{4\pi}}(\pm1)^l.
$$
Thus, in this case,
$$
\frac{1}{|\mathbf{r}-\mathbf{r}'|}=\sum_{l=0}^\infty (\pm d)^l \sqrt{\frac{ 4\pi}{2l+1}} \frac{Y_{l0}(\theta,\phi)}{r^{l+1}}=\sum_{l=0}^\infty (\pm d)^l  \frac{P_{l}(\cos\theta)}{r^{l+1}}.
$$
If you put it all together, then, the $l=0$ components of the charges at $(0,0,\pm d)$ will cancel with the one at the origin (all the other multipole terms of which vanish, of course), and the $l=1$ terms will kill each other due to that sign. The full potential will therefore be
$$
\Phi=q\sum_{l=2}^\infty \left[1+(-1)^l \right] d^l \frac{P_{l}(\cos\theta)}{r^{l+1}}=\sum_{k=0}^\infty 2q d^{2+2k} \frac{P_{2+2k}(\cos\theta)}{r^{3+2k}}.
$$
Now, as to how to extract the multipole moments, it depends on what normalization you use. I would use a normalization as
$$
\Phi=\sum_{l=0}^\infty\sum_{m=-l}^l q_{lm}\frac{Y_{lm}(\theta,\phi)}{r^{l+1}},
$$
but it depends on what the multipolar fields are defined like in your book. Since the nonzero-$m$ terms have already vanished, we must have $q_{2,\pm1}=q_{2,\pm2}=0$ as the problem's symmetry demands (as I indicated already in the comments). The $m=0$ component is then simply
$$q_{2,0}=2q d^2,$$
but, again, this depends on the normalization you're using.


text:
Q: Create a PDF document using just VB.NET? Is it possible to create (set formatting, add text by form etc) a PDF document in VB.NET without using any third party libraries?  This would be done in a website.

A: I know you said w/o a third party control, but maybe free will work ... but I'll just throw this out there just in case in proves to be informational.
We have to do the same thing in our environment ... and we opted to just use Crystal Reports (which you have a license to with Visual Studio) and leverage the export to PDF functionality. Allows us to deliver pretty forms and lists to the customer.
I'm not a big fan of Crystal Reports, for a variety of reasons ... but it was easy to implement and at no additional cost to our end customer.

A: You can do this with iTextSharp, which is technically third-party (but it's free):
http://beta.codeproject.com/KB/aspnet/Creating_PDF_documents_in.aspx
Here are some more options:
http://www.aspnetworld.com/articles/2004011801.aspx


text:
Q: How do linux users manage unmet dependencies? I use Tex live on Debian. While I have no issues using the stable repository, I also want to try out the latest packages and changes that are only available on testing/sid.
Unfortunately, when I reconfigure my config file to prioritize sid then sudo apt-get update followed by sudo apt-get upgrade and sudo apt-get install texlive-full, I am greeted with a long list of unmet dependency errors. When I try to manually downgrade them, the unmet dependencies themselves also have that problem, creating a recursive issue of unknown depth. I tried this on a mostly clean installation.
How do skilled users navigate this problem? Is debian not the right choice here?


text:
Q: suPHP : proper use of the chroot feature I started using suPHP recently, and I'm spending an amazing amount of time debugging the configurations and different compile options to get something that actually works. I've tried contacting the development team through their mailing list, but it's obviously made of ghosts...
I am trying to use the chroot parameter, but it trigger a 500 Internal Error which I just can't solve.
I am using DBD MySQL for the DocumentRoot definition:
<VirtualHost *:80>
    ServerName *

    DBDriver mysql
    DBDParams <params>
    DBDocRoot "SELECT document_root FROM domains WHERE name=%s" HOSTNAME

    suPHP_Engine on
    AddType application/x-httpd-php .php .php3 .php4 .php5 .phtml
    suPHP_AddHandler application/x-httpd-php
</VirtualHost>

Once the VirtualHost has set the DocumentRoot, suPHP is supposed to apply an additional chroot. See the relevant section of my /etc/suphp.conf below:
docroot=${HOME}
chroot=${HOME}

allow_file_group_writeable=false
allow_file_others_writeable=false
allow_directory_group_writeable=false
allow_directory_others_writeable=false
check_vhost_docroot=false

The chroot parameters couldn't possibly be simpler, yet suPHP spits:
Caused by SystemException in API_Linux.cpp:465: chdir() failed: No such file or directory

... when I make a request to a PHP script. The suphp log does not contain any information, this line comes from the Apache error log.
Does anyone on Earth actually now how to setup this horrible chroot feature? I've been through countless forums and mails from the listing, but no-one has yet given a proper answer (even though this feature has been patched an unbelievable number of times). Or maybe I should switch to suExec, hoping it'll offer more satisfying results...?

A: Your problem is caused by the fact that you do not understand how chroot works. Once you chroot into /home/user, that's the new root and the paths are "relative" to it. So, if you have your files in /home/user/public_html and want to chroot to /home/user then the chdir should actually be /public_html and the fastcgi document root would be the same (/public_html).
It is technically impossible for suPHP to run chroot at a farther point in the way to launching the process.


text:
Q: After creating custom Search Pipe to Dynamically Filter results , i am still getting Failed: parse errors: The pipe 'filter' could not be found I am deploying a project in angular4 and node.js. I created a custom pipe filter file named  filter.pipe.js. And all the related code. Still i am getting the error -->
Failed: Template parse errors:
The pipe 'filter' could not be found ("

] dat of result | filter:filterdata|
 paginate: { itemsPerPage: 5, currentPage: p };let i = index ">
  "): ng:///DynamicTestModule/TransactionComponent.html@220:23

CODE
filter.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';

 @Pipe({
   name: 'filter'
  })

 export class FilterPipe implements PipeTransform {
 transform(items: any[], filterdata: string): any[] {
 if(!items) return [];
 if(!filterdata) return items;
  filterdata = filterdata.toLowerCase();
  return items.filter( it => {
  return it.toLowerCase().includes(filterdata);
   });
   }
  }

app.module.ts
 import { FilterPipe} from './transaction/filter.pipe';
 import { Pipe, PipeTransform } from '@angular/core';

 @NgModule({
 imports: [ ..],

   declarations: [ FilterPipe,..]
  )}

app.component.ts
 import { Pipe, PipeTransform } from '@angular/core';
 import { FilterPipe} from '../transaction/filter.pipe';

app.component.html

              <input class="form-control" id="input1-group1 "
  style="margin-top:20px" type="text" name="search" placeholder="Enter
  Search Text"
  [(ngModel)]="filterdata">

 //some more html

Please help.

A: here is my sample app you can test it on stackblitz
stackblitz

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { FilterPipe} from './filter.pipe';
import { Pipe, PipeTransform } from '@angular/core';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent, FilterPipe ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

app.component.ts

        import { Component } from '@angular/core';
        import { Pipe, PipeTransform } from '@angular/core';
        import { FilterPipe} from './filter.pipe';
        @Component({
         selector: 'my-app',
         templateUrl: './app.component.html',
         styleUrls: [ './app.component.css' ]
        })
        export class AppComponent  {
         name = 'Angular 5';
         public filterdata = null;

         public result = [
            { id: 1, name: 'Vikram'},
            { id: 2, name: 'Vivek'},
            { id: 3, name: 'Vijay'}
         ]
        }

filter.pipe.ts

        import { Pipe, PipeTransform } from '@angular/core';

        @Pipe({
         name: 'filter'
        })

        export class FilterPipe implements PipeTransform {
         transform(items: any[], filterdata: string): any[] {
         if(!items) return [];
         if(!filterdata) return items;
          console.log(filterdata);
          filterdata = filterdata.toString().toLowerCase();
          return items.filter( it => {
            console.log(it);
            return it.name.toLowerCase().includes(filterdata);
           });
         }
        }

app.component.html

    <input class="form-control" id="input1-group1 "
    style="margin-top:20px" type="text" name="search" placeholder="Enter
    Search Text"
    [(ngModel)]="filterdata">

        Id	 Name

    {{data.id}}	 {{data.name}}


text:
Q: How to create a slow view? I want to test the timeout-behavior of my MS-Access application (with linked tables). It would be super convenient to have a slow database query. If possible, even with a predefined query duration.
I tried this:
CREATE VIEW slow_view AS
WAITFOR DELAY '00:01:05'
SELECT 1 AS one

but WAITFOR is not allowed inside a tsql view definition.
How can I create a slow database view in SQL Server, that provokes a timeout?

A: One option would be to lock a table.
In SSMS or a different tool, execute a query with a begin transaction, but don't include the commit or rollback.
BEGIN TRAN

SELECT *
FROM MyTable with(tablockx)

Then try to access the same table from a different session, it will wait until the transaction is completed / rollbacked.
In action in SSMS, left side is the locking query, right side is the blocked query.

To stop the blocking query, you can execute COMMIT in the locking query session, by selecting the COMMIT and executing it F5.


text:
Q: Error with sample code from Django docs I copied the full example code from: [customizing admin user][1] (part of the django documentation), but when I run it the django will not  came out error,but when i add a user ,the django will the came out following error .
I have not changed any code for the example,and setting follow up the document.
follow up link is example:
https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#a-full-example
Error:
IntegrityError at /admin/app01/myuser/add/
NOT NULL constraint failed: app01_myuser.last_login
Request Method: POST
Request URL:    http://127.0.0.1:8000/admin/app01/myuser/add/
Django Version: 1.8.5
Exception Type: IntegrityError
Exception Value:
NOT NULL constraint failed: app01_myuser.last_login
Exception Location: /Library/Python/2.7/site-packages/django/db/backends/sqlite3/base.py in execute, line       318

A: There is clearly a discrepancy between the custom user model you are using from the Django sample code and the definition of the table it represents in database.  The error is from the database saying the last_login column of the app01_myuser table has a NOT NULL constraint on it and you are trying to create a user with that field NULL.
Your MyUser model contains the last_login field inherited from AbstractBaseUser.  Here is the definition of last_login from the AbstractBaseUser class:
last_login = models.DateTimeField(_('last login'), blank=True, null=True)

Based on that definition of last_login, the NOT NULL constraint should not exist in your database.
Make sure your database is up to date by running migrations.  Watch for any errors that occur when running the migrations.
You can also check the app01 migrations code to try to see when and why app01_myuser was created with the NOT NULL constraint in the first place.


text:
Q: How to start 1:1 conversation with user by sending OAuthPrompt I'm using Bot Framework v4 and c# to build a teams bot that signs in user when added to channel.
My use case, is that each time a new user is added to the channel, I want to send him an OAuthPrompt in 1:1 in order to sign him in.
The samples provided for proactive message shows only how to send a simple message, and can't find the right resources to solve this problem.


text:
Q: JSF bidirectional set managed bean property value as another bean property I'm trying to set a managed property value from another bean.
faces-config.xml
<managed-bean>
    <managed-bean-name>beanA</managed-bean-name>
    <managed-bean-class>com.project.BeanA</managed-bean-class>
    <managed-bean-scope>view</managed-bean-scope>

    <managed-property>
        <property-name>value</property-name>
        <value>#{sessionBean.currentValue}</value>
    </managed-property>
</managed-bean>

<managed-bean>
    <managed-bean-name>sessionBean</managed-bean-name>
    <managed-bean-class>com.project.SessionBean</managed-bean-class>
    <managed-bean-scope>session</managed-bean-scope>
</managed-bean>

SessionBean.java and BeanA.java
class SessionBean {
    private Object currentValue; // getter+setter
}
class BeanA {
    private Object value; // getter+setter
}

I understand that the value standing in sessionBean.currentValue gets dumped into beanA.value, but when setting any value (from beanA) like beanA.setValue(x), sessionBean.currentValue remains unaltered - is this expected? If so how to enable this bidirectionality?


text:
Q: Calculate percentile from a long array? Given a long array of latencies which are in milliseconds, I want to calculate percentile from them. I got below method which does the work but I am not sure how I can verify whether this gives me accurate result?
  public static long[] percentiles(long[] latencies, double... percentiles) {
    Arrays.sort(latencies, 0, latencies.length);
    long[] values = new long[percentiles.length];
    for (int i = 0; i < percentiles.length; i++) {
      int index = (int) (percentiles[i] * latencies.length);
      values[i] = latencies[index];
    }
    return values;
  }

I would like to get 50th, 95th, 99th and 99.9th percentile from latencies array.
long[] percs = percentiles(latencies, 0.5, 0.95, 0.99, 0.999);

Is this the right way to get percentile given a long array of latencies? I am working with Java 7.

A: public static double percentile(double percentile, List<Double> items) {
    Preconditions.checkArgument(percentile >= 0);
    Preconditions.checkArgument(percentile <= 100);
    Preconditions.checkArgument(!items.isEmpty());

    Collections.sort(items);
    return items.get((int) Math.round(percentile / 100.0 * (items.size() - 1)));
}

@Test
public void test1() {
    List<Double> list = Arrays.asList(0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0);
    assertThat(percentile(0, list)).isEqualTo(0.0);
    assertThat(percentile(20, list)).isEqualTo(2.0);
    assertThat(percentile(80, list)).isEqualTo(8.0);
    assertThat(percentile(100, list)).isEqualTo(10.0);
}

@Test
public void test2() {
    List<Double> list = Arrays.asList(0.0, 1.0, 2.0, 3.0);
    assertThat(percentile(51, list)).isEqualTo(2.0);
    assertThat(percentile(49, list)).isEqualTo(1.0);
}

@Test
public void test3() {
    List<Double> list = Arrays.asList(42.0);
    assertThat(percentile(0, list)).isEqualTo(42.0);
    assertThat(percentile(100, list)).isEqualTo(42.0);
}

A: This is what you are looking for:
public static void main(String[] args) {
    List<Long> latencies = new List<Long>() { 3, 6, 7, 8, 8, 9, 10, 13, 15, 16, 20 };
    Collections.sort(latencies);

    System.out.println(percentile(latencies, 25));
    System.out.println(percentile(latencies, 50));
    System.out.println(percentile(latencies, 75));
    System.out.println(percentile(latencies, 100));
}

public static long percentile(List<Long> latencies, double percentile) {
    int index = (int) Math.ceil(percentile / 100.0 * latencies.size());
    return latencies.get(index-1);
}

A: According to Wikipedia, there is no standard definition of percentile; however, they give a few possible definitions.  The code you've posted appears to be closest to the Nearest Rank Method, but it's not quite the same.
The formula they give is
n = ceiling((P / 100) x N)

where N is the length of the list, P is the percentile, and n will be the ordinal rank.  You've already done the division by 100.  Looking at the examples they give, it's clear that the "ordinal rank" is the index in the list, but it's 1-relative.  Thus, to get an index into a Java array, you'd have to subtract 1.  Therefore, the correct formula should be
n = ceiling(percentile * N) - 1

Using the variables in your code, the Java equivalent would be
(int) Math.ceil(percentiles[i] * latencies.length) - 1

This is not quite the code you've written.  When you cast a double to an int, the result is rounded toward 0, i.e. it's the equivalent of the "floor" function.  So your code computes
floor(percentiles[i] * latencies.length)

If percentiles[i] * latencies.length is not an integer, the result is the same either way.  However, if it is an integer, so that "floor" and "ceiling" are the same value, then the result will be different.
An example from Wikipedia is to compute the 40th percentile when the list is {15, 20, 35, 40, 50}.  Their answer is to find the second item in the list, i.e. 20, because 0.40 * 5 = 2.0, and ceiling(2.0) = 2.0.
However, your code:
int index = (int) (percentiles[i] * latencies.length);

will result in index being 2, which isn't what you want, because that will give you the third item in the list, instead of the second.
So in order to match the Wikipedia definition, your computation of the index will need to be modified a little.  (On the other hand, I wouldn't be surprised if someone comes along and says your computation is correct and Wikipedia is wrong.  We'll see...)

A: If the array is sorted, you should just return the relative element in your array (e.g., p99 in a 1000-elements array is the 990th element).
If the array is unsorted, and in order to calculate percentiles more efficiently, you should probably use something like Quickselect.


text:
Q: Overlapping content in popups in kivy I followed the documentation for using FileChoose on the kivy website (https://kivy.org/doc/stable/api-kivy.uix.filechooser.html). However, when I open the popup for LoadDialog() and click on one of the icons, there's a lot of overlap for the folder's content.
main.py
class Root(Screen):
    loadfile = ObjectProperty(None)
    savefile = ObjectProperty(None)
    text_input = ObjectProperty(None)

    def dismiss_popup(self):
        self._popup.dismiss()

    def show_load(self):
        content = LoadDialog(load=self.load, cancel=self.dismiss_popup)
        self._popup = Popup(title="Load file", content=content,
                            size_hint=(0.9, 0.9))
        self._popup.open()

class LoadDialog(FloatLayout):
    load = ObjectProperty(None)
    cancel = ObjectProperty(None)

main.kv
<LoadDialog>:
    BoxLayout:
        size: root.size
        pos: root.pos
        orientation: "vertical"
        FileChooserIconView:
            id: filechooser

            GridLayout:
                cols:2
                size_hint_y: None
                height: 30
                Button:
                    text: "Cancel"
                    on_release: root.cancel()

                Button:
                    text: "Load"
                    on_release: root.load(filechooser.path, filechooser.selection)

If I use BoxLayout instead of FloatLayout in the LoadDialog() class, the overlapping issue is solved, however, the popup is divided in half with two columns.
main.py
class LoadDialog(BoxLayout):
    load = ObjectProperty(None)
    cancel = ObjectProperty(None)

I've also tried using GridLayout, but that has the same overlapping issue as with FloatLayout.


text:
Q: Set values to zero in specific columns in a data.table In a data.table, I try to set the values in the columns; 2018, 2019, 2020, 2021 to zero, if the values in column ID and Score are identical.
This would be an example data.table:
library(data.table)

data = data.table(
  ID = c("a1", "a2", "a2", "a1", "a2", "a1", "a1"),
  Score = c("A","B","C","A","B","C","A"),
  "2018" = c(3,5,1,3,5,6,6),
  "2019" = c(3,5,6,2,1,4,2),
  "2020" = c(9,6,6,9,6,9,9),
  "2021" = c(4,0,3,8,5,4,6))

data <- data[order(ID, Score)]

I tried it with duplicated(), but with that function, it deletes the whole row. I only want to set the values to zero as shown in the solution example data.table.
solution = data.table(
  ID = c("a1", "a2", "a2", "a1", "a2", "a1", "a1"),
  Score = c("A","B","C","A","B","C","A"),
  "2018" = c(3,5,1,0,0,6,6),
  "2019" = c(3,5,6,2,1,4,0),
  "2020" = c(9,6,6,0,0,9,0),
  "2021" = c(4,0,3,8,5,4,6))

solution <- solution[order(ID, Score)]

Thanks a lot!

A: You can use replace with duplicated to turn the repeated values to 0 in each group.
library(data.table)

cols <- 3:6
data[, (cols) := lapply(.SD, function(x) replace(x, duplicated(x), 0)),
                 .SDcols = cols, .(ID, Score)]
data

#   ID Score 2018 2019 2020 2021
#1: a1     A    3    3    9    4
#2: a1     A    0    2    0    8
#3: a1     A    6    0    0    6
#4: a1     C    6    4    9    4
#5: a2     B    5    5    6    0
#6: a2     B    0    1    0    5
#7: a2     C    1    6    6    3


text:
Q: How to get my resource data from a HAL response? I'm building an API using Spring Boot 2 and the Angular 6 client has to deal with responses such as this one for example :
{
  "_embedded" : {
    "userResourceList" : [ {
      "firstname" : "Stephane",
      "lastname" : "Toto",
      "email" : "toto@yahoo.se",
      "confirmedEmail" : false,
      "password" : "bWl0dGlwcm92ZW5jZUB5YWhvby5zZTptaWduZXRjNWRlMDJkZS1iMzIwLTQ4Y2YtOGYyMS0wMmFkZTQ=",
      "userRoles" : [ {
        "role" : "ROLE_ADMIN",
        "id" : 1
      } ],
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/api/users/1"
        },
        "roles" : {
          "href" : "http://localhost:8080/api/users/1/roles"
        }
      },
      "id" : 1
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/api/users"
    }
  },
  "page" : {
    "size" : 20,
    "totalElements" : 1,
    "totalPages" : 1,
    "number" : 0
  }
}

All REST resources endpoints would retrun such HALified responses.
I wonder how to deal with these. If there is such library that eases the parsing and extraction of the actual payload.
I heard of the RestAngular library but I'm not so sure it's what I want.
Maybe something less invasive only assisting in the parsing like :
const user: User = hal2Json.parse<User>(response);

UPDATE: I didn't find any such library and so I resorted to this implementation:
public getSome(searchTerm: string, sortFieldName: string, sortDirection: string, currentPage: number, limit: number): Observable<any> {
  let httpParams = new HttpParams()
  .set('page', currentPage.toString())
  .set('size', limit.toString());
  if (searchTerm) {
    httpParams = httpParams.append('searchTerm', searchTerm);
  }
  if (sortFieldName && sortDirection) {
    httpParams = httpParams.append('sort', sortFieldName + ',' + sortDirection);
  }
  return this.httpService.get(this.usersUrl, httpParams);
}

export class UsersApi extends PaginationApi {

  constructor(users: User[], currentPageNumber: number, elementsPerPage: number, totalElements: number, totalPages: number) {
      super(currentPageNumber, elementsPerPage, totalElements, totalPages);
      this.users = users;
  }

  users: User[];

}

getUsers(searchTerm: string, sortFieldName: string, sortDirection: string, currentPageNumber: number): Observable<UsersApi> {
  return this.userService.getSome(searchTerm, sortFieldName, sortDirection, currentPageNumber, this.elementsPerPage)
    .pipe(
      map(response => {
        return new UsersApi(
          response._embedded.userResourceList as User[],
          this.paginationService.correctPageNumberMispatch(response.page.number),
          response.page.size,
          response.page.totalElements,
          response.page.totalPages
        );
      })
    );
}

A: Define an interface to wrap the HAL response. This is how I did it for my book service:
// book.service.ts
import { Injectable } from '@angular/core';
import { Book } from '../book';
import { Observable, map } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Injectable({
    providedIn: 'root'
})
export class BookService {

    private booksUrl = 'http://localhost:8080/books';

    constructor(private http: HttpClient) { }

    getBooks(): Observable<Book[]> {
        return this.http.get<GetBooksResponse>(this.booksUrl).pipe(
            map(response => response._embedded.bookList)
        );
    }
}

interface GetBooksResponse {
    _embedded: {
        bookList: Book[];
        _links: {self: {href: string}};
    };
}

The HAL response:
Credit goes to this post: https://medium.com/@tbrouwer/spring-boot-backend-for-angular-tour-of-heroes-106dc33a739b

A: You could try the halfred npm module. Seems to do what you want:
https://www.npmjs.com/package/halfred
npm install halfred --save

then import it:
import * as 'halfred' from 'halfred' // something like this should work

then use it:
const resource = halfred.parse(object)


text:
Q: Blank configuration page I want to install phpfox, but after two steps, I see a blank page and not configuration page.
What can I do?

A: This is usually due to an error which is being hidden. A few things to check...
Most of this is defined in your php.ini file which you can modify to change it globally. You will have to restart apache.

*

*Check your error_log file

*

*On the index.php add ini_set('error_log', '/path/to/log'); to specify log file

*Turn on displaying of errors display_errors

*

*On the index.php add ini_set('display_errors', true);

*Echo your way placing echo __LINE__ . "<br />"; to see how far you get into the script.

A: You have phpfox setup without licence. So your installation process is not working properly.
Please install it on your local system and upload server.sett.php file and database online. And change the credentials in server.sett.php file after upload

A: I had this problem
This happend when you use phpfox which have not licence. As I know, there is no way. you have to buy a licence.

A: You can skip Phpfox License Key checking by insert this line : define('PHPFOX_SKIP_INSTALL_KEY',  true); into file: install/index.php
Then you can start install Phpfox without license key.
Please notice that you should use it only for experimental purpose only.


text:
Q: Are there rest calls for these Api Management actions? Say I want to automate API Management, I would want to

*

*Create Api (https://learn.microsoft.com/en-us/rest/api/apimanagement/apis#Apis_CreateOrUpdate)

*Create certificate (https://learn.microsoft.com/en-us/rest/api/apimanagement/certificates#Certificates_CreateOrUpdate)

*Tie certificate to API (¿?)

*Create API Policy (¿?)

I've went through all the calls one by one, and wasn't able to identify anything meaningful.
edit: or a confirmation that this is not yet possible with the API.
edit: looking at the swagger definition of ApiManagement, I don't think its there?
edit: exported configuration to Git, doesn't look like it contains the cert, so this also wouldn't help?

A: The client Certificate is not represented in the model of the ApiContract. When you want to tie a Certificate to an API, we create a policy authentication certificate policy in the API Scope.

<policies>
<inbound>
    <base />
    <authentication-certificate thumbprint="***19B22E********5E2E**820" />
</inbound>
<backend>
    <base />
</backend>
<outbound>
    <base />
</outbound>
<on-error>
    <base />
</on-error>

You can create an API Policy using https://learn.microsoft.com/en-us/rest/api/apimanagement/apimanagementrest/azure-api-management-rest-api-api-entity#SetAPIPolicy


text:
Q: sqlalchemy: 'metadata.drop_all' does not work I tried to drop all the exist tables in the schema by using 'Base.metadata.drop_all(bind=engine)', and recreate a new table. However, the table did not be dropped as I thought, and records were just appended to the old table. I'm new to sqlalchemy, could anyone tell me what I was doing wrong here...thanks!
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

engine = create_engine("mysql+pymysql://root:pswd@127.0.0.1:3306/bond?charset=utf8", echo=True)
Session = sessionmaker(bind=engine)
session = Session()
Base = declarative_base(bind=engine)
Base.metadata.drop_all(bind=engine)
table = Table('TradeHistory', Base.metadata,
     Column('Id', Integer, primary_key=True),
     Column('trade_date', String(50)),
     Column('rem_period', String(50)),
      Column('bond_code', String(50)),
      Column('bond_name', String(50)),
      Column('bond_rating', String(50)),
      Column('bond_yield', String(50)),
      Column('note', String(50)),
      Column('offer', String(50)),
      Column('bid', String(50)),
      Column('amount', String(50)))
Base.metadata.create_all(bind=engine)
conn.execute(table.insert(), listToWrite)
session.commit()
session.close()

A: Base.metadata.drop_all(bind=engine) will drop all tables that it knows about.
You are defining table 'TradeHistory' after that line, so that table is not going to be deleted.
So, first define your whole data model (that is usually done in a separate model module btw), then perform operations like drop_all and create_all.


text:
Q: Java SQL JTable, my first project, how can i improve and simplify my code? any suggestions I am studying java for 4 months and this project is what i came up with, i know i should make more classes and methods for quality but i am still learning. Please help to me if there is any simpler and cleaner ways to achieve the same results as this. thank you.
  import java.awt.FlowLayout;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.event.ListSelectionEvent;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.JTable;
    import javax.swing.JLabel;
    import java.awt.Font;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.sql.Statement;
    import java.util.Vector;
    import javax.swing.JTextField;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;

    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;

    public class GUI extends JDialog {

        private JTextField txtID;
        private JTextField txtName;
        private JTextField txtDep;
        private JTextField txtGender;
        private JTextField txtPosition;
        private JTextField txtSalary;
        private JTable table;
        ResultSet rs;
        Connection conn;
        Statement statement;

        public GUI() throws SQLException {

            setBounds(100, 100, 671, 448);
            getContentPane().setLayout(null);
             try {
                    // Set System L&F
                    UIManager.setLookAndFeel(
                            UIManager.getSystemLookAndFeelClassName());
                } catch (UnsupportedLookAndFeelException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
                    System.out.println(ex.getMessage());
                }

            table = new JTable();
            JScrollPane scrollPane = new JScrollPane();
            scrollPane.setBounds(10, 11, 635, 205);
            getContentPane().add(scrollPane);

            scrollPane.setViewportView(table);

            String dbURl = "jdbc:mysql://localhost:3306/employees";
            try {
                conn = DriverManager.getConnection(dbURl, "root", "1234");
                if (conn != null) {
                    System.out.println("Connected");

                    String s1 = "SELECT * FROM employees";
                    statement = conn.createStatement();

                    rs = statement.executeQuery(s1);

                    table.setModel(buildTableModel(rs));
                    table.setBounds(10, 11, 634, 216);

                }

            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }

            table.getSelectionModel().addListSelectionListener((ListSelectionEvent event) -> {
                try {

                    if (table.getSelectedRow() >= 0) {
                        Object employee_id = table.getValueAt(table.getSelectedRow(), 0);
                        Object full_name = table.getValueAt(table.getSelectedRow(), 1);
                        Object gender = table.getValueAt(table.getSelectedRow(), 2);
                        Object department = table.getValueAt(table.getSelectedRow(), 3);
                        Object position = table.getValueAt(table.getSelectedRow(), 4);
                        Object salary = table.getValueAt(table.getSelectedRow(), 5);

                        txtID.setText(employee_id.toString());
                        txtName.setText(full_name.toString());
                        txtGender.setText(gender.toString());
                        txtDep.setText(department.toString());
                        txtPosition.setText(position.toString());
                        txtSalary.setText(salary.toString());
                    }
                } catch (Exception ex) {
                    System.out.println(ex.getMessage());
                }
            });

            JPanel buttonPane = new JPanel();
            buttonPane.setBounds(0, 376, 655, 33);
            FlowLayout fl_buttonPane = new FlowLayout(FlowLayout.LEFT);
            fl_buttonPane.setHgap(10);
            buttonPane.setLayout(fl_buttonPane);
            getContentPane().add(buttonPane);

            JButton btnAdd = new JButton("ADD");
            btnAdd.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    String sql_stmt = "INSERT INTO employees (full_name,gender,department,position,salary)";
                    sql_stmt += " VALUES ('" + txtName.getText() + "','" + txtGender.getText() + "','" + txtDep.getText()
                            + "','" + txtPosition.getText() + "','" + txtSalary.getText() + "')";

                    try {

                        statement.executeUpdate(sql_stmt);
                        rs = statement.executeQuery("select * from employees");
                        table.setModel(buildTableModel(rs));

                    } catch (SQLException e) {
                        System.out.println(e.getMessage());
                    }

                    clearInputBoxes();
                }
            });
            buttonPane.add(btnAdd);

            JButton btnUpdate = new JButton("UPDATE");
            btnUpdate.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {
                    String sql_stmt3 = "UPDATE employees SET full_name = '" + txtName.getText() + "'";
                    sql_stmt3 += ",gender = '" + txtGender.getText() + "'";
                    sql_stmt3 += ",department = '" + txtDep.getText() + "'";
                    sql_stmt3 += ",position = '" + txtPosition.getText() + "'";
                    sql_stmt3 += ",salary = '" + txtSalary.getText() + "'";
                    sql_stmt3 += " WHERE employee_id = '" + txtID.getText() + "'";

                    try {

                        statement.executeUpdate(sql_stmt3);
                        rs = statement.executeQuery("select * from employees");
                        table.setModel(buildTableModel(rs));

                    } catch (SQLException e) {
                        System.out.println(e.getMessage());
                    }

                    clearInputBoxes();
                }
            });
            btnUpdate.setActionCommand("OK");
            buttonPane.add(btnUpdate);
            getRootPane().setDefaultButton(btnUpdate);

            JButton btnDel = new JButton("DELETE");
            btnDel.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent arg0) {

                    String sql_stmt2 = "DELETE FROM employees WHERE employee_id = '" + txtID.getText() + "'";
                    try {

                        statement.executeUpdate(sql_stmt2);
                        rs = statement.executeQuery("select * from employees");
                        table.setModel(buildTableModel(rs));

                    } catch (SQLException e) {
                        System.out.println(e.getMessage());
                    }

                    clearInputBoxes();
                }

            });

            btnDel.setActionCommand("Cancel");
            buttonPane.add(btnDel);

            JLabel lblID = new JLabel("ID");
            lblID.setFont(new Font("Verdana", Font.BOLD, 14));
            lblID.setBounds(26, 237, 79, 23);
            getContentPane().add(lblID);

            JLabel lblFullname = new JLabel("Fullname");
            lblFullname.setFont(new Font("Verdana", Font.BOLD, 14));
            lblFullname.setBounds(26, 271, 79, 23);
            getContentPane().add(lblFullname);

            JLabel lblGender = new JLabel("Gender");
            lblGender.setFont(new Font("Verdana", Font.BOLD, 14));
            lblGender.setBounds(340, 237, 79, 23);
            getContentPane().add(lblGender);

            JLabel lblPosition = new JLabel("Position");
            lblPosition.setFont(new Font("Verdana", Font.BOLD, 14));
            lblPosition.setBounds(340, 271, 79, 23);
            getContentPane().add(lblPosition);

            JLabel lblDep = new JLabel("DEP");
            lblDep.setFont(new Font("Verdana", Font.BOLD, 14));
            lblDep.setBounds(26, 305, 79, 23);
            getContentPane().add(lblDep);

            JLabel lblSalary = new JLabel("Salary");
            lblSalary.setFont(new Font("Verdana", Font.BOLD, 14));
            lblSalary.setBounds(340, 305, 79, 23);
            getContentPane().add(lblSalary);

            txtID = new JTextField();
            txtID.setBounds(115, 240, 215, 20);
            getContentPane().add(txtID);
            txtID.setColumns(10);

            txtName = new JTextField();
            txtName.setColumns(10);
            txtName.setBounds(115, 274, 215, 20);
            getContentPane().add(txtName);

            txtDep = new JTextField();
            txtDep.setColumns(10);
            txtDep.setBounds(115, 308, 215, 20);
            getContentPane().add(txtDep);

            txtGender = new JTextField();
            txtGender.setColumns(10);
            txtGender.setBounds(429, 240, 107, 20);
            getContentPane().add(txtGender);

            txtPosition = new JTextField();
            txtPosition.setColumns(10);
            txtPosition.setBounds(429, 274, 215, 20);
            getContentPane().add(txtPosition);

            txtSalary = new JTextField();
            txtSalary.setColumns(10);
            txtSalary.setBounds(429, 308, 215, 20);
            getContentPane().add(txtSalary);

        }

        public static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException {

            ResultSetMetaData metaData = rs.getMetaData();

            // names of columns
            Vector<String> columnNames = new Vector<String>();

            int columnCount = metaData.getColumnCount();

            for (int column = 1; column <= columnCount; column++) {
                columnNames.add(metaData.getColumnName(column));

            }

            // data of the table
            Vector<Vector<Object>> data = new Vector<Vector<Object>>();

            while (rs.next()) {

                Vector<Object> vector = new Vector<Object>();

                for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
                    vector.add(rs.getObject(columnIndex));
                }
                data.add(vector);
            }

            return new DefaultTableModel(data, columnNames);

        }

        private void clearInputBoxes() {
            txtID.setText("");
            txtName.setText("");
            txtGender.setText("");
            txtDep.setText("");
            txtPosition.setText("");
            txtSalary.setText("");
        }

        public static void main(String[] args) throws Exception {
            GUI g = new GUI();
            g.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            g.setVisible(true);
        }
    }

A:
if there is any simpler and cleaner ways to achieve the same results

*

*Don't use null layouts. Swing was designed to be used with layout managers. Read the section from the Swing tutorial on Layout Managers for more information and working examples.

*Use PreparedStatement for your SQL. It is easier to create and maintain the SQL statement. Read the API for basic information about the class and then search the forum/web for examples.


text:
Q: Save output of grep to file depending on grep match Got a quick question here:
Say I'm trying to separate the lines of a group of files, they all look like this:
pid text number
And I want to separate the lines into different files using the pid, how can I achieve this?
So far, I've tried something like:
cat files | grep '\([0-9]\{3\}\)' > $1.txt

That ofcourse, doens't work.. any ideas?

A: The file with pids :
$ cat /tmp/l
123 azerty
234 qwerty
456 bepo

The awk code :
$ awk '/^[0-9]{3}/{print $0 > $1".txt"}' /tmp/l

The output of ls :
$ ls
123.txt
234.txt
456.txt


text:
Q: Why wsdl2java generated code use CXF dependencies at will? I use Apache CXF 3.0.4 wsdl2java to generate code from this wsdl with following command:
./wsdl2java -client -exsh true -d weather -p weather -verbose url

As far as I know wsdl2java generates pure java code using only JAX-WS. Generated code works fine without any additional library/dependency. I've grepped it to find any CXF classes, but it seems to be free from CXF. The problem flows out when I add specific CXF dependency to my pom.xml. This dependency is:
<dependency>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-rt-frontend-jaxws</artifactId>
    <version>3.1.0</version>
</dependency>

After adding this, application seems to use different implementation of JAX-WS( is it even possible?).
Generated code contains among other things WeatherSoap interface. One of it's methods is getWeatherInformation()
@WebService(targetNamespace = "http://ws.cdyne.com/WeatherWS/", name = "WeatherSoap")
@XmlSeeAlso({ObjectFactory.class})
public interface WeatherSoap {

    /**
     * Gets Information for each WeatherID
     */
    @WebResult(name = "GetWeatherInformationResult", targetNamespace = "http://ws.cdyne.com/WeatherWS/")
    @RequestWrapper(localName = "GetWeatherInformation", targetNamespace = "http://ws.cdyne.com/WeatherWS/", className = "weather.GetWeatherInformation")
    @WebMethod(operationName = "GetWeatherInformation", action = "http://ws.cdyne.com/WeatherWS/GetWeatherInformation")
    @ResponseWrapper(localName = "GetWeatherInformationResponse", targetNamespace = "http://ws.cdyne.com/WeatherWS/", className = "weather.GetWeatherInformationResponse")
    public weather.ArrayOfWeatherDescription getWeatherInformation();

...

}

Without cxf-rt-frontend-jaxws dependency

*

*Step into getWeatherInformation() while debugging leads to GetWeatherInformation( another generated class.

*Step into GetWeatherInformation leads to com.oracle.webservices.internal.api.message.BasePropertySet

*...

*Result from SOAP webservice received.

With cxf-rt-frontend-jaxws dependency

*

*Step into getWeatherInformation while debugging leads to org.apache.cxf.jaxws.JaxWsClientProxy (why?)

*...

*Exception is thrown:

Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: Could not find conduit initiator for address: http://wsf.cdyne.com/WeatherWS/Weather.asmx and transport: http://schemas.xmlsoap.org/soap/http
    at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:161)
    at com.sun.proxy.$Proxy33.getWeatherInformation(Unknown Source)
    at weather.WeatherSoap_WeatherSoap_Client.main(WeatherSoap_WeatherSoap_Client.java:49)
Caused by: java.lang.RuntimeException: Could not find conduit initiator for address: http://wsf.cdyne.com/WeatherWS/Weather.asmx and transport: http://schemas.xmlsoap.org/soap/http
    at org.apache.cxf.binding.soap.SoapTransportFactory.getConduit(SoapTransportFactory.java:224)
    at org.apache.cxf.binding.soap.SoapTransportFactory.getConduit(SoapTransportFactory.java:229)
    at org.apache.cxf.endpoint.AbstractConduitSelector.createConduit(AbstractConduitSelector.java:145)
    at org.apache.cxf.endpoint.AbstractConduitSelector.getSelectedConduit(AbstractConduitSelector.java:107)
    at org.apache.cxf.endpoint.UpfrontConduitSelector.prepare(UpfrontConduitSelector.java:63)
    at org.apache.cxf.endpoint.ClientImpl.prepareConduitSelector(ClientImpl.java:853)
    at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:511)
    at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:425)
    at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:326)
    at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:279)
    at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
    at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:139)
    ... 2 more

I know that there is workaround for this exception which is mentioned here and it works. But not for my work application. It throws NPE after all:
Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: java.lang.NullPointerException
    ...
Caused by: org.apache.cxf.binding.soap.SoapFault: java.lang.NullPointerException
    at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.unmarshalFault(Soap11FaultInInterceptor.java:86)
    at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.handleMessage(Soap11FaultInInterceptor.java:52)
    at org.apache.cxf.binding.soap.interceptor.Soap11FaultInInterceptor.handleMessage(Soap11FaultInInterceptor.java:41)
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307)
    at org.apache.cxf.interceptor.AbstractFaultChainInitiatorObserver.onMessage(AbstractFaultChainInitiatorObserver.java:113)
    at org.apache.cxf.binding.soap.interceptor.CheckFaultInterceptor.handleMessage(CheckFaultInterceptor.java:69)
    at org.apache.cxf.binding.soap.interceptor.CheckFaultInterceptor.handleMessage(CheckFaultInterceptor.java:34)
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307)
    at org.apache.cxf.endpoint.ClientImpl.onMessage(ClientImpl.java:802)
    at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:1642)
    at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:1533)
    at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1336)
    at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56)
    at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:652)
    at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307)
    at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:516)
    at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:425)
    at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:326)
    at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:279)
    at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
    at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:139)
    ... 7 more

Question time

*

*Why Apache-CXF is used even when application works fine without it?

*Is it possible to force application to stop using Apache-CXF in this case?

I don't need this dependencies for client( since it works fine without them). I just want to produce SOAP as well. And thats why I need this dependencies. The only solution which I see is to split application into separate consumer and producer.

A:
application seems to use different implementation of JAX-WS( is it even possible?).

Yes. CXF have it's own jax-ws provider and it's jar contains a service file declaring it. (when the JVM needs a jax-ws provider: it looks on the classpath to see if there is a non-default provider declared... and if any use it).
Why ?
That's the Java specs : http://docs.oracle.com/javaee/5/api/javax/xml/ws/spi/Provider.html#provider()

Is it possible to force application to stop using Apache-CXF in this case?

Yes. Create the appropriate resource file on your classpath to redirect to the default implementation.
In details : the file must be here : META-INF/services/javax.xml.ws.spi.Provider (if you use maven: put it simply here : /src/main/resources/META-INF/services/javax.xml.ws.spi.Provider)
And it must contains one single line :
javax.xml.ws.spi.Provider


text:
Q: Is it a good practice to use JAVA 8 for android development? I read the instructions for using Java8 for android development from this answer and (orfjackal/retrolambda).
I wanted to know if it is a good practice to use this technique to implement Java 8. Does this affects the application performance?
It is mentioned in the blog-
retrolambda It does this by transforming your Java 8 compiled bytecode so that it can run on an older Java runtime.

A: I think it is too early to say that use Java 8 is a good practice for android development, officially android needs the Java 6 JDK as mentioned at the bottom of this page: https://developer.android.com/sdk/installing/installing-adt.html
Also, there are some Android APIs that even not support try with resources, so I don't think they'll support Java 8 at all.


text:
Q: Fetch 2 API and show the both result together. (React.JS) I'm new to react.js, and currently conducting a project in my university. I am facing some problem regarding to Reactjs. Hopefully you guys can guide me to solve this.
So I have an Item Listing API which is gonna display in card component. I also have an API for Item Photo View, which is actually pass the id from Listing API and also will show in card component. So each item has differents image. Therefore, I am gonna call this two API in my react and I will see all the Item in the UI include their images.
This is Listing result from console log.:

Every item have different photo, so I create another API to view the item photo according to their id
Here is my front-end code, how I call the API:
    componentDidMount(){
        // console.log(loginEmail)
          fetch(`http://localhost:9000/api/item/list`,)
          .then((resp)=>{
            resp.json().then((res)=>{
             console.log(res.data);
              this.setState({data: res.data});

            }

            )
          })

          const id = this.state.data.id;

          fetch(`http://localhost:9000/api/item/photo/view/${id}`,)
          .then((resp)=>{
            resp.json().then((res)=>{
             console.log(res);
              this.setState({res});}
            )
          })
        }

Render component:
    render() {
        const data = this.state.data;
        return (
                <>

Item list

                        {
                                Object.keys(data).map((key) =>

                                    {/*  */} //no idea for the this, how to call the image

{ data[key].organisation_name}

asdasdaasd

                                    <button type="button" className="btn btn-primary text-capitalize" >
                                        details
                                    </button>
                                    Item Detail

                                )
                        }

                </>
            );
    }
}

The first Listing API is able to run, and the detail of item are able to show in card. But, I can't get the result of Second API(Item Image View). The image could not shown out, and getting the error of this on my preview

Is there any place I'm wrong? or there is another way that I can get the image from 2nd API and put it in card?

A: Put inside of the first API call the second API call:
componentDidMount(){
        // console.log(loginEmail)
          fetch(`http://localhost:9000/api/item/list`,)
          .then((resp)=>{
            resp.json().then((res)=>{
             console.log(res.data);
              this.setState({data: res.data});
              const id = data.id;

              fetch(`http://localhost:9000/api/item/photo/view/${id}`,)
              .then((resp)=>{
                resp.json().then((res)=>{
                console.log(res);
                  this.setState({res});}
                )
              })

            }

            )
          })
        }

Or use async/await syntax to improve the readability.


text:
Q: Understanding the GHS linker file Can anybody teach me how to understand the linker file.It will have different ROM and RAM sections.
My question is on what basis how we will decide the memory sections,its addresses and size.
How .map will generate on this.

A: The linker directive file is an input to the linking stage of the build.  The linker directive file specifies the type, location and size of memories available to the linker so that the linker can determine where to locate the various code and data portions of the program.  The information that you put in the linker directive file is based upon the design of your hardware and your application.  For example, your microcontroller may have internal SRAM and Flash memories and your board may have external SRAM and Flash memories tied to particular chip selects.  The linker directive file is how you make the linker aware of the location and size of these memories.  Furthermore, for your application you may want particular code or data to be located in a named memory section at a particular address.  For example, you want the startup routine to be located at the reset vector.  The linker directive file is how you specify the name, location, and size of these special sections.  (A pragma statement in the source code can be used to place a routine in a named section.)
The map files is an output of the link stage of the build.  After the linker has located all the code and data sections into the available memories, it produces the map file to detail all those locations.
Typically, toolchain or eval board vendors will provide example linker directive files for common evaluation boards.  And even when you're working with a custom board you can usually tweak the linker directive file provided for a similar evaluation board rather than writing the linker directive file from scratch.


text:
Q: Unable to scale Gunicorn/Flask HelloWorld over 125 RPS I have a Flask app that I have been unable to scale past 125 RPS locally. It is a simple 'hello world' as seen below.
I'm using the Locust.io load testing tool. I have pointed the same load test to a local Golang hello world, and am able to get into 1000's of RPS. IMHO this rules out my Locust and OS configurations as potential bottlenecks.
I'm using 17 workers as my machine has 8 cores ((2*CPU)+1 is recommended by Gunicorn docs)
From what I've read, using the gevent worker type for Gunicorn should allow me to reach 1000's of RPS, just like with Golang. Is this a correct assumption? or am I missing something critical?
abbreviated code:
app = Flask(__name__)

@app.route('/')
def hello():
    return 'hello world!'

Gunicorn conf:
gunicorn -k gevent -w 17  --worker-connections 100000 app:app

Locust load test results. Each 'user' GETs '/' once per 4s

A: Answer from authors here: https://github.com/benoitc/gunicorn/issues/305
After another week of debugging, I figured it out! Turns out there is an additional worker type, gevent_pywsgi. Using this worker type increased the throughout roughly 10x, to levels I would consider acceptable.
My testing showed no difference in performance between the sync worker and gevent worker, so I'm still not sure what's going on there, or what the intent of the gevent worker type is.

A: I was also in the same scenario and was using sync workers (the default worker class) in gunicorn and the goal was the same, to increase the RPS.
Then I switched to async workers with the help of gevent (one of the other options).
The common mistake that we do (I did too) when using gevent with gunicorn is just using it as an argument i.e --worker-class=gevent.
which makes the whole gunicorn command seem like this...
gunicorn --bind=127.0.0.1:5000 --workers=4 --worker-class=gevent wsgi:application

What we all forget to do is to make changes in the flask code accordingly.
We've to modify this
from flask import Flask

app = Flask(__name__)

    @app.route('/')
    def hello():
        return 'hello world!'

into this
from gevent import monkey
monkey.patch_all() # monkey patching

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello():
    return 'hello world!'

Adding these lines is crucial and you will experience an increment in the RPS.
In my case, I got
~90 RPS  with 20 sync workers + EC2 server (compute optimized) + API hit from local
~430 RPS with 8 async workers (gevent) + 1 thread per worker + EC2 server (normal) + API hit from local
~600 RPS with 8 async workers (gevent) + 16 threads per worker + EC2 server (normal) + API hit from local
~900 RPS with 8 async workers (gevent) + 32 threads per worker + EC2 server (normal) + API hit from local
You can see the drastic 10x increment in RPS using those 2 lines in my case (even though I was using a normal EC2 machine in later tests).


text:
Q: ComboBox _Click and _Change events triggering on ListFillRange edit? (Excel VBA) Using Excel 2010 here. Starting with a blank sheet, I create an ActiveX combo box.
1) Open the properties window and set:
ListFillRange = "A1:A3"

2) Manually populate each cell in range A1:A3 with the words "one", "two" and "three", respectively (these strings are arbitrary).
3) Click the combo box drop-down arrow to check that the values appear in the list.
4) Enable Design Mode and double-click the combo box to open the VBA editor, then paste the following code (which assumes the combo box name is is "ComboBox1"):
Private Sub ComboBox1_change()
    MsgBox "Change event"
End Sub

Private Sub ComboBox1_click()
    MsgBox "Click event"
End Sub

5) Return to the sheet containing the combo box and disable Design Mode.
6) Click the combo box drop button and select the top item ("one") from the list. Immediately after you release the mouse button you should get two MsgBox windows, one for the _click event and another for the _change event, as instructed by the above Subs.
7) With "one" still selected, double-click in any of the cells in ListFillRange (so, for example, cell "A2")
Result: Step 7 triggers both the _click and _change events! This happens whenever a value in the ListFillRange range is edited AND the string in the combo box exactly matches at least one of the values in ListFillRange.
Any idea why this could be? Is it a bug? Thanks in advance!

A: I don't use ListFillRange for ActiveX controls. You should probably avoid using those. If the data is static then try populating it using AddItem through code.