text:
Q: Get enum description and send to List I am very new in WPF and I don't know much about this. I have a group dataGrid list with group that makes a dropdown list in my dataGrid. I want to change the enum value to string so I add a description on my enum. But what makes me confused is how to call the description on my enum and set it to my list. Below is my code.
*** C# ***
public ProcessData()
        {
            InitializeComponent();

            List<User> items = new List<User>();

            items.Add(new User() { Description = "Operating pressure", Unit = 1, Type = Group.kg_kmol, Case1 = " " });
            items.Add(new User() { Description = "Operating Temperature", Unit = 2, Type = Group.DD });
            items.Add(new User() { Description = "Gas flow rate", Unit = 3, Type = Group.DD });
            items.Add(new User() { Description = "Gas molecular weight", Unit = 4, Type = Group.Unit_DD });
            items.Add(new User() { Description = "Gas Desnsity", Unit = 4, Type = Group.Unit_DD });
            items.Add(new User() { Description = "HC Liquid flow rate", Unit = 4, Type = Group.Unit_DD });
            items.Add(new User() { Description = "Water flow rate", Unit = 5, Type = Group.Unit_DD });
            items.Add(new User() { Description = "Sand Flow rate", Unit = 6, Type = Group.Unit_DD });
            lvUsers2.ItemsSource = items;

            CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(lvUsers2.ItemsSource);
            PropertyGroupDescription groupDescription = new PropertyGroupDescription("Unit");
            view.GroupDescriptions.Add(groupDescription);

        }

public enum Group {
            [Description("this is a string 1")]
            kg_kmol,
            [Description("this is a string 2")]
            DD,
            [Description("this is a string 3")]
            Unit_DD,
            SomeValue
        };

public class User
        {

            public string Description { get; set; }

            public int Unit { get; set; }

            public Group Type { get; set; }

        public string Case1 { get; set; }

        }

*** And this is my XAML ***
<Grid>
                    <DataGrid  Name="lvUsers2" ItemsSource="{Binding GroupedCustomers}" >
                        <DataGrid.GroupStyle>
                            <GroupStyle>
                                <GroupStyle.HeaderTemplate>
                                    <DataTemplate>
                                        <StackPanel>
                                            <TextBlock Text="{Binding Path=Name}" />
                                            <TextBlock  Text="yeah" />
                                        </StackPanel>
                                    </DataTemplate>
                                </GroupStyle.HeaderTemplate>
                                <GroupStyle.ContainerStyle>
                                    <Style TargetType="{x:Type GroupItem}">
                                        <Style.Resources>
                                            <ControlTemplate x:Key="MultiItemGroupTemplate" TargetType="{x:Type GroupItem}">
                                                <Expander IsExpanded="False">
                                                    <Expander.Header>
                                                        <StackPanel Orientation="Horizontal">
                                                            <TextBlock Text="{Binding Path=Name}" />
                                                        </StackPanel>
                                                    </Expander.Header>
                                                    <ItemsPresenter />
                                                </Expander>
                                            </ControlTemplate>
                                            <ControlTemplate x:Key="SingleItemGroupTemplate" TargetType="{x:Type GroupItem}">
                                                <ItemsPresenter />
                                            </ControlTemplate>
                                        </Style.Resources>
                                        <Style.Triggers>
                                            <DataTrigger Binding="{Binding ItemCount}" Value="1">
                                                <Setter Property="Template" Value="{StaticResource SingleItemGroupTemplate}">
                                                </Setter>
                                            </DataTrigger>
                                        </Style.Triggers>
                                        <Setter Property="Template" Value="{StaticResource MultiItemGroupTemplate}"/>
                                    </Style>
                                </GroupStyle.ContainerStyle>
                            </GroupStyle>
                        </DataGrid.GroupStyle>
                    </DataGrid>

                </Grid>

A: The easiest and most MVVM friendly way to do this would be to add a read-only property (called "TypeDescription" in the example below) to the User class that gets the description of the enum and then bind to or group by this one:
public class User
{
    public string Description { get; set; }

    public int Unit { get; set; }

    public Group Type { get; set; }

    public string Case1 { get; set; }

    public string TypeDescription
    {
        get
        {
            string stringValue = Type.ToString();
            FieldInfo fi = typeof(Group).GetField(Type.ToString());
            DescriptionAttribute[] attributes = fi.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
            return attributes != null && attributes.Length > 0 ? attributes[0].Description : stringValue;
        }
    }
}

A: You can try this trick
as an array
var gh = Enum.GetValues (typeof(Group))

or as IEnumerable
IEnumerable <Group> gh = Enum.GetValues (typeof(Group)).Cast<Group>();

thank u


text:
Q: (Pyinstaller) failed to create process Я перерыл все сайты в надежде на то, что я смогу найти решение проблемы, из-за которой я не могу конвертировать .py в .exe. Уже переустановил pefile, pyinstaller и pypiwin32 на новую версию, но это тоже не помогло. Что я могу сделать ещё?

*

*Путь к python.exe: C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\python.exe

*Путь к pyinstaller-script.py: D:\Python34\Scripts\pyinstaller-script.py

A: Да уж, я неплохо попотел, но в принципе справился с работой. Всё, что я сделал, это просто плюнул на pyinstaller и использовал cx_freezer. Один гайд мне очень сильно помог мне справиться с проблемой: https://overcoder.net/q/67404/как-я-могу-конвертировать-py-в-exe-для-python.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Discord.js Bot -- How to check every day which day is i want to make a bot that every day checks if its the birthday of a member. But i dont know how to check everyday's day.
Im writting my bot with node.js.
Thanks.

A: You can do this easily with Date a built in feature of node.js. Date Docs
For today's date: 10th of August
function getToday(){
    let today = new Date();
    let months = [`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`];
    let suffix = [`st`,`nd`,`rd`];
    return `${today.getDate()}${suffix[today.getDate()] || `th`} of ${months[today.getMonth()]}`;
}
console.log(getToday());


text:
Q: Operation with Complex number We've the following 3 complex numbers
$z_1=2\text{cis}(\frac{\pi}{6})~~$,  $z_2=2\text{cis}(\frac{5\pi}{6})~~$, $z_3=2\text{cis}(\frac{-\pi}{2})$
We are asked to show that $z_1^{3n}+z_2^{3n}=2z_3^{3n}$
I have calculated $z_1^{3n}=2^{3n}\text{cis}(\frac{n\pi}{2})~~$, $z_2^{3n}=2^{3n}\text{cis}(\frac{5n\pi}{2})~~$,
$z_3^{3n}=2^{3n}\text{cis}(\frac{-3n\pi}{2})$.
I'm stuck on how to proceed further to prove the above equations.  Any help really appreciated, Please assist .
Thank you ,
Arif

A: Hint:

*

*$z_1^3 = 2^3 \operatorname{cis}\left(3 \cdot \cfrac{\pi}{6}\right)=8\operatorname{cis}\left(\cfrac{\pi}{2}\right)=8i$

*$z_2^3 = 2^3 \operatorname{cis}\left(3 \cdot \cfrac{5 \pi}{6}\right)=8\operatorname{cis}\left(\cfrac{5 \pi}{2}\right)=8\operatorname{cis}\left(2\pi+\cfrac{\pi}{2}\right)=8\operatorname{cis}\left(\cfrac{\pi}{2}\right)=8i$

*$z_3^3 = 2^3 \operatorname{cis}\left(-3 \cdot \cfrac{\pi}{2}\right)=8\operatorname{cis}\left(- 3 \cdot \cfrac{\pi}{2}+ 2 \pi\right)=8\operatorname{cis}\left(\cfrac{\pi}{2}\right)=8i$
Therefore $\;z_1^3=z_2^3=z_3^3\,$.


text:
Q: Places Google Api - Autocomplete This is a bit weird, I followed the Google places API to add autocomplete for my android app. Google Places API request denied for Android autocomplete, even with the right api key. I even tried to check with the JSON Client and requested both GET/POST still same error because I'm sure my code follows the integration for google api autocomplete accordingly. I have not found any solution that resolves the error. Some answers suggest removing sensor with place_id. I don't know. Kindly explain
a solution or suggestion that would help me to get the autocomplete working fine.
https://maps.googleapis.com/maps/api/place/autocomplete/json/?sensor=false&key=API_KEY&components=country=us&input=california

A: Try this url with your api key:
https://maps.googleapis.com/maps/api/place/autocomplete/json?sensor=true&key= api key&language=en&input=kir

A: It will work in android app only. Don't try it in REST client. Instead try debugging your app to see response.

A: public class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements
    Filterable {
private ArrayList<MapdataList> resultList;

public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
    super(context, textViewResourceId);

}

@Override
public int getCount() {
    return resultList.size();
}

@Override
public String getItem(int index) {

    MapdataList data = resultList.get(index);

    return data.getPlaceName();

}

public String mthod(int index) {
    MapdataList data = resultList.get(index);

    return data.getPlaceID();

}

@Override
public Filter getFilter() {
    Filter filter = new Filter() {
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults filterResults = new FilterResults();
            if (constraint != null) {
                // Retrieve the autocomplete results.
                resultList = autocomplete(constraint.toString());

                // Assign the data to the FilterResults
                filterResults.values = resultList;
                filterResults.count = resultList.size();
            }
            return filterResults;
        }

        @Override
        protected void publishResults(CharSequence constraint,
                FilterResults results) {
            if (results != null && results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    };
    return filter;
}

private static final String LOG_TAG = "ExampleApp";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
private static final String API_KEY = "serverkry";

private ArrayList<MapdataList> autocomplete(String input) {
    ArrayList<MapdataList> resultList = null;

    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {
        StringBuilder sb = new StringBuilder(PLACES_API_BASE
                + TYPE_AUTOCOMPLETE + OUT_JSON);
        sb.append("?key=" + API_KEY);
        // sb.append("&components=country:uk");
        sb.append("&sensor=true");
        sb.append("&input=" + URLEncoder.encode(input, "utf8"));

        URL url = new URL(sb.toString());
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Load the results into a StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
    } catch (MalformedURLException e) {
        Log.e(LOG_TAG, "Error processing Places API URL", e);
        return resultList;
    } catch (IOException e) {
        Log.e(LOG_TAG, "Error connecting to Places API", e);
        return resultList;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    try {
        // Create a JSON object hierarchy from the results
        JSONObject jsonObj = new JSONObject(jsonResults.toString());
        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

        // Extract the Place descriptions from the results
        resultList = new ArrayList<MapdataList>(predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {

            MapdataList mapData = new MapdataList();
            mapData.setPlaceName(predsJsonArray.getJSONObject(i).getString(
                    "description"));
            mapData.setPlaceID(predsJsonArray.getJSONObject(i).getString(
                    "place_id"));

            resultList.add(mapData);

            // resultList.add(predsJsonArray.getJSONObject(i).getString(
            // "description"));
            // resultList.add(1,predsJsonArray.getJSONObject(i).getString(
            // "place_id"));
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Cannot process JSON results", e);
    }

    return resultList;
  }
  }

`
public class TestMapAutocomplete extends Activity {
PlacesAutoCompleteAdapter obj;

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

    AutoCompleteTextView YY = (AutoCompleteTextView) findViewById(R.id.Google_autoCompleteTextView1);
    obj = new PlacesAutoCompleteAdapter(this, R.layout.google_list_items);
    YY.setAdapter(obj);

    YY.setOnItemClickListener(getPlaceId);

}

public OnItemClickListener getPlaceId = new OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        // TODO Auto-generated method stub

        // int dd= (Integer) parent.getItemAtPosition(position);
        String mcityselect = obj.mthod(position);
        // String mcityselect = (String) parent.getItemAtPosition(position);
        String mcityccselect = (String) parent.getItemAtPosition(position);

    }
};

  }

its working ... do like this create server key and allow all then in android   use autoacmpltere Create a server key in google api console and allow all then enable google feture in permissions
its working bro try this ....

A: So jaswinder the changes I need to make as I assumed is replace the sensor with place_id and my try catch should also change to look like your code snippet;
try {

        // Create a JSON object hierarchy from the results

        JSONObject jsonObj = new JSONObject(jsonResults.toString());

        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

        // Extract the Place descriptions from the results

        resultList = new ArrayList<String>(predsJsonArray.length());

        for (int i = 0; i < predsJsonArray.length(); i++) {

            resultList.add(predsJsonArray.getJSONObject(i).getString(

            "description"));

        }

    } catch (JSONException e) {

        Log.e(TAG, "Cannot process JSON results", e);

    }

    return resultList;

Then I can create server key as you explained, I should be good to go then. Thanks

A: Hey guys now the autocomplete is working Jaswinder I just added place_id where you commented it out and wala! it works like a charm.

Hope this code helps someone. I used the Key for browser application and enabled both Places api and Goople map api in the console.
private class PlacesAutoCompleteAdapter extends ArrayAdapter<String>
        implements Filterable {
    private ArrayList<String> resultList;

    public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
        super(context, textViewResourceId);
    }

    @Override
    public int getCount() {
        return resultList.size();
    }

    @Override
    public String getItem(int index) {
        return resultList.get(index);
    }

    @Override
    public Filter getFilter() {
        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults filterResults = new FilterResults();
                if (constraint != null) {
                    // Retrieve the autocomplete results.
                    resultList = autocomplete(constraint.toString());

                    // Assign the data to the FilterResults
                    filterResults.values = resultList;
                    filterResults.count = resultList.size();
                }
                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence constraint,
                    FilterResults results) {
                if (results != null && results.count > 0) {
                    notifyDataSetChanged();
                } else {
                    notifyDataSetInvalidated();
                }
            }
        };
        return filter;
    }
}

// Get array list of addresses
private ArrayList<String> autocomplete(String input) {

    ArrayList<String> resultList = null;

    HttpURLConnection conn = null;

    StringBuilder jsonResults = new StringBuilder();

    try {
        StringBuilder sb = new StringBuilder(PLACES_API_BASE
                + TYPE_AUTOCOMPLETE + OUT_JSON);

        sb.append("?sensor=true&key="

        + API_KEY);

        // for current country.Get the country code by SIM

        // If you run this in emulator then it will get country name is
        // "us".

        String cName = getCountryCode();

        if (cName != null) {
            countryName = cName;
        } else {
            countryName = "za";
        }
        sb.append("&components=country:" + countryName);
        sb.append("&input=" + URLEncoder.encode(input, "utf8"));

        URL url = new URL(sb.toString());

        conn = (HttpURLConnection) url.openConnection();

        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Load the results into a StringBuilder

        int read;

        char[] buff = new char[1024];

        while ((read = in.read(buff)) != -1) {

            jsonResults.append(buff, 0, read);

        }

    } catch (MalformedURLException e) {

        Log.e(TAG, "Error processing Places API URL", e);

        return resultList;

    } catch (IOException e) {

        Log.e(TAG, "Error connecting to Places API", e);

        return resultList;

    } finally {

        if (conn != null) {

            conn.disconnect();

        }

    }

    try {

        // Create a JSON object hierarchy from the results

        JSONObject jsonObj = new JSONObject(jsonResults.toString());

        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

        // Extract the Place descriptions from the results

        resultList = new ArrayList<String>(predsJsonArray.length());

        for (int i = 0; i < predsJsonArray.length(); i++) {

            resultList.add(predsJsonArray.getJSONObject(i).getString(

            "description"));

            resultList.add(predsJsonArray.getJSONObject(i).getString(
                    "place_id"));

        }

    } catch (JSONException e) {

        Log.e(TAG, "Cannot process JSON results", e);

    }

    return resultList;

}

}


text:
Q: Increment column based on second column Consider a dataframe like this:
dat <- data.frame(name = c("John", "John", "John", "John", "Sam", "Sam", "Sam", "Sam", "Emily", "Emily", "Emily", "Emily", "Alex", "Alex", "Alex", "Alex"),
                  grade = c(9, NA, NA, 12, 10, NA, NA, NA, 9, 10, 10, 11, NA, 11, 11, NA),
                  year = c(2007, 2008, 2009, 2010, rep(c(2018, 2019, 2019, 2020), 3)))

    name grade year
1   John     9 2007
2   John    NA 2008
3   John    NA 2009
4   John    12 2010
5    Sam    10 2018
6    Sam    NA 2019
7    Sam    NA 2019
8    Sam    NA 2020
9  Emily     9 2018
10 Emily    10 2019
11 Emily    10 2019
12 Emily    11 2020
13  Alex    NA 2018
14  Alex    11 2019
15  Alex    11 2019
16  Alex    NA 2020

I'd like to fill in the missing NAs in grade based on year.  So Sam for example is in 10th grade in 2018, and in 2019 he'll be in 11th grade:
dat_desired <- data.frame(name = c("John", "John", "John", "John", "Sam", "Sam", "Sam", "Sam", "Emily", "Emily", "Emily", "Emily", "Alex", "Alex", "Alex", "Alex"),
                  grade = c(9, 10, 11, 12, 10, 11, 11, 12, 9, 10, 10, 11, 10, 11, 11, 12),
                  year = c(2007, 2008, 2009, 2010, rep(c(2018, 2019, 2019, 2020), 3)))

    name grade year
1   John     9 2007
2   John    10 2008
3   John    11 2009
4   John    12 2010
5    Sam    10 2018
6    Sam    11 2019
7    Sam    11 2019
8    Sam    12 2020
9  Emily     9 2018
10 Emily    10 2019
11 Emily    10 2019
12 Emily    11 2020
13  Alex    10 2018
14  Alex    11 2019
15  Alex    11 2019
16  Alex    12 2020

How can I do this?  I've tried:
dat %>%
  group_by(name) %>%
  fill(grade, .direction = "updown")

which doesn't work because it doesn't take year into account.  Adding a group_by(year) doesn't help either, because then no NAs are replaced.

A: Could try:
dat %>%
  group_by(name) %>%
  mutate(
    grade = coalesce(grade, first(grade[!is.na(grade)]) - (first(year[!is.na(grade)]) - year))
  )

Output:
# A tibble: 16 x 3
# Groups:   name [4]
   name  grade  year
   <fct> <dbl> <dbl>
 1 John      9  2007
 2 John     10  2008
 3 John     11  2009
 4 John     12  2010
 5 Sam      10  2018
 6 Sam      11  2019
 7 Sam      11  2019
 8 Sam      12  2020
 9 Emily     9  2007
10 Emily    10  2008
11 Emily    10  2009
12 Emily    11  2010
13 Alex     10  2018
14 Alex     11  2019
15 Alex     11  2019
16 Alex     12  2020

A: A rough solution can be implemented with a for loop:
X <- as.character(unique(dat$name))

for ( i in 1:length(X)){
a <- min(dat[dat$name==X[i],]$grade, na.rm = T)
b <- min(dat[dat$name==X[i],]$year, na.rm = T)
dat[dat$name==X[i] & is.na(dat$grade),]$grade <- dat[dat$name==X[i] & is.na(dat$grade),]$year-b+a
}


text:
Q: push view without showing tabbar removes bottom of view I'm trying to push a view while hiding the uitabbar.
The view which is being pushed have another view inside it which is located in the bottom.
Whenever this view is pushed the uitabbar is not displayed (which is good) but the bottom view I added is not displayed.
how can I hide the tab bar but still show the view I added in the bottom?
Thanks!


text:
Q: Recursive method for Linked Lists I have a question about a recursive function that I have written. The function is supposed to return the sum of all the even entries in the list. The code, along with the helper recurisve method, is given below.
public int sumEven() {

return sumEven(head);
}

private int sumEven(IntListNode n) {
    int nodeNumber=1;
    int count=0;
    if(n==null){
        return count;
    }
    else if(nodeNumber%2==0 && n.getNext()==null){
        return n.getValue();
    }
    else if(nodeNumber%2!=0 && n.getNext()==null){
        return 0;
    }
    else if(nodeNumber%2==0 &&(n.getNext()).getNext()==null){
        return n.getValue();
    }
    else{
        nodeNumber++;
        if(nodeNumber%2==0){
            count+=n.getValue();
            return count+ sumEven(n.getNext());
        }
        else{
            return count + sumEven(n.getNext());
        }

    }

}

I am unsure as to whether I can use the nodeNumber and count in the way that I have done in the function. Each time sumEven is called, isn't the nodeNumber and the count being set back to zero. If so, then this method can't possibly work right? How else can I keep track of the count and increasing nodeNumber then?
Thanks a lot!!!

A: You may try it this way:
public static void main(String args[]) {
    List<Integer> list = new LinkedList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8));
    System.out.printf("Sum of %s is: %s\n", list, sumOfEvenNumbers(list.iterator()));
}

private static int sumOfEvenNumbers(Iterator<Integer> iterator) {
    if (!iterator.hasNext()) return 0;
    Integer value = iterator.next();
    return sumOfEvenNumbers(iterator) + (value % 2 == 0 ? value : 0);
}

A: Here is simple pseudo-code which you can finish:
int findSum(nodeptr temp, int count, int sum)
{
    if(temp==NULL)  // this indicates end of list. Return the sum until now
       return sum;
    count++;   //increment count:number of nodes encountered
    if(count%2==0)  //if it is even node, add the contents of the node
    {
        sum += temp->value;
    }
    return findSum(temp->next, count, sum); //recursively call the function on subsequent nodes
}

Call the function from your main code as follows
res = findsum(myList, 0, 0);

I have followed the C/C++ convention. Change it appropriately.
This is pretty simple to understand. The key idea is to pass updated values as method parameters rather than using local variables.


text:
Q: Upper bound on the singular values of the square root of a matrix It is well known (see Upper bound for the sum of absolute values of the eigenvalues) that for a matrix $A=(a_{ij})\in\mathbb{R}^{n\times n}$
$$
\sum_{i=1}^n s_i(A)\leq\sum_{i,j=1}^n |a_{ij}|,
$$
where $s_i(A)$ denote the singular values of $A$. I am now wondering whether the following generalization
$$
\sum_{i=1}^n \sqrt{s_i(A)}\leq\sum_{i,j=1}^n \sqrt{|a_{ij}|}
$$
still holds true.

A: In fact, the assertion is true. To see this let $A=U|A|$ be a polar decomposition of $A$ and denote its $i$-th column by $a_i$. Then
$$
\sum_{i=1}^n \sqrt{s_i(A)}=\operatorname{tr}(|A|^{1/2})=\operatorname{tr}[(U^TA)^{1/2}]=\sum_{i=1}^n (U^TA)^{1/2}(i,i)\leq \sum_{i=1}^n \sqrt{(U^TA)(i,i)},
$$
where the last step used Peierls-Jensen's inequality. Since $U$ is orthogonal, we infer
$$
\sum_{i=1}^n \sqrt{(U^TA)(i,i)}\leq\sum_{i=1}^n\sqrt{\|Ua_i\|_2}=\sum_{i=1}^n\sqrt{\|a_i\|_2}\leq \sum_{i=1}^n\sqrt{\|a_i\|_1}.
$$
The proof is finished by using the elementary inequality $\sqrt{a+b}\leq\sqrt{a}+\sqrt{b}$, $a,b\geq 0$, for $n-1$ times.


text:
Q: Webpack Babel-loader - not supported in a preset I have been trying to solve the following error for the past 2 days but to no avail:

I tried playing around with the .babelrc file and subsequently decided to include the presets in the webpack config file itself.
The following is my babel-loader configuration in webpack.config.js.
rules: [
    {
      test: /\.js$/,
      exclude: /node_modules/,
      use: [
        {
          loader: 'babel-loader',
          options: {
            babelrc: false,
            cacheDirectory: true,
            presets: ["react", "es2015", "stage-0"]
          },
        },
        {
          loader: 'eslint-loader',
        }
      ],
    }
  ]

The following is my package.json info:
  "dependencies": {
    "babel-core": "7.0.0-alpha.9",
    "babel-loader": "7.0.0",
    "babel-polyfill": "7.0.0-alpha.9",
    "babel-preset-es2015": "6.24.1",
    "babel-preset-react": "6.24.1",
    "babel-preset-stage-0": "6.24.1",
    "babel-register": "6.24.1",
    "webpack": "2.4.1",
    "webpack-chunk-hash": "0.4.0",
    "webpack-dev-middleware": "1.10.2",
    "webpack-dev-server": "1.14.1",
    "webpack-hot-middleware": "2.18.0",
   }

If any light could be shed on what's causing this error, it would be highly appreciated.

A: babel-core's 7.x version has stricter restrictions on what presets can do. Since you're still using babel-preset-react@6.24.1, it will fail.
If you're going to use the 7.0.0-alpha.X releases, you should do it for all the presets and babel-register too.


text:
Q: How to perform deferred tasks in backend Actually the problem is very common. Let me describe this by example.
Imagine you have a web service where users register and pay for some gold status. There is expiration date. The question is how to remove the gold status in time?
I see at least two solutions:

*

*Write a daemon that checks user statuses and current time and perform some actions

*Use cron as a deamon and do the same

But I believe there are other approaches. By the way the language the system is written is Python but I don't think this really matters.

A: Assuming you're using a database to store account information, filtering a search on "account_expiry>=get_date()" on the database (i.e. in SQL) is a negligible operation.
If you're not using a database for account information, your approach would vary based on what you're using.
To answer your titled question, how do you run a deferred task on a backend in python, look at Celery

A: I believe there are two basic approaches:

*

*check the current status every time it's necessary

*have a process run at some regular interval to do the checking

The problem with the first method is it can get resource intensive, while the problem with the second is that there may be a window where the user shouldn't have the "gold status" but does.
For the second option whether you use cron or a custom deamon or a custom timed method in the program itself really makes no difference.


text:
Q: Cloudant Sorting on a nullable field I want to sort on a field lets say name which is indexed in Cloudant DB. I am getting all the documents both which has this name field and which doesn't by using the index without sort . But when i try to sort with the name field I am not getting the documents which doesn't have this name field in the doc.
Is there any way to do this by using the query indexes. I want all the documents in sorted order which doesn't have the name field too.
For Example :
Below are some documents:
{
 "_id": 1234,
 "classId": "abc",
 "name": "Happa"
}
{
  "_id": 12345,
  "classId": "abc",
  "name": "Prasanth"
}
{
  "_id": 123456,
  "classId": "abc",
}

Below is the Query what i am trying to execute:
{
  "selector": {
    "classId": "abc",
    "name" :{
      "or" : [
        {"$exists": true},{"$exists": false}
      ]
    }
  },
  "sort": [{ "classId": "asc" }, { "name": "asc" }],
  "use_index": "idx-classId_name"
},

I am expecting all the documents to be returned in a sorted order including the document which doesn't have that name field.

A: Your query makes no sense to me as it stands. You're requesting a listing of documents which either have, or don't have a specific field (meaning every document), and expecting to sort those on this field that may or may not exist. Such an order isn't defined out of the box.
I'd remove the name clause from the selector, sorting only on the classId field which appear in every document, and then do the secondary partial ordering on the client side, so you can decide how you intend to mix in the documents without the name field with those that have it.
Another solution is to use a view instead of a Cloudant Query index. I've not tested this, but hopefully the intent is clear:
function(doc) {
    if (doc && doc.classId) {
        var name = doc.name || "[notfound]";
        emit(doc.classId+"-"+name, 1);
    }
}

which will key the docs on "classId-name" and for docs with no name, a specified sentinel value.
Querying the view should return the documents lexicographically ordered on this compound key (which you can reverse with a query parameter if you wish).


text:
Q: find, replace and escape string linux I'm trying find all instances of a string and replace them, the original string looks like this:

Some Text Here

the replacement looks like this:

<a href="<?php print $somevar;?>/some.php">Something new

What would be a good way to do this in the CLI
Thanks

A: I think the sed command would do the job nicely, provided your onclick handler and the "Some Text Here" don't include any nested HTML tags that the regex might confuse for the closing tags of the replacement string.

A: Searching and replacing in HTML is a guaranteed headache. At some point someone will pass you malformed HTML and even the most careful crafted regexp will fail horribly.
I'd definitely work with the HTML at the highest possible level of abstraction, preferably a homegrown tool that uses DOM or SAX.
For a quick fix

*

*A command line tool using XSL/XSLT

A: Standard way of searching and replacing in linux command line is sed, eg:
sed -i yourfilename -e "s%textyouwantoreplace%newtext%g"
The only thing is, sed uses regular expressions, so you'll need to escape stuff that might be a wildcard, by putting a \ before it, eg write \$ instead of $.
-i means: edit the file in-place
-e means: the next thing in the commandline is an expression to evaluate, ie the whole thing in quotes after it
's' means 'substitute'
'g' means 'global' substitution


text:
Q: xaml WebView: How to catch a "OnNavigation" event @Windows Store App I am developing Windows Store Apps with C#/xaml.
How do I notice if a link in my WebView gets klicked? There is no Event for that afaik. I've already looked into this and that but it doesn't provide me with a suitable solution.
May I give an example: I am embedding the stream of a facebook page in my WebView via iFrame. I want to block all links that might be in that iFrame.

A: You can call InvokeScript with some of your own Javascript to set up a listener for when the user navigates away from your page. This would look something like the following in C#:
var navigationListenerString = @"
(function() {
  function leavingPage() {
    window.external.notify("LEAVING PAGE");
  }
  window.onbeforeunload = leavingPage;
})()";

webView.InvokeScript("eval", new string[] { navigationListenerString });

Then you can use ScriptNotify to listen for your particular message to determine that the page is unloading and the user is leaving. Unfortunately you cannot detect where a user is going. Also, if the hyperlink opens in a new window and the webview does not unload, you cannot detect that either.


text:
Q: How can I grab each page of text in a Word doc separately (using .NET)? I need to determine which pages of a Word document that a keyword occurs on.  I have some tools that can get me the text of the document, but nothing that tells me which pages the text occurs on.  Does anyone have a good starting place for me?  I'm using .NET
Thanks!
edit: Additional constraint: I can't use any of the Interop stuff.
edit2: If anybody knows of stable libraries that can do this, that'd also be helpful.  I use Aspose, but as far as I know that doesn't have anything.

A: This is how I get the text out,  I believe you can set set the selection range to a page, then you could test that text, might be a little backwards from what you need but could be a place to start.
Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();
object missing = Type.Missing;
object fileName = @"c:\file.doc";
object objFalse = false;

wordApplication.DisplayAlerts = Microsoft.Office.Interop.Word.WdAlertLevel.wdAlertsNone;
Microsoft.Office.Interop.Word.Document doc = wordApplication.Documents.Open(ref fileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing,ref objFalse, ref missing, ref missing, ref missing, ref missing);

//I belevie you can define a SelectionRange and insert here
doc.ActiveWindow.Selection.WholeStory();
doc.ActiveWindow.Selection.Copy();

IDataObject data = Clipboard.GetDataObject();
string text = data.GetData(DataFormats.Text).ToString();

doc.Close(ref missing, ref missing, ref missing);
doc = null;

wordApplication.Quit(ref missing, ref missing, ref missing);
wordApplication = null;

A: How are you defining a page?
If you only count section/hard page breaks it complex, but doable. If you want to count soft page breaks the task becomes very very difficult and somewhat meaningless. Consider that the determination of where soft-page breaks land is dynamically generated at run-time and is not stored in the file itself. It depends on a huge number of factors including the active printer driver (yes it can change for the same file on a different computer), fonts, kerning, line spacing, margins, etc, etc ,etc.

A: One crappy way to do this with Aspose is to convert the Word file to a PDF and then grab text on each page.
I don't know anything about the Aspose internals or how they define their soft pages when converting, but this is the best I've got so far.

A: Thank you for using Aspose.Words.
In the public API we currently have only the "flow-document" information e.g. paragraphs, tables, lists etc. Internally, we build a page layout model that has classes like page, block of text, line of text and so on. There are internal links of course between the document model and the layout model and it is possible to find out which page ends where and all the stuff. Making this information available via the public API is (well, still) high on our priority list.
Have you logged your request in the Aspose.Words support forums? We use this info to maintain a voting system and will work on features that get more votes first.


text:
Q: If $A \subseteq B$ and if $A$ dedekind-infinite, then $B$ dedekind-infinite I have a question about the above theorem. I try to prove it on my own.
First we have the premises, i.e. $A' \subset A$ and $f: A \to A'$ bijective, as well as $ A \subseteq B$.
Then we define a new function $g: f \cup id^{B-A}$, so that $g(x) = f(x)$ for $x \in A$ and $g(x) = x$ for $x \in B-A$. Now, because of $A' \subset A$ we get $rng(g) = A' \cup (B-A) \subset B$.
But to prove B dedekind-infinite I also need to show that $h: B \to rng(g)$ is bijective. But how can that be done? I neither see the idea nor the formalization.


text:
Q: Iterate through a dictionary and return keys and values that share x amount of values? x is user input?
Given a file named hobbies.txt.
This file contains a group of Facebook users and their hobbies.
Each line in the file contains a user/username and a list of hobbies
  of that user. The data in each line is delimited by commas.
For instance in the line: 2254,reading,coding,swimming,playing soccer,
The user/username is: 2254
The hobbies are: reading`, coding, swimming, and playing soccer
The number and type of hobbies may differ from one user to another.
This file will be your data set that your code has to read to be able
  to implement  a code that does the following:
Finding circles/networks of friends:
In each circle you will report, all the users should share at least x
  number of hobbies
x is a variable that a user can input to the program.
Circles of friends should be written to a file named circles.txt.
Each line should have the usernames in the circle/network you found,
  tab character, and list of shared hobbies.
for example, a line may look like:
  2254,552,1258    reading,swimming,hiking
Finding popular users:
Popularity is based on being part of at least y circles/networks.
y can be variable that a user can input to the program.
Popular users should be written to a file named popular.txt.  Each
  user and how many circles/networks the user belongs to, should be in
  separate line and separated by the tab character.
For instance: 2254   5
This step should occur after step (a.).
Hint:  You may want to save the circles you found in part (a.) in some
  data structure so that you can us them in this part.

My Code: python
import csv
csv_file = open ('hobbies.txt')
csv_reader = csv.reader(csv_file, delimiter=',')
csv_dict={}
for row in csv_reader:
  k= row[0]
  v = row[1:]
  csv_dict[k] = [x.strip() for x in v]

for i in csv_dict.values():
  i.pop()

keyList =[*csv_dict]
circle ={}
for i in range(len(keyList)):
   i_item = keyList[i]
   for j in range(i+1, len(keyList)):
      j_item = keyList[j]
      user1 = set(csv_dict[i_item])
      user2 = set(csv_dict[j_item])
      hob = user1.intersection(user2)
      if (len(hob) > 1):
      hob = tuple(hob)
      circle[hob] = [i_item, j_item]
print(circle)

output:
{('cosplay', 'textiles'): ['2345', '4545'], ('orienteering', 'running'):
['4567', '5050'], ('orienteering', 'jumping', 'running'): ['8888', '5050'],
('dancing', 'singing'): ['9999', '1010'], ('cake', 'racing', 'decorating',
'car'): ['4545', '5050']}

Right now my code is only comparing between two users, how can I compare for maybe 3, 4, 5, ......, n that share x hobbies?

A: You can make a dictionary of hobbies to a set of users who share them.
Say hobby_users. Use this to make a dictionary of hobbies to number of users who share them (hobby_user_count).
user_hobbies = defaultdict(set)
all_hobbies = set()

for row in csv_reader:
    user, hobbies = row[0], [h.strip() for h in row[1:]]
    user_hobbies[user].update(hobbies)
    all_hobbies.update(hobbies) # build set of hobbies to be used later

hobby_users = {
    h: set(u for u, hs in user_hobbies.items() if h in hs) for h in all_hobbies
}

hobby_user_count = {
    h: len(us) for h, us in hobby_users.items()
} # if you have hobby_users or

hobby_user_count = {
    h: sum(1 for hs in user_hobbies.values() if h in hs) for h in all_hobbies
} # just using all hobbies

You can look up hobby_user_count for the user input.
shared_hobbies_matching_count = [
    h for h, user_count in hobby_user_count.items() if user_count is user_input
]


text:
Q: Is there a (pattern?) name to various concurrent computation? I am looking for the name and info on a pattern (?) that I'm contemplating. As I don't know the name, it's difficult to search for it.
Here's what I'm trying to do, with a totally hypothetical example...
find-flight ( trip-details, 'cheapest') :: flight
I have this public function, find-flight(...), that accepts 2 parameters, trip-details and  some instruction to apply. It returns a single flight, not a list of them.
When I call it with 'cheapest', the function will wait for all available flight results to come in from expedia, travelocity, hotwire, etc, to assure the cheapest flight is found.
When I call it with 'shortest-flight', the function would do the same kind of underlying work as 'cheapest' but would return the shortest flight. I'm sure you can come up with other instructions to apply.
BUT! I'm specifically interested in a variant of this: the instruction (implied or not) would be 'I-am-filthy-rich-and-I-want-to-buy-a-ticket-now'. In other words, the function would call all the sources such as expedia, orbitz, etc, but would return the very first internally received result, at any price point.
I'm asking because I want my public function to be as quick as possible. I can think of a number of strategies that would make it respond fast, but I'm not sure that I know which approach would be best considering that the parameter is unknown until called, right?
So I'm thinking about writing various versions of this function that would all be called by the public version. It'd return the first result. Then, the other strategies could optionally be aborted. If I did that, I could get some metrics on the function and further optimize.
If I were to write this in Java, I'd have a bunch of future objects that the function would loop through to see which one is done first. I'd return that one.
What's that called?

A: It's been proposed that the pattern is called Promise Race


text:
Q: How to continue executing other part of code while pop up window is open in perl I am executing a perl script as a part of other bigger code.
My perl code opens up a pop up window based on status value (success or failure). This issue is, the script does not continue executing other parts of code untill I close this pop up window created by perl. How can I solve this. Please help. I want to keep the pop up open and continue executing other parts of parent script.
I am using following perl script to open up pop up.
#!/usr/local/bin/perl
use Tk;
my $status = shift;
my $opt = shift;
my $mw = MainWindow->new;
$mw->title("DONE");
if($status eq "success") {
  $mw->Label(-text => "$opt dummyFill for 'test1' succeeded",       -background => "green")->pack(-ipadx => 10, -ipady => 10);
    $mw->Button(-text => "Close", -background => "green", -command => sub { exit})->pack(-fill => "x");
} else {
    $mw->Label(-text => "$opt dummyFill for 'test1' FAILED", -background => "red")->pack(-ipadx => 10, -ipady => 10);
    $mw->Button(-text => "Close", -background => "red", -command => sub { exit})->pack(-fill => "x");
}
$mw->geometry("+250+50");
MainLoop;

I appreciate your help.
Thanks
Sam

A: Your main script is probably waiting for a return from the call to Perl.  In Tk Perl stays in the MainLoop either you call the TK specific exit routine, which closes out the main window, or directly call destroy on your main window object.
The solution isn't in this script but in the calling code.  The calling code needs to fork the execution of this Perl script into a separate process or thread.


text:
Q: Test case to check state update doesn't seem to be giving a correct output I have a simple function that toggles the state of a component from true to false on a click event.
Here is the function
public toggleAvailability(dayTime: string): void {
    const isAvailable = this.state[dayTime] === false ? true : false;

    this.setState(
      { [dayTime]: isAvailable },
      () => {
      const instructor = {
        userId: this.props.userId,
        availability: this.state.friEarlyAfternoon
      };
      this.props.updateInstructor(instructor);
    });
  }

I am using Jest+Enzyme for unit tests and I am trying to test my toggle function as follows:
describe('Method toggleAvailability()', () => {
    function test_toggleAvailability(dayTime: string, currentState: boolean, toggledState: boolean): void {
      beforeEach(() => {
        wrapper.setState({
          dayTime: currentState,
        });
        wrapper.instance().toggleAvailability(dayTime);
      });

      it(`Sets the state's ${dayTime} to ${toggledState}`, () => {
        expect(wrapper.state().dayTime).toEqual(toggledState);
      });
    }
    test_toggleAvailability('monEarlyMorning', false, true);
    test_toggleAvailability('monEMorning', true, false);
  });

For some reason I cannot get my tests to pass. I am getting this:

Anyone got a suggestion here?

A: Any time you're setting state based on existing state, you must use the callback version of setState and the state argument it passes you, because state updates are asynchronous and can get batched together.
So this:
const isAvailable = this.state[dayTime] === false ? true : false;
this.setState(
  { [dayTime]: isAvailable },
  () => {
  const instructor = {
    userId: this.props.userId,
    availability: this.state.friEarlyAfternoon
  };
  this.props.updateInstructor(instructor);
});

should be this, where you're passing in a function for the first argument as well:
this.setState(
  prevState => {
    const isAvailable = prevState[dayTime] === false ? true : false;
    return { [dayTime]: isAvailable };
  },
  () => {
    const instructor = {
      userId: this.props.userId,
      availability: this.state.friEarlyAfternoon
    };
    this.props.updateInstructor(instructor);
  }
);

Side note: Or if you don't actually need strict equality on that === false, you could just use !:
this.setState(
  prevState => ( { [dayTime]: !prevState[dayTime] } ),
  () => {
    const instructor = {
      userId: this.props.userId,
      availability: this.state.friEarlyAfternoon
    };
    this.props.updateInstructor(instructor);
  }
);


text:
Q: How can I replace class on anchor tag without breaking functionality? In the code below I have anchor tag where window and less class are applied. How can I remove anchor tag such that classes that are applied to anchor tags are used in the code and functionality does

A: It seems that you want the following html:

${properties.readText}

${properties.readLessLinkText}

I've removed the a tags and added the a classes to the child span tags.
Your css will no longer work because you are matching based on DOM hierarchy, not just class name. See this article for a more in-depth treatment, but essentially in e.g. this section:
.read-window-section .read-window-links .window .read-window p:after {
  content: url(down_arrow_icon.png);
  display: inline-block;
}

you are saying, "set content to url(down_arrow_icon.png) and display to inline-block for a p which is a descendant of an element with class read-window which is a descendant of an element with class window which is a descendant of an element with class read-window-links..." etc. If you change the DOM hierarchy, you need to change your css to match, which means something like

${properties.readText}

.read-window-section .read-window-links .window.read-window p:after {
  content: url(down_arrow_icon.png);
  display: inline-block;
}

Notice how there is no space between .window and .read-window, which means "match an element with both .window and .read-window classes."


text:
Q: Formatting a Alphabetized Collection i have a Collection for lastnames read in from an employee class.  Is it possible to Organize the output of the sorted names after the Sort?  I need an output that is similar to the line i have commented out, instead of the generic single line output with lastnames seperated by comma "[Name1, Name2, Name3...]" which i get now from the Collection...
 public void alpha1()
    {
     LinkedList<String> alphalist = new LinkedList<String>();
     ListIterator<Employee> iterate = list.listIterator(0);
    // System.out.println("First Name" + "\t" + "Last Name" + "\t" + "Salary");
     while (iterate.hasNext())
      {
           emp = iterate.next();

       alphalist.add(emp.getlastname());
      }
      Collections.sort(alphalist, new Comparator<String>() {
         @Override
         public int compare(String o1, String o2) {
             return Collator.getInstance().compare(o1, o2);
         }
     });
     System.out.println(alphalist);
    }

A: I think better to create Comparator on Employee object and sort the original collection itself.
Once your collection is sorted, iterate and print your collection using Employee object itself.
e.g.
 public void alpha1()
   {
       Collections.sort(list, new Comparator<Employee>() {
        @Override
        public int compare(Employee o1, Employee o2) {
          return o1.getLastName().compareTo(o2.getLastName());
        }
      });

      ListIterator<Employee> iterate = list.listIterator();
      while (iterate.hasNext())
      {
        emp = iterate.next();
        System.out.println("First Name" + "\t" + "Last Name" + "\t" + "Salary");
      }
    }

A: Instead of storing a list of last name strings, the better approach would be to store employee objects and sort them by their last name.
You can implement Comparable in your Employee class to define its natural sorting.  Then, you make alphalist a list of employees, and sort it using Collections.sort(alphalist).
public class Employee implements Comparable<Employee> {
    ...

    @Override
    public int compareTo(Employee emp) {
        return this.getLastName().compareTo(emp.getLastName());
    }
}

Then, your new alpha1() method:
public void alpha1() {
    LinkedList<Employee> alphalist = new LinkedList<Employee>();
    ListIterator<Employee> iterate = list.listIterator(0);
    while (iterate.hasNext()) {
        alphalist.add(iterate.next());
    }
    Collections.sort(alphalist);
    System.out.println(alphalist);
}


text:
Q: Console app doesn't print when executing with xp_cmdshell under sql server agent proxy I have a requirement to automatically print an ssrs report to a specific printer on the network whenever a new row is inserted into a database table.  There is a trigger on the database table which uses xp_cmdshell to call a console application which renders and prints the report.  When I execute the console application from the command prompt it works.  Also, when I change the account that sql server runs as to administrator, xp_cmdshell works as expected and the report is printed.  But, I do not want sql server to run as administrator so I set up a proxy account, using sp_xp_cmdshell_proxy_account. I used administrator as the account that SQL Server executes xp_cmdshell as and set SQL Server to run as Local System.  However, when I log into SQL Server with an account that is not sysadmin and execute the console app with xp_cmdshell the console app generates the following exception:
The RPC server is unavailable - Source:System.Drawing - Stack Trace: at System.Drawing.Printing.StandardPrintController.OnStartPrint(PrintDocument document, PrintEventArgs e) at System.Windows.Forms.PrintControllerWithStatusDialog.OnStartPrint(PrintDocument document, PrintEventArgs e) at System.Drawing.Printing.PrintController.Print(PrintDocument document) at System.Drawing.Printing.PrintDocument.Print() at PrintQCChecklist.Program.Main(String[] args)
I then called whoami.exe with xp_cmdshell and it returns 'administrator'.  Why would a document print when sql server is running as admin but crash when running under a proxy as admin???  (Please do not bite my head off for using xp_cmdshell.  I am aware of the security risks.  Thank you.)

A: Have you thought about publishing the SSRS reports to a network share, and have a printer program pick up the report, print it, and then archive it? I used to do something similar with a cheap third party printing tool - supported by the vendor, and - in my mind - cleaner.


text:
Q: How to display categories as titles on my page in wordpress? I have created a custom post type named "State Leagues" using types plugin. My post type has some categories and outputs both. When I display the posts' titles it displays correctly. My code for displaying post titles is this:
 <?php
            $args = array(
                'post_type' => 'stateleague-pos-type',
                'posts_per_page' => 4,
                'order_by' => 'post_date',
                'order' => 'DESC'
            );
             $loop = new WP_Query($args);
//            $counter = 0;
//            $big = 1;
            while ($loop->have_posts()) : $loop->the_post();
          ?>

                <a href="<?php the_permalink(); ?>">

 <?php the_title(); ?>

?>

Now I want to display the categories' names as the title instead of the posts' titles. I have searched for it but didn't find anything that works. Is it possible to display category names as titles?

A:     <?php
    $taxonomy = 'filters';
    $terms = get_terms($taxonomy);

    if ( $terms && !is_wp_error( $terms ) ) :
    ?>

            <?php foreach ( $terms as $term ) { ?>

<a href="<?php echo get_term_link($term->slug, $taxonomy); ?>"><?php echo $term->name; ?>

            <?php } ?>

    <?php endif;?>

Or in fuctions.php Put  this:

  function get_the_category_custompost( $id = false, $tcat = 'category' ) {
    $categories = get_the_terms( $id, $tcat );
    if ( ! $categories )
        $categories = array();

    $categories = array_values( $categories );

    foreach ( array_keys( $categories ) as $key ) {
        _make_cat_compat( $categories[$key] );
    }

    return apply_filters( 'get_the_categories', $categories );
}

and call the function as:

<?php $cat = get_the_category_custompost($post->ID, 'Your Custom Taxonomy'); ?>

Try this i hope it will help


text:
Q: Makefile: updating variables
Possible Duplicate:
arithmetic in a Makefile

I'm very much a beginner using Makefile. I would like to update a variable, like this more or less:
LEVEL=0

train:
     while (eval_score > previous_eval_score)
     make iterate

iterate:
     do stuff
     write files to /path/to/$(LEVEL)/asdf.txt
     $(LEVEL)++

In other words, every iteration writes some files to a directory, first to /path/to/0, then /path/to/1, etc. until some threshold is reached.
So apparently it's not allowed to update or reassign a variable inside a function. I have searched for a while now but can't find any satisfactory answers. Maybe I have but I don't understand everything. I have also tried stuff like calculating in bash but eventually I still have to update the variable. Perhaps I should try something like update a file instead and for every iteration, just read from the file?
Thanks for your time.

A: The main problem with your Makefile is that each make iterate spawns a sub-make, which could update its environment variables, but with no effect on the parent make and thus no effect on the next iteration. In addition, you cannot update variables from within rules, but that is a secondary problem.
You can do iterative make just like you suggested and increment the level via the shell:
train:
    LEVEL=0; while need_more_iterations; do \
       $(MAKE) LEVEL=$$LEVEL iterate; \
       LEVEL=`echo $$LEVEL + 1 | bc`; \
    done


text:
Q: How to make VNC Server work with ubuntu-desktop without xfce I have Ubuntu Server LTS 14.04 and I want to know whether it's possible to install vnc4server and make it work with ubuntu-desktop (and not xubuntu-desktop) without installing xfce4.
I think I have to configure the vnc4server configuration file but I'm a beginner with all this.
Please, don't suggest that I use xrdp or gnome-core. I just want to run a VNC Server using only the original ubuntu-desktop installation. I use VNC Viewer to connect to my servers, but I don't have any problem with suggestions that I use something different than vnc4server if it's going to work with ubuntu-desktop.

A: install these packages
# apt-get install gnome-panel gnome-settings-daemon metacity nautilus gnome-terminal

and use this xstartup file
#!/bin/sh

export XKL_XMODMAP_DISABLE=1
unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS

[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup
[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources
xsetroot -solid grey
vncconfig -iconic &

gnome-panel &
gnome-settings-daemon &
metacity &
nautilus &
gnome-terminal &

A: I had to add gnome-session & prior to gnome-panel & to get any window management to work. Without it, I could only view the default desktop.


text:
Q: Django urls straight to html template Learning django & python.
Just set up a new site after doing the tutorial. Now for arguments sake say I want to add a bunch of About us, FAQ basic html pages with very limited dynamic elements do you go ahead and write a new line in my urls.py file for each page? or is their some neat way to say map all * *.html to the relevant .html file directly?
In general even if it does require a view will I have to write a new line in the url.py file for every page?

A: As long as there is some uniquely identifying section in the URL, you will not need to create an entry in urls.py for each direct-template url.
For example, you could say that all urls ending in ".html" are referencing a direct file from the templates.
urlpatterns = patterns('django.views.generic.simple',
    (r'(.+\.html)$', 'direct_to_template'),
    # ...
)

Take a look at http://docs.djangoproject.com/en/1.2/ref/generic-views/#django-views-generic-simple-direct-to-template for details.

A: Currently the best way to do this is using TemplateView from generic class-based views:
from django.views.generic.base import TemplateView

url(r'^$', TemplateView.as_view(template_name='index.html'), name='home'),

A: One way to do this would be to write a single custom view that wraps the direct_to_template generic view. The wrapper could accept a parameter and accordingly form the name of the template and pass it to direct_to_template. This way you can route multiple pages with a single URL configuration.
Something like this:
url(r'^foo/(?P<page_name>\w+).html$', 'my_static_wrapper', name = 'my_static_wrapper'),

def my_static_wrapper(request, page_name):
    # form template name and call direct_to_template

That said I suspect that there are better solutions out there though.

A: Write a url which grabs the static pages you're interested in
url(r'^(?P<page_name>about|faq|press|whatever)/$', 'myapp.staticpage', name='static-pages')

The staticpage view function in myapp
from django.views.generic.simple import direct_to_template
from django.http import Http404

def staticpage(request, page_name):
    # Use some exception handling, just to be safe
    try:
        return direct_to_template(request, '%s.html' % (page_name, ))
    except TemplateDoesNotExist:
        raise Http404

Of course, you need to follow a naming convention for your templates, but this pattern can be expanded upon as needed.
This is better than the .+\.html pattern because it will treat templates which don't exist as 404s, whereas .+\.html will blow up with 500 errors if the template doesn't exist.

A: If you're using the class based views because direct_to_template has been deprecated, you can create a simple wrapper that renders your own templates directly:
from django.views.generic import TemplateView
from django.template import TemplateDoesNotExist
from django.http import Http404

class StaticView(TemplateView):
    def get(self, request, page, *args, **kwargs):
        self.template_name = page
        response = super(StaticView, self).get(request, *args, **kwargs)
        try:
            return response.render()
        except TemplateDoesNotExist:
            raise Http404()

and in your router:
from myapp.static.views import StaticView

urlpatterns = patterns('',
    url(r'^(?P<page>.+\.html)$', StaticView.as_view()),
    # ...
)

A: Slight Changes for latest versions of Django.
from django.views.generic.base import TemplateView

urlpatterns = [
 path('',TemplateView.as_view(template_name='index.html'), name='home'),
]


text:
Q: Malfunction SOQL Query I have the below Data Categories
Group1
     Category1
     Category2
Group2

Now the query which I am trying to execute is below to get all the articles in published state and linked with Group 2, but the query is giving the malfunction error in workbench. Any help
SELECT Title FROM KnowledgeArticleVersion WHERE PublishStatus='online' WITH DATA CATEGORY Group2__c

A:
The syntax of the data category selection in a WITH DATA CATEGORY
  clause in a SOQL query includes a category group name to use as a
  filter, the filter selector, and the name of the category to use for
  filtering.

If you want to select all the article in a group use the ABOVE_OR_BELOW  filter selector like this: SELECT Title FROM KnowledgeArticleVersion WHERE PublishStatus='online' WITH DATA CATEGORY Group1__c ABOVE_OR_BELOW Category1__c
See Filtering Selectors for a list of valid selectors.
In your case, I believe there is no category under group2, so your query should look like this: SELECT Title FROM KnowledgeArticleVersion WHERE PublishStatus='online' WITH DATA CATEGORY Group2__c AT All__c


text:
Q: ASP.NET Link Button change on jQuery slider I have two jQuery sliders in my page - A user will be a width and height and then click a button which should go to a New Url with them value as querystring parameters.
So I have two asp HiddenFields on my page that I set too the value of the slider - that seems to be working ok.
<asp:linkbutton ID="bmiLink" class="action-button" Text="Click for BMI" ToolTip="View your BMI" runat="server" OnClick="btnBMI_Click" />

I then have the following C# in my Code Behind:
    protected void btnBMI_Click(object sender, EventArgs e)
    {
        //Get Values from Hidden Fields
        string weight = weight .Value;
        string height= height.Value;

        bmiLink.PostBackUrl = string.Format("/BMIPage?{0}={1}&{2}={3}", QueryStringConstants.Weight, weight , QueryStringConstants.Height, height);
    }

When I first load the page the slider values are both zero and if I hover over the button - the link is appearing as -
javascript: __doPostBack('ct100$ct100$bodyContent$formContent$bmiLink',")

If I change the slider value to say weight 150 and height 180 I want the button link to get updated.  What is the best way to achieve this?
The way it is working now - I have to click the button which gets the values and then posts back to the page and resets the sliders to 0 but updates the link on the button to include the correct query parameters.  So is there a way I can easily dynamically set the link on the button driven by the values that the sliders are set too?

A: Well, you could instead consider doing everything on the client, so in your button do:
<asp:LinkButton .. OnClientClick="postback(this, event);" />

function postback(sender, e) {
   //you may have to use e.stopPropagation() and e.preventDefault() to prevent the default postback operation

   var val = /* jquery expression to get the value */
   __doPostBack("<%= Button.UniqueID %>", val);
}

And then it will grab the value from the client.  You can then change it to whatever you want.

A: Change the last line in the btnBMI_Click event handler to:
Response.Redirect(string.Format("http://domain.com/BMIPage?{0}={1}&{2}={3}", QueryStringConstants.Weight, weight , QueryStringConstants.Height, height));


text:
Q: how to downgrade flutter version? Im trying to downgrade to 3.0.5 with terminal and typed
git reset --hard e85ea0e79c6d894c120cda4ee8ee10fe6745e187

but error says
fatal: not a git repository (or any of the parent directories): .git

how can I solve??

A: flutter downgrade 3.0.5
Change the version from 3.0.5 to as your wish
Run this command.

A: Stop installing and uninstalling versions! Get yourself an install of package:fvm, aka https://pub.dev/packages/fvm, aka http://fvm.app.  You can have per-project selection of any flutter version that has been published, as well as keep the latest version as your global default.


text:
Q: Android alarm manager only repeats once after reboot I'm trying to send a broadcast intent using alarm manager roughly every 60 seconds
I'm using the following function to set the alarm manager:
fun alarm(context: Context) {
        println("load alarms5")
        val alarmManager =
            context.getSystemService(Context.ALARM_SERVICE) as AlarmManager

        val alarmIntent = Intent(context, CheckAlarms::class.java).let { intent ->
            PendingIntent.getBroadcast(context, -1, intent, PendingIntent.FLAG_IMMUTABLE)
        }

        val calendar: Calendar = Calendar.getInstance().apply {
            timeInMillis = System.currentTimeMillis()
        }

        alarmManager.setInexactRepeating(
            AlarmManager.RTC_WAKEUP,
            calendar.timeInMillis,
            1000*60,
            alarmIntent
        )

        println("-alarm search-")
    }

If I use the function normally it sets the alarm correctly and I every 60 seconds or so the intent is sent.
But when I use the following function to set the alarm when the phone boots, the alarm manager only runs once without repeating, and the intent is only sent once.
class BootReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
    if (intent.action == "android.intent.action.BOOT_COMPLETED") {
        PlannerAlarmManager.alarm(context)
    }
}

Manifext:
<receiver android:name="pt.keeponcare.planner.BootReceiver"
        android:enabled="false"
        android:exported="false">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

This code runs when the app is opened:
context.packageManager.setComponentEnabledSetting(
        receiver,
        PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
        PackageManager.DONT_KILL_APP
    )


text:
Q: Does USB supply a "constant" 5V or "up-to" 5V? I am trying to reverse engineer a digitizer* inside an old laptop. I am fairly certain it is a USB device because I noticed a twisted pair of cables next to a ground wire. Just to make sure it is USB I probed the pin to the other side of (what I suspect to be) D-.  When I did this I saw different voltages flashing very quickly but nothing close to 5V.  I believe the max I saw was 1.2V and min being somewhere around .3V.
I don't want to wire this up to a USB cable out of fear of destroying the digitizer if it can't in fact handle 5V.
This would make sense to be USB VCC if it does offer up to 5V but I couldn't find anything definitive that I could understand at least.
* It's a Wacom digitizer in a Fujitsu T901 laptop from about the year 2011.

A: USB Vcc is 5V - constant.
It should only drop if you draw too much current, in which case a PTC (automatically resetting fuse) will open and shut off the current.  In that case the voltage will drop to near zero.
The voltage on the data lines is a different story.  D+ and D- transmit data at high speed.  Your multimeter can't make any sense of what is there - it changes way too fast for the meter.

A: If there isn't a clear sign that it is USB, consider that it could be SPI, I2C/SMBus or some other form of serial connection, particularly for an internal device. These are (and were) commonly used for internal data connections at fairly low data rates.
What did you probe the signal with? If a voltmeter, the readings of 0.3 to 1.2V could be (or almost certainly are) misleading on a data line. If an oscilloscope, can you post a picture of the signal?
It would also help if you post a picture (or details of markings) of any ICs on the digitizer, and any silkscreen markings on the PCB where the suspected USB line is attached.

A: TL;DR just because it's connected to the USB does not mean 5V or even that it is powered from USB.
For versions 1 of USB The spec says 5V +/- 5%, so you should design to accept 4.75V to 5.25V.
For USB 2.0 the spec says:
• The voltage supplied by high-powered hub ports is 4.75 V to 5.50 V.
• The voltage supplied by low-powered hub ports is 4.4 V to 5.50 V.
USB Version 3.something introduces the availability of increased voltages (up to 20V). but a device has to explicitly request increased voltage, else they just get the same Approximately 5V.
When I plug my phone into its charger via a power meter I see the voltage jump to 9V
My laptop's charger uses a USB C connector and can provide 5,9,15, or 20V (according to the label)
Now, your laptop's internal device may be designed for some voltage other than 5V. The USB data lines D+ and D- signal at only 3.3V.  So, 3.3V could instead be the  supply to the (touch-screen) digitizer.
In general the USB host can't see the device's supply voltage, it only sees the data signals.
Some USB devices (eg: laser printers) do not use the USB VCC line for power.

A: USB will power 5v constant. If your digitizer has unkonwn input voltage requirement, it is better to do more research or ask the manufacturer of the device or laptop. If you directly power it for experiment, it may blow some component or IC which maybe very difficult to find in the open market.

A: I recently bought two cheap measurent devices, one for Micro USB and another one for USB-C to verify the wall-charger/cable/QI-charger chain for different devices. Nowadays USB seems to constantly haggle about voltage and wattage! Some of my chargers would provide up to 12 V through USB (far off the original specification) but some devices would even consume it under varying circumstances.
To cut a short story shorter: You will not get around to measure your specific case. The specifications are interpreted in enough ways to ake this necessary.

A: It sounds like you probed a data line.
USB supplies 5V for power. However, signalling is at lower voltages. USB 1.1 used 3.3V signalling, and USB 2.0 High Speed uses about 400mV. If you could see the line changing then it was likely a data line.
That is if it was USB at all of course. It could be PS2 or something else.


text:
Q: Try except in python/selenium still throwing NoSuchElementException error I am trying to capture some website elements using selenium in python, and I am using try/except in case there is a specific element that cannot be found in that particular page. This all well and good, however the script still throws a NoSuchElementException even though I am expecting it and have told the script to handle it a certain way or pass.
The only thing I can think that may be an issue is that this try/except is nested inside another try/except, so that i goes like this
for month in (month_start, month_end):

    for date in (date_start, date_end):

        try: #this is just a general try in case there is a breakdown in finding one of the elements
            driver.get(url)
            results = driver.find_elements_by_xpath("""//*[@class="results"]/div""")

            for result in results:
                sample_element = result.find_element_by_xpath("blah").text

                #seems to be where the problem starts
                specific_element = ""
                try:
                    #this is a specific element that I know may not exist
                    specific_element = result.find_element_by_xpath(""".//*[@class="specific"]/div""").text
                except NoSuchElementException:
                    specific_element = ""
                    #I have tried pass instead as well with no luck
                #throws an error here and won't continue if the specific element is not found
        except:
            #pretty much a copy of the above try with some changes

So I generally think that I have a decent understanding of the try/except function in python but this is doing my head in. The "result in results" loop will happily continue until it doesn't find specific_element and just throws a "selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element:"
If being nested inside the try/except is the cause of the whole issue, could you please explain why that is the case, and recommend a possible solution that I could research or implement? Or maybe I have missed something fundamental.

A: I don't do python but if it were me, I would remove all the try/catches and replace them with find_elements_* and check for empty list. For example
replace
specific_element = result.find_element_by_xpath(""".//*[@class="specific"]/div""").text

with
elements = result.find_elements_by_xpath(".//*[@class='specific']/div")
if elements
    specific_element = elements[0]

This basically just makes sure that any element is found before accessing it and you can avoid all the try/catches. I'm of the opinion that exceptions should be exceptional... rare. They shouldn't be expected or used as flow control, etc.

A: You have to take care of a couple of points here :

*

*There is no absolute necessity to try driver.get(url)

*The issue is in the following block :
try:
    specific_element = result.find_element_by_xpath(""".//*[@class="specific"]/div""").text

Analysis
You have tried a chain of events before the try() actually comes into action :

*

*Evaluate
result.find_element_by_xpath(""".//*[@class="specific"]/div""")

*Next
result.find_element_by_xpath(""".//*[@class="specific"]/div""").text

*Next
specific_element = result.find_element_by_xpath(""".//*[@class="specific"]/div""").text

So,

*

*Once result.find_element_by_xpath(""".//*[@class="specific"]/div""") fails though NoSuchElementException is raised, try still remains silent.

Solution
A simple solution would be :
try:
    specific_element = result.find_element_by_xpath(""".//*[@class="specific"]/div""")
    specific_element_text = specific_element.text
    # other works

except NoSuchElementException:
    specific_element = ""
    # other works


text:
Q: A conjecture about prime test
Conjecture If $\varphi(m)<\varphi(n)$ for all $m<n$,then $n$ is a prime number.

I tried to find a counterexample when $n=pq$ ($p,q$ are prime), then we have to find a prime between $(p-1)(q-1)$ and $pq$, but I don't know if this is an open problem.


text:
Q: How to auto start virtual machine in VMware for ubuntu? Currently installed VMware Workstation on Ubuntu 14.04 server and in that the VMware Workstation version is 11.0.0 build 2305 329 is installed now, our question is as follow
Currently we have created 4 different virtual machine inside the workstation, now we want to autostart those machine when the host machine gets started in a different order. So what is the procedure we should do to get things done?
We've already searched for solutions over the Internet but couldn't find much about it or rather we are not searching in a proper manner. Can anybody help us in this regard and earliest please.
We thank you for your time and your reply in advance so what's this post
Have a good day


text:
Q: Controllers want a Key still if the new class is based on another class I am doing this-
File -> new project -> Visual C#  .Net Framework 4.5. -> ASP.Net MVC 4 Web Application.
I am creating a class Personne and a class Etudiant deriving from Personne (under the models folder)
Personne.cs
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Web;

 namespace TestTryHelper.Models
 {
     public class Personne
     {
         public int PersonneId { get; set; }
         public string Nom { get; set;}
         public string Prenom { get; set; }

     }

     public class Etudiant : Personne
     {
         public string Ecole { get; set; }
     }
 }

I am trying to add a HomeController  (Controllers/  ADD/ Controller)
Controller Name:  HomeController
Scalfolding options
Template : MVC controller with read/write actions and views using Entity Frameworkd
Model Class: Etudiant (TestTryHelper.Models)
Data context class:
  in the window New Data Context   TestTryHelper.Models.TestTryHelperContext
click OK
Views: Razor
Click ADD
I got this error message
 Unable to retrieve metadata for 'TestTryHelper.Models.Etudiant'.
 One or more validation errrors were detected during mode generation:

 -System.Data.Entity.Edm.EdmEntity,Type:  EntityType 'Etudiant'
 has no key defined.  Define the key for this EntityType.
 -system.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet ' Etudiants' is based on type
 'Etudiant that has no keys defined.

For some reason it is working for other people.  I can fix this by adding a EtudiantId under the Etudiant Class.
Anyone will know why it is working for some people and not for other ?
Thanks

A: If you change the property PersonneId to just Id I think it will work for both types. Alternatively, decorate the PersonneId property with the [Key] attribute, which will indicate to EF what property you want to use as the table key:
 public class Personne
 {
     [Key]
     public int PersonneId { get; set; }
     public string Nom { get; set;}
     public string Prenom { get; set; }

 }

You may also have to add this to the top of your code:
 using System.ComponentModel.DataAnnotations;


text:
Q: Change autoref name of items of a specific list In my document I have a customized list subtasks type (using enumitem) to insert subtasks.
I would like to reference them using \autoref.
However, since these are lists, \autoref inserts the word "item" before the label, where I would like to have "subtask".
If I just use \def\itemautorefname{subtask} all items in all lists will be reference with the word "subtask".
Is there a way to only change the autoref name for items of the subtasks list?

A: I can't give you an answer for how to get \autoref to show "Subtask" instead of "Item". Fortunately, it's straightforward to provide a solution that uses the cleveref package and its \cref cross-referencing command. With \cref, it's also easy to create multiple cross-references with a single command. (In the MWE, hyperref is loaded only to create hyperlinks, not to create cross-references.)

\documentclass{article}

\usepackage{enumitem}
\newlist{subtask}{enumerate}{1}     % this creates a dedicated counter named 'subtaski'
\setlist[subtask,1]{label=\arabic*} % set form of enumeration label here

\usepackage[colorlinks=true]{hyperref}

\usepackage[nameinlink]{cleveref}      % 'nameinlink' option emulates look of \autoref
\crefname{subtaski}{subtask}{subtasks} % set prefix for items of type 'subtaski'

\begin{document}
\begin{subtask}
\item Uno \label{subtask:1}
\item Dos \label{subtask:2}
\item Tres\label{subtask:3}
\end{subtask}

A cross-reference to \cref{subtask:2}.

As stated in \cref{subtask:3,subtask:1}, \dots
\end{document}


text:
Q: How to mock react-native-copilot? Trying to mock with jest react-native-copilot
This is the point in the screen where the module is imported.
import { walkthroughable, CopilotStep } from 'react-native-copilot';
...
const CopilotText = walkthroughable(Text);
...
<View>
  <CopilotStep order={2} name='name'>
    <CopilotText testID={'test-schedule-name'}>
      {this.props.scheduleName}
    </CopilotText>
  </CopilotStep>
</View>
...

This is how it's mock it so far in the test:
jest.mock('react-native-copilot', () => ({
  getCurrentStep: jest.fn(() => { }),
}));

This is the test:
it('displays name', () => {
    const { getByTestId } = render(<MyComponent />);
    const scheduleName = getByTestId('test-schedule-name'); // it doesn't get this... why?
    ...
});

This is the error:
Unable to find an element with testID: test-schedule-name
...
const CopilotText = walkthroughable(Text);
                    ^

Any idea?


text:
Q: How to add Youtube Video Like in iOS app I have requirement in one of my iPhone app.
I want to add "LIKE" and "SUBSCRIBE" functionality for YouTube video which is playing in my app.
I have static video youtube list which is playing in my app. Below this video, I need to add "LIKE" and "SUBSCRIBE" UIButton.
Can anyone let me know, how to implement "LIKE" and "SUBSCRIBE" function from iPhone app.
I have checked with below youtube apis urls:

*

*https://developers.google.com/youtube/v3/

*https://developers.google.com/youtube/v3/docs/videos/rate
But I don't know what to pass in "onBehalfOfContentOwner" parameter, and what can be steps to achieve it from iPhone application.
Can anyone know about this how to do this from native iPhone app?
Thanks.

A: YouTube Direct Lite for iOS has similar samples, you can pass "onBehalfOfContentOwner" as an optional parameter.

A:     @property (nonatomic, strong) NSURLSessionDataTask *sessionTask;

    NSString *strToken = [NSString stringWithFormat:@"Bearer %@",setTokenhere];
    NSString * strUrl = [NSString stringWithFormat:@"https://www.googleapis.com/youtube/v3/videos/rate?&id=%@&rating=like",setVideoId];
   AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
   AFHTTPRequestSerializer *requestSerializer = [AFJSONRequestSerializer serializer];
   [requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
   [requestSerializer setValue: strToken forHTTPHeaderField:@"Authorization"];
   manager.responseSerializer = [AFJSONResponseSerializer serializer];
   manager.requestSerializer = requestSerializer;

   __weak __typeof(self) weakSelf = self;
   self.sessionTask = [manager POST:strUrl parameters:self.parameter progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject)
    {
          NSLog(@"responseObject -> %@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
          weakSelf.sessionTask = nil;
          NSLog(@"%@",error);
    }];

This code For Like the Video


text:
Q: Question from entrance exam on Probability.
$7$ babies were born in a particular week in a private hospital. What is the probability that three babies were born on the same day of the week?

My answer is the denominator is $7^7$. The numerator will be $6480\times49= 317520$. Is it correct? The reasoning is to first select 3 babies from 7 babies and then the remaining babies have 6 days each, and then multiply it with 7.

A: Let us introduce seven events $A_1, \ldots, A_7$, where $A_i$ means that some three babies were born at $i$th day. Then we should find the probability of
$$
A=A_1\cup A_2\cup\ldots\cup A_7.
$$
Note that these events are not disjoint, and $A_1\cap A_2$ means that three babies were born at the first day and another three - at the second day. The intersections of more than two events are impossible. So
$$
\mathbb P(A) = \sum_{i=1}^7 \mathbb P(A_i) - \sum_{i<j}\mathbb P(A_i\cap A_j)
$$
where the second sum is over all possible pairs of $i,j$ with each pair appeared only once. The first sum containes $7$ identical probabilities
$$
\mathbb P(A_1) = \frac{\binom{7}{3}\cdot 6^4}{7^7}
$$
and the second sum containes $\binom{7}{2}$ identical probabilities
$$
\mathbb P(A_1\cap A_2) = \frac{\binom{7}{3}\cdot\binom{4}{3}\cdot 5}{7^7}.
$$
Indeed, firstly we choose three babies to born at the first day, then choose three babies from four to born at the second day, then the rest baby can born at any of the rest five days.
So
$$
\mathbb P(A)= 7\cdot \frac{\binom{7}{3}\cdot 6^4}{7^7} - \binom{7}{2} \cdot \frac{\binom{7}{3}\cdot\binom{4}{3}\cdot 5}{7^7} = \frac{302820}{7^7}.
$$


text:
Q: Using the value of a hidden field within a PHP recordset. I have a form :
<form method="POST">
<input name="imagekey" type="hidden" value="<?php echo $row_images['key']; ?>">
</form>

This returns an integer (the unique key for a recordset 'images'). I'm trying to create a second recordset that includes every value of 'images' with a greater key than the one specified in the hidden value.  ie if the hidden value is 5, then the second recordset will include everything with a key 6 and above.
I'm using Dreamweaver to create this, and the recordset code for this is:
SELECT *
FROM images
WHERE `key` > colname
ORDER BY `key` ASC

with colname being:
$colname_images2 = "-1";
if (isset($_POST['imagekey'])) {
  $colname_images2 = $_POST['imagekey'];

At the moment, I'm still getting the whole recordset including the hiddenvalue in my second recordset. Am I missing something obvious?
thanks

A: I think you can minus directly you POST value
if (isset($_POST['imagekey']))
{
    $colname_images2 = $_POST['imagekey'] - 1;
}

The way you did you were setting for variable $colname_images2 = "-1" and then you were overwriting it with $_POST['imagekey']
in other hands you can set directly in your form the desired second value
<form method="POST">
    <input name="imagekey" type="hidden" value="<?php echo $row_images['key']; ?>">
    <input name="imagekey2" type="hidden" value="<?php echo ($row_images['key'] - 1); ?>">
</form>

and now assign to a variable
$colname_images2 = $_POST['imagekey2'];


text:
Q: Advanced search : how to apply wildcardFilter for custom attribute I have added some custom product attribute to advance search if I search for lower case letter then all work, but when I search using capital letter then it does not give any result.
the same thing is working for SKU search, but not working for another attribute.
so I review the code at vendor/magento/module-catalog-search/etc/search_request.xml and found that
<filter xsi:type="wildcardFilter" name="sku_query_filter" field="sku" value="$sku$"/>

wildcardFilter is applied for the SKU attribute.
So my question is how we can apply the same for custom-created attributes and attribute type if textarea.


text:
Q: 3D Touch on Xcode 8 & Simulator 10 I've read a ton of threads debating if 3D touch is available on the latest Xcode 7 versions. The consensus was that it's possible but only with a 3D phone or trackpad. My question is if with the new Xcode and Simulator, has that changed?
I'm on a 2012 MacBook running Sierra:

I can see some force touch options:

But can I somehow enable those options so I can starting testing my 3D Touch code?

A: Make sure you also have a device that can support it lol. Had simulator set up to iPhone 5S/SE and didn't realize why it wasn't working (head slap)

A: Only a MacBook Pro or MacBook 12' after 2015 is shipped with a force-touch trackpad which you can use to simulate 3D touch in Xcode's simulator. You can check that with your mac in System Preferences->Trackpad->Point&Click.

A: To test 3D touch in the simulator, you would need a force-touch trackpad (i.e. a MacBook with a force-touch trackpad built in, or a Magic Trackpad 2). If you have one, those menu items come to life. If you don't have one, you can only test on a device!


text:
Q: How to set multiple audience in urban airship I am using php client to send notification request to urban airship.
For that I have referred below link.
https://support.urbanairship.com/entries/70144047-Simple-PHP-API-v3-examples
In that audience is set to
$push = array("audience"=>"all", "notification"=>$notification, "device_types"=>$platform);

I want to sent notification so selected iOS and Android devices.
For that I am creating an array for iOS and android each.
like this.
$iosDevices = array();
array_push($iosDevices, "Channel_id_for_iOS_device_1");
array_push($iosDevices, "Channel_id_for_iOS_device_2");
$main__channel['ios_channel'] = $iosDevices;
$push = array("audience"=>  $main__channel,"notification"=>$notification, "device_types"=>$platform);

This works fine, however when I try to add channel id array of android it doesn't allow me.
$androidDevices = array();
array_push($androidDevices, "Channel_id_for_android_device_1");
array_push($androidDevices, "Channel_id_for_android_device_2");
$main_channel['android_channel'] = $androidDevices;
$push = array("audience"=> $main__channel,"notification"=>$notification, "device_types"=>$platform);

I want to send notification to both iOS and android devices ids(selected one only).
And I want to pass those array to audience. Is there any way to do so?
Response

{"ok":false,"error":"Could not parse request
  body.","error_code":40210,"details":{"error":"Specified more than one
  type of selector ('android_channel' was
  unexpected)","path":"audience.android_channel[0]","location":{"line":1,"column":127}},"operation_id":"2b00a2a0-73cd-11e5-a4ba-90e2ba2901f0"}
  Got negative response from server: 40

A: Got the reply from urban airship support. below is the answer.
"audience": {
      "OR": [
         { "ios_channel": [
            "Channel_id_for_iOS_device_1",
            "Channel_id_for_iOS_device_1"
         ] },
         { "android_channel": [
            "Channel_id_for_android_device_1",
            "Channel_id_for_android_device_2",
            "Channel_id_for_android_device_3"
         ] }
      ]
   }

I tested it, It works fine for both iOS and android.


text:
Q: Update a slice in a struct passed to a function Need help in understanding how to update a slice that is contained in a struct and passed to a function.
Function addBookToShelfInLibrary(l *library, shelfid int, b book) - takes as input a library, tries to add to book to the shelf with the id = shelfid (passed as param). The function appends to the books array and also assigns it to books array. What am I missing?
At the end of code run, I expect the books to contain two books, "harrypotter", "bible" but I see only one, i.e. harrypotter. Also, I am passing a pointer to the library but I don't think that matters in this case.
playground code:- https://play.golang.org/p/JrjtLSj-jHI
func main() {
    lib := library{
        shelves: []shelf{
            {
                id: 1,
                books: []book{
                    {name: "harrypotter"},
                },
            },
        },
    }
    addBookToShelfInLibrary(&lib, 1, book{name: "bible"})
    fmt.Printf("%v", lib)

}

type library struct {
    shelves []shelf
}
type shelf struct {
    id    int
    books []book
}

type book struct {
    name string
}

func addBookToShelfInLibrary(l *library, shelfid int, b book) {
    for _, s := range (*l).shelves {
        if s.id == shelfid {
            //found shelf, add book
            s.books = append(s.books, b)
        }
    }
}

Thanks for your answer / explanation in advance.

A: In this statement:
s := range (*l).shelves

the variable s is a copy of the slice element.  The later call to append modifies this copy, the not slice element.  Change the code to modify the slice element:
func addBookToShelfInLibrary(l *library, shelfid int, b book) {
    for i := range l.shelves {
        s := &l.shelves[i]
        if s.id == shelfid {
            //found shelf, add book
            s.books = append(s.books, b)
        }
    }
}

Another approach is to use a pointer to a shelf:
type library struct {
    shelves []*shelf
}

lib := library{
    shelves: []*shelf{
        {
 ...

All other code remains the same. Run it on the playground.


text:
Q: Determine $\inf_{f \in C[0,1]} \int_0^1 t^2 \mathrm{Re}f(t)dt$ subject to certain constraints
Determine the value of $$\inf_{f \in C[0,1]} \int_0^1 t^2 \mathrm{Re}f(t)dt$$ subject to the conditions $\int_0^1f(t)dt = \int_0^1 tf(t)dt=0$ and $\int_0^1|f(t)|^2dt=1$.  Is the infimum attained?  If so, for which $f\in C[0,1]$?

Here, $C[0,1]$ is the set of complex-valued continuous functions on $[0,1]$.
I realize that the integrals in the question can be written in terms of the inner product $$\langle f,g \rangle = \int_0^1f(t)\overline{g(t)}dt.$$  If we do this, then the conditions say that $f$ is normalized and is orthogonal to the constant function at $1$ and the identity function.  I have tried to write the inner product in the infimum in terms of the ones where the value is given but failed.  I have also tried creating some some sort of orthonormal system, maybe using the Gram-Schmidt orthonormalization process, and somehow using the properties of an orthonormal system to evaluate the infimum, but have also not succeeded.


text:
Q: Accessing List Of Class Objects I am still a beginner when it comes to programming, and am wondering what is wrong with my program (A* Pathfinder Algorithm GUI). I have been trying to debug for several days now, and it keeps giving me the "calculateSurroundingHeuristic() error" when I am trying to print gridRowList[0][0]. My program takes 4 inputs through the GUI: start and end x & y values. GridRowList is just a list which I have created by appending 50 rows of 50 pixels inside each row.
The following are my global variables and the Pixel Class
#Define global variables
x1_int = 0
y1_int = 0
x2_int = 0
y2_int = 0
startPixel = None
endPixel = None
gridList = 0
gridRowList = 0

class Pixel:
    def __init__(self, x, y, heuristic):
        self.x = x
        self.y = y
        self.heuristic = heuristic

    def __str__(self):
        return str(self.getCoordinate() + "H = " + str(self.getHeuristic()))

    def __repr__(self):
        return str(self)

    def getCoordinate(self):
        return (str(self.x) + ", " + str(self.y))

    def getx(self):
        return self.x

    def gety(self):
        return self.y

    def getHeuristic(self):
        return int(self.heuristic)

    def get(self):
        return self

    def updateHeuristic(self, new_heuristic):
        self.heuristic = new_heuristic

    def calculatePixelHeuristic(self, x2_int, y2_int):

        local_x = int(self.getx())
        local_y = int(self.gety())

        local_x_differential = int(abs(local_x - x2_int))

        print(local_x_differential)

        local_y_differential = int(abs(local_y - y2_int))

        print(local_y_differential)

        local_heuristic = int(math.sqrt((local_x_differential ** 2) + (local_y_differential ** 2)))

        return local_heuristic

def calculateSurroundingHeuristic(x1_int, y1_int, x2_int, y2_int):

    rowNumber = int(y1_int)
    columnNumber = int(x1_int)
    listofMoves = []

    try:
        #R-1, C-1
        newRow = int(rowNumber) - 1
        newColumn = int(columnNumber) - 1

        #TEST
        global gridRowlist
        print(gridRowlist[0][0])
        print(gridRowList[newRow][newColumn])

        #find a way here to access a pixel based on coordinates in the gridRowlist and modify its heuristic
        #gridRowList[rowNumber]

    except:
        #TEST
        print("calculateSurroundingHeuristic() error")
        pass

After this, they are appended to a list called rowList, and are appended in 50 rows of 50 pixels. This is what happens after:
Append items to gridRowList & populate GUI grid
    tempString = "r"
for i in range(1, 51):
    tempString = tempString + str(i)
    gridRowList.append(eval(tempString))
    tempString = "r"


text:
Q: How to run Node controlled Phantomjs/Casperjs script in Heroku I've written a Casperjs script to do some scraping, however, after running into memory exhaustion issues, I've now written a node script to turn Phantom off and on via exec. I can run this with no issues locally, however when I deploy to heroku I get the following error
Error: Command failed: casperjs turnitoffandon.js
ERROR: stderr was:/bin/sh 1: casperjs: not found

I used the nodejs buildpack and have Phantom and Casper defined in my dependencies. In the heroku bash, running phantomjs --version returns 2.1.1 and casperjs --version returns 1.1.4.
Do I need to define where Casper is? If so how? I have set my PATH variable as /usr/local/bin:/usr/bin:/bin:/app/vendor/phantomjs/bin:/app/vendor/casperjs/bin:/node_module/casperjs/bin , like in this SO question

A: The issue actually had nothing to do with Heroku. As noted in this SO answer, using exec and providing any environmental variables in the options parameter replaces the entire set of environment variables. This includes the path, effectively overwriting any paths already specified to Heroku in the buildpack and npm modules.
You can create a copy of process.env and pass that along in the parameters in addition to other environmental parameters needed to be passed.


text:
Q: How to check to see if a wordpress shortcode $atts is equal to something I am trying to figure out how to figure out how to check to see if a shortcode attribute is equal something and than if it is set a variable.
I have an image shortcode with an attribute of float and I want to set a class to float right if the user enters in float="right" as an attribute but if not than do nothing.
add_shortcode( 'img', 'img_shortcode' );
function img_shortcode( $atts, $content = null ) {
$atts = shortcode_atts(
array(
    'float' =>'',
), $atts);

$ImgFloat = '';

if(float attribute = right){
        $ImgFloat = 'class="img-right"';
    }

return '
<div class="img-shortcode">
    <img '. $ImgFloat .' src="'. $content .'" />
</div>
';
}

Above is the shortcode, as you can see the If statement is where I'm having the trouble, I would like to figure out how to check to see if the attribute float is set to anything if it is set to right, than make $imgFloat variable equal to the float right class that I have set.

A: Change this:
if(float attribute = right){
        $ImgFloat = 'class="img-right"';
}

To this:
if ( 'right' == $atts['float'] ) {
    $ImgFloat = 'class="img-right"';
}

OK so I may have complicated the answer by flipping the conditional around but it's a good habit to get into :)
The important part is we're saying if $atts['float'], which is the value of float="" in the shortcode, is equal to right then add the class.
shortcode_atts(... at the top of the function is where $atts['float'] is given a default value. If the user doesn't enter float=".. then the value is a blank string.

A: shortcode_atts returns an array combining the parameters passed in with the defaults you specify.  So the float attribute will be stored in $atts['float']