text:
Q: Android: tablayout/viewpager fragments within fragment or activity I have a project I am working on in Android. I have one big fragment that covers the whole of the screen in my main activity. Normally I for each ui screen the user uses I would just do a replace command and swap the fragments for each screen.
In my current one I want to put a tablayout/viewpager combo with three different fragments and depending on what tab is pushed I will show a new fragment. Problem with this is that is a tablayout showing three different fragments inside another fragment. Is this even possible or recommended? and if I have to change it to a new activity. Would the navigation drawer act normally and just shut as I loaded the activity or is there going to be a problem there as well.
Thanks for your help

A: You can check below official documentation for the same or can use my demo snippet:
https://developer.android.com/reference/android/support/v4/app/FragmentTabHost.html
Try to do this to handle the Tabs in main fragment:
public class MainFragment extends Fragment {
private FragmentTabHost mTabHost;

//Mandatory Constructor
public MainFragment() {
}

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_tabs,container, false);

    mTabHost = (FragmentTabHost)rootView.findViewById(android.R.id.tabhost);
    mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);

    mTabHost.addTab(mTabHost.newTabSpec("fragmentb").setIndicator("Fragment B"),
            FragmentB.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("fragmentc").setIndicator("Fragment C"),
            FragmentC.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("fragmentd").setIndicator("Fragment D"),
            FragmentD.class, null);

    return rootView;
}

}
With this tabs layout:
<android.support.v4.app.FragmentTabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent">

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/realtabcontent"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

</LinearLayout>

A: Yes, TabLayout with viewPager will maintain it's different fragments in the memory.
Since, there are going to be only 3 tabs in your case it won't affect your memory performance, you can go with pagerAdapter.
You can reuse a single fragment for other tabs, but as i said since there are only 3 tabs, it won't affect your performance.
And Yes you can have tabLayout inside your main fragment, you main fragment is a part of your activity right, it will follow the same life cycle as the hosting activity except few other callbacks.


text:
Q: Creating a table of workers with first shift last week I am trying to extract a list of workers who had their first shift during last week.
Right now, my SQL works if I put a specific worker with a first shift in last week in my where clause (WHERE c.temp_nr ='XXXX'), but when I remove that clause, it just timeout
SELECT MIN(p.start_date), CONCAT(c.first_name, ' ', c.last_name) AS 'c.fullname', c.temp_nr
FROM contactstable c
LEFT JOIN projectlines p on c.temp_nr = p.candidate_number
WHERE c.temp_nr ='XXXX' and c.contact_type = 'Candidate'
HAVING MIN(p.start_date) between DATE_SUB( CURDATE( ) , INTERVAL (dayofweek(CURDATE())+6)
DAY )
AND DATE_SUB( CURDATE( ) , INTERVAL (dayofweek(CURDATE()))
DAY )

A: Use GROUP BY c.temp_nr
SELECT MIN(p.start_date), CONCAT(c.first_name, ' ', c.last_name) AS 'c.fullname', c.temp_nr
FROM contactstable c
LEFT JOIN projectlines p on c.temp_nr = p.candidate_number
WHERE c.contact_type = 'Candidate'
GROUP BY c.temp_nr
HAVING
    MIN(p.start_date)
        between
            DATE_SUB(CURDATE(), INTERVAL (dayofweek(CURDATE())+6) DAY)
            AND DATE_SUB(CURDATE() , INTERVAL (dayofweek(CURDATE())) DAY)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Number Theory: Class Groups I have the following question regarding class groups.

Show that $K=\mathbb{Q}(\sqrt{-19})$ is of class number 1.

From what I understand, the Minkowski bound says, for a number field $K$, that any ideal class contains an integral ideal with norm bounded above by
\begin{equation}
\frac{n!}{n^n}  \left(\frac{4}{\pi}\right)^{r_2}\sqrt{|\text{disc}(K)|}
\end{equation}
In this particular example:
\begin{eqnarray}
\frac{2!}{2^2}  \left(\frac{4}{\pi}\right)^{1}\sqrt{19}&=& \frac{2}{\pi}\sqrt{19}<3
\end{eqnarray}
Thus it is suffice to check how (2) and (3) split K.
This is where I am stuck. I was thinking of going about it using quadratic reciprocity to see how 2 and 3 split into $K$. I get split and inert respectively. Because $2$ split in $K$, I was to check and see if there were any integer solution for
\begin{eqnarray}
N\left(a+b\left(\frac{1+\sqrt{-19}}{2}\right)\right) & = & a^2+ab+5b^2=\pm2
\end{eqnarray}
Am I on the right track? If so, how do I proceed? If not, where did I go wrong and how do I properly approach this?
Thank you for your time and thank you for your feedback.

A: Yes, you are on the right track. You can evaluate the Jacobi symbol (or Kronecker symbol) to determine the factorisation of the ideals $(2)$ and $(3)$, see here: How to factor ideals in a quadratic number field?. Then you can proceed in the usual way, like here:
Showing that $\mathbb Q(\sqrt{17})$ has class number 1.
There is another way to show that $\mathbb{Q}(\sqrt{-19})$ has class number one, namely the analytic class number formula. In your case the class number is equal to
$$
h=\frac{\sqrt{\mid d_k\mid}}{2\pi}L(1,\chi),
$$
with the $L$-series attached to a corresponding Dirichlet character, and $d_K=-19$. It is easy to see that this gives $h=1$, because $L(1,\chi)\sim 1.44146156829133589$.


text:
Q: Reading .txt file for specific data and storing into sql fields I'm In the process of trying to understand Python and need help on how I will read a text file containing massive amounts of data, take specific information that is needed, and store it into database.
*-------------------------------------------*
* xxxxxxxxxxxx STARTED AT 2017-06-07-21.32.43.
*-------------------------------------------*

******* D I S P L A Y ************
*                                                 *
*REC READ     =  56,813
*REC WRITTEN  =  56,813
*CALLS   =     617
*FOUND   =     963
*NOT FND =         54
*FOUND   =     4963
*NOT FND =       0
*SYS   =           1
*SYS   =     462
*--------------------------------------------*
* xxxxxxxxxxxx COMPLETED AT 2017-06-07-21.35
*--------------------------------------------*

    with open(fname) as f:
content = f.readlines()
content = [x.strip() for x in content]

My idea: From my understanding should I approach this by reading the .txt line by line, storing it into an array somehow, then using an if statement to test to see if the value in the indexes are true for example (Rec read, written) etc. How will I get the values next to it?...
(Just an idea, this might be completely wrong)
UPDATE: Using the code below, I'm able to read all the line and get the correct information that is needed. The Keywords get stored in line[0] and the values get stored in line[1]. I am now trying to append each value into a list so I can run a query on the list and add it to the correct fields in my access database. Right now when I print a list it only shows me one value rather then the others. My original file have multiple values paired with the same data. In other words there is multiple "Rec Read".
   file = open(r"C:\Users\cqt7wny\Desktop\joblogs.txt")

rec_read = []
rec_written = []
calls = []

for line in file:
   if "REC READ" in line: #This if statement looks through the line
     line = line.split("=") #This makes the line two items in a list
     rec_read.append(line[1])

   if "REC WRITTEN" in line:
       line = line.split("=")
       rec_written.append(line[1])
   if "CC01 CALLS" in line:
       line = line.split("=")
       calls.append(line[1])

print(rec_read)

The output:
['   7,558,265

What I want:
[7558265,324322,22232,etc]

A: You have a good theoretical approach. Here's some code to help you get started, but you will have to change it to match your needs.
To open a file with Python:
file = open('filename.txt')
To iterate through the file line by line:
for line in file:
   if "REC READ" in line: #This if statement looks through the line
     line = line.split("=") #This makes the line two items in a list
     print(line[0])

This for statement can also be made into a while loop if necessary. More information about looking through files in python can be found here.
I do not know what type of database you want to implement (there are several kinds for different purposes). A common one is postgresql, which is accessed through python by the psycopg2 driver for Python (psycopg2 install info here).
You can then start working on the database in python:
import psycopg2
conn = psycopg2.connect(database=url.path[1:],user=url.username,password=url.password,host=url.hostname,port=url.port)
cur = conn.cursor()
cur.execute("""CREATE TABLE tablename (col1, col2, col3)""")
cur.execute("""INSERT INTO tablename (col1, col2, col3) VALUES (%s, %s, %s);""", (item1, item2, item3))
conn.commit()

Hope this can help you get started. Keep trying different things, then post your questions or cool things you find along the way to stackoverflow!
Cheers!


text:
Q: Xamarin Forms - Android - FormsAppCompatActivity - prevent navigate back I need to catch navigating back and depending on some conditions, I need to cancel it.
Note that overriding OnBackPressed as suggested in another question doesn't work (anymore!?):
   public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        public override void OnBackPressed()
        {
            base.OnBackPressed();  // not called
        }
    }


text:
Q: How to bundle dylibs correctly on OSX? My app depends on libcurl and libexpat. I have no specific requirements in my app and want to target 10.6.0 and up. At the moment I just link to the libs the standard way ( added them with Xcode ). But that messes up my app. If I compile it on Lion it won't work on Snow Leopard. It complains the libs are to old. How do I specify a minimum version needed? Or should I just copy the libs into my bundle? Can I copy the ones from Lion to make it work on 10.6?
Thanks
Edit: Is this as easy as setting the Base SDK to 10.6?

A: Its as simple as using an older base SDK. In this case 10.5


text:
Q: Trying to connect Metamask wallet to my react app through web3.js I am trying to connect the metamask wallet to my react-app. But in the process I am getting a few errors as mentioned below please help.
getWeb3.js
import Web3 from 'web3';
import {useEffect, useState} from 'react';

// Wallet connect code

const useWeb3 = () => {
    const [web3,setweb3] = useState(null);

    useEffect(() => {
        var instance;
        if(window.ethereum) {
            try{
                instance = new Web3(window.ethereum);
            }catch(error){
                console.error(error);
            };
        }else if (window.web3) {
            instance =  new Web3(window.web3);
        }else{
            const provider = new Web3.provider.HttpProvider('http://127.0.0.1:8545')
            instance = new Web3(provider);
        }setweb3(instance);

    },[]);

    return web3;

};

export {useWeb3};

store.js
import React, {useReducer, useContext, createContext} from 'react';

const StoreContext = createContext();

const initialState = {
    message: '',
    address: null,
    balance: 0
};

const reducer = (state, action) => {
    switch(action.type){
        case "NEW-ADDRESS":
            return {
                ...state,
                address: action.newAddress,
                message: action.message
            }
        default:
            throw new Error('Unknown type of action ${action.type');
    }
};

export const StoreProvider = ({children}) => {
    const [state, dispatch] = useReducer(reducer, initialState);

    return (
        <StoreContext.Provider value = {{state, dispatch}}>
            {children}
        </StoreContext.Provider>
        );
};

export const useStore = () => useContext(StoreContext);

storeApi.js
import {useStore} from './store'

const useStoreApi = () => {
    const {state, dispatch} = useStore();

    return {
        address: state.address,
        balance: state.balance,
        message: state.message,
        setBalance: (newBalance) => {
            dispatch({
                type: "SET-BALANCE",
                newBalance
            });
        },
        setAddress: newAddress => {
            dispatch({
                type: "New-Address",
                newAddress,
                message: "New account added successfully!"
            });
        }
    };
};

export {useStoreApi};

app.js
import { useStoreApi } from './storeApi';
import { useWeb3 } from './getWeb3';
import logo from './logo.svg';
import './App.css';
import {Button} from '@material-ui/core';

function App() {
  const {address,balance,message, setBalance,setAddress} = useStoreApi();
  const web3 = useWeb3();

  const setUserAccount = async (e) => {
    console.log("rhis add");

    if(window.ethereum) {
      await window.ethereum.enable();
      web3.eth.getAccounts().then(accounts => {
        setAddress(accounts[0]);
        console.log("rhis add");
      });

    }

  };
  setUserAccount();
  return (

           src/App.js

        {
          address ? (
            <>

 Your add: {address}
</>
          ): "s"
         }
        {/* <Button variant="outlined" color="primary" onClick={() => setUserAccount()}>Conn</Button> */}
        {/* <form action="http://localhost:3000/">
          <button type="submit" onClick={() => setUserAccount()}>Submit</button>
        </form> */}

  );
}

export default App;

index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import {StoreProvider} from './store';

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

reportWebVitals();

Errors:

*

*App.js:16 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'eth')
at setUserAccount (App.js:16)

*store.js:20 Uncaught Error: Unknown type of action ${action.type

*index.js:1 The above error occurred in the  component:
at StoreProvider (http://localhost:3000/static/js/main.chunk.js:847:3)

A: It looks like you're importing useWeb3 wrong:
const web3 = useWeb3();

But you export it like:
export {useWeb3};

So now you would have to call it like: web3.useWeb3()
Is this code you found at a tutorial somewhere? It's hard to follow...


text:
Q: Protected members in Java public SuperClass{
    protected int a1;
}

// Consider that two classes are in different package.
public SubClass extends SuperClass{
    void m1(){
        SuperClass sp = new SuperClass();
        sp.a1 = 1; // Error: Subclass.a1 is not visible
    }
}

I think that protected member a1 is visible to SubClass. In addition, field a1 belongs to SuperClass. So why it's not visible?

A: You are instantiating a object of SuperClass. Then trying to access protected member of SuperClass. Evnethough it is inside SubClass, this is basically an instance trying to access protected member. Try this.a1 instead.


text:
Q: Pandas Dataframe: Count unique words in a column and return count in another column I have a dataframe which has the following columns

*

*df['Album'] (contains album names of artistX )

*df['Tracks'] (contains Tracks in the albums of artistX)

*df['Lyrics'] (contains Lyrics of the tracks )

I am trying to count the number of words in df['Lyrics'] and return a new column called df['wordcount'] as well count the number of unique words in df['Lyrics'] and return a new column called df['uniquewordcount'].
I have been able to get df['wordcount'] by counting every string in df['lyrics'] minus white space.
totalscore = df.Lyrics.str.count('[^\s]') #count every word in a track
df['wordcount'] = totalscore
df
I have been able to count unique words in df['Lyrics']
import collections
from collections import Counter

results = Counter()
count_unique = df.Lyrics.str.lower().str.split().apply(results.update)
unique_counts = sum((results).values())
df['uniquewordcount'] = unique_counts

And that gives me the count of all the unique words in df['Lyrics'], which is what the code is meant to do, but I want the unique words in the lyrics of each track, My python isn't great currently so the solution might be obvious to everyone but not me. I would love someone to point me in the right direction on how to get the count of the unique words for each track.
expected output:
Album    Tracks    Lyrics                      wordcount  uniquewordcount
 A         Ball   Ball is life and Ball is key       7           5
           Pass   Pass me the hookah Pass me the     7           4

what I got:
Album    Tracks    Lyrics                    wordcount  uniquewordcount
  A     Ball   Ball is life and Ball is key       7           9
        Pass   Pass me the hookah Pass me the     7           9

A: Here is one alternative solution:
import pandas as pd

df = pd.DataFrame({'Lyrics': ['This is some life some collection of words',
                              'Lyrics abound lyrics here there eveywhere',
                              'Come fly come fly away']})

# Split list into new series
lyrics = df['Lyrics'].str.lower().str.split()

# Get amount of unique words
df['LyricsCounter'] = lyrics.apply(set).apply(len)

# Get amount of words
df['LyricsWords'] = lyrics.apply(len)

print(df)

Returns:
                                       Lyrics  LyricsCounter  LyricsWords
0  This is some life some collection of words              7            8
1   Lyrics abound lyrics here there eveywhere              5            6
2                      Come fly come fly away              3            5

A: Using just the standard library, you can indeed use collections.Counter. However, ntlk is advisable since there are many edge cases that may interest you, e.g. dealing with punctuation, plurals, etc.
Here's a step-by-step guide for Counter. Note we go further here than required, since we are also calculating the counts of each word. This data held in Counter dictionaries is discarded when we drop df['LyricsCounter'].
from collections import Counter

df = pd.DataFrame({'Lyrics': ['This is some life some collection of words',
                              'Lyrics abound lyrics here there eveywhere',
                              'Come fly come fly away']})

# convert to lowercase, split to list
df['LyricsList'] = df['Lyrics'].str.lower().str.split()

# for each set of lyrics, create a Counter dictionary
df['LyricsCounter'] = df['LyricsList'].apply(Counter)

# calculate length of list
df['LyricsWords'] = df['LyricsList'].apply(len)

# calculate number of Counter items for each set of lyrics
df['LyricsUniqueWords'] = df['LyricsCounter'].apply(len)

res = df.drop(['LyricsList', 'LyricsCounter'], axis=1)

print(res)

                                       Lyrics  LyricsWords  LyricsUniqueWords
0  This is some life some collection of words            8                  7
1   Lyrics abound lyrics here there eveywhere            6                  5
2                      Come fly come fly away            5                  3


text:
Q: $cordovaFileTransfer removing/ Deleting Local file Is $cordovaFileTransfer capable of removing/deleting file in Local,I already use it  for downloading, my problem now is , i want to delete old file, before downloading the new one,if it is capable can you give some example links on how i will implement it .

A: Use remove method of file entry.
You can use the following codes :
function removeFile(){
    window.resolveLocalFileSystemURL(fileUrl, gotFileRemove, function(error){});
}

function gotFileRemove(entry){
    entry.remove(function(file){
    },function(error){
        });
    }


text:
Q: Bootstrap - Navbar with Image Hello I want to achieve the following design, but it has to be responsive (I am using bootstrap):

I used the following HTML5 tags

home

test dp

The problem is when re-sizing the browser (i.e. opening from mobile device or re-sizing the browser size ), the image Banner.png change place and is not aligned anymore with the blue navbar
Edit 1:
I have used Absolute Positioning and added the code here, it works fine but is not stable (i.e. produces the space between the image and the navbar is not the same when I resize the browser with different sizes)
https://jsfiddle.net/c45xqLe9/


text:
Q: Why does this return None? Instead of returning fact? (it returns none)---> why?
fact = 1
def factorial(n):
    if (n-1)!=0:
        global fact
        fact=fact*n
        n=n-1
        print(fact)
        factorial(n)
    else:
        return fact

n=int(input())
g=factorial(n)
print(g)

A: Because you need to return factorial(n) in factorial function, otherwise it just gets called and does not return any result in the calling function. Also, you don't need the global variable, simply pass it along with n in the factorial function itself when doing recursive call.
Also, there's a cleanest solution without any unnecessary variables:
def factorial(n):
    if n < 2:
        return 1
    else:
        return n * factorial(n-1)

And if you dont wanna reinvent the wheel just use math module:
import math

math.factorial(1234)


text:
Q: Firebase Storage security rule error- User does not have permission I am authenticating to firebase using custom tokens. I want to restrict only the current user to have access to write and delete the image and grant read access to everyone.
below code is part of my swift code related to storage
let filePath = REF_STORAGE.child("/"+(FIRAuth.auth()?.currentUser?.uid)!+"/profilepic.jpeg")
let metaData = FIRStorageMetadata()
metaData.contentType = "image/jpeg"

And my current firebase storage rule is as shown below
service firebase.storage {
  match /b/test-123456789.appspot.com/o {
    match /{uid}/{allPaths=**} {
      allow read: if request.auth != null;
      allow write: if request.auth.uid == uid;
    }
  }
}

When i try to upload image i get the following error
User does not have permission to access gs://test-123456789.appspot.com/MYAUTHUID/profilepic.jpeg.
But if i change the storage rule to below storage rule, i am able to upload the image and the profilepic is stored under /gs://test-123456789.appspot.com/123456789/profilepic.jpeg
service firebase.storage {
  match /b/test-123456789.appspot.com/o {
    match /{allPaths=**} {
      allow read: if request.auth != null;
      allow write: if request.auth != null;
    }
  }
}

Kindly let me know how to fix this issue.

A: Does your {uid} contain any special characters? (e.g '+' sign)
Note: Firebase Support replied to me that this issue is under investigation, following a bug report I sent them 3 days ago: I discovered that calling {userid} doesn't work for me in Firebase Storage Rules if it contains the '+' sign.
I use phone numbers in E.164 format (e.g: "+97234567899").
I tried several run tests, and they clearly showed there's an issue with the value returned from {uid}:

*

*request.auth != null; - Worked

*request.auth.uid != null; - Worked

*request.auth.uid == "+97234567899"; - Worked

*request.auth.uid == uid; - Didn't work
However, I found a way to bypass this issue. This is what I came up with:

Solution
resource.name.split('/')[position]

Since {uid} represents a folder name, you can extract its value by manipulating the full path string of the file using resource.name, splitting it by ('/') and then selecting the relevant hierarchy.
For example: if this is your path: /Images/Profiles/{uid}/profile.jpg, then extract the uid like this: resource.name.split('/')[2]
In your code sample, I would do this:
service firebase.storage {
  match /b/test-123456789.appspot.com/o {
    match /{uid}/{allPaths=**} {
      allow read: if request.auth != null;
      allow write: if request.auth.uid == resource.name.split('/')[0];
    }
  }
}

Edit (July 28th, 2017)
Firebase Support has replied to my report a month ago, and the issue has been identified & now being taken care of.
However, in the meantime, if you wished to authenticate by phone number (like I did) - we shouldn't be using Custom Tokens anymore, because Firebase now supports such authentication.

A: For anyone still having this problem: Updating your firebase security rules to the following did the trick for me.
service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth.uid != null;
    }
  }
}


text:
Q: mapping value to one key in php array I have a array with many key and value pairs. I want to get all value with one key in php array.
I Have result like
 $seat=[
        (int) 0 => [
            (int) 0 => 'A_1',
            (int) 1 => 'A_2',
            (int) 2 => 'A_3',
            (int) 3 => 'A_4'
        ],
        (int) 1 => [
            (int) 0 => 'B_1',
            (int) 1 => 'B_2',
            (int) 2 => 'B_3'
        ]
    ]

i want to change like following syntax.
$seat=[
        (int) 0 => [
            (int) 0 => 'A_1',
            (int) 1 => 'A_2',
            (int) 2 => 'A_3',
            (int) 3 => 'A_4'
            (int) 4 => 'B_1',
            (int) 5 => 'B_2',
            (int) 6 => 'B_3'
        ]
    ]

thank all:

A: try this,
<?php

$result = array();

$seat=array(
    "0" => array("0" => 'A_1',"1" => 'A_2',"2" => 'A_3',"3" => 'A_4'),
    "1" => array("0" => 'B_1',"1" => 'B_2',"2" => 'B_3'),
    "2" => array("0" => 'C_1',"1" => 'C_2',"2" => 'C_3'));

for($i=0;$i<count($seat);$i++){
    $result = array_merge($result,$seat[$i]);
}
echo "<pre>";print_r($result);

?>

OUTPUT
Array
(
    [0] => A_1
    [1] => A_2
    [2] => A_3
    [3] => A_4
    [4] => B_1
    [5] => B_2
    [6] => B_3
    [7] => C_1
    [8] => C_2
    [9] => C_3
)

A: Simply using array_merge function.
$result = call_user_func_array('array_merge', $seat);

WORKING DEMO: http://phpio.net/s/1tx5

A: You can simply do it like this:
function flattenArray($arr) {
    $toflat = array($arr);
    $res = array();

    while (($r = array_shift($toflat)) !== NULL) {
        foreach ($r as $v) {
            if (is_array($v)) {
                $toflat[] = $v;
            } else {
                $res[] = $v;
            }
        }
    }

    return $res;
}

$newArray = array(flattenArray($array1)); // This will be your desired result

OUTPUT:
// So for example, if you pass array to flatternArray($array) method:

$array = array:2 [
  0 => array:3 [
    0 => 1
    1 => 2
    2 => 3
  ]
  1 => array:3 [
    0 => 4
    1 => 5
    2 => 6
  ]
]

// then $newArray will results in:

array:1 [
  0 => array:6 [
    0 => 1
    1 => 2
    2 => 3
    3 => 4
    4 => 5
    5 => 6
  ]
]

Hope this helps!

A: Since your input is an indexed array, you can just flatten the structure (with a classic splat&merge technique) and push the merged structure into an empty array to achieve the desired result (no loop required).
Code: (Demo)
$seat = [
    ['A_1', 'A_2', 'A_3', 'A_4'],
    ['B_1', 'B_2', 'B_3'],
    ['C_1']
];

var_export(
    [array_merge(...$seat)]
);

Output:
array (
  0 =>
  array (
    0 => 'A_1',
    1 => 'A_2',
    2 => 'A_3',
    3 => 'A_4',
    4 => 'B_1',
    5 => 'B_2',
    6 => 'B_3',
    7 => 'C_1',
  ),
)


text:
Q: SimpleXMLElement Object When I do print_r($nodes); I get:
Array (
  [0] => SimpleXMLElement Object (
    [kategoria_6] => 1
    [opis_6] => 1
    [img] => slides/slide0.jpg
  )
  [1] => SimpleXMLElement Object (
    [kategoria_6] => 2
    [opis_6] => 2
    [img] => slides/slide1.jpg
  )
  [2] => SimpleXMLElement Object (
    [kategoria_6] => 3
    [opis_6] => 3
    [img] => slides/slide4.jpg
  )
  [3] => SimpleXMLElement Object (
    [kategoria_6] => 4
    [opis_6] => 4
    [img] => slides/slide3.jpg
  )
  [4] => SimpleXMLElement Object (
    [kategoria_6] => 7
    [opis_6] => 7
    [img] => slides/slide2.jpg
  )
)

And now in this case, I can't do this:
$nodes->asXML("c:\\aaa.xml");

because this is an array i could do f.ex:
$nodes[1]->asXML("c:\\aaa.xml");

but I'll get only one element. I need to get all of this array, or better change it to this:
SimpleXMLElement Object (
  [item] => Array (
    [0] => SimpleXMLElement Object (
      [kategoria_6] => 1
      [opis_6] => 1
      [img] => slides/slide0.jpg
    )
    [1] => SimpleXMLElement Object (
      [kategoria_6] => 2
      [opis_6] => 2
      [img] => slides/slide1.jpg
    )
    [2] => SimpleXMLElement Object (
      [kategoria_6] => 3
      [opis_6] => 3
      [img] => slides/slide4.jpg
    )
    [3] => SimpleXMLElement Object (
      [kategoria_6] => 4
      [opis_6] => 4
      [img] => slides/slide3.jpg
    )
    [4] => SimpleXMLElement Object (
      [kategoria_6] => 7
      [opis_6] => 7
      [img] => slides/slide2.jpg
    )
  )
)

How do solve it?

A: Unfortunately, SimpleXML by itself does not easily allow you to do what you want to do. Luckily, DOM does (FIXED):
// Create a new DOMDocument
$dom = new DOMDocument('1.0', 'utf-8');

// Create the DocumentElement
$documentElement = $dom->appendChild($dom->createElement('objects'));

// Loop the SimpleXML elements and import them into DOM
foreach ($val as $element) {
  $documentElement->appendChild($dom->importNode(dom_import_simplexml($element), TRUE));
}

// Save to file
$dom->save("c:\\aaa.xml");


text:
Q: How to read a network stream in scala? How could I read a audio stream from the internet (e.g http://70.36.96.24:13384/;stream.mp3) and save its content to my local disk using Scala language?
I have tried to do it with:
val stream = new URL("http://70.36.96.24:13384/stream.mp3").openStream()

But it raises this exception:
java.io.IOException: Invalid Http response
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1342)
at java.net.URL.openStream(URL.java:1037)
at .<init>(<console>:15)
at .<clinit>(<console>)
at .<init>(<console>:7)
at .<clinit>(<console>)
at $print(<console>)
    ...

The same command works with this other streaming url:e.g
http://174-123-32-173.webnow.net.br/98fm.mp3
UPDATE: This code works perfectly on Linux, but not in Mac. Does anybody know the reason?
UPDATE2: Actually this code works on Java 6 but not in Java7. It doesnt matter the OS.

A: Your code doesn't work because the server isn't sending valid HTTP response. Notice this HTTP request sent, awaiting response... 200 No headers, assuming HTTP/0.9
$ wget -O- "http://70.36.96.24:13384/;stream.mp3"
--2014-01-20 17:09:12--  http://70.36.96.24:13384/;stream.mp3
Connecting to 70.36.96.24:13384... connected.
HTTP request sent, awaiting response... 200 No headers, assuming HTTP/0.9
Length: unspecified
Saving to: `STDOUT'

    [<=>                                                                                ] 0           --.-K/s              ICY 200 OK
icy-notice1:
This stream requires Winamp

icy-notice2:SHOUTcast Distributed Network Audio Server/Linux v1.9.8

icy-name:Radio Brasileirissima
icy-genre:Musica Brasileira
icy-url:http://radiobrasileirissima.com.br
content-type:audio/mpeg
icy-pub:0
icy-br:64

....BINARY CONTENT SKIPPED....

You can still read the data by skipping the first few lines until the character sequence \r\n\r\n, where icy-br:64 ends, and the actual AUDIO content begins. For this you can create a Socket, connect to it and sent a GET request to `/;stream.mp3' and read the data:
val timeout = 2000
val host = "70.36.96.24"
val port = 13384
val socket = new Socket
val endPoint = new InetSocketAddress(host, port)
socket.connect(endPoint, timeout);
// Here you send the GET request and read back the response.
// Every time you read the response, you have to skip
// the first few bytes until `\r\n\r\n`

EDIT1
NOTE: Your GET request must include extra newline for it to be an HTTP request

GET /;stream.mp3 HTTP/1.1

Here is the working example on the same URL:
  def socketurl = {
    val timeout = 2000
    val host = "70.36.96.24"
    val port = 13384
    val socket = new Socket
    val endPoint = new InetSocketAddress(host, port)
    socket.connect(endPoint, timeout);
    val (in, out) = (socket.getInputStream(), socket.getOutputStream())
    val httpRequest = "GET /;stream.mp3 HTTP/1.1\r\n\r\n"
    val command = httpRequest.getBytes()
    println(httpRequest)
    out.write(command)

    var buf = Vector(0, 0, 0, 0)
    var c = in.read()
    var cont = true
    while (c != -1 && cont) {
      buf = buf.drop(1) :+ c
      print(c.toChar)
      if (buf(0) == '\r' && buf(1) == '\n' && buf(2) == '\r' && buf(3) == '\n') {
        cont = false
        println("Its a match")
      }
      c = in.read()
    }

    while (c != -1) {
      // keep buffering the data from here on!
    }
  }

// call the method
socketurl


text:
Q: Jboss keeps using up the max memory with large dataset I'm new to JBOSS and I have a memory issue with a JVM (running under JBoss) and I wanted to see if you could help?
My JBOSS server running Teiid has been running out of memory when querying against a large table (130 million rows with 45 columns).
Here are some details:
Jboss EAP 6.4 with Teiid 8.7.1
It's running on a dedicated AWS Windows Server instance with 244GB ram, 32 processors

I have the JVM arguments as below:
-server -d64 -XX:+AggressiveOpts -XX:+UseFastAccessorMethods -XX:+PrintGCDetails -Xms200g -Xmx200g -XX:NewSize=8g -XX:MaxNewSize=8g -XX:SurvivorRatio=8 -XX:MaxDirectMemorySize=10g -XX:+UseParallelGC -XX:+UseParallelOldGC -XX:+UseLargePages

Teiid Buffer Manager settings:
allow-env-function" => false,
   "async-thread-pool" => "teiid-async",
   "authorization-validator-module" => undefined,
   "buffer-service-encrypt-files" => false,
   "buffer-service-inline-lobs" => true,
   "buffer-service-max-buffer-space" => 500000L,
   "buffer-service-max-file-size" => 150000L,
   "buffer-service-max-open-files" => 64,
   "buffer-service-max-processing-kb" => -1,
   "buffer-service-max-reserve-kb" => -1,
   "buffer-service-max-storage-object-size" => 16777216,
   "buffer-service-memory-buffer-off-heap" => true,
   "buffer-service-memory-buffer-space" => -1,
   "buffer-service-processor-batch-size" => 30000,
   "buffer-service-use-disk" => true,
   "detect-change-events" => true,
   "distributed-cache-jgroups-stack" => undefined,
   "exception-on-max-source-rows" => true,
   "lob-chunk-size-in-kb" => 100,
   "max-active-plans" => 20,
   "max-row-fetch-size" => 20480,
   "max-source-rows-allowed" => -1,
   "max-threads" => 64,
   "policy-decider-module" => "org.jboss.teiid",
   "preparedplan-cache-enable" => true,
   "preparedplan-cache-infinispan-container" => "teiid-cache",
   "preparedplan-cache-name" => "preparedplan",
   "query-threshold-in-seconds" => 600,
   "query-timeout" => 0,
   "resultset-cache-enable" => true,
   "resultset-cache-infinispan-container" => "teiid-cache",
   "resultset-cache-max-staleness" => 60,
   "resultset-cache-name" => "resultset",
   "thread-count-for-source-concurrency" => 0,
   "time-slice-in-milliseconds" => 2000,
   "workmanager" => "default",

As you can see I've assigned the Heap size to 200gb but it's still maxing out the memory every time and the server just hangs up with "Full GC(Ergonmics)" error. Below is a sample log:
[GC (Allocation Failure) [PSYoungGen: 7549952K->838656K(7549952K)] 176791593K->176710678K(208876544K), 64.7327072 secs] [Times: user=1476.97 sys=9.75, real=64.73 secs]
GC (Allocation Failure) [PSYoungGen: 7549952K->838656K(7549952K)] 183421974K->183391750K(208876544K), 68.1115075 secs] [Times: user=1554.99 sys=9.14, real=68.12 secs]
[GC (Allocation Failure) [PSYoungGen: 7549952K->838656K(7549952K)] 190103046K->190019046K(208876544K), 70.2219754 secs] [Times: user=1603.11 sys=9.98, real=70.23 secs]
[GC (Allocation Failure) [PSYoungGen: 7549952K->838656K(7549952K)] 196730342K->196631886K(208876544K), 87.7628514 secs] [Times: user=2007.72 sys=8.92, real=87.76 secs]
[Full GC (Ergonomics) [PSYoungGen: 838656K->0K(7549952K)] [ParOldGen: 195793230K->193496415K(201326592K)] 196631886K->193496415K(208876544K), [Metaspace: 130959K->130959K(139264K)], 429.0076056 secs] [Times: user=1582.83 sys=5.59, real=429.00 secs]
[GC (Allocation Failure) [PSYoungGen: 6711296K->838656K(7549952K)] 200207711K->200111591K(208876544K), 49.8578163 secs] [Times: user=1141.05 sys=3.48, real=49.86 secs]
[Full GC (Ergonomics) [PSYoungGen: 838656K->0K(7549952K)] [ParOldGen: 199272935K->200062941K(201326592K)] 200111591K->200062941K(208876544K), [Metaspace: 130999K->130999K(139264K)], 383.1849674 secs] [Times: user=570.09 sys=7.91, real=383.17 secs]
Full GC (Ergonomics) [PSYoungGen: 6711296K->5262703K(7549952K)] [ParOldGen: 200062941K->201326365K(201326592K)] 206774237K->206589069K(208876544K), [Metaspace: 131005K->131005K(139264K)], 573.4518437 secs] [Times: user=608.89 sys=15.22, real=573.45 secs]

A: Never mind. Just found out the issue was caused by incorrect JDBC driver set up for the data source. Thanks.


text:
Q: Plotting error "memory exhausted or requested size too large" If I want to draw a sin(x) graph using octave, I would do
x = -6:0.1:6;
plot (x, sin(x));

and this works.
I wanted to draw a sigmoid function so I tried
x = -6:0.1:6;
plot (x, 1/(1+exp(-x)));

But this gives me
error: memory exhausted or requested size too large for range of Octave's index type -- trying to return to prompt

I tried with x = -4:0.2:4; and this time got
error: invalid conversion of NDArray to Matrix
error: evaluating argument list element number 2

What is the problem?

A: The problem is in 1/(1+exp(-x)). The error MATLAB throws is:
Error using  /
Matrix dimensions must agree.

As per Carandraug's comment Octave fails with:
operator /: nonconformant arguments (op1 is 1x1, op2 is 1x121)

What you want is elementwise division (note the dot):
x = -6:0.1:6;
plot (x, 1./(1+exp(-x)));


text:
Q: Why a VPN slows down LAN access? We have an access server providing VPN to some of our clients and the workforce with laptops. They usually connect from outside of the office, and everything works fine. However, for simplicity and also security, when someone connects from within the office, VPN is also used on the LAN. That works fine as well, except that the speed on the LAN connection is very slow, compared to 1Gbps of the LAN. scp yields 150kB/s using VPN and full speed (which varies as the desktop computers take a lot of bandwidth themselves, but is about 20 times faster) if I manually connect surpassing VPN. So,

*

*Question 1: What could be the cause of it?

*Question 2: How can I improve it? (people are really complaining)

*Question 3: If the answer to the above two questions is unknown, how can I further diagnose it?

The OpenVPN configs are as follows:
Server:

dev tun
ifconfig 10.0.2.1 10.0.2.2
secret /etc/openvpn/static.key
proto tcp-server
port 1194
cipher DES-EDE-CBC
daemon
verb 4
log-append /var/log/openvpn.log
keepalive 10 900
comp-lzo

Client:

remote 10.0.1.3
secret /home/jkowalski/openvpn.key
dev tun
proto tcp-client
port 1194
cipher DES-EDE-CBC
ifconfig 10.0.2.2 10.0.2.1
script-security 2
route 10.0.0.0 255.255.255.0

I have tried so far:
Changing the cipher, port, compression setting. Disabling encryption altogether. No errors in the server log, although some machines take a long time to connect.
The server machine is a Debian 7.8 32 bit. Client machines are Windows 7/8.1 64 bit, XP 32 bit and Ubuntu 14.04LTS.
Thanks in advance.
UPDATE: I never found out what the original problem was. The solution was to upgrade to a 64-bit Debian 9. Now everything works fine. I also switched to UDP and it works like a charm.


text:
Q: Why is the left-multiplication map a surjection in this context? I will be awarding a bounty for this question as soon as I can, because this is a problem that is bothering me for quite a while now.
Here is a theorem that I know is true.

Let $S$ be a simple ring and $L$ be a non-zero left ideal of $S$.
  Consider $D:= \operatorname{End}({ }_S L)$. Note that $D$ acts on $L$
  via evaluation. Then the natural map
$$f: S \to \operatorname{End}_D(L_D): r \mapsto (f_r: L \to L= l
 \mapsto rl)$$
is a ring isomorphism.

and I want to prove the following:

Let $R$ be a $k$-algebra where $k$ is an algebraically closed field.
  Suppose that $V:= k^n$ is a simple left $R$-module. Then the map
$$f: R \to \operatorname{End}(V_k): r \mapsto (f_r : V \to V: v
 \mapsto r.v)$$
is a surjection.

In my notes, a short proof is sketched. I will post it here:

Consider the ringhomomorphism $f: R \to \operatorname{End}(V_k): r
 \mapsto f_r$. This induces a well-defined ring monomorphism
$$\overline{R}:=R/\ker f \hookrightarrow \operatorname{End}(V_k):
 \overline{r} \mapsto f_r$$
Note that $\overline{R}$ is finite-dimensional as $k$-algebra, because
  $\overline{R}$ embeds in $\operatorname{End}(V_k) \cong M_n(k)$. Thus
  $\overline{R}$ is Artinian, and hence the quotient ring
  $\overline{\overline{R}}:=\overline{R}/J(\overline{R})$ ($J$ is the
  jacobson radical) is Artinian as well. Thus $\overline{\overline{R}}$
  is a semisimple ring.
By Wedderburn-Artin, there are simple rings $B_1, \dots, B_m$ such
  that $$\overline{\overline{R}} \cong B_1 \times \dots \times B_m$$
Now, note that $V$ is a simple left $\overline{R}$ -module for the
  action induced by the action of $R$ on $V$. Since $V$ is simple, we
  have $J(\overline{R})V = 0$ and hence we can view $V$ as a simple
  $\overline{\overline{R}}$-module, essentially with an equivalent
  module structure as the one induced by the $R$-action on $V$.
Going further, we can view $V$ as a simple $B_1 \times \dots \times
B_m$-module, and we get
$$V= (B_1 \times \dots \times B_m) V = B_1 V \oplus \dots \oplus B_m
V$$
where we have identified $B_i$ with natural ideal of $B_1 \times \dots
 \times  B_m$. Since $V$ is simple, there is a unique $i \in \{1,
 \dots, m\}$ such that
$$B_i V \ne 0; \quad V = B_i V$$
Employing the theorem above, we get an isomorphism
$$h:B_i \to \operatorname{End}(V_k): b \mapsto h_{b}$$
Composing with the obvious surjections
$$R \to \overline{R} \to \overline{\overline{R}} \to B_1 \times \dots
\times B_m \to B_i \to \operatorname{End}(V_k)$$
the result follows. $\quad \square$

Question:

How exactly is the theorem above applied to get that  $$h:B_i \to
 \operatorname{End}(V_k): b \mapsto h_{b}$$ is an isomorphism (and thus
  a surjection)?
I.e. what ideal $L$ is used? It seems that more is going on because I
  really can't understand this step.

For anyone trying to help, thousand times thanks!

A: You're right: a bit more is going on here. Let's denote $B:=B_i$ for the sake of brevity.
As $V$ is simple, we can choose a nonzero element $v_1\in V$ such that $B\cdot v_1 = V$ and then extend it to a $k$-basis $v_1,\dots,v_n$ of $V$. Then we can consider the chain of left ideals
$$
L_m:= \{b\in B\mid b\cdot v_j =0,\quad j=2,\dots,m\},\quad m\leqslant n.
$$
Obviously, $L_1=B$. If now for some $m\leqslant n$ we have $L_m\neq 0$, but $L_{m+1}=0$, we get that $b\cdot v_{m+1} \neq 0$ for all $b\in L_m$, and so the map $\mu\colon L_m\to V$, $b\mapsto b\cdot v_{m+1}$ is

*

*injective, because if $b\in L_m$ and $b\cdot v_{m+1}=0$, then $b\in L_{m+1}=0$;

*surjective, because $L_{m}\cdot v_{m+1}$ is a non-zero $B$-submodule of $V$, and the latter is simple;

*a map of $B$-modules by construction.

Thus, $\mu$ an isomorphism of $B$-modules, and we can apply the theorem to $L=L_m$.


text:
Q: ServiceAccount unable to delete a deployment or service, but is able to create it Kubernetes v1.20.0 , on Ubuntu 20.04.1, docker 19.3.11
Using the following configuration I am able to create a deployment in the namespace "live" using this serviceaccount's token, but I am unable to delete the deployment using the same token.
Trying to find the correct Role to bind to my programmatic ServiceAccount user, but I am unable to get the correct role mapping for deployment deletion.  I've tried with and without slashes, asterisks in the resource names, and pluralizing the Resources.
Here's the error i get from the API:
  warnings.warn(
Exception (403)
Reason: Forbidden
HTTP response headers: HTTPHeaderDict({'Cache-Control': 'no-cache, private', 'Content-Type': 'application/json', 'X-Content-Type-Options': 'nosniff', 'X-Kubernetes-Pf-Flowschema-Uid': 'xxxx-bf2f-43b3-af5d-3ce15b086080', 'X-Kubernetes-Pf-Prioritylevel-Uid': 'xxxx-0d42-4b08-820e-396249f74107', 'Date': 'Mon, 28 Dec 2020 13:33:00 GMT', 'Content-Length': '408'})
HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"deployments.apps \"live-stream-deploy-testing123\" is forbidden: User \"system:serviceaccount:live:live-serviceaccount\" cannot delete resource \"deployments\" in API group \"apps\" in the namespace \"live\"","reason":"Forbidden","details":{"name":"live-stream-deploy-testing123","group":"apps","kind":"deployments"},"code":403}

Here is the deployment i'm trying to delete:
$ kubectl -n live get deploy
NAME                            READY   UP-TO-DATE   AVAILABLE   AGE
live-stream-deploy-testing123   1/1     1            1           76m

Here's where i'm currently at with my role definition ( I have tried with asterisks in Resource Names as well this did not work for create, many iterations later:):
$ kubectl -n live describe role
Name:         live-serviceaccount-role
Labels:       <none>
Annotations:  <none>
PolicyRule:
  Resources          Non-Resource URLs  Resource Names  Verbs
  ---------          -----------------  --------------  -----
  deployment/        []                 []              [get watch create list delete]
  deployment         []                 []              [get watch create list delete]
  deployments/       []                 []              [get watch create list delete]
  deployments        []                 []              [get watch create list delete]
  service/           []                 []              [get watch create list delete]
  service            []                 []              [get watch create list delete]
  services/          []                 []              [get watch create list delete]
  services           []                 []              [get watch create list delete]
  services           []                 []              [get watch create list delete]
  deployment.apps/   []                 []              [get watch create list delete]
  deployment.apps    []                 []              [get watch create list delete]
  deployments.apps/  []                 []              [get watch create list delete]
  deployments.apps   []                 []              [get watch create list delete]
  service.apps/      []                 []              [get watch create list delete]
  service.apps       []                 []              [get watch create list delete]
  services.apps/     []                 []              [get watch create list delete]
  services.apps      []                 []              [get watch create list delete]

Role binding:
$ kubectl -n live describe rolebindings
Name:         live-serviceaccount-rolebinding
Labels:       <none>
Annotations:  <none>
Role:
  Kind:  Role
  Name:  live-serviceaccount-role
Subjects:
  Kind            Name                 Namespace
  ----            ----                 ---------
  ServiceAccount  live-serviceaccount  live

pip package kubernetes==12.0.1.  I have not tested it against a previous version.
Script that results in error:
import kubernetes.client
from kubernetes.client.rest import ApiException
import logging
logger = logging.getLogger(__name__)

DEPLOYMENT_NAME = "live-stream-deploy-testing123"

configuration = kubernetes.client.Configuration()
configuration.api_key['authorization'] = "service account token here..."
configuration.api_key_prefix['authorization'] = 'Bearer'
configuration.verify_ssl = False

configuration.host = "https://my_k8s_API:6443"

with kubernetes.client.ApiClient(configuration) as api_client:

    try:
        api_instance = kubernetes.client.AppsV1Api(api_client)
        api_instance.delete_namespaced_deployment(
            name=DEPLOYMENT_NAME, namespace="live")
        logger.info("Deployment deleted. %s" % DEPLOYMENT_NAME)

    except ApiException as e:
        logger.error("Exception %s\n" % e)

Some additional "can-i" action:
$ kubectl -n live auth can-i  --as=system:serviceaccount:live:live-serviceaccount delete deploy
yes
$ kubectl auth can-i --as=system:serviceaccount:live:live-serviceaccount  --list -n live
Resources                                       Non-Resource URLs                     Resource Names   Verbs
selfsubjectaccessreviews.authorization.k8s.io   []                                    []               [create]
selfsubjectrulesreviews.authorization.k8s.io    []                                    []               [create]
deployment/                                     []                                    []               [get watch create list delete]
deployment                                      []                                    []               [get watch create list delete]
deployments/                                    []                                    []               [get watch create list delete]
deployments                                     []                                    []               [get watch create list delete]
service/                                        []                                    []               [get watch create list delete]
service                                         []                                    []               [get watch create list delete]
services/                                       []                                    []               [get watch create list delete]
services                                        []                                    []               [get watch create list delete]
deployment.apps/                                []                                    []               [get watch create list delete]
deployment.apps                                 []                                    []               [get watch create list delete]
deployments.apps/                               []                                    []               [get watch create list delete]
deployments.apps                                []                                    []               [get watch create list delete]
service.apps/                                   []                                    []               [get watch create list delete]
service.apps                                    []                                    []               [get watch create list delete]
services.apps/                                  []                                    []               [get watch create list delete]
services.apps                                   []                                    []               [get watch create list delete]
                                                [/.well-known/openid-configuration]   []               [get]
                                                [/api/*]                              []               [get]
                                                [/api]                                []               [get]
                                                [/apis/*]                             []               [get]
                                                [/apis]                               []               [get]
                                                [/healthz]                            []               [get]
                                                [/healthz]                            []               [get]
                                                [/livez]                              []               [get]
                                                [/livez]                              []               [get]
                                                [/openapi/*]                          []               [get]
                                                [/openapi]                            []               [get]
                                                [/openid/v1/jwks]                     []               [get]
                                                [/readyz]                             []               [get]
                                                [/readyz]                             []               [get]
                                                [/version/]                           []               [get]
                                                [/version/]                           []               [get]
                                                [/version]                            []               [get]
                                                [/version]                            []               [get]

Here are the YAMLs that produced the above outputs.  They are all on the live namespace.  Forgive the mess on the roles, but I've been trying to iterate through to a solution:
$ cat role.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: live-serviceaccount-role
  namespace: live
rules:
- apiGroups: ["","apps"]
  resources: ["services", "services/", "deployment", "deployment/", "service", "service/", "deployments", "deployments/"]
  resourceNames: [""]
  verbs: ["get", "watch", "create", "list", "delete"]
- apiGroups: [""]
  resources: ["services"]
  resourceNames: [""]
  verbs: ["get", "watch", "create", "list", "delete"]

$ cat serviceaccount.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: live-serviceaccount
  namespace: live

$ cat rolebinding.yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: live-serviceaccount-rolebinding
  namespace: live
subjects:
- kind: ServiceAccount
  name: live-serviceaccount # "name" is case sensitive
  namespace: live
roleRef:
  kind: Role #this must be Role or ClusterRole
  name: live-serviceaccount-role # this must match the name of the Role or ClusterRole you wish to bind to
  apiGroup: "rbac.authorization.k8s.io"

Here is a sample of the script that successfully lights up the deployment in the live namespace:
import kubernetes.client
from kubernetes import client
import logging
logger = logging.getLogger(__name__)

DEPLOYMENT_NAME = "live-stream-deploy-testing123"
POD_APP_LABEL = "lab"

configuration = kubernetes.client.Configuration()

# Configure API key authorization: BearerToken
configuration.api_key['authorization'] = "service account token here..."
# Uncomment below to setup prefix (e.g. Bearer) for API key, if needed
configuration.api_key_prefix['authorization'] = 'Bearer'
configuration.verify_ssl = False

# Defining host is optional and default to http://localhost
configuration.host = "https://<myk8sapi>:6443"

# Enter a context with an instance of the API kubernetes.client
#with kubernetes.client.ApiClient(configuration) as api_client:
with kubernetes.client.ApiClient(configuration) as api_client:

    api_instance = kubernetes.client.AppsV1Api(api_client)

    def create_deployment_object():
        # Configureate Pod template container
        container = kubernetes.client.V1Container(
            name="lab-container",

            # redacted for privacy
            image="nginx:latest",

            termination_message_path="/var/log/messages",
            image_pull_policy="IfNotPresent",
            resources=client.V1ResourceRequirements(
                requests={"memory": "5Gi"},
                limits={"memory": "16Gi"}
            ),
            volume_mounts=[
                client.V1VolumeMount(mount_path="/etc/nginx/nginx.conf.template", name="nginxconftemplate", sub_path="nginx.conf")
            ]
        )
        volume1 = client.V1Volume(
            name="nginxconftemplate",
            config_map=client.V1ConfigMapVolumeSource(
                name="live-nginx-conf",
                default_mode=0o0777
            )
        )
        # Create and configurate a spec section
        template = client.V1PodTemplateSpec(
            metadata=client.V1ObjectMeta(labels={"app": POD_APP_LABEL}),
            spec=client.V1PodSpec(containers=[container],
                                  volumes=[volume1],
                                  node_selector={"backend": "yes"},
                                  )
        )
        # Create the specification of deployment
        spec = client.V1DeploymentSpec(
            replicas=1,
            template=template,
            selector={'matchLabels': {'app': POD_APP_LABEL}})
        # Instantiate the deployment object
        deployment = client.V1Deployment(
            api_version="apps/v1",
            kind="Deployment",
            metadata=client.V1ObjectMeta(name=DEPLOYMENT_NAME),
            spec=spec)

        return deployment

    def create_deployment(api_instance, deployment):
        # Create deployement
        api_response = api_instance.create_namespaced_deployment(
            body=deployment,
            namespace="live")
        logger.info("Deployment created. status='%s'" % str(api_response.status))

    deployment = create_deployment_object()
    create_deployment(api_instance, deployment)

A: Here is the correct role definition that works for me:

apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: live-serviceaccount-role
  namespace: live
rules:
- apiGroups: ["","apps"] # "" indicates the core API group
  resources: ["deployments"]
  verbs: ["create", "delete"]

Which produces this can-i output:
$ kubectl auth can-i --as=system:serviceaccount:live:live-serviceaccount  --list -n live
Resources                                       Non-Resource URLs   Resource Names   Verbs
deployments                                     []                  []               [create delete]
deployments.apps                                []                  []               [create delete]
selfsubjectaccessreviews.authorization.k8s.io   []                  []               [create]
selfsubjectrulesreviews.authorization.k8s.io    []                  []               [create]
                                                [/api/*]            []               [get]
                                                [/api]              []               [get]
                                                [/apis/*]           []               [get]
                                                [/apis]             []               [get]
                                                [/healthz]          []               [get]
                                                [/healthz]          []               [get]
                                                [/livez]            []               [get]
                                                [/livez]            []               [get]
                                                [/openapi/*]        []               [get]
                                                [/openapi]          []               [get]
                                                [/readyz]           []               [get]
                                                [/readyz]           []               [get]
                                                [/version/]         []               [get]
                                                [/version/]         []               [get]
                                                [/version]          []               [get]
                                                [/version]          []               [get]

A: While your answer covers the solution it does not explain why the new set of roles that you provided are working successfully in contrast to the previous ones.
The can-i command was a bit misleading in this case. Result of it, was in fact correct since with this role you were able to delete but only chosen/mentioned resources. Since you used  resourceNames with an empty list [""], your role did not allow to delete anything.
To simply test this I placed the exact deployment name in the resourceNames:
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: live-serviceaccount-role
  namespace: live
rules:
- apiGroups: ["","apps"]
  resources: ["services", "services/", "deployment", "deployment/", "service", "service/", "deployments", "deployments/"]
  resourceNames: ["live-stream-deploy-testing123"]
  verbs: ["get", "watch", "create", "list", "delete"]

Once I did that I launched your code and deployment was successfully deleted.
So to sum up You should either fill the resourceNames with names of resources or omit it completely.


text:
Q: Probability density function from the inverse of another function Given the function:
$$f(x) = 1/sin(x)$$
where x is the angular interval 0  ≤ x < 1.5708 (in radians). I want to obtain a probability density function which represents the inverse case of f(x).
Programmatically, I can obtain a mass function which is an approximation to the desired pdf over a fixed range, 0 ≤ x < 1.5533 [0-89°], using the following hack (which is satisfactory for my code application):
% in matlab code
% find f(x) at 1 degree intervals and plot
fx = zeros(90,1);
theta = 0;
for i = 1:90;
    fx(i) = 1/sind(theta);
    theta = theta+1;
end
plot(0:89,fx);

% hack desired pdf
fx = zeros(90,1);
theta = 0;
for i = 1:90;
    fx(i) = 1/cosd(theta);
    theta = theta+1;
end
maxi = fx(90);
% flip dimension of the reverse sign of fx
fxF = flipdim(-fx+maxi,1);
% normalize
xPDF =  fxF/sum(fxF(:));
% plot
plot(0:89, xPDF);

What I require is the probability density function which equates to the distribution displayed in the second graph. I am more of a programmer than a mathematician so I would appreciate it if you go easy on me!
Thanks in advance

A: If I understood you code correctly, you get for the second one something among the lines of
$$
f(x) = g( \frac 1 {sin(90} - \frac 1 {sin(x)})
$$
Where $g$ is your flipdim function.
If understand what it does correctly your result should be along the lines of
$$
f(x) = - \frac 1 {sin(90} + \frac 1 {sin(x)}
$$
Though if I were you, I'd use
$$
f(x)  = \frac 1 {sin(x)} - 1
$$


text:
Q: Send data to thunderbird Add-on from chrome extension Is there a way to send data/messages from the chrome extension to the thunderbird add-on? I didn't find any API.

A: Use Native Messaging to send all information required to compose an e-mail (to, subject, body, attachment) from your Chrome extension to a native application, such as a Python script:
https://developer.chrome.com/docs/apps/nativeMessaging/
The Python script (which you must program yourself) then calls Thunderbird from the command line, with the appropriate command-line arguments:
http://kb.mozillazine.org/Command_line_arguments_-_Thunderbird


text:
Q: How do I remove a watch expression ( referring to variable not in current scope ) in Xcode IDE? I have pointer variable, uint16_t *pointer in function scope. When in the function, I added the watch expression: *pointer >> 1 . This results in the debugger ( lldb ) crashing. I restart Xcode, and whenever I enter said function, thus the variable appears in the scope, it Xcode crashes again.
I would remove this watch expression, but when there no such variable in the current scope, the watch expression does not show up in the watch window.
The Xcode version is 7.3 , the code is C++


text:
Q: Clear a scale component from view matrix. Camera-independent scaling I need for my little program to scale a gizmo by camera distance to conveniently move objects at anytime. I think I have two options:

*

*Calculate distance from gizmo to camera, make a matrix for scaling, multiply all points in cycle:
glm::mat4 scaleMat;
scaleMat= glm::scale(scaleMat, glm::vec3(glm::distance(cameraPos,gizmoPos)));

for (int i = 0; i < vertices.size(); i++)
{
    vertices[i] = glm::vec3(scaleMat * glm::vec4(vertices[i], 1.0));
}

*Clear the scale component of the view (lookAt) matrix only for gizmo.
If I use the first way my scale of gizmo accumulates the scale and increase size of gizmo any time when I change camera position. I think the second way is more accurate, but how to do that? Thank you!

A: If you want to apply different scaling each time to the same model, you should not manipulate vertexes (you should never do, in fact), but the Model Matrix. Through that you can manipulate the object without processing the vertexes via code.
I would go with something like this:
glm::mat4 modelMatrix(1.0f);
modelMatrix = glm::scale(modelMatrix,glm::vec3(glm::distance(cameraPos,gizmoPos)));

This will give you the scaled Model View matrix. Now you only need to pass it to your Vertex Shader.
You should have, roughly, something like this:
#version 330 core

// Input vertex data, different for all executions of this shader.
layout(location = 0) in vec3 vertexPosition_modelspace;

uniform mat4 M;

void main(){
    gl_Position =  M * vec4(vertexPosition_modelspace,1);
}

I have not tested the code but it is really similar to the code of one of my projects. There I keep my model matrix so the scaling is accumulated, but if you pass to the vertex shader a brand new matrix each time, nothing will be remembered.
If you need more about passing the uniform to the shader, have a look here at my current project's code.
You can find the scaling inside TARDIS::applyScaling and the shader loading in main.cpp


text:
Q: Wrong count of documents in MongoDB shard cluster I have a cluster with three shards using MongoDB 4.2. I have a collection (users) that, before sharding can be checked it has 600000 documents:
mongos> db.users.count()
600000

Next, I shard it with the usual commands (first DB, next collection):
mongos> sh.enableSharding("app")
mongos> sh.shardCollection("app.users", {"name.first": 1})

getting after a couple of minutes or so an equally distrution of chunks amongs the shards:
chunks:
    shard0000   3
    shard0001   2
    shard0002   3

So far so good.
However, if I get a count just after this, I get a weird value, higher than the number of documents in the collection:
mongos> db.users.count()
994243
mongos> db.users.find({}).count()
994243

Moreover, the getShardDistribution() result on the collection is also weird, showing the total number of document all them in one of the shards (which makes no sense, as part of them have been distributed in the other two shards):
mongos> db.users.getShardDistribution()

Shard shard0000 at localhost:27018
 data : 95.85MiB docs : 236611 chunks : 3
 estimated data per chunk : 31.95MiB
 estimated docs per chunk : 78870

Shard shard0001 at localhost:27019
 data : 64.06MiB docs : 157632 chunks : 2
 estimated data per chunk : 32.03MiB
 estimated docs per chunk : 78816

Shard shard0002 at localhost:27020
 data : 243.69MiB docs : 600000 chunks : 3
 estimated data per chunk : 81.23MiB
 estimated docs per chunk : 200000

Totals
 data : 403.62MiB docs : 994243 chunks : 8
 Shard shard0000 contains 23.74% data, 23.79% docs in cluster, avg obj size on shard : 424B
 Shard shard0001 contains 15.87% data, 15.85% docs in cluster, avg obj size on shard : 426B
 Shard shard0002 contains 60.37% data, 60.34% docs in cluster, avg obj size on shard : 425B

Interestingly, if I wait a while (not sure how much, but not more than 30 minutes), count and getShardDistribution() are back to normality:
mongos> db.users.count()
600000
mongos> db.users.getShardDistribution()

Shard shard0001 at localhost:27019
 data : 64.06MiB docs : 157632 chunks : 2
 estimated data per chunk : 32.03MiB
 estimated docs per chunk : 78816

Shard shard0002 at localhost:27020
 data : 83.77MiB docs : 205757 chunks : 3
 estimated data per chunk : 27.92MiB
 estimated docs per chunk : 68585

Shard shard0000 at localhost:27018
 data : 95.85MiB docs : 236611 chunks : 3
 estimated data per chunk : 31.95MiB
 estimated docs per chunk : 78870

Totals
 data : 243.69MiB docs : 600000 chunks : 8
 Shard shard0001 contains 26.28% data, 26.27% docs in cluster, avg obj size on shard : 426B
 Shard shard0002 contains 34.37% data, 34.29% docs in cluster, avg obj size on shard : 426B
 Shard shard0000 contains 39.33% data, 39.43% docs in cluster, avg obj size on shard : 424B

Why is this happening? How I can avoid this effect? (maybe forcing somekind of sync with a command?)
Thanks!
PD: In the case it may be relevant, I'm using a testing environment setup, which uses a standalone mongod process to implement each shard. The config server uses a mono-node replica set configuration.

A: count provides an estimated count, and may not be accurate. Use countDocuments to get an accurate count.
You can read the source of getShardDistribution by typing db.users.getShardDistribution in the shell. It seems to use information stored in the config database.
It is quite reasonable to expect that the statistics stored by the database aren't exactly accurate. This is because there is a cost to have them be up-to-date whenever any operation is performed anywhere in the cluster.
You seem to be looking at statistics at a point in time after some chunks have been copied from one shard to another and before these chunks are removed from the original shard. In this situation the data is stored twice in the cluster. The statistics aren't accurate in this case. To obtain an accurate count, use countDocuments.


text:
Q: Something went wrong while saving the file(s) After Saving the category from the admin side, it successfully saved the category. But in the exception.log file I got the following error.
"exception":"[object] (Magento\\Framework\\Exception\\LocalizedException(code: 0): Something went wrong while saving the file(s). at /opt/lampp/htdocs/m2/vendor/magento/module-catalog/Model/ImageUploader.php:215)"

Any Help will be appreciated. My Magento version is 2.3.1.

A: Seems like permissions issue, try to fix it for the whole project:

*

*Magento 2 DevDocs

*StacExchange answer
anyway I'll recommend you to check all images which saving during category save process using the xDebug or something similar, because exception throws when magento trying to copy/move a media file from one place to another.


text:
Q: GitHub Pages started giving me Jekyll build failure notices, even though I changed nothing - and they persist after I reset to last successful build Out of the blue recently, I started receiving notifications that my Jekyll builds were failing on GitHub Pages:

Page build failed. For more information, see https://help.github.com/articles/troubleshooting-github-pages-builds/.

Besides that, there was no info given, and the site built fine on my local machine. I tried everything I could think of: I built the site locally (worked fine on my machine), I deleted the last few files that had been added (no improvement), and I reset the master branch to exactly as it was when I last had a successful build. I figured for sure the last tactic would work, but I kept getting build failures.
I eventually figured out the answer, which I'm going to write in a moment.

A: It turned out the problem was that GitHub upgraded their version of Jekyll. I had to come to the solution by two steps:

*

*Upgrade the github-pages gem on my own computer:
$  bundle update github-pages

*Discover an interesting new error message:
Liquid Exception: undefined method `gsub' for 1000:Fixnum in /_layouts/post.html
After some fiddling around (and using Jekyll's --verbose option to find where the build was choking), I discovered that this gsub error was caused by a post I had, which was titled "1,000". (It was about a sleepless night, where I tried to count my way to sleep, and gave up after 1,000.) Some updated parser was trying to parse this as a number, apparently. To fix it I changed
title: 1,000

to
title: "1,000"

And voilà, GitHub Pages was satisfied.


text:
Q: Adding an outer name to JSON response in API I have written an API which returns data in JSON format.
The response looks like:
[{"leadID":1,"eventID":2,"companyID":3},{"leadID":4,"eventID":5,"companyID":6}]

But to me that does not ideal, I would like to add a name to this collection.
Ideally I would like the output to be like:
{"data":[{"leadID":1,"eventID":2,"companyID":3},{"leadID":4,"eventID":5,"companyID":6}]}

My action is:
public HttpResponseMessage GetLeadsSinceLastPoll()
{
    using (var context = new MyDbContext())
    {
        var leads = context.Lead.Where(q => q.dateAdded > AuthorizedUser.LastPollDate).ToList();
        var x = JsonConvert.SerializeObject(leads);
        var res = Request.CreateResponse(HttpStatusCode.OK);
        res.Content = new StringContent(x, System.Text.Encoding.UTF8, "application/json");
        return res;
    }
}

Is there a way to add an outer name/label to the result?

A: If you want leads to be the data property of an object, that's easy: Just create an object like that, and serialize it. With serialization, it's always best to manipulate the objects, not the serialized text. One unescaped quotation mark can wreak havoc. You don't want to get tangled up in those details.
var obj = new { data = leads };
var x = JsonConvert.SerializeObject(obj);

Or if you're using an old version of C# (< C#4) that doesn't support anonymous types:
var dict = new Dictionary<String, Object>();

dict["data"] = leads;

x = JsonConvert.SerializeObject(dict);

Or if you want something so quick and dirty that it actually takes longer:
var x = JsonConvert.SerializeObject(leads);

x = $@"{{""data"":{x}}}";

A: Create two classes
Class 1 is a list of Class 2 objects
public class Objects
{
    public List<Object1> data;
}

public class Object1
{
    public int LeadID;
    public int EventID;
    public int CompanyID;
}

Add items to the list like so:
Objects ObjectList = new Objects()
{
    data= new List<Object1>()
};

Object1 object= new Object1()
{
    LeadID = 1,
    EventID = 2,
    CompanyID = 3
};

ObjectList.data.Add(object);

Convert ObjectList to Json:
string jsonTxt = JsonConvert.SerializeObject(ObjectList);


text:
Q: angularJS bind to input's enter key and submit if input is button I have such directive, to go to next input (or button) in modal window:
.directive('autoVrm', function () {
    return function (scope, element, attrs) {
                var counter = 0;
            element.bind("keydown keypress", function (event) {
                console.log(element);
                if(event.which === 13) {
                        counter++;
                    event.preventDefault();
                    var elementToFocus = element.find('input')[counter] || element.find('button')[1];
                    console.log(elementToFocus.type);
                    if(angular.isDefined(elementToFocus))
                        elementToFocus.focus();
                    if (elementToFocus.type === 'button'){
                        counter = -1;
                        elementToFocus.bind("keydown keypress", function (eventSubmit) {
                            if(eventSubmit.which === 13) {
                                console.log('submit');
                            }
                        });
                    }
                }
            });
        };

but i have one trouble, if i'm on button, and click enter i get:
Uncaught TypeError: undefined is not a function
but why? how to make enter click to submit form? without dependency to controller?

A: Try angular.element(elementToFocus).bind for the Uncaught TypeError.
Regarding your new comment:
If this is defined in your controller
$scope.registerUser = function() {
    ...
}

Then call it in the directive simply by
elementToFocus.bind("keydown keypress", function (eventSubmit) {
    if(eventSubmit.which === 13) {
        scope.registerUser();
    }
});

As a guess, you could do something like check the attrs parameter to get the value of 'data-ng-click' and call the appropriate function:
elementToFocus.bind("keydown keypress", function (eventSubmit) {
    if(eventSubmit.which === 13) {
        if (attrs.dataNgClick == "registerUser()" {
            scope.registerUser();
        }
        else if (attrs.dataNgClick == "sign()" {
            scope.sign();
        }
        else if (attrs.dataNgClick == "frgtPassword()" {
            scope.frgtPassword();
        }
    }
});

A: This behavior is already defined in web technologies. When you press ENTER inside a form, it is submitted. To achieve this, you need to handle the right event (ng-submit). You can achieve the effect you're looking for with less code.

angular.module('app', [])
.controller('MyCtrl', function () {
  var self = this;
  self.message = "press ENTER to submit";
  self.count = 0;
  this.onSubmit = function () {
    self.count++;
    self.message = "form submitted " + self.count + " times";
  };
});
<!DOCTYPE html>

    <link rel="stylesheet" href="style.css" />

Hello Stack Overflow!

    <form ng-submit="ctrl.onSubmit()">
      <input type="text" placeholder="press ENTER"/>
      <input type="text" placeholder="press ENTER"/>
      <input type="submit" value="Send" />
    </form>

{{ctrl.message}}


text:
Q: Profile target mismatch: /archetype-catalog.xml when release staging repo in Sonatype I am trying to release artifacts to Sonatype for the first time, but I am getting this error, any ideas?
Profile target mismatch: /archetype-catalog.xml

See image from their UI
Sonatype support responded with the following:
"Can your build be configured to not produce/upload the archetype.xml file? The staging rule is working as designed to prevent files that live outside the groupId structure that you've been approved for from being released."
Can someone help as to how I can do this?
Thanks!

A: Try to generate project from maven archetype:
mvn archetype:generate \
-DgroupId=io.github.name \
-DartifactId=artifactId \
-Dversion=1.0 \
-DpackageName=io.github.name \
-DarchetypeGroupId=org.apache.maven.archetypes \
-DarchetypeArtifactId=maven-archetype-quickstart \
-DarchetypeVersion=1.0 \
-DinteractiveMode=false

A: I had the same problem.  It turns out there was a bug Sonatype had yesterday. Here is a link for someone else experiencing that issue on Sonatype's jira system.  Try it now, releasing an artifact is working for me today.


text:
Q: Generating annotated text description of structs with size/offset of fields for a given architecture during compilation? Basically, I would like to obtain the information about packing of structs on a given architecture during the compilation process, formatted as a text file with the struct description (code stripped of original comments), with added comments containing the size and offset of a given field.
Let me give an example - consider the following trivial code, test_struct.c:
#include <stdint.h>
#include <stdio.h>

struct MyStruct {
  uint8_t first;    // this is the first field
  uint16_t second;  // second field
  uint32_t third;   // third field is also important
  uint64_t fourth;  // do not forget fourth field
};
typedef struct MyStruct MyStruct_t;

MyStruct_t my_object = {
  .first  = 10,
  .second = 20,
  .third  = 30,
  .fourth = 40,
};

int main(void) {
  printf("Start: %d\n", my_object.first);
  while ( 1 ) {
    ;
  }
}

I can compile this for PC (say Linux) with:
gcc -Wall -g -o test_struct.exe test_struct.c

... and I can compile for ARM with:
arm-none-eabi-gcc --specs=nosys.specs -Wall -g -o test_struct.elf test_struct.c

Now, for outputting the struct info, I've found Extract detailed symbol information (struct members) from elf file compiled with ARM-GCC :

is pahole what you need? it can dump variable structure with size and offset.

... and indeed, on Linux I can do:
$ pahole -C MyStruct test_struct.exe
struct MyStruct {
    uint8_t                    first;                /*     0     1 */

    /* XXX 1 byte hole, try to pack */

    uint16_t                   second;               /*     2     2 */
    uint32_t                   third;                /*     4     4 */
    uint64_t                   fourth;               /*     8     8 */

    /* size: 16, cachelines: 1, members: 4 */
    /* sum members: 15, holes: 1, sum holes: 1 */
    /* last cacheline: 16 bytes */
};

... and that is the output that I want - compilable text description of the struct, with the original comments stripped, and comments with size and offset of fields added.
However, that "try to pack" worries me - I would like a description of the struct exactly as-is in code; and ultimately, I'd like to compare the default packing of the struct between architectures (in this example, Linux and ARM).
So, I was thinking - since it is generally "the same compiler" (GCC) being used in both cases, would it be possible to instruct the compiler (maybe through a custom script?) to generate such descriptions for selected structs in code? Such that it would be the "same" gcc command in a Cmake/Makefile that executes, regardless of which architecture the code is being built for - and it generates the information for that architecture?
If not, I guess I'd be forced to extract this information in a post-build step; in that case, is pahole my only option, or are there other tools that can generate this kind of information? pahole on Linux seems able to parse the ARM .elf file (pahole -C MyStruct test_struct.exe) - but is does that give accurate architecture-specific information? How do I ensure that I get a description of a struct as-is in memory for a given architecture build, without any attempts for packing by such tools?
( and in either of these cases, are there options to control the text formatting? For instance, I'd rather get an output like this, compared to the above pahole example:
struct MyStruct {
    uint8_t  first;  // 0 1
    uint16_t second; // 2 2
    uint32_t third;  // 4 4
    uint64_t fourth; // 8 8
};

)


text:
Q: Deploy iPad App - Enterprise or Developer Licence I'm sorry if this question has been asked. I have looked but can not find the question/answer.
I work for a web agency and am now developing IOS Apps for deployment on iPads.
We have the Developer licence from Apple however, reading the blurb it suggests that the Apps need to go through the App Store.
Due to the nature of the Apps (Medical) they can not be on the App Store.
Is this Developer licence using the "Ad Hoc" option enough to deploy the App to clients (not in our company) using a link, or do I need to use the Enterprise Licence?
The Enterprise Licence does say:

You plan to only distribute your iOS apps within your company or organization
The Enterprise Program is intended for developers who wish to develop
  and distribute their iOS apps within their company or organisation.

Any advice would be greatly appreciated. I'm sorry this is a bit of a random/bitty question.
Thanks in advance.

A: The ad-hoc distribution is limited to 99 devices and the enterprise limitation is 2k or 5k, not sure. If you want to really distribute your app, but limit its usage, then you have to build an authorization mechanism into your app (like http://www.doccheck.com for doctors). You may use an existing service like this or you can implement your own.
Enterprise distribution, btw, requires the registration of the device in your company. I would not do that as a customer in that case, maybe that is an issue in your case, too.


text:
Q: Debugger stopping at a non existent breakpoint in Xcode 4 Since upgrading to Xcode 4 my app stops at what I think are non existent break points. When it breaks there is no breakpoint showing in the breakpoint navigator and the editor says:

Thread:1 Stopped at breakpoint 17

Anyone else seeing this? Is this something new, maybe?

A: Press Command + alt + B to see all breakpoints.
Select the breakpoint that you want to remove and press delete.

A: user278859's answer is basically really a true answer, as this seems to be a bug in Xcode 4. I just had the same problem. I set a breakpoint at one place in a UIWebView delegate's shoudlStartLoadWithRequest-method (no other active breakpoints in the project) and the debugger stops in another method (in this case repeatedly webViewDidFinishLoad:) of the same object.
So I'd say this is an Xcode bug. Found no way of fixing this btw., other than removing the above breakpoint ... Screenshot:

A: Ok, I deleted the only breakpoint in the offending class which was no where near the line where the debugger was breaking and the problem went away.
Fasttracks, thanks for the suggestion. I am using xCode 4 and command+alt+b no longer works. There is now a Breakpoint Navigator where all the brekpoints are listed. There was no breakpoint in the list that corresponded to the line where the break was happening.

A: Maybe it's an Xcode bug but I still have a solution.
You can use LLDB to see and manipulate all the actual breakpoints.
Just type the following commands in the lldb window:
(lldb) is the prompt.

(lldb) help    -> for help
(lldb) help breakpoint   -> for breakpoint subcommand's help
(lldb) breakpoint list    -> list all the breakpoints.
(lldb) breakpoint delete  -> Delete the specified breakpoint(s).  If no breakpoints are
               specified, delete them all.
(lldb) breakpoint delete 7.1   -> delete breanpoint 7.1

and, you can use this command to continue the program:
(lldb) c

A: I have the same problem before, I think its an Xcode bug. You may check if there any unwanted breakpoints created by Xcode in Breakpoint Navigator (cmd 6), delete them and it should be fine.

A: Xcode 4 introduced an Exception breakpoint which seems to be on by default.
i.e. when there's an exception it breaks.
This will catch an exception even if you haven't clicked the Breakpoints button.
You can check via the Debug Navigator whether it's been triggered - you'll see an "objc_exception_throw".

A: Open the Breakpoints view: alt+shift+5 and then right click in the empty space and hit "delete all". It will actually remove the not existent breakpoints.

A: I found one additional case when such breakpoint is activated:
If you set breakpoint on the code, which is actually is not compiled for selected target this part of code is not highlighted or marked, and breakpoint is set actually elsewhere in this file where debugger consider is as close as it can.
So you need to be sure that code, where breakpoint is set is compiled :-)

A: Not knowing what exactly Swift error breakpoint is...I had enabled it by doing such:

Guess what happens?!
It will act like a breakpoint on errors thrown by your own code, i.e. wherever you use a throw statement.
For more see here and here


text:
Q: Where are the reference strings for NSVoiceLocaleIdentifier? I'd like to do text to voice on OSX with Swift where the voice is speaking in a different language than preferences set for the system. I believe the correct way to do this is to use NSVoiceLocaleIdentifier. I see this in the API documentation:

NSVoiceLocaleIdentifier
The language of the voice. An NSString
Declaration
NSString *const NSVoiceLocaleIdentifier;
Discussion
The canonical locale identifier string describing the
voice's locale. A locale is generally composed of three pieces of
ordered information: a language code, a region code, and a variant
code. Refer to documentation about the NSLocale class or
Internationalization and Localization Guide for more information.

I have combed through the links for documentation about the NSLocale class and Internationalization and Localization Guides, downloaded sample code, etc. but I still haven't found a reference for what those NSStrings look like. Does anybody know what those language, region, and variant codes are and how they're formatted?
Many thanks in advance.

A: Stitching together a few things--first credit where credit is due, thanks to Eric Aya for explaining how to get an Xcode playground to do speech synthesis, George Warner for sample code printing out the available voices and locations, and of course Matt in the comment above who oriented me to a working path. Unless I have this very wrong, it would appear that various voices are oriented around specific languages. So I believe you set the voice for the location.
Here's a setup for an Xcode playground:
import Cocoa
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

Here's how to get a voice speaking in Spanish:
let synth = NSSpeechSynthesizer()
synth.setVoice( "com.apple.speech.synthesis.voice.paulina.premium" )
synth.startSpeaking( "Hola Mundo mañana" )

How did I know that com.apple.speech.synthesis.voice.paulina.premium spoke in Spanish?
for voiceIdentifierString: String in NSSpeechSynthesizer.availableVoices() {
    var voiceLocaleIdentifier = ( NSSpeechSynthesizer.attributes( forVoice: voiceIdentifierString )[ NSVoiceLocaleIdentifier ] as! String )
    print( "\(voiceIdentifierString) speaks \(voiceLocaleIdentifier)" )
}

If I'm wrong in my assumptions, please correct me. I'm posting this for anyone who may encounter a similar need.


text:
Q: How to allow devise users to edit their profil? I have a namespace called "backend" which is protected by Devise.
I would like now to allow users to edit their profil.
So I created a users_controller in Backend.
Here's the users_controllercode :
class Backend::UsersController < ApplicationController
layout 'admin'
before_filter :authenticate_user!

    def index
        @users = Backend::User.all

         respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @users }
    end
    end

    def show
    @user = Backend::User.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @user }
    end
  end

    def edit
        @user = Backend::User.find(params[:id])
    end

    def update
    @user = Backend::User.find(params[:id])

    respond_to do |format|
      if @user.update_attributes(params[:user])
        format.html { redirect_to @user, notice: 'Article was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end
end

When I go on backend_users_path there is a list of all the users. I would like to permit to edit only his own profil.
So I go on the Edit page : <%= link_to "Edit", edit_backend_user_path(backend_user.id) %> .
Here's the Edit page code :
<%= simple_form_for @user do |f| %>

<%= f.label :email %>

  <%= f.input :email, :autofocus => true %>

<%= f.submit "Update" %>

<% end %>

And there is my problem : when I try to modify the email address, nothing happen. The update fails.
How can I do this ?
I'm quite lost.
Thanks by advance.
Here's the log file :
Started PUT "/backend/users/1" for 127.0.0.1 at 2012-11-13 12:13:51 +0100
Processing by Backend::UsersController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"wWrUDh7LVWhP+P7OWO6laDWaCKInxk37AA2BPuQWAI4=", "backend_user"=>{"email"=>"grellazzi@laposte.net"}, "commit"=>"Update", "id"=>"1"}
  [1m[35mBackend::User Load (0.0ms)[0m  SELECT `backend_users`.* FROM `backend_users` WHERE `backend_users`.`id` = 1 LIMIT 1
  [1m[36mBackend::User Load (0.0ms)[0m  [1mSELECT `backend_users`.* FROM `backend_users` WHERE `backend_users`.`id` = ? LIMIT 1[0m  [["id", "1"]]
  [1m[35mSQL (1.0ms)[0m  BEGIN
  [1m[36m (0.0ms)[0m  [1mCOMMIT[0m
Redirected to http://localhost:3000/backend/users/1
Completed 302 Found in 23ms (ActiveRecord: 1.0ms)

Started GET "/backend/users/1" for 127.0.0.1 at 2012-11-13 12:13:51 +0100
Processing by Backend::UsersController#show as HTML
  Parameters: {"id"=>"1"}
  [1m[35mBackend::User Load (0.0ms)[0m  SELECT `backend_users`.* FROM `backend_users` WHERE `backend_users`.`id` = 1 LIMIT 1
  [1m[36mBackend::User Load (0.0ms)[0m  [1mSELECT `backend_users`.* FROM `backend_users` WHERE `backend_users`.`id` = ? LIMIT 1[0m  [["id", "1"]]
  Rendered backend/users/show.html.erb within layouts/admin (0.0ms)
Completed 200 OK in 7ms (Views: 5.0ms | ActiveRecord: 0.0ms)

Thanks for your links, I tried to modify my user_controller with
if params[:user][:password].blank?
      params[:user].delete("password")
      params[:user].delete("password_confirmation")
    end

    @user = User.find(current_user.id)
    if @user.update_attributes(params[:user])
      # Sign in the user bypassing validation in case his password changed
      sign_in @user, :bypass => true
      redirect_to root_path
    else
      render "edit"
    end

But it fails...

A: If nothing happens, that usually indicates a validation error, in your case probably a missing password or other data that is not part of your form but is still being validated. To debug this, output @user.errors.inspect to your logfile or look at  error_messages_on @user in your view.
In general, take a look at these guides on how to allow users to edit their (partial) profile:

*

*https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-account-without-providing-a-password

*https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-password


text:
Q: Why is my Deliver BroadcastReceiver never getting called? I'm sending a message via SmsManager and my Send Receiver seems to be working exactly as expected but my Delivery Receiver doesn't appear to be getting called.
public void sendSms(BaseFragment fragment, String address, String message) {

    if (isSimAvailable(fragment)) {
        try {
            String SENT = "SMS_SENT";
            String DELIVERED = "SMS_DELIVERED";

            PendingIntent sentPI = PendingIntent.getBroadcast(fragment.getContext(), 0, new Intent(SENT), 0);
            PendingIntent deliverPI = PendingIntent.getBroadcast(fragment.getContext(), 0, new Intent(DELIVERED), 0);

            fragment.getContext().registerReceiver(new SentReceiver(), new IntentFilter(SENT));
            fragment.getContext().registerReceiver(new DeliverReceiver(), new IntentFilter(DELIVERED));

            SmsManager smsMgr = SmsManager.getDefault();
            smsMgr.sendTextMessage(address, null, message, sentPI, deliverPI);
        } catch (Exception e) {
            Toast.makeText(fragment.getContext(), e.getMessage() + "!\n" + "Failed to send SMS", Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    } else {
        Toast.makeText(fragment.getContext(), "Cannot send SMS because SIM is not available", Toast.LENGTH_LONG).show();
    }
}

class DeliverReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        switch (getResultCode()) {
            case Activity.RESULT_OK:
                Toast.makeText(context, "Text delivered",
                        Toast.LENGTH_LONG).show();
                break;
            case Activity.RESULT_CANCELED:
                Toast.makeText(context, "sms_not_delivered",
                        Toast.LENGTH_LONG).show();
                break;
        }

    }
}

class SentReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        switch (getResultCode()) {
            case Activity.RESULT_OK:
                Toast.makeText(context, "Sent text", Toast.LENGTH_LONG).show();
                break;
            case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                Toast.makeText(context, "Generic failure", Toast.LENGTH_LONG).show();
                break;
            case SmsManager.RESULT_ERROR_NO_SERVICE:
                Toast.makeText(context, "No service", Toast.LENGTH_LONG).show();
                break;
            case SmsManager.RESULT_ERROR_NULL_PDU:
                Toast.makeText(context, "Null PDU", Toast.LENGTH_LONG).show();
                break;
            case SmsManager.RESULT_ERROR_RADIO_OFF:
                Toast.makeText(context, "Radio off", Toast.LENGTH_LONG).show();
                break;
        }
    }
}

I've added the following 4 permissions.
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />

Again, I'm able to send texts find and the onReceive for my Sent Receiver is getting invoked.  It's just the onReceive on my Deliver Receiver that is not getting invoked.
I'm doing my testing on AT&T network, if that makes a difference.  I do remember reading somewhere that some networks don't send delivery reports back but I would be shocked if that were the case for AT&T.