text:
Q: How can I achieve java byte code encryption (against reverse engineering)
Possible Duplicate:
How to lock compiled Java Classes to prevent decompilation

...ideally combined with licensing?
Our product is ported from PHP to Java. With PHP, there was a great code encryption / license tool named IONCube Encoder. It encrypts the PHP source code an allows the execution only if a appropriate license is present.
Is there any equivalent for a Java application (that does not rely on a hardware dongle)?

A: Take a look at JET Excelsior. That's what we've been using and it's worked pretty well for us.

A: IONCube Encoder works by obfuscating your code, not encrypting it.  If you want to get the same effect, there are a number of obfuscation tools for Java, such as

*

*KlassMaster

*DashO

A: You might also want to have a look at the proguard obfuscator


text:
Q: qmake searching for library in absolute path I am cross-compiling a Qt Application. My host is a Ubuntu system and target is ARM board with buildroot based filesystem and I am using Qt 5.3.1. When I try to run make, I get the following error:
/home/hamzah/vibrante/toolchains/tegra-4.8.1-nv/usr/bin/armv7a-vfpv3-cortex_a15-linux-gnueabi/../../libexec/armv7a-vfpv3-cortex_a15-linux-gnueabi/gcc/arm-cortex_a15-linux-gnueabi/4.8.1/ld: cannot find /lib/libpthread.so.0
/home/hamzah/vibrante/toolchains/tegra-4.8.1-nv/usr/bin/armv7a-vfpv3-cortex_a15-linux-gnueabi/../../libexec/armv7a-vfpv3-cortex_a15-linux-gnueabi/gcc/arm-cortex_a15-linux-gnueabi/4.8.1/ld: cannot find /usr/lib/libpthread_nonshared.a
collect2: error: ld returned 1 exit status

As you can see, it is using absolute path in target for libpthread.so.0 and libpthread_nonshared.a. This library is placed in the target filesystem hosted on my host. The target library search path has been added in qmake.conf using QMAKE_LIBDIR variable:
QMAKE_LIBDIR  += /home/hamzah/buildroot/output/host/usr/arm-buildroot-linux-gnueabihf/sysroot
QMAKE_LIBDIR  += /home/hamzah/buildroot/output/host/usr/arm-buildroot-linux-gueabihf/sysroot/usr/lib

I need to know how to make the ld able to find this library using sysroot variable or any other approach.
PS: I am compiling Qt Application. Pre-built Qt applications are running on both my host and target

A: Use the qmake built by Buildroot in output/host/usr/bin. This one has the right paths pre-configured. If it still doesn't work, please submit a bug report in the Buildroot bug tracker, with a simple test case to reproduce the problem, as well as the list of steps to reproduce it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trying to convert C to Assembly I have a struct in C:
struct struct1 {
    uint16_t a;
    uint32_t b;
    char * c;
    struct struct2* d;
}

How can I define the same struct in Nasm? I've tried this:
struc struct1
  .a resw
  .b resdw
  .c ???? ; what should be here?
  .d ???? ; what should be here?
endstruc

How can I do that?

A: Is this some exam test, or real world C struct?
In real world it may be padded to align it's members, so the .b may be then 4 or 8 (or more, depends on compile time setup of padding), not 2.
When doing C<->asm for real, make sure to use some "padding/packing" pragma or compile time switch to compile always to the same struct structure in C binaries (first step).
Then probably pad/align by hand, for example I would put "a" as last and "c" and "d" at the beginning. So the order in memory would be "c, d, b, a" (which I would find "enough" aligned even for 64b target in "packed" mode, the resulting offsets would be [0, 8, 16, 20] and size would be 22 bytes) (edit: and I would add another word at end just to pad it to 24B size, if I would know I will use many of them in array).
Finally what is c and d in memory -> pointers. By "nasm" word usage I sense x86 target platform, and by "uint32_t" I sense it will be not 16b real mode, so they are either 32 or 64 bits (depends on your target platform). 32 bits is 4 bytes, 64 bits is 8 bytes.

BTW, you can always write some short C source exercising access to the struct, and check the output of compiler.
For example I put this into http://godbolt.org/:
#include <cstdint>

struct struct1 {
    uint16_t a;
    uint32_t b;
    char * c;
    void * d;
};

std::size_t testFunction(struct1 *in) {
    std::size_t r = in->a;
    r += in->b;
    r += uintptr_t(in->c);
    r += uintptr_t(in->d);
    return r;
}

And got this out (clang 3.9.0 -O3 -m32 -std=c++11):
testFunction(struct1*):              # @testFunction(struct1*)
        mov     ecx, dword ptr [esp + 4]   ; ecx = "in" pointer
        movzx   eax, word ptr [ecx]        ; +0 for "a"
        add     eax, dword ptr [ecx + 4]   ; +4 for "b"
        add     eax, dword ptr [ecx + 8]   ; +8 for "c"
        add     eax, dword ptr [ecx + 12]  ; +12 for "d"
        ret     ; size of struct is 16B

And with 64b target:
testFunction(struct1*):              # @testFunction(struct1*)
        mov     rax, qword ptr [rdi]
        movzx   ecx, ax
        shr     rax, 32
        add     rax, rcx
        add     rax, qword ptr [rdi + 8]
        add     rax, qword ptr [rdi + 16]
        ret

The offsets are now 0, 4, 8 and 16, and size is 24B.
And 64b target with added "-fpack-struct=1":
testFunction(struct1*):              # @testFunction(struct1*)
        movzx   ecx, word ptr [rdi]
        mov     eax, dword ptr [rdi + 2]
        add     rax, rcx
        add     rax, qword ptr [rdi + 6]
        add     rax, qword ptr [rdi + 14]
        ret

Offsets are 0, 2, 6 and 14 and size is 22B (and performance will be hurt by unaligned access to members b, c and d).
So for example for the 0, 4, 8, 16 case (64b aligned) your NASM struct should be:
struc struct1
  .a resd 1
  .b resd 1
  .c resq 1
  .d resq 1
endstruc

From your further comments... I think you maybe sort of miss what is "struc" in assembly. It's a gimmick, it's just other way of specifying address offsets. The example above can be written also as:
struc struct1
  .a resw 1
     resw 1   ; padding to make "b" start at offset 4
  .b resd 1
  .c resq 1
  .d resq 1
endstruc

Now you have your "resw" for "a" too. It doesn't matter for the ASM, as for the code only the value of symbols .a and .b is important, and those values are 0 and 4 in both examples. It doesn't matter how you reserve the space inside the struc definition, it doesn't affect the result, as long as you specify the correct amount of bytes for particular "variable" + its padding.


text:
Q: pip install error python3 linux I'm using linux mint and can not install the pip from the downloaded script file due to zlib error.
1 ) Tried to reinstall zlib with following command and it is success.

$ sudo apt-get install --reinstall zlibc zlib1g zlib1g-dev

2) python3 is installed correctly.

$ which python3

/usr/local/bin/python3

3) Whenever I try to run get-pip.py file following errors are displayed.

$ python3 get-pip.py

Traceback (most recent call last):
  File "get-pip.py", line 20061, in <module>
    main()
  File "get-pip.py", line 194, in main
    bootstrap(tmpdir=tmpdir)
  File "get-pip.py", line 82, in bootstrap
    import pip
zipimport.ZipImportError: can't decompress data; zlib not available

How can I run the script? It has no problem when installing zlib using apt-get.

A: Maybe you need to install zlib
apt-cache search zlib
apt-get install zlib


text:
Q: Determining if this data is really in 4th normal form? I got a few - company, location and product details to store in a db.
sample data
company  location      product
------------------------------
abc      hilltop       alpha
abc      hilltop       beta
abc      riverside     alpha
abc      riverside     beta
buggy    underbridge   gama
buggy    underbridge   theta
buggy    underbridge   omega

The relationships are multi-valued, as I understand. And the data needs to be normalized as the MVD's are

*

*not derived from a candidate key (company ->> location and company ->> product where company is not a candidate key)

*or the union does not make the whole  set (company U location < R and so with product).
But my colleague disagrees with me, who insists that for a relation to have multi-valued dependency at least four same values in company column should exist for each company. i.e
t1(company) = t2(company) = t3(company) = t4(company),
for company abc this is true. But for company "buggy", which does only one product in three locations, this is untrue.

For the formal definition and similar examples I refernced:
https://en.wikipedia.org/wiki/Multivalued_dependency
 and Fourth_normal_form  example also on wiki.
I know my colleague is being pedagogy, but I too started seeing the same question after reading the formal definition. (After all these are derived on mathematical basis.)
update: I am not asking how to normalize this data in to 4NF, I think I know that. (I need to break it in to two tables 1) company - location and 2) company - product.
which I have done already.
Can some one explain how this relation is still a MVD even though it does not satisfy the formal definition?
Detailed explanations are very much welcome.

A: "There exist" says some values exist, and they don't have to be different. EXISTS followed by some name(s) says that there exist(s) some value(s) referred to by the name(s), for which a condition holds. Multiple names can refer to the same value. (FOR ALL can be expressed in terms of EXISTS.)
The notion of MVD can be applied to both variables and values. In fact the form of the linked definition is that a MVD holds in the variable sense when it holds in the value sense "in any legal relation". To know that a particular value is legal, you need business knowledge. You can then show whether that value satisfies an MVD. But to show whether its variable satisfies the MVD you have to show that the MVD is satisfied "in any legal relation" value that the variable can hold. One valid value can tell you that a MVD doesn't hold in (it and) its variable, but it can't tell you that a MVD does hold in its variable. That requires more business knowledge.
You can show that this value violates 4NF by using that definition of MVD. The definition says that a relation variable satisfies a MVD when a certain condition holds "for any valid relation" value:

for all pairs of tuples t1 & t2 in r such that t1[a] = t2[a] there exist tuples t3 & t4 [...]

For what MVD and values for t1 & t2 does your colleague claim there doesn't exist values for t3 & t4? There is no such combination of MVD and values for t1 & t2. Eg for {company} ↠ {product} and t1 & t2 both (buggy, underbridge, gamma), we can take (company, underbridge, gamma) as a value for both t3 & t4, and so on for all other choices for t1 & t2.
Another definition for F ↠ T holding is that binary JD (join dependency) *{F U T, F U (A - T)} holds, ie that the relation is equal to the join of its projections on F U T & F U (A - T). This definition might be more immediately helpful to you & your colleague in that it avoids the terminology that you & they are misinterpreting. Eg your example data is the join of these two of its projections:
company  location
--------------------
abc      hilltop
abc      riverside
buggy    underbridge

company  product
----------------
abc      alpha
abc      beta
buggy    gamma
buggy    theta
buggy    omega

So it satisfies the JD *{{company, location}, {company, product}}, so it satisfies the MVDs {company} ↠ {location} and {company} ↠ {product} (among others). (Maybe you will be able to think of examples of relations with zero, one, two, three etc tuples for which one or more (trivial and/or non-trivial) MVDs hold.)
Of course, the two definitions are two different ways of describing the same condition.
PS 1 Whenever a FD F → T holds, the MVD F ↠ T holds. For a relation in BCNF, the MVDs that violate 4NF & 5NF are those not so associated with FDs.
PS 2 A relation variable is meant to hold a tuple if and only if it makes a true statement in business terms when its values are substituted into a given statement template, or predicate. That plus the JD definition for MVD gives conditions for a relation variable satisfying a MVD in business terms. Here our predicate is of the form ...company...location...product.... (Eg company namedcompanyis located atlocationand makes productproduct.) It happens that this MVD holds for a variable when for all valid business situations, FOR ALL company, location, product,
        EXISTS product [...company...location...product...]
    AND EXISTS location [...company...location...product...]
IMPLIES ...company...location...product...


text:
Q: get data from Item renderer and use in main application in flex I haave some data in item renderer and need to use in application level.
Example:- i have a button itemRenderer in datagrid. when i click on the button i have to carry some data to dispatch event at application level. So how to get the item renderer data into the mail application. I had written a custom Event and listen the event in main application. But it does not work. Can anyone have a better idea to solve it.

A: if you want to listen a event from itemrender to outside component then event's bubble value must be true, default its value is false so you have to true after your custom variable....
this.dispatchEvent(new customEvent(CutomEventType, CustomVariable, **true)**);

Good luck!

A: You can simply access the dataGridId.selectedItem to get whatever item is selected without an event, however you won't know when it changes.  If you only need to know the value after some user action you can use the selectedItem property.  If you need to know when it changes using an event is definitely the best way to go, as JK Patel states it must be marked to bubble if you're not listening for it directly on the object that dispatches it... instead of a custom event if you dispatch the event from the renderer itself, you can use event.target.data to get a handle on the data without a custom event.


text:
Q: How are LAN routers, WAN routers and eNodeBs connected to each other (TCP/IP)? I'm new to telecommunication, and from what I understand, an user equipement is either connected to a LAN router or an eNodeB, and a LAN router is connected to a WAN router, and routers send the packets to the correct destination with a routing table. The part that I don't understand is how does all this work with IP/TCP? Let's say UE1 is a stationary device connected to a LAN router and sends a message to UE2, which is a mobile device connected to an eNodeB, how would that work? As far as I understand :

*

*UE1 sends a message to the LAN router

*the LAN router sees that the message is not intended for the local network, and sends the message to the corresponding WAN router.

*the WAN router sends that message to the corresponding eNodeB

*the eNodeB sends the message to UE2

Is this correct? Also, is I understand correctly, an eNodeB is basically a bounch of antennas with some software that can send/receive data from UEs in it's covered area, and a router does pretty much the same thing, so what are the differences between the 2 in terms of functionality (except that the eNodeB covers a wider area)?
Thanks

A: I'm neither an IP Guru, but think i have a solid understanding of it and I just started working in mobile telecommunications. So I will try to help you here.
The problem in your understanding might be the fact, that the eNodeB is not directly connected to the Internet.
You probably should follow @Bimpelrekkie advice and have a look at the OSI Model to understand how this all works together.
Directly jumping into a mixture of Ethernet and mobile communications is hard. Maybe you should have a look at the EUTRAN=LTE basics, e.g. see https://en.wikipedia.org/wiki/System_Architecture_Evolution.
You simplified the eNodeB pretty much to some antennas and software. That might be true if you simplify it really much. I'll simplify as well, maybe it helps you.
The (simplified) task of the eNodeB is to transmit Data over the Air interface while making sure that each user gets a fair share of the air interface.
What Data is transferred must be differentiated between Userplane Data (Data that is actually "useful") and Control Plane data (data that is used to control the connection).
the eNodeB (simplified) transfers the Userplane data to the Packet Gateway and from the Packet Gateway to the UE. The Packet Gateway is between the eNodeB and the Internet.
Have a look at this figure (you will understand it easier, if you have understood the OSI model):
https://www.slideshare.net/sofianonline/ip-concept-in-lte/7
(You can also search for "LTE Stack OSI model" or similar to get some other diagrams).
If you understand Ethernet or "LAN" a bit better, you should maybe compare the eNodeB to a WiFi Access Point. The WiFi Access Point does not directly "talk" IP. It gets IP packets from somewhere and is just (simplified) an Antenna which will put the IP Packet on the Air...
hope that helps


text:
Q: Autodesk forge translate object custom in forge configurator inventor I want to custom translate a model in the forge configurator inventor. This model will be a model that is created and cached after the update process. I want to translate the abc.iam file in the "cache / projectid / hash / model.zip" file and get the urn after this operation.
I couldn't find the document about translate object custom. Also, how can I do this with the model in the cache of this project?

A: This is how the content is organized - highlighted the bucket name:

You can either use the https://forge.autodesk.com/en/docs/data/v2/reference/http/buckets-:bucketKey-objects-:objectName-details-GET/ endpoint to get the ObjectId of the file or construct it yourself based on the template: urn:adsk.objects:os.object:<bucket name>/<file name URL encoded>
Note: make sure the file name is URL encoded if making the REST call directly instead of using the Forge SDK
You can see what ObjectId is provided for a given file e.g. using the Autodesk Forge Tools Extension in VS Code:

You need to base64 encode the ObjectId in order to get the urn of the file and then use that to kick off the translation: https://forge.autodesk.com/en/docs/model-derivative/v2/tutorials/translate-zip-to-stl/
In case of a zip file you also have to provide the rootFilename (it's pointed out in the sample referenced above) - in case of e.g. the Wheel assembly that's the WheelAssembly.iam file


text:
Q: Why these lines of code doesn't run as expected? I'm creating a chat application and I want to display names in Bold . When the form is first load, I display the History conversation from database on a RichTextBox control using these lines of code and i want to display the name in Bold :
Here's all the code to make this possible :
string strProvider = "Data Source=" + srv_host + ";Database=" + srv_db + ";User ID=" + srv_user + ";Password=" + srv_pass;
        MySqlConnection myConn = new MySqlConnection(strProvider);
        try
        {
            myConn.Open();
            string strCmd = "SELECT * FROM comments WHERE task_id=@task_id AND ((from_usr=@from AND to_usr=@to) OR (from_usr=@to AND to_usr=@from)) ORDER BY at_time ASC";
            MySqlCommand myCmd = new MySqlCommand(strCmd, myConn);
            myCmd.Parameters.AddWithValue("from", frm_usr);
            myCmd.Parameters.AddWithValue("to", to_usr);
            myCmd.Parameters.AddWithValue("task_id", tid);
            myCmd.ExecuteNonQuery(); // execute now

            MySqlDataReader dr = myCmd.ExecuteReader();

            while (dr.Read())
            {
                string text = dr.GetValue(1).ToString() + ": " + dr.GetValue(6) + Environment.NewLine;
                richTextBox1.AppendText(text);
                richTextBox1.SelectionStart = 0;
                richTextBox1.SelectionLength = dr.GetValue(1).ToString().Length;
                richTextBox1.SelectionFont = new Font(richTextBox1.Font,FontStyle.Bold);
            }

            myConn.Dispose();
        }

        catch (Exception E) { MessageBox.Show(E.Message); }

And these are the lines of code that doesn't work as expected :
 while (dr.Read())
            {
                string text = dr.GetValue(1).ToString() + ": " + dr.GetValue(6) + Environment.NewLine;
                richTextBox1.AppendText(text);
                richTextBox1.SelectionStart = 0;
                richTextBox1.SelectionLength = dr.GetValue(1).ToString().Length;
                richTextBox1.SelectionFont = new Font(richTextBox1.Font,FontStyle.Bold);
            }

Edit:
dr.GetValue(1).ToString() Holds tha full name of user  dr.GetValue(6).ToString() Hold the message
The problem with code above is that it displays only the first name in Bold but other lines are not affected. See the image
Could some one please tell me the reason why the code isn't working. I couldn't figure out where is the error.Thank-you

A: The problem you are having here is that richTextBox1.SelectionStart is always zero, meaning that the formatting will only ever be applied to the first line in the text box.
Try setting this to richTextBox1.SelectionStart = richTextBox1.TextLength.
Edit:
Try setting it to
richTextBox1.SelectionStart = richTextBox1.TextLength - text.Length;

Edit 2:
I think the Invalid Argument thing is caused by the use of Environment.NewLine. If I use instead "\n", the code works fine. The problem is that Environment.NewLine is of course \r\n on Windows, yet the richtextBox1 seems to be ignoring the \r. This results in richTextBox1.TextLength - text.Length being -1 in the first iteration.

A: I am unable to test but it may be because the SelectionStart index is always 0, try setting it to the start of the line you just added
        while (dr.Read())
        {
            string text = dr.GetValue(1).ToString() + ": " + dr.GetValue(6) + Environment.NewLine;
            richTextBox1.AppendText(text);
            richTextBox1.SelectionStart = richTextBox1.GetFirstCharIndexOfCurrentLine();
            richTextBox1.SelectionLength = dr.GetValue(1).ToString().Length;
            richTextBox1.SelectionFont = new Font(richTextBox1.Font,FontStyle.Bold);
        }


text:
Q: MySQL / PHP - is a PDO buffer overflow possible? I'm coding a website right now. I store the users accounts inside a MySQL table.
I use PDO to access them as it's a lot safer and takes care of any attacks.
I store usernames as a VARCHAR(24).
But here is my question: does PDO take care of overflows? For example if the user would try to set his username to a length of 25?

A: Not sure whether you did the obvious thing and just tried yourself but... No, PDO is not a complex ORM. It won't waste resources parsing SQL queries to determine what tables and columns are to be written and fetching table definitions from server to validate input data.
Depending on your MySQL configuration, your query will fail with an error or it'll proceed happily and you'll get data loss as a feature. But it'll all happen at MySQL server:
mysql> CREATE TABLE user (
    ->  user_id INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
    ->  username VARCHAR(24) NOT NULL,
    ->  PRIMARY KEY (user_id)
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> SET @@SESSION.sql_mode='';
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO user (username) VALUES ('this.is.a.very.long.username');
Query OK, 1 row affected, 1 warning (0.00 sec)

mysql> SHOW WARNINGS;
+---------+------+-----------------------------------------------+
| Level   | Code | Message                                       |
+---------+------+-----------------------------------------------+
| Warning | 1265 | Data truncated for column 'username' at row 1 |
+---------+------+-----------------------------------------------+
1 row in set (0.00 sec)

mysql> SELECT * FROM user;
+---------+--------------------------+
| user_id | username                 |
+---------+--------------------------+
|       1 | this.is.a.very.long.user |
+---------+--------------------------+
1 row in set (0.00 sec)

mysql> SET @@SESSION.sql_mode='TRADITIONAL';
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO user (username) VALUES ('this.is.also.a.very.long.username');
ERROR 1406 (22001): Data too long for column 'username' at row 1

I you are talking about what the term buffer overflow commonly refers to, both PHP and great parts of MySQL Server are written in C, which is a rather low level language that's certainly vulnerable to it. But of course both developer teams try their best to avoid it and if you face one it'll be the result of a bug, it should be reported as potential security vulnerability and it's highly unlikely to be caused by the simple case you describe.

A: PDO don't cares about length by default. If you use MySQL as database, this cell will be automatically truncated to field length;


text:
Q: Cannot read property 'requestAnimationFrame' of undefined After I've included "echarts-for-react" library to my project, I've started getting Cannot read property 'requestAnimationFrame' of undefined error.
The interesting part is that I'm only getting this error on Windows 10. When I open the project on OS X, everything works as expected. I'm using Chrome version 64.0.3282.186 on both OSs. screenshot
I'm using:
react: v15.4.1,
webpack: v1.14.0
Do you have any suggestions about this problem?

A: Some browsers don't support requestAnimationFrame.
You can use a polyfill like this here which will use a setTimeout if requestAnimationFrame is not available

A: I am the author of echarts-for-react.
Related issue, ref: Running into a '__resizeListeners__' of undefined with react and Semantic-UI accordion


text:
Q: Uncaught TypeError: Cannot read properties of undefined (reading 'toLowerCase') React - Redux i'm getting the following error while trying to search.  I'm using redux to hold my state. Everytime i navigate away from the following page and back to it i get the error.
"Uncaught TypeError: Cannot read properties of undefined (reading 'toLowerCase')"
the following is my insurance component
 import React, { Component } from 'react';
import { connect } from "react-redux";
import { fetchAllInsurances } from '../../actions/insurance.action';
import { Link } from 'react-router-dom';
import Card from '../Card';
import SearchBar from '../SearchBar';
import Header from '../Header';

export class Insurance extends Component {
  constructor(props){
    super(props);
    this.state = {sCode:null};
  }

  onSearchSubmit = (term) => {
    this.setState({sCode:term})
  }

  componentDidMount(){
      this.props.fetchAllInsurances();
  }

  render() {
    return (
      <>

            <SearchBar onSubmit={this.onSearchSubmit}/>

        {this.renderCreate()}

        {this.renderCard()}
        </>
    )
  }

  renderCreate(){
    return(
        <>
          <Link to ={'/addinsurance'} className = "ui primary button">Add Insurance</Link>
        </>
    )
  }

  renderCard(){
    return(

        {this.props.insurance.filter(((c)=>{
          if(this.state.sCode == null){
            return c;
          }
          else if(c.VendorName.toLowerCase().includes(this.state.sCode.toLowerCase().toString())){
            return c
          }
          })).map((c, i) => (
            <Card key={i} InsData={c} />
          ))}

    )
  }
}

const mapStateToProps = state =>{
  return{
    insurance:Object.values(state.insurance)
  }
}

export default connect(mapStateToProps,{fetchAllInsurances})(Insurance);

the following is my search component
    import React from 'react'

 class SearchBar extends React.Component {
    state = {term:''};

    onFormSubmit =(event) =>{
        event.preventDefault();
        //send the state data to the parent
        this.props.onSubmit(this.state.term);
    }
    render(){
        return (

                <form onSubmit = {this.onFormSubmit} action="" className="ui form">

                        Insurance Vendor Search

                            <input
                            type="text"
                            value={this.state.term}
                            onChange={e=> this.setState({term:e.target.value})}
                            placeholder='Enter the insurance vendor to search...'/>

                </form>

        )
    }
}
export default SearchBar;

A: As the error state, the variable is undefined. You will need to test the variable first.
So either use
c.VendorName?.toLowerCase()

or
if (c.VendorName) {
    c.VendorName.toLowerCase()........
}


text:
Q: Merge node in activity diagram I'm learning Activity diagram in UML and now I'm confused with the following diagram for representing procedures when calling a pizza.
I think a merge node should be added before the join node because if not, the join node will wait forever. Is that correct?
Thank you.

A: I think you are right.
There should be a merge node merging the two flows coming from the decision right after Ask for toppings and a merge node to merge the two flows that have been split by the decision right after Deliver Pizza
A join node will only continue if it gets a token from all incoming flows, which will never happen if those flows are mutually exclusive because of a decision earlier on.


text:
Q: SQL query, how to do the sum() on some field, but fall back to 'NA' if one of them the values in sum() is null We use mysql. At certain place in the SQL query, I have to calculate a field as sum of other values but at the same time, to take into account that if one of these values that are being summed up has a value null, the calculated value is not the sum() but null as well.
(for the sake of simplicity of the question I say that the fallback condition value is null, but in any case, some fix value).
How to integrate additional fallback conditions into sum() function in mysql? Example of data is:
id  value  some_fk
1   1      AL
2   3      AL
3   jak    AL
4   7      AL
5   6      AL

if I sum them up, like this:
select sum(value) from tmp;

, I want to be returned value 'not summable', since there is a value 'jak' in one of the rows, which is not summable with the others.

A: Are you looking for IFNULL()?
Sample data
CREATE TABLE SAMPLE(ID INT, SAL INT);
INSERT INTO SAMPLE VALUES(1,1000);
INSERT INTO SAMPLE VALUES(1,2000);
INSERT INTO SAMPLE VALUES(2,'3000');
INSERT INTO SAMPLE VALUES(2,'1000');
INSERT INTO SAMPLE VALUES(3,NULL);
---------NEW SAMPLE BASED ON COMMENT---------
INSERT INTO SAMPLE VALUES(3,NULL);
INSERT INTO SAMPLE VALUES(3,'MYTEXT');
INSERT INTO SAMPLE VALUES(3,500);
INSERT INTO SAMPLE VALUES(4,'MYTEXT2');
INSERT INTO SAMPLE VALUES(4,'MYTEXT3');
INSERT INTO SAMPLE VALUES(4,10.2);
INSERT INTO SAMPLE VALUES(5,NULL);
INSERT INTO SAMPLE VALUES(5,NULL);

If I understood correctly, for the above data you are expecting the result as shown below.
+----+------------+
| ID | SUM_RESULT |
+----+------------+
| 1  | 3000       |
+----+------------+
| 2  | 4000       |
+----+------------+
| 3  | N/A        |
+----+------------+

In that case, you can use
SELECT ID,
       IFNULL(SUM(SAL),'N/A') AS SUM_RESULT
FROM SAMPLE GROUP BY ID

CHECK DEMO HERE
UPDATE BASED ON COMMENT:
You can use the below query if you want to display your error message if a group contains some text.
select ID,
       CASE WHEN
            MAX(CASE WHEN SAL REGEXP ('^[0-9]+$') THEN SAL ELSE 'N/A' END) !='N/A'
            THEN
                SUM(SAL)
       ELSE 'NOT SUMMABLE' END AS MYRESULT
FROM SAMPLE
GROUP BY ID

OUTPUT
+----+--------------+
| ID |   MYRESULT   |
+----+--------------+
|  1 | 3000         |
|  2 | 4200         |
|  3 | NOT SUMMABLE |
|  4 | NOT SUMMABLE |
|  5 | NOT SUMMABLE |
+----+--------------+

CHECK DEMO HERE

A: You can do it with this CASE expression:
select
  case
    when exists (
      select 1 from tmp
      where value is null or concat(value + 0) <> value
    ) then null
    else (select sum(value) from tmp)
  end result

EXISTS checks for invalid integer values and nulls and returns null if it finds any.
The ELSE part safely returns the sum.
See a simplified demo.


text:
Q: Error: StaticInjectorError(AppModule)[SomeComponent -> Renderer2] when creating an Angular service with Renderer2 I am trying to create a service to inject a <script></script> in my DOM, instead of doing this via my Component.
My implementation of Renderer2 works perfectly when using it in a Component, but when using Rendere2 via a service I get this error:

core.js:15724 ERROR Error: Uncaught (in promise): Error:
  StaticInjectorError(AppModule)[ContactUsPageComponent -> Renderer2]:
  StaticInjectorError(Platform: core)[ContactUsPageComponent ->
  Renderer2]:
      NullInjectorError: No provider for Renderer2! Error: StaticInjectorError(AppModule)[ContactUsPageComponent -> Renderer2]:
  StaticInjectorError(Platform: core)[ContactUsPageComponent ->
  Renderer2]:

I have tried importing Renderer2 in my AppModule, but get this notification:

(alias) class Renderer2 import Renderer2 Extend this base class to
  implement custom rendering. By default, Angular renders a template
  into DOM. You can use custom rendering to intercept rendering calls,
  or to render to something other than DOM.
Create your custom renderer using RendererFactory2.
Use a custom renderer to bypass Angular's templating and make custom
  UI changes that can't be expressed declaratively. For example if you
  need to set a property or an attribute whose name is not statically
  known, use the setProperty() or setAttribute() method.

This is my service implementation:
import { Injectable, Renderer2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

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

  constructor(private renderer2: Renderer2, @Inject(DOCUMENT) private document) {}

  showChatbot() {
    const s = this.renderer2.createElement('script');
    s.type = 'text/javascript';
    s.id = 'ze-snippet';
    s.src = 'https://static.zdassets.com/ekr/snippet.js?key=7e...';
    s.text = ``;
    this.renderer2.appendChild(this.document.body, s);
  }
}

And I simply call it from a component using: this.chatbotService.showChatbot();
Any suggestions o how to implement this correctly would be greatly appreciated!

A: Here is the answer to my question:
NOTE: to use Renderer2 in a service, you need to create an instance of Renderer2, using RendererFactory2. From there it is straight forward.
Here is my Service code:
import { Injectable, Renderer2, RendererFactory2, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';

@Injectable({
  providedIn: 'root'
})
export class ChatbotService {
  private renderer: Renderer2;

  constructor(private rendererFactory: RendererFactory2, @Inject(DOCUMENT) private document) {
    this.renderer = rendererFactory.createRenderer(null, null);
  }

  showChatbot() {
    const s = this.renderer.createElement('script');
    s.type = 'text/javascript';
    s.id = 'ze-snippet';
    s.src = 'https://static.zdassets.com/ekr/snippet.js?key=7e...';
    s.text = ``;
    this.renderer.appendChild(this.document.body, s);
  }
}

Here is my Component call: this.chatbotService.showChatbot();
Hope this helps someone else!


text:
Q: Операция со строками, поиск слов с окончанием на определённую букву python Сам не так давно начал питон, немного не понимаю почему он не ищет мне слова и вообще ничего не выводит.
Задание такое: Дан набор слов, разделенных точкой с запятой (;). Набор заканчивается двоеточием (:). Определить, сколько в нем слов, заканчивающихся буквой а.
Мой код, помогите доделать до конца)
string = "Добро;Зло;Земля;Игра;Машина:"
i = 0
k = 0
while i == 1:
    len(string) - 1
    if string[i]== "а" and string[i+1] == ";" or string[i+1] == ":":
        k=k+1
        print(k)

Вроде уже лучше стало, но результат не совсем правильный вроде
string = "Добро;Зло;Земля;Игра;Машина;Куша:"
i = 0
k = 0
for i in range(len(string)-1):
    if string[i] == "а" and string[i+1] == ";" or string[i+1] == ":":
        k = k+1

print(k)

A: string = "Добро;Зло;Земля;Игра;Машина:"
words = []
i = 0 #счётчик для обхода входной строки
while i < len(string) and string[i] != ":": #проходим, пока не дойдём до знака конца
    word = "" #временная переменная для заполнения слова
    while i < len(string) and string[i] != ";" and string[i] != ":": #заполняем слово, пока не встретим знак конца слова (или всего ввода)
        word += string[i]
        i =  i + 1
    words.append(word) #когда встретим знак конца слова, выйдем из цикла и занесём завершённое слово в массив
    i = i + 1 #игнорируем ";"
k = 0
for word in words:
    if word[len(word)-1] == 'а':
        k = k + 1
print(k)

Проверка на len(string), чтобы не вылететь за пределы массива. Возможно есть решение элегантнее, но на больную голову ничего лучше не придумывается

A: Можно использовать регулярное выражение:
string = "Добро;Зло;Земля;Игра;Машина:"
print(len(re.findall(r'а;|а:', string)))
>>2

Здесь мы ищем все вхождения символа "а" с точкой с запятой или двоеточием.

A: string = "Добро;Зло;Земля;Игра;Машина:"

len([ i for i in string[:-1].split(";") if i[-1]=='а'])
2

A: string = "Добро;Зло;Земля;Игра;Машина:"
print(string.count('а;') + string.count('а:'))
>>2


text:
Q: Problems with ts header I write this question to see if anyone might know what happens to this piece of code. Wrote the following lines with the intention of removing the header bits of a TS packet, but I have several problems with the code.
This is the code:
static GstPadProbeReturn TS_Packet (GstPad *padd, GstPadProbeInfo *info, gpointer user_data)
{
       guint8 *byte;
       gchar *paquete;
       gsize   count_print=0;

       GstBitReader *bytes_cabecera;

       GstMapInfo map;
       GstBuffer *buffer;

       if (GST_EVENT_TYPE (GST_PAD_PROBE_INFO_DATA (info)) != GST_EVENT_EOS){

          buffer = GST_PAD_PROBE_INFO_BUFFER (info);
          buffer = gst_buffer_make_writable (buffer);

          gst_buffer_map (buffer, &map, GST_MAP_WRITE);
          byte=(guint8 *)map.data;

          while(count_print<map.size){

              g_print("\n");
              g_print("-Paquete numero del paquete: %d-\n",i);
              i=i+1;

              for(n=0; n<8 ;n++){
                  paquete[n]=byte[n+count_print];
                  g_print(" %02x ",byte[count_print+n]);
              }/*for*/
              g_print("\n");

              bytes_cabecera=gst_bit_reader_new(paquete, map.size);
              g_print("       ->stream header (32bits)-\n");
              guint8 sync = gst_bit_reader_get_bits_uint8_unchecked(bytes_cabecera,8);

              if(sync==71){
                  g_print("         Sync_byte: %02x (available) \n",sync);
              }else{
                  g_print("         Sync_byte: %02x (no available) \n",sync);
              }/*else*/

              guint8 transport_error_indicator = gst_bit_reader_get_bits_uint8_unchecked(bytes_cabecera,1);
              if(transport_error_indicator==0){
                  g_print("         Transport_error_indicator: %d (No_error)\n", transport_error_indicator);
              }else if (transport_error_indicator==1){
                  g_print("         Transport_error_indicator: %d (Error)\n", transport_error_indicator);
              }/*cierro casos de error*/

              guint8 Payload_start_indicator = gst_bit_reader_get_bits_uint8_unchecked(bytes_cabecera,1);

              if(Payload_start_indicator==0){
                  g_print("         Payload_start_indicator: %d (No_Star_indicator_avalible)\n", Payload_start_indicator);
              }else if (Payload_start_indicator==1){
                  g_print("         Payload_start_indicator: %d (Start_indicator_avalible)\n", Payload_start_indicator);
              }/*cierro casos de payload start indicator*/

              guint8 transport_priority = gst_bit_reader_get_bits_uint8_unchecked(bytes_cabecera,1);

              if(transport_priority==0){
                  g_print("         Transport_priority: %d (No_Priority_avalibe)\n", transport_priority);
              }else if (transport_priority==1){
                  g_print("         Transport_priority: %d (Priority_avalible)\n", transport_priority);
              }/*cierro casos de Priority*/

              guint16 pid_ts= gst_bit_reader_get_bits_uint16_unchecked(bytes_cabecera,13);
              g_print("         PID: %02d \n",pid_ts);

              guint8 scramblin_control= gst_bit_reader_get_bits_uint8_unchecked(bytes_cabecera,2);

              if(scramblin_control==0){
                g_print("         Scrambling control: %d (Not scrambled)\n", scramblin_control);
              }else if (scramblin_control==1){
                g_print("         Scrambling control: %d ( Reserved for future use)\n", scramblin_control);
              }else if (scramblin_control==2){
                g_print("         Scrambling control: %d (Scrambled with even key)\n", scramblin_control);
              }else if (scramblin_control==3){
                g_print("         Scrambling control: %d (Scrambled with odd key)\n", scramblin_control);
              }/*cierro el if del scramblin*/

               guint8 Adaptation_field_exist= gst_bit_reader_get_bits_uint8_unchecked(bytes_cabecera,1);

               if(Adaptation_field_exist==0){
                 g_print("         Adaptation field_exist: %d (No exist)\n", Adaptation_field_exist);
               }else if (Adaptation_field_exist==1){
                 g_print("         Adaptation field_exist: %d (Exist)\n", Adaptation_field_exist);
               }/*cAdaptation field*/

               guint8 Contains_payload= gst_bit_reader_get_bits_uint8_unchecked(bytes_cabecera,1);

               if(Contains_payload==0){
                 g_print("         Contains payload: %d (No exist)\n", Contains_payload);
               }else if (Contains_payload==1){
                 g_print("         Contains payload: %d (Exist)\n", Contains_payload);
               }/*cAdaptation field*/

              guint8 Continuity_counter= gst_bit_reader_get_bits_uint8_unchecked(bytes_cabecera,4);
              g_print("         Continuity counter: %d \n",Continuity_counter);

              if(Adaptation_field_exist==1){
                  g_print("          ->Adaptation Field-\n");

                  guint8 Adaptation_field_lenght= gst_bit_reader_get_bits_uint8_unchecked(bytes_cabecera,8);
                  g_print("            Adaptation field lenght: %d \n",Adaptation_field_lenght);

                  guint8 Discontinuity_indicator= gst_bit_reader_get_bits_uint8_unchecked(bytes_cabecera,1);
                  g_print("            Discontinuity indicator: %d \n",Discontinuity_indicator);

                  guint8 Random_acces= gst_bit_reader_get_bits_uint8_unchecked(bytes_cabecera,1);
                  g_print("            Random Access indicator: %d \n",Random_acces);

                  guint8 Stream_priority= gst_bit_reader_get_bits_uint8_unchecked(bytes_cabecera,1);
                  g_print("            ES_priority indicator: %d \n",Stream_priority);

                  guint8 PCR_Flag= gst_bit_reader_get_bits_uint8_unchecked(bytes_cabecera,1);
                  g_print("            Flag PCR: %d \n",PCR_Flag);

                  guint8 OPCR_Flag= gst_bit_reader_get_bits_uint8_unchecked(bytes_cabecera,1);
                  g_print("            Flag OPCR: %d \n",OPCR_Flag);

                  //guint8 Splicing_point_flag= gst_bit_reader_get_bits_uint8_unchecked(bytes_cabecera,1);
                  //g_print("          Flag Splicing point: %d \n",Splicing_point_flag);

                  //guint8 Transport_private_data_flag= gst_bit_reader_get_bits_uint8_unchecked(bytes_cabecera,1);
                  //g_print("          Flag Transport private data point: %d \n",Transport_private_data_flag);

                  //guint8 Adaptation_field_extension_flag= gst_bit_reader_get_bits_uint8_unchecked(bytes_cabecera,1);
                  //g_print("          Adaptation field extension flag: %d \n",Adaptation_field_extension_flag);

              }/*cierro el caso para mi adaptation field*/

              g_print("\n");

              count_print=count_print+188;

          }/*cierro el while*/

          gst_buffer_unmap (buffer, &map);

       }/*general*/

       return GST_PAD_PROBE_OK;

 }/*pad probe*/

problems and doubts:
1) when I add in more element of analysis "Splicing Point Flag" eclipse does not execute the code, somo shows the line g: print, and complete.
2) whether the conditional if (n, n <8; n ++) give it a value greater than 8 only shows a limited number of packages of a ts file, not all.
Does anyone know why these problems, or another way to do the same thing differently?

A: OK, I feel very foolish. I found the problem. The problem is to define the variable as a package the definitive gchar when having to work should be defined as guint8 and with a certain size. If we create a pipeline with ts demux, we can put this line of code to visualize and study the bits that make up the TS header.
with this modification, I can now resize one of 8 188 and see all items.


text:
Q: how to fire menu item click event in ATL OR WTL? Currently i am using the ON_WM_SELECT messgae
but it will fire on mouse hover over the menu.

A: Instead of the ON_WM_SELECT i used the  COMMAND_RANGE_HANDLER(0, 10000, OnClickCopyItem)
to get the click event for the each menu item
COMMAND_RANGE_HANDLER( idFirst, idLast, func )


text:
Q: Can i use group_concat () for for images? Can I use group_concat() function to retrieve image from the database?
Using it the images are displayed as broken because maybe it's not reading image name properly?
$sql="SELECT product.*, group_concat(images.image) as imag FROM product LEFT JOIN images on product.id=images.pid group by product.id";

the loop for displaying image:
foreach(explode('.',$row['imag']) as $url)
 {?>

   <?php  $imageURL = 'pictures/'.$url;?>
   <img src="<?php echo $imageURL; ?>" alt="" width="100" height="100" />

   <?php
}

This is what I'm getting as output:


text:
Q: Selenium IDE scripts stopped working - failing to find element with ID I have been using Selenium IDE (with Chrome and Firefox) with no issue until yesterday. All of a sudden, all of the scripts I have with a particular web site - 22 tests in all - are failing. They are failing on the same thing, and in both Chrome and Firefox. They are failing to match an element by its id.
So, let me just say this is not an obscure id, nor one that changes. The id is username. It is present on the page, but Selenium fails to find it.
Even weirder, if I set it to Record, the new command that I record uses the exact same id (target: id=username). When I try playback again ... NOPE. Element doesn't exist. It definitely does, numb-nuts, you literally just found it on the page seconds ago!
Any explanation as to what the heck is going on here?


text:
Q: C and C++ compiler give different messages for the following code, why? I was asked to give the output of the following code in an interview.
int a[] = {1,2,3,4,5};
int *p = &a + 1;
printf("%d, %d", *(a+1), *(p - 1));

I said I could not determine the result of the second one, so I failed the interview.
When I got back to home, and tried to compile the code, g++ will report an error, but gcc will only give a warning. The result printed is '2,5'.
Anyone knows why the C and C++ compiler behave differently on this?

A: Well, a is array of 5 ints, so &a is a pointer to array of 5 ints. in C++, you can't assign that address in a int* without cast it. gcc (in C language) gives only warning, but I think that is not valid C.
For the code:
&a+1 is the next array after a, meaning, the address of the 6th element in a, so p-1 is the address of the 5th element of a.
(I'm not sure if &a+1 is legal. it's the address of the element that is after the array, which is usually legal, but since &a is not an array, it may be illegal.)

A: int a[] = {1,2,3,4,5};
int *p = &a + 1;

This is invalid C code.
The expression &a + 1 is of type int (*)[5]. You cannot assign an expression of type int (*)[5] to an int *.
Except with the generic object pointer type void *, there is no implicit conversion between object pointers. A cast is required to initialize p with &a + 1 value.
Where does C says this declaration is invalid?
int *p = &a + 1;

in the constraints of the assignment operator:

(C99, 6.5.16.1p1) "both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right"

And an int and an array type are not compatible types (see 6.2.7p1 for more on type compatibility).
well also, it is an initialization not an assignment, but the same constraint applies:

(C99, 6.7.8p11) "The initializer for a scalar shall be a single expression, optionally enclosed in braces. The initial value of the object is that of the expression (after conversion); the same type constraints and conversions as for simple assignment apply, taking the type of the scalar to be the unqualified version of its declared type."

A: a is an array of integers, which converts to a pointer to the first element when needed. a+1 invokes that conversion, and gives a pointer to the second element.
&a is a pointer to the array itself, not to the first element of it, so &a + 1 points beyond the end of the array (to the point where the second array would be, if it were a 2-dimensional array).
The code then converts that pointer (of type int (*)[5]) to a pointer to an integer (type int*). C++ doesn't allow such a conversion without an explicit reinterpret_cast, while C is more lenient in the pointer conversions it allows.
Finally (assuming that p and p2 are supposed to be the same thing), p - 1 points to the last element of a.

A: The C++ compiler gave an error because &a evaluates to int(*)[5], which is a pointer to 5 integers, and you're attempting to assign it to an int*.
If you did fix the type, this code would print the second item in the array, followed by the address of the array.
My guess is that C decays the array into a pointer, resulting in &a evaluating to int**, and allows that to be assigned to int*. However, I don't do much C, so someone else may know better.


text:
Q: LinearLayout space between 2 buttons this is my linearLayout:
<LinearLayout
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="ANNULLA"
        android:id="@+id/button4"
        android:layout_gravity="bottom"
        android:textColor="#FFF"
        android:background="#87a914"
        android:textStyle="bold"
        android:textSize="20dp"
        android:layout_marginBottom="2dp"
        android:layout_marginLeft="3dp" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="SALVA"
        android:id="@+id/button5"
        android:layout_gravity="bottom"
        android:textColor="#FFF"
        android:background="#87a914"
        android:textStyle="bold"
        android:textSize="20dp"
        android:layout_marginBottom="2dp"
        android:layout_marginRight="3dp" />
</LinearLayout>

and this the result:

I would like to have a space between the button "SALVA" and the button "ANNULLA"
i mean something like that:

A: just add this attribute in the second button
android:layout_marginLeft="xdp"

A: One way is to add an empty View in between them with a suitable weight
<View
    android:layout_width="0dp"
    android:layout_height-"wrap_content"
    android:layout_weight=".2"/>  // change this to what works for you

your width for the Buttons should be "0dp" when using layout_weight

A: My favourite way is to add invisible view between buttons, something like this:
<View
    android:layout_width="5dp"
    android:layout_height="wrap_content"
    android:visibility="invisible" />


text:
Q: Does UIImage's imageNamed still cause memory issues on iOS4 for large images? I found a couple of Memory Management articles that mentioned UIImage's imageNamed causing problems when you have a lot of large images in memory.
http://akosma.com/2009/01/28/10-iphone-memory-management-tips/
http://www.alexcurylo.com/blog/2009/01/13/imagenamed-is-evil/
Both of these were written for OS version <= 3.0.
Does anyone know if these are still a problem in iOS 4?

A: No longer a problem, see here, and maybe here.

A: If you look at this link: Dispelling the UIImage imageNamed: FUD you'll see there are really two problems with large images and imageNamed:

*

*Prior to iOS 3.0 was a bug in the caching routines of imageNamed: such that it would not let go of its cache even when it received a mem warning.  This was a pretty major issue and was the source of a lot of memory crashes for me personally, as there's no way you could get memory back after using imageNamed: to load it.  This is NOT an issue anymore, as this seems to have been fixed in 3.0.

*imageNamed: keeps, in its cache, the uncompressed image data itself.  For really large (in terms of their size on screen - width x height) images, this data can be really large.  width * height * 4 is what I've commonly seen cited for its uncompressed size.  This would still potentially be a problem for you if you are using rather large images - and is especially to be avoided if you don't need to redraw them often.

So to recap:  1 is no longer a problem, 2 might be.

A: it does.
In combination with UIPageViewController, definitely it does.
trying to build a kids application displaying animal's sound and cartoon keyFrame animation
all individual animal details are in their own UIViewController
All views are displayed in UIPageViewController (Transition:scroll).
Didn't know about imageNamed bug and for nearly a month , thought it was a problem caused by UIPageViewController. Memory was never being released by ARC.
ASA i switched to imageWithContentsOfFile instead of imageNamed, all problems solved.
UIPageViewController was innocent in real. It works smooth now. No unreleased memory problem.


text:
Q: ERROR: operator does not exist: timestamp without time zone >= boolean Hint: No operator matches the given name and argument type(s) Am trying to execute a Named Query using JPA. Query has to search and pull the records based on criteria of the query. Criteria is query should pull the records between specific given times(Records between From and To Dates provided) and name of the Application.
Query works fine, when executed in Postgresql. But, through JPA it gives error while executing the query
Here is my Query in PostgreSQL :
SELECT  auditLog.busn_sys_id
        , sourceSystem.busn_sys_full_nm
        , auditLog.purge_ts
        , auditLog.rec_purge_cnt

FROM    rec_ret.rec_rtn_purge_adt                   auditLog
LEFT    JOIN    gbl_dm.gbl_busn_sys_dm              sourceSystem            on (auditLog.busn_sys_id = sourceSystem.busn_sys_id)

    WHERE   (auditLog.purge_ts BETWEEN '2019-08-19' AND '2019-08-25')
      and  sourceSystem.busn_sys_full_nm like 'PROFILE'

    order by auditLog.busn_sys_id ;

Here is my JPA implementation to get Results List
try{

            Query query = entityManager.createNativeQuery("SELECT auditLog.busn_sys_id, sourceSystem.busn_sys_full_nm, auditLog.purge_ts, auditLog.rec_purge_cnt " +
                    "FROM rec_ret.rec_rtn_purge_adt auditLog " +
                    "LEFT JOIN gbl_dm.gbl_busn_sys_dm sourceSystem on (auditLog.busn_sys_id = sourceSystem.busn_sys_id) " +
                    "WHERE (auditLog.purge_ts BETWEEN auditLog.purge_ts = :requestedFrom AND auditLog.purge_ts = :requestedTo) " +
                    //"WHERE (auditLog.purge_ts BETWEEN requestedFrom = (?) AND requestedTo = (?)) " +
                    "and  sourceSystem.busn_sys_full_nm = :sourceSystem " +
                    "order by auditLog.busn_sys_id ");

            query.setParameter("requestedFrom",auditLogCriteria.getFromDate());
            query.setParameter("requestedTo",auditLogCriteria.getToDate());
            query.setParameter("sourceSystem",auditLogCriteria.getSourceSystem());;

            query.executeUpdate();
            return query.getResultList();

        }catch (Exception e){
            logger.error("Fetching of logs failed with message : " + e.getMessage());
            throw e;
        }

Here is my implementation of Entity/Model class code
@NotNull (message = "Name of the Source System should be entered")
    private String sourceSystem;

    @NotNull (message = "Specify FromDate to filter records")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss[.SSS]")
    @Convert(converter = LocalDateTimeConverter.class)
    private LocalDateTime fromDate;

    @NotNull (message = "Specify ToDate to filter records")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern="yyyy-MM-dd HH:mm:ss[.SSS]")
    @Convert(converter = LocalDateTimeConverter.class)
    private LocalDateTime toDate;
\\ Getters and Setters

Here is the Error :
Hibernate: SELECT auditLog.busn_sys_id, sourceSystem.busn_sys_full_nm, auditLog.purge_ts, auditLog.rec_purge_cnt FROM rec_ret.rec_rtn_purge_adt auditLog LEFT JOIN gbl_dm.gbl_busn_sys_dm sourceSystem on (auditLog.busn_sys_id = sourceSystem.busn_sys_id) WHERE (auditLog.purge_ts BETWEEN auditLog.purge_ts = ? AND auditLog.purge_ts = ?) and  sourceSystem.busn_sys_full_nm = ? order by auditLog.busn_sys_id

[ERROR] 2019-08-29 10:02:00.558 [http-nio-8080-exec-2] SqlExceptionHelper - ERROR: operator does not exist: timestamp without time zone >= boolean
  Hint: No operator matches the given name and argument type(s). You might need to add explicit type casts.
  Position: 267
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not execute statement
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:181)
    at org.hibernate.query.internal.AbstractProducedQuery.executeUpdate(AbstractProducedQuery.java:1593)

So, result should be all the records matching with the criteria has to be returned as a response to JSON request

A: This part of your JPA query looks wrong:
BETWEEN auditLog.purge_ts = :requestedFrom AND auditLog.purge_ts = :requestedTo

I think it should be:
BETWEEN :requestedFrom AND :requestedTo


text:
Q: MongoDB how to edit/update an array inside a document object via key/index/value? Lets say we have a document in MongoDB contains an array ob objects like this:
addresses: [
    {
      city: "Tel Aviv",
      street: "Alenby",
      streetNumber: 50
    },
    {
      city: "Jerusalem",
      street: "King David",
      streetNumber: 10
    },
    {
      city: "Beer Sheva",
      street: "King Shlomo",
      streetNumber: 20
    }
  ]

THE QUESTION SLICED FOR SINGLE UNDER PIECES

*

*We want to update the second address of this client, from King David 10 to King Shaul 35.
How can we do that?

*We want to remove only the second address by index or key or matched key+value.

*We want to push another address between first to second, so first will remain first, a new address will be injected, and all of the next will be auto indexed by next.
Note: I am asking how do I do that using MongoDB query language, aka NoSQL.
If you also have a solution for doing it using AngularJS it will be welcome, but please place it after the first solution for Mongo query language (MQL).
Thanks!

A: Creating collection in order to demonstrate
> db.so.find().pretty()
{
    "_id" : ObjectId("5a0413ad008e3cd140e59af7"),
    "addresses" : [
        {
            "city" : "Tel Aviv",
            "street" : "Alenby",
            "streetNumber" : 50
        },
        {
            "city" : "Jerusalem",
            "street" : "King David",
            "streetNumber" : 10
        },
        {
            "city" : "Beer Sheva",
            "street" : "King Shlomo",
            "streetNumber" : 20
        }
    ]
}

Update a single field of a document stored in an array in MongoDB.
> db.so.update({ "addresses.street": "King David" }, { $set: { "addresses.$.street" : "King Shaul" }});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.so.find().pretty()
{
    "_id" : ObjectId("5a0413ad008e3cd140e59af7"),
    "addresses" : [
        {
            "city" : "Tel Aviv",
            "street" : "Alenby",
            "streetNumber" : 50
        },
        {
            "city" : "Jerusalem",
            "street" : "King Shaul",
            "streetNumber" : 10
        },
        {
            "city" : "Beer Sheva",
            "street" : "King Shlomo",
            "streetNumber" : 20
        }
    ]
}

Remove a document from an array in MongoDB.
> db.so.update({}, { $pull: { "addresses" : { "street": "King Shaul"} }});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.so.find().pretty()
{
    "_id" : ObjectId("5a0413ad008e3cd140e59af7"),
    "addresses" : [
        {
            "city" : "Tel Aviv",
            "street" : "Alenby",
            "streetNumber" : 50
        },
        {
            "city" : "Beer Sheva",
            "street" : "King Shlomo",
            "streetNumber" : 20
        }
    ]
}

Add a document to a specific index in an array in MongoDB.
> db.so.update({"_id" : ObjectId("5a0413ad008e3cd140e59af7")}, {$push: {"addresses": {$each: [{"city": "New York", "street": "Jones"}], $position: 1}}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.so.find().pretty()
{
    "_id" : ObjectId("5a0413ad008e3cd140e59af7"),
    "addresses" : [
        {
            "city" : "Tel Aviv",
            "street" : "Alenby",
            "streetNumber" : 50
        },
        {
            "city" : "New York",
            "street" : "Jones"
        },
        {
            "city" : "Beer Sheva",
            "street" : "King Shlomo",
            "streetNumber" : 20
        }
    ]
}


text:
Q: ImportError: cannot import name 'speech_v1p1beta1' i`m trying to run the following script in python which converts video file into text:
from google.cloud import speech_v1p1beta1 as speech
client = speech.SpeechClient()

with open(speech_file, 'rb') as audio_file:
    content = audio_file.read()

audio = speech.types.RecognitionAudio(content=content)

config = speech.types.RecognitionConfig(
    encoding=speech.enums.RecognitionConfig.AudioEncoding.LINEAR16,
    sample_rate_hertz=16000,
    language_code='en-US',
    model='video')

response = client.recognize(config, audio)

for i, result in enumerate(response.results):
    alternative = result.alternatives[0]
    print('-' * 20)
    print('First alternative of result {}'.format(i))
    print(u'Transcript: {}'.format(alternative.transcript))

when i run this script i get the following error:

ImportError: cannot import name 'speech_v1p1beta1'

Any suggestions on how to fix this?

A: Try running
$ pip install --upgrade google-cloud-speechto update your dependency.


text:
Q: Inner product space proof of equality $\|a-c\|=\|a-b\|+\|c-b\|$ is anybody out there who can help with this little problem? I know the definition of inner product space, but I don't know how to do the proof of the exercise below.
Let $a,b,c$ be elements of an inner product space. Show that the following equality
$$
\|a-c\|=\|a-b\|+\|c-b\|
$$ holds iff there exists a real number $\mu\in[0,1]$ s.t. $b=\mu a+(1-\mu)c$.
Can you give an example that shows that this is not true in an arbitrary normed space?

A: If $b=\mu a+(1-\mu)c$ and $\mu\in[0,1],$ then
$$
\|a-b\|+\|c-b\| \\
= \|a-\mu a-(1-\mu)c\|+\|c-\mu a-(1-\mu)c\| \\
= \|(1-\mu)(a-c)\|+\|(-\mu)(a-c)\| \\
= (1-\mu)\,\|a-c\| + \mu\,\|a-c\| \\
= \|a-c\|
$$
If $\|a-c\|=\|a-b\|+\|c-b\|$ and the norm is derived from an inner product, we get the following:
\begin{eqnarray}
\|a-c\| & = & \|a-b\|+\|c-b\| \\
\|a-c\|^2 & = & \|a-b\|^2+\|c-b\|^2 \\
& & +2\cdot\|a-b\|\cdot\|c-b\| \\
\langle a-c,a-c\rangle & = & \langle a-b,a-b\rangle+\langle c-b,c-b\rangle \\
& & +2\cdot\|a-b\|\cdot\|c-b\| \\
\langle a,a\rangle-\langle c,a\rangle-\langle a,c\rangle+\langle c,c\rangle
 & = &
\langle a,a\rangle-\langle b,a\rangle-\langle a,b\rangle+\langle b,b\rangle \\
& & +\langle c,c\rangle-\langle b,c\rangle-\langle c,b\rangle+\langle b,b\rangle \\
& &
 +2\cdot\|a-b\|\cdot\|c-b\| \\
-\langle c,a\rangle+\langle b,a\rangle+\langle c,b\rangle-\langle b,b\rangle
 &  &  \\
-\langle a,c\rangle+\langle a,b\rangle+\langle b,c\rangle-\langle b,b\rangle
& = & 2\cdot\|a-b\|\cdot\|c-b\| \\
\langle c-b ,b-a\rangle
+\langle b-a,c-b\rangle
& = & 2\cdot\|a-b\|\cdot\|c-b\| \\
2\operatorname{Re}\; \langle c-b ,b-a \rangle
& = & 2\cdot\|a-b\|\cdot\|c-b\| \\
\operatorname{Re}\; \langle c-b ,b-a \rangle
& = & \|c-b\|\cdot\|b-a\| \\
\end{eqnarray}
From $\operatorname{Re}(z)\leq |z|$ and from the Cauchy-Schwarz inequality
we conclude
$$
\operatorname{Re}\; \langle c-b ,b-a \rangle
\leq |\,\langle c-b ,b-a \rangle\,|
\leq \|c-b\|\cdot\|b-a\|
$$
As we have shown $\operatorname{Re}\; \langle c-b ,b-a \rangle=\|c-b\|\cdot\|b-a\|$, this means
$$
 |\,\langle c-b ,b-a \rangle\,|
= \|c-b\|\cdot\|b-a\|
$$
The Cauchy-Schwarz inequality tells us that this is a sufficient condition for $c-b$ and $b-a$ being linearly dependent, i.e. there are numbers $\lambda_1$ and $\lambda_2$ with $(\lambda_1,\lambda_2)\neq(0,0)$ such that $\lambda_1(c-b) + \lambda_2 (b-a) =0.$
In the following, we only consider the non-degenerate case $a\neq c.$ Then $\lambda_1\neq \lambda_2$. (If we had $\lambda_1=\lambda_2$, then $\lambda_1(c-b) + \lambda_2 (b-a) =0$ would imply $a=c$.)
From $\lambda_1(c-b) + \lambda_2 (b-a) =0$ we get
$$
b=\frac{\lambda_2}{\lambda_2-\lambda_1}\cdot a
+\frac{-\lambda_1}{\lambda_2-\lambda_1}\cdot c
$$
Now we can set $\mu = \frac{\lambda_2}{\lambda_2-\lambda_1}$ and we have
$$
b=\mu a
+(1-\mu) c
$$
In order to show that this $\mu$ must be in $[0,1],$ we can put the $b$ into $\|a-c\|=\|a-b\|+\|c-b\|$, like in the first part of the proof, and we get
$$
\|a-c\|=\left(|1-\mu| +|\mu|\right)\cdot \|a-c\|
$$
which means
$$
|1-\mu| +|\mu| = 1
$$
In other words, the sum of the distances of the complex number $\mu$ to the points $0$ and $1$ in the complex plane must be $1.$ This can obviously be fulfilled if and only if $\mu\in[0,1].$
Let $a=\binom{1}{0},\;\;b=\binom{0}{1},\;\;c=\binom{-1}{0}.$ Then there is no $\mu$ such that $b=\mu a+(1-\mu)c$, but
$$
\|a-c\|_{\infty} = \|a-b\|_{\infty}+\|c-b\|_{\infty}
$$

A: In general, if $\|\cdot\|$ is induced by an inner product, then $\|x+y\|=\|x\|+\|y\|$ if and only if one of $x$ and $y$ is a nonnegative scalar multiple of the other.
Now let $x=a-b$ and $y=b-c$. The given condition implies that $\|x+y\|=\|x\|+\|y\|$. Therefore, one of $x$ and $y$ is a nonnegative scalar multiple of the other. Without loss of generality, let $y=kx$ for some $k\ge0$. Then $b-c=k(a-b)$. Hence $b=\frac{k}{k+1}a+\frac{1}{k+1}c$ and you may take $\mu=\frac{k}{k+1}$.
The case is different if the norm is not induced by an inner product. E.g. let $a=(1,0),\,b=(0,0)$ and $c=(0,1)$ in $\mathbb R^2$. We have $\|a-c\|_1=2=\|a-b\|_1+\|c-b\|_1$, but $b$ does not lie on the line segment delimited by $a$ and $c$.


text:
Q: Requirements to prove the Markov property in a DAG Suppose that I have the following PDFs well-defined:
$$
f_A(A), f_B(B|A), f_C(C|B,D), f_D(D)
$$
From these PDFs I can deduce the following direct dependence relation:
$$
A \rightarrow B \rightarrow C \leftarrow D
$$
Given the above, on what grounds can I be sure that the joint probability function is correctly written as:
$$
f(A,B,C,D)=f_A(A)f_B(B|A)f_C(C|B,D)f_D(D)
$$
and not in some other way.
Note that usually the Markov property of a DAG is assumed from which follows that the joint probability can be decomposed as above. The question here is backwards. I have the partial probabilities (from which I can construct the above DAG), and I want to prove that what I have meets the Markov property.
Once I am sure that the joint probability can be written as above, I can use the theory.

A: You cannot define $A \rightarrow B \rightarrow C \leftarrow D$ from your PDFs alone. You also need independence assumptions such as, in your case $(C|B) \perp A$ that cannot be deduced from the densities you mentioned. Except maybe if you consider that the model is fully defined by these densities, which is equivalent to implicitly defining independences and which is, IMHO, an error-prone solution.
Elucidating and using these hidden independences, it is likely that you could  factorize the $f(A,B,C,D)$ as in your last equation.


text:
Q: Upgrade from ubuntu 17.04 to some new supported version As you can tell, I'm a bit of a Linux noob. I haven't upgraded my ubuntu 17.04 and this is causing me a painful headache. I can't use apt-get at all. I imagine the reason behind this is the lack of support of my version. I tried following some tutorials, including this one: https://help.ubuntu.com/community/EOLUpgrades
No matter what I do or whether I update sources.list or not, apt-get seems to still be unsupported.
If I run apt-get update, for instance, I get the following response:
Reading package lists... Done
W: The repository 'http://ppa.launchpad.net/ehbello/fritzing/ubuntu zesty Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
W: The repository 'http://ppa.launchpad.net/js-reynaud/kicad-5/ubuntu zesty Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: Failed to fetch http://ppa.launchpad.net/ehbello/fritzing/ubuntu/dists/zesty/main/binary-i386/Packages  404  Not Found
E: Failed to fetch http://ppa.launchpad.net/js-reynaud/kicad-5/ubuntu/dists/zesty/main/binary-i386/Packages  404  Not Found
E: Some index files failed to download. They have been ignored, or old ones used instead.

Or else, running apt-get upgrade gives me:
Reading state information... Done
You might want to run 'apt --fix-broken install' to correct these.
The following packages have unmet dependencies: mono-devel : Depends: mono-roslyn (= 5.10.1.20-0xamarin1+debian7b1) but it is not installed
E: Unmet dependencies. Try 'apt --fix-broken install' with no packages (or specify a solution).

The result of apt --fix-broken install is:
enter code here
After this operation, 13,6 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
dpkg: warning: files list file for package 'mono-devel' missing; assuming package has no files currently installed
dpkg: warning: files list file for package 'monodoc-base' missing; assuming package has no files currently installed
dpkg: warning: files list file for package 'monodoc-manual' missing; assuming package has no files currently installed
(Reading database ... 266394 files and directories currently installed.)
Preparing to unpack .../mono-roslyn_5.10.1.20-0xamarin1+debian7b1_all.deb ...
Unpacking mono-roslyn (5.10.1.20-0xamarin1+debian7b1) ...
dpkg: error processing archive /var/cache/apt/archives/mono-roslyn_5.10.1.20-0xamarin1+debian7b1_all.deb (--unpack):
 trying to overwrite '/usr/bin/csc', which is also in package chicken-bin 4.11.0-1
dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Errors were encountered while processing:
 /var/cache/apt/archives/mono-roslyn_5.10.1.20-0xamarin1+debian7b1_all.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

The link above uses aptitude to install the packages needed, but I can't find a way to install it without apt-get.
Thanks in advance.
UPDATE
That's how my sources.list file looks like:
deb http://old-releases.ubuntu.com/ubuntu/ zesty main restricted universe multiverse
deb http://old-releases.ubuntu.com/ubuntu/ zesty-updates main restricted universe multiverse
deb http://old-releases.ubuntu.com/ubuntu/ zesty-security main restricted universe multiverse


text:
Q: Unable to get a Fragment Object into MainActivity : android I have created an experimental app in which I'm trying to learn to establish a successful communication b/w two fragments.
What I have is just one activity which is Main Activity. In this activity I have a view pager element in XML. I've created custom pager adapter which extends to Fragment Pager Adapter and two Fragments which are children and supplied by my pager adapter to the view pager.
What I'm trying to do is: FirstFragment has one button which on clicked changes the background color of the SecondFragment(there's a relative layout as parent), which will be visible on one swipe.
What I've done so far: I created an interface in FirstFragment, implemented in MainActivity, created a method in SecondFragment which changes the background color of layout and finally getting the SecondFragment in MainActivvity (at least trying to) and calling its method. But app is crashing on button click saying "Fragment SecondFragment not attached to a context"
Here's the code:
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</android.support.constraint.ConstraintLayout>

MainActivity.java
package com.example.android.laboratory;

import...

public class MainActivity extends AppCompatActivity implements FirstFragment.MyListener {

    ViewPager viewPager;
    MyPagerAdapter adapter;

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

        viewPager = findViewById(R.id.view_pager);
        adapter = new MyPagerAdapter(getSupportFragmentManager());
        viewPager.setAdapter(adapter);

    }

    @Override
    public void changeColor() {
        SecondFragment secondFragment = new SecondFragment();
        secondFragment.changeColor();
    }
}

Custom Adapter:
package com.example.android.laboratory;

import ...

public class MyPagerAdapter extends FragmentPagerAdapter {
    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {

        switch (i) {
            case 0:
                return new FirstFragment();
            case 1:
                return new SecondFragment();
        }

        return null;
    }

    @Override
    public int getCount() {
        return 2;
    }
}

First Fragment:
package com.example.android.laboratory;

import ...

public class FirstFragment extends Fragment {

    MyListener listener;

    public FirstFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_first, container, false);

        Button button = view.findViewById(R.id.button);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listener.changeColor();
            }
        });

        return view;
    }

    public interface MyListener{
        void changeColor();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        try {
            listener = (MyListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(getActivity().toString() + " must implement MyListener interface.");
        }
    }
}

Second Fragment:
package com.example.android.laboratory;

import ...

public class SecondFragment extends Fragment {

    RelativeLayout relativeLayout;

    public SecondFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_second, container, false);

        relativeLayout = view.findViewById(R.id.layout);

        return view;
    }

    public void changeColor() {
        relativeLayout.setBackgroundColor(getResources().getColor(R.color.colorAccent));
    }

}

Crash log:
12-23 12:18:03.574 31428-31428/com.example.android.laboratory E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.android.laboratory, PID: 31428
    java.lang.IllegalStateException: Fragment SecondFragment{2bfa6ff2} not attached to a context.
        at android.support.v4.app.Fragment.requireContext(Fragment.java:696)
        at android.support.v4.app.Fragment.getResources(Fragment.java:760)
        at com.example.android.laboratory.SecondFragment.changeColor(SecondFragment.java:32)
        at com.example.android.laboratory.MainActivity.changeColor(MainActivity.java:28)
        at com.example.android.laboratory.FirstFragment$1.onClick(FirstFragment.java:31)
        at android.view.View.performClick(View.java:4791)
        at android.view.View$PerformClick.run(View.java:19903)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5296)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:912)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:707)

A: You can see this doc https://developer.android.com/training/basics/fragments/communicating
If you want to make you own bicycle for some reasons, you could try something like this (observer pattern)
MyModel
import java.util.ArrayList;

public class MyModel {
private int color = R.color.colorPrimary;

private ArrayList<MyObserver> observers = new ArrayList<>();

interface MyObserver {
    void setColor(int color);
}

public void setColor(int color) {
    this.color = color;
    for (int i = 0; i < observers.size(); i++) {
        observers.get(i).setColor(color);
    }
}

public void addObserver(MyObserver newObserver) {
    if (observers.indexOf(newObserver) < 0) {
        observers.add(newObserver);
    }
}

public void deleteObserver(MyObserver oldObserver) {
    if (observers.indexOf(oldObserver) >  -1) {
        observers.remove(oldObserver);
    }
}
}

FirstFragment
public class FirstFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_first, container, false);

    Button button = view.findViewById(R.id.button);

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            MainActivity mainActivity = (MainActivity) getActivity();
            mainActivity.myModel.setColor(R.color.colorAccent);
        }
    });

    return view;
}
}

SecondFragment
public class SecondFragment extends Fragment implements MyModel.MyObserver {

RelativeLayout relativeLayout;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_second, container, false);

    relativeLayout = view.findViewById(R.id.layout);
    MainActivity mainActivity = (MainActivity) getActivity();
    mainActivity.myModel.addObserver(this);
    return view;
}

@Override
public void onDestroy() {
    MainActivity mainActivity = (MainActivity) getActivity();
    mainActivity.myModel.deleteObserver(this);
    super.onDestroy();
}

@Override
public void setColor(int color) {
    relativeLayout.setBackgroundColor(getResources().getColor(color, null));
}
}

MainActivity
public class MainActivity extends AppCompatActivity {

ViewPager viewPager;
MyPagerAdapter adapter;

public MyModel myModel = new MyModel();

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

    viewPager = findViewById(R.id.view_pager);
    adapter = new MyPagerAdapter(getSupportFragmentManager());
    viewPager.setAdapter(adapter);

}
}


text:
Q: make: 'file' is up to date, followed by nothing to be done for all I'm trying to create a basic makefile for my program. It looks like this:
all: example
example: example.c
    gcc -o example example.c
clean:
    rm example

If I 'make clean', then enter 'make', I receive "make: Nothing to be done for all".
If I make a slight change to my source code, save it, then run make, I receive "gcc -o example example.c
If I enter 'make example', I receive "'example' is up to date. I'm using indents, not spaces, before 'gcc' and 'rm' in the make file, and the indents are not secretly spaces. I'm sure it's something I'm doing wrong with my makefile, but I would appreciate some help figuring out what mistake I'm making.
edit: changed 'clear make' to 'make clean'

A: if you enter
make

then the 'example' program will be generated.
then, If you then enter
make example

nothing will happen because the program 'example' is already done and its dependencies ('example.c') time stamp has not changed.


text:
Q: Hide or show CheckBox in CustomAdapter I'm using databse in my app. I can create some "notes" , and define the type : Homework or Test.
Then I display it in a ListView.
But, when the row is created, I'd like to check if I chose "Homework" as the type, and if I did, I add a checkbox to that row in my listView, but If I chose "Test", I do not display the CheckBox.
Then, with the checkbox I can set the homework as DONE or NOT DONE with the cb.isChecked(). But first I have to only display the checkBox if it's a homework. But I don't know how to check it..
How can I do that ?
Here's my CustomAdapter class
public class CustomAdapterJalons extends SimpleCursorAdapter {

private Context mContext;
private Context appContext;
private int layout;
private Cursor cr;
private final LayoutInflater inflater;

public CustomAdapterJalons(Context context, int layout, Cursor c, String[] from, int[] to) {
    super(context, layout, c, from, to);
    this.layout = layout;
    this.mContext = context;
    this.inflater = LayoutInflater.from(context);
    this.cr = c;
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    return inflater.inflate(layout, null);
}

@Override
public void bindView(View view, final Context context, final Cursor cursor) {
    super.bindView(view, context, cursor);

    LinearLayout root_view = (LinearLayout)view.findViewById(R.id.item_root);

    root_view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            //method
        }
    });

   final int position = cursor.getPosition();

    cursor.moveToPosition(position);

    int devoir = cursor.getInt(3);
    int evaluation = cursor.getInt(4);
    CheckBox cbdevoir = (CheckBox)view.findViewById(R.id.CBDevoir);

    if(devoir==1)
    {
     cbdevoir.setVisibility(View.VISIBLE);
    }
   if(evaluation==1)
   {
       cbdevoir.setVisibility(View.INVISIBLE);
   }
    }

}
Thank you guys !

A: you have to check that in bindview method
@Override
public void bindView(View view, final Context context, final Cursor cursor) {
    super.bindView(view, context, cursor);

    LinearLayout root_view = (LinearLayout)view.findViewById(R.id.item_root);

    root_view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            //method
        }
    });

   final int position = cursor.getPosition();

    cursor.moveToPosition(position);

    int devoir = cursor.getInt(3);
    int evaluation = cursor.getInt(4);
    CheckBox cbdevoir = (CheckBox)view.findViewById(R.id.CBDevoir);

    if(devoir==1)
    {
     cbdevoir.setVisibility(View.VISIBLE);
    }
    else{
    cbdevoir.setVisibility(View.INVISIBLE);
    }

    }

A: Your condition is not OK. In your adapters bindView() method:
Use:
if(devoir == 1) {
    cbdevoir.setVisibility(View.VISIBLE);
} else {
    cbdevoir.setVisibility(View.GONE);
}

Instead of:
if(devoir==1)
{
    cbdevoir.setVisibility(View.VISIBLE);
}
if(evaluation==1)
{
    cbdevoir.setVisibility(View.INVISIBLE);
}

A: Steps

*

*In XML row make checkbox is hide

android:visibility="gone"

*In bindview method
@Override

    public void bindView(View view, final Context context, final Cursor cursor) {

        super.bindView(view, context, cursor);

    LinearLayout root_view=LinearLayout)view.findViewById(R.id.item_root);

root_view.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        //method
    }
});

CheckBox cbdevoir = (CheckBox)view.findViewById(R.id.CBDevoir);

If(type.equals("Homework"){

  cbdevoir.setVisibility(View.VISIBLE)
 }
else{

    cbdevoir.setVisibility(View.GONE);
}

if(cbdevoir.isChecked())
{
    //method to set the homework done
}
else
    {
        //method to set the homework undone
    }
}


text:
Q: $ax=0$ if and only if $a=0$ or $x=0$ Prove that $ax=0$ $\Leftrightarrow$ $a=0$ $\lor$ $x=0$, where $a$ is a scalar from a field and $x$ is an element of the vector space on this field.
I would like a hint or maybe a solution to prove this theorem by using vector space axioms. Can you explain if there is a difference in the proof of this theorem if we use abstract algebra without the need of vector space axioms but only by using group theory knowledge.


text:
Q: Why alignment mark list is different on WebKit when using :before height? Code: http://jsbin.com/maropaxivo/1/edit?html,css,output
See the sample code Firefox and Chrome browsers. Why alignment mark list is different?

li:before {
  height: 20px;
  content: " ";
  display: block;
  background-color: #ccc;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>

123

123

123

123

123

A: So I investigated more into this issue:

*

*Here is how it behaves now- note that the before is a block element while the content of li is inline.

li:before {
  height: 20px;
  content: " ";
  display: block;
  background-color: #ccc;
}

123

123

123

123

123

*If I make both the items a block element by wrapping the text in a div, we have the same behaviour.

li:before {
  height: 20px;
  content: " ";
  display: block;
  background-color: #ccc;
}

123

123

123

123

123

*If I change the before element to inline-block, we will finally see the same behavior in Firefox and Chrome:

li:before {
  height: 20px;
  content: " ";
  display: inline-block;
  width: 100%;
  background-color: #ccc;
}

123

123

123

123

123

*If I change the before element to inline-block, and keep the content as block we will again see the same behavior in Firefox and Chrome:

li:before {
  height: 20px;
  content: " ";
  display: inline-block;
  width: 100%;
  background-color: #ccc;
}

123

123

123

123

123

Comments:
So whenever the before is inline-block (cases 3 and 4 above) or even inline for that matter, we see same behavior in Firefox and Chrome.

*

*In Firefox, the numbers are aligned with the first inline element.

*In Chrome, it doesn't matter even if it is a block element.
I strongly believe that this behavior is because there is a small difference in the user agent(browser) implementation of list-item display.
Conclusion:
Use inline-block and you won't face this discrepancy.
Let me know your feedback on this. Thanks!
EDIT:
So if you want it to look like the Firefox implementation of your code in both browsers, you can make the before absolute relative to the li:

li{
  position: relative;
  margin-top: 25px;
}
li:before {
  height: 20px;
  content: " ";
  display: block;
  width: 100%;
  background-color: #ccc;
  position:absolute;
  top: -20px;
}

123

123

123

123

123


text:
Q: Get dot separated path of a standard library function from the function itself Is there a way to get a full name (dot separated path of a function including its name) of a standard library function? For example:
import sys
import os
from random import choice

my_function = choice([sys.exit, os.path.join, os.getcwd])

print(my_function) # Somehow generate full name of the built-in function
# Would expect to get one of 'sys.exit', 'os.path.join' or 'os.getcwd'

A: You can get the information you're looking for using the __module__ and __qualname__ attributes of a function (under Python 3).  For example:
>>> import sys
>>> func = sys.exit
>>> print('{}.{}'.format(func.__module__, func.__qualname__))
sys.exit

This also works for class members:
>>> import email.message

>>> func = email.message.Message.get_payload
>>> print('{}.{}'.format(func.__module__, func.__qualname__))
email.message.Message.get_payload

It's a little more work under Python 2.x because the __qualname__ attribute isn't available:
>>> print('{}.{}.{}'.format(func.__module__, func.im_class.__name__, func.__name__))


text:
Q: What's the difference between displayP3Red and red In Swift I have found two ways to initialize an UIColor
UIColor(displayP3Red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)
UIColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)

Is there a difference between those two ways?

A: This answer is my summary from the following resource

https://creativepro.com/how-do-p3-displays-affect-your-workflow/

UIColor(red...) is in the sRGB colorspace which can display a specific gamut (or range) of colors. Most displays, printers, other devices can display colors in this color space.
There are other colorspaces, such as the Adobe RBG color space, or Apple's P3 color space that can display a wider range of colors. A device that can display these colors are known as wide gamut displays.
The below image compares the adobe, p3, and srgb color spaces.
 (Picture taken from https://creativepro.com/how-do-p3-displays-affect-your-workflow/)

A: Nice recent article from Apple here: https://developer.apple.com/news/?id=5cda5ipr
TL;DR
Apple says of Display P3 Colors:
"They'll look richer and more vibrant on any device with a wide color gamut display.
You can find wide color gamut Retina displays on most Macs, as well as iPhone, iPad, and Apple Watch. They bring more true-to-life colors and deep hues to the screen, not only making for excellent image and video viewing but also heightening people's everyday app experience.
Use Display P3 assets in your app to amplify important elements of your interface: the colors of a VU meter in an audio app, for instance, or the redline in a rev counter inside your racing game."


text:
Q: Strict inequality in CSS media queries Say I have this:
@media only screen and (max-width: 600px) {
    nav {
        display: none;
    }
}
@media only screen and (min-width: 601px) {
    nav {
        display: block;
    }
}

This means undefined behaviour for a width like 600.5, which is a possible logical width on HiDPI diplays. The problem with min-width, max-width, etc are that they are weak inequalities (>= and <= respectively). How do I achieve strict inequality in CSS media queries (> and <)?

A: The width of the document will always be rounded to an integer in px. If you're interested in details, you can read this article.
Let's make a simple test:

// set width to 600.5px:
document.querySelector('body').style.width = '600.5px';

// get actual width:
console.log('600.5px gets parsed to ' + document.querySelector('body').offsetWidth);

// set width to 600.4999px:
document.querySelector('body').style.width = '600.4999px';

// get actual width
console.log('600.4999px gets parsed to ' + document.querySelector('body').offsetWidth);

This technically means @media (max-width:600px) applies when document width is equal or below 600.49994(9)px. In practice, it never has decimal width.

A: You can achieve strict inequality using negation and nested media queries:
@media only screen and (max-width: 600px) {
    nav { display: none; }
}
@media only screen {
    @media not all and (max-width: 600px) {
        nav { display: block; }
    }
}

Support seems excellent. But it won't work on IE.
Another technique is to have a separate stylesheet. This is the only way on IE:
<style media="screen">
@media not screen and (max-width: 600px) {
    nav { display: block; }
}
</style>

Of course, if you don't care about other media types you could just put this in the original stylesheet. It will apply to screen above max-width, and to all other types regardless of width.
@media only screen and (max-width: 600px) {
    nav { display: none; }
}
@media not screen and (max-width: 600px) {
    nav { display: block; }
}

But in the real world, we need to at least care about the print output, closely followed by accessibility (speech) and other media types. That's why we need to limit this to screen only using one of the two techniques.


text:
Q: Cache flushing and cold caches The code below showed up on one of the kernel mailing lists. I can't cite it at the moment because the message has not posted to any of the kernel archives (mail-archive.com, marc.info, or spinics.net):
static void clflush(void)
{
    extern char const _init, _fini;
    char const *p = &_init;

    while (p < &_fini) {
        asm("clflush %0" : : "m" (*p));
        p += 64;
    }
}

Here's the description of the function from the message:

*

*Before every even-numbered iteration, I flushed the I-cache
of everything from _init to _fini (i.e. all the non-library code).
This cold-cache case is what is going to happen in the kernel.

I don't quite understand what is going on with the _init to _fini trick.
What is the purpose of the loop based on _init, _fini (and function pointers in between)? Why is a simple pointer that takes cache size and associativity not used?

Here's the full code provided in the message. The code attempts to benchmark a proposed algorithm (SipHash) with the cache in a certain state (cold) to avoid potentially skewed measurements.
static void clflush(void)
{
        extern char const _init, _fini;
        char const *p = &_init;

        while (p < &_fini) {
                asm("clflush %0" : : "m" (*p));
                p += 64;
        }
}

typedef uint32_t cycles_t;
static cycles_t get_cycles(void)
{
        uint32_t eax, edx;
        asm volatile("rdtsc" : "=a" (eax), "=d" (edx));
        return eax;
}

static int benchmark(void)
{
        cycles_t start, finish;
        int i;
        u32 seq_number = 0;
        __be32 saddr6[4] = { 1, 4, 182, 393 }, daddr6[4] = { 9192, 18288, 2222222, 0xffffff10 };
        __be32 saddr4 = 28888, daddr4 = 182112;
        __be16 sport = 22, dport = 41992;
        u32 tsoff;
        cycles_t result[4];

        printf("seq num benchmark\n");

        for (i = 0; i < 10; i++) {
                if ((i & 1) == 0)
                        clflush();

                start = get_cycles();
                seq_number += secure_tcpv6_sequence_number_md5(saddr6, daddr6, sport, dport, &tsoff);
                finish = get_cycles();
                result[0] = finish - start;

                start = get_cycles();
                seq_number += secure_tcp_sequence_number_md5(saddr4, daddr4, sport, dport, &tsoff);
                finish = get_cycles();
                result[1] = finish - start;

                start = get_cycles();
                seq_number += secure_tcpv6_sequence_number(saddr6, daddr6, sport, dport, &tsoff);
                finish = get_cycles();
                result[2] = finish - start;

                start = get_cycles();
                seq_number += secure_tcp_sequence_number(saddr4, daddr4, sport, dport, &tsoff);
                finish = get_cycles();
                result[3] = finish - start;

                printf("* Iteration %d results:\n", i);
                printf("secure_tcpv6_sequence_number_md5# cycles: %u\n", result[0]);
                printf("secure_tcp_sequence_number_md5# cycles: %u\n", result[1]);
                printf("secure_tcpv6_sequence_number_siphash# cycles: %u\n", result[2]);
                printf("secure_tcp_sequence_number_siphash# cycles: %u\n", result[3]);
                printf("benchmark result: %u\n", seq_number);
        }

        printf("benchmark result: %u\n", seq_number);
        return 0;
}
//device_initcall(benchmark);

int
main(void)
{
        memset(net_secret, 0xff, sizeof net_secret);
        memset(net_secret_md5, 0xff, sizeof net_secret_md5);
        return benchmark();

}