text:
Q: How does vector's begin() and end() work, and how should I write it for my custom vector? I am currently studying Bjarne's PPP, and I don't really understand how begin() and end() works, and how I am supposed to implement it.
Here is my code for the vector.
template<typename T> class vector {
    int sz;
    T *elem;
    int space;
    std::allocator<T> alloc;
public:
    vector():sz{0},elem{nullptr},space{0}{}
    explicit vector(int s):sz{s},elem{new T[s]}, space{s}{
        for(int i = 0; i<sz; i++) elem[i]=0;
    }
    T &at(int n);
    const T &at(int n) const;
    void reserve(int newalloc);
    void resize(int newsize, T def=T());
    int capacity() const { return space;}
    void push_back(int d);
    vector &operator=(const vector &a);

    T *begin();
    const T *begin() const;
    T *end();
    const T *end() const;

    unsigned long size();
};

A: begin() and end() should return an iterator. Basically, iterator is a class that implements variables such as iterator_category and value_type, which let other functions to know how to use it.
It should also implement functions required by the iterator_category that you choose to use.
For your a vector, you need a random access iterator. You need two classes: constant access iterator (returned by const function) and non-constant access iterator. Usually you would derive the non-constant class from the constant class.
The positions pointed by the iterators: begin points to the beginning of the data, and end is begin() + size().
template<typename T>
class vector_iterator {
public:
    typedef std::random_access_iterator_tag iterator_category;
    typedef T value_type;
    typedef std::ptrdiff_t difference_type;
    typedef const value_type& reference;
    typedef const value_type* pointer;

    // Functions come here

    // You must implement some operators
    reference operator*() const { /* must implement */ }
    vector_iterator operator+(const difference_type) const { /* must implement */ }

    // Some operators can use the operations that are already implemented
    vector_iterator operator-(const difference_type n) const { return *this + (-n); }
    reference operator[](const difference_type n) const { return *(*this + n); }
};


text:
Q: React Native Flatlist height dynamic I am using react native 0.59, for layout I am using native base and react-native-easy-grid.
Because of different size of mobile device, I need to put flatlist height dynamic. it is starting almost middle of the screen, and I would like to show it until the footer bar.
here is my code
<Container>
<ImageBackground source={require(imagePath+"bg-default.png")}
                                 style={{width: screenWidth, height: screenHeight, resizeMode: 'cover'}} >

    <Content scrollEnabled={false}>

        <Grid>
            <Row style={{ height: screenHeight*0.36, alignItems:'center',justifyContent:'center' }}>
                <Image style={styles.iconImage} source={{ uri: this.state.image_url.displayImage}}/>

            </Row>

            <Row style={{ backgroundColor: "#1a0568", height:screenHeight*0.058, textAlignVertical: 'center', alignItems: 'center'}}>
                <Text style={styles.titleStyle}>{"Information list"}</Text>
            </Row>

            <Row style={{ backgroundColor: 'none',height:screenHeight*0.38}}>
                <FlatList
                    style={[styles.listContainer]}
                    data={this.state.informationList}
                    keyExtractor={this._keyExtractor}
                    renderItem={this._renderItem}
                />
            </Row>

        </Grid>
    </Content>
</ImageBackground>
</Container>

As you can see, I set flatlist height screenHeight*0.38, therefore, in some mobile its perfect, but in some mobile there is some empty space. (See the attached picture)
I have tried to make it dynamic with different example to fill rest of the space like
How to set the style attribution to fill the rest space?
(though I need to fill until footer bar), This example works well with normal component But it didnt work with flatlist. Flatlist doesnt scroll anymore. Because it loads all rows which goes out of the screen. what is the right way of setting dynamic height with flatlist?

A: I could solve it by playing around with different options and taking help from How to set the style attribution to fill the rest space?
Unfortunately Grid, Row did not work with this.
Here is the demo (Don't forget to select iOS or android tab to view the app)
https://snack.expo.io/@shaondebnath/layouttest

redpajama_set_name: RedPajamaStackExchange


text:
Q: Defining a macro for iterate I wanted to define a new clause for the iterate macro. Something similar to Python's range where you have a start, stop, step. Here's a first try:
(defmacro-clause (for var start start stop stop step step)
  (if (minusp step)
      `(for ,var from ,start downto ,stop by (- ,step))
      `(for ,var from ,start to     ,stop by ,step)))

It deals with increasing and decreasing ranges using the to and downto keywords of iterate. (Note that, unlike Python, these include the stop value.)
This works as desired for
(iter (for x start 5 stop 3 step -1)
      (collect x))

;; => (5 4 3)

(iter (for x start 2 stop 5 step 1)
      (collect x))

;; => (3,4,5)

However it fails for anything like
(let ((a 9)
      (b 3)
      (c -1))
  (iter (for x start a stop b step c)
        (collect x)))

Is it a quirk of iterate that it requires explicit numbers in these places? It has no problem with things like
(iter (for x below (+ 3 3) by (+ 1 1))
      (collect x))

Concretely my question is, how can I define a new iterate clause that accepts variables which are bound to numbers in these places?

A: The problem is that you are trying to decide things at macro-expansion time which can't be known then, such as the sign of a variable.  In particular you can't write a macro which expands into (part of) another macro depending on anything which is only known at run time, or you can, but that necessarily means you have to call the moral equivalent of eval at run-time, and ... don't do that.
Instead you have to make the decision about which way to count at run-time.  This means you can't use any of the (for var from ...) or related clauses because there don't seem to be any which are agnostic about direction (why (for i from 1 to -5 by -1) doesn't work is beyond me but ... well).
So whatever clause you end up with needs to expand into a (for var next ...) clause, I think.
Here is an attempt at such.  Disclaimer: not tested very much, I don't use iterate, may explode on contact, poisonous to fish.
(defmacro-driver (for v in-range a to b &optional by s)
  (let ((firstp (make-symbol "FIRSTP"))
        (value (make-symbol "VALUE"))
        (limit (make-symbol "LIMIT"))
        (step (make-symbol "STEP")))
    `(progn
       (with ,firstp = t)
       (with ,value = (let ((v ,a))
                        (unless (numberp v)
                          (warn "doomed"))
                        (when (null v)
                          (warn "extremely doomed"))
                        v))
       (with ,limit = (let ((v ,b))
                        (unless (numberp v)
                          (warn "also doomed"))
                        v))
       (with ,step = (let ((v (or ,s (signum (- ,limit ,value)))))
                       (when (not (numberp v))
                         (warn "doomed again"))
                       (when (zerop v)
                         (warn "zero step"))
                       (when (not (= (signum v) (signum (- ,limit ,value))))
                         (warn "likely doomed"))
                       v))
       (,(if generate 'generate 'for)
        ,v
        next (if ,firstp
                 (progn
                   (setf ,firstp nil)
                   ,value)
               (progn
                 (incf ,value ,step)
                 (when (if (> ,step 0)
                           (>= ,value ,limit)
                         (<= ,value ,limit))
                   (terminate))
                 ,value))))))

And now
> (iter (for i in-range 1 to 5 by 2)
    (print i))

1
3
nil

> (iter (for i in-range 1 to -1)
    (print i))

1
0
nil

> (iter (for i in-range 1 to 5 by -2)
    (when (< i -20)
      (terminate)))
Warning: likely doomed
nil

Obviously some of the checks could be better.


text:
Q: Apps script library automatic updation on client side (on doc refresh)? I have

*

*an Apps Script Library 'MyLib'.

*template Google Spread Sheet ('MyGSSheet').  Through Script Editor I added the library 'MyLib' to 'MyGSSheet'. I set 'Development mode' 'on'.

*users get a 'copy' of this template ('MyGSSheet').

How can I have a setup wherein any changes I make to 'MyLib' get picked up across these copies automatically (once the Spreadsheet is reloaded)?
I thought having 'Development mode' 'on' is all that's needed for this continuous update of the code in all the Spreadsheets.
However, I don't see this happening. The copies aren't picking the latest code.
I also granted 'edit' permission to all users within our company domain.

A: I am not able to comment so I hope I am contributing enough to justify an answer..
So I tried to reproduce this:
I created a standalone App Script 'MyLib' and wrote a single function:
function myFunction()
{
  SpreadsheetApp.getUi().alert("TEST");
}

Next I created a spreadsheet and added a script to it via Tools. I'll call it "Spreadsheet Script".
In the Spreadsheet Script I added the MyLib as a library and turned the development mode 'on'.
Also I added two functions to Spreadsheet Script:
 function onOpen(e)
 {
   myFunction();
 }

 function myFunction()
 {
    MyLib.myFunction();
 }

Ok, now I shared the Spreadsheet and the MyLib - script to my colleague with edit rights. He opened the spreadsheets and got the alert "TEST".
Now when I modified the alert text from the MyLib-script's myFunction to "TEST 2 " and just saved the file (File/Save, did not save a new version), my colleague saw the changes in the spreadsheet. Then, I made him to take a copy of the spreadsheet( To test the effect of the spreadsheet owner change).
I changed the alert the text to "TEST 3". The change was reflected in his copy of the spreadsheet.
Are you able to reproduce this or does this approach fail to update for the other users? I am choosing this kind of simple example as sometimes the reason might reside in the code too...


text: Q: Can't get 100% happiness, it's stuck at 99% and EA support doesn't know either I am currently level 25 and all my buildings are maxed construction, they are all covered by parks and population booster buildings, they have plenty of everything and I've followed everything they've asked in the small chat bubbles to a T, but for some reason my happiness level will only stay at 99%, it's been like this for months. I've tried everything and the support EA has no idea either… Does anyone have any tips or ideas?


text:
Q: Elasticsearch query to match on one nested object, but return another I have an ElasticSearch mapping as follows:
{
  "person": {
    "properties": {
      "accounts": {
        "type": "nested",
        "properties": {
          "username": {
            "type": "string"
          }
          "account_type": {
            "type": "string"
          }
        }
      }
    }
  }
}

I want to write a query that matches the username for at least one of the nested accounts, but only returns the inner hit for the account that matches a specific type.
For example, for a person with accounts
{"accounts": [{"username": "Foo", "type": "foo-type"},
              {"username": "Bar", "type": "bar-type"}]}}

I want a query that when searching for username "fo*", and type "bar-type", will return the user with an inner hit containing the nested object {"username": "Bar", "type": "bar-type"}, because the user has at least one account that matches the username, but the "bar-type" account type is always the one returned.
My query so far, looks like:
{
  "query": {
    "filtered": {
      "query": {
        "nested": {
          "inner_hits": {
            "size": 1
          }
          "path": "accounts",
            "query": {
              "bool": {
                "must": [
                  {
                    "query": {
                    "wildcard": {
                      "accounts.username": {
                        "value": "fo*"
                      }
                    }
                  }
                ]
              }
            }
          }
        }
      }
    }
  }
}

but (for obvious reasons) this returns the inner hit that matches the query. I'm not sure how to amend the query to return a different nested object that matches on the type "bar-type" as specified.


text:
Q: NUnit testcase generation: how to create sub-folders (hierarchy)? I am generating NUnit testcases based on the file names.
The directory looks like this:
Customer
    CustomerTestCase1.xml
    CustomerTestCase2.xml

Account
    AccountTestCase1.xml
    AccountTestCase2.xml

I am using TestCaseSource:
    string[] list = Directory.GetFiles(path, "*", SearchOption.AllDirectories)

    foreach (string file in list)
    {
        yield return new TestCaseData(file)
    }

How do I introduce hierarchy into the generated testcases? I need them to be organized in groups according to folder structure, so I could tick "Account" and all the account testcases would be selected.

A: Charlie Poole @ NUnit-Discuss
Hi Andrey,
If that structure is dynamic, then there is little you can do. However,
if the structure does not change, then you can simply code multiple
fixtures, with tests that take data from different sources.
So you might have a Customer fixture, pulling test data from some
particular source or sources, and an Account fixture pulling its data
from other sources.
Put the common code for these fixtures into a base class so that
you don't have to repeat the logic. In fact, it should be easy to
refactor directly from what you have to use of a base class and
then to create separate leaf classes for the tests you want to
select separately.
Charlie
http://groups.google.com/group/nunit-discuss/browse_thread/thread/543102e801511c41


text:
Q: how to add beginning of file to another file using loop I have files 1.txt, 2.txt, 3.txt and 1-bis.txt, 2-bis.txt, 3-bis.txt
cat 1.txt
#ok
#5
6
5

cat 2.txt
#not ok
#56
13
56

cat 3.txt
#nothing
#

cat 1-bis.txt
5
4

cat 2-bis.txt
32
24

cat 3-bis.txt

I would like to add lines starting with # (from non bis files) at the beginning of files "bis" in order to get:
cat 1-bis.txt
#ok
#5
5
4

cat 2-bis.txt
#not ok
#56
32
24

cat 3-bis.txt
#nothing
#

I was thinking to use grep -P "#" to select lines with # (or maybe sed -n) but I don't know how to loop files to solve this problem
Thank you very much for your help

A: You can use this solution:
for f in *-bis.txt; do
  { grep '^#' "${f//-bis}"; cat "$f"; } > "$f.tmp" && mv "$f.tmp" "$f"
done

If you only want # lines at the beginning of the files only then use:
Change
grep '^#' "${f//-bis}"

with:
awk '!/^#/{exit}1' "${f//-bis}"

A: You can loop over the ?.txt files and use parameter expansion to derive the corresponding bis- filename:
for file in ?.txt ; do
    bis=${file%.txt}-bis.txt
    grep '^#' "$file" > tmp
    cat "$bis" >> tmp
    mv tmp "$bis"
done

You don't need grep -P, simple grep is enough. Just add ^ to only match the octothorpes at the beginning of a line.


text:
Q: Looping over *args resets counter I'm working on some made up code to try to understand *args functionality and am having difficulty getting my counter variable to not reset.
After the 4th item, the numbering resets back to 0, but I want it to continue across the args.
lst = ['apple', 'banana', 'orange', 'lemon']
lst2 = ['apple2', 'banana2', 'orange2', 'lemon2']
lst3 = ['apple3', 'banana3', 'orange3', 'lemon3']

def generateMenu(*args):
    counter = 0

    for i in args:
        def recurse(l, counter):
            for i in l:
                counter += 1
                if isinstance(i, (list, tuple)):
                    recurse(i, counter)
                else:
                    print("{}. {}.".format(counter, i))
        recurse(i, counter)

generateMenu(lst, lst2, lst3)

Output:
1. apple.
2. banana.
3. orange.
4. lemon.
1. apple2.
2. banana2.
3. orange2.
4. lemon2.
1. apple3.
2. banana3.
3. orange3.
4. lemon3.

A: You should make counter a nonlocal (nonlocal was introduced in Python3)
lst = ['apple', 'banana', 'orange', 'lemon']
lst2 = ['apple2', 'banana2', 'orange2', 'lemon2']
lst3 = ['apple3', 'banana3', 'orange3', 'lemon3']

def generateMenu(*args):
    counter = 0

    for i in args:
        def recurse(l):
            nonlocal counter
            for i in l:
                counter += 1
                if isinstance(i, (list, tuple)):
                    recurse(i)
                else:
                    print("{}. {}.".format(counter, i))
        recurse(i)

generateMenu(lst, lst2, lst3)

Alternatively, return counter from recurse
lst = ['apple', 'banana', 'orange', 'lemon']
lst2 = ['apple2', 'banana2', 'orange2', 'lemon2']
lst3 = ['apple3', 'banana3', 'orange3', 'lemon3']

def generateMenu(*args):
    counter = 0

    for i in args:
        def recurse(l, counter):
            for i in l:
                counter += 1
                if isinstance(i, (list, tuple)):
                    counter = recurse(i, counter)
                else:
                    print("{}. {}.".format(counter, i))
            return counter
        counter = recurse(i, counter)

generateMenu(lst, lst2, lst3)

A: The problem is that your recurse function is not aware of your counter from upper scope. So what you are increasing in each for i in l: loop is just the "inner" counter variable.
Your example might confuse you because you are using same variable names twice (counter and i). Try to rename them in a different way and you might get a better idea of what is happening with your code.

A: Python has slightly odd rules about writing to variables outside of the function's scope. The easiest way to avoid this IMO is just to make sure that your recursive function returns the counter value at each state. I've slightly refactored to make it a bit clearer what is going on.
lst = [('apple', 'banana'), 'orange', 'lemon']
lst2 = ['apple2', 'banana2', 'orange2', 'lemon2']
lst3 = ['apple3', 'banana3', 'orange3', 'lemon3']

def generateMenu(*args):
    outer_counter = 1

    def recurse(l, inner_counter):
        for i in l:
            if isinstance(i, (list, tuple)):
                inner_counter = recurse(i, inner_counter)
            else:
                print("{}. {}.".format(inner_counter, i))
                inner_counter += 1
        return inner_counter

    for i in args:
        outer_counter = recurse(i, outer_counter)

generateMenu(lst, lst2, lst3)


text:
Q: How to iterate columns with control statement? I have the following code right now:
import pandas as pd

df_area=pd.DataFrame({"area":["Coesfeld","Recklinghausen"],"factor":[2,5]})
df_timeseries=pd.DataFrame({"Coesfeld":[1000,2000,3000,4000],"Recklinghausen":[2000,5000,6000,7000]})

columns_in_timeseries=list(df_timeseries)
columns_to_iterate=columns_in_timeseries[0:]

newlist=[]

for i,k in enumerate(columns_to_iterate):
    new=df_area.loc[i,"factor"]*df_timeseries[k]
    newlist.append(new)

newframe=pd.DataFrame(newlist)
df1_transposed = newframe.T

The code multiplys each factor from an area with the timeseries from that area. In this example the code is iterating immediately the rows and columns after multiplying. In the next step I want to expand the df_area-Dataframe like the following:
df_area=pd.DataFrame({"area":["Coesfeld","Coesfeld","Recklinghausen","Recklinghausen"],"factor":[2,3,5,6]})

As you can see, I have different factors for the same area. The goal is to iterate the columns in df_timeseries only when the area in df_area changes. My first intention is to use an if-Statement but right now I have no idea how to realize that with the for-loop.

A: I can't shake off the suspicion that there is something wrong about your whole approach. A first red flag is your use of wide format instead of long format – in my experience, that's probably going to cause you unnecessary trouble.
Be it as it may, here's a function that takes a data frame with time series data and a second data frame with multiplier values and area names as arguments. The two data frames use the same structure as your examples df_timeseries (area names as columns, time series values as cell values) and df_area (area name as values in column area, multiplier as value in column factor). I'm pretty sure that this is not a good way to organize your data, but that's up to you to decide.
What the function does is it iterates through the rows of the second data frame (the df_area-like). It uses the area value to select the correct series from the first data frame (the df_timeseries-like), and multiplies this series with the factor value from that row. The result is added as an element within a list generator.
def do_magic(df1, df2):
    return [df1[area] * factor for area, factor in zip(df2.area, df2.factor)]

You can insert this directly into your code to replace your loop:
df_area = pd.DataFrame({"area": ["Coesfeld", "Recklinghausen"],
                        "factor": [2, 5]})
df_timeseries = pd.DataFrame({"Coesfeld": [1000, 2000, 3000, 4000],
                              "Recklinghausen": [2000, 5000, 6000, 7000]})

newlist = do_magic(df_timeseries, df_area)
newframe = pd.DataFrame(newlist)
df1_transposed = newframe.T

It also works with your expanded df_area. The resulting list will consist of four series (two for Coesfeld, two for Recklinghausen).


text:
Q: SQl query calculations across multiple tables OK, I have 3 database tables at the moment:

*

*users

*

*id: 1, 2

*name: User1, User2

*companies

*

*id: 1, 2, 3

*share_price: 10.00, 0.45, 5.98

*portfolios

*

*user_id: 1, 1, 2

*company_id: 1, 2, 1

*amount_of_shares: 200, 100, 30

Just so you know, this is for a basic stock market simulation. I need to get the top 5 users based on their total portfolio values, which are calculated as such:
companies.share_price * portfolios.amount_of_shares
Keeping in mind that 1 user can have stock from multiple companies in his portfolio, it seems like a waste to select all the data and then loop through it in PHP, because theoretically I could have about 200 companies... So I was wondering if it's possible to write an SQL query that calculates the value of each companie's stock owned and then sums all of those values up to produce only one variable, so I can do ORDER BY and LIMIT 5 (get the Top5 performers)
EDIT: I'm using CodeIgniter for this project, if that makes a difference.

A: SELECT *, SUM(amount_of_shares*c.share_price) as total FROM `portfolios`
LEFT JOIN companies c ON c.id = portfolios.company_id
GROUP BY `user_id`
ORDER BY total DESC
LIMIT 5

A: select u.name, sum(c.share_price * p.amount_of_shares) as total
from portfolios p
inner join companies c on p.company_id = c.id
inner join users u on p.user_id = u.id
group by u.name
order by total desc
LIMIT 5


text:
Q: Flutter Offline app with Spring Boot as Backend using MongoDB Currently, I have a flutter app using Spring Boot Framework with MongoDB. I want to add Offline functionality to the application.
App Functionality:
User fills various forms(personal details, family member details, etc).
Use Case: When the user fills the Personal Details Form fields like 'name', 'dob' are filled manually and location (selected using the dropdown(GET APIs)).
The internet connection might be gone while filling these forms.
How can I make the application offline ready?
One way that I thought of is storing all the data using any local database like SQLite but there can more than 10 Forms so it can be difficult for maintaining a lot of data. Moreover, how the data will sync with Backend?
Questions:
How to store data?
How to sync store data with Backend when the app comes Online?
Is there any other better approach to achieve this task?


text:
Q: Is there a way to play an .ogg file in Android at an increased speed? I have sound files that I want to play at 1x speed, 2x speed and 3x speed. It should be pitch corrected. There are many solutions for changing the file offline and simple having three files. However that means that my app takes more disc space.
Is there a straightforward way for online speed increase, so that I only have to include one version of the file in my App?
My App is closed source, so I can't use a GLP library.

A: The feature you are probably looking for is Audio Time Stretching. Simply changing the sample rate is not an option as it will induce pitch variation (similar to the effect produced by analogue records or cassettes)
If you want true time stretching, try using a real-time Digital Signal Processing Library. If you're willing to add an additional library to your project, TarsosDSP is a native Java framework works on Android on default.
https://github.com/JorenSix/TarsosDSP
There is even Audio Time Stretching example code included in their repository which even comes with a swing interface.
EDIT: TarsosDSP is GPL'd. Audio timestretching is a big deal in the audio industry so many of the algorithms used are either proprietary or GPL'd.
If you are willing to learn some DSP, I would recommend checking out
https://github.com/philburk/jsyn
It is under the Apache license and supports Android.


text:
Q: Visual Studio setup project and msm file I need to create a Setup Project using Visual Studio. This project contains a .msm file and no Others files.
When I create the .msi file correctly it creates an empty folder in Application Folder and all my software work properly.
There is a way to create a Setup Project without the Application Folder considering that it is an empy folder?
Thank you.


text:
Q: Move sign in to bottom in my top links I want my top links in the order like:

*

*My Account

*My Wishlist

*My Orders

*Sign In

But I am getting like:

*

*My Account

*My Wishlist

*Sign In

*My Orders

Below is my code:
<referenceBlock name="top.links">
        <block class="Magento\Customer\Block\Account\AuthorizationLink" name="authorization-link" before="my-account-link"
               template="Magento_Customer::account/link/authorization.phtml"/>

        <block class="Magento\Customer\Block\Account\Link" name="my-account-link" after="authorization-link">
            <arguments>
                <argument name="label" xsi:type="string" translate="true">My Account</argument>
                <argument name="sortOrder" xsi:type="number">110</argument>
            </arguments>
        </block>
        <block class="Magento\Framework\View\Element\Html\Link\Current" name="customer-account-navigation-orders-link-top" after="my-account-link" before="-">
            <arguments>
                <argument name="path" xsi:type="string">sales/order/history</argument>
                <argument name="label" xsi:type="string" translate="true">My Orders</argument>
            </arguments>
        </block>

        <block class="Magento\Customer\Block\Account\RegisterLink" name="register-link">
            <arguments>
                <argument name="label" xsi:type="string" translate="true">Create an Account</argument>
            </arguments>
        </block>

    </referenceBlock>

A: Try the below code instead of yours:
<referenceBlock name="top.links">
    <block class="Magento\Customer\Block\Account\Link" name="my-account-link">
        <arguments>
            <argument name="label" xsi:type="string" translate="true">My Account</argument>
            <argument name="sortOrder" xsi:type="number">110</argument>
        </arguments>
    </block>
    <block class="Magento\Customer\Block\Account\SortLinkInterface" name="customer-account-navigation-orders-link">
        <arguments>
            <argument name="path" xsi:type="string">sales/order/history</argument>
            <argument name="label" xsi:type="string" translate="true">My Orders</argument>
            <argument name="sortOrder" xsi:type="number">40</argument>
        </arguments>
    </block>
    <block class="Magento\Customer\Block\Account\AuthorizationLink" name="authorization-link" after="customer-account-navigation-orders-link-top"
           template="Magento_Customer::account/link/authorization.phtml">
        <arguments>
            <argument name="sortOrder" xsi:type="number">10</argument>
        </arguments>
    </block>
</referenceBlock>

Flush the cache and test.


text:
Q: I'm already using a functional component and I keep getting error : Hooks can only be called inside the body of a function component Hello I'm trying to use hooks in my component but I keep getting this message :
Hooks can only be called inside the body of a function component.
There are three common reasons you might be seeing it:
You might have mismatching versions of React and React DOM.
You might be breaking the Rules of Hooks.
You might have more than one copy of React in the same app.
although my react version is 17.0.2 my react dom version is 17.0.2 and my react native version is 0.64.2
here is my code

import React,{useState,useEffect} from 'react';
import {View, Text, Alert, StyleSheet, TouchableOpacity} from 'react-native';

import {
  DrawerContentScrollView,
  DrawerItemList,
  DrawerItem,
} from '@react-navigation/drawer';

import AsyncStorage from '@react-native-community/async-storage';
import { GoogleSignin, statusCodes } from '@react-native-google-signin/google-signin';

const CustomSidebarMenu = (props) => {
  const[user,setUser] = useState({})

    signOut = async () => {
        try {
          await GoogleSignin.revokeAccess();
          await GoogleSignin.signOut();
          this.setState({ user: null }); // Remember to remove the user from your app's state as well
        } catch (error) {
          console.error(error);
        }
      };

      getCurrentUser = async () => {

        const currentUser = await GoogleSignin.getCurrentUser();
        setUser(currentUser)

      };

  return (
    <View style={stylesSidebar.sideMenuContainer}>
      <View style={stylesSidebar.profileHeader}>
        <View style={stylesSidebar.profileHeaderPicCircle}>
          <Text style={{fontSize: 25, color: '#307ecc'}}>
            {'A'.charAt(0)}
          </Text>
        </View>
        <Text >
            {user}
        </Text>
      </View>
      <View style={stylesSidebar.profileHeaderLine} />

      <DrawerContentScrollView {...props}>
        <DrawerItemList {...props} />

        <DrawerItem
          label={({color}) =>
            <Text style={{color: '#d8d8d8'}}>
              Déconnexion
            </Text>
          }
          onPress={() => {
            props.navigation.toggleDrawer();
            Alert.alert(
              'Déconnexion',
              'Vous êtes sur?',
              [
                {
                  text: 'Annuler',
                  onPress: () => {
                    return null;
                  },
                },
                {
                  text: 'Confirmer',
                  onPress: () => {
                    AsyncStorage.clear();
                    props.navigation.replace('Auth');
                    signOut();
                  },
                },
              ],
              {cancelable: false},
            );
          }}
        />
      </DrawerContentScrollView>
    </View>
  );
};

export default CustomSidebarMenu;

const stylesSidebar = StyleSheet.create({
  sideMenuContainer: {
    width: '100%',
    height: '100%',
    backgroundColor: '#307ecc',
    paddingTop: 40,
    color: 'white',
  },
  profileHeader: {
    flexDirection: 'row',
    backgroundColor: '#307ecc',
    padding: 15,
    textAlign: 'center',
  },
  profileHeaderPicCircle: {
    width: 60,
    height: 60,
    borderRadius: 60 / 2,
    color: 'white',
    backgroundColor: '#ffffff',
    textAlign: 'center',
    justifyContent: 'center',
    alignItems: 'center',
  },
  profileHeaderText: {
    color: 'white',
    alignSelf: 'center',
    paddingHorizontal: 10,
    fontWeight: 'bold',
  },
  profileHeaderLine: {
    height: 1,
    marginHorizontal: 20,
    backgroundColor: '#e2e2e2',
    marginTop: 15,
  },
});

A: I think it's because you forgot to change the this.setState to setUser in signOut

    const signOut = async () => {
        try {
          await GoogleSignin.revokeAccess();
          await GoogleSignin.signOut();
          setUser(null); // Remember to remove the user from your app's state as well
        } catch (error) {
          console.error(error);
        }
      };

A: I think you forget to declare const in your function
 const signOut = async () => {
        try {
          await GoogleSignin.revokeAccess();
          await GoogleSignin.signOut();
          this.setState({ user: null }); // Remember to remove the user from your app's state as well
        } catch (error) {
          console.error(error);
        }
      };

      const getCurrentUser = async () => {

        const currentUser = await GoogleSignin.getCurrentUser();
        setUser(currentUser)

      };

or
async function signOut() {}
async function getCurrentUser() {}


text:
Q: Angular 4 Routing Issues Angular does not seem to be loading the components that I configure to the empty '' path.
Here is my project set up:
project/
|- app/
|   |- landing-page/
|   |- second-page/
|   |- third-page/
|   |- app-routing.module.ts
|   |- app.component.html
|   |- app.component.ts
|   `- app.module.ts
|- index.html
`- main.ts

app-routing.component.ts:
const appRoutes: Routes = [{
        path: '',
        loadChildren: 'app/landing-page/landing-page.module#LandingPageModule'
    },{
        path: 'second',
        loadChildren: 'app/second-page/second-page.module#SecondPageModule'
    },{
        path: 'third',
        loadChildren: 'app/third-page/third-page.module#ThirdPageModule'
    },{
        path: '**',
        redirectTo: '/'
}]

@NgModule({
    imports: [
        RouterModule.forRoot(
            appRoutes,
           { enableTracing: true }
        )
    ],
    exports: [
        RouterModule
    ]
})
export class AppRoutingModule { }

app.component.html:
<router-outlet></router-outlet>

index.html:
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>AnguTest</title>
    <base href="/">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
    <app-root></app-root>
</body>
</html>

landing-page.component.ts (all 3 components are declared just like this):
const landingRoutes: Routes = [
  { path: '',  component: LandingPageComponent }
]
export const landingRouting = RouterModule.forChild(landingRoutes)

@NgModule({
  imports: [
    CommonModule,
    landingRouting
  ],
  declarations: [LandingPageComponent]
})
export class LandingPageModule { }

The problem is whenever I navigate to the app in my browser, the output is always:
second-page works!

Even when I change the url to http://localhost:4200/ or http://localhost:4200/third, I only ever see the out put of the 2nd page.
I have tried to rearrange the route declaration order but it is still always the second-page.
If its helpful, I have included the output from the Chrome console. It looks like the app is identifying the route correctly.
Router Event: NavigationStart
NavigationStart(id: 1, url: '/')
NavigationStart
Angular is running in the development mode. Call enableProdMode() to enable the production mode.
Router Event: RoutesRecognized
RoutesRecognized(id: 1, url: '/', urlAfterRedirects: '/', state: Route(url:'', path:'') { Route(url:'', path:'') } )
RoutesRecognized
Router Event: GuardsCheckStart
GuardsCheckStart(id: 1, url: '/', urlAfterRedirects: '/', state: Route(url:'', path:'') { Route(url:'', path:'') } )
GuardsCheckStart
Router Event: GuardsCheckEnd
GuardsCheckEnd(id: 1, url: '/', urlAfterRedirects: '/', state: Route(url:'', path:'') { Route(url:'', path:'') } , shouldActivate: true)
GuardsCheckEnd
Router Event: ResolveStart
ResolveStart(id: 1, url: '/', urlAfterRedirects: '/', state: Route(url:'', path:'') { Route(url:'', path:'') } )
ResolveStart
Router Event: ResolveEnd
ResolveEnd(id: 1, url: '/', urlAfterRedirects: '/', state: Route(url:'', path:'') { Route(url:'', path:'') } )
ResolveEnd
Router Event: NavigationEnd
NavigationEnd(id: 1, url: '/', urlAfterRedirects: '/')
NavigationEnd

========== RESOLVED ==========
The problem was that I did not actually declare the route config in all of my modules:
// this bit....
const landingRoutes: Routes = [
  { path: '',  component: LandingPageComponent }
]
export const landingRouting = RouterModule.forChild(landingRoutes)

The empty path '' was not working because I was importing the Modules which I was routing to in app.module.ts, effectively doing a double import and causing weird behavior.
After removing the FirstPageModule and SecondPageModule from the imports list, the issue was resolved.
See this answer for more details:
Default route redirect not working for lazy loaded routes in Angular 2

A: Try Changing the route to some thing like this
  const appRoutes: Routes = [
    {
      path:'',
      redirectTo: 'first',
      pathMatch: 'full'
    },
    {
      path: 'first',
      loadChildren: 'app/landing-page/landing-page.module#LandingPageModule'
    },
    {
     path: 'second',
     loadChildren: 'app/second-page/second-page.module#SecondPageModule'
    },
    {
     path: 'third',
     loadChildren: 'app/third-page/third-page.module#ThirdPageModule'
   },
   {
     path: '**',
     redirectTo: '/'
  }];


text:
Q: Configuring VNC session for admin rights on ubuntu I configured VNC on Ubuntu headless, using this tutorial.
I don't have any administrative access to set up anything and I need to know what I need to do to raise the level permission on the file system. What should I do?


text:
Q: How do I use the FileUpload Class in an MVC web app I am using this post as a reference for what I want to do. I am trying to add a button on my web app that allows the user to click a button upload an excel document straight to a database. In the example I am referencing they use the FileUpload class but It appears I do not know how to use this in a web app.
I attempted putting it in a service file:
 FileUpload fileUpload1 = new FileUpload();

but I cannot reference the fileUpload1 variable in that context. My best guess at this point is that this is a web app and I am trying to use a windows form class. I get a reference to System.Web.UI.WebControls; when I use it though.
Any suggestions?


text:
Q: Spark job ( oozie - hue) stuck in running state I have a spark job to convert csv to parquet. And I am trying to run it via oozie workflow in hue. It is the simplest workflow comprising a single step(a spark program).
When I run it for a simple program jar(say hello spark types example), it works fine when submitted via hue.
But when I have a bigger jar(~96 MB), the job gets stuck in running state.
There is no issue with the code as the same jar works perfectly with spark-submit on the very same environment, with the same conditions - running both in client mode for simplicity of debugging.
Also, normally you can view from logs if there are certain exceptions or the job is hung due to memory issues(the continuous 'heart beat' info logs) but in this case I cannot even view the logs. When i manually kill the job, still no logs are accessible, it says :

Could not find job job_1481270830724_0007.
{"RemoteException":{"exception":"NotFoundException","message":"java.lang.Exception:
  job, job_1481270830724_0007, is not
  found","javaClassName":"org.apache.hadoop.yarn.webapp.NotFoundException"}}
  (error 404)

Can you help letting me know what could be the issue?
Is it something to do with memory allocated for hue?

A: Which version of Hue are you using? I am asking cause there is a bug in Cloudera's JIRA. Better handling of expired YARN apps
Maybe you should upgrade version of Hue.


text:
Q: Dot Net Nuke 7.2 (To get RollInfo by Role name) I am using DNN 7.2 I want to get RoleInfo Object by Roll name.
Please suggest
Following code giving me error
RoleController.GetRoleByName(portalSettings.PortalId, Role);
Error :Error    35  An object reference is required for the non-static field, method, or property 'DotNetNuke.Security.Roles.RoleController.GetRoleByName(int, string)'

A: I got it.
var roleController = new RoleController();
                    RoleInfo roleInfo = roleController.GetRoleByName(portalSettings.PortalId, Role);


text:
Q: Can't find the ADF Swing option on JDeveloper 12.1.3 Has it been removed in 12c? Can't find the ADF Swing tier. I can only use it on JDeveloper 11c.

A: it is  Deprecated starting from Version: 11.1.2
but still supported, with no future enhancements as Oracle says in this URL
http://www.oracle.com/technetwork/developer-tools/jdev/12cdeprecatedfeatures-2542989.html
you can use version 11.1.6, to build ADF Swing apps.


text: Q: Connections in Pyqt forms I have been newly working on developing a desktop application and i am stuck with this topic. I have two forms and I want to connect Buttons/widgets of one form to Buttons/widgets of another. Is it even possible to do that? I know it can be done in the same form but if someone knows about it, please help. Thanks in advance


text:
Q: Create mysql select - multiple parameters (some are unnecessary) Let's asume I have following object in PHP:
class param{
 public $home; //set by another function
 public $user; //set by another function
 public function createRequest(){
//in this function I want to create mysql string with $home and $user
  $sql = "select * FROM table WHERE home =".$this->home." AND user=".$this->user;
  return $sql;
}

Problem is, that $home (or $user) could be empty string and in this case I want to include all homes (or users), not just columns, where home="" (or user="");
Do you have any suggestion how to do that? Or is this idea wrong? (I'm just beginner with PHP)

A: This is not the most elegant, and we should be using PDO prepared statements... but for sake of example:
class param{
  public $home; //set by another function
  public $user; //set by another function
  public function createRequest(){
    //in this function I want to create mysql string with $home and $user
    $sql = "select * FROM table";
    if(strlen($this->home) || strlen($this->user)) {
      $sql .= " WHERE ";
      $and = array();
      if(strlen($this->home))
        $and[] = " home='".$this->home."' ";
      if(strlen($this->user))
        $and[] = " user='".$this->user."' ";
      $sql .= implode(" AND ", $and);
    }
    return $sql;
  }
}

Example test output:
$p = new param;
echo $p->createRequest();
echo "
";

$p->home = "foo";
echo $p->createRequest();
echo "
";

$p->user = "bar";
echo $p->createRequest();
echo "
";

$p->home = "";
echo $p->createRequest();

Will yield:
select * FROM table
select * FROM table WHERE home='foo'
select * FROM table WHERE home='foo' AND user='bar'
select * FROM table WHERE user='bar'

A: class param{
 public $home; //set by another function
 public $user; //set by another function
 public function createRequest(){
//in this function I want to create mysql string with $home and $user
    $ClauseArray = array(' 1 = 1 ');
    if ($this->home != '') $ClauseArray[] = " home = '".$this->home."' ";
    if ($this->user != '') $ClauseArray[] = " user = '".$this->user."' ";
    $sql = "select * FROM table WHERE ".implode('AND', $ClauseArray);
    return $sql;
}


text:
Q: How to pass debug messages to a macro in SystemVerilog I'm attempting the following SystemVerilog:
`define DEBUG (ARG) \
`ifdef DEBUG_ON \
  $display ARG;
`endif

module my_mod;
logic a;
logic [1:0] b;

assign a = 1'b0;
assign b = 2'b01;

`DEBUG(("a=%x, b=%b", a, b))
endmodule

VCS gives me the following compile error:
Error-[SE] Syntax error
  Following verilog source has syntax error :
  "/media/psf/Home/projects/dep2/hw/rtl/dep_dc/dep_dc_cs.sv", 254 (expanding
  macro): token is '('
        `DEBUG(("a=%x, b=%b", a, b))
              ^

#0, DEBUG : "<my_file>":21
full expansion of macro (DEBUG), error at line 1
=>(ARG)
  `ifdef DEP_DEBUG_ON
  ...

According to this answer: How to emulate $display using Verilog Macros?
This seems like the correct syntax to me. Can someone spot anything wrong?

A: So I found it apparently, the compiler doesn't like spaces between the macro definition and arguments:
`define DEBUG(ARG) \
`ifdef DEBUG_ON \
  $display ARG;
`endif

Works.


text:
Q: How to Get input in one page and print in next Html page using Angular 2

Am new to Angular 2, and am working with data binding I don't know how to print the value from one page to another throw components.I am trying with this piece of code but it prints the value in the same page, If anybody knows the logic help me, Thanks in advance!
//child.component.ts
import {Component, EventEmitter, Input, Output} from '@angular/core';
import {Student} from './student';
import {Router} from '@angular/router';

@Component({
    selector: 'child-one',
    template: `

{{childTitle}}

          First Name:<input (input)="student.fname=$event.target.value" />

          Last Name:<input (input)="student.lname=$event.target.value" />
          <button (click)="addStudent()">Add Student</button>

    `,
})

export class ChildOneComponent {

    constructor(private _router: Router){ }

    @Output('addStudentEvent')
    addStdEvent = new EventEmitter<Student>();

    student = new Student();
    childTitle = '---Child One---';

    addStudent() {
       this.addStdEvent.emit(this.student);
       this._router.navigate(['name']);
    }
}

//Parent.component.ts
import {Component,EventEmitter,Input} from '@angular/core';
import {Student} from './student';
import {Router} from '@angular/router';

@Component({
   selector: 'input-output',
   template: `

{{parentTitle}}

Name: {{stdFullName}}

      <child-one  (addStudenztEvent) = "saveData($event)"></child-one>
    `
    // providers: [Student]
    })

export class ParentComponent {
    parentTitle = 'Parent Component';
    stdAddMsg = 'Add Student';

    //Property used in parent
    stdFullName = '';

    saveData(std) {
        this.stdFullName = std.fname + ' ' + std.lname ;
    }
}

A: This issue is about "Communication between components"
You can find answer here:

https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service


text:
Q: 8086 emulator for mac OSX I want to study about 8086 instructions. I want to know how the registers, flags, stack pointer etc are changing according to each instructions. So that I want to install an 8086 emulator in my Mac OS. Can anyone suggest me some options?
I have installed dosBox and checked it. But I cant find a way to see the register values, flags etc..
If there is no such emulator please suggest me some good tutorials. I want to know , how the segment registers(ES, CS, DS, SS, IP), general purpose registers(AX, BX, CX,DX, SP,BP, SI, DI), and all the flags(OF, DF,IF,TF, ZF,SF, AF, PF,CF) are changing according to each instruction.

A: Both QEMU and Bochs can be used for Mac OSx.
(Never tried this on my own, but projects are really good)


text:
Q: Calligraphic or handwriting fonts that use diacritics As the subject heading suggests, I'm looking for a calligraphic or (if need be) handwriting font for a small part of my document that renders letters with macrons (a kind of diacritic), like this:
Quō ūsque tandem, Catilina, abūtēre patientiā nostrā?
I'd love one that works using a pdfLaTeX compiler on Overleaf without my needing to tie myself in knots to get it done, but I realize that may be asking too much.
I've tried Calligra and Augie, and either the macrons didn't show up (Calligra) or the letters with macrons showed up as black boxes (Augie). Then a friend significantly more knowledgeable than I said she didn't know of anybody, so I figured the next step was to turn to the experts.
Is there a way out of this pickle?

A: If you're free to use either XeLaTeX or LuaLaTeX, there are literally hundreds, if not thousands, of chancery-type and handwriting-type fonts out there that are set up to handle diacritics.
The following example shows just two such possibilities: Apple Chancery and Zapfino. (Times New Roman is shown mostly for contrast.)

\documentclass{article}
\usepackage{fontspec}
\setmainfont{Times New Roman} % set a suitable default text font
\defaultfontfeatures{Scale=MatchUppercase}
\newfontfamily{\AC}{Apple Chancery}
\newfontfamily{\zapfino}{Zapfino}
\begin{document}
\obeylines % just for this document
Times New Roman
Quō ūsque tandem, Catilina, abūtēre patientiā nostrā?
\bigskip Apple Chancery
{\AC Quō ūsque tandem, Catilina, abūtēre patientiā nostrā?}
\bigskip ...
\bigskip Zapfino
{\zapfino Quō ūsque tandem, Catilina, abūtēre patientiā nostrā?}
\end{document}

A: Of the type 1 fonts listed in the font catalogue, miama appears to work:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{miama}
\begin{document}
\fmmfamily
Quō ūsque tandem, Catilina, abūtēre patientiā nostrā?

Qu\=o \=usque tandem, Catilina, ab\=ut\=ere patienti\=a nostr\=a?
\end{document}

The TeX Gyre version of Zapf Chancery also works:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{tgchorus}
\begin{document}
Quō ūsque tandem, Catilina, abūtēre patientiā nostrā?

Qu\=o \=usque tandem, Catilina, ab\=ut\=ere patienti\=a nostr\=a?
\end{document}


text:
Q: Web placeholder issue with the input excel data which is getting overlapped While finding if the email address is valid or not, I am getting this issue wherein placeholder from Web site always hides my excel input and it don't go to next command.
Also need to capture the message from innertext of web page in excel next to email address.
Using VBA web will enter email from cell A2 of excel in Sign in page of web and click on next.
Sub Test()
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.navigate "https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=13&ct=1549662555&rver=6.7.6631.0&wp=MBI_SSL&wreply=https%3a%2f%2fwww.bing.com%2fsecure%2fPassport.aspx%3frequrl%3dhttps%253a%252f%252fwww.bing.com%252fsearch%253fq%253dmsn%2526form%253dEDGEAR%2526qs%253dPF%2526cvid%253d904d7a00fd1b4125ab81e0f3bb83208e%2526cc%253dUS%2526setlang%253den-US%2526wlsso%253d1%2526wlexpsignin%253d1%26sig%3d22F3BD543C546368216CB1A93D3562E7&lc=1033&id=264960&CSRFToken=f4af0dd6-d72f-4001-9430-e76c6c91253b&aadredir=1"

Do While IE.readyState <> 4: DoEvents: Loop
IE.document.getElementById("i0116").Value = "absdrs@outlook.com"
End Sub

If there is an error like "account doesn't exist. Enter a different account" mention "error" in front of cell A2 in excel else "valid". It will keep on going to next value in cell A2 till last. (VBA for web in loop)

A: The site is expecting key strokes. Either find a way to trigger this, perhaps with FireEvent, in IE or switch to using selenium basic. After installing selenium basic, go VBE > Tools > References and add a reference to Selenium Type Library.
Option Explicit

Public Sub test()
    Dim d As ChromeDriver, loginDetails(), ws As Worksheet, i As Long
    Set ws = ThisWorkbook.Worksheets("Sheet2")
    loginDetails = ws.Range("A1:B2").Value       ' Column A has email, col B has password
    Set d = New ChromeDriver
    With d
        .get "https://login.live.com/"

        For i = LBound(loginDetails, 1) To UBound(loginDetails, 1)
            .FindElementById("i0116").SendKeys loginDetails(i, 1)
            .FindElementById("idSIButton9").Click

            'Other code ....
        Next
        .Quit
    End With
End Sub


text:
Q: NA when trying to summarize a subset of data (R) Whole vector is ok and has no NAs:
> summary(data$marks)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
   1.00    6.00    6.00    6.02    7.00    7.00

> length(data$marks)
[1] 2528

However, when trying to calculate a subset using a criteria I receive lots of NAs:
> summary(data[data$student=="John",]$marks)
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's
  1.000   6.000   6.000   6.169   7.000   7.000     464

> length(data[data$student=="John",]$marks)
[1] 523

A: I think the problem is that you have missing values for student. As a result, when you subset by student, all the NA values for student end up producing NA for marks when you take your subset. Wrap the subsetting condition in which() to avoid this problem. Here are a few examples that will hopefully clarify what's happening:
# Fake data
set.seed(103)
dat = data.frame(group=rep(LETTERS[1:3], each=3),
                 value=rnorm(9))
dat$group[1] = NA

dat$value
dat[dat$group=="B", "value"]
dat[which(dat$group=="B"), "value"]

# Simpler example
x = c(10,20,30,40, NA)

x>20
x[x>20]

which(x>20)
x[which(x>20)]

A: First Note that NA=="foo" results in NA. When subsetting a vector with a NA value the result is NA.
t = c(1,2,3)
t[c(1,NA)]

A: a tidyverse solution.  I find these to be easier to read than base R.
library(tidyverse)

data %<%
  filter(student == "John") %<%
  summary(marks)


text:
Q: Sort a feature table by geographic location Here's in interesting challenge: I need to embed a table in a map layout so that the records in the table are sorted according to their geographic position on the ground. For example, in a north-to-top map, the northern-most feature (points in this case) should be first record, and the southern-most the last.
The map composition is in ArcGIS, but I'm willing to use gdal/ogr, qgis, etc. for the table sorting if need be.
To expand this question beyond my immediate use case and thereby make it more useful to the community, a robust solution would allow choosing other geographic sorts, such as west to east or inner to outer.

A: To sort in the direction with a bearing of a degrees east of north, precompute the unit direction vector as (sin(a), cos(a)).
With a field calculation, obtain the (projected) [X] and [Y] coordinates of features (use their centroids or whatever for non-point features) if they aren't already available and compute a new field equal to the distance along the bearing, given by the dot product of the direction vector with the coordinates:
z = sin(a) * [X] + cos(a) * [Y]

Sort the table on [z] in ascending order.
For example, for a north-to-south sort the bearing is 180 degrees, v = (sin(180), cos(180)) = (0, -1), and the  resulting sort therefore is on -[Y], which arranges the records from largest [Y] (first) down to smallest [Y] (last), exactly as intended.

An "inner to outer" sort could mean many things, but one interpretation is that the sorting should be by distance relative to a central location.  A similar solution applies, using the Pythagorean theorem to compute (squared) distance from a fixed point.  (Applying the square root is unnecessary because it does not change the sort order.)

A more fanciful sort order is explained and illustrated at "One-dimensional map of the world."

A: To express whuber's answer in terms of tool use, here's a simple implementation of the North-South, East-West use case when using point data in Arcgis:

*

*Add X and Y (or Lat and Long) columns to the attribute table, Calculate Geometry

*export to Excel or whatever, sort by the column of interest (X for East-West, Y for North-South), and then bring back in with Add X/Y data.

courtesy of Esri Technical Article HowTo: Sort features North/South or East/West for Export
How to change the order of features in a shapefile? has solutions to do the table sorting part for both Arcgis and Qgis without need to export to an external program (though you still need to duplicate the table/feature class), and Sorting shapefile records on attribute to update new rank field using Python? has an arcpy method.

A: As commented by @klewis:

ArcGIS 10.0 and greater provides a Spatial Sort option in the Sort Tool

The Sort tool help, which needs an Advanced level license, describes its spatial_sort_method which:
Specifies how features are spatially sorted. Sort method is only enabled when the Shape field is selected as one of the sort fields.
UR —Sorting starts at upper right corner. This is the default.
UL —Sorting starts at upper left corner.
LR —Sorting starts at lower right corner.
LL —Sorting starts at lower left corner.
PEANO —Sorting uses a space filling curve algorithm, also known as a Peano curve.


text:
Q: MessageBox shows Japanese characters when using return value from a function I'm creating a function for get the directory from the current exe file, when I use the variable inside the function ExePath, I get the correct directory, but if I use the return value from the function ExePath in another function, I get Japanese characters. This is my code:
#include <Windows.h>
#include <iostream>
#include <string>
#include <wchar.h>

using namespace std;

LPCWSTR ExePath();

int _tmain(int argc, _TCHAR* argv[])
{
    // ------ > HERE SHOWS JAPANESE CHARACTERS < -------------------------
    MessageBox(NULL, ExePath(), L"Inside main function", MB_OK); // Here show foreign characters

    return 0;
}

// This function returns the directory of this current exe file
LPCWSTR ExePath()
{
    // Get Exe Path
    WCHAR* buffer = new WCHAR[MAX_PATH];
    DWORD len = GetModuleFileName(GetModuleHandle(NULL), buffer, MAX_PATH );
    buffer[len] = L'\0';
    // Get only the directory (without the file name)
    wstring ws(buffer);
    const size_t last_slash_idx = ws.rfind('\\');
    if (std::string::npos != last_slash_idx)
    {
        ws = ws.substr(0, last_slash_idx);
    }
    // Show the directory
    // ws.c_str() = directory
    // ------ > HERE SHOW THE CORRECT DIRECTORY < ------------------------
    MessageBox(NULL, ws.c_str(), L"Inside ExePath Function", MB_OK); // Here show the correct directory
    return ws.c_str();
}

What am I doing wrong?


text:
Q: google-php-spreadsheet-api was return not all data from sheet If in sheet has row with all empty cell. Example:
   cell1     cell2
row1 : not empty not empty
row2 : not empty not empty
row3 : empty     empty
row4 : not empty not empty
row5 : not empty not empty

Google returned data like:
   cell1     cell2
row1 : not empty not empty
row2 : not empty not empty

How get all data with empty cell to. I using php-google-spreadsheet-client . My code:
....

$tokenArray = $client->fetchAccessTokenWithAssertion();
$accessToken = $tokenArray["access_token"];

$serviceRequest = new DefaultServiceRequest($accessToken);
ServiceRequestFactory::setInstance($serviceRequest);
$spreadsheetService = new Google\Spreadsheet\SpreadsheetService();

$tokenArray = $client->fetchAccessTokenWithAssertion();
$accessToken = $tokenArray["access_token"];

$serviceRequest = new DefaultServiceRequest($accessToken);
ServiceRequestFactory::setInstance($serviceRequest);

$spreadsheetService = new Google\Spreadsheet\SpreadsheetService();
$spreadsheetFeed = $spreadsheetService->getSpreadsheets();
$spreadsheet = $spreadsheetFeed->getByTitle('MySpreadsheet');
$worksheetFeed = $spreadsheet->getWorksheets();
$worksheet = $worksheetFeed->getByTitle('Sheet 1');
$listFeed = $worksheet->getListFeed();
foreach ($listFeed->getEntries() as $entry) {
    $values = $entry->getValues();
    $array [] = $values;
}

A: There is a property called 'return-empty' which is set to false by default hence only returning cells that aren't empty in the feed. Set this to 'true' in your cell query and you will be able to update the value of empty cell.
You may use the  Official Google Documentation for your reference. Documentation includes sample codes.


text:
Q: How to make a modern website which deals good with IE7? I have done few sites for my clients but I came to know these are not working very well in IE7, There are still 3% people using IE7 :( What is the super quick way to fix it. You can refer me to some article or some js solution. Please advice!

A: www.modernizr.com/
It doesn't get more super quick that this. Just remember to place it at the beginning of your scripts (in the head)

A: *

*Make sure your sites are not in quirks mode (ie have a valid doctype at the start of the html)

*Use a Javascript framework to hide the browser differences.  There are several options, but MooTools or jQuery are good choices
If you're lucky, it might even work in IE6.

A: Consider using a CSS framework that supports IE7.
For instance, try Cascade Framework. It supports IE from IE6 upwards, is about as feature rich as Bootstrap and has a grid system more flexible than any other grid systems around.


text:
Q: Delegate method to pass data forward I am successfully passing data back between two view controllers using a delegate method.
The first view controller is a "Review" screen and the second is an "Edit" screen which mainly contains a UITextView.
When I change the content of the Text View on the edit screen and hit save it successfully passes to the review screen. However when I return to the Edit screen the UITextView is empty.
How can I make sure the edit screen keeps the value that is stored in the delegate?
Thanks for taking the time to have a look.
Review View Controller
class AddCampaignViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate, TitleViewDelegate {

    @IBOutlet var titleSubtitle: UILabel!

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if segue.identifier == "AddTitleViewController" {

            let addTitleViewController = segue.destinationViewController as! AddTitleViewController

             addTitleViewController.delegate = self

         }

    }

    override func viewDidLoad() {

        super.viewDidLoad()

    }

    func setCampaignTitle(campaignTitle: String) {

        titleSubtitle.text = campaignTitle

    }

}

Edit View Controller
protocol TitleViewDelegate {

    func setCampaignTitle(campaignTitle: String)

}

class AddTitleViewController: UIViewController, UITextViewDelegate {

    var delegate : TitleViewDelegate!

    var campaignTitle : String!

    @IBOutlet var titleTextView: UITextView!

    override func viewDidLoad() {

        super.viewDidLoad()

        titleTextView.becomeFirstResponder()

        let logButton : UIBarButtonItem = UIBarButtonItem(title: "Save", style: UIBarButtonItemStyle.Plain, target: self, action: "saveTitle:")

        self.navigationItem.rightBarButtonItem = logButton

    }

    func saveTitle(sender: UIBarButtonItem) {

            delegate.setCampaignTitle(titleTextView.text!)

            self.navigationController?.popViewControllerAnimated(true)

    }

}

A: The segue will create a new EditViewController every time.  To pass data forward, you will need to assign the data to an EditViewController property and then copy that data into titleTextView.text in the viewDidLoad method.  This is necessary because the @IBOutlets are not set up and are still nil when prepareForSegue runs.
So:

*

*add the property var textToEdit = "" to your EditViewController.

*In prepareForSegue, set addTitleViewController.textToEdit = /* the text you want to edit */

*In viewDidLoad of EditViewController, set titleTextView.text = textToEdit.

Note: Your delegate should be declared weak to avoid a retain cycle (which will cause you to leak memory by never freeing EditViewControllers.  Your @IBOutlets should also be declared weak.


text:
Q: Process huge volume of data using Java As part of the requirement we need to process nearly 3 million records and associate them with a bucket. This association is decided on a set of rules (comprising of 5-15 attributes, with single or range of values and precedence) which derive the bucket for a record.
Sequential processing of such a big number is clearly out of scope.
Can someone guide us on the approach to effectively design a solution?

A: 3 million records isn't really that much from a volume-of-data point of view (depending on record size, obviously), so I'd suggest that the easiest thing to try is parallelising the processing across multiple threads (using the java.util.concurrent.Executor framework). As long as you have multiple CPU cores available, you should be able to get near-linear performance increases.

A: It depends on the data source. If it is a single database, you will spend most of the time retrieving the data anyway. If it is in a local file, then you can partition the data into smaller files or you can pad the records to have equal size - this allows random access to a batch of records.
If you have a multi-core machine, the partitioned data can be processed in parallel. If you determined the record-bucket assignment, you can write back the information into the database using the PreparedStatement's batch capability.
If you have only a single core machine, you can still achieve some performance improvements by designing a data retrieval - data processing - batch writeback separation to take advantage of the pause times of the I/O operations.

A: I'm not quite sure what you're after but here's a blog post about how the New York Times used Apache Hadoop Project to process a large volume of data.

A: As a meaningless benchmark, we have a system that has a internal cache. We're currently loading 500K rows. For each row we generate statistics, place keys in different caches, etc. Currently this takes < 20s for us to process.
It's a meaningless benchmark, but it is an instance that, depending on the circumstances, 3M rows is not a lot of rows on todays hardware.
That said.
As others have suggested, break the job up in to pieces, and parallelize the runs, 1-2 threads per core. Each thread maintains their own local data structures and state, and at the end, the master process consolidates the results. This is a crude "map/reduce" algorithm. The key here is to ensure that the threads aren't fighting over global resources like global counters, etc. Let the final processing of the thread results deal with those serially.
You can use more than one thread per core if each thread is doing DB IO, since no single thread will be purely CPU bound. Simply run the process several times with different thread counts until it comes out fastest.
We've seen 50% speed ups even when we run batches through a persistent queueing system like JMS to distribute the work vs linear processing, and I've seen these gains on 2 core laptop computers, so there is definite room for progress here.
Another thing if possible is don't do ANY disk IO (save reading the data from the DB) until the very end. At that point you have a lot more opportunity to batch any updates that need to be made so you can, at least, cut down on network round trip times. Even if you had to update every single row, large batches of SQL will still show net gains in performance. Obviously this can be memory intensive. Thankfully, most modern systems have a lot of memory.

A: Is there a reason that you have to use Java to process the data? Couldn't you use SQL queries to write to intermediate fields? You could build upon each field -- attributes -- until you have everything in the bucket you need.
Or you could use a hybrid of SQL and java... Use different procedures to get different "buckets" of information and then send that down one thread path for more detailed processing and another query to get another set of data and send that down a different thread path...

A: This goes the same for most projects where you need to process large amounts of information. I am going to assume that each record is the same, e.g. you process it the same way each time, which would be the point you can spawn a separate thread to do the processing.
The second obvious point is where you are fetching your information, this case you mentioned a database, but really that is pretty irrelevant. You want to separate your I/O and processing elements in your code to separate threads (or more likely, a pool of executors for the processing).
Try to make each as independent as possible, and remember to use locking when necessary. Here are some links that you may want to read up on.
http://www.ibm.com/developerworks/library/j-thread.html

http://www.ibm.com/developerworks/java/library/j-threads1.html

http://www.devarticles.com/c/a/Java/Multithreading-in-Java/

A: Effective design steps for this scenario consist of first, determining any and all places where you can partition the records to be processed to allow full-engine parallelization (i.e., four units running against 750k records each is comparatively cheap).
Then, depending upon the cost of the rules that summarize your record (I am viewing assignment of a bucket as a summarization operation), determine if your operation is going to be CPU bound or record retrieval bound.
If you're CPU bound, increasing the partitioning is your best performance gain. If you're IO bound, rule processing worker threads that can work in parallel in response to chunked data retrieval is a better-performing design.
All of this assumes that your rules will not result in state which needs to be tracked between records. Such a scenario deeply threatens the parallelization approach. If parallelization is not a tractable solution because of cumulative state being a component of the rule set, then your best solution may in fact be sequential processing of individual records.

A:
Sequential processing of such a big
  number is clearly out of scope.

I don't think you know that.  How long does it take to process 1,000 records in this way?  10,000?  100,000?  1,000,000?  If the answer is really "too long," then fine: start to look for optimizations.  But you might find the answer is "insignificant," and then you're done.
Other answers have alluded to this, but it's my entire answer.  Prove that you have a problem before you start optimizing.  Then you've at least got a simple, correct system to profile and against which to compare optimized answers.

A: Based on the revised description, I think I'd try and look at sorting the data.
Sorting can be an nlog(n) process; and if most of the comparisons are for direct equality on sortable fields, this should yield a total complexity of ~O(nlog(n)). Theoretically. If after assigning an item to a bucket it's no longer needed, just remove it from the list of data.
Even if the data needed to be resorted a few times for various steps in the logic, it should still be a bit faster then then n^2 approach.
Basically, this would involve preprocessing the data to make it easier for actual processing.
This makes certain assumptions about the logic of bucket assigning (nameley that it's not too far from the psuedo code provided); and would be invalid if you needed to extract data from every pair of A,B.
Hope this helps.
Edit: I would comment if I could; but, alas, I am too new. Preprocessing applies as much to the data as it does to the individual categories. Ultimately all you need to do to go from a 15 minute compute time to a 5 minute compute time is to be able to programmatically determine 2/3s+ of the categories that cannot and will never match... in less then O(n) amortized time. Which might not be applicable to your specific situation, I admit.

A: I would make efforts to push back with the specification author to focus more on 'what' needs to be done, rather than how.  I can't imagine why a specifcation would push'java' for a data intensive operation.  If it has to do with data, do it with SQL.  If your using Oracle there is a function called nTile.  So creating a fixed set of buckets is as trivial as:
select ntile(4)over(order by empno) grp,
 empno,
 ename
from emp
Which results in:
GRP EMPNO ENAME
--- ----- ---------
1  7369 SMITH
1  7499 ALLEN
1  7521 WARD
1  7566 JONES
2  7654 MARTIN
2  7698 BLAKE
2  7782 CLARK
2  7788 SCOTT
3  7839 KING
3  7844 TURNER
3  7876 ADAMS
4  7900 JAMES
4  7902 FORD
4  7934 MILLER

At minimum you could at least establish your 'buckets' in SQL, then your Java Code would just need to process a given bucket.
Worker worker = new Worker(bucketID);
worker.doWork();

If you don't care about the number of buckets (the example above was asking for 4 buckets) tbut rather a fixed size of each bucket (5 records per bucket) then the SQL is:
select ceil(row_number()over(order by empno)/5.0) grp,
  empno,
  ename
from emp

Output:
GRP      EMPNO ENAME
    --- ---------- -------
1       7369 SMITH
1       7499 ALLEN
1       7521 WARD
1       7566 JONES
1       7654 MARTIN
2       7698 BLAKE
2       7782 CLARK
2       7788 SCOTT
2       7839 KING
2       7844 TURNER
3       7876 ADAMS
3       7900 JAMES
3       7902 FORD
3       7934 MILLER

Both examples above come from the terrific book:
SQL Cookbook, 1st Edition by Anthony Molinaro


text:
Q: Accessing a private member without getter function I'm preparing for an exam, and I'm trying to solve a question I suspect might be unsolvable.
In the supermarket, every item you buy has a name, cost, and quantity.
So the teacher defined this class:
class items {
public:
    items(string, double, int);
    void InputItems ();
    void SetCount (int const);
    string GetName () const;
    string toString () const;

private:
    string name;
    double cost;
    int count;
}

But when you go to the supermarket, you don't always buy several copies of just one item. You can buy several items. So our question was to define a class Purchase that handles an array of type items.
I defined it like this:
class Purchase
{
    private:
        items *arr;
        int max_items,current_items;
    public:
        Purchase(int New_max_items){
            max_items=New_max_items;
            current_items=0;
            arr= new items("",0,0)[max_items];
        }
        void AddItem(items const newitems);
        items RemoveItem(string const name);
        int Find(string const name);
        int const sum();
        int get_now();
        items &operator[](int) const;
}

The exercise asked that I implement items &operator[](int) const; and int const sum();. And I managed to implement the operator:
goods & Purchase::operator[](int i) const
{
    if ((i>=0)&&(i<current_items))
        return arr[i];
}

No problem there.
The problem is with the function to sum the entire cost of the purchase.
I can't access arr[i].cost and arr[i].count directly, since they are private members of the class Items, and I can't get them indirectly since the teacher did not include getter functions for those class members in his class Items.
Is it possible to write a program that returns the sum of the entire purchase without changing the class Items?

A: Maybe the purpose is to have a table outside the classes on item names and cost.
So you can call GetName() and GetCount() and lookup the cost for each item in the external table (map or hash table).

A: class Purchase
{
    private:
        items *arr;
        int max_items,current_items;
        **int sum;**
    public:
        Purchase(int New_max_items){
            max_items=New_max_items;
            current_items=0;
            arr= new items("",0,0)[max_items];
            **sum = 0;**
        }
.
.
.

In AddItems() increment the price and in RemoveItems() decrement it ;)


text:
Q: Uipath email activity for multiple email Is it possible to have an array of email addresses (string) to pass into the send email activity on uipath? I can't see a way on the activity, except using the cc but I have 10 email addresses for he same email

A: You can have multiple to addresses separated by the ; character.
The easiest way to do this is to use string.Join method and construct a string from the array.
https://msdn.microsoft.com/en-us/library/57a79xd0(v=vs.110).aspx

A: Create Variable ccMail like this
string ccMail="firstMail;secondMail;thirdMail;"
then pass this variable to CC in mail Activity
for Reference:
https://www.c-sharpcorner.com/article/create-a-sequence-project-for-sending-a-mail-using-smtp-activity-by-taking-crede/


text:
Q: Cant get kivy animation to work with pos_hint I want a widget to move with the animation function, instead of using pos, I want to use pos_hint as it simplifies a lot of things. When the animation starts, it sets the pos_hint to an empty {} for some reason. I think it has something to do with binding pos_hint properly to button or maybe anim isn't sending the pos_hint values correctly.
I've tried using pos and it works fine.
from kivy.graphics import *
from kivy.uix.floatlayout import FloatLayout
from kivy.animation import *
from kivy.lang.builder import Builder

Builder.load_string("""
<FloatLayout>:
    button:
        size_hint: 1,1/4
        pos_hint: {'center_y':0.5,'right':0}
        canvas:
            Color:
                rgba: [1,0,1,1]
            Rectangle:
                pos: self.pos
                size: self.size
""")

class button(FloatLayout):
    def __init__(self, **kwargs):
        super(ButtonSr, self).__init__(**kwargs)

        def checkpos(inst,val):
            print(val) #prints {} as soon as self.startanim() is fired and
                        nothing else. pos_hint stays as {}

        self.bind(pos_hint=checkpos)
        self.startanim()

    def startanim(self):
        anim = Animation(pos_hint={'center_x':0.5},d=2)
        anim.start(self)

I want button to move from outside of the screen to the chosen pos_hint

A: Try setting a separate variable that defines the position hint you want to change in the kv code. Then in your animation, change that variable instead of trying to change the pos_hint attribute.
in kv:
my_y_hint: .5
pos_hint: {"center_y": self.my_y_hint, "right": 0}

Then in your animation:
anim = Animation(my_y_hint=1)

I also made a quick video tutorial on how to do this recently.


text:
Q: Cloudinary upload image not working (react native and nodes I am trying to upload an image from my react native app to the nodejs and to the cloudinary cloud, but its not working for me. Thats my react-native code:
const App = () => {
  const [profileImageSource ,setProfileImageSource] = useState(require('./images/profilePic.png'));
  const [imageData, setImageData] = useState("");
  const [okay, setOkay] = useState(false);

  const config = {
    withCredentials: true,
    baseURL: 'http://localhost:3000/',
    headers: {
      "Content-Type": "application/json",
    },
  };
  const handleProfileImage = () => {
      const options = {
        title: 'Select photo',
        base64: true
      };

      ImagePicker.showImagePicker(options, (res) => {
        if(res.didCancel){
        }
        else if(res.error){
        }
        else{
          const image = {data: res.data};

          axios
          .post('/clients/upload-image', {
            data: JSON.stringify({image})
          },
          config
        )
          .then((res) => console.log("ok"))
          .catch((err) => alert(err));
        }
      })
    }

And that's my nodesjs code:
require('dotenv').config();

const cloudinary = require('cloudinary').v2;

//Cloudinary configurations
cloudinary.config({
    cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET
});

app.post('/clients/upload-image', (req, res) => {
    const imageStr = req.body.data;
    const uploadedResponse =
        cloudinary
        .uploader
        .upload(imageStr, {
            upload_preset: 'user',
        })
        .then((uploadedResponse) => console.log(uploadedResponse))
        .catch((err) => console.log("error"));
}

Where am I wrong? I keep getting errors and the pictures are not uploaded to the cloudinary

A: Can you share the error message you've received?
Also, can you confirm that imageStr (aka req.body.data) is received correctly in the backend? (maybe print it before uploading?)

A: Here is a simple for File uploading and using formidable as your bodyParser it will make your life easy using formidable, same might vouch for multer now that comes down to preference
So firstly I would advise that in your client you also use JavaScript FormData(built-in lib)

*

*So how you would handle things when time to send picture to server is like this below:

const uploadPicture = ()=>{

    const data = new FormData();

    data.append('image', file)// So 'image' is the key and **file** now this is the file uploaded in user that you have in state

    axios.post(url, data).then(res=>{

         console.log(res)

    }).catch(err=>{

        console.log(err)

    })

}

Now how handle things is back-end

*

*Firstly install npm i formidable or yarn add formidable

*Once that is done you ready to go.

const cloudinary = require('cloudinary').v2;
const Formidable = require('formidable');

cloudinary.config({
    cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
    api_key: process.env.CLOUDINARY_API_KEY,
    api_secret: process.env.CLOUDINARY_API_SECRET
});

router.post('/api/upload', (req, res)=>{

    const form = new Formidable.IncomingForm();//Here you initialze your formidable instance
    form.parse(req, (error, fields, files)=>{

       const {image} = files //So due to in our request we sent a **file** which is an image then formidable parsed that request and placed file received from client in **files** that you see in callback function so now we de-structure it by key that we set in client

        cloudinary.uploader.upload(image.path, {folder:'here you can specify folder you want'}, (err, results)=>{

            if (err) return console.log(err)
            const image_url = results.secure_url
        })

    })

})

*

*Now like this you uploaded your image

If this did not make sense to you: Here is a shameless plug

*

*Go checkout my channel on YouTube I have covered how to work with cloudinary

*Link: https://youtu.be/mlu-tbr2uUk


text:
Q: Cannot retrieve (file content) data from MongoDB import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException;

import org.apache.jackrabbit.JcrConstants; import org.apache.jackrabbit.oak.Oak; import org.apache.jackrabbit.oak.jcr.Jcr; import org.apache.jackrabbit.oak.plugins.document.DocumentMK; import org.apache.jackrabbit.oak.plugins.document.DocumentNodeStore; import org.apache.jackrabbit.oak.spi.security.OpenSecurityProvider;

import com.mongodb.DB; import com.mongodb.MongoClient;

import javax.jcr.Binary; import javax.jcr.LoginException; import javax.jcr.Node; import javax.jcr.Repository; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.version.Version; import javax.jcr.version.VersionHistory; import javax.jcr.version.VersionIterator; import javax.jcr.version.VersionManager;

public class Versioning {

public static void main(String[] args) throws LoginException,
        RepositoryException, FileNotFoundException {
    // TODO Auto-generated method stub

    DB db = new MongoClient("127.0.0.1", 27017).getDB("mydb");
    DocumentNodeStore ns = new DocumentMK.Builder().setMongoDB(db)
            .getNodeStore();
    System.out.println("start");
    Repository repo = new Jcr(new Oak(ns)).with(new OpenSecurityProvider())
            .createRepository();
    Session session = repo.login();

    VersionManager vm = session.getWorkspace().getVersionManager();
    Node parentNode = session.getRootNode();
    String multiPartFileName = "pdf";
    FileInputStream stream;
    Binary binary;
    Node node;
    Node content;
    Node fileNode;
    if (parentNode.hasNode("pdfFileNode")) {
        node = parentNode.getNode("pdfFileNode");
    } else {
        node = parentNode.addNode("pdfFileNode", "nt:unstructured");
    }

    if (node.hasNode(multiPartFileName)) {
        fileNode = node.getNode(multiPartFileName);
        System.out.println("filenode available");
    } else {
        fileNode = node.addNode(multiPartFileName, "nt:file");
        System.out.println("creating the filenode");
    }
    stream = new FileInputStream(new File("D:/pdf-sample.pdf"));

    if (fileNode.hasNode("jcr:content")) {
        content = fileNode.getNode("jcr:content");
    } else {
        content = fileNode.addNode("jcr:content", "nt:resource");
    }
    System.out.println("crossed");
    binary = session.getValueFactory().createBinary(stream);

    node.addMixin(JcrConstants.MIX_VERSIONABLE);
    content.setProperty("jcr:data", binary);
    session.save();

    System.out.println("node.getPath() :" + node.getPath());

    Version firstVersion = vm.checkin(node.getPath());

    System.out.println("firstVersion :" + firstVersion);
    Node child = parentNode.getNode("pdfFileNode");

    System.out.println("child.getPath() :" + child.getPath());

    vm.checkout(child.getPath());

    System.out.println("checkout child.getPath() :" + child.getPath());

    stream = new FileInputStream(new File("D:/pdf-sample.pdf"));

    //content = fileNode.addNode("jcr:content", "nt:resource");
    binary = session.getValueFactory().createBinary(stream);

    content.setProperty("jcr:data", binary);
    session.save();
    vm.checkin(child.getPath());

    System.out.println("checkin child.getPath() :" + child.getPath());

    VersionHistory history = vm.getVersionHistory(child.getPath());
    for (VersionIterator it = history.getAllVersions(); it.hasNext();) {
        Version version = (Version) it.next();
        System.out.println("Version: " + version.getName() + " created on "
                + version.getCreated().getTime());
    }

    vm.checkout(child.getPath());
    System.out.println("restoring checkout child.getPath() :"
            + child.getPath());
    session.logout();
    ns.dispose();

    // vm.restore(firstVersion, true);
}
}

Through the above code I am doing changes in the file and save that file again and again so that its version is created as follow.

Version: 1.0 created on Mon Jul 17 15:00:00 IST 2017
Version: 1.1 created on Mon Jul 17 15:00:00 IST 2017
Version: 1.2 created on Mon Jul 17 15:07:12 IST 2017
...

I am not sure that my code is actually saving each and every version of file data or not in mongo DB or just the last one (overwriting).
Now, Through below code i am trying to fetch the file content(data) based on their version but i am not able to that.
import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream;

import javax.jcr.LoginException; import javax.jcr.Node; import javax.jcr.NodeIterator; import javax.jcr.Repository; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.version.Version; import javax.jcr.version.VersionHistory; import javax.jcr.version.VersionIterator; import javax.jcr.version.VersionManager;

import org.apache.jackrabbit.oak.Oak; import org.apache.jackrabbit.oak.commons.IOUtils; import org.apache.jackrabbit.oak.jcr.Jcr; import org.apache.jackrabbit.oak.plugins.document.DocumentMK; import org.apache.jackrabbit.oak.plugins.document.DocumentNodeStore; import org.apache.jackrabbit.oak.spi.security.OpenSecurityProvider;

import com.mongodb.DB; import com.mongodb.MongoClient;

public class Retrive {

public static void main(String[] args) throws LoginException,
        RepositoryException, IOException {
    // TODO Auto-generated method stub

    Node childNode;

    DB db = new MongoClient("127.0.0.1", 27017).getDB("mydb");
    DocumentNodeStore ns = new DocumentMK.Builder().setMongoDB(db)
            .getNodeStore();
    System.out.println("start");
    Repository repo = new Jcr(new Oak(ns)).with(new OpenSecurityProvider())
            .createRepository();
    String multiPartFileName = "pdf";
    Node document = null;
    Node fileNode;
    Session session = repo.login();
    VersionManager vm = session.getWorkspace().getVersionManager();
    Node root = session.getRootNode();
    if (root.hasNode("pdfFileNode")) {
        document = root.getNode("pdfFileNode");
        System.out.println("pdfFileNode available");
    }

    NodeIterator nodeIterator = document.getNodes();
    System.out.println("Size of nodeIterator :" + nodeIterator.getSize());
    Node nameFile;

    VersionHistory history = vm.getVersionHistory(document.getPath());
    for (VersionIterator it = history.getAllVersions(); it.hasNext();) {
        Version version = (Version) it.next();
        System.out.println("Version: " + version.getName() + " created on "
                + version.getCreated().getTime());

        if (version.getName().equals("1.1")) {
            while (nodeIterator.hasNext()) {
                nameFile = nodeIterator.nextNode();
                String filename = nameFile.getName();
                System.out.println("filename :" + filename);
                if (filename.equals("pdf")) {
                    Node jcrContent = nameFile.getNode("jcr:content");
                    InputStream is = jcrContent.getProperty("jcr:data")
                            .getBinary().getStream();

                    BufferedInputStream bis = new BufferedInputStream(is);
                    ByteArrayOutputStream buf = new ByteArrayOutputStream();
                    int result = bis.read();
                    while (result != -1) {
                        byte b = (byte) result;
                        buf.write(b);
                        result = bis.read();
                    }

                    System.out.println("plain text: " + buf.toString());

                    break;
                } else {
                    System.out.println("not found");
                }
            }
        }
    }
    System.out.println("end");
}
}

Can anyone let me know what is missing , or what is the best way to retrieve all the file content(data) based on their version?


text:
Q: Laravel: Storage not putting file inside public folder When I use:
Storage::putFile('documents', $content, 'public');

I expect the folder structure inside public directory, like:
+
+-- storage
+--|-- app
+--|--|-- public
+--|--|--|-- documents
+--|--|--|--|-- XyZ.pdf
+

Instead of:
+
+-- storage
+--|-- app
+--|--|-- documents
+--|--|--|-- XyZ.pdf
+--|--|-- public
+

So, to force storage at "right" place I need to explicit put:
Storage::putFile('public/documents', $content, 'public');

What returns me a path that I'm not able to save at database because its values is "public/documents/xyz.pdf" and will not work properly with asset() helper.
How to use Storage facade to put files inside storage/app/public?

A: This isn't explicity in the docs.
Looking at config/filesystems.php, we have a public disk. Just use it:
Storage::disk('public')->put('documents', $content);

A: For anyone who wants every file to be stored in public and also wishes framework to magically handle the storage location is by using .env files. Open your .env file and you will find following line
FILESYSTEM_DRIVER=local

Change the value to public
FILESYSTEM_DRIVER=public

Now all your storage method will by default store all files inside storage/app/public directory. Regardless of methods you use
Storage::store
Storage::storeAs
Storage::put
Storage::putFileAs
$request->file('avatar')->storeAs

Note: If there's anything you want to store locally (inside non-public directory), then you have to mention the disk as
Storage::disk('local')


text:
Q: Why won't my break work in my if else statement in javascript? I have been working on a small game where you ask people to spell a random number from 1-10.
I've done this by using an if/else statement. I've tried to add a feature where if the user enters the word 'quit', the game will display an alert saying 'Goodbye' and the game will break. But when I test it, and enter the word 'quit', it displays an alert saying 'Goodbye', but it will not break.
I've tried to figure out the solution, but I just can't figure it out. Any helpful hints?
P.S I'm new to coding, please do not judge my lack of knowledge.
var numSpelling = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
var num;
var answer;
var i;

alert('If you want to exit the game, just enter the word quit');

for (i = 0; i < 10; i++) {

  num = Math.floor(Math.random() * 10) + 1;

  answer = prompt('What is the spelling for the number ' + num);

  while (true) {
    if (answer == 'quit') {
      alert('Goodbye');
      break;
    } else if (answer == numSpelling[num]) {
      alert('Correct');
      break;
    } else {
      alert('Incorrect');
      answer = prompt('Please try to spell ' + num + ' again')
    }
  }
}

A: break just breaks the while loop. But after it for loop will again work it's next iteration.
You can add more condition in the for loop - i < 10 && answer !== 'quit'

let numSpelling = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
let num, answer;

alert('If you want to exit the game, just enter the word quit');

for(let i = 0; i < 10 && answer !== 'quit'; i++) {
    num = Math.floor(Math.random() * 10) + 1;

    answer = prompt('What is the spelling for the number ' + num);

    while (true) {
       if(answer == 'quit') {
          alert('Goodbye');
          break;
       } else if (answer == numSpelling[num]) {
          alert('Correct');
          break;
       } else {
          alert('Incorrect');
          answer = prompt('Please try to spell ' + num + ' again')
       }
    }
}

A: May tag your outer for loop:
  main: for(i = 0; i < 10; i++){

And then you can exit it with
  break main;

Docs

A: You are only breaking out of your while loop and not from your for loop
let quit = false;
while(true) {
   if(answer == 'quit'){
    alert('Goodbye');
    quit = true;
    break;
   }else if(answer == numSpelling[num]){
    alert('Correct');
    break;
   } else {
    alert('Incorrect');
    answer = prompt('Please try to spell ' + num + ' again')
   }
}
if (quit) { break; }


text:
Q: systemctl --user takes tens of seconds to run I have an intermittent problem on one of my servers where it takes up to ~15 seconds to login. This is over ssh as my own user, not as root.
Also, once I've logged in, sometimes "sudo su" takes ~tens of seconds.
Finally, I just noticed that I can reproduce the issue on demand by running "systemctl --user" as my user (not as root).
I can see the systemd process spiking to 100% CPU when this happens.
# in htop
    PID USER       PRI  NI  VIRT   RES   SHR S  CPU%▽MEM%   TIME+  Command
 206136 todd        20   0 53680 46120  8656 R  99.0  1.2  6h10:06 /usr/lib/systemd/systemd --user

I can watch the process in strace, but nothing is really standing out to me, or seems to correlate with the hangup / resume. I do see a lot of these, so perhaps it's reallocating / rearranging some data structures?
brk(0x5607dc128000)                     = 0x5607dc128000
brk(0x5607dc149000)                     = 0x5607dc149000

Also, sometimes it doesn't complete, and times out
0 %  [via 192.168.99.8] systemctl --user
Failed to list units: Connection timed out

Any ideas what I can do to debug / identify the issue?
1 %  [via 192.168.99.8] uname -a
Linux bifrost 5.19.10-arch1-1 #1 SMP PREEMPT_DYNAMIC Tue, 20 Sep 2022 15:17:59 +0000 x86_64 GNU/Linux

0 %  [via 192.168.99.8] pacman -Q systemd
systemd 251.4-1

One other detail - as I've been seeing this off and on for months - I know that if I reboot the machine, the issue doesn't recur for a few days.
EDIT: with strace -r to show relative timestamps, it seems I've found the culprit.
     0.000128 getrandom("\xeb\x49\xb5\x3d\x37\x5a\xc4\xd6\x59\x2e\x5c\x5c\x8a\x5a\x35\xfd", 16, GRND_INSECURE) = 16
     0.000141 getrandom("\x04\xa7\xa1\xa9\xe4\xbb\x5c\x2c\xa3\x42\x0c\xf8\x36\xd7\x43\x7d", 16, GRND_INSECURE) = 16
    16.183344 newfstatat(AT_FDCWD, "/dev/disk/by-diskseq/19565", {st_mode=S_IFBLK|0660, st_rdev=makedev(0x8, 0x10), ...}, 0) = 0
     0.000389 newfstatat(AT_FDCWD, "/dev/disk/by-id/usb-Generic-_SD_MMC_MS_PRO_20120926571200000-0:0", {st_mode=S_IFBLK|0660, st_rdev=makedev(0x8, 0x10), ...}, 0) = 0

But I do not know why fstatat("/dev/disk/by-diskseq/19565") would take a super long time.
This system has just one disk. According to smartctl -a /dev/sda, there are no errors,
  9 Power_On_Hours          0x0032   100   100   000    Old_age   Always       -       47363
SMART Error Log Version: 0
No Errors Logged

That's about 5.5 years of uptime
EDIT2:
Someone asked about the /dev/disk/by-diskseq symlinks. I had just assumed they would point at /dev/sda, but that is not the case.
0 % ls -alhi /dev/disk/by-diskseq/
159385 lrwxrwxrwx 1 root root   9 Oct  6 11:45 39685 -> ../../sdb

The symlink name (39685) seems to increment by 1 every ~minute or so. And apparently there's an sdb that I didn't know about.
0 % lsblk -ap
NAME        MAJ:MIN RM   SIZE RO TYPE MOUNTPOINTS
/dev/sda      8:0    0 111.8G  0 disk
├─/dev/sda1   8:1    0   487M  0 part /boot
└─/dev/sda2   8:2    0 111.3G  0 part /
/dev/sdb      8:16   1     0B  0 disk

0 % fdisk -l /dev/sdb
fdisk: cannot open /dev/sdb: No medium found

Ahh, looks like it's the USB device? But there is nothing plugged into the USB slots.
% udevadm info /dev/sdb
P: /devices/pci0000:00/0000:00:14.0/usb1/1-5/1-5.1/1-5.1:1.0/host2/target2:0:0/2:0:0:0/block/sdb
M: sdb
U: block
T: disk
D: b 8:16
N: sdb
L: 0
S: disk/by-diskseq/39699
S: disk/by-path/pci-0000:00:14.0-usb-0:5.1:1.0-scsi-0:0:0:0
S: disk/by-id/usb-Generic-_SD_MMC_MS_PRO_20120926571200000-0:0
Q: 39699
E: DEVPATH=/devices/pci0000:00/0000:00:14.0/usb1/1-5/1-5.1/1-5.1:1.0/host2/target2:0:0/2:0:0:0/block/sdb
E: DEVNAME=/dev/sdb
E: DEVTYPE=disk
E: DISKSEQ=39699
E: MAJOR=8
E: MINOR=16
E: SUBSYSTEM=block
E: USEC_INITIALIZED=4178478
E: ID_VENDOR=Generic-
E: ID_VENDOR_ENC=Generic-
E: ID_VENDOR_ID=0bda
E: ID_MODEL=SD_MMC_MS_PRO
E: ID_MODEL_ENC=SD\x2fMMC\x2fMS\x20PRO\x20\x20\x20
E: ID_MODEL_ID=0153
E: ID_REVISION=1.00
E: ID_SERIAL=Generic-_SD_MMC_MS_PRO_20120926571200000-0:0
E: ID_SERIAL_SHORT=20120926571200000
E: ID_TYPE=disk
E: ID_INSTANCE=0:0
E: ID_BUS=usb
E: ID_USB_INTERFACES=:080650:
E: ID_USB_INTERFACE_NUM=00
E: ID_USB_DRIVER=ums-realtek
E: ID_PATH=pci-0000:00:14.0-usb-0:5.1:1.0-scsi-0:0:0:0
E: ID_PATH_TAG=pci-0000_00_14_0-usb-0_5_1_1_0-scsi-0_0_0_0
E: DEVLINKS=/dev/disk/by-diskseq/39699 /dev/disk/by-path/pci-0000:00:14.0-usb-0:5.1:1.0-scsi-0:0:0:0 /dev/disk/by-id/usb-Generic-_SD_MMC_MS_PRO_20120926571200000-0:0
E: TAGS=:systemd:
E: CURRENT_TAGS=:systemd:

EDIT3
Nothing has any sdb files open, or diskbyseq links.
% lsof | grep sdb
# nothing
% lsof | grep diskseq
# nothing

System has been up for 13 days
% uptime
 09:55:33 up 13 days, 22:36,  1 user,  load average: 2.13, 2.08, 2.03


text:
Q: Would a library installation question fit SO better than SU? I feel that my question at Super User doesn't get enough attention, am I targeting the wrong public?
Is it fine for Stack Overflow that I ask to migrate this question there? Or aren't these type of Qs allowed?

A: There are a fair number of Scrapy questions on SO already, so this probably fits. Not saying you'll get an answer there either, but it's probably worth a shot. I would remove your question from SU though if you do post on SO.

A: Ah, the irony of there being no answers to your question yet :)
It looks like a reasonable question for SO, especially since you form your questions intelligently.