text:
Q: Hibernate oneToMany Abstract Class override ID I'm using JPA 1.0 so I am limited in what I can do but I still think it should be possible to do the following however I cant get it working...
Table CustomerA
    a_id

Table ProductB
    a_id
    b_id

Table ProductC
    a_id
    c_id

@Entity
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class AbstractProduct {

    @Id
    @GeneratedValue....
    private Long id;

    private String name;

 @ManyToOne()
 JoinColumn(name="a_id")
 private CustomerA customerA;

}

Now I want to create a subclass which can over ride the Id or create a composite Key based on the PK of Table A and the key of the derived table...
@Entity
@Table(name="ProductB")
public class ProductB extends AbstractProduct {

     //@AttributeOverride(name="id", column=@Column(name="B_ID") //Can only be used     with MappedSuperClass and also Emmbedded Objects
     //@Id //cant override the ID Column so that cant go here
    //PrimaryKeycolumn join not what i want here
    private Long productB_id;

    private String productName;
}

@Entity
@Table(name="CustomerA")
public class CustomerA
{
    @Id
    @GeneratedValue....
    @Column(name="a_id")
    private Long aId

     @OneToMany(mappedBy="customerA", cascade=CascadeType.ALL)
    private Set<AbstractProduct> product;
}

So essentially CustomerA can contain many products, but it will always only be of either ProductB or ProductC.  How can i override the Id in the subclass as you cant use attributeoverride and Entity, and if you use @Entity you must specify @Id whenever you specify an @Entity.  I've read the jpa wiki and it looks rather complicated and ott to achieve this in JPA 1.0, but i'm wondering if I am missing something?

A: My suggestion is to share a base class between your two products, so that you can reference them both in a single way.  In JPA/Hibernate that means creating a shared table that will contain the common elements of your Product, namely the reference to the CustomerA.
The way you can accomplish this is with the 'JOINED' inheritance strategy:
@Inheritance(strategy=InheritanceType.JOINED)

The drawback of using this strategy is it may collide with your existing 'TABLE_PER_CLASS' stategy already used in your AbstractProduct base class.... although this may be the appropriate base class to use for this.  From what I remember, you cannot mix inheritance strategies.
Here's an example:
@Entity
@Table(name="CustomerA")
public class CustomerA
{
    @Id
    @GeneratedValue....
    @Column(name="a_id")
    private Long aId

    @OneToMany(mappedBy="customerA", cascade=CascadeType.ALL)
    private Set<AbstractProduct> product;
}

@Entity
@Table(name="ProductB")
public class ProductB extends AbstractProduct {

    private String specificProductBValue;
}

@Entity
@Table(name="ProductC")
public class ProductC extends AbstractProduct {

    private String specificProductCValue;
}

@Entity
@Inheritance(strategy=InheritanceType.JOINED)
public abstract class AbstractProduct {

    @Id
    @GeneratedValue....
    private Long id;

    private String name;

    @ManyToOne()
    JoinColumn(name="customer_id")
    private CustomerA customerA;

}

Seems like you are almost there with your example, just need to use the correct inheritance strategy.
Also, this assumes that you do not have other Products that extend your AbstractProduct base class.  If you do and you don't want those referenced by your Customer, then you would have to reconsider your domain design.
Hope that helps.


text:
Q: Can't get value from input I'm trying to make a guessing game with three questions and three guesses total but I can't get the value from the inputs so I can't progress any further. Rough draft for my code
guesses = 3
def guess():
  if guesses >= 0:
    alive = True
  else:
    print("You Failed")
Q1 = "What is 1+1"
Q2 = ""
Q3 = ""

def retry():
  input("Wrong Answer Try Again")

def questions():

 Q1 = input("What is 1+1")

def answer():
  if Q1 == "2":
    print("Q2")
  else:
    retry()
  if retry() == 2:
    print("Q2")

questions()
answer()

I've tried using lists functions if statements but I can't get the value of the inputs no matter what as its always a local variable.

A: Here's a simple approach to this problem.
The crucial part is the list of 2-tuples. Each tuple maintains a question and the correct answer to that question. By adding more questions and answers to the list your program can become more elaborate without having to change anything else in the code.
Something like this:
Questions = [("What is 1+1", "2"), ("What is 2+2", "4"), ("What is 3+3", "6")]

score = 0
TRIES = 3

for q, a in Questions:
    for _ in range(TRIES): # number of tries allowed
        if input(f'{q}? ').lower() == a.lower() :
            score += 1
            print('Correct')
            break
        else:
            print("Incorrect please try again")
    else:
        print('Maximum tries exceeded')

print(f'Your final score is {score}')

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery val() returns undefined, prepend() doesn't append in jQuery style and can't change text input size I have a bunch of problems, maybe they're caused by the same issue.
Here is my code:

Aufgaben:

Aufgabenname: <input type="text" name="aufgabenname" id="aufgabenname" size="20" maxlength="20"></input> Maximalpunktzahl: <input type="text" name="maxPunkte" id="maxPunkte" size="2" maxlength="2"></input>
<button id="add" data-icon="plus" data-iconpos="notext"></button>

I can create a new
, but aufgabenname and maxPunkte are undefined. Furthermore, the
 element doesn't show off in jQuery style, in particular the button is not what it is expected to be. And the text input size is at full length, no matter what I put in the size attribute.

A: You need to use # to target id. Change from:
var aufgabenname = $("aufgabenname").val();
var maxPunkte = $("maxPunkte").val();

to:
var aufgabenname = $("#aufgabenname").val();
var maxPunkte = $("#maxPunkte").val();

Fiddle Demo

A: May Issue: You need to call jquery functionality after ready event fired from JQuery.
size and maxlength it works as we expected.maxlength how many char user can type and Size determine visible width, in characters.

Aufgaben:

Aufgabenname: <input type="text" name="aufgabenname" id="aufgabenname" size="20" maxlength="20"></input> Maximalpunktzahl: <input type="text" name="maxPunkte" id="maxPunkte" size="2" maxlength="2"></input>
<button id="add" data-icon="plus" data-iconpos="notext"></button>

Fiddle Demo

A:  var maxPunkte = $(#"maxPunkte").val();

there is one problem;
var maxPunkte = $("#maxPunkte").val();


text:
Q: keep getting xml parsing error I'm trying to retrieve the user's design after creating a session (login) but I keep getting a parsing error: XML Parsing Error: junk after document element. I tried this on my local machine and on the server side as well. on the servers side, I only get a blank page since I think the errors are set not to be displayed.
Here is my code:
$ch = curl_init("http://api.spreadshirt.$tld/api/v1/sessions");
curl_setopt($ch, CURLOPT_HEADER, true); // get the header
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/xml'));
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $login->asXML());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_ENCODING, '');

$result = curl_exec($ch);

if (curl_errno($ch)) {
echo 'cURL error: ' . curl_error($ch);
return null;
}
curl_close($ch);
$headers = parseHttpHeaders($result);
$arr = explode('/', $headers[0]['Location']);
define('SESSION_ID', $arr[count($arr) - 1]);

$header = array();
$header[] = createSprdAuthHeader("GET", "http://api.spreadshirt.$tld/api/v1/users/$userId/designs");
$header[] = "Content-Type: application/xml";
$ch = curl_init("http://api.spreadshirt.$tld/api/v1/users/$userId/designs");
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_ENCODING, '');
$result = curl_exec($ch);
curl_close($ch);

header('Content-Type: application/xml; charset=utf-8');
echo $result;

function createSprdAuthHeader($method, $url) {
$apiKey = SPREADSHIRT_API_KEY;
$secret = SPREADSHIRT_API_SECRET;
$session = SESSION_ID;
$time = time() * 1000;

$data = "$method $url $time";
$sig = sha1("$data $secret");

return "Authorization: SprdAuth apiKey=\"$apiKey\", data=\"$data\", sig=\"$sig\", sessionId=\"$session\"";
}


text:
Q: Connect to a device's SSH on a network that has no inbound traffic enabled and no static IP address what I'm trying to do is to enable a Raspberry, physically placed in a client's site, that has internet access via Dynamic IP, to receive SSH commands from the wild without having to manipulate the client's router and firewall. No Inbound connections allowed on that network, plus, the internet address of the Client's site is dynamic.
Edit: to know the solution for this problem, refer to the replies of Kevin_Kinsey and Florin Godard, or scroll to the end of my question to know how I was able to get it working on non-standard SSH port 22.
I've already tried to study and understand what's proposed on ssh to private-ip on Unix Stack Exchange, but I'm really not getting the point.
I do want to connect from my, say, laptop, to the Client's VPS server, and make the VPS server connect to the Raspberry SSH. So:
           ( firewall access allow in+out )
      | =>           VPS Server              \    ( firewall access allow out only )
      |                                      | =>    Raspberry
MY PC /

Here is it a case scenario with given IP adresses, ports and names configurations:
MY PC
    name: mypc@local.lan

Client VPS Server
    name: remote.null.tld
    IP Address: 98.76.54.32
    SSH Port: 9876

Raspberry
    model: Zero W
    name: raspi1@clientlocal.lan
    IP Address: dynamic IP ( based on Internet Provider )
    SSH Port: 6789
    Raspberry's iptables: empty
    Router's Firewall Restrictions: allow only out
    Internet stability: very low

The Raspberry's external IP is the one assigned from the Internet Provider, and may vary depending on router restarts. Cannot determine it absolutely.
Internet Access on the client's network is really unstable. Radio link or something like that. Anyway, internet connection suffers of very dancing bandwidth.
Plus, the Client's router cannot be manipulated not because of laziness but because of restrictions imposed by the Client's IT dep.
I do have SSH access to the Client's VPS and I'm able to install whatever software on it.
Edit: solution to the problem
On my configuration, ports were non-standard. So, the solution was this one:
On the Raspberry:
# login to username@remote.null.tld is done via private/public key with no passwords
ssh -p 9876 -f -N -T -R 55555:localhost:6789 username@remote.null.tld

On the Raspberry's crontab:
# A re-connect is performed at every 10th minute of every hour to prevent accidental tunnel breakdowns.
10 * * * * ps -ef | grep 'ssh -p 9876 -f -N -T -R' | grep -v grep | awk '{print $2}' | xargs -r kill -9 && sleep 30s && ssh -p 9876 -f -N -T -R 55555:localhost:6789 username@remote.null.tld >/dev/null 2>&1

On the bridge VPS remote.null.tld
ssh -p 55555 raspberry_username@localhost

Or, a more elegant solution via modifying the VPS's ssh config:
Host tunnelToRemoteRaspberry
    Hostname localhost
    User raspberry_username
    Port 55555

A: I am assuming the user names remote on the VPS and pi on the raspberry.

*

*You choose a free port on the VPS. A random five-digit value below 65000 should work.

*On the Raspberry, you run
ssh -R PORT:localhost:22 remote@vps

*On the VPS, you connect to the Raspberry with
ssh -p PORT pi@localhost

Replace the PORT with the port you have chosen in the first step.
In step 2, you create a reverse tunnel from the PORT on the VPS to port 22 on the Raspberry, which is where the Raspberry's SSH server listens. In step 3, you connect to the PORT on the VPS and get transferred to the port 22 on the Raspberry.
You can then configure a connection inside the VPS' ~/.ssh/config such as:
Host raspberryTunnel
  Hostname localhost
  User pi
  Port PORT

If that works reliably, you can replace the single SSH connection on the Raspberry with autossh, which will automatically recreate the connection when it goes down.
autossh -R PORT:localhost:22 remote@vps

A: This is possible.  Use "reverse port forwarding".  You'll probably need a cronjob set up to check if it's connected.  If not, run something like this:
ssh -f -N -T -R 2210:localhost:22 me@example.com

"Example.com" is some server outside the FW that you do have access to.  You're forwarding port 22 on the RPi to port 2210 on example.com.  You can then SSH into example.com and do:
ssh RaspberryUser@localhost -p 2210

And you'll be connected to the RPi box.

A: What you're trying to do exactly as you ask is impossible:

No Inbound connections allowed on that network

However, you can easily:

*

*have the Pi  make an outbound connection to your laptop using reverse SSH that you schedule

*ssh from your laptop  to the VPS server and from the VPS server ssh again to the Pi

A: Essentially, you can reach your goal only with maintenance connections from the device to a server you maintain.
What exactly these connections consist of can be different:

*

*connect, fetch tasks to execute and proceed with them.

*connect to a VPN and be part of that, allowing to be connected to

*connect via SSH and establish a tunnel connection

Usable protocols

*

*VPN (uses several ports)

*SSH

*HTTPS

*even UUCP, although a little bit outdated

Depending on what the customer allows inside their network, you can even implement several of these methods to then choose from.
Each method has its pros and cons.

*

*SSH:

*

*+: only one port needed

*-: maybe not every network allows outbound SSH connections

*VPN:

*

*+: easiest integration into server's network

*-: several ports needed

*-: maybe not every network allows outbound SSH connections

*HTTPS:

*

*+: probably supported

*-: no real command line, only "work packages" are sendable

*-: big effort needed to set up

*UUCP:

*

*+: allows batches to be sent

*-: outdated protocol

A: If Pi firewall doesn't allow incoming connections then there is no way to establish connection. Your only way is to punch a hole through a firewall by using established connections.

A: I'd check out ZeroTier: it lets you set up a virtual network with the rules you want, e.g., that any node can directly connect to any other node. They handle all kinds of connectivity issues under the hood, including relaying traffic through their servers if needed.


text:
Q: Redux useReducer and mapDispatchToProps not working I'm building a react app using redux for state management.
Inside the SearchField component I am using useReducer for handle the search field inputs (cityField and countryField).
When i submit  the  fetchData function runs and sends a request to an API.
the SearchField component code:
import React, { useReducer } from "react";
import { connect } from 'react-redux';

import { SET_CITY_FIELD, SET_COUNTRY_FIELD } from '../../redux/search-field/search-field.types';
import { reducer, INITIAL_STATE } from "../../redux/search-field/search-field.reducer";
import { fetchData } from '../../redux/weather-api-data/data.actions';

import { SearchFieldContainer, SearchInput, OptionalField, FormComponent } from './search-field.styles';

const SearchField = () => {
    const [state, dispatch] = useReducer(reducer, INITIAL_STATE);
    const { cityField, countryField } = state;

    const onFormSubmit = e => {
        e.preventDefault()
        cityField.length < 1 ?
          alert('Please insert a city')
        :
        fetchData(cityField, countryField);
      }

    return (
        <SearchFieldContainer>
            <FormComponent onSubmit={onFormSubmit}>
                <SearchInput type="search" placeholder="Search City" aria-label="Search"
                    onChange={event => dispatch({ type: SET_CITY_FIELD, payload: event.target.value })}
                />
            </FormComponent>
            <FormComponent className='country-form' onSubmit={onFormSubmit}>
                <SearchInput className='country' type="search" placeholder="Country" aria-label="Search"
                    onChange={event => dispatch({ type: SET_COUNTRY_FIELD, payload: event.target.value })}
                />
                <OptionalField>OPTIONAL</OptionalField>
            </FormComponent>
        </SearchFieldContainer>
    )
}

const mapDispatchToProps = dispatch => ({
    fetchData: (cityField, countryField) => dispatch(fetchData(cityField, countryField))
})

export default connect(null, mapDispatchToProps)(SearchField);

The problem is that when the OnFormSubmit function is called, the fetchData function does not send any request and there is no errors in the console. The searchField and countryField data are stored correctly (or at least if I show them in the console I get the actual values). The fetchData function was previously located in the App and worked correctly.
I thank in advance anyone who gives me an answer and tries to find the solution.
The fetchData code:
export const fetchData = (cityField, countryField) => {
return (dispatch) => {
    dispatch(fetchCurrentDataRequest())
    axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${cityField},${countryField}&units=metric&appid=MY_API_KEY`)
        .then(response => {
            const currentData = response.data
            dispatch(fetchCurrentDataSuccess(currentData));
            const { lat, lon } = currentData.coord
            dispatch(fetchDailyDataRequest())
            axios.get(`https://api.openweathermap.org/data/2.5/onecall?lat=${lat}&lon=${lon}&units=metric&exclude=current,minutely,hourly,alerts&appid=MY_API_KEY`)
                .then(response => {
                    const dailyData = response.data.daily
                    dispatch(fetchDailyDataSuccess(dailyData))
                })
                .catch(error => {
                    const errorMessage = error.message
                    dispatch(fetchCurrentDataFailure(errorMessage))
                })
        })
        .catch(error => {
            const errorMessage = error.message
            alert('No results found')
            dispatch(fetchCurrentDataFailure(errorMessage))
        })
}

A: I resolved using useDispatch hook instead of mapdispatchToProps, so the new code is:
import React, { useReducer } from "react";
import { useDispatch } from 'react-redux';

import { fetchData } from '../../redux/weather-api-data/data.actions';
import { reducer, INITIAL_STATE } from '../../redux/search-field/search-field.reducer';
import { SET_CITY_FIELD, SET_COUNTRY_FIELD } from '../../redux/search-field/search-field.types';

import { SearchFieldContainer, SearchInput, OptionalField, FormComponent } from './search-field.styles';

const SearchField = () => {
    const dispatchData = useDispatch();
    const [state, dispatch] = useReducer(reducer, INITIAL_STATE);
    const { cityField, countryField } = state;

    const onFormSubmit = e => {
        e.preventDefault()
        cityField.length < 1 ?
          alert('Please insert a city')
        :
        dispatchData(fetchData(cityField, countryField));
      }

    return (
        <SearchFieldContainer>
            <FormComponent onSubmit={onFormSubmit}>
                <SearchInput type="search" placeholder="Search City" aria-label="Search"
                    onChange={event => dispatch({ type: SET_CITY_FIELD, payload: event.target.value })}
                />
            </FormComponent>
            <FormComponent className='country-form' onSubmit={onFormSubmit}>
                <SearchInput className='country' type="search" placeholder="Country" aria-label="Search"
                    onChange={event => dispatch({ type: SET_COUNTRY_FIELD, payload: event.target.value })}
                />
                <OptionalField>OPTIONAL</OptionalField>
            </FormComponent>
        </SearchFieldContainer>
    )
}

export default SearchField;


text:
Q: save data using hooks I fetch data from goodreads API and save it in books array using hooks.
I need to get data and display in component according to search query. but there is an issue in console (Uncaught TypeError: setSearchText is not a function)
function App() {
  const [books, setBooks] = useState([])
  const [searchText, setSearchText] = ('')

  const key = "xxx"
   const url =  `https://cors-anywhere.herokuapp.com/` +
      `https://www.goodreads.com/search/index.xml?key=${key}&q=${searchText}`;

  useEffect (()=> {
    loadData()
  }, [])

   const loadData = async () => {
     axios.get(url).then((res) => {
       setBooks(res.data)
       console.log(books)
     })
   }
   const onTextChange = (e) => {
     setSearchText(e.target.value)
   }
  return (
    <>
        <Container>

Bookstore

            <input type='text'
                   placeholder='Search...'
                   name="searchText"
                   onChange={onTextChange}
                   value={searchText}
            />

        </Container>

    </>
  );
}

A: You are missing a function call on the right side of the destructuring assignment.
const [books, setBooks] = useState([])
const [searchText, setSearchText] = ('') // This should be useState('')


text:
Q: NFA to DFA for odd a's and even b's The regular expression for accepting odd a's and even b's I calculated is: (aa)*a(bb)* and the NFA:

+-------+-----+---+
| State | a   | b |
+-------+-----+---+
|   A   | B,C |   |
|   B   |     | D |
|   C   | A   |   |
|   D   |     | B |
+-------+-----+---+

Now I want to convert this into DFA so I transform the transistion table as:
+-------+-----+---+
| State | a   | b |
+-------+-----+---+
|   A   |[BC] |   |
| [BC]  | A   | D |
+-------+-----+---+

I think that there's something wrong with DFA of it. It seems to have a missing transition from D to CB for 'b' which I don't see in table.

A: Your given regular expression is : $(aa)^*a(bb)^*$.
Regular language is : $\{a^{2m+1}b^{2n}|m,n\ge 0\}$
Your given NFA is for above language :

So, the transitition table for above NFA is :
+-------+-----+---+
| State | a   | b |
+-------+-----+---+
|   A   | B,C |   |
|   B   |     | D |
|   C   | A   |   |
|   D   |     | B |
+-------+-----+---+

Conversion from NFA to DFA :
+-------+-----+---+
| State | a   | b |
+-------+-----+---+
|   A   | B,C | Φ |
|  B,c  | A   | D |
|   D   | Φ   | B |
|   B   | Φ   | D |
|   Φ   | Φ   | Φ |
+-------+-----+---+

The DFA will be :

A: Hint: Let's consider your second table, it's not completed yet, since you have $D$ in the third column. So, you need another row: put $D$ into the column "State" and fill respective states into columns $a$ and $b$ (it should be $\emptyset$ and $B$ respectively). Then you'll need to do the same for state $B$. And so on, you'll need a new row for every new state that could be obtained in the right hand side of the table (in columns $a$ or $b$). And also (very important!) don't forget to fill the row for the state $\emptyset$ (it will be the row: $\emptyset\:|\:\emptyset\:|\:\emptyset$).


text:
Q: Android Developing: Is there a plugin or so for Eclipse , where a friend and i can develop at the same time? Is there a plugin or so for Eclipse, where a friend and i can develop at the same time?

A: There are many plugins for source code version control (SVN, GIT, CVS), if that is what you are asking for. (Sorry if I misunderstood the question!)
I suggest you take a look at http://subclipse.tigris.org/ (SVN)!
(And if you need free SVN/GIT repositories: https://xp-dev.com/ or http://code.google.com)


text:
Q: Angular: how to update non-angular javascript variable in response to a change of scope model? I've a huge jQuery plugin with domain logic from a third-party team and I really don't want to mess with its guts. This plugin exposes an object called browser to the global namespace.
I have a simple Angular controller. I made it $watch() the changes of browser (using object equality, not referential equality) and update the scope accordingly:
$scope.$watch(browser, function(newValue, oldValue, scope) { scope.browser = newValue; }, true);

Fine, but now I need to do the reverse: I need to update the global browser object when $scope.browser model changes in the course of Angular's $digest loop. How do I do that?
Probably, I need to create a custom hook to Angular's dirty-checking loop. I understand, that this is a bad approach and that the whole point of two-way binding was to avoid these manual callbacks, but I just can't figure out a better solution.

A: Simply you can reverse back as the same way
$scope.$watch("browser", function(newValue, oldValue, scope) { browser = newValue; }, true);


text:
Q: PySpark: org.apache.spark.sql.AnalysisException: Attribute name ... contains invalid character(s) among " ,;{}()\n\t=". Please use alias to rename it I'm trying to load Parquet data into PySpark, where a column has a space in the name:
df = spark.read.parquet('my_parquet_dump')
df.select(df['Foo Bar'].alias('foobar'))

Even though I have aliased the column, I'm still getting this error and error propagating from the JVM side of PySpark.  I've attached the stack trace below.
Is there a way I can load this parquet file into PySpark, without pre-processing the data in Scala, and without modifying the source parquet file?
---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
/usr/local/python/pyspark/sql/utils.py in deco(*a, **kw)
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:

/usr/local/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    318                     "An error occurred while calling {0}{1}{2}.\n".
--> 319                     format(target_id, ".", name), value)
    320             else:

Py4JJavaError: An error occurred while calling o864.collectToPython.
: org.apache.spark.sql.AnalysisException: Attribute name "Foo Bar" contains invalid character(s) among " ,;{}()\n\t=". Please use alias to rename it.;
    at org.apache.spark.sql.execution.datasources.parquet.ParquetSchemaConverter$.checkConversionRequirement(ParquetSchemaConverter.scala:581)
    at org.apache.spark.sql.execution.datasources.parquet.ParquetSchemaConverter$.checkFieldName(ParquetSchemaConverter.scala:567)
    at org.apache.spark.sql.execution.datasources.parquet.ParquetSchemaConverter$$anonfun$checkFieldNames$1.apply(ParquetSchemaConverter.scala:575)
    at org.apache.spark.sql.execution.datasources.parquet.ParquetSchemaConverter$$anonfun$checkFieldNames$1.apply(ParquetSchemaConverter.scala:575)
    at scala.collection.IndexedSeqOptimized$class.foreach(IndexedSeqOptimized.scala:33)
    at scala.collection.mutable.ArrayOps$ofRef.foreach(ArrayOps.scala:186)
    at org.apache.spark.sql.execution.datasources.parquet.ParquetSchemaConverter$.checkFieldNames(ParquetSchemaConverter.scala:575)
    at org.apache.spark.sql.execution.datasources.parquet.ParquetFileFormat.buildReaderWithPartitionValues(ParquetFileFormat.scala:293)
    at org.apache.spark.sql.execution.FileSourceScanExec.inputRDD$lzycompute(DataSourceScanExec.scala:285)
    at org.apache.spark.sql.execution.FileSourceScanExec.inputRDD(DataSourceScanExec.scala:283)
    at org.apache.spark.sql.execution.FileSourceScanExec.inputRDDs(DataSourceScanExec.scala:303)
    at org.apache.spark.sql.execution.ProjectExec.inputRDDs(basicPhysicalOperators.scala:42)
    at org.apache.spark.sql.execution.WholeStageCodegenExec.doExecute(WholeStageCodegenExec.scala:386)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:117)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$execute$1.apply(SparkPlan.scala:117)
    at org.apache.spark.sql.execution.SparkPlan$$anonfun$executeQuery$1.apply(SparkPlan.scala:138)
    at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
    at org.apache.spark.sql.execution.SparkPlan.executeQuery(SparkPlan.scala:135)
    at org.apache.spark.sql.execution.SparkPlan.execute(SparkPlan.scala:116)
    at org.apache.spark.sql.execution.SparkPlan.getByteArrayRdd(SparkPlan.scala:228)
    at org.apache.spark.sql.execution.SparkPlan.executeTake(SparkPlan.scala:311)
    at org.apache.spark.sql.execution.CollectLimitExec.executeCollect(limit.scala:38)
    at org.apache.spark.sql.Dataset$$anonfun$collectToPython$1.apply$mcI$sp(Dataset.scala:2803)
    at org.apache.spark.sql.Dataset$$anonfun$collectToPython$1.apply(Dataset.scala:2800)
    at org.apache.spark.sql.Dataset$$anonfun$collectToPython$1.apply(Dataset.scala:2800)
    at org.apache.spark.sql.execution.SQLExecution$.withNewExecutionId(SQLExecution.scala:65)
    at org.apache.spark.sql.Dataset.withNewExecutionId(Dataset.scala:2823)
    at org.apache.spark.sql.Dataset.collectToPython(Dataset.scala:2800)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:280)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:214)
    at java.lang.Thread.run(Thread.java:748)

During handling of the above exception, another exception occurred:

AnalysisException                         Traceback (most recent call last)
<ipython-input-37-9d7c55a5465c> in <module>()
----> 1 spark.sql("SELECT `Foo Bar` as hey FROM df limit 10").take(1)

/usr/local/python/pyspark/sql/dataframe.py in take(self, num)
    474         [Row(age=2, name=u'Alice'), Row(age=5, name=u'Bob')]
    475         """
--> 476         return self.limit(num).collect()
    477
    478     @since(1.3)

/usr/local/python/pyspark/sql/dataframe.py in collect(self)
    436         """
    437         with SCCallSiteSync(self._sc) as css:
--> 438             port = self._jdf.collectToPython()
    439         return list(_load_from_socket(port, BatchedSerializer(PickleSerializer())))
    440

/usr/local/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py in __call__(self, *args)
   1131         answer = self.gateway_client.send_command(command)
   1132         return_value = get_return_value(
-> 1133             answer, self.gateway_client, self.target_id, self.name)
   1134
   1135         for temp_arg in temp_args:

/usr/local/python/pyspark/sql/utils.py in deco(*a, **kw)
     67                                              e.java_exception.getStackTrace()))
     68             if s.startswith('org.apache.spark.sql.AnalysisException: '):
---> 69                 raise AnalysisException(s.split(': ', 1)[1], stackTrace)
     70             if s.startswith('org.apache.spark.sql.catalyst.analysis'):
     71                 raise AnalysisException(s.split(': ', 1)[1], stackTrace)

AnalysisException: 'Attribute name "Foo Bar" contains invalid character(s) among " ,;{}()\\n\\t=". Please use alias to rename it.;'

A: Have you tried,
df = df.withColumnRenamed("Foo Bar", "foobar")

When you select the column with an alias you're still passing the wrong column name through a select clause.

A: I tried @ktang 's method and it worked for me as well. I'm working with SQL and Python, so it may be different for you, but it worked nonetheless.
Ensure there are no spaces in your column names/headers. Despite the list of characters provided in the error message, space ( ) doesn't seem to be acceptable by Pyspark.
I was initially using:
master_df = spark.sql(f'''
SELECT occ.num, 'Occ Event' AS `Event Type`,
...

Changing the space ( ) in Event Type to an underscore (_) worked:
master_df = spark.sql(f'''
SELECT occ.num, 'Occ Event' AS `Event_Type`,
...

A: quick solution..
from pyspark.sql.functions import col

df = df.select([col(c).alias(
        c.replace( '(', '')
        .replace( ')', '')
        .replace( ',', '')
        .replace( ';', '')
        .replace( '{', '')
        .replace( '}', '')
        .replace( '\n', '')
        .replace( '\t', '')
        .replace( ' ', '_')
    ) for c in df.columns])

A: It was fixed in Spark 3.3.0 release (I tested).


text:
Q: Show only HTML elements that fit fully in the parent div? (Includes JsFiddle example) JS Fiddle Example

I have a div which contains user generated HTML elements. Each line in the div can be any number of characters, but displays only on one line, and does not wrap. My issue is that partial elements are shown vertically, and due to the variety of HTML elements, I cannot anticipate exactly how many lines of text can fit.
The image below shows the issue, in this case using only list item elements (highlighted with a red arrow.) I've included the HTML and CSS are below as well.
I have been looking for a ReactJS compatible solution to prevent element that do not fit completely from being displayed (I'm open to nearly anything CSS, NPM module, JavaScript snippets, just no jQuery.) All elements needs to remain at a static size, so dynamically resizing the text or container is also not suitable unfortunately.
The solution need only work in Chrome.
Unfortunately despite hours and hours searching for solutions in the form of modules on NPM or CSS solutions such as -webkit-line-clamp, I've found nothing suitable. -webkit-line-clamp will only work (as far as I can tell) on text within a single element, so it will fix a paragraph with 5 lines, but it will not fix 5 single line paragraphs.
Any ideas on how to solve this would be appreciated greatly. I've been struggling with this for months. Thank you very much for reading.


text:
Q: Default value along with uniqueness validation I have a Path model with name attribute as unique. I want to set default value as '/'
 to the same.
I have done in the following manner.
class Path < ActiveRecord::Base
  attr_accessible :name

  validates :name, presence: true, uniqueness: true

  before_validation :set_default_path

  private

  def set_default_path
    self.name = name.presence || '/'
  end
end

Domain model is designed as:
class Domain < ActiveRecord::Base
  attr_accessible :name, path_id

  validates :name, :path_id, presence: true
  validates :name, uniqueness: {scope: :path_id}
end

But this doesn't work for consecutive inserts with a blank name for path.
path = Path.find_or_create_by_name('')

domain = Domain.new(name: 'stackoverflow.com')
domain.path = path
domain.save!  # Fails with validation error
 ActiveRecord::RecordInvalid:
   Validation failed: Path can't be blank

Is there a robust way to achieve this ?

A: You should remove following callback
before_validation :set_default_path

and use validation for name as following:--
validates :name, presence: true, uniqueness: true, :if => 'name.present?'

and write a migration file to add default value to name attribute of paths table as either of followings:--
change_column :paths, :name, :string, :default => '/'

or
change_column_default :paths, :name, '/'

A: add condition on validation:
validates :name, presence: true
validates :name, uniqueness: true, unless: proc { |e| e.name == "/" }


text:
Q: A button fires another created one by Javascript I am currently working on a project using javascript and Django but I'm facing a problem that is that the inbox, sent, or archive button fires any other buttons upon clicking. EX: when I click on the inbox button it shows me the mails in the inbox but if I click on "click here" button to view the content of the mail it doesn't work although when I eliminate the inbox button and click on "click here " button directly it works.
in script:

  // Use buttons to toggle between views
  document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox'));
  document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent'));
  document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive'));
  document.querySelector('#compose').addEventListener('click', compose_email);

  // By default, load the inbox
  load_mailbox('inbox');
});

function compose_email() {

  // Show compose view and hide other views
  document.querySelector('#emails-view').style.display = 'none';
  document.querySelector('#compose-view').style.display = 'block';

  // Clear out composition fields
  document.querySelector('#compose-recipients').value = '';
  document.querySelector('#compose-subject').value = '';
  document.querySelector('#compose-body').value = '';
}

function load_mailbox(mailbox) {

  // Show the mailbox and hide other views
  document.querySelector('#emails-view').style.display = 'block';
  document.querySelector('#compose-view').style.display = 'none';

  // Show the mailbox name
  document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`;
}

document.addEventListener('DOMContentLoaded', function() {

  document.querySelector('#compose-view').onsubmit = function() {
    fetch('/emails', {
      method: 'POST',
      body: JSON.stringify({
          recipients: document.querySelector('#compose-recipients').value,
          subject: document.querySelector('#compose-subject').value,
          body: document.querySelector('#compose-body').value,
      })
    })
}
});

function email(emails) {
  let emaill = document.querySelector("#emails-view");
  let inboxdiv = document.createElement('div');
    let inboxtable = document.createElement('table')
    let divAttr = document.createAttribute('id');
        inboxdiv.setAttributeNode(divAttr);
        inboxdiv.setAttribute('id', `ok`)
    emails.forEach(email => {
        if (email['sender'] !== ''){

        let id = email.id
        let newtr = document.createElement("tr");
        let myAttr = document.createAttribute("id");
        newtr.innerHTML = `${email['subject']}
        ${email['sender']}
        ${email['timestamp']}
        `;
        let newbutton = document.createElement("button")
        let nerAttrbutton = document.createAttribute("id");
        newbutton.setAttributeNode(nerAttrbutton);
        newbutton.setAttribute('id', `${id}`);
        newbutton.innerHTML='click Here';
        inboxdiv.appendChild(newbutton);
        newtr.setAttributeNode(myAttr);
        newtr.setAttribute("id", `o${id}`);
        inboxtable.appendChild(newtr);
        inboxdiv.appendChild(inboxtable);
        emaill.appendChild(inboxdiv);
      ;
        }
      }

  );

            };

document.addEventListener('DOMContentLoaded', function() {
  document.querySelector('#inbox').addEventListener('click',function(){
  fetch('/emails/inbox')
  .then(response => response.json())
  .then(emails =>email(emails)

)});

document.querySelector('#sent').addEventListener('click',function(){
  fetch('/emails/sent')
  .then(response => response.json())
  .then(emails =>email(emails)

)});

document.querySelector('#archived').addEventListener('click',function(){
  fetch('/emails/archive')
  .then(response => response.json())
  .then(emails =>email(emails));

});
  });

document.addEventListener('DOMContentLoaded', function() {
window.addEventListener('load',function (){

  let theemailview = document.querySelector('#emails-view');
theemailview.querySelectorAll('button').forEach(button => {
  button.addEventListener('click', function (){

    var email_id = button.id
    fetch('/emails/' + email_id)
    .then(response => response.json())
    .then(email => {
    // Print email

                // ... do something else with email ...
              let emailsview =document.querySelector('#emails-view');
              let newmaildiv = document.createElement('div');
              newmaildiv.innerHTML = `
${email['subject']}

${email['sender']}

${email['body']}

${email['timestamp']}
<button id='reply'>Reply</button><button id='archive'>Archive</button>`
              emailsview.appendChild(newmaildiv);
              let reply = document.querySelector('#reply');
              let emmailview = document.querySelector('#emails-view')
                reply.addEventListener('click', function (){
                  let replydiv = document.createElement('div');
                  replydiv.innerHTML = `
Reply

                  <form>

                          From: <input disabled class="form-control" id='reply-sender' value="${email['recipients']}">

                          To: <input disabled class="form-control" id='reply-recipient' value='${email['sender']}'>

                          <input class="form-control" placeholder="Subject" id='reply-subject' value='Re:${email['subject']}'>

                      <textarea class="form-control"  placeholder="Body" id='reply-body'></textarea>
                      <input type="submit" id='reply-submit' class="btn btn-primary"/>
                  </form>`
                  let replyAttrbutton = document.createAttribute("id");
                replydiv.setAttributeNode(replyAttrbutton);
                replydiv.setAttribute('id', 'reply-div');
                  emmailview.appendChild(replydiv);

                  document.querySelector('#reply-div').onsubmit = function() {
                    fetch('/emails', {
                      method: 'POST',
                      body: JSON.stringify({
                          recipients: document.querySelector('#reply-recipient').value,
                          subject: document.querySelector('#reply-subject').value,
                          body: document.querySelector('#reply-body').value,
                      })})};
                });

                let archive = document.querySelector('#archive');
                archive.addEventListener('click',function(){
                  fetch('/emails/' + email_id , {
                    method: 'PUT',
                    body: JSON.stringify({
                        archived: true
                    })
                  })
                })
              })
  });

});
})
});

HTML page:
{% extends "mail/layout.html" %}
{% load static %}

{% block body %}

{{ request.user.email }}

    <button class="btn btn-sm btn-outline-primary" id="inbox">Inbox</button>
    <button class="btn btn-sm btn-outline-primary" id="compose">Compose</button>
    <button class="btn btn-sm btn-outline-primary" id="sent">Sent</button>
    <button class="btn btn-sm btn-outline-primary" id="archived">Archived</button>
    Log Out

New Email

        <form id="compose-form">

                From: <input disabled class="form-control" value="{{ request.user.email }}">

                To: <input id="compose-recipients" class="form-control">

                <input class="form-control" id="compose-subject" placeholder="Subject">

            <textarea class="form-control" id="compose-body" placeholder="Body"></textarea>
            <input type="submit" class="btn btn-primary"/>
        </form>

{% endblock %}

{% block script %}

{% endblock %}

I'm using fetch to import data from django models.
Here is the full project: https://github.com/mostafamohamed198/CS50W-mail.git
so what is the problem?


text:
Q: Golang Mongodb insertOne returns empty ID ObjectID("000000000000000000000000") I am using Go with MongoDB and creating a New Record but when I convert the insertedID to string it returns ObjectID("000000000000000000000000").
client := connect()
db := client.Database("godb")
// fmt.Println(db)

usersCollection := db.Collection("users")

result, err := usersCollection.InsertOne(ctx, bson.D{
    {Key: "title", Value: "The Polyglot Developer Podcast"},
    {Key: "author", Value: "Nic Raboy"},
})

if err != nil {
    log.Fatal(err)
}

newID := result.InsertedID
fmt.Println("InsertOne() newID:", newID)
fmt.Println("InsertOne() newID type:", reflect.TypeOf(newID))

oid, _ := newID.(primitive.ObjectID)
fmt.Println(oid)

OUTPUT
InsertOne() newID: ObjectID("5e947e7036a5c1587fa4a06e")
InsertOne() newID type: primitive.ObjectID
ObjectID("000000000000000000000000")

A: You must specify omitempty for the ID!
type User struct {
    ID primitive.ObjectID `json:"_id,omitempty" bson:"_id,omitempty"`
}


text:
Q: Standard and Best practice in dealing with Muliple/Complex Columns with Forms I've want to know what is the best practice or approach in dealing with multiple and complex columns with a form inside.
here's an example of the form I'm dealing with

How to properly write a HTML markup for this? If I wrap every form element with a 'DIV' for every column it would take a lot 'DIVs' and styles; and the width for every column that is not repeating.
So what I did is, I put all form element in the table. And I think that is not the standard way to do it.
If your in my shoes,
How would you deal with the columns with non-repeating width?

A: There is no standard for complex forms, but there are plenty of blog posts claiming to have figured out the perfect way to approach this problem. Most of them are well thought out, but ultimately you have to pick the one you're most comfortable with. I have some suggestions though:

*

*Check out the US postal service change of address form. It's surprisingly well done

*If you have lots of forms, using a grid system like 960.gs, blueprint.css, or YUI grids (shudder) is an easy way to implement a form. However grid systems are definitely considered bloat if that's the only place you'll use them.

*

*Do a search for "tableless forms" on Google. You will see a lot of different implementations. Choose the one you like.

A: I would probably put each form element in a list item within an unordered list (I think semantically, it is a list of input elements that need to be filled in.)
I would then add classes to them for positioning and width etc - the columned ones would need to be given a width and floated left...
so:

Full name:<input name="name"/>

Email:<input name="email"/>

   etc etc...

I believe this would be semantically correct and the most accessible way to do it.


text:
Q: Asp.net MVC ReportViewer ,IIS 7 issue I use asp.net mvc 2, added webform with reportviewer controls.
The web.config file looks
     <add verb="*" path="Reserved.ReportViewerWebControl.axd" type = "Microsoft.Reporting`enter code here`.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b0`enter code here`3f5f7f11d50a3a" />

    <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />

  <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
    <add name="Reserved.ReportViewerWebControl.axd" path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode" />

IIS is configured as a link
http://otkfounder.blogspot.com/2007/11/solving-reportviewer-rendering-issue-on.html
But I still have the error

            Report Viewer Configuration Error
        The Report Viewer Web Control HTTP Handler has not been registered in the application's web.config file.  Add <add verb="" path="Reserved.ReportViewerWebControl.axd" type = "Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> to the system.web/httpHandlers section of the web.config file, or add <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> to the system.webServer/handlers section for Internet Information Services 7 or later.

A: Here's what we have - it should support both IIS 6 and IIS7+
I think you've got a reference to v9 of Reserved.ReportViewerWebControl.axd (Reporting Services 2005)
<system.web>
    <compilation debug="true" targetFramework="4.0">
        <assemblies>
                                <etc />
            <add assembly="Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
            <add assembly="Microsoft.ReportViewer.Common, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
        </assemblies>
                        <!-- Edit Unsure as to whether this is needed, or should be Microsoft.ReportViewer.Webforms. Was upgraded from RDLC v9 -->
        <buildProviders>
            <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
        </buildProviders>
    </compilation>

    <!-- NB : The below is for earlier IIS -->
    <httpHandlers>
        <add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" validate="true"/>
    </httpHandlers>

</system.web>
<system.webServer>
    <!-- NB : The below is for IIS 6+ W2008 Server / Vista -->
    <handlers>
        <add name="Reserved-ReportViewerWebControl-axd" path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" resourceType="Unspecified" preCondition="integratedMode"/>
    </handlers>
</system.webServer>

Edit : Note that as of v10 the RdlBuildProvider is now in Microsoft.ReportViewer.WebForms not in Microsoft.ReportViewer.Common


text:
Q: Getting code coverage of my application using JaCoCo Java agent on Tomcat I want to measure the code coverage of integration tests using the JaCoCo and Sonar tools.
For that, I start my Tomcat 5.5 configured with the JaCoCo agent in order to get the dump file from JaCoCo.
Thus, I set the JAVA_OPTS for that:
set JAVA_OPTS=-Xrs -XX:MaxPermSize=256m -XX:PermSize=256m -XX:NewRatio=3 -Xms512m -Xmx1024m -XX:+UseParallelGC -javaagent:C:\dev\servers\jacoco-agent.jar=destfile=C:\dev\servers\jacoco.exec,append=true,includes=my.application.*

When I start Tomcat, the C:\dev\servers\jacoco.exec file is generated, but no data is filled.
Is there something I forgot in the configuration of my server?
Regards.

A: As far as I remember - file would be populated during shutdown of Tomcat.

A: Besides the maven solution, you can also consider https://www.eclemma.org/jacoco/trunk/doc/cli.html
Basically, you start your service on the remote machine with the javaagent option like (you can change the port number and omit includes if you want to have coverage for all of the classes):
-javaagent:/tmp/jacocoagent.jar=port=36320,destfile=jacoco-it.exec,output=tcpserver,includes=a.b.c.d.*"
Then connect to the remote machine by providing remote host address or open a tunnel to the remote machine.  The following example assumes I have set up a port forwarding between local host's 36320 and remote host's 36320
java -jar jacococli.jar dump  --port 36320 --destfile /tmp/jacoco-it.exec
If you have multiple .exec files, you need to merge them:
java -jar jacococli.jar merge /tmp/jacoco-it-1.exec /tmp/jacoco-it-2.exec --destfile  /tmp/merge
Then generate the html report (path1 can be a path to the jar file or the class files folder)
java -jar jacococli.jar report /tmp/jacoco-it.exec --classfiles path1 --sourcefiles path2 --html /tmp/report

A: I realize this may not have been an option 2 years ago when this question was asked, but presently you have some other options available to fetch the JaCoCo execution data without shutting down Tomcat (or any JVM instrumented with the JaCoCo java agent).
First take a look at the current documentation for the JaCoCo Java Agent:  http://www.eclemma.org/jacoco/trunk/doc/agent.html
You can use the output=tcpserver option on the JaCoCo agent to have the Java agent listen for commands.  You can set address=* to have the tcpserver listen on all interfaces, and you can set the port=6300 argument to choose the port where the tcpserver should listen.
Through the tcpserver the JaCoCo java agent can be instructed to send you the data whenever you ask for it.
If your JVM is currently exposing JMX you have another option which you can utilize without opening additional ports. By setting the jmx=true option the JaCoCo java agent exposes an MBean which you can interact with.
If you are using maven you can take a look at the plugin I recently wrote in order to gather JaCoCo data from remote JVM's while running.  The project for the plugin is located at:
https://github.com/mattcj/jacocotogo


text:
Q: How to save date value in dd/mm/yyyy into excel from SSIS where TimeZone=Eastern in server I have an SSIS package, which I am running a Stored Procedure and save the resultset in a object type of variable (as temptable) in the control flow, and in the data flow I am using a script to retrieve data from the object type of variable saving the result set in an excel file.
Everything works well except the date column. It should be in dd/mm/yyyy format, however whatever I have tried I could not prevent it to be in m/d/yyyy format in the excel.
What I have tried are:
1- Added this to connectionstring of Excel ConnectionManager -> Excel 12.0;HDR=Yes;IMEX=0;Readonly=False and Excel 12.0;HDR=Yes;IMEX=1;Readonly=False. Both did not work.
2- Added a Derived Column task, derived a new "DerivedMyDate" column as STR, WSTR, Date. Used this column to save the date value in the excel file, where type is set as STR and DATE. None of my trials worked.
3- Added Data Conversion task, tried all same things that I've tried in 2nd step, none worked.
4- Added a dummy first line in the excel, where the data column is like 15/01/1900. Does not work, it is adding the other rows below where date values in m/d/yyyy format.
Checked those pages, the answers did not work for me:
Date format problem using SSIS for Excel into SQL Server
https://social.msdn.microsoft.com/Forums/sqlserver/en-US/7e34a0af-a744-4a51-b925-3284d0fba296/problem-in-date-format-while-exporting-to-excel-destination-from-flat-file-source-in-ssis?forum=sqlintegrationservices
TimeZone of my PC: (UTC-05:00) Eastern Time (US & Canada), changing this is not an option.
Any help or advice would be appreciated.

A: I will try to propose a little modify a T-SQL query in a next solution for you.
At the step of extracting data from the Stored Procedure, if this one returns not many columns, you should declare a table variable with a names, types and columns count appropriated with your stored procedure columns, for example @var. Then you need to pass executed stored prococedure result in variable,
INSERT INTO @VAR
EXEC sp_your_stored_prodedure

At the last step you should retrieve data not from stored  procedure, but from @var, and to add in the select statement new field with CONVERT T-SQL function with date format 103 :
SELECT
      v.*
      ,CONVERT (NVARCHAR, v.date_field, 103) as target_date_format
FROM @var AS v

After this, you may work with this DataFlow and Date in the appropriate format.


text:
Q: R produces different result after IO on file As new to R, I have a question about writing and reading vector data.
My Example 1

n = 100
g = 6
set.seed(g)
d <- data.frame(x = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))),
                y = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))))
plot(d)
require(vegan)
fit <- cascadeKM(scale(d, center = TRUE,  scale = TRUE), 1, 10, iter = 1000)
plot(fit, sortg = TRUE, grpmts.plot = TRUE)
calinski.best <- as.numeric(which.max(fit$results[2,]))
cat("Calinski criterion optimal number of clusters:", calinski.best, "\n")

(source), it prints "Calinski criterion optimal number of clusters: 5" as expected.
Example 2: (write data frame d first, then read it)

n = 100
g = 6
set.seed(g)
d <- data.frame(x = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))),
                y = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i^2))))

write.table(d, "d.txt", sep='\t', quote=FALSE) #write data frame
d = read.table("d.txt", header=TRUE, sep = '\t') #read later
plot(d)

require(vegan)
fit <- cascadeKM(scale(d, center = TRUE,  scale = TRUE), 1, 10, iter = 1000)
plot(fit, sortg = TRUE, grpmts.plot = TRUE)
calinski.best <- as.numeric(which.max(fit$results[2,]))
cat("Calinski criterion optimal number of clusters:", calinski.best, "\n")

However, example 2 prints "Calinski criterion optimal number of clusters: 1".
I think the format (or something else) has been changed after IO from file in R. But i have no knowledge about how R read and write numbers. Can anyone give me some clues, thanks.
EDIT
If the file is written without col name and row name, problem solved.

write.table(d, "d.txt", sep='\t', quote=FALSE, row.name=FALSE, col.names=FALSE)

When reading, R also reads the row and col names,.
Another is to escape those names when reading.

A: The Calinski index cannot be calculated for one group, but it becomes either Inf or -Inf. In the first example it happened to be -Inf, and in the second it happened to be Inf and when you looked for which.max, Inf was what you got. I do not know why we actually bother to calculate the index for one-class case, but if you search for the best result, you should ignore the first case. We do so in the plot command which gives five clusters as the best result in both cases. The following modification of your code will give the same answer in both cases:
calinski.best <- as.numeric(which.max(fit$results[2,-1])) + 1
cat("Calinski criterion optimal number of clusters:", calinski.best, "\n")

We had to have +1 because we omitted one column.
Small details for the Inf/-Inf indeterminacy. As you see in ?cascadeKM, Calinski criterion is defined as (SSB/(K-1))/(SSW/(n-K)) and for one group K=1 so that SSB/0 = Inf. For one group also SSB=0, but that is computed zero and these are rarely exact in digital computers, and in my computer zero is -2.8e-14 and -2.8e-14/0 = -Inf. In the second example SSB=2.8e-14 and 2.8e-14/0 = Inf. Just ignore the first column when you look for the optimum. Occasionally SSB can be exact zero and then 0/0 = NaN (not a number).


text:
Q: Embedding $\mathbb{Q}$ with the usual topology into a power of the two point discrete space? I came across this question and I don't have any idea where to start, so any help would be greatly appreciated!
The question is as follows: "Prove that $\mathbb{Q}$ with its usual topology can be embedded into a power of the two point discrete space".
I thought for a moment to look at it from a categorical product point of view but this got a little messy so is there something I am overlooking or an easier way to approach this?
Many thanks!

A: You have a countable family of maps $\mathcal C:=\{f_{n,q}:\mathbb Q\to\{0,1\}\mid n\in\mathbb N,q\in\mathbb Q\}$ where $f_{n,q}$ is the characteristic function of the open interval with radius $1/n$ centered at $q$. This family separates points and $\mathbb Q$ has the initial topology with respect to this family. The embedding theorem then implies that the evaluation map $e:\mathbb Q\to\{0,1\}^{\mathcal C}$ which is defined $e(x)(f)=f(x)$ is an embedding.

A: I will give an embedding of $\mathbb Q\cap (0,1)$ into $2^{\mathbb N}$.
$\mathbb Q $ is homeomorphic to $\mathbb Q\cap (0,1)$, so it is enough to embed the latter set.
Let $\alpha$ be irrational. Map each $q\in \mathbb Q\cap [0,1]$ to the binary representation of $q+\alpha$ mod 1, i.e., to the binary representation of the fractional part of $q+\alpha$.
(Note that the natural map from $2^{\mathbb N}\setminus A$ onto $Q\cap [0,1]\setminus B$ is a homeomorphism if you let $A$ and $B$ be the "dyadic rationals".)


text:
Q: Error handling of batch script with adb commands I want to make a simple batch script to install apk on android device. I can do this if Debugging is on and Device drivers are installed.
When device drivers are not installed it show error device not found and when debug acces is not allowed it show please allow usb debug from device.
I want to know how i can switch between these errors i want to start adbdriverinstaller.exe if no drivers are installed and if it requires usb debug access then just echo please allow usb debug access form mobile.
Here is my code
@ECHO off

echo Writing Configuration...

adb push Config.cfg /sdcard/Config.cfg
if errorlevel 1 echo Failed with error #%errorlevel%.

//here i want to switch between error types (if no device found error or allow usb debug access error)

if errorlevel 1 start "" AdbDriverInstaller.exe
if errorlevel 1 PAUSE
if errorlevel 1 EXIT

echo Installing Apk...
adb install -r myApk.apk

echo opening apk

adb shell am start -n com.myApk.myApk/.myApkActivity

PAUSE

what i want to do is
if
error: device not found
error: device not found

error arises then simply open adbdriver installer and if
error: device unauthorized. Please check the confirmation dialog on your device.

error: device unauthorized. Please check the confirmation dialog on your device.

Error arises than simply display please allow USB debug access from mobile.

A: ADB on its own does not tell why it could not find the device. But you could use powershell "gwmi Win32_USBControllerDevice" to get status of USB devices in Windows. This allows you to find all enumerated adb interfaces and check whether they have appropriate drivers installed. For details read adb device detection in Windows


text:
Q: Send TitleLabel from UIButton to a UILabel in a different UIView Controller, But it's not being sent I have one UIViewController that I am trying to send the titleLabel of a UIButton to a UILabel held within a different UIView Controller.
I have followed the same steps and pattern as within a previous method that worked fine, but the Title Text is just not getting passed onto the next VC.
I have a Button class called MtsCardsButton, but this just sets the animation and appearance of the button.
Thank you for reviewing.
Here is my code for the Button in the first VC:
import UIKit

class MTSCardsPage: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    //This is to make mtsCardsSetArray available to this ViewController
    let otherVC = MTSDiscriminators()
    mtsCardsSetArray2 = otherVC.mtsCardsSetArray

    let otherVC2 = MTSDiscriminators()
    allMtsDescriminatorsArray2 = otherVC2.allMtsDescriminatorsArray

    //Set Card Titles from Array
    Card1ButtonOutlet.setTitle(mtsCardsSetArray2[0], for: .normal)
    Card2ButtonOutlet.setTitle(mtsCardsSetArray2[1], for: .normal)
    Card3ButtonOutlet.setTitle(mtsCardsSetArray2[2], for: .normal)
    Card4ButtonOutlet.setTitle(mtsCardsSetArray2[3], for: .normal)
    Card5ButtonOutlet.setTitle(mtsCardsSetArray2[4], for: .normal)

    //Do any additional setup after loading the view.

}

var mtsCardsButton = MtsCardsButton()

func addActionToMtsCardsButton() {
     mtsCardsButton.addTarget(self, action: #selector(CardButton), for: .touchUpInside)

 }

//This is to TELL the Button to do something AND to goto
//the MTS Discriminators UIView.

var cardButtonPressed = ""

@IBAction func CardButton(_ sender: MtsCardsButton) {
    let secondVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "DiscrimUIViewCollection") as! DiscrimUIViewCollection
   cardButtonPressed = sender.currentTitle!
    secondVC.updateTheLabel2 = cardButtonPressed

   ////I'VE TRIED THIS SECTION INSTEAD OF ABOVE AND IT STILL DOESN'T WORK.

//        func prepare(for segue: UIStoryboardSegue, sender: Any?)
//    {
//        if segue.destination is DiscrimUIViewCollection
//        {
//            let vc = segue.destination as? DiscrimUIViewCollection
//            vc?.updateTheLabel2 = cardButtonPressed
//        }
//    }

    //switch area to make button move when pressed
    switch cardButtonPressed {
    case mtsCardsSetArray2[0]:
        Card1ButtonOutlet.shakeMtsCardsButton()
    case mtsCardsSetArray2[1]:
        Card2ButtonOutlet.shakeMtsCardsButton()
    case mtsCardsSetArray2[2]:
        Card3ButtonOutlet.shakeMtsCardsButton()
    case mtsCardsSetArray2[3]:
        Card4ButtonOutlet.shakeMtsCardsButton()
    case mtsCardsSetArray2[4]:
        Card5ButtonOutlet.shakeMtsCardsButton()
    default:
        print("Error, unrecognised button pressed!")
    }

    guard let destinationVC = storyboard?.instantiateViewController(withIdentifier: "DiscrimUIViewCollection") as? DiscrimUIViewCollection else {
        return
    }
    present(destinationVC, animated: true, completion: nil)

}

 //Outlet for sending anything to the MTS Card Button
 @IBOutlet weak var Card1ButtonOutlet: MtsCardsButton!
 @IBOutlet weak var Card2ButtonOutlet: MtsCardsButton!
 @IBOutlet weak var Card3ButtonOutlet: MtsCardsButton!
 @IBOutlet weak var Card4ButtonOutlet: MtsCardsButton!
 @IBOutlet weak var Card5ButtonOutlet: MtsCardsButton!

}

Here is the code for the second receiving VC:
class DiscrimUIViewCollection: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

@IBOutlet weak var discriminatorTitle: UILabel!

var updateTheLabel2: String?

@IBAction func discrimButtonPressed(_ sender: UIButton) {
    //action here to name what discriminator means.
    print(sender.currentTitle!)
}

@IBOutlet weak var collectionView: UICollectionView!

override func viewDidLoad() {
    super.viewDidLoad()

    Card1ButtonOutlet.setTitle(mtsCardsSetArray2[0], for: .normal)
    Card2ButtonOutlet.setTitle(mtsCardsSetArray2[1], for: .normal)
    Card3ButtonOutlet.setTitle(mtsCardsSetArray2[2], for: .normal)
    Card4ButtonOutlet.setTitle(mtsCardsSetArray2[3], for: .normal)
    Card5ButtonOutlet.setTitle(mtsCardsSetArray2[4], for: .normal)

    collectionView.dataSource = self
    collectionView.delegate = self
    self.collectionView.backgroundColor = .black

        discriminatorTitle.text = updateTheLabel2
        discriminatorTitle.font = UIFont(name: "Mukta Mahee", size: 18)
        discriminatorTitle.font = UIFont.boldSystemFont(ofSize: 18)
        discriminatorTitle.numberOfLines = 2
        discriminatorTitle.minimumScaleFactor = 0.1
        discriminatorTitle.baselineAdjustment = .alignCenters
        discriminatorTitle.textAlignment  = NSTextAlignment.center
        discriminatorTitle.clipsToBounds = true
        discriminatorTitle.backgroundColor = colourYellow
        discriminatorTitle.textColor = .black
        discriminatorTitle.layer.borderColor = UIColor.black.cgColor
        discriminatorTitle.layer.borderWidth = 2.0
        discriminatorTitle.layer.cornerRadius = 7
        discriminatorTitle.layer.shadowColor = UIColor.black.cgColor
        discriminatorTitle.layer.shadowOffset = CGSize(width: 0.0, height: 6.0)
        discriminatorTitle.layer.shadowRadius = 7
        discriminatorTitle.layer.shadowOpacity = 0.5
        discriminatorTitle.clipsToBounds      = false
        discriminatorTitle.layer.masksToBounds  = true

let layout = self.collectionView.collectionViewLayout as! UICollectionViewFlowLayout
layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)
layout.minimumInteritemSpacing = 2
layout.itemSize = CGSize(width: (self.collectionView.frame.size.width - 0)/1, height:self.collectionView.frame.size.height/3)
      //Do any additional setup after loading the view.

func numberOfSections(in collectionView: UICollectionView) -> Int {
       // 1
       return 1
   }
  }

A: So, after many hours of studying up various websites I found the answer. I needed to add code and re-position the code. I Changed the Storyboard ID to match the DiscrimUIViewCollection.swift file.
I place the following code at the bottom of the 'switch' statement in the MTSCardsPage.swift file.
    //To capture the card title and store it for
       //preparation for changing based on Label.

    guard let DiscrimUIViewCollection : DiscrimUIViewCollection = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DiscrimUIViewCollection") as? DiscrimUIViewCollection else {
        return
    }
    DiscrimUIViewCollection.updateTheLabel = sender.currentTitle!

    present(DiscrimUIViewCollection, animated: true, completion: nil)

}

And to my delight, it all works fine!
The website I used to help me the most was this one:
https://fluffy.es/3-ways-to-pass-data-between-view-controllers/
Thanks for your assistance guys, each little comment made me think.
It's big learning curve!


text:
Q: External @context files for "composite" JSON objects? TL;DR:
Given that:

*

*Ca is a JSON-LD @context file that describes JSON object A;

*Cb is a JSON-LD @context file that describes JSON object B;

*Every B JSON object contains an element whose assigned value is an A object;

1) How can/should this relationship between A and B be described in Cb? Is it a @type, an @id, an inner @context?
2) If an A object, when used as value in a B object, could also mean something described in a vocabulary such as schema.org, how should both relationships of A be described in Cb?

Some users of my API don´t want metadata at all, so I have pure JSON as default response format, and I would like to use JSON-LD @context files as a simple syntactic and semantic schema, should users want one, according to https://www.w3.org/TR/json-ld/#interpreting-json-as-json-ld .
If I got it correctly, if I have a simple data structure which uses primitive types, the JSON-LD file will be something simple -- like this, for defining a certain part of an event:
{
  "@context": {
    "schema": "http://schema.org/docs/schema_org_rdfa.html",
    "xsd": "http://www.w3.org/2001/XMLSchema#",
    "titulo": {
      "@id": "schema:name",
      "@type": "xsd:string"
    },
    "dataHoraInicio": {
      "@id": "schema:startDate",
      "@type": "xsd:dateTime"
    },
    "dataHoraFim": {
      "@id": "schema:endDate",
      "@type": "xsd:dateTime"
    }
  }
}

But some of my JSON structures have some other structures embedded into them. In other words: in some of my JSON structures, there are elements which receive as values some other of my API´s JSON structures. The representation of a speech, for example, might have as part of it an element named "momento", and its value would be the above mentioned structure which represents a part of an event.
If so, how should I represent this "composition" relation between entities in an external JSON-LD @context file? How should I describe what "momento" is and the kind of value it receives in the JSON-LD @context file?
Browsing other questions here, I found that there is no problem in an external @context being referred to by another @context file. But do I have to use the other file´s URL as the value for @id? Or for @type? Or in a completely different way than that used for the primitive datatypes?
And what if some of these nested/referred data structures should also be classified with a vocabulary term? For example, I would like to express that "momento" can be understood as schema.org´s "Event", and at the same time I would like to express that the object it takes as value is described in another JSON-LD file.
Thank you very much!


text:
Q: GeoNode credentials not valid for OGC services I have GeoNode 2.6.3 installed in ubuntu 16.04 server (standard instalation). The web portal works fine with authentications, view and download permissons, etc. But when i try to access via WFS/WMS services on QGis, Geonode credetials are not valid. I can access with no credentials and see the public layers, and i can access using the geoserver credentials, but not with geonode ones (tried with diferent users).
geoserver.log file shows:
2017-11-13 12:14:47,164 WARN [geofence.cache] - org.geoserver.geofence.cache.CachedRuleReader$NoAuthException: Can't auth user [gpadmin]

(gpadmin is the geonode admin username)
Geofence configuration is as default, and not service security rules added. I can access geoserver adminUI with geonode credentials.
I´ve read this link too but can´t figure out the problem.
Any ideas or tips to find the problem?


text:
Q: Xamarin lowering video size i want to "compress" videos (for upload) in Xamarin (iOS).
I found out about the AVAssetWriter Class and i red that you could set the resolution, bitrate etc.
How would you use it? Which other classes?
As you may already noticed, im very new to app development.

A: Here is a sample using AVAssetReader to feed AVAssetWriter to re-sample and/or transcode a video.
In this example, I am taking a video named "Pool.mp4" that was included in app bundle (BundleResource) and saving into the "tmp" directory as "NewVideo.mp4" at a size of 300x300 at 1Mbps (reducing the original file size by ~50%...)
Note: No return values or error codes are being checked, that is left up to the implementor.
var asset = AVAsset.FromUrl(NSUrl.FromFilename("Pool.mp4"));
NSError assetReaderError;
var assetReader = AVAssetReader.FromAsset(asset, out assetReaderError);
var assetTrack = asset.Tracks.First();
var inputSettings = new AVVideoSettingsUncompressed()
{
    Height = 300,
    Width = 300,
};
var assetReaderOutput = new AVAssetReaderTrackOutput(assetTrack, settings: inputSettings);
assetReaderOutput.AlwaysCopiesSampleData = false;

string tempFile = Path.Combine(Path.GetTempPath(), "NewVideo.mp4");
if (File.Exists(tempFile)) File.Delete(tempFile);
var url = NSUrl.FromFilename(tempFile);
NSError assetWriterError;
var assetWriter = new AVAssetWriter(url, AVFileType.Mpeg4, out assetWriterError);
var outputSettings = new AVVideoSettingsCompressed()
{
    Height = 300,
    Width = 300,
    Codec = AVVideoCodec.H264,
    CodecSettings = new AVVideoCodecSettings
    {
        AverageBitRate = 1000000
    }
};
var assetWriterInput = new AVAssetWriterInput(mediaType: AVMediaType.Video, outputSettings: outputSettings);
assetWriterInput.ExpectsMediaDataInRealTime = false;
assetWriter.AddInput(assetWriterInput);

assetWriter.StartWriting();
assetReader.AddOutput(assetReaderOutput);
assetReader.StartReading();
assetWriter.StartSessionAtSourceTime(CoreMedia.CMTime.Zero);

var mediaInputQueue = new DispatchQueue("mediaInputQueue");
assetWriterInput.RequestMediaData(mediaInputQueue, () =>
{
    while (assetWriterInput.ReadyForMoreMediaData)
    {
        var nextBuffer = assetReaderOutput.CopyNextSampleBuffer();
        if (nextBuffer != null)
        {
            assetWriterInput.AppendSampleBuffer(nextBuffer);
        }
        else
        {
            assetWriterInput.MarkAsFinished();
            assetWriter.FinishWritingAsync();
            assetReader.CancelReading();
            assetReader.Dispose();
            assetReaderOutput.Dispose();
            assetWriter.Dispose();
            assetWriterInput.Dispose();
            break;
        }
    }
});


text:
Q: C++ difference between automatic type conversion to std::string and char* As a learning exercise, I have been looking at how automatic type conversion works in C++.  I know that automatic type conversion should generally be avoided, but I'd like to increase my knowledge of C++ by understanding how it works anyway.
I have created a StdStringConverter class that can be automatically converted to a std::string, but the compiler (g++ 4.3.4 on Debian) seems not to do the conversion when the object is compared against a real std::string (please ignore the lack of passing-by-reference and unnecessary creation of temporary objects):
#include <string>

class StdStringConverter
{
public:
    explicit StdStringConverter(std::string name) : m_name(name) {}
    operator const std::string () const { return m_name; }
private:
    std::string m_name;
};

int main()
{
    StdStringConverter converter(std::string("Me"));
    const std::string name = "Me";
    // Next line causes compiler error:
    // no match for 'operator==' in 'converter == name'
    return (converter == name) ? 0 : 1;
}

On the other hand, if I change it slightly to a CStringConverter class, the automatic conversion does take place, although comparing char pointers probably isn't what I intended:
#include <string>

class CStringConverter
{
public:
    explicit CStringConverter(std::string name) : m_name(name) {}
    operator const char* () const { return m_name.c_str(); }
private:
    std::string m_name;
};

int main()
{
    CStringConverter converter(std::string("Me"));
    const char* name = "Me";
    // Next line compiles fine, but they are not equal because the
    // pointers don't match.
    return (converter == name) ? 0 : 1;
}

Is there something special about the difference between a std::string and a char* in this context that makes the compiler not treat them the same?

A: The problem is due to the fact std::string is actually an instance of the class template std::basic_string. An operator== that is available in namespace std takes two std::basic_string templates:

template<class charT, class traits, class Allocator>
bool operator==(const basic_string& lhs,
                const basic_string& rhs);

If this version of operator== was overloaded specifically on std::string, your code would be fine. But that's not the case, which would require the compiler to perform template argument deduction on the template parameters of std::basic_string so it could understand that the return of your conversion operator is a possible match.
However, the compiler won't do that. I don't know which part of the standard states this precisely. But the general idea is that such conversions work only for non-template types.
One thing I can suggest is for you to place StdStringConverter in a namespace and provide a version of operator== for std::string in that namespace. This way, when your compiler find an expression like that ADL (Argument Dependent Lookup) comes into play and everything works fine.

#include <string>

namespace n1 {

class StdStringConverter
{
public:
    explicit StdStringConverter(std::string name) : m_name(name) {}
    operator std::string () { return m_name; }
private:
    std::string m_name;
};

bool operator==(std::string const& a, std::string const& b)
{
  return a == b; //EDIT: See Paul's comment on std::operator== here.
}

}

int main()
{
    using namespace n1;
    StdStringConverter converter(std::string("Me"));
    std::string name = "Me";
    return (converter == name) ? 0 : 1;
}

A: In the first example the two compared classes (string and StdStringConverter) do not get any special treatment from the compiler for type converting.  That means the operator overload you made doesn't even get triggered.  The compiler looks through the list of operator== overloads and non of them take in a StdStringConverter so it yells at you.
In the second example the name is char *.  Since it is a primitive type then the compiler attempts to convert the non primitive down to a char *.  Since you have an override in place it works and you compare addresses.
The compiler will not explicit type cast on operations that don't include primitive types.  Something it will do is attempt to use constructors to make the types match.  For example if you change your first example to this:
#include <string>

class StdStringConverter
{
public:
    StdStringConverter(std::string name) : m_name(name) {}
    bool operator==(const StdStringConverter &name) { return m_name == name.m_name; }
    operator const std::string () const { return m_name; }
private:
    std::string m_name;
};

int main()
{
    StdStringConverter converter(std::string("Me"));
    const std::string name = "Me";
    // Next line causes compiler error:
    // no match for 'operator==' in 'converter == name'
    return (converter == name) ? 0 : 1;
}

Now the program returns 0.  Since the constructor is now not explicit the compiler will attempt to use it to convert the string to a StdStringConverter.  Since there is now an operator== in the StdStringConverter everything works.

A: There are multiple factors. If you change the return statement thusly
return (std::operator==(name, name)) ? 0 : 1;
it compiles, although it obviously does not do the same thing. On the other hand
return (std::operator==(converter, name)) ? 0 : 1;
does not but provides a more interesting error message
no matching function for call to 'operator==(StdStringConverter&, const std::string&)
which reminds me that operator== is templated on basic_string<>, which has three template parameters to boot. If you use int in your example rather than std::string, the compiler does not complain.
How to obtain the desired effect with std::string is more intriguing ...


text:
Q: Cannot output result at Python lines.first() from SparkContext I am writing my first test.py at spark.
Code
from pyspark import SparkConf, SparkContext

conf = SparkConf().setMaster("local").setAppName("My Test")
sc = SparkContext(conf = conf)

lines = sc.textFile("file:///home/hduser/spark-1.5.2-bin-hadoop2.6/README.md") # Create an RDD called lines

lines.count()
lines.first()

Output:

hduser@borischow-VirtualBox:~/spark-1.5.2-bin-hadoop2.6$ bin/spark-submit test.py
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/home/hduser/spark-1.5.2-bin-hadoop2.6/lib/spark-assembly-1.5.2-hadoop2.6.0.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/usr/local/hadoop/share/hadoop/common/lib/slf4j-log4j12-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.Log4jLoggerFactory]
15/12/28 17:42:46 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
****15/12/28 17:42:46 WARN Utils: Your hostname, borischow-VirtualBox resolves to a loopback address: 127.0.1.1; using 10.0.2.15 instead (on interface eth0)
15/12/28 17:42:46 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to another address
15/12/28 17:42:48 WARN Utils: Service 'SparkUI' could not bind on port 4040. Attempting port 4041.
15/12/28 17:42:48 WARN MetricsSystem: Using default name DAGScheduler for source because spark.app.id is not set.****
hduser@borischow-VirtualBox:~/spark-1.5.2-bin-hadoop2.6$

Questions:

*

*I cannot generate the expected output from lines.count() & lines.first(). Why?

*What are the reasons behind of the warning messages?

15/12/28 17:42:46 WARN NativeCodeLoader: Unable to load native-hadoop
  library for your platform... using builtin-java classes where
  applicable
15/12/28 17:42:46 WARN Utils: Your hostname, borischow-VirtualBox resolves to a loopback address: 127.0.1.1; using 10.0.2.15 instead (on
  interface eth0)
15/12/28 17:42:46 WARN Utils: Set SPARK_LOCAL_IP if you need to bind to >another address
15/12/28 17:42:48 WARN Utils: Service 'SparkUI' could not bind on port 4040. Attempting port 4041.
15/12/28 17:42:48 WARN MetricsSystem: Using default name DAGScheduler
  for source because spark.app.id is not set.

Thanks a lot!

A: You don't see an output because it is not count or first methods don't output anything to std.out.
Just use print:
from __future__ import print_function
from pyspark import SparkConf, SparkContext

conf = SparkConf().setMaster("local").setAppName("My Test")
sc = SparkContext(conf = conf)

lines = sc.textFile("file:///home/hduser/spark-1.5.2-bin-hadoop2.6/README.md")

print(lines.count())
print(lines.first())


text:
Q: Select Unique Record from List based on Particular value In Linq I am using LINQ. I have a list in which there some duplicate record based on a particular column value . I want to get unique record based on particular value from a list using Linq .
I am using distict method to get the unique record but it is not supported.
Here is my code.
        private List<CountOnlineUserModel> GetUserList()
        {

            List<CountOnlineUserModel> Users = new List<CountOnlineUserModel>();
            CountOnlineUserModel p = new CountOnlineUserModel();

            p.UserUniqueID = "IMW3";
            p.Username = "Rahul";
            Users.Add(p);

            p.UserUniqueID = "IMW4";
            p.Username = "Raheem";
            Users.Add(p);

            p.UserUniqueID = "IMW3";
            p.Username = "Rahul";
            Users.Add(p);

            p.UserUniqueID = "IMW4";
            p.Username = "Raheem";
            Users.Add(p);

            return Users;
        }

A: Try implementing IEquatable<CountOnlineUserModel> in CountOnlineUserModel.
public class CountOnlineUserModel : IEquatable<CountOnlineUserModel> {
    // ...

    public bool Equals(CountOnlineUserModel other) {
        return UserUniqueID == other.UserUniqueID;
        // use the above if you just want to compare the IDs. Use below if you want to compare both the ID and name
        return UserUniqueID == other.UserUniqueID &&
            Username == other.Username;
    }
}

Now you can do Distinct:
        CountOnlineUserModel p = new CountOnlineUserModel();

        p.UserUniqueID = "IMW3";
        p.Username = "Rahul";
        Users.Add(p);

        p = new CountOnlineUserModel();
        p.UserUniqueID = "IMW4";
        p.Username = "Raheem";
        Users.Add(p);

        p = new CountOnlineUserModel();
        p.UserUniqueID = "IMW3";
        p.Username = "Rahul";
        Users.Add(p);

        p = new CountOnlineUserModel();
        p.UserUniqueID = "IMW4";
        p.Username = "Raheem";
        Users.Add(p);
        Console.WriteLine(Users.Distinct());

A: You can do GroupBy:
return Users.GroupBy(c => c.UserUniqueID).Select(c => c.First()).ToList();

Make sure to add this on your using statements if you want to use GroupBy or Distinct:
using System.Linq;

A: You can use GroupBy().
List<CountOnlineUserModel> distinctOnlineUsers = GetUserList()
  .GroupBy(p => p.UserUniqueID)
  .Select(g => g.First())
  .ToList();

You can groups on multiple properties as well, can be done as follows:
List<CountOnlineUserModel> distinctOnlineUsers = GetUserList()
  .GroupBy(p => new {p.UserUniqueID, p.Username} )
  .Select(g => g.First())
  .ToList();

A: First of all, your sample data is messed up. You have created a list containing four references, all to the same object (whose properties you set once and then overwrite three times). Unless you are doing something pretty unusual, you have to instantiate a new object for each entry:
private List<CountOnlineUserModel> GetUserList()
{
    var users = new List<CountOnlineUserModel>
        {
            new CountOnlineUserModel
                {
                    UserUniqueID = "IMW3",
                    Username = "Rahul"
                },
            new CountOnlineUserModel
                {
                    UserUniqueID = "IMW3",
                    Username = "Rahul"
                },
            new CountOnlineUserModel
                {
                    UserUniqueID = "IMW4",
                    Username = "Raheem"
                },
            new CountOnlineUserModel
                {
                    UserUniqueID = "IMW3",
                    Username = "Rahul"
                }
        }
}

Second, I think you may be overthinking the problem. With the sample data you have provided, if you just want one of the records that matches on a particular value, you don't need distinct or group by.  Just take the first record that matches.
var record = users.Where( u => u.UserUniqueID == "IMW3" ).First();


text:
Q: How to fix Null Pointer Exception in Junit test? I'm getting a Null Pointer Exception as shown in the code when I run the following Junit test. Can someone please help me fix it?
import com.apexsct.pouservice.amq.inboxlistener.GetUpdateAvailablePositionInfo;
import com.apexsct.servcomm.amq.pouservice.dto.DeliveryPositionData;

public class GetUpdateAvailablePositionInfoActionTest {
    @Mock
    protected PositionRepository positionRepo;

    @Mock
    protected UserInterfaceGroupRepository uiGroupRepo;

    @InjectMocks
    private GetUpdateAvailablePositionInfo service;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testEmptyRequest() {
        DeliveryPositionData response = (DeliveryPositionData) service.perform(); // NULL POINTER EXCEPTION HERE
        assertEquals(ErrorMessageConstant.INVALID_REQUEST, response.getErrMsg());
    }

}

A: Based on your test name you want to test a case where the request is empty.
However you still need to supply an actual object, as your code does not
handle the case where request is null.
You could adjust the test to look like this:
public class GetUpdateAvailablePositionInfoActionTest {

    @Mock
    protected PositionRepository positionRepo;

    @Mock
    protected UserInterfaceGroupRepository uiGroupRepo;

    @Mock // creates and injects a mock for the request
    UpdAvlbPosRequest request;

    @InjectMocks
    private GetUpdateAvailablePositionInfo service;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testEmptyRequest() {

        // defines that the sn of the request is an empty string
        // (Depending on what StringUtils class you use, it might also handle null correctly.
        //  In this case this line can be removed)
        Mockito.when(request.getSn()).thenReturn("");

        DeliveryPositionData response = (DeliveryPositionData) service.perform();
        assertEquals(ErrorMessageConstant.INVALID_REQUEST, response.getErrMsg());
    }
}


text:
Q: What happens to a logical volume when a physical volume fails? I have recently run out of storage space on a server and would like to migrate to lvm to make handling this scenario easier in the future. I would like to combine all of my drives (not including OS drive) to a single logical volume so the entire available space can be mounted at a single mount point. In this scenario, I would create a single PV for each disk and create one VG for all of my PVs. I plan on using a single LV from my VG. In this way I can aggregate all the storage available into a single mount point.
What happens if one of my disks fail? Will all of the data in the LV be corrupted? Or will I only lose data associated with the PV for the failed disk? Losing data is not ideal, but this is also not critical data, I can tolerate some loss but would prefer not to lose everything.

A: If you create only a single LV and lose one of the disks, the LV (and the filesystem on it) will be corrupted and you won't able to mount it and recover the data. You might be able to save some of the data using tools like photorec and ddrescue but it's not guaranteed. If you are afraid of data loss, you can always create RAID1 LV to have redundancy (but this will of course reduce the "usable" space).

A: If you have one VG (and in your case one LV) spread across multiple disks, then if any one disk fails you will lose the entire VG (in your case the entire LV).
Bear in mind that as you add disks to an array you reduce the mean time between failures (MTBF), making it more likely you will lose one disk of your collection. Look up the statistics for RAID 0.
One solution is backups. In fact, this should be your primary solution for any event.
Once you have backups sorted consider RAID 1, or the LVM mirror equivalent. This ensures all writes go to two disks simultaneously, but requires twice as much raw storage to implement.


text:
Q: retrieving detailed usb midi device information on windows xp The function midiOutGetDevCaps returns a structure MIDIOUTCAPS.
I'd need more specific information when querying a usb midi device on windows xp, in particular I'd need the information displayed under "Location" when opening the respective device using the Device Manager.
I need this information in order to programmatically distinguish between several MIDI Interfaces connected to a computer. Using midiOutGetDevCaps, I uniformly get "USB Audio Device" for every midi usb interface connected to the computer, so distinguishing between the interfaces is impossible.
To make matters worse, this string is localized, so e.g. on a German Windows you'll get "USB Audiogerät" instead of "USB Audio Device".

A: I guess it depends on how desperate you are.  I've had my own run in with USB devices.  In my case I needed to enumerate certain USB COM port related devices . . . regardless if they are currently attached to the system or not.
It is all company proprietary code, sorry I cannot post it, but the search for all information regarding USB related devices starts here (Perl):
$hostnamePrefix = "//$hostname/";
my $baseKey = "${hostnamePrefix}HKEY_LOCAL_MACHINE/System/CurrentControlSet/";
my $regVidList = Win32::TieRegistry->new("${baseKey}Enum/USB/", $optionsRef);

If memory serves me it is a reasonably straight forward structure.  I believe you actually have to loop through two separate sections of the registry to get everything you need . . . if you are desperate enough to attempt this, I'm happy to answer questions where I can, but posting code would required approval from our legal department.  (Not impossible, but it would take weeks to obtain.)
Also, while this will work on XP . . . I have no idea how it will work on Win7.  (I don't know either way, nobody has tried it yet that I am aware of.)
Coding this was not that bad (resulting Perl Script is around 1000 lines of code which is almost 50% comments), but working out all the relationships between the keys and the special cases took several days.


text:
Q: regex not picking up new lines https://regex101.com/r/zAt2dw/3
I am seaching for lines like so
{"url":"/search?cflt=active&find_loc=37801","name":"Active Life"},

but as u can see in 101 example
{"url":"\/search\?cflt=[^<>]+?&find_loc=37801","name":"[^<>]+?"},

match1 is huge and match 8 has 2 lines instead of 1

A: You should use lazy quantifiers: +? instead of +.


text:
Q: Best solution to cache objects and images on Android? What is the preferred way of caching different objects (including images) on Android? My goal is to cache some data for quick access, and to keep them available for longer time (for days).
Thanks!

A: Use a disk cache. Jack Wharton's DiskLruCache is very good https://github.com/JakeWharton/DiskLruCache.
It will save what you want to disk and read from it, and you can build around it to set max-age values for cache.

A: use Volley for the better caching of images and objects. Its a faster library for android to load data from web.
http://www.androidhive.info/2014/05/android-working-with-volley-library-1/