text:
Q: python multiprocessing pool in a function with multiple input parameter but only one iterable I have a function with multiple parameters, iterable_token,dataframe,label_array. However, only iterable_token is iterable in the function.
def cross_tab(label,token_presence):
    A_token=0
    B_token=0
    C_token=0
    D_token=0
    for i,j in zip(list(label),list(token_presence)):
        if i==True and j==True:
            A_token+=1
        elif i==False and j==False:
            D_token+=1
        elif i==True and j==False:
            C_token+=1
        elif i==False and j==True:
            B_token+=1
    return A_token,B_token,C_token,D_token

def My_ParallelFunction(iterable_token,dataframe,label_array):
    A={}
    B={}
    C={}
    D={}
    token_count={}
    token_list=[]
    token_presence_sum=0
    i=0

    for token in iterable_token:
        try:
            token_presence=dataframe['Master'].str.contains('\\b'+token+'\\b')
            token_presence_sum=sum(token_presence)
            if token_presence_sum:
                A_token,B_token,C_token,D_token=cross_tab(label_array,token_presence)
                A[token]=A_token
                B[token]=B_token
                C[token]=C_token
                D[token]=D_token
                token_count[token]=token_presence_sum
                token_list.append(token)
        except Exception as e:
            pass
    return (A,B,C,D,token_count,token_list)

How do i parallelize My_ParallelFunction function?
Edit1: I tried the method suggested in example 1 because that's what i am looking for, to parallelize function.
import multiprocessing as mp
with mp.Pool(mp.cpu_count()) as p:
    results = p.starmap(My_ParallelFunction, (iterable_token, dataframe,label_array))

but error message is
RemoteTraceback                           Traceback (most recent call last)
RemoteTraceback:
"""
Traceback (most recent call last):
  File "/usr/lib/python3.6/multiprocessing/pool.py", line 119, in worker
    result = (True, func(*args, **kwds))
  File "/usr/lib/python3.6/multiprocessing/pool.py", line 47, in starmapstar
    return list(itertools.starmap(args[0], args[1]))
TypeError: My_ParallelFunction() takes 3 positional arguments but 949 were given
"""

The above exception was the direct cause of the following exception:

TypeError                                 Traceback (most recent call last)
<timed exec> in <module>

/usr/lib/python3.6/multiprocessing/pool.py in starmap(self, func, iterable, chunksize)
    272         `func` and (a, b) becomes func(a, b).
    273         '''
--> 274         return self._map_async(func, iterable, starmapstar, chunksize).get()
    275
    276     def starmap_async(self, func, iterable, chunksize=None, callback=None,

/usr/lib/python3.6/multiprocessing/pool.py in get(self, timeout)
    642             return self._value
    643         else:
--> 644             raise self._value
    645
    646     def _set(self, i, obj):

TypeError: My_ParallelFunction() takes 3 positional arguments but 949 were given

Edit2: Here is the file i am using. You can download it from here and unzip. Also, run below script to get the required input parameters. Make sure to install nltk, pandas and numpy and change path to the file TokenFile.csv.
from nltk import word_tokenize,sent_tokenize
import pandas as pd
import numpy as np

dataframe=pd.read_csv('/home/user/TokenFile.csv',nrows=100)

def get_uniquetoken(stop_words,input_doc_list):
    ##get unique words across all documents
    if stop_words:
        unique_words=[word for doc in input_doc_list for sent in sent_tokenize(doc) for word in word_tokenize(sent) if word not in stop_words]
    else:
        unique_words=[word for doc in input_doc_list for sent in sent_tokenize(doc) for word in word_tokenize(sent)]
    unique_words=set(unique_words)
    print('unique_words done! length is:',len(unique_words) )
    return unique_words

input_token_list=dataframe['Master'].tolist()
label_array=dataframe['label_array'].tolist()
iterable_token=get_uniquetoken(None,input_token_list)

Edit 3 This is the solution i am using
def My_ParallelFunction(iterable_token,dataframe,label_array):
    A={}
    B={}
    C={}
    D={}
    token_count={}
    token_list=[]
    i=0

    with mp.Pool(4) as p:
        token_result = p.starmap(_loop,[(token, dataframe, label_array,A,B,C,D,token_count,token_list) for token in iterable_token])
    #print(token_result[0])
    return token_result#(A,B,C,D,token_count,token_list)

def _loop(token, dataframe, label_array,A,B,C,D,token_count,token_list):
    #print(token)
    try:
        token_presence=dataframe['Master'].str.contains('\\b'+token+'\\b')
        token_presence_sum=sum(token_presence)
        #print(token_presence_sum)
        if token_presence_sum:
            A_token,B_token,C_token,D_token=cross_tab(label_array,token_presence)
            #print('token,A_token,B_token,C_token,D_token',token,A_token,B_token,C_token,D_token)
            A[token]=A_token
            B[token]=B_token
            C[token]=C_token
            D[token]=D_token
            token_count[token]=token_presence_sum
            token_list.append(token)
#             print('token_list:',token_list)
    except Exception as e:
        pass
    return A,B,C,D,token_count,token_list

However it is not giving me the result i want. Its a 949 X 6 X different_sizes matrix

A: Here are two toy examples to show how you can parallelize a similar function.
First Option. If you want to parallelize the whole function. You can do that using Pool.starmap(). .starmap() works like map(), but you can pass multiple arguments to it.
from multiprocessing import Pool
import time

#Example 1 Simple function parallelization
def f(a,b,c,_list):
    x = a+b+c
    time.sleep(1)
    _list.append(x)
    return _list

inputs = [
    (1,2,3,['a','b','c']),
    (1,2,3,['d','e','f']),
    (1,2,3,['x','y','z']),
    (1,2,3,['A','B','C']),
]

start = time.time()
with Pool(4) as p:
    results = p.starmap(f, inputs)
end = time.time()

for r in results:
    print(r)

print(f'done in {round(end-start, 3)} seconds')

Output:
['a', 'b', 'c', 6]
['d', 'e', 'f', 6]
['x', 'y', 'z', 6]
['A', 'B', 'C', 6]
done in 1.084 seconds

Second option. If you want to parallelize only the for-loop inside the function. In that case, you should rewrite your loop as a function and call it using Pool.map() or Pool.starmap().
#Example 2. Function calling a parallel function

#loop
def g(_string):
    time.sleep(1)
    return _string + '*'

#outer function
def f(a,b,c,_list):
    x = a+b+c
    _list.append(str(x))
    #loop parallelization
    with Pool(4) as p:
        new_list = p.map(g, _list)
    return new_list

start = time.time()
result = f(1,2,3,['a','b','c'])
end = time.time()

print(result)
print(f'done in {round(end-start, 3)} seconds')

Output:
['a*', 'b*', 'c*', '6*']
done in 1.048 seconds

Note that the "loop function" contains the logic to deal with a single element of the iterable. Pool.map() will take care of run it for all the elements.
The time.sleep(1) calls are to simulate some time-consuming calculation. If the parallelization works, you should be able to process 4 inputs in 1 second rather than in 4 seconds.
Here is an example using your code:
def My_ParallelFunction(iterable_token, dataframe, label_array):

    with mp.Pool(4) as p:
        token_result = p.starmap(
            _loop,
            [(token, dataframe, label_array) for token in iterable_token]
        )
    return token_result

def _loop(token, dataframe, label_array):
    A={}
    B={}
    C={}
    D={}
    token_count = {}
    token_list = []
    try:

        token_presence=dataframe['Master'].str.contains('\\b'+token+'\\b')
        token_presence_sum=sum(token_presence)
        if token_presence_sum:
            A_token, B_token, C_token, D_token = cross_tab(label_array, token_presence)
            A[token]=A_token
            B[token]=B_token
            C[token]=C_token
            D[token]=D_token
            token_count[token]=token_presence_sum
            token_list.append(token)
            return A,B,C,D,token_count,token_list

    except Exception as e:
        print(e)

A: Something along these lines should work, if you wish to only multiprocess the for loop and not the entire function.
from multiprocessing import Pool

def My_ParallelFunction(iterable_token,dataframe,label_array):
    def get_token_counts(token,dataframe,label_array):
        try:
            token_presence=dataframe['Master'].str.contains('\\b'+token+'\\b')
            token_presence_sum=sum(token_presence)
            if token_presence_sum:
                A_token,B_token,C_token,D_token=cross_tab(label_array,token_presence)
                return token,A_token,B_token,C_token,D_token
        except Exception as e:
            print(e)
            pass

    A={}
    B={}
    C={}
    D={}
    token_count={}
    token_list=[]
    token_presence_sum=0
    i=0

    with Pool() as p:
        p_results = p.starmap(get_token_counts, [(token, dataframe, label_array) for token in iterable_token])

    for res in p_results:
        if res is None:
            continue
        token,A_token,B_token,C_token,D_token = res
        A[token]=A_token
        B[token]=B_token
        C[token]=C_token
        D[token]=D_token
        token_count[token]=token_presence_sum
        token_list.append(token)
    return (A,B,C,D,token_count,token_list)

I removed the part where you add elements to lists and dictionnaries from the worker function since you'd have to look into queues or shared objects in order to multip appending to a list or a dict. It's more work but should make your code run slightly faster (it all depends on how many elements you have in your iterable and what takes a lot of time to compute).
The idea behind this code is you create a worker function get_token_counts that will run inside every thread provided it has a token, a dataframe and a label_array. The returning part of the function contains all the elements needed to add your elements to a dictionnary (since you can't really know which thread finishes first, you return token with it and it solves all your indexing problems. Although, maybe starmap keeps the order of the arguments, so maybe it's not necessary).
Once all elements have been computed, you proceed to adding them to your lists and dicts.
This is basically multiprocessing some of the dataframe functions along with cross_tab, not exactly My_ParallelFunction.
Since you gave no example I can't really test out the code and come up with something better.


text:
Q: SQL Archive Script I'm trying to archive records from a table in a database to an identical table in an archive database. I need to be able to do an insert for all records with a date greater than three years ago, and then delete those rows. However, this table has millions of records which are live, so I want to run this in a loop of roughly 100  to 1000 chunks at a time. So far my stored procedure does the entire insert statement, then a delete statement (in a transaction) with essentially the same WHERE clause as the insert statement. My WHILE loop is looking for the oldest date in the table to determine when the loop is completed. Some of this seems pretty inefficient. Is there a way I can do an insert and delete on the chunk of records without having to look them up twice in the same loop execution? Is there a better way to determine when the WHILE statement is completed? Running MS SQL Server 2000.
This is my current Procedure (ISAdminDB is the main DB, ISArchive is the archive DB):
    WHILE ( (SELECT MIN( [MyTable].[DateTime]) FROM  [ISAdminDB].[dbo].[MyTable]) < DATEADD(d, -(3 * 365), GetDate()))
BEGIN

INSERT INTO [ISArchive].[dbo].[MyTable]
(<Fields>)
SELECT TOP 1000 (<Fields>)
FROM  [ISAdminDB].[dbo].[MyTable]
WHERE
   [MyTable].[DateTime] < DATEADD(d, -(3 * 365), GetDate())
AND  UniqueID in (SELECT TOP 1000 UniqueID  FROM  [ISAdminDB].[dbo].[MyTable] ORDER BY [MyTable].[DateTime] ASC )

BEGIN TRAN
DELETE FROM  [ISAdminDB].[dbo].[MyTable]
WHERE   [MyTable].[DateTime] < DATEADD(d, -(3 * 365), GetDate())
AND  (UniqueID in (SELECT TOP 1000 UniqueID FROM  [ISAdminDB].[dbo].[MyTable] ORDER BY [MyTable].[DateTime] ASC))
COMMIT

END

A: Firstly, you're deleting records earlier than a specific date, 3 years ago. You don't care what order they're deleted in, you just need to keep deleting them until there aren't any left. You can also speed things up by using a temporary table to store the IDs, and by storing the cut-off date in a variable and repeatedly referring to it.
So now we have :
DECLARE @NextIDs TABLE(UniqueID int primary key)
DECLARE @ThreeYearsAgo datetime
SELECT @ThreeYearsAgo = DATEADD(d, -(3 * 365), GetDate())

WHILE EXISTS(SELECT 1 FROM [ISAdminDB].[dbo].[MyTable] WHERE [MyTable].[DateTime] < @ThreeYearsAgo)
BEGIN
    BEGIN TRAN

    INSERT INTO @NextIDs(UniqueID)
        SELECT TOP 1000 UniqueID FROM [ISAdminDB].[dbo].[MyTable] WHERE [MyTable].[DateTime] < @ThreeYearsAgo

    INSERT INTO [ISArchive].[dbo].[MyTable] (<Fields>)
        SELECT (<Fields>)
        FROM  [ISAdminDB].[dbo].[MyTable] AS a
        INNER JOIN @NextIDs AS b ON a.UniqueID = b.UniqueID

    DELETE [ISAdminDB].[dbo].[MyTable]
    FROM  [ISAdminDB].[dbo].[MyTable]
    INNER JOIN @NextIDs AS b ON a.UniqueID = b.UniqueID

    DELETE FROM @NextIDs

    COMMIT TRAN
END

redpajama_set_name: RedPajamaStackExchange


text:
Q: About absolutely summing operators The concept of absolute summing operator between two Banach spaces is already well-known. I just would like to know if one can extend the definition between general spaces, say locally convex spaces. I would like to be clarified with this and thanks for your help in advance...

A: The notion of absolutely summing mappings for locally convex spaces was given by Albrecht Pietsch in the book Nuclear locally convex spaces. p. 34.
The definition is exactly the same as for normed spaces: operator $T$ is called absolutely summing if for any convergent series $\sum_{i} x_i$, the series $\sum_iT(x_i)$ is absolutely convergent.
The only thing in this definition you need to redefine for locally convex spaces is absolute convergence.
We say that the series $\sum_{i}x_i$ in a locally convex space is absolutely convergent if for any neighbourhood of zero the series $\sum_{i} p_U(x_i)$ converges in $\mathbb{R}$ (here $p_U$ denote Minkowski functional of $U$).


text:
Q: Unable to update cart total after shipping option selected I just updated Magento to 1.9.2 and while testing, I noticed that on the cart page, the Update Total button is always disabled even after selecting a shipping option. I'm not sure if I had this same problem before updating.
I don't see any console/JS errors or any errors in the logs. Anyone else experience this/Have any advice on how to debug? I've disabled all extensions, cleared all the cache and still have same problem.

A: Thanks @Fabian Blechschmidt for the tip that let me to a fix.
I'm using a theme based on the rwd theme.
I copied over the changes in the file /app/design/frontend/base/default/template/checkout/cart/shipping.phtml
to
/app/design/frontend/{{my_themes}}/{{my_theme}}/template/checkout/cart/shipping.phtml
There was some changes to the forms and also the button html.


text:
Q: How to return h1 element from an API using React and Axios I am trying to display the title of a movie based on the movie searched for using movieDB's API, and using React and Axios. I have already tested the API in vanilla Javascript with fetch and data['results'][0]['title'] gets the value I am trying to return as an H1 element. I had a submit button in vanilla javascript but I am now confused on where and how to implement it in react and not sure if that's what I need to do, or where to go from here based on tutorials I was watching, so far my code is:
App.js
import React from "react"
import Movielist from './components/Movielist'

function App() {
    return (

            <input type="search" />

title

            <Movielist />

    )
}

export default App

Movielist.js (PROBLEM AREA)
import React from 'react';

import axios from 'axios';

export default class Movielist extends React.Component {
  state = {
    title: ""
  }

  componentDidMount() {
    const API_KEY = '*********';
    const query = document.getElementById('search');
    axios.get(`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&query=${query}`)
      .then(res => {
        const title = res.data['results'][0]['title'];
        this.setState({ title });

      })
  }

  render() {
    return (

{this.state.title.value}

    )
  }
}

index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
    <App />,
    document.getElementById('root')
);

This is what returns from the API in the browser with correct information and "Joker" as the query so I know that the API information is not the issue

A: Search API should be called via a trigger and not on the component mount, that logic can be moved into a function and can be called as and when required.
You need

*

*A trigger(button) to fire the search event.

*An event handler that would be called on button click.

Since your input box is in App.js, it's a good idea to keep the button there as well. Also instead of getting the value of the input element via DOM, you can store it in state.
App.js
import React from "react";
import Movielist from "./components/Movielist";

class App extends React.Component {
  state = {
    searchText: "",
    title: ''
  };

  handleChange = (e) => {
    this.setState({searchText: e.target.value});
  }

  handleClick = () => {
    const API_KEY = "*********";
    const query = this.state.searchText;
    axios
      .get(
        `https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&query=${query}`
      )
      .then(res => {
        const title = res.data["results"][0]["title"];
        this.setState({ title });
      });
  };

  render() {
    return (

        <input type="search" onChange={this.handleChange} />
        <button onClick={this.handleClick}>Submit</button>

title

        <Movielist title={this.state.title}/>

    );
  }
}

export default App;

MovieList.js
import React from "react";

const MovieList = props => {
    return (
{props.title}
);
}

export default MovieList


text: Q: Symmetry group of QCD In "Remarks on the chiral phase transition in chromodynamics" (1984) by Pisarski and Wilczek it is stated that the (classical) global flavor symmetry is $SU(2)\times SU(2) \times U_A(1)$ where the $U_A(1)$ is broken by an anomaly. This seems wrong. Where is the unbroken $U_V(1)$? Is there an explanation? This seems essential for the point of the whole paper? Am I missing something?


text:
Q: Bootstrap Carousel Isn't Responsive in Full Screen I am working on a carousel that is 50% off a page. It is the same one that is in the bootstrap modern business template. I have tried multiple ways to get the images to be responsive when re-sizing the page with no luck. The images are 1920px x 740px. The 1st one is correctly aligned when it's a half page, but when it's in fullscreen mode it is cut off. The code in the 3rd image is what came in the template and the first two were my attempts to fix it.
The carousel scrolls correctly, the buttons work etc. It's just the responsive portion I cannot figure out.
This is my first post on here, so if there is more information you need please let me know. Also I apologize if this is not formatted correctly. Thank you for any & all help.

Caption 2

Caption 3

There are 2 .css files in the template I am using. Here is the css for the carousel for both
/* Home Page Carousel */

header.carousel {
height: 50%;
}

header.carousel .item,
header.carousel .item.active,
header.carousel .carousel-inner {
height: 100%;
}

header.carousel .fill {
width: 100%;
height: 100%;
background-position: center;
background-size: cover;
}

And the second - I didn't include the controls css since that part is working.
.carousel {
position: relative;
}
.carousel-inner {
position: relative;
width: 100%;
overflow: hidden;
}
.carousel-inner > .item {
position: relative;
display: none;
-webkit-transition: .6s ease-in-out left;
   -o-transition: .6s ease-in-out left;
      transition: .6s ease-in-out left;
}
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
line-height: 1;
}
@media all and (transform-3d), (-webkit-transform-3d) {
.carousel-inner > .item {
-webkit-transition: -webkit-transform .6s ease-in-out;
     -o-transition:      -o-transform .6s ease-in-out;
        transition:         transform .6s ease-in-out;

-webkit-backface-visibility: hidden;
        backface-visibility: hidden;
-webkit-perspective: 1000;
        perspective: 1000;
}
.carousel-inner > .item.next,
.carousel-inner > .item.active.right {
left: 0;
-webkit-transform: translate3d(100%, 0, 0);
        transform: translate3d(100%, 0, 0);
}
.carousel-inner > .item.prev,
.carousel-inner > .item.active.left {
left: 0;
-webkit-transform: translate3d(-100%, 0, 0);
        transform: translate3d(-100%, 0, 0);
}
.carousel-inner > .item.next.left,
.carousel-inner > .item.prev.right,
.carousel-inner > .item.active {
left: 0;
-webkit-transform: translate3d(0, 0, 0);
        transform: translate3d(0, 0, 0);
}
}
.carousel-inner > .active,
.carousel-inner > .next,
.carousel-inner > .prev {
display: block;
}
.carousel-inner > .active {
left: 0;
}
.carousel-inner > .next,
.carousel-inner > .prev {
position: absolute;
top: 0;
width: 100%;
}
.carousel-inner > .next {
left: 100%;
}
.carousel-inner > .prev {
left: -100%;
}
.carousel-inner > .next.left,
.carousel-inner > .prev.right {
left: 0;
}
.carousel-inner > .active.left {
left: -100%;
}
.carousel-inner > .active.right {
left: 100%;
}

A: What about change your class:
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
line-height: 1;
}

to:
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
line-height: 1;
display: block;
max-width: 100%;
height: auto;
}

and check it out?.


text:
Q: When should setReorderingAllowed() be called on a FragmentTransaction? At this part of a talk given at Google I/O 2017, the speaker introduces a new API for setReorderingAllowed() than can be called on a FragmentTransaction.
The speaker explains:

It allows all the execution to happen all at once without changing
  your fragment state and then at the very end we bring up all the
  fragments that need to be brought up and tear down all the fragments
  that need to be torn down…so we can optimize this for you.

And shows the following code sample:
fragmentManager.beginTransaction()
    .replace(R.id.container, fragment1)
    .addToBackStack("state1")
    .setReorderingAllowed(true)
    .commit();

fragmentManager.beginTransaction()
    .replace(R.id.container, fragment2)
    .addToBackStack("state2")
    .setReorderingAllowed(true)
    .commit();

Wouldn't committing the FragmentTransactions separately negate any optimization that .setReorderingAllowed(true) gives you because they are occurring separately?
Since this is a newly announced API it looks like there is no documentation currently available.

A: I believe the method they mention already exists since support library 25.1.0 but is currently called setAllowOptimization(true). The documentation clearly states "optimizing operations within and across transactions" so it will optimize distinct transactions.


text:
Q: c++ how to create iterator over one field of a struct vector I have a structure of all primitive types, like so:
struct record {
    int field1;
    double field2;
}

I have a vector of instances of this struct, like so:
vector<record> records;

Is it possible/what is the best way to create a vector<int>::iterator that will iterate over field1?
What about if I used an array record records[n]? I need something that looks like vector<int>::iterator.
EDIT: I need something that IS a vector<int>::iterator.

A: Making an iterator adaptor
First of all, the simplest solution is to iterate over the container and access the fields from the iterator.
for (auto&& r : records) {
    int value = r.field1;
    /* do something with 'value' */
}

Anyway, if you really want an iterator that returns field1 when dereferenced you can easily implement an iterator adaptor that derives from the container's own iterator.
struct my_it : public std::vector<record>::iterator {
    using std::vector<record>::iterator::iterator;
    int operator*() { return std::vector<record>::iterator::operator*().field1; }
};

And use it like this:
for (my_it it = std::begin(records); it != std::end(records); ++it) {
    int value = *it; // Dereferencing now returns 'field1'.
}

Is it an XY problem?
As explained in the answer by Ben Voigt, there is no way to create a std::vector<int>::iterator that iterates over something else than int elements stored in a contiguous array.
If you need a function that takes input iterators then make it a template function. This way it will work with iterators for any container type. This is how all the algorithms in the standard library is implemented.
template <typename InputIt>
void func(InputIt first, InputIt last) {
    for (; first != last; ++first) {
        value = *it; // Dereferences input iterator of any type.
    }
}

Iterators should be interfaced through their operations (i.e. read, increment, decrement, random access), not their explicit type. Iterators are categorized by the number of operations they support.
For instance, if you need to iterate over a range and read all the values in a single pass then you want input iterators as arguments. The type of the iterator itself should be irrelevant.
See this for more info about iterator categories

A: You're out of luck.
vector<int>::iterator is not polymorphic1.  There's no place to reach in and change the pointer step size.  vector<int>::iterator iterates a sequence of contiguous int objects, only, and your int objects are not stored contiguously.
This is why all the C++ standard algorithms are templated to accept iterators of any type.  If you make your function a template accepting arbitrary iterator types, you can use an iterator adaptor like the one Snps wrote.

1Polymorphism is slow relative to pointer arithmetic, no one would use std::vector if it didn't have similar performance to a plain array

A: You can use lambdas on your original vector.
For example:
for_each(records.begin(), records.end(), [](record& foo){/*operate on foo.field1 here*/});

Note that the vast majority of other algorithms also accept lambdas, so you can just iterate over your original vector using the lambda to access just field1.
I'm being presumptuous here but the behavior you are looking for seems to closely resemble that of a map so you might wanna have a look at that.
I suppose that you're into Boost and evil you could also cobble something together with this: http://www.boost.org/doc/libs/1_57_0/libs/range/doc/html/range/reference/adaptors/reference/strided.html

A: It seems like you are asking for something like this
for(std::vector<record>::iterator i=records.begin(), end=records.end(); i!=end; ++i)
{
    std::cout << i->field1 << std::endl;
}

Or in C++11
for(auto i=records.begin(), end=records.end(); i!=end; ++i)
{
    std::cout << i->field1 << std::endl;
}

A: If you really want a member iterator, you can do something like this:
template <class M>
struct member_traits;

template <class T, class C>
struct member_traits<T C::*>
{
    using class_type = C;
    using return_type = T;
};

template <class Iterator, class C, class M>
struct member_iterator : Iterator
{
public:
    using Iterator::Iterator;

    template <class I, class Member>
    member_iterator(I&& begin, Member&& member)
        : std::vector<C>::iterator(std::forward<I>(begin))
        , member(std::forward<Member>(member))
    {
        static_assert(std::is_member_pointer<Member>::value,
                      "Member must be dereferenceable");
    }

    typename member_traits<M>::return_type& operator*()
    {
        return (*static_cast<Iterator&>(*this)).*member;
    }
private:
    M member;
};

template <class Member, class Iterator>
auto make_member_iterator(Member&& member, Iterator&& it)
    -> member_iterator<std::decay_t<Iterator>, typename member_traits<Member>::class_type, std::decay_t<Member>>
{
    return {std::forward<Iterator>(it), std::forward<Member>(member)};
}

struct Record
{
    int field1;
    double field2;
};

int main()
{
    std::vector<Record> v { {1, 1.0}, {2, 2.0}, {3, 3.0} };

    for (auto it = make_member_iterator(&Record::field1, v.begin()); it != v.end(); ++it)
    {
        std::cout << *it << " ";
    }
}

Demo


text:
Q: How are CP (Cost Complexity) values calculated in RPART (or decision trees in general) From what I understand, the cp argument to the rpart function helps pre-prune the tree in the same way as the minsplit or minbucket arguments.  What I don't understand is how CP values are computed.  For example
df<-data.frame(x=c(1,2,3,3,3,4), y=as.factor(c(TRUE, TRUE, FALSE, TRUE, FALSE, FALSE)), method="class")
mytree<-rpart(y ~ x, data = df, minbucket = 1, minsplit=1)

Resulting tree...
mytree
n= 6

node), split, n, loss, yval, (yprob)
      * denotes terminal node

1) root 6 3 FALSE (0.5000000 0.5000000)
  2) x>=2.5 4 1 FALSE (0.7500000 0.2500000) *
  3) x< 2.5 2 0 TRUE (0.0000000 1.0000000) *

Summary...
summary(mytree)

Call:
rpart(formula = y ~ x, data = df, minbucket = 1, minsplit = 1)
  n= 6

         CP nsplit rel error    xerror      xstd
1 0.6666667      0 1.0000000 2.0000000 0.0000000
2 0.0100000      1 0.3333333 0.6666667 0.3849002

Where's the .666 and .01 coming from?

A: I was searching for same from many days and I came to know one thing that cp value calculation is taken care by package.
By default if you do not specify "CP" value then rpart will take its as 0.01.
Cp value is cost of adding node to the tree.

A: The complexity parameter (cp) in rpart is the minimum improvement in the model needed at each node. It's based on the cost complexity of the model defined as

For the given tree, add up the misclassification at every terminal node.
Then multiply the number of splits time a penalty term (lambda) and add it to the total misclassification.
The lambda is determined through cross-validation and not reported in R.
For regression
models (see next section) the scaled cp has a very direct interpretation: if any split does
not increase the overall R2 of the model by at least cp (where R2
is the usual linear-models
definition) then that split is decreed to be, a priori, not worth pursuing. See the longintro document for rpart


text:
Q: pattern to allow an optional hyphen between 2 alpha numerics and restrict space as well sub:  pattern to allow an optional hyphen between 2 alphanumeric and restrict space as well.No other specialcharacters
I need a regex to match following test cases:-

"all-owed" "allowe-d" "a-llo-wed-12" "allowed12" "allow-12ed"
  "allowed-12" "allo-wed-12"
"not allowed" "not allowed " " notallowed" " nota-llowed"
  "not--allowed" "not@allowed"

patterns tried:
^[^-]*-?[^-]*$
^\\w+(-\\w+)*$

Regex to text a string which will have only numbers and an optional hyphen. Hyphen can be at any position after character 2
javascript regex for special characters
Java regex - alphanumeric, at most one hyphen, period or underscore, seven characters long
PHP regex to match alphanumeric and hyphens (not spaces) for use as subdomain
and some more
PLEASE POST THE DUPLICATE QUESTION LINK. We may learn from the solutions provided there and improve our search

A: Your second regex ^\w+(-\w+)*$ would match your cases but \w would also match an underscore.
Perhaps you are looking for a pattern that matches one or more times an alphanumberic [a-z0-9]+ and then repeats matching a dash followed by one or more times matching an alphanumeric (?:-[a-z0-9]+)*
Note that this matches only lowercase characters. You can use the case insensitive flag to match both upper and lowercase characters.
^[a-z0-9]+(?:-[a-z0-9]+)*$

const strings = [
  "all-owed",
  "allowe-d",
  "a-llo-wed-12",
  "allowed12",
  "allow-12ed",
  "allowed-12",
  "allo-wed-12",
  "notallo-wed-12_",
  "not allowed",
  "not allowed ",
  " notallowed",
  " nota-llowed",
  "not--allowed",
  "not@allowed"
];
let pattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;

strings.forEach((s) => {
  console.log(s + " ==> " + pattern.test(s));
});

A: You can use positive lookbehind and lookahead to ensure that - is between two alphanumeric characters.
^((?<=\w)-(?=\w)|\w|\d)*$
Online demo


text:
Q: OpenLDAP does not validate TLS certificate I am trying to run OpenLDAP (2.4.44 on RedHat 7.6) as a client against an existing LDAP server with TLS. This is working well - too well, actually. It looks to me as if OpenLDAP accepts any server certificate, instead of validating it against the CAs I provided.
Here is my ldap.conf file:
TLS_CACERT /etc/openldap/cacerts/ldap-2019.pem
TLS_REQCERT demand
URI ldaps://ldap.mydomain.com/
BASE ou=people,dc=mydomain,dc=com

# Some optimizations suggested by
# https://sourceforge.net/p/xcat/wiki/Setting_up_LDAP_in_xCAT/
set_cachesize 0 268435456 1
set_lg_regionmax 262144
set_lg_bsize 2097152

What I want to accomplish is of course that OpenLDAP validates the certificate for ldaps://ldap.mydomain.com against the list of CAs in TLS_CACERT.
But in reality, no matter what I put into the TLS_CACERT file, openldap seems to connect successfully, just as long as it is a valid PEM file.
What am I missing? Is there a second list of CAs that OpenLDAP consults? I also removed the CAs in /etc/pki/tls, just in case.
More details:
ldapsearch -x -uid=somename fails if I delete the file I specified in TLS_CACERT. It also fails if TLS_CACERT is not a valid PEM file. This is of course expected behavior when the client cannot validate a TLS certificate:
ldapsearch -x uid=somename
ldap_sasl_bind(SIMPLE): Can't contact LDAP server (-1)

But if I put a completely nonsensical certificate into the TLS_CACERT file, ldapsearch will return a result as if the server's certificate was valid.
ldapsearch -x uid=somename
# extended LDIF
#
# LDAPv3
# base <ou=people,dc=mydomain,dc=com> (default) with scope subtree
# filter: uid=somename
# requesting: ALL
#

# somename, People, mydomain.com
dn: uid=somename,ou=People,dc=mydomain,dc=com
...

For example, I tried using a certificate for www.google.com as a TLS_CACERT. I would have expected this connection to fail with the same "Can't contact LDAP server" error.
Update:
I found the cause but not the solution. OpenLDAP uses the certificate bundle in /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem . Renaming this file causes ldapsearch to behave as I expected, but of course that is not an acceptable solution since this is a systemwide file, not just for OpenLDAP.
So my new question is: how do I prevent OpenLDAP from using this file?
Update 2:
For clarification, this is on RedHat 7.6, and OpenLDAP 2.4.44. I assume that using the systemwide CA bundle is a RedHat modification to the stock OpenLDAP.


text:
Q: Replace forward slash "/ " character in JavaScript string? I have this string:
var someString = "23/03/2012";

and want to replace all the "/" with "-".
I tried to do this:
someString.replace(///g, "-");

But it seems you cant have a forward slash / in there.

A: Just use the split - join approach:
my_string.split('/').join('replace_with_this')

A: Try escaping the slash: someString.replace(/\//g, "-");
By the way - / is a (forward-)slash; \ is a backslash.

A: Escape it: someString.replace(/\//g, "-");

A: Remove all forward slash occurrences with blank char in Javascript.
modelData = modelData.replace(/\//g, '');

A: You can just replace like this,
 var someString = "23/03/2012";
 someString.replace(/\//g, "-");

It works for me..

A: First of all, that's a forward slash. And no, you can't have any in regexes unless you escape them. To escape them, put a backslash (\) in front of it.
someString.replace(/\//g, "-");

Live example

A: You need to escape your slash.
/\//g

A: The option that is not listed in the answers is using replaceAll:
 var someString = "23/03/2012";
 var newString = someString.replaceAll("/", "-");

A: Area.replace(new RegExp(/\//g), '-') replaces multiple forward slashes (/) with -


text:
Q: zend framework 3, multiple db tables in one controller I have a ZF3 project and an index controller that accesses a single postgres table.  I have the usual factories setup
return array(
        'factories' => [
            Model\IsdepotstockTable::class => function($container) {
                $tableGateway = $container->get(Model\IsdepotstockTableGateway::class);
                return new Model\IsdepotstockTable($tableGateway);
            },
            Model\IsdepotstockTableGateway::class => function ($container) {
                $dbAdapter = $container->get(AdapterInterface::class);
                $resultSetPrototype = new ResultSet();
                $resultSetPrototype->setArrayObjectPrototype(new Model\Isdepotstock());
                return new TableGateway('isdepotstock', $dbAdapter, null, $resultSetPrototype);
            },
        ],

I also have my controller constructor thus:
public function __construct(IsdepotstockTable $table)
{
    $this->isdepotstockTable = $table;
}

My question is, if I wish to access a second table, how do I modify the construct statement to handle multiple tables?  Obviously I have to add the factories for the additional table that much I understand.
I've looked through the ZF3 documentation but cannot find any example.
Thanks

A: I believe you are looking for a controller factory function which will instantiate the controller and pass the arguments to the constructor.
Add your second table class as the 2nd argument in the __construct() method, then create your factory in module.config.php.
<?php
use Zend\ServiceManager\Factory\InvokableFactory;

return [
    // ...

    'controllers' => [
        'factories' => [
            Controller\IndexController::class => InvokableFactory::class
            // Put other controllers registration here
        ],
    ],

    // ...
];

Here is a free open source book on ZF3, I link to the controller registration section for your reference. Good luck! https://olegkrivtsov.github.io/using-zend-framework-3-book/html/en/Model_View_Controller/Controller_Registration.html


text:
Q: Erro que esta ocorrendo
  @Html.ActionLink("Editar","EditarPessoa", new { cod=item.Id }) |
  @Html.ActionLink("Details", "Detalhes", new { cod=item.Id }) |
  @Html.ActionLink("Deletar","DeletarPessoa", new { cod=item.Id })

public ActionResult EditarPessoa(int id)
{
  var pessoaOBJ = pessoaNegocio.BuscarPessoa(id);
  var pessoaVM = ModelParaModel(pessoaOBJ);
  return View(pessoaVM);
}

[HttpPost]
public ActionResult EditarPessoa(ViewModelPessoa modelPessoa)
{
  pessoaNegocio.Alterar(ViewModelParaModel(modelPessoa));
  return View("ListarPessoa","Pessoa");
}

public ActionResult DeletarPessoa(int id)
{
  var pessoaOBJ = pessoaNegocio.BuscarPessoa(id);
  var pessoaVM = ModelParaModel(pessoaOBJ);
  return View(pessoaVM);
}

[HttpDelete]
public ActionResult DeletarPessoa(ViewModelPessoa modelPessoa)
{
  var pessoa = ViewModelParaModel(modelPessoa);
  pessoaNegocio.Deletar(pessoa.Id);
  return View();
}

quando clica no botão excluir e editar da o seguinte erro:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult EditarPessoa(Int32)' in 'ProjetoDadosPessoa.Controllers.PessoaController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
  Nome do parâmetro: parameters

Erro de Servidor no Aplicativo '/'.

The number of primary key values passed must match number of primary key values defined on the entity.
  Nome do parâmetro: keyValues
  Descrição: Ocorreu uma exceção sem tratamento durante a execução da atual solicitação da Web. Examine o rastreamento de pilha para obter mais informações sobre o erro e onde foi originado no código.

Detalhes da Exceção:

System.ArgumentException: The number of primary key values passed must match number of primary key values defined on the entity.
  Nome do parâmetro: keyValues

Erro de Origem:
Linha 34:         public T Buscar(params object[] Key)
Linha 35:         {
Linha 36:             return _db.Set<T>().Find(Key);
Linha 37:         }
Linha 38:

Arquivo de Origem:

C:\Users\DELL\Desktop\Projetos_CSharp\projetos_estudados\ProjetoDadosPessoa\ProjetoDadosPessoa.DAL\Repositorio\GenericRepositorio.cs    Linha: 36

Rastreamento de Pilha:
[ArgumentException: The number of primary key values passed must match number of primary key values defined on the entity.
Nome do parâmetro: keyValues]
   System.Data.Entity.Internal.WrappedEntityKey..ctor(EntitySet entitySet, String entitySetName, Object[] keyValues, String keyValuesParamName) +429
   System.Data.Entity.Internal.Linq.InternalSet`1.Find(Object[] keyValues) +121
   System.Data.Entity.DbSet`1.Find(Object[] keyValues) +29
   ProjetoDadosPessoa.DAL.Repositorio.GenericRepositorio`1.Buscar(Object[] Key) in C:\Users\DELL\Desktop\Projetos_CSharp\projetos_estudados\ProjetoDadosPessoa\ProjetoDadosPessoa.DAL\Repositorio\GenericRepositorio.cs:36
   ProjetoDadosPessoa.Negocio.Negocio.PessoaNegocio.BuscarPessoa(Int32 id) in C:\Users\DELL\Desktop\Projetos_CSharp\projetos_estudados\ProjetoDadosPessoa\ProjetoDadosPessoa.Negocio\Negocio\PessoaNegocio.cs:42
   ProjetoDadosPessoa.Controllers.PessoaController.DeletarPessoa(Int32 id) in C:\Users\DELL\Desktop\Projetos_CSharp\projetos_estudados\ProjetoDadosPessoa\ProjetoDadosPessoa\Controllers\PessoaController.cs:47
   lambda_method(Closure , ControllerBase , Object[] ) +96
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.<>c.<BeginInvokeSynchronousActionMethod>b__9_0(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__11_0() +50
   System.Web.Mvc.Async.<>c__DisplayClass11_1.<InvokeActionMethodFilterAsynchronouslyRecursive>b__2() +228
   System.Web.Mvc.Async.<>c__DisplayClass7_0.<BeginInvokeActionMethodWithFilters>b__1(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
   System.Web.Mvc.Async.<>c__DisplayClass3_6.<BeginInvokeAction>b__3() +35
   System.Web.Mvc.Async.<>c__DisplayClass3_1.<BeginInvokeAction>b__5(IAsyncResult asyncResult) +100
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
   System.Web.Mvc.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState) +11
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +45
   System.Web.Mvc.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller) +13
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState) +28
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9748493
   System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +48
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +159

Informações sobre a Versão: Microsoft .NET Framework Versão:4.0.30319; Versão do ASP.NET:4.7.2558.0

da esse erro aqui

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ProjetoDadosPessoa.DAL.Repositorio.Interface;
using System.Linq.Expressions;
using ProjetoDadosPessoa.DAL.Contexto;
using System.Data.Entity;

namespace ProjetoDadosPessoa.DAL.Repositorio
{
    public class GenericRepositorio<T> : IGenericRepositorio<T>, IDisposable where T : class
    {
        private readonly ProjetoDadosPessoaContexto _db;

        public GenericRepositorio()
        {
            _db = new ProjetoDadosPessoaContexto();
        }

        public void Adicionar(T entidade)
        {
            _db.Set<T>().Add(entidade);
            Commit();
        }

        public void Atualizar(T entidade)
        {
            _db.Entry(entidade).State = EntityState.Modified;
            Commit();
        }

        public T Buscar(params object[] Key)
        {
            return _db.Set<T>().Find(Key);
        }

        public void Commit()
        {
            _db.SaveChanges();
        }

        public void Deletar(int i)
        {
            var obj = Buscar(i);
            _db.Set<T>().Remove(obj);
            Commit();
        }

        public void Dispose()
        {
            if(_db != null)
            {
                _db.Dispose();
            }

            GC.SuppressFinalize(this);
        }

        public List<T> Obter(Expression<Func<T, bool>> predicate)
        {
            return _db.Set<T>().Where(predicate).ToList();
        }

        public List<T> ObterTodos()
        {
            return _db.Set<T>().ToList();
        }

        public T Primeiro(Expression<Func<T, bool>> predicate)
        {
            return _db.Set<T>().Where(predicate).FirstOrDefault();
        }
    }
}

A: Pelo o que posso ver no seu trecho de código, você recebe no seu método o parametro int id, mas no seu código você passa cod. Isso faz com que o parametro não seja reconhecido.
Você não mostrou o código dos Detalhes, mas irei fazer para ele da mesma forma que fiz para os outros.
Tente fazer o seguinte:

    @Html.ActionLink("Editar","EditarPessoa", new { id = item.Id }) |
    @Html.ActionLink("Details", "Detalhes", new { id = item.Id }) |
    @Html.ActionLink("Deletar","DeletarPessoa", new { id = item.Id })


text:
Q: Releasing a c++ program I've built a program in my Win7 64BIT in C++, and I want to share it with my Windows XP 32 bit computer.
When I run the release build in my Windows XP, it says invalid win32 application..
but when I'm in the Project Configurator, theres a marker on the "Platform - Win32", so I have no idea why am I getting this error..
the EXE works perfectly at my computer..
By the way, the windows XP does not have Visual Studio or any other similar program installed...
Things I have tried :
- I've installed updates to the VS - Update 4, and choose in the Platform Toolset - Visual Studio 2012 - Windows XP (v110_xp), yet I still get the same error...
Thanks!

A: Make sure your XP machine is fully updated.  Windows XP Service Pack 3 (SP3) for x86 is supported, but not previous service packs.  Note: same is true for VS2013 except the toolset changed to v120_xp

A: By default Visual C++ programs require the C++ redistributable to run that are built with Visual Studio. So the client machine has to have it installed. Make sure your client machine have the actual or higher version of C++ redist installed and then try again.
You can search in MS Developer Center to download it or you might find it poking around the VS installation disk.
However, MS has removed support for XP, so not sure that you will be able to install the latest C++ Redist into it. But worth a try.


text:
Q: OpenCL, problem with vector types: cross product is not working as I expect I am newbie to OpenCL as well as heavy parallel computing. I came across a problem with operations over vector types.
I am crazy about taking advantage of SIMD instructions for operations with vectors and matrices. But the problem is that vector types, float float3 may be not working as I expect...
The thing is quite simple I just need to make my function to the cross product of two vectors.
I've written version of that function in Scala and it's working perfectly.
Here is the code in Scala:
    @inline def crossProduct(other: Vector3D) = Vector3D(
        y * other.z - z * other.y,
        z * other.x - x * other.z,
        x * other.y - y * other.x)

And this one is version in OpenCL and fails the test:

float3 cross_pro(float3 a, float3 b) {
    return (float3) (
        (a.y * b.z) - (a.z * b.y),
        (a.z * b.x) - (a.x * b.z),
        (a.x * b.y) - (a.y * a.x));
}

Given set of parameters: cross_pro((float3) (0, 1, 0), (float3) (1, 0, 0));
Online calculators say that the result must be (float3) (0, 0, -1)
but OpenCL version prints: (float3) (0, 0, 0)!
 I can not even imagine why it happens? so I checked this function for overloading, experimented with these vector types an did so many other stuff...

A: (a.x * b.y) - (a.y * a.x));

should be
(a.x * b.y) - (a.y * b.x));

also OpenCL has cross product already
https://www.khronos.org/registry/OpenCL/sdk/1.1/docs/man/xhtml/cross.html
float4 cross (float4 p0,float4 p1)
float3 cross (float3 p0,float3 p1)

double4 cross(double4 p0,double4 p1)   // if double extension enabled
double3 cross(double3 p0,double3 p1)   // if double extension enabled

half4 cross(half4 p0,half4 p1)   // if half extension enabled
half3 cross(half3 p0,half3 p1)   // if half extension enabled

Description
Returns the cross product of p0.xyz and p1.xyz. The w component of the
  float4 result (or double or half if the cl_khr_fp64 or cl_khr_fp16
  extensions are enabled) will be 0.0.

If you need SIMD performance of a CPU: I guess, drivers will handle any available CPU cross product or dot product-like functions efficiently if you use their cross product function definition.


text:
Q: Как правильно спарсить данные JSON? Есть вот такой JSON:
"data": [
    {
      "updated_at": 1576048969000,
      "prices": {
        "last": 5300,
      },
      "name": "Jacket",
    },
    {
      "updated_at": 1576048969000,
      "prices": {
        "last": 2000.12,
      },
      "name": "T-shirts",
    }
]

Как можно спарсить значения в price обратившись при этом к name?
Что-то типа как в SQL, SELECT price FROM data WHERE name = Jacket (чтоб была понятна логика)

A: При условии что не будет повторяющихся имен
$arr = json_decode($json, true);

$full = array();

foreach ($arr["data"] as $value) {
  $full[$value["name"]] = $value;
}


text:
Q: Interface Builder won't connect button, but the tutorial says it should work I've been trying to learn Core Data, and browsing through questions on Stack Overflow lead me to a recommendation that I try the tutorial on Core Data over at Cocoa Dev Central (Link).
Everything is making sense so far in the tutorial, but when I got to step 16, it wouldn't let me connect the + button to the Posts array controller.  I've gone back and double, triple-checked each step along the way and can't see where anything is off, but it still won't let me connect.  I'm using the latest versions of Xcode and Interface Builder (just re-downloaded them last week); could this be a version compatibility issue?
Addendum
Seems that the problem was in that I had to change the name by changing the class in the inspector, and that removed the default actions for the array controller.  Changing the class back to NSArrayController restores functionality, but now it appears as "Array Controller" wherever it appears, which seems like it'd become problematic with 3 controllers in play once I fix the Authors and Topics controllers.

A: Got it.  Under the inspector, use "Name" to change the name of the object, not "Class".  Newbie error.

A: Based on your comments, you changed the class of the Posts controller from an NSArrayController to a custom class called Posts. Interface builder couldn't find an implementation for this custom class, hence, did not show any actions or outlets available to bind against.
Changing the class back to NSArrayController fixed the problem.
(Interface builder lets you do this as you may want to define your own custom controller. You can add the actions and outlets to the object in IB, then generate the class and add the implementation in XCode. This is quite useful - but can confuse new users of the tool.)


text:
Q: Creating a table with number of records of other tables I would like to create a table RECORDS_COUNT with 2 columns TABLE_NAME and COUNT which displays the number of rows of 5 tables:
TABLE1, TABLE2,.. TABLE5 and POP-TOTAL.
For example:
TABLE-NAME |  COUNT
 ----------------------

TABLE1     |  200
----------------------
TABLE2     |  100
----------------------
TABLE3     |  200
----------------------
TABLE4     |  350
---------------------
TABLE5     |  150
----------------------
POP-TOTAL      |  1000

These numbers will change everyday and I need to access the results quickly without having to open the 5 tables.

A: I've left my old answer below for interest, but I think this addresses your question more accurately:
SELECT
[TableName] = so.name,
[RowCount] = MAX(si.rows)
into #temp
FROM
sysobjects so,
sysindexes si

WHERE
so.xtype = 'U'
AND
si.id = OBJECT_ID(so.name)
and so.name in ('TABLE1', 'TABLE2', 'TABLE3', 'TABLE4', 'TABLE5')
GROUP BY
so.name

select *
from #temp
union all
select 'POP-TOTAL', (select SUM([RowCount]) from #temp)

This will produce the results you want in a temporary table. Then sum them up and display them.
Old answer:
This may not work for you if the format is important, but there is an answer here:
Select COUNT in two table in one query with MYSQL
It might put you on the right track.
select (select count(*) from table1) as t1_amount,
       (select count(*) from table2) as t2_amount,
       (select count(*) from table1) + (select count(*) from table2) as Total

With this method you would have a column per table, plus one for the total.
Its not the most efficient, but if you are just looking to check each day, it should do the job.
Output:
t1_amount | t2_amount | Total
-----------------------------
1121      | 544       | 1665


text:
Q: How can I determine if a HTML document is well formed or not in JAVA? Heyy guys, I need to determine if a given HTML Document is well formed or not.
I just need a simple implementation using only Java core API classes i.e. no third party stuff like JTIDY or something. Thanks.
Actually, what is exactly needed is an algorithm that scans a list of TAGS. If it finds an open tag, and the next tag isn't its corresponding close tag, then it should be another open tag which in turn should have its close tag as the next tag, and if not it should be another open tag and then its corresponding close tag next, and the close tags of the previous open tags in reverse order coming next on the list. I've already written methods to convert a tag to a close tag. If the list conforms to this order then it returns true or else false.
Here is the skeleton code of what I've started working on already. Its not too neat, but it should give you guys a basic idea of what I'm trying to do.
public boolean validateHtml(){

    ArrayList<String> tags = fetchTags();
    //fetchTags returns this [<html>, <head>, <title>, </title>, </head>, <body>, <h1>, </h1>, </body>, </html>]

    //I create another ArrayList to store tags that I haven't found its corresponding close tag yet
    ArrayList<String> unclosedTags = new ArrayList<String>();

    String temp;

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

        temp = tags.get(i);

        if(!tags.get(i+1).equals(TagOperations.convertToCloseTag(tags.get(i)))){
            unclosedTags.add(tags.get(i));
            if(){

            }

        }else{
            return true;//well formed html
        }
    }

    return true;
}

A: Yeah string manipulation can seem like a pickle sometimes,
you need to do something like
First copy html into an array
bool tag = false;
string str = "";
List<string> htmlTags = new List();

for(int i = 0; i < array.length; i++)
{
  //Check for the start of a tag
  if(array[i] == '<')
  {
    tag == true;
  }

  //If the current char is part of a tag start copying
  if(tag)
  {
    str += char;
  }

  //When a tag ends add the tag to your tag list
  if(array[i] == '>')
  {
    htmlTags.Add(str);
    str = "";
    tag == false;
  }
}

Something like this should get you started, you should end up with an array of tags, this is only pseudo code so it wont shouldn't compile

A: Don't think you can do this without undertaking a huge amount of work, would be much easier to use a third party package

A: Try validating against HTML4 or 4.1 or XHTML 1 DTD
"strict.dtd"
"loose.dtd"
"frameset.dtd"

Which might help !


text:
Q: one to many relationships in different columns This is newbee SQL question I struggled to find a clear answer to. So please help. I have two tables in database with fields as listed below:
ConstructionProjects

*

*id                (unique, nonempty)

*developer         (one, nonempty)

*main_contractor   (one, nonempty)

*architect         (one, nonempty)

*(other fields)

Companies

*

*id                (unique, nonempty)

*projects_developed            (many or none)

*projects_as_main_contractor   (many or none)

*projects_as_architect         (many or none)

*(other fields)

So every project has only one developer, one architect and one contractor, however, it may be the same company. Any company may be involved in as many projects in any roles.
Is there a way to avoid creating 3 additional association tables to establish many to many relationships? and make 3 one to many relationships instead?
If so, which practice is better?
*In other words, I don't understand relationships (one to many and many to many) relate (1) row to row or (2) row to "specific cell"?

*

*(1) if row to row then I have many to many relationships

*(2) if row to specific cell then it is multiple one to many relationships...*

I'm learning Flask_alchemy and PostgreSQL.
I ran into problem, writing a code like this (there's no reference to specific columns between tables). So this is not ok?
class Company(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    constr_projects_developed = db.relationship('ConstrProject', backref='developer')
    constr_projects_main_contracts = db.relationship('ConstrProject', backref='main_contractor')
    constr_projects_architect = db.relationship('ConstrProject', backref='architect')

class ConstrProject(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    developer_id = db.Column(db.Integer, db.ForeignKey('company.id'))
    main_contractor_id = db.Column(db.Integer, db.ForeignKey('company.id'))
    architect_id = db.Column(db.Integer, db.ForeignKey('company.id'))

Then my question is, the correct way to do it is like this (1):
class Company(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    constr_projects_developed = db.relationship('ConstrProject', back_populates='developer')
    constr_projects_main_contracts = db.relationship('ConstrProject', back_populates='main_contractor')
    constr_projects_architect = db.relationship('ConstrProject', back_populates='architect')

class ConstrProject(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    developer_id = db.Column(db.Integer, db.ForeignKey('company.id'))
    developer = db.relationship('Company', back_populates='constr_projects_developed')
    main_contractor_id = db.Column(db.Integer, db.ForeignKey('company.id'))
    main contractor = db.relationship('Company', back_populates='constr_projects_main_contracts')
    architect_id = db.Column(db.Integer, db.ForeignKey('company.id'))
    architect = db.relationship('Company', back_populates='constr_projects_architect')

Or like this(2)?:
class Company(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    cp_developed = db.relationship('Company', secondary=cp_developer_company, back_populates='developer')
    cp_main_contracts = db.relationship('Company', secondary=cp_main_contractor_company, back_populates='main_contractor')
    cp_architects = db.relationship('Company', secondary=cp_architect_company, back_populates='architect')

class ConstrProject(db.Model):
    id = db.Column(db.Integer, primary_key = True)
    developer = db.relationship('Company', secondary=cp_developer_company, back_populates='cp_developed')
    main_contractor = db.relationship('Company', secondary=cp_main_contractor_company, back_populates='cp_main_contracts')
    architect = db.relationship('Company', secondary=cp_architect_company, back_populates='cp_architects')

cp_developer_company = db.Table('cp_developer_company'
    db.Column('company_id', db.Integer, db.ForeignKey('company.id'))
    db.Column('constr_project_id', db.Integer, db.ForeignKey('constrproject.id'))
    )

cp_main_contractor_company = db.Table('cp_main_contractor_company'
    db.Column('company_id', db.Integer, db.ForeignKey('company.id'))
    db.Column('constr_project_id', db.Integer, db.ForeignKey('constrproject.id'))
    )

cp_architect_company = db.Table('cp_architect_company'
    db.Column('company_id', db.Integer, db.ForeignKey('company.id'))
    db.Column('constr_project_id', db.Integer, db.ForeignKey('constrproject.id'))


text:
Q: How do I offset an element using the 'top' CSS property inside a TD? So I want to offset an element 5 pixels up. I set position: absolute and top: -5px. Now the element is positioned relative to the page, not the containing TD tag. Am I understanding absolute positioning wrong? It does say

position it at a specified position relative to its closest positioned
  ancestor or to the containing block.

Ancestor is TD, right?
Similarly, the top definition says

For absolutely positioned elements (those with position: absolute or
  position: fixed), it specifies the distance between the top margin
  edge of the element and the top edge of its containing block.

So why does this JsFiddle render the table content block relative to the page, not the TD?

A: You're missing a position: relative; in the parent TD element. The TD doesn't include that by default.
JS fiddle. http://jsfiddle.net/2p225mv2/2/
CSS to fix it:
td {
  position: relative;
}

A: Because you're missing the part that says: closest positioned ancestor with the key word being "positioned".
Add:
td {
    position:relative;
}

and you'll get this jsFiddle example


text:
Q: Unable to pass model from a post form to a controller I have a problem (or I don't understand how forms work) with passing a model to a controller from a form. I have a model called EmptySurveyViewModel, that has a list consisting of EmptyQuestionViewModel. This question model has a property Answer that is empty, and is to be filled by the form. However, one survey has many questions, and at the end i want to pass a model to the controller that is a EmptySurveyViewModel, containing a list of EmptyQuestionViewModel, that each has the Answer property. That property can be filled in different ways, depending on the type of the question. My problem is that if I don't have the if statement (see below), all questions are displayed as radio style questions, and the model passed to the controller has only questions that have the Answer property filled. However, when i add the if (i intend to add other ifs, to catch all possible types), only some questions are listed, and when i submit the form, the model is completely empty (it's not null, but its property Questions is null. I think the first situation (without the if) can be dealt with by other logic later on, but returning an empty list can't. Why is that happening?
The Models:
public class EmptySurveyViewModel {
    //Something else here
    public List<EmptyQuestionViewModel> Questions { get; set; }
}

public class EmptyQuestionViewModel {
    //Something else here
    public string Answer { get; set; }
}

The View:
@model cq.Models.EmptySurveyViewModel

@using (Html.BeginForm("New", "Client", FormMethod.Post, new { role = "form" })) {
    for (int i = 0; i < Model.Count(); i++) {
        if (Model.Questions[i].Type == "Single choice") {
            @Html.RadioButtonFor(m => m.Questions[i].Answer, "foo")
            @Html.RadioButtonFor(m => m.Questions[i].Answer, "bar")
        }
        <br />
    }

    <input type="submit" value="submit" />
}

And the Action in the controller:
[HttpPost]
public ActionResult New(EmptySurveyViewModel survey) {
    //Do something with the survey here
}

A: I believe this happens because you are skipping some of the indices. So when the data is posted back, you maybe post objects with indices 0, 1, 3, while 2 is missing because it happened to be filtered out by if. That breaks the continuity of the collection, something model binding cannot deal with. More details can be found in this Haacked post.
There are few possible solutions:

*

*Add other if's to cover all question types. That will make sure there are no skips.

*As Phil suggests in the post, add a hidden Index field to each question (also see this post). Note that this will cause only rendered questions to be posted back.

*Render filtered out questions as hidden inputs entirely, again avoiding skipping any of them.


text:
Q: Could the universe have non-vanishing net colour charge? I've heard that the strong force doesn't decrease in strength with increasing distance, and that's why quarks must be confined within hadrons. But could there be, say, a single quark out there, so that the universe would be colour neutral without it, but with it, it's not? Would such a quark have a "strong field" that would extend through the entire universe?

A: No, confinement means that such a state cannot exist, or more precisely, it cannot have a finite energy/mass. If such a colored state had a finite energy, it would mean that far enough from the colored particle, the quantum fields very closely approach the vacuum state. But if that's so, you could always combine two such objects of opposite colors. The total energy would be pretty much inevitably close to the sum of the energies of each, and you would get a "stretched meson", a pair of oppositely charged, widely separated, colored particles, in a direct conflict with confinement.
One may see why such an object is impossible in various more explicit ways. For example, close enough to the particle, the QCD gauge potentials would go like $1/r$, just like in the Coulomb case. But these "gluon" gauge fields are color-charged as well because QCD is non-Abelian, so they induce additional, increasing densities of the QCD field strengths.
Already if the color charge is uncancelled within the region comparable to the nuclear radii, the energy contribution just from this nuclear-radius-sized vicinity of the colored particle will greatly exceed the QCD scale. Due to positive energy theorems etc., this positive mass/energy can't be cancelled by anything that is even further from the colored source. So the non-existence of objects like yours is already decided at distances shorter than or comparable to the confinement length scale.


text:
Q: iPhone Simulator Refresh/Redraw View when debugging? anyone does knows how redraw a  view when debugging code?
When Xcode is in the debugger mode, doesn't refresh the screen. If I add a view or a button, nothing  is show on the screen!

A: If you're looking for the swift equivalent:
(lldb) expr CATransaction.flush()

You can still use the objective-c version in a swift context so long as you manually set the expression language:
(lldb) expr -l objc -- (void)[CATransaction flush]

A: No - you need to rebuild the project so it deploys the latest app to the Simulator

A: When the application is paused you can update live in the simulator or on the device while you are still in the debugger using the LLDB command below:
 (lldb) e (void)[CATransaction flush]

if you have Chisel use the alias caflush


text:
Q: Confuse with Count usage in this code. I have a problem knowing what a part of this code works.
Here it is:
public class fia1 {
  public static void main(String [] args) {
   Band b0 = new Band();
   b0.name = "Beastie";
   b0.age = 25;
   Band b1 = new Band();
   b1.name = "Orchestra";
   b1.age = 100;
   System.out.println(b0.count);

   Band b2 = new Band();
   b2.name = "Polka";
   b2.age = 5;

   System.out.println("Names: " + b0.name + " " + b1.name + "
   " + b2.name);
   System.out.println(Band.count);
   b1 = b2;
   b1.age = 10;
   b0.age = b2.age + b0.age;

   System.out.println("Ages = " + b0.age + " " + b1.age + " "
   + b2.age);
    }
      }

  class Band {
   String name;
   int age;
   static int count = 1;
   Band() {
   count = count * 2;
   }
     }

So what this print is:
4
Names: Beastie, Orchestra, Polka
8
Ages: 35, 10, 10

I am confused as to how I get a 4 from my first count. Also I know that
 static int count = 1;

is where I am misunderstanding. Is this how java counts the variables? by 1, then 2 is Beastie, 3 is Orchestra and 4 is Polka? I really don't know how this is working. Thanks for your help!

A: You are using a static variable in static int count = 1;, which means every time you create a new Band the variable will be doubled for all Bands (since count = count * 2;)
See code below with comments that explains what happens:
public static void main(String [] args)
{
    Band b0 = new Band(); //Count becomes 1*2 = 2.
    b0.name = "Beastie";
    b0.age = 25;

    Band b1 = new Band(); //Count becomes 2*2 = 4.
    b1.name = "Orchestra";
    b1.age = 100;
    System.out.println(b0.count); //Prints 4.

    Band b2 = new Band(); //Count becomes 4*2 = 8.
    b2.name = "Polka";
    b2.age = 5;

    System.out.println("Names: " + b0.name + " " + b1.name + " " + b2.name);
    System.out.println(Band.count); //Prints 8.
    b1 = b2;
    b1.age = 10;
    b0.age = b2.age + b0.age;

    System.out.println("Ages = " + b0.age + " " + b1.age + " " + b2.age);
}

A: the count field in your Band class is a static field or class variable, meaning that all object of the Band class share it. Each time the constructor is called, count is updated. If you want to learn more about class variables, you can check out this Java documentation

A: Since your variable count is static, as it's declared as a static int count = 1;, each new construction of the class will perform any actions on count to all objects that have count. Anotherwords, when you call b1, the count = count * 2; command affects all instances of count, so the count variable in b0 is also doubled as well.
Hence, when you first construct band() with b0, it takes count and sets it equal to 1 * 2 = 2. The second instance of band() with b1 causes all instances of count to be equal to itself * 2. So, the count in b1 is equal to 1*2 = 2, and the count in b0 is equal to 2*2 = 4.


text:
Q: Match absolute tile sizes of two different ggplots when saving as PNG When creating PNG files for a document using ggplot2 and geom_tile, is there a way to set the size of the tiles to some absolute unit (cm, pt)? I have multiple plots that, when inserted into a document, do not have the exact same tile sizes. Of course I could change the width and height of the plots manually, so the tiles almost match each other, but that's cheating...
The variable names on the x- and y-axis have different lengths. So rather than setting the dimensions of the whole plot (including all the labels), I would like to set the dimensions of only the plot area to some fixed value, maybe through scale_x/y_discrete? Or maybe the individual plots can be extracted after they have been resized with gridExtra or gtable?
# Create some example data.
set.seed(1)
dt1 <- data.table(x=letters[1:5], y=rep(c("aaaaaaaaa", letters[2:3]), rep(5,3)),
                  value=runif(5*3))

dt2 <- data.table(x=letters[1:4], y=rep(letters[1:4], rep(4,4)),
                  value=runif(4*4))

# Make two tile plots.
p1 <- ggplot(dt1, aes(x, y, fill=value)) +
        geom_tile() +
        coord_equal(); p1

p2 <- ggplot(dt2, aes(x, y, fill=value)) +
        geom_tile() +
        coord_equal(); p2

# Save tile plots to drive.
# ggsave("p1.png", p1, width=5)
# ggsave("p2.png", p2, width=5)

Here's a screenshot from a document with PNG images inserted, note that the labels have the same size:

And this is what I'm after: the absolute distance between the red arrows is identical in both images, without resizing the labels.

Any suggestions greatly appreciated!


text:
Q: Display messages in test/unit result I want to display the message after test is passed. Where i need to print the message so that i can get in result of test.
require 'test/unit'

class MyTest < Test::Unit::TestCase
  def sample
    begin
      count = 0
      5.times do
        assert(true)
        count = count + 1
      end
    rescue
    ensure
    print "Total number of times: 5, Success count: 3 , Failures count: 2 "
    end
  end
end

I want to get some thing like this
Loaded suite
Started
"Total number of times: 5, Success count: 3 , Failures count: 2 "
.
Finished in 0.0 seconds.

1 tests, 5 assertions, 0 failures, 0 errors

Can anyone help me ?


text:
Q: Angularjs model not update view when modified by child controller I have to update a parameter of the parent controller from a nested controller.
I'm able to read the parameter, but when I change it it does not update into the view (webpage)... help plz :)
This is my js:
    app.controller('signalCtrl', [ '$scope', 'DB', function($scope, service) {
        this.address = null;
    }]);

    app.controller('reportMap', ['$scope', function($scope) {
        this.updateParent = function() {
            $scope.$parent.tab.address = 'something';
        }
    }]);

And this is my HTML:

    <input type="text" ng-model="signal.address">
    [...]

    [...]

A: The address property in parent controller is not bound to $scope, but to this object, so you even can't reach that property that way. I suggest you to move your updating function to parent controller:
app.controller('signalCtrl', [ '$scope', 'DB', function($scope, service) {
    var self = this;
    self.address = null;
    self.update = function(newValue) {
        self.address = newValue;
    }
}]);

app.controller('reportMap', ['$scope', function($scope) {
    var self = this;
    self.someValue = 'something';
}]);

HTML:

    <input type="text" ng-model="signal.address">
    [...]

        <button type="button" ng-click="signal.update(map.someValue)">Click!</button>
    [...]

You don't call updating function in the presented code, so I added a button to show how to use it.

A: use signal instead of tab
app.controller('reportMap', ['$scope', function($scope) {
    this.updateParent = function() {
        $scope.$parent.signal.address = 'something';
    }
}]);

see this link : https://plnkr.co/edit/RhQLfBy2heecJDuCcq9s?p=preview

A: Ok, probably the error is into te HTML:
(function () {
var app = angular.module('segnalazioni', ['filters', 'smart-table', 'smart-table-server']);

app.controller('nuovaSegnalazioneCtrl', [ '$scope', 'DB', function($scope, service) {
    var self = this;
    this.activatedTab = "tab_animale";
    this.chipNumber = null;
    this.indirizzo = 'ind';

    this.setIndirizzo = function() {
        self.indirizzo = "VIA ROMA";
        console.log("AGGIORNAMENTO INDIRIZZO");

    }

I call setIndirizzo from the child (i don't pass a value I know, but it is not the problem): into the console i read "AGGIORNAMENTO INDIRIZZO", but the value into the VIEW does not change...
this is a link to the complete html file.
https://www.dropbox.com/s/gzlm997ub8fot7r/html.txt?dl=0


text:
Q: Order by Descending with multiple comparisons I want to order the result with multiple comparisons like (by paid users, updated date, created date).
var order = _vrepository.Details()
                          .Where(od => od.Order.Id != null
                                       && od.PlanName.ToLower().Contains("DP".ToLower())
                                       && od.Order.Status == true)
                          .OrderByDescending(od => od.ValidityTill)
                          .Select(ord => ord.Order.Id.Value);

The above one I am getting the paid users.
var updatedList = _repository.GetUsers()
                             .Where(c => c.UpdatedDate != null
                                         && fresh <= c.UpdatedDate)
                             .Select(c => c.Id);

This second query I am getting updated users.
var UsersListByCreatedDate = _repository.GetUsers()
                                        .Where(c => fresh <= c.CreatedDate)
                                        .Select(c => c.Id);

The third one is for get the users by created date. Then I am selecting the Id (an Integer)
lstId = order.ToList();
lstUpdatedUsersId = updatedList ToList();
lstCreatedDatewiseUsers = UsersListByCreatedDate.ToList();

To show the ordered list I did the following code:
Func<IQueryable<User>, IOrderedQueryable<User>> orderingFunc = query =>
{
    if (order.Count() > 0)
        return query.OrderByDescending(rslt => lstId .Contains(rslt.Id))
                    .ThenByDescending(rslt => lstUpdatedUsersId .Contains(rslt.Id))
                    .ThenByDescending(rslt => lstCreatedDatewiseUsers.Contains(rslt.Id));
    else
        return query.OrderByDescending(rslt => lstUpdatedUsersId .Contains(rslt.Id))
                    .ThenByDescending(rslt => rslt.UpdatedDate);
};

But I am getting result as One Paid user, some Created user and the date is before 3 years like wise. I want to get the exact order is as follows

*

*Ordered User

*Updated User

*Created User

Please help me to solve this issue. Hope I will get correct result.

A: I have tried this snipepd of code according to your
public class Program
{
    public static void Main()
    {
        var l1= new List<int>{1,2,3};
        var l2= new List<int>{4,5,6};
        var l3= new List<int>{7,8,9};
        var testList = new List<Test>{new Test{Id=9,Name="test1"},new Test{Id=11,Name="test1"},new Test{Id=5,Name="test1"},new Test{Id=7,Name="test1"},new Test{Id=2,Name="test1"}};
        var orderedList= testList.OrderByDescending(e=> l1.Contains(e.Id)).ThenByDescending(e=> l2.Contains(e.Id)).ThenByDescending(e=> l3.Contains(e.Id));
        Console.WriteLine(string.Join("\t", orderedList.Select(e=> e.Id).Cast<int>().ToArray()));
// it prompts 2    5    9    7    11
    }
}

public class Test{
    public int Id{get; set;}
    public string Name{get; set;}
}

and it works as you expected. Maybe I haven't understood what you are trying to achieve.
Maybe the function that you are using to sort items is in the wrong branch of the if statment, check for if (order.Count() > 0)


text:
Q: I, cannot set property 'IS_CHECK' of undefined TYPE ERROR I'm trying to make a checkbox that when it selected everything should be selected. I handled the code using this link with angular 2 example.
But I get an error called "ERROR TypeError: Cannot set property 'IS_CHECK' of undefined"
How do I resolve this error. I can't seem to fix this.
Here's what I did.
html:

      Application No
      RPU No
      Name with Initials
      NIC/PP No

        <input
          type="checkbox"
          name="selectedAll"
          [(ngModel)]="selectedAll"
          id="selectedAll"
          (change)="CheckAll()">

      {{transfer.AA_APPLICATION_NO}}
      {{transfer.AA_PREV_RPU_NO}}
      {{transfer.AA_NAME_WITH_INTL}}
      {{transfer.AA_NIC_NO || transfer.AA_PASSPORT_NO}}

        <input
          type="checkbox"
          [(ngModel)]="transfer.IS_CHECK"
          (change)="checkIfAllSelected()"
          (click)="$event.stopPropagation()">

The typescript.
selectedAll: boolean = false;

CheckAll() {
  for (var i = 0; this.AllTransfers.length; i++) {
    this.AllTransfers[i].IS_CHECK = this.selectedAll;
    console.log(this.selectedAll);
  }
}

checkIfAllSelected() {
  this.selectedAll = this.AllTransfers.every(function(item: any) {
    return item.IS_CHECK == true;
  });
}

The JSON object is
Data: [{
  "AA_APPL_ID": 114731,
  "AA_NIC_NO": "835678904V",
  "AA_NAME_WITH_INTL": "R.DAYARATHNE",
  "AA_APPLICTION_NO": "SYS12132132",
  "IS_CHECK": false
}]

This is the way I tried to implement the select all checkbox using the link. Help would be appreciated.

A: Add  i < this.AllTransfers.length to the for loop.
for (var i = 0; i < this.AllTransfers.length; i++) {
  this.AllTransfers[i].IS_CHECK = this.selectedAll;
  console.log(this.selectedAll);
}


text:
Q: Google inapp billing not working anymore after successfully integrated Sorry if this not the place for this issue.
I've just started using inapp billing and I'm having trouble with three inapp products.
This items are
X Pack
Y Pack
Z Pack
I've set up a test account to simulate the real purchase flow and I cancelled the purchases after I saw that were working properly. But now I cannot purchase the items using the test account (gmail email address (different from developer account) added to test accounts in Google Developer Console). The X Pack doesn't even launch the purchase dialog from Google Play and for the other two I get displayed the message "The item that you were attempting to purchase could not be found". What can I do to make it working again?

A: I had two test apps, one exhibiting this problem and the other not. The only difference I could find was one of the apps was "Published" (on Alpha only) and the other was still in "Draft" mode. I filled in the remaining fields to bring it from "Draft" to "Ready to Publish", added Alpha testers, and "Published" on alpha. I had to wait a bit for Google to put the app in store (again for alpha testers only) and it works again.
Google's documentation still says testing In-App Billing with test accounts should work in "Draft" mode, but that definitely stopped working for me.


text:
Q: Console outputting state which is not yet updated in Redux reducer First of all, I have no idea if this problem is related to Chrome console, Redux or JavaScript objects.
I have the following function in my React + Redux app:
function InputReducer(state = [{ }], action) {
    console.log('input-reducer.js', 'state', state[0], JSON.stringify(state[0]));
    switch (action.type) {
        case 'STORE_INPUT_VALUE':
            let newState = {};
            newState = state[0];
            _.set(newState, action.storePointer, action.value);
            console.log('input-reducer.js', 'newState', newState, JSON.stringify(newState));
            return [newState];
        break;
        default:
            return state;
    }
}

I know the state should not be replaced, but updated instead. Don't mind about it now, this is in the middle of the process.
This works, but what I don't understand is that when I see the logs, when updating the state, the first log returns exactly the same object as the newState. This should not be possible, since as far as I know, the function which updates the state should not be executed at a time when logging happens.
What makes this even more weird is that when I stringify the object, it returns correct, expected values.
If I modify the function to return some nonsense state, like this:
function InputReducer(state = [{ a: 0 }], action) {
    console.log('input-reducer.js', 'state', state[0], JSON.stringify(state[0]));
    switch (action.type) {
        case 'STORE_INPUT_VALUE':
            let k = state[0].a + 1
            let newState = {a: k};
            console.log('input-reducer.js', 'newState', newState, JSON.stringify(newState));
            return [newState];
        break;
        default:
            return state;
    }
}

...the logs show the objects correctly... or at least they seem as I would expect them to be.
So what is this behaviour related to and what am I missing here?

A: newState = state[0]; gives you the reference to the 1st element in the array.
_.set(newState, action.storePointer, action.value); Your newState is modified, therefore state[0] is modified directly.


text:
Q: "is not a valid choice" when trying to update a field I have this field in my User model
THEMES = [
    ("black", "black"),
    ("light", "light"),
    ("dark", "dark")
]

theme = models.CharField(
    max_length=100, choices=CHAT_STYLES,
    default=THEMES[1][1], null=True, blank=True
)

I'm trying to write a put request for it. this is the serializer.py
class UpdateThemeSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ["theme"]

        def update(self, instance, validated_data):
            new_theme = validated_data["theme"]
            User.objects.update(theme=new_theme)

and here is the view
class UpdateTheme(APIView):
    permission_classes = [IsAuthenticated]

    def put(self, request):
        serializer = UserSerializer(request.user, data=request.data, partial=True)
        if serializer.is_valid():
            serializer.save()
            return Response(data=serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors)

but when I test it in Postman i get this error
{
    "theme": [
        "\"dark\" is not a valid choice."
    ]
}

A: Update this :
THEMES = [
    ("black", "black"),
    ("light", "light"),
    ("dark", "dark")
]

theme = models.CharField(
    max_length=100, choices=THEMES,
    default=THEMES[1][1], null=True, blank=True
)


text:
Q: In Fluent NHibernate how do you combine automapped types with non-automapped types? Right now, I'm switching my project over from the classic fluent nhibernate style of manually defining a ClassMap for each domain entity, to having the auto-mapper auto-generate the mappings for me.  But I'd like to keep using the classes I've already mapped in the classic style, until I can tweak the automappings to match the old classic mappings.
The only problem is that fluent nhibernate crashes when the auto mapper hits a class that's already been mapped in the classic fluent nhibernate style.
Here's my AutoPersistenceModel setup code:
_autoPersistenceModel = AutoMap.AssemblyOf<DomainEntity>();
_autoPersistenceModel.AddMappingsFromAssembly(typeof (PlayerPersistenceMap).Assembly);

_autoPersistenceModel.Alterations(x =>
                    x.Add<AutoMappingAlteration>())
                .Setup(s =>
                {
                    s.FindIdentity = type => type.Name == "ID";

                    s.IsBaseType = type => (type == typeof(DomainEntity));
                })
                .Conventions
                    .AddFromAssemblyOf<IdentityColumnConvention>()
                    .UseOverridesFromAssemblyOf<PlayerMappingOverride>();

Can anyone help me out here?
More Info:
I also tried the technique mentioned on the fluent-nhibernate wiki here.  Alas I'm still getting the error: Duplicate class/entity mapping.

A: The mixed fluent mappings and auto mappings example in the wiki should work, if it doesn't then there's a bug.
As a work-around, exclude the types that have been manually mapped from you automappings. You'd do that by using the Where method, as show in the wiki examples, something like this:
AutoMap.AssemblyOf<DomainEntity>()
  .Where(type => type != typeof(OneOfYourManuallyMappedClasses));

If you have a lot of fluent mappings, you could create a collection to keep the automapping setup clean:
var mappedTypes = new[] { typeof(One), typeof(Two) };

AutoMap.AssemblyOf<DomainEntity>()
  .Where(type => !mappedTypes.Contains(type));

Again, this shouldn't be necessary, but if you're certain it's not working with the wiki example then I'd suggest raising an issue.


text:
Q: How to iterate throught parameters of a soap protocol I try to make a loop on a function that contains the get method on soap protocol to have the list of ActionList   that have appointments at the workshop.
here is the code I managed to do :
def get_xml():
    for iddms in ['7','16','15','10','25','8','11','12','14','13']:
        for idaction in ['1','2']:
            url = "http://url.com/soap/IWSDialog"
            headers = {"content-type" : "application/soap+xml ; charset=utf-8 "}
            body ="""<soapenv:Envelope>
               <soapenv:Header/>
                   <soapenv:Body>
                          <urn:getActionList>
                             <EntId >1013</EntId>
                             <DMSId>"""+iddms+"""</DMSId>
                             <GroupActionId>"""+idaction+"""</GroupActionId>
                          </urn:getActionList>
                   </soapenv:Body>
                </soapenv:Envelope>"""
        ActionList = requests.post(url,data=body,headers=headers)
    return ActionList.content
ActionList = get_xml()

I am blocked how to iterate two parameters :DMSId,GroupActionId  and append the result.
Any help will be highly appreciated.
Thank you in advance

A: The answer to my question was to make a loop then create a dataframe from the content for each iteration like this:
url = "http://url.com/soap/IWSDialog"
headers = {"content-type" : "application/soap+xml ; charset=utf-8 "}
tree = pd.DataFrame()

for iddms in ['7','16','15','10','25','8','11','12','14','13'] :
   for idaction in ['1','2']:
            url = "http://url.com/soap/IWSDialog"
            headers = {"content-type" : "application/soap+xml ; charset=utf-8 "}
            body ="""<soapenv:Envelope>
               <soapenv:Header/>
                   <soapenv:Body>
                          <urn:getActionList>
                             <EntId >1013</EntId>
                             <DMSId>"""+iddms+"""</DMSId>
                             <GroupActionId>"""+idaction+"""</GroupActionId>
                          </urn:getActionList>
                   </soapenv:Body>
                </soapenv:Envelope>"""

            ActionList = requests.post(url, data=body, headers=headers)
            result = ActionList.content
            ActionList = pd.read_xml(result , xpath= "//NS2:path", namespaces={"NS2":"urn:WSD"})
            df= pd.concat([ActionList, df])


text:
Q: How can I disable auto bracket closing in Ace editor? I'm using ace to develop a collaborative code editor and each time I put an opening bracket a closing one pairs in and the cursor reaches the end. Please tell me if there's a way to disable the auto closing of brackets.
Thanks.
Heres what I've tried so far

<script src="/ext-language_tools.js"></script>

<script>
    $(document).ready(() => {
      var editor = ace.edit("editor");
        editor.setTheme("ace/theme/github");
        editor.session.setMode("ace/mode/javascript");
        editor.setOptions({
          fontSize: "15pt",
          enableBasicAutocompletion: false,
          enableLiveAutocompletion: false
        });
</script>

A: use behavioursEnabled: false option https://github.com/ajaxorg/ace/wiki/Configuring-Ace


text:
Q: Creating Events for hard disk read and write I am trying to write something that will fire an event anytime the hard disk reads data or writes data. I know this involves using System.Diagnostics.PerformanceCounter but I don't know this well enough to be able to do this on my own. Can someone point me in the right direction? Also, I'd like the event that fires to return which drive is being read or written to. Any help would be appreciated. This is C#, by the way.

A: The following does not create events but you could use it together with a timer to display information in the tray (as per comments):
using System.Diagnostics;

private PerformanceCounter diskRead = new PerformanceCounter();
private PerformanceCounter diskWrite = new PerformanceCounter();

diskRead.CategoryName = "PhysicalDisk";
diskRead.CounterName = "Disk Reads/sec";
diskRead.InstanceName = "_Total";

diskWrite.CategoryName = "PhysicalDisk";
diskWrite.CounterName = "Disk Writes/sec";
diskWrite.InstanceName = "_Total";

_Total is for ALL disks... to get the specific instancenames of available disks use:
var cat = new System.Diagnostics.PerformanceCounterCategory("PhysicalDisk");
var instNames = cat.GetInstanceNames();

you can then create a pair of diskRead/diskWrite for every instance you are interested in... for sample on how to use this in combination with a timer see this.


text:
Q: jQuery sortable margin issues I'm having two sortable lists where I can add items from the first list to the second list. The default behavior removes the element from the source list, but that's not what I want (I want it to be copied to the destination list), so I made some adjustments to clone the moved element in the source list before it gets deleted.
It works, but I have weird issues with margins on cloned elements. See for yourself:
This is before:

After some dragging, margin inconsistencies appear:

I have a jsfiddle of the problem here: http://jsfiddle.net/JNbsX/
I've tested it on Chrome and Firefox and the issue exists in both browsers. Any help is appreciated. Thanks!

A: Not entirely sure why it's happening, but some of your list items are coming out with display: list-item; instead of display: inline-block;, despite your css.
Setting the ul > li to just li seems to fix the issue: http://jsfiddle.net/RichardTowers/rZuRt/

A: You still can use display: inline-block but you need to add white space before and after all item.

$('ul#source').sortable({
    helper: 'clone',
    connectWith: 'ul#dest',
    start: function(event, ui) {
        $("ul#source > li").eq($(ui.item).index()).after(
            $(ui.item).clone().addClass('clone').show()
        );
        $('.sortable-placeholder').before(' ').after(' '); // add white space here
    },
    change: function(event, ui) {
        $('.sortable-placeholder').before(' ').after(' '); // add white space here
        ui.item.before(' ').after(' '); // add white space here
    },
    remove: function(event, ui) {
        $("ul#source > li").removeClass('clone');
    },
    stop: function(event, ui) {
        $("ul#source > li.clone").remove();
    },
    placeholder:'sortable-placeholder',

});


text:
Q: Magento 2 - Different billing and shipping address I would like to force the user to use the default billing address he has in its account on checkout.
So I set the quote billing address programatically and hide / uncheck the checkbox "My billing and shipping address are the same" but when the user is changing the shipping address it stills updating the billing address how can I fix this ?


text:
Q: How do I use com.google.firebase.database classes in a Java (not Android) library? I have an Android Studio project in which I have three modules:

*

*app: An Android app

*model: A Java library containing my POJOs that get persisted to Firebase Database

*service: An App Engine web application with a servlet that persists some stuff to Firebase Database

Both the service and the app modules depend on the model module. The model module doesn't depend on either the app or the service.
The model module contains only POJOs, but I've just found myself needing to use the com.google.firebase.database.Exclude annotation in order to prevent a field from being written to the database. As soon as I add a compile dependency to either the Firebase admin or the Firebase server SDK to my module project and rebuild, my app crashes before it gets as far as logging anything.
I've tried using these dependencies in the model module (one at a time, not both at once):
compile 'com.google.firebase:firebase-admin:4.0.3'

compile 'com.google.firebase:firebase-server-sdk:3.0.1'

My guess is that they're both pulling in a bunch of stuff that doesn't belong in an Android app. I've also tried:
compile 'com.google.firebase:firebase-database:10.0.1'

But that gives me a gradle error:
Error:Module 'biketracker-android-service:model:unspecified' depends on one or more Android Libraries but is a jar

Is there a library I can use that gives me just the bare minimum Firebase Database classes and is not an Android library?


text:
Q: SQL Server : why convert to date use index and convert to nvarchar not? I have the following 2 queries with function on the index, one do index seek and one index scan:
This uses the index:
select num_of_row
from test0
where convert(date, index_date) = '2017-06-13'

This does not use the index:
select num_of_row
from test0
where convert(nvarchar, index_date, 103) = '2017-06-13'

Why is the index used when I convert to date, but not when I convert to nvarchar?

A: Usually you can't use any functions for a field if you want it to be SARGable (=to use index), but datetime -> date is one of the exceptions, most likely because the order can be guaranteed to be the same (in dates and datetimes), but not in datetimes and (n)varchars.


text:
Q: Difference of Means for Stopwatch Times (independent t-test ?) I want to conduct a t-test for the difference of means between two samples, but the data are times (i.e., taken from a stopwatch). Is Student's T appropriate here ? I question this because I am not convinced that time follows a normal distribution. (Binomial ?)
Many thanks for your assistance here ! I am a great fan of the community, and this is my first question posed.
Notes:
i. No, I couldn't find this anywhere on here or elsewhere, but welcome links.
ii. No, these are not time-series data.

A: The standard 2-sample t test is appropriate provided the times in each sample are independent and can be described by a normal distribution. If the data are skewed or there are outliers, you may be able to transform the data (square root, log, etc.) to fix this. Otherwise there are analogous non-parametric tests that might be applicable.