text:
Q: Integral of $te^{-i\omega t}$ and Fubini's Theorem I have a question about the value of the integral
$\int_0^\infty t e^{-i \omega t} dt$. I stumbled upon it while trying to compute the Fourier transform of $|t|$.
On one hand, we have that $|t e^{-i \omega t}|$ doesn't go to 0 as $t \to \infty$. This implies that the integral diverges.
On the other hand, using the trick of $\int_0^\infty e^{-xt} dx = 1$ for all $t$, we can write
\begin{eqnarray*}
\int_0^\infty t e^{-i \omega t} \times 1 dt & = &
\int_0^\infty t e^{-i \omega t} \times \int_0^\infty e^{-xt} dx dt \\
& \substack{= \\ (1)}& \int_0^\infty \int_0^\infty t e^{-i \omega t}  e^{-xt} dt dx \\
& = &
\int_0^\infty \int_0^\infty \dfrac{e^{-t(i \omega +x)}}{i\omega + x} dt dx \\
& = & \int_0^\infty \dfrac{1}{(i\omega + x)^2} dx = \dfrac{1}{i \omega}
\end{eqnarray*}
where in $(1)$, we use Fubini's Theorem.
One of these two statements must be wrong, but which one ?
Thanks for your help.
Best, Olivier

A: Here is a graph for
$$
{\rm Re} \left( \int _{0}^{S}\!t{{\rm e}^{it}}{dt} \right)
$$
for $S$ from $0$ to $50$.  (So take $\omega=-1$.) Does it look like it converges as $S \to \infty$?

Of course Fubini would only be applicable for a function with $\int_0^\infty \int_0^\infty |f(t,x)|dtdx < \infty$.


text:
Q: Writing Personalized Error Messages in Python I'm a user of R, but have to learn Python for a school project. Now, in R, I frequently use the base function stop in my code, and I'd like to know how to emulate this functionality in Python. For a concrete example, take this R code:
add.two <- function(t) {
     if (!is.numeric(t)) stop('Please make t numeric.')
     t + 2
}

This function does three things, (i) it adds two to (e.g.) a numeric vector, (ii) if it is passed a non-numeric argument it returns a personal, concise, and easy to understand error message, and (iii) it ceases the function from running any further in the case that t is non-numeric.
My first attempt for how to do this in Python is
def add_two(t):
    if not ( isinstance(t, int) or isinstance(t, float) ):
        print('Error: Please make t numeric.')
    else:
        print(t+2)

However, this only does things (i) and (ii). In other words, if the body of this function were longer (although, in this example, it is not), Python would not know to stop running. Another option is
def add_two(t):
    if not ( isinstance(t, int) or isinstance(t, float) ):
        print('Error: Please make t numeric.')
        raise
    else:
        print(t+2)

Which, I suppose, does things (i) and (iii), but the error message is at best cluttered and confusing, and at worst incorrect and misleading.
Does someone know of a way to achieve all three goals in Python? Thank you for your time.
Edit: IDK why, I said 'error' instead of 'stop' just a brain fart.

A: Use the raise keyword while creating an Exception object. You can customize the message with an argument:
def add_two(t):
    if not (isinstance(t, int) or isinstance(t, float)):
        raise ValueError('t must be numeric')
    else:
        print(t + 2)

Like most programming languages, there are different types of exceptions to represent different types of faults. The list of those is here, and you can of course make custom Exception subclasses if you want your own custom exception types.

In your case, though, this isn't so much necessary. If you do
def add_two(t):
    print(t + 2)

then an error will be thrown anyway if t is of a type that you can't add an integer to (e.g. a string - a TypeError will be raised). Python typically advocates doing this when possible: "ask forgiveness rather than permission".

A: One option is using:
raise ValueError('your error message here')

This will throw an error with the custom message you want.

redpajama_set_name: RedPajamaStackExchange


text:
Q: alternate background-colors between Div Labels I have a table like structure made out of divs.
I want to alternate the background-color of only the divLabels.
Each divrow of a table has a divlabel and a divdata element.
this is what I have tried so far:-
http://jsfiddle.net/o5dv4qkc/
unfortunately, the color of the labels do not alternate, instead show the same color mentioned for the odd rows only:-
.About_RowLabel:nth-of-type(odd) {
    background-color: #DEF3CA;
}

Can anyone tell me why this does not work with my div elements?

A: You're not selecting properly the children: move up by one level to their parents, and start from there, like .someParentClass:nth-of-type(even) .child{}: demo

.About_Row {
  height: 2em;
  width: 500px;
  /*float:left;*/
}
.About_RowLabel {
  width: 98px;
  color: black;
  float: left;
  background-color: #71cd7b;
}
.About_RowData {
  width: 200px;
  float: left;
  margin-left: 20px;
}
.About_Row:nth-of-type(odd) .About_RowLabel {
  background-color: #DEF3CA;
}
.serv_resize {
  border: 1px solid #E2E2E2;
  color: #444;
  width: 425px;
  float: left;
  margin: 10px 10px 10px 0;
  padding: 5px;
  height: 239px;
}

      BirthDate:

      <asp:Label ID="lblDoB" runat="server" Text="DoB"></asp:Label>

      As of:

      <asp:Label ID="lblAsOf" runat="server" Text="Dt"></asp:Label>

      Phone:

      <asp:Label ID="lblPhone" runat="server" Text="Ph"></asp:Label>

A: all the nth- pseudo selectors work with sibling elements. That is, elements that share the same immediate parent.
All your .About_RowLabel are the first in their parent (the .About_Row element) so they are all odd.
Target the alternating parents
.About_Row:nth-of-type(odd) .About_RowLabel {
    background-color: #DEF3CA;
}

Demo at http://jsfiddle.net/o5dv4qkc/4/


text:
Q: Submit java.util.Map from Jsp to Struts 1 Action class I am using Struts 1,
I want to submit data from my JSP page to Struts 1 Action Class using,
Field in FormBean is something like below
Map<String, Map<String,List<Object>>> data = new HashMap<String, Map<String,List<Object>>>();

Does any one know how to achieve this?

A: In order to keep the talk short, I'm giving a solution for a Map<String,List<MyBean>>. With little effort, one can extend the following to be the answer to the question:
Struts 1.x requires you to create all objects in ActionForm.reset() before it populates primitive values. If your form has an object with children, those children must be assigned proper values, i.e. if you have
<html:text property="parent.child" /> then you must do parent.setChild(new Child()) in your reset().
Similarly, if you have a list-based form element, then every referenced index of the form element have to be initialised, i.e. <html:text property="myBeanList[12].beanMember"/> requires something equivalent to myBeanList.add(12, new MyBean()) in the reset() method. Maps also have a similar requirement; <html:text property="myBeanMap('key').beanMember"/> requires myBeanMap.put('key',new MyBean()).
With the help of some extra hidden form fields or -better- a parser to detect indexes that are needed, you can detect the index positions at which you have to create new objects.
If we go the easy way and send required index information with HTTP GET/POST parameters, we map keys reside in mapKeys, e.g.
<input type="hidden" name="mapKeys" value="key1,key2,key3"/>

and the lengths of lists at each key position reside in variables like key1_length:
<input type="hidden" name="key1_length" value="10"/>

In this case, the reset() method would be something like this:
public void reset(ActionMapping mapping, HttpServletRequest request) {
   this.data = new HashMap<String,List<MyBean>>();
   String requiredKeys=request.getParameter("mapKeys");
   for (String key: requiredKeys.split(",")) {
     List<MyBean> lst = new ArrayList<MyBean>();
     int listLength = Integer.parseInt(request.getParameter(key+"_length"));
     for (int i = 0; i < listLength; i++)
        lst.add(new MyBean());
     this.data.put(key, lst);
   }

}
so that it can get
<html:text property="data('key1')[3].beanMember"/>

when the form is populated. In case the index information is not consistent with the other form elements, you might run into exceptions regarding BeanUtils.setProperty().
Btw, all I told is ok to get data from an HTML form which is not multipart/form-data, so no lists and file uploads together.


text:
Q: iOS-Obj C How to change a object view maintaining constraints I'm using Autolayout and Size classes for my project.
Now, I've to transform a UIImageView into View. But is there a way to do it without losing all previous constraints for UIImageView?


text:
Q: Use bitwise AND on an int in C++ My question is simple: how do I perform a bitwise AND on an int in C++?
#include <iostream>

int main() {
    unsigned int foo = 3;
    unsigned int bar = 6;
    std::cout << foo & bar;
    return 0;
}

Instead of outputting 2, it prints 3.
When I do any other bitwise operation, it also just prints the first variable.
How do I get it to do the operation?

A: You need to add parentheses around your foo & bar because the & operator has a lower precedence than the shift << operator.
std::cout << (foo & bar);

As a side note, I am surprised that the code compiles without the parentheses. Bonus: the doc for operator precedence rules on cppreference


text:
Q: Pass TextInput value to imported component i am developing the mobile app in react native. i am new to react native so i am stuck at 1 point.
The issue is i have navigation file in which stack navigator wrapped in tab navigator.
i have a custom header with the drawer menu open button and search bar.
i have a separate component for search view. which is showing and hiding on my home page on the base of focusing on search bar.
Now the question in that on my home page when i click search bar the search component showing there, and what i need is to get the value of that search bar in my search component.
May be its little bit confusing please feel free to ask me anything.
i am going to attack images and my code as well.

my navigation js looks like this.

import Search from '../Search/search';

StackNavigator

const SearchBarI = (props) => {
return (
    (<View style={searchSection}>
        <TextInput style={searchBarInput} placeholder="Search" ref={input => { this.searchInput = input }}
            onChangeText={(text) => this.onChangeText(text)} />
        <Icon style={searchIcon} name="ios-search" size={20} color="#000" />
        <TouchableOpacity style={closeIconBtn} onPress={() => ClearText()}>
            <Icon style={closeIcon} name="ios-close" size={20} color="#000" />
        </TouchableOpacity>

    </View>)
)
}
const feedStackNavigation = createStackNavigator({
feed: {
    screen: Feed,
    navigationOptions: ({ navigation }) => {
        const { params = {} } = navigation.state;
        return {

            headerTitle: <SearchBarI/>,
            headerStyle: headerStyle,
            headerRight: (
                <TouchableOpacity style={{ paddingRight: 10 }} onPress={(params.ClearSearch)}>
                    <Text style={{ color: '#fff' }}>Cancel</Text>
                </TouchableOpacity>
            ),

            headerLeft: <HeaderLeft navigation={navigation} />,

        }
    }
},
})

And include in tab navigator and export it.

const appTabNavigation = createBottomTabNavigator({
Feed: feedStackNavigation,
})

export default appTabNavigation;

what i need when onChangeText in my search bar i want to pass that value in my search component and need to change the state and other functionality there.

Home Page Screenshot.

After clicking on the search bar screenshot.

after typing in search bar i got an alert which is the function inside
  the navigation file.

Hope it will give you the clear look.
Thanks in advance.

A: I don't know if it would work but i used some approach for this before, i needed intercommunication between 2 components in the same page and it was a nightmare. Now i don't use the header of react navigation because i have a custom header 7u7. But, you can try this.
First. Don't define  headerTitle in the navigationOptions of the stack. Instead, define it in the screen Feed.
So per example, in your screen feed you need to add  a static navigationoptions, and also send a callback as a prop to the headertitle
export default class App extends React.Component {
  constructor() {....}

  static navigationOptions = { //here is the navoptions
  headerTitle: <SearchBarI callback={this.handlecallback}/>  //here is the callback that we are sending
  };

  handlecallback =(props)=>{ //here is the handler , it NEEDS to be a fat arrow function [that's how mafia works]
      alert(props)
       //do whatever you want in that page
  }

  render() {
    return (

      <View>
      </View>

    );
  }
}

and in your searchbar textinput
<TextInput style={searchBarInput} placeholder="Search" ref={input => { this.searchInput = input }}
            onChangeText={(text) => props.callback(text)} />


text:
Q: Android Volley Multidimensional JSON Request post Method How to send multidimensional array on volley post method.
    {
  "code": "001",
    "Emp_id": "0000",
    "Exp_Dt": "2021-05-27T00:00:00.000",
    "users": [
        {
                "id": "1087",
                "name": "Abhishek Saini",
                "email": "info@ezacake.com",
                "gender" : "male"
        },
        {
                "id": "1088",
                "name": "Gourav",
                "email": "gourav9188@gmail.com",
                "gender" : "male"

        }
  ]
}

This format I want to call API. Please help
Note - I want to Request with array on my API, not a response

A: hi you are trying to send a json object there =>
create a parent json object
JSONObject reqJO = new JSONObject();

put other properties eg
reqJo.put("code",0001);

create a user json object
JSONObject user = new JSONObject();

put user properties(if more users loop creating new users)eg
user.put("id",1087)

create a json array of users
JSONArray users = new JSONArray();

add user in users array
users.put(user);

put users array in parent object
reqJO.put("users",users);

Then you continue  with your JsonObjectRequest

A: Here is the  answer
RequestQueue queue = Volley.newRequestQueue(this);
JsonObjectRequest jobReq = new JsonObjectRequest(Request.Method.POST, url, jObject,
        new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {

            }
        },
        new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });

queue.add(jobReq);


text:
Q: Converge? $\sum_{k=1}^{\infty}\frac{ \sin \left(\frac{1}{k}\right) }{k} $ Determine whether the series converges:
$$\sum_{k=1}^{\infty}\frac{ \sin \left(\frac{1}{k}\right) }{k} $$
I tired to use direct comparison test but since 1/k is not convergent, so I am not sure about in this case.

A: Hint
Since you want a direct comparison use this inequality
$$\sin(x)\le x,\; \forall x\ge0$$

A: It converges absolutely: $\left|\sin\left(\dfrac{1}{k}\right)\right| < \dfrac{1}{k}$

A: It converges since it has positive terms and:
$$ \sin\dfrac1k \sim_{\infty}\frac1k,\enspace\text{hence}\enspace\frac{ \sin\frac1k }{k}\sim_{\infty}\frac1{k^2}.$$


text:
Q: Confusion about the inputs array of useEffect(React Hooks API) Some React Hooks API like useEffect, useMemo, useCallback have a second parameter: an array of inputs:
useEffect(didUpdate, inputs);

As the official document said:
@see Conditionally firing an effect

*

*
That way an effect is always recreated if one of its inputs changes.

*
every value referenced inside the effect function should also appear in the inputs array.

So we can see, the inputs array takes two responsibilities.
In most situations, they are working properly. But sometimes they conflict.
For example, I have a little counting program, it does two things:

*

*Click button and the count plus 1.

*Send the count to server every 5 seconds.
Codesandbox:
https://codesandbox.io/s/k0m1mq9v
Or see the code here:
import { useState, useEffect, useCallback } from 'react';

function xhr(count) {
  console.log(`Sending "${count}" to my server.`);
  // TODO send count to my server by XMLHttpRequest
}

function add1(n) {
  return n + 1;
}

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  // Handle click to increase count by 1
  const handleClick = useCallback(
    () => setCount(add1),
    [],
  );

  // Send count to server every 5 seconds
  useEffect(() => {
    const intervalId = setInterval(() => xhr(count), 5000);
    return () => clearInterval(intervalId);
  }, []);

  return (

You clicked {count} times

      <button onClick={handleClick}>
        Click me
      </button>

  );
}

export default Example;

When I run this code, I'll always send count = 0 to my server, because I haven't passed the count to useEffect.
But if I pass count to useEffect, my setInterval will be cleared and the whole callback will be recreated each time when I click the button.
I think maybe there's another paradigm to achieve my goal which I haven't think of. If not, that is a conflict of the inputs array.

A: Reply from React:
React discussion Github
A better solution may be implemented, but not now.
But life will continue, so a workaround pattern like this may help:
const [count, setCount] = useState(0);
const countRef = useRef(count);
useEffect(() => {
  countRef.current = count
}, [count]);

A: useRef() can solve your problem. I think this is an elegant solution: code in sandbox
function App() {
  const [count, setCount] = useState(0);

  // ***** Initialize countRef.current with count
  const countRef = useRef(count);

  const handleClick = useCallback(() => setCount(add1), []);

  // ***** Set countRef.current to current count
  // after comment https://github.com/facebook/react/issues/14543#issuecomment-452996829
  useEffect(() => (countRef.current = count));

  useEffect(() => {
    // ***** countRef.current is xhr function argument
    const intervalId = setInterval(() => xhr(countRef.current), 5000);
    return () => clearInterval(intervalId);
  }, []);

  return (

You clicked {count} times

      <button onClick={handleClick}>Click me</button>

  );
}

EDIT
After comment: https://github.com/facebook/react/issues/14543#issuecomment-452996829


text:
Q: When importing elements from Selenium writes to multiple lines on CSV instead of one I can pull the code and it writes to the CSV but when imported to excel only the first line of the html shows in the excel file. It does work properly in Google Sheets. I am sure an imported line break is in there but I do not know how to strip it before writing to CSV. Thanks for any and all help.
My code.
def grabAddress():
    element = browser.find_elements(By.XPATH, '//*[@id="memberDetail"]/section/div/div[1]/div[3]/p[2]/strong')

    strings = []
    for x in element:
        strings.append(x.text)
    splitstrings = "".join(strings)
    address.append(splitstrings)
    return 0

with open(r"C:\bnicsv\compiled.csv", "w", newline ="") as compiledCSV:
    writecompiledtoCSV = csv.writer(compiledCSV, delimiter=",")
    writecompiledtoCSV.writerows(compiled_list)

HTML I am pulling...

        Jack Jackson

        Jacks Jewelers

        1985 East End Blvd.

        St. Paul Park, MN 55555


text:
Q: How to parse table of numbers in C++ I need to parse a table of numbers formatted as ascii text.  There are 36 space delimited signed integers per line of text and about 3000 lines in the file.  The input file is generated by me in Matlab so I could modify the format.  On the other hand, I also want to be able to parse the same file in VHDL and so ascii text is about the only format possible.
So far, I have a little program like this that can loop through all the lines of the input file.  I just haven't found a way to get individual numbers out of the line. I am not a C++ purest. I would consider fscanf() but 36 numbers is a bit much for that. Please suggest practical ways to get numbers out of a text file.
int main()
{
    string line;
    ifstream myfile("CorrOut.dat");
    if (!myfile.is_open())
        cout << "Unable to open file";
    else{
        while (getline(myfile, line))
        {
            cout << line << '\n';
        }
        myfile.close();
    }
    return 0;
}

A: Use std::istringstream.  Here is an example:
#include <sstream>
#include <string>
#include <fstream>
#include <iostream>

using namespace std;

int main()
{
    string line;
    istringstream strm;
    int num;
    ifstream ifs("YourData");
    while (getline(ifs, line))
    {
        istringstream strm(line);
        while ( strm >> num )
           cout << num << " ";
        cout << "\n";
    }
}

Live Example
If you want to create a table, use a std::vector or other suitable container:
#include <sstream>
#include <string>
#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    string line;

    // our 2 dimensional table
    vector<vector<int>> table;

    istringstream strm;
    int num;
    ifstream ifs("YourData");
    while (getline(ifs, line))
    {
        vector<int> vInt;
        istringstream strm(line);
        while ( strm >> num )
           vInt.push_back(num);
        table.push_back(vInt);
    }
}

The table vector gets populated, row by row.  Note we created an intermediate vector to store each row, and then that row gets added to the table.
Live Example

A: You can use a few different approaches, the one offered above is probable the quickest of them, however in case you have different delimitation characters you may consider one of the following solutions:
The first solution, read strings line by line. After that it use the find function in order to find the first position o the specific delimiter. It then removes the number read and continues till the delimiter is not found anymore.
You can customize the delimiter by modifying the delimiter variable value.
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    string line;
    ifstream myfile("CorrOut.dat");
    string delimiter = " ";
    size_t pos = 0;
    string token;

    vector<vector<int>> data;

    if (!myfile.is_open())
        cout << "Unable to open file";
    else {
        while (getline(myfile, line))
        {
            vector<int> temp;
            pos = 0;
            while ((pos = line.find(delimiter)) != std::string::npos) {
                token = line.substr(0, pos);
                std::cout << token << std::endl;
                line.erase(0, pos + delimiter.length());
                temp.push_back(atoi(token.c_str()));
            }
            data.push_back(temp);
        }
        myfile.close();
    }
    return 0;
}

The second solution make use of regex and it doesn't care about the delimiter use, it will search and match any integers found in the string.
#include <iostream>
#include <string>
#include <regex> // The new library introduced in C++ 11
#include <fstream>

using namespace std;

int main()
{
    string line;
    ifstream myfile("CorrOut.dat");
    std::smatch m;
    std::regex e("[-+]?\\d+");

    vector<vector<int>> data;

    if (!myfile.is_open())
        cout << "Unable to open file";
    else {
        while (getline(myfile, line))
        {
            vector<int> temp;
            while (regex_search(line, m, e)) {
                for (auto x : m) {
                    std::cout << x.str() << " ";
                    temp.push_back(atoi(x.str().c_str()));
                }
                std::cout << std::endl;

                line = m.suffix().str();
            }

            data.push_back(temp);
        }
        myfile.close();
    }
    return 0;
}


text:
Q: Removing a Shape from a Layout How To Remove A shape example quadrant from the corner of a drawable, I found many examples for a circular corner, but none where i could remove the radius of a corner of a layout.
Like This:

Is there a way to accomplish this just by using the drawable.
This is the code for the rounded corners which is not on the same lines as what I need-:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFFFFF"/>
    <stroke android:width="3dp" android:color="#B1BCBE" />
    <corners android:radius="10dp"/>
    <padding android:left="0dp" android:top="0dp" android:right="0dp"
        android:bottom="0dp" />
</shape>

A: background.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:width="100dp"
        android:height="75dp">
        <shape android:shape="rectangle">
            <solid android:color="#95FFEE" />
            <stroke
            android:width="2dp"
            android:color="#C0BFBF" />
        </shape>
    </item>

    <item
        android:width="24dp"
        android:height="24dp">
        <shape android:shape="rectangle">
            <solid android:color="#FFFF" />
            <corners
                android:bottomRightRadius="24dp"/>
        </shape>
    </item>

    <item
        android:width="26dp"
        android:height="26dp">
        <shape android:shape="rectangle">
            <solid android:color="#C0BFBF" />
            <corners
                android:bottomRightRadius="26dp"/>
        </shape>
    </item>

    <item
        android:width="24dp"
        android:height="24dp">
        <shape android:shape="rectangle">
            <solid android:color="#FFFF" />
            <corners
                android:bottomRightRadius="24dp"/>
        </shape>
    </item>

    <item
        android:width="26dp"
        android:height="26dp"
        android:gravity="end">
        <shape android:shape="rectangle">
            <solid android:color="#C0BFBF" />
            <corners
                android:bottomLeftRadius="26dp"/>
        </shape>
    </item>

    <item
        android:width="24dp"
        android:height="24dp"
        android:gravity="end">
        <shape android:shape="rectangle">
            <solid android:color="#FFFF" />
            <corners
                android:bottomLeftRadius="24dp"/>
        </shape>
    </item>

    <item
        android:width="26dp"
        android:height="26dp"
        android:gravity="end|bottom">
        <shape android:shape="rectangle">
            <solid android:color="#C0BFBF" />
            <corners
                android:topLeftRadius="26dp"/>
        </shape>
    </item>

    <item
        android:width="24dp"
        android:height="24dp"
        android:gravity="end|bottom">
        <shape android:shape="rectangle">
            <solid android:color="#FFFF" />
            <corners
                android:topLeftRadius="24dp"/>
        </shape>
    </item>

    <item
        android:width="26dp"
        android:height="26dp"
        android:gravity="start|bottom">
        <shape android:shape="rectangle">
            <solid android:color="#C0BFBF" />
            <corners
                android:topRightRadius="26dp"/>
        </shape>
    </item>

    <item
        android:width="24dp"
        android:height="24dp"
        android:gravity="start|bottom">
        <shape android:shape="rectangle">
            <solid android:color="#FFFF" />
            <corners
                android:topRightRadius="24dp"/>
        </shape>
    </item>

</layer-list>


text:
Q: Jetpack Compose - How to search and display specific data from room in LazyColumn? I want to fetch data from room table using a search query and present the result in LazyColumn instead of the someList I present there.
In other words, how to implement search function using compose from room table?
//Getting the list from room and presenting it in lazy column

val someList by mainViewModel.getSomeItems.collectAsState(initial = emptyList())

LazyColumn(
 verticalArrangement = Arrangement.spacedBy(8.dp),
  modifier = Modifier
   .fillMaxSize()
    .padding(16.dp)
                        ) {

itemsIndexed(items = someList) { itemIndex, item ->

//not really important to the question
item.currentInventory?.let {

MainScreenItemRow(
itemId = item.id,
itemNumber = item.itemNumber,
itemDescription = item.itemDescription,
currentInventory = it,
)
             }
         }
     }
} // end of lazy

I want to use DAO query and present the result list if query matches to one of the items in "someList".
@Query("SELECT * from someList WHERE id LIKE :search OR itemNumber LIKE :search OR itemDescription LIKE :search")
    fun searchInventory (search: String): Flow<List<SomeList>>

How can I insert the query results into a list and present it in lazy column?

A: Leaving my updated code for people who might need it. Didn't use DAO or anything like that, just filtering the main list with some adjustments:
SearchView:

@Composable
fun SearchView(
    modifier: Modifier = Modifier,
    state: MutableState<TextFieldValue>,
    placeHolder: String
    ) {

    TextField(
        value = state.value,
        onValueChange = { value ->
            state.value = value
        )

}

Main Screen that presents final list
val textState = remember { mutableStateOf(TextFieldValue("")) }

//Place the composable SearchView wherever is needed

SearchView(state = textState, placeHolder = "")

val searchedText = textState.value.text

LazyColumn showing main list and if something entered in searchedText,
the list updates only with the searched items.
*Changed from itemsIndexed to items with key as item.id because after the list was updated according to the search, the index was reset so couldn't control my items in the same way.
LazyColumn() {

             items(items = inventoryList.filter {
             it.itemNumber.contains(searchedText, ignoreCase = true) ||
             it.itemDescription.contains(searchedText, ignoreCase = true)
    }, key = {it.id}) { item ->

                                    MainScreenItemRow(
                                        itemNumber = item.itemNumber,
                                        itemDescription = item.itemDescription,

                                    )
                                }
                            }
                        }


text:
Q: Setting an array element with a sequence python import math
import pylab
from matplotlib.pylab import *
import numpy as np
import scipy.fftpack
from scipy.io.wavfile import read
w = read('c:/users/ggg.wav')
a=np.array(w[1])
l=len(a)
#from __future__ import division
#b=(l/w[0])
b=(float(l)/w[0])
c=b*1000
d=int(c/40)
print d
print l/d
e=l/d
for i in range(0,d):
    k[9]=np.array(a[(i*e)+1:((i+1)*e)])
print k

this is a python code to frame an audio signal. But when i executed this code,i got an error "ValueError: setting an array element with a sequence.". How can i avoid this error?

A: There is another problem with your code I can at least help you with:
You can't assign k[9] without k being undefined. E.g:
>>> k[9] = 'test'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'k' is not defined

'k' needs to be defined as an array and needs to get the 'proper' index. You can't assign the index on it straight after.
See the following examples:
>>> k[9]='test'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range

and
>>> k = [None]*10
>>> k[9]='test'
>>> k
[None, None, None, None, None, None, None, None, None, 'test']

A: This works fine with a sample .wav
w = read('ggg.wav')
a = w[1]  # already an array
l=len(a)
b=(float(l)/w[0])
c=b*1000
d=int(c/40)
e=l/d
k = a[:e*d].reshape(d,e)
print k.shape
print k
print ''
k = [[] for i in range(d)]  # initialize python list
for i in range(0,d):
    k[i] = a[(i*e)+1:((i+1)*e)]
for i in k:
    print i
# or
k = np.zeros((d,e-1),dtype='int') # initialize np.array
for i in range(d):
    k[i,:] = a[(i*e)+1:((i+1)*e)]
print k

w[1] is already an np.array.  I think what you want to break a into blocks e long.  To do that, I truncated a and reshaped it, producing my k.  Your indexing misses a[0], a[e], etc.


text:
Q: Implying the idiom "just shy of (something)" with hyphenation Since, I am constantly redirected to this site for my many, many questions and I am an aspiring author, I shall make my first post a query.
When using the idiom "just shy of (something)" would it be incorrect to simplify or imply the idiom with hyphenation?  And if so, why?
(The rest was just shy of an hour and revitalized him.)
vs.
(The hour-shy rest revitalized him.)
Thank you for your wisdom and time.
~e

A: 'Just shy of an hour' is the correct expression, as in just short of an hour, just before.
Hour-shy I've never seen used before and (but I have no proper arguments or references) sounds like 'work-shy', where shy indicates a dislike for something.
In terms of aesthetics, hour-shy reads 'ugly', feels like a hasty contraction that's not fully linguistically correct.


text:
Q: how to use cloud functions to save user's displayName when creating account in firebase Question: When a user account is created, how to use cloud functions to save his displayName to realtime DB in firebase
The scenario steps:

*

*I have a signup page containing email, password, displayName fields,
to allow users to create new account in firebase

*Above page will 1) trigger createUserWithEmailAndPassword to create
the user account, 2) save displayName value to userProfile in Auth DB.

*In Cloud function,  the code below is used so new user's email can
be saved to DB users node.

    exports.createProfile = functions.auth.user().onCreate(event =>
    return admin.database().ref(`/users/${event.data.uid}`).update
    ({email: event.data.email})

*I wish to save displayName to users node with above code, but it seems not possible because it is not in the context of event in onCreate.

What shall I do? It becomes nasty if I need to use both client and cloud function to update users node.
Best regards,
D

A: You need to use firebase.User.updateProfile() method to update the displayName once the firebase.auth().createUserWithEmailAndPassword(email, password) method completes. Like this -
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function (error) {

}).then(function (user) {
        user.updateProfile({
            displayName: "Jane Q. User",//pass displayName from your signup form here
            photoURL: "<image-url>"//you can pass this empty
        }).then(function () {
            //redirect to your post-registration page
        });
})

A: The documentation for auth events suggests the displayName is accessible via event.data.displayName.  If you are seeing any other behavior, it's a bug or you might be doing something wrong that you're not mentioning here.


text:
Q: Program loops when invalid character is entered I'm planning to output an error statement when a character was entered in the obj.nextInt();.
But whenever i entered an invalid character type, it's looks rather than go to the catch.
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

import Methods.FileSys;

class Main {
    public static void main(String args[]) throws FileNotFoundException, IOException {
        Scanner obj = new Scanner(System.in);
        FileSys fileSys = new FileSys();

    while (true){
        System.out.println("\nMain Menu");
        System.out.println("[1] Create");
        System.out.println("[2] Read");
        System.out.println("[3] Update");
        System.out.println("[4] Delete");
        System.out.println("[5] Search");
        System.out.println("[6] Exit");
    try {
        System.out.print("\nWhat do you want to do? ");
        int decision = obj.nextInt();
        obj.nextLine();

        switch(decision){
            case 1:
                fileSys.createNote();
            break;

            case 2:
                fileSys.displayNote();
            break;

            case 3:
                fileSys.updateNote();
            break;

            case 4:
                fileSys.deleteNote();
            break;

            case 5:
                fileSys.searchNote();
            break;

            case 6:
                System.exit(0);
            break;

            default:
                System.out.print("Invalid input!\n");
            break;
        }
    }
    catch (InputMismatchException e) {
    }
}
}
}

It should output an error message then go back to the main menu rather rather looping non stop


text:
Q: In wpf ,I need to use a flag to decide to use default contextmenu or my customized contextmenu In my project ,I use wpf to create a UI. For the textboxes on the UI, I want to customize their context menus. however A new requirement asks me to switch context menu more flexibility , I need to use a flag in my view modelto decide to use default context menu or customized context menu. My original code is like below
<TextBox>
    <TextBox.ContextMenu>
        <ContextMenu
          ItemsSource="{Binding MenuItems}"
          ItemContainerStyle="{StaticResource itemStyle}"/>
    </TextBox.ContextMenu>
</TextBox>

MenuItems is thedata in view model
Now I want to use a flag in view model to implement the new requirement ,any suggestions on this issue?


text:
Q: How do I sell to merchants? I found some Glitch merchants in town willing to sell me things, but I don't see an option or window to sell things. How do I convince them to take my useless things?

A: You cant yet. There will be an update (eventually) when you place the item you wish to sell on a block/crafting table like item and it gives you pixels.

A: As of 1.0 stable, most merchants have a 'sell' tab. You can drag your items or use shift click to add items to the sell list and see how much the items will sell for. Remember to click the sell button, otherwise the items will be returned to your inventory after the merchant's window is closed


text:
Q: Setting button background via theme makes the button unclickable Like the title indicates, when setting background of a button via theme, the button stops responding. I believe it is an issue on a few android versions, since my Nexus 4 running KitKat has no issue, however my HTC Desire S running 2.3.5 has it happenning. By the way, I am using the HoloEverywhere 2.0 atm. What is the problem?
The way I set the theme is the following:
<style name="AppTheme" parent="@style/Holo.Theme.Light.DarkActionBar">
    <item name="android:buttonStyle">@style/MyButtonStyle</item>
</style>

The button style is the following:
<style name="MyButtonStyle" parent="android:style/Widget.Holo.Light.Button">
    <item name="android:background">@drawable/button_yellow</item>
</style>

This works on the N4, but will NOT work on the HTC Desire S. However, if I set the same background directly on the button, it is working well on the HTC too, like this:
<Button
    android:id="@+id/example_button"
    android:text="Example"
    android:gravity="center"
    android:onClick="onClickEvent"
    android:background="@drawable/button_yellow"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

Any idea what is going wrong?

A: You should use Holo.Button.Light as parent in your custom button style.


text:
Q: Usage of clone method in Chisel IO interface constructors Several IO interface constructors of the Sodor processor collection implements its own clone method. I looked into the usage of clone method in Scala but still cannot figure out why exactly that is done. (I could not find any explicit usage of these methods anywhere in the design)

A: Sodor is still currently still on Chisel 2. clone was renamed to cloneType in Chisel 3 to distinguish it from clone in Java and Scala. cloneType is generally required by Chisel in order to instantiate new instances of parameterized Bundles. For example:
class MyBundle extends Bundle {
  val foo = UInt(32.W)
}
class MyParameterizedBundle(width: Int) extends Bundle {
  val bar = UInt(width.W)
}

Chisel often needs to create an instance of a given Bundle class from another instance of that class. Chisel uses Java reflection to do this. If there are no arguments to the constructor then it can just instantiate the object from the default constructor. However, it cannot determine the value of width from an instance of MyParameterizedBundle via reflection, so it cannot provide an appropriate parameter to the constructor. This is what the cloneType function is for. It tells Chisel how to create a new instance of a Bundle from a given object.
We hope to fix this wart in the future, but have not had the time to implement it. The most promising way is to automatically generate cloneType via Scala macro annotations.


text:
Q: What is the origin of "daemon" with regards to computing? Daemon has an interesting usage in computing. From my local dictionary:

a background process that handles requests for services such as print spooling and file transfers, and is dormant when not required

Does anyone know where this came from? I assume its relation to the word demon is notable. My dictionary also lists daemon as an archaic form of demon. Why did computing use daemon instead of demon?

A: In this interesting history, which is the actual description of the origin of this use from Professor Corbato, he explains that daemon originally had the connotation of "an attendant ... or indwelling spirit" and that:

By the late 16th century, the general supernatural meaning was being distinguished with the spelling daemon, while the evil meaning remained with demon.

He goes on to share the story of Maxwell's daemon.  Maxwell was a 19th century scientist who'd posed a physics problem in which a tiny daemon was the attendant at a gate between two chambers that was large enough for a single molecule to enter.  The daemon observed the molecules and chose which ones to allow to pass through the gate.
So now we come to the crux of it. We have established a daemon as an attendant, and a scientist used a hypothetical daemon in a famous problem in which the daemon's job was to monitor molecular movement.  Professor Corbato wraps up his explanation with

As you probably know, the "system processes" called daemons monitor other tasks and perform predetermined actions depending on their behavior. This is so reminiscent of Maxwell's daemon watching his molecules that we can only assume that whoever dubbed these "system processes" had Maxwell's daemon in mind.

The history also notes that Professor Saltzer, who also worked on Project MAC with Professor Corbato at the time "daemon" came into use for this purpose, confirms that this is the origin of daemon as it is used in computing.

A:
According to Fernando J. Corbato who
worked on Project MAC in 1963 his team
is the first to use the term daemon.
The use of the term daemon was
inspired by Maxwell's daemon, in
physics and thermodynamics as an
imaginary agent which helped to sort
molecules.
"We fancifully began to use the word
daemon to describe background
processes which worked tirelessly to
perform system chores."
(...)
In the Unix System Administration
Handbook, Evi Nemeth states the
following about daemons:
"Many people equate the word "daemon" with the word "demon",
implying some kind of satanic
connection between UNIX and the
underworld. This is an egregious
misunderstanding. "Daemon" is actually
a much older form of "demon"; daemons
have no particular bias towards good
or evil, but rather serve to help
define a person's character or
personality. The ancient Greeks'
concept of a "personal daemon" was
similar to the modern concept of a
"guardian angel"—eudaemonia is the
state of being helped or protected by
a kindly spirit. As a rule, UNIX
systems seem to be infested with both
daemons and demons."

See a full explanation in the Daemon (computing) Wikipedia article.

A: According to https://kb.iu.edu/d/aiau, "Daemon" stands for Disk and Execution Monitor.
More information on this meaning here:
www.techopedia.com: Disk and Execution Monitor (Daemon)
Extract:
What Does Disk and Execution Monitor (Daemon) Mean?
A disk and execution monitor (daemon) is a background process run in computer multitasking operating systems, usually at bootstrap time, to perform administrative changes or monitor services.
Common daemon processes include email handlers, print spoolers and other programs that perform OS administrative tasks. Daemons also perform specified operations at predefined times in response to events.


text:
Q: how to edit json attribute without manipulating state say I have a json object like so called student :
{id: 1,
 name: jon,
 hobbies:[running, basketball, soccer]
}

Without mutating state, I want to edit the hobbies array so that each element is a Hobby model. So basically iterate through each element in student.hobbies and call new Hobby(element) on each element. How can I do this without mutating state?

A: You can map() over the hobbies and use each value to create a Hobby object, code could look something like this.
const [student, setStudent] = useState();

useEffect(() => {
  fetch("url").then(res => res.json()).then(data => {
    // imagine data is { id: 1, name: "jon", hobbies: ["running", "basketball", "soccer"] }
    setStudent({
      ...data,
      hobbies: data.hobbies.map(h => new Hobby(h))
    });
  });
}, []);


text:
Q: Laravel Intervention Image not working I installed Laravel Intervention Image class by composer, from this tutorial, And when I type composer update, composer returns:
D:\WEB\htdocs\zanbil>composer update
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing intervention/image (dev-master b91b0d6)
    Downloading: 100%
    Downloading: 100%

intervention/image suggests installing intervention/imagecache (Caching extension for the Intervention Image library)
intervention/image suggests installing ext-imagick (to use Imagick based image processing.)
Writing lock file
Generating autoload files
Generating optimized class loader

And this is what I am going to use with Intervention Image:
$image=Input::file('image');
        $name = Input::file('image')->getClientOriginalName();
        var_dump(Image::make($image->getRealPath()->resize('280','280')->save('public/up/city/'.$name)));

And when I run that code Laravel return (with browser):

Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_ERROR)
  Call to a member function resize() on a non-object

What is the Problem?

A: You call resize on the result of getRealPath(). I think you want to do something like this instead:
Image::make($image->getRealPath())->resize('280', '280')->save('public/up/city/'.$name)

Thanks lukasgeiter for Answer


text:
Q: Using Paypal Login API I've been trying to get the Paypal Login API to work.
Login With Paypal
Problem one is that the Paypal Javascript Button Builder is not working... no code is produced.
Problem two is that when I generate the appropriate code using the Paypal PHP core sdk, it pops up a screen that does nothing.
Code sample below:
<?php
$sdklib="sdk-core-php-master/lib";
require_once("$sdklib/PPConfigManager.php");
require_once("$sdklib/PPConstants.php");
require_once("$sdklib/common/PPApiContext.php");
require_once("$sdklib/auth/openid/PPOpenIdSession.php");

$apicontext = new PPApiContext(array('mode' => 'sandbox'));
$clientId = "AaggjRACLgNPQNEF83qQchE8_KzyKS4mCxmeaTDHTPSFp4hsGlAx4KPMqfZP";
$scope = array('openid', 'email');
$redirectUri = 'http://uc.mithril.com.au/testloginreturn.php';
$openidurl = PPOpenIdSession::getAuthorizationUrl($redirectUri, $scope , $clientId,  $apicontext);

echo "Login Here";
?>

Clicking on the revealed link again produces a blank screen.
Is there some obvious step I am missing, or is the Sandbox just not working right now?

A: To resolve this issue I

*

*Created a new application in My Apps on Paypal Developer

*Clicked on 'Advanced Options' in the Login With Paypal feature.

*Made sure all the "Information Requested from Customers" boxes were ticked.

*Made sure the "Privacy Policy" and "User Agreement" URLs went to a valid page.

*Checked "Use Seamless Checkout" and "Allow the customers who haven't yet confirmed their email address with PayPal"

*Hit Save.

*Went back again and re-entered the Privacy Policy URLs a second time because they didn't save the first time.

*Made sure "scope" only contained valid data, as per Paypal Scopes
NB: The button generator only worked intermittently, and the default scope setting contained invalid options.


text:
Q: SFTP failed to process file with name contains asterisk I have a query with respect to SFTP.
I have used sftp for a file transfer functionality (in a java scheduler program).
The program would transfer a file from one location to other remote location using sftp.
All the files are getting transferred successfully except files with name contains asterisk in it.
Asterisk is considered as wildcard characters in sftp.
But, is there a way to configure sftp so that it would accept * and transfer file with name contains asterisk in it?
Any help would be appreciable.
Note:
I have used com.zehon.sftp.SFTP API as the SFTP client.
I have used the following method from this api:
public static int sendFile(java.lang.String localFilePath,
                           java.lang.String sftpDestFolder,
                           java.lang.String serverName,
                           java.lang.String username,
                           java.lang.String password)
                    throws FileTransferException

Thanks
Marshal

A: You'll need to escape the filename with a backslash to get it not to interpret the asterisk as a wildcard; e.g.
String oldstring = "file*name";
String escaped = oldstring.replace("*", "\\*");

Then you use escaped instead of oldstring. Most of the jsch ftp code does mention globbing for the operations, so you have to be aware of this when using the code.

A: The Zehon SFTP Javadoc for that function doesn't mention anything about honoring wildcards. You should consider reporting the issue to them as a bug (a documentation bug, at least).
In the meantime, you could work around it by opening the source file yourself, and using the sendFile() function that takes an inputStream:
try (FileInputStream fis = new FileInputStream(theLocalFile)) {
    SFTP.SendFile(fis, theRemoteName, theRemoteDir,
                  theRemoteServer, theRemoteUer, theRemotePass);
}


text:
Q: MediaCodec multi-threaded reference There are two threads to access the same MediaCodec object, and they may need to run simultaneously. Now I have a problem: when the two threads are running at the same time, the code is following:
try {
   mediaCodec.releaseOutputBuffer(encoderStatus, false);
} catch (IllegalStateException e) {
    e.printStackTrace();
}

How to deal with this code?
Because the two threads reference to the same mediaCodec object, one thread executes this code will affect the other thread's reference to the mediaCodec, and the other thread cannot run normally. How to solve it?

A: I am not sure if it is wise access MediaCodec from multiple thread, you will need to be careful with the synchronization, and a lot of synchronization may stall your (encoding/decoding) process.
If you want to push it to the PC while saving a MP4 file, I think what you should do is do your MediaCodec stuff in one thread, put the output result in a thread safe queue and process the result in other thread asynchronously ( can be done by using Handler, Executor etc)

A: Though it is not an must-have for MediaCodec to be multithreading-safe in synchronous mode (e.g. you can have a thread for dequeueInputBuffer(), filling one end of the pipeline, and a second Thread for dequeueOutputBuffer(), draining the other end of the Pipeline), I don't know of any HW decoder that crashes when you work with 2 Threads and 1 MediaCodec instance (and my App has been tested on a lot of devices). I think you are good to go.


text:
Q: Installing wxPython on Windows: DistutilsPlatformError: Microsoft Visual C++ 14.2 or greater is required I have installed:

*

*Python 3.10.1

*PyCharm Community 2021.3

*Visual Studio Build Tools 2022, including:

*

*C++ Build Tools Core Features

*C++ 2022 Redistributable Update

*C++ core desktop features

*MSVC v143 - VS 2022 C++ x64/x86 build tools (Latest)

*Windows 10 SDK (10.0.19041.0)

*C++ CMake tools for Windows

*Testing tools core features - Build Tools

*C++ AddressSanitizer

*C++/CLI support for v143 build tools (Latest)

*C++ Modules for v143 build tools (x64/x86 - experimental)

When trying to install wxPython in my project's virtualenv, I get this error:
distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 14.2 or greater is required. Get it with "Microsoft C++ Build Tools": https://visualstudio.microsoft.com/visual-cpp-build-tools/
Both the error and anything I can find on the internet (including here) tells me to download C++ build tools and install C++ 14.2 or greater / the latest version. I have:

*

*done that (see the list above),

*rebooted

*venv/Scripts/pip install --upgrade setuptools

*venv/Scripts/pip install --upgrade wheel

*venv/Scripts/pip install --upgrade pip
What am I missing here? Is there some sort of path variable that I need to configure somewhere so pip/wheel/setuptools knows where to find the compiler?

A: I have the same problem. Solved for me to use Python 3.9.9.
Its maybe about a distutils problem in Python 3.10.1 with this warning from msvc9compiler.py:

DeprecationWarning: The distutils package is deprecated and slated for
removal in Python 3.12

This leads to:

raise DistutilsPlatformError("Unable to find vcvarsall.bat")

A: The current wxPython 4.1.1 is not compatible with python 3.10 on windows (it works on Linux). You can download an older version of Visual Studio Build Tools to get around the issue with the DistutilsPlatformError, however you will not be able to successfully install on python 3.10 on windows. I found a solution for the problem, the link is Compile_wxPython_4.1.2a1_Python3.10_Windows. I was not able to compile it but there is a link to the whl file that was bult using the procedure. I downloaded and installed it using the command pip install wxPython-4.1.2a1-cp310-cp310-win_amd64.whl
I am confident in the near future 4.1.2 will be released to PyPy and you will be able to install it using pip.

A: The answers here have already provided the right pointers, but in this anser I would like to list all the necessary steps directly so you don't have to visit other resources, and it also provides the solution for both 64-bit and 32-bit versions of Python 3.10.x.
Solution for 64-bit version of Python 3.10.x

*

*Download the wxPython wheel file directly here: wxPython-4.1.2a1-cp310-cp310-win_amd64.whl.

*Using the Windows command line, move to the folder where you downloaded the wheel file.

*Run: pip install wxPython-4.1.2a1-cp310-cp310-win_amd64.whl
Solution for 32-bit version of Python 3.10.x
Prerequisites

*

*Download and install Microsoft C++ Build Tools.

*Download and install cygwin.

*Download and install GitHub Command Line Interface (GitHub CLI).

Build wxPython
In the Windows command line ran as Administrator, execute the following commands:
gh repo clone wxWidgets/Phoenix
cd .\Phoenix\
git submodule update --init --recursive
python -m venv venv
.\venv\Scripts\activate
pip install -r .\requirements.txt
python build.py dox etg --nodoc sip build

Create wheel
Still in the command line, execute the following:
python setup.py bdist_wheel

Install wheel
Still in the command line, execute the following:
cd dist
pip install <created-wheel-filename>

The <created-wheel-filename> should be the wheel you just created, so something like: wxPython-4.2.0a1-cp310-cp310-win32.whl
Source

*

*Compile wxPython 4.1.2a1 using Microsoft C++ Build Tools 2019

A: This problem is currently being fixed. Or rather it is fixed and a PR will be made with the fix pretty soon. I wrote a proper MSVC build environment script instead of the one that comes with either distutils or setuptool neither of which really work correctly when setting up an MSVC build environment.
Here is a link to the script I wrote that handles setting up the build environment properly
https://github.com/kdschlosser/python_msvc
and here is a link to a working fork of wxPython
https://github.com/oleksis/Phoenix/tree/try-pyMSVC
The problem with wxPython compiling properly is because neither setuptools or distutils has the capability of detecting Visual Studio 2022 properly. My script uses COM interfaces to collect the information needed to set up the build environment. The environment is set up without using the vcvar*.bat files.


text:
Q: Is there something I am missing in this, because I am getting error on HackerRank while it's working in JupyterLab? I am making a simple program to check if a UID is valid or not.
It must contain at 2 least uppercase English alphabet characters.
It must contain at 3 least digits (0 - 9).
It should only contain alphanumeric characters (a-z, A-Z & 0-9 ).
No character should repeat.
There must be exactly characters in a valid UID.
And this is the code I'm using. It works perfectly fine in my JupyterLab but it's giving me the Type Error on Hackerrank.
    if __name__ == '__main__':
        n = int(input("Enter the number of test cases: "))
        q = str(input("Enter the UID: "))

    cap_count = 0
    num_count = 0

    for x in q:
        if x.isupper():
            cap_count = cap_count+1
        if cap_count > 1 and x.isnumeric():
            num_count = num_count+1

    if (len(q) == 10) and (q.isalnum()) and (len(q) == len(set(q))) and (cap_count > 1) and (num_count > 2):
        print("Valid")
    else:
        print("Invalid")

IT's supposed to return valid or not valid
Here is the complete Traceback

Traceback (most recent call last):
File "Solution.py", line 17, in
if (len(q) == 10) and (q.isalnum()) and (len(q) == len(set(q))) (cap_count > 1) and (num_count > 2):
TypeError: 'bool' object is not callable

I know it's not the cleanest code that you guys have seen. But could really use the insight on why it works perfectly well on Jupiterlab and not on hackerrank even when both use python3.
Also, I'm taking input n cause it's required as one of the inputs, but no use for it.


text:
Q: DateFormatter is not printing value in the given format My date-time format string is : yyyy-MM-dd'T'HH:mm:ss.SSSZ
I am using DateTimeFormatter from Joda Time to print my date in the above mentioned format.
Now, consider the date as

2016/04/01 23:00:00

then it should have printed

2016-04-01T23:00:00.000Z

But, it prints

2016-04-01T23:00:00.000+0200

Please help me in getting the date printed in the same format as specified in the string format.

A: 2016-04-01T23:00:00.000Z != 2016-04-01T23:00:00.000+0200
Here is what Basil Bourque has commented on the wrong answer:

No, no, no. All you have done is append text, creating a falsity. If
your date-time represents a moment in a time zone that is two hours
ahead of UTC such as Europe/Helsinki, and you slap a Z on the end
which says Zulu and means UTC, you are now telling a lie, representing
value that is off by two hours. This is like replacing the dollar sign
in a price with a Euro currency symbol but failing to change the
number.

Just to illustrate what he has mentioned:
£100 != $100

The Z in 2016-04-01T23:00:00.000Z is the timezone designator for zero-timezone offset. It stands for Zulu and specifies the Etc/UTC timezone (which has the timezone offset of +00:00 hours). The same moment will be presented in different timezones with different values e.g.
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        Instant instant = Instant.parse("2016-04-01T23:00:00.000Z");

        ZonedDateTime zdtNewYork = instant.atZone(ZoneId.of("America/New_York"));
        ZonedDateTime zdtIndia = instant.atZone(ZoneId.of("Asia/Kolkata"));
        ZonedDateTime zdtNepal = instant.atZone(ZoneId.of("Asia/Kathmandu"));

        System.out.println(zdtNewYork);
        System.out.println(zdtIndia);
        System.out.println(zdtNepal);

        // Or at a fixed timezone offset of +02:00 hours
        OffsetDateTime odtWithTwoHoursOffset = instant.atOffset(ZoneOffset.of("+02:00"));
        System.out.println(odtWithTwoHoursOffset);
    }
}

Output:
2016-04-01T19:00-04:00[America/New_York]
2016-04-02T04:30+05:30[Asia/Kolkata]
2016-04-02T04:45+05:45[Asia/Kathmandu]
2016-04-02T01:00+02:00

To understand this concept a bit further, try converting a date-time from one timezone to another e.g. I have shown a conversion of a New York date-time into UTC. I have shown another conversion of a date-time with a timezone offset of +02:00 hours into UTC.
import java.time.Instant;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        // #######Example of converting a date-time from one timezone to another#####
        ZonedDateTime zdtNewYork = ZonedDateTime.parse("2016-04-01T19:00-04:00[America/New_York]");

        Instant instant = zdtNewYork.toInstant();
        System.out.println(instant);

        // Or as ZonedDateTime
        ZonedDateTime zdtUtc = zdtNewYork.withZoneSameInstant(ZoneId.of("Etc/UTC"));
        System.out.println(zdtUtc);

        // Alternatively, this can be obtained from instant
        zdtUtc = instant.atZone(ZoneId.of("Etc/UTC"));
        System.out.println(zdtUtc);
        // ###########################################################################

        System.out.println();

        // #####Example of converting a date-time at a fixed timezone offset to UTC###
        OffsetDateTime odtNewYork = OffsetDateTime.parse("2016-04-02T01:00+02:00");

        instant = odtNewYork.toInstant();
        System.out.println(instant);

        // Alternatively
        OffsetDateTime odtUtc = odtNewYork.withOffsetSameInstant(ZoneOffset.UTC);
        System.out.println(odtUtc);

        // Alternatively,
        odtUtc = instant.atOffset(ZoneOffset.UTC);
        System.out.println(odtUtc);
        // ###########################################################################
    }
}

Output:
2016-04-01T23:00:00Z
2016-04-01T23:00Z[Etc/UTC]
2016-04-01T23:00Z[Etc/UTC]

2016-04-01T23:00:00Z
2016-04-01T23:00Z
2016-04-01T23:00Z

A: According https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html Z has special meaning:
Z       zone-offset

If you want to escape Z quote Z with ':
yyyy-MM-dd'T'HH:mm:ss.SSS'Z'

For example:
java.time.LocalDateTime date = java.time.LocalDateTime.now();
java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter
                .ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
java.lang.String text = date.format(formatter);
System.out.println(text);

prints
2016-06-11T18:39:41.962Z


text:
Q: How to remove unwanted characters from list of string? I want to remove the special characters using re library
and by using only one method: cleanName(),
I am coding on code chef
input_list=["Donald_Trump", "Joe1@Bidden", "Kamala Harris1"]

output_list=["Donald Trump", "Joe Bidden", "Kamala Harris"]

I am using this code but didn't get help:
import re
input_list=["Donald_Trump", "Joe1@Bidden", "Kamala Harris1"]
print [re.sub('[^a-zA-Z0-9]+', '', _) for _ in input_list]

can it be done through iteration(using for loop)?

A: It seems like you have 2 cases here.

*

*Replace some characters with a space

*Replace some characters with nothing

import re

input_list=["Donald_Trump", "Joe1@Bidden", "Kamala Harris1"]

output_list=[re.sub(r"[_@]", " ", word) for word in input_list]
output_list=[re.sub(r"[^a-zA-Z\s]", "", word) for word in output_list]

print(output_list) # ['Donald Trump', 'Joe Bidden', 'Kamala Harris']

As requested, in a for loop:
import re

input_list = ["Donald_Trump", "Joe1@Bidden", "Kamala Harris1"]

output_list = []

for word in input_list:
  filtered_word = re.sub(r"[_@]", " ", word)
  filtered_word = re.sub(r"[^a-zA-Z\s]", "", filtered_word)

  output_list.append(filtered_word)

print(output_list)

A: Your print should have a bracket in python 3.0+ and instead of '', change to ' ' or "".
The differences between a single quote('') and double quote("") are double quote has 1 length in it and the single quote has 0. Try assigning both of them into a variable and use the len() to find out.
print([re.sub('[^a-zA-Z0-9]+', ' ', _) for _ in input_list])


text:
Q: How to start multiple tornado instance using bash I have a tornado server and I would like to start multiple instances on different ports, so I created the following bash file to start 3 instances.
#!/bin/bash

#start tornado instances in different ports
python startup.py --port="8081"
python startup.py --port="8082"
python startup.py --port="8083"

As you can see, the above code is problematic, because the first command will block the second one.
So anyone has any idea about how to start 3 together?
Thanks in advance.

A: If you need to run them just in current session, add & at the end of each line:
python startup.py --port="8081" &
python startup.py --port="8082" &
python startup.py --port="8083" &

But it is much more convenient to use systemd, upstart or other init system, because it gives you an easy way to start, stop and restart your instances.
If you need an example, i will update this answer.

Update
As long as you're using OS X, you can use default init system – launchd.
Step 1 – create a config file for your job:
vim /Library/LaunchDaemons/my_job.plist

File contents:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
        <key>Label</key>
        <string>my.awesome.label</string>

        <key>ProgramArguments</key>
        <array>
                <string>/usr/bin/python</string>
                <string>/Users/ivanvinogradov/tort.py</string>
        </array>

        <key>OnDemand</key>
        <false/>

        <key>UserName</key>
        <string>ivanvinogradov</string>

        <key>StartInterval</key>
        <integer>60</integer>

        <key>StandardErrorPath</key>
        <string>/tmp/AlTest1.err</string>

        <key>StandardOutPath</key>
        <string>/tmp/AlTest1.out</string>
</dict>
</plist>

Path to your .py script goes to <key>ProgramArguments</key>.
Put name of user, who will run your job in <key>UserName</key> section.
Also note that <key>Label</key> section is required.
Step 2 – ensure that .plist file has appropriate permissions:
sudo chown root:wheel /Library/LaunchDaemons/my_job.plist
sudo chmod 600 /Library/LaunchDaemons/my_job.plist

Step 3 – start and stop your job:
sudo launchctl load -w /Library/LaunchDaemons/my_job.plist
sudo launchctl unload /Library/LaunchDaemons/my_job.plist

This is a very simple example of launchd. You can learn more about it here on SO or on an Apple doc page.


text:
Q: How to print thousands of personalized documents over the web I need to generate thousands of personalized letters from more than 800 workstations in diverse locations.
While we had only a dozen of customers per location, we used Crystal Reports over the web and its PDF/Word export function to produce multi-page document for print. With thousand of customers this just doen't work for the following reasons:

*

*Browser unable to reliably download huge report

*Server resourses insufficient to handle simultanious requests from several workstations

*Even if Server and Client are Ok, you cannot start printing until whole reort is downloaded (i.e. for hours)

Workstations only have browsers and local high perfromance printers at the moment.
What is the solution for this problem? How should I do this?

A: In the past, we had a similar challenge.   To solve it, we created a C# application which was installed at each location.  It would communicate with the server via web services to get the data it needed to print.
Then we used the native printing functionality built into .NET for the actual printing.  The downloads were quick, and it could handle high volume printing.

A: Since the question was clarified as:

Remote warehouse only has browser and printer. It connects to the server and enters information about the item that just arrived. In responce to that, printing of thousands of shipping labels should start, warehouse cannot wait until labels are printed elswhere and delivered to its location.

...the rational way to do this would be to make all the printers network printers. The workstations could share them using Windows networking, or pick your own favourite print server technology.
The web application needs to be told which printer needs the labels. It then prints to whichever print server is appropriate.
The alternative - download the document and print locally - is too user-driven to be appropriate in my opinion.


text:
Q: How to pick up timespec_add_safe() for a Linux C++ application Folks,
Anyone know what/how I can include the appropriate header in order to pick up timespec_add_safe() for a Linux C++ application? Or maybe which library to link to in order to extern to timespec_add_safe()? My environment is kernel version 3.11.0-14-generic within Ubuntu 13.10 Saucy Salamander, and I am already linking my application with -lrt.
Note that my unfruitful investigations have indicated that timespec_add_safe() is coming from time.h, which in my environment is: /usr/src/linux-headers-3.11.0-13/include/linux/time.h  Also, note that my application is already including the standard time.h (/usr/include/time.h) for struct timespec and other "time" definitions. Further, I observe that the kernel has its own time.h (of course lacking the declaration for timespec_add_safe()) in /usr/include/linux/time.h. So, an extension of my question is, what are the differences/caveats between these inlude directories:
/usr/include                        - standard headers?
/usr/include/linux                  - kernel headers?
/usr/src/linux-headers-xxx/include  - what exactly is this? when/how to use?

Thanks in advance for any answers.

A: timespec_add_safe is in the kernel (grep timespec_add_safe /proc/kallsyms should reveal this), not in any userland code, so even if you #include a file with the declaration, the definition is not present, so it will not link. The implementation is trivial. You could even cadge it from time.c in the linux kernel.
                    – Petesh


text:
Q: Get data out MySQL is very slow I need to get some data from MySQL workbench into Python so I can make graphs.
But when I try to insert it and try to print the values, this is with pymysql (see code). It runs very slow.
So I think when I'm doing live graphs and more stuff the program will freeze...
Does someone have a solution?
My code:
import pymysql

conn= pymysql.connect(host='127.0.0.1',
                      port= 3306,
                      user= 'root',
                      passwd= '******',
                      db= 'energie'
                      )
a = conn.cursor()

sql1 = 'SELECT `VarValue`, `VarName` from `gasmeter1`;'
a.execute(sql1)

gasmeter1 = a.fetchone()

sql2 = 'SELECT `VarValue` from `gasmeter2`;'
a.execute(sql2)

gasmeter2 = a.fetchone()

sql3 = 'SELECT `VarValue` from `gasmeter349`;'
a.execute(sql3)

gasmeter349 = a.fetchone()

sql4 = 'SELECT `VarValue` from `binnentemp ahu3010`;'
a.execute(sql4)

Binnentemperatuur = a.fetchone()

sql5 = 'SELECT `VarValue` from `buiten temp241`;'
a.execute(sql5)

Buitentemperatuur = a.fetchone()

print (gasmeter1[0] , gasmeter2[0] , gasmeter349[0] , Buitentemperatuur[0] , Binnentemperatuur[0])

It is just a simple code but it is very slow. Someone suggestions?
Time:
code:
import pymysql
import time

conn= pymysql.connect(host='127.0.0.1',
                    port= 3306,
                    user= 'root',
                    passwd= 'ohdecg',
                    db= 'energie'
                     )

a = conn.cursor()

t1 = time.time()

sql1 = 'SELECT `VarValue` from `gasmeter1`;'
a.execute(sql1)

gasmeter1 = a.fetchone ()

sql2 = 'SELECT `VarValue` from `gasmeter2`;'
a.execute(sql2)

gasmeter2 = a.fetchone ()

sql3 = 'SELECT `VarValue` from `gasmeter349`;'
a.execute(sql3)

gasmeter349 = a.fetchone ()

sql4 = 'SELECT `VarValue` from `binnentemp ahu3010`;'
a.execute(sql4)

Binnentemperatuur = a.fetchone()

sql5 = 'SELECT `VarValue` from `buiten temp241`;'
a.execute(sql5)

Buitentemperatuur = a.fetchone()

t2 = time.time()
print("The SQL statement took : {} s".format(t2 - t1))
#print (gasmeter1[0] , gasmeter2[0], gasmeter349[0])

>>>
========================= RESTART: C:\Python27\j.py =========================
The SQL statement took : 32.0269999504 s
>>>

A: How big are your tables? You're retrieving the entire table each time and then just take the first element. You could try and time them with something like this:
import time
...

t1 = time.time()
sql4 = 'SELECT `VarValue` from `binnentemp ahu3010`;'
a.execute(sql4)
t2 = time.time()
print("The SQL statement took : {} s".format(t2 - t1))


text:
Q: Image Alignment on Featured Images When a client edits a featured image, they notice that they have the ability to set its "Alignment". If they were working with standard images embedded via the Editor, then this wouldn't be a problem. But since it is a featured image, WordPress doesn't pass in the appropriate class.
Is there a way to know which alignment option was set? If so, I can use that to add a class to the featured thumbnail accordingly.

A: Short answer: you don't.
The alignment settings only apply to images that the user adds to the Post Content. The Featured Image is incorporated into the template and is not added by the user to the Post Content.
The Featured Image is directly integrated into the template, usually as a "post thumbnail" displayed on archive index pages, or as a "post header image" displayed above the post on archive index pages and/or single blog posts. In such cases, the Theme developer accounts for the presentation of the Featured Image via the template markup and CSS.
(That's not to say that the user can't manually add to the post the image used as the Featured Image; the user certainly can - and in which case, the manually added image will use/apply the alignment setting.)

A: I am sort of confused with your question but I hope that this link will help.
http://codex.wordpress.org/CSS#WordPress_Generated_Classes

A: As a tag-along to Chip's answer (which is correct), here's a sample of the meta that's stored for image attachments via wp_get_attachment_meta($attachment_id):
array (
  'width' => '228',
  'height' => '147',
  'hwstring_small' => 'height='82' width='128'',
  'file' => '2009/06/1.jpg',
  'sizes' =>
  array (
    'thumbnail' =>
    array (
      'file' => '1-150x147.jpg',
      'width' => '150',
      'height' => '147',
    ),
  ),
  'image_meta' =>
  array (
    'aperture' => '0',
    'credit' => '',
    'camera' => '',
    'caption' => '',
    'created_timestamp' => '0',
    'copyright' => '',
    'focal_length' => '0',
    'iso' => '0',
    'shutter_speed' => '0',
    'title' => '',
  ),
)

The image description is stored in the attachment post_content column in the posts table.


text:
Q: Recurrence Relation on Ternary Sequences I have the following homework assignment:

Let $s_n$ be the number of ternary sequences of length n, such that the sub-sequences 00, 01, 10, and 11 never occur.
Prove that $s_n = s_{n-1} + 2s_{n-2}$ for $ n \ge 3$ with $s_1 = 3$ and $s_2 = 5$
Then find a direct formula for $s_n$.

So I found the direct formula using the second-order homogeneous linear difference equation and got  $s_n = - {\frac{1}{3}}(-1)^n + {\frac{4}{3}}(2)^n $
as my solution for the second part. I'm not quite sure how to go about proving the recurrence relation for this.


text:
Q: ionic 3: How to create orderpay string to pass at alipay plug in from server side i have an existing ionic3 application i need to integrate alipay and we chat payment, i know there are plug for both but I need any reference of how to generate order string or payment object at server side (Php laravel 5.4) which can be pass to plugin's payment method.
I have go through alipay documentation but couldn't get proper guidance.
Any example code or any ref for the same would be appreciated.


text:
Q: Remove all after space in SQL Server data column I have a data column in SQL Server that always starts with a number and sometimes has a space after the number with additional details. This is a text column. I need a query that will remove everything after and including space if there is a space or additional info. In other words, I need only the number to be in this column. Sometimes there is only a number and sometimes not. Can I get assistance in a query that will do this?

A: Try this
 Select case When charIndex(' ', columnName) > 0
           Then substring(columnName, 1, charIndex(' ', columnName)-1)
           else ColumnBame End
 From tableName

A: Try this one (replacing mydb and textfield with whatever name you have) :
UPDATE mytable
SET textfield = LEFT(textfield+' ', CHARINDEX(' ', textfield) - 1)
WHERE CHARINDEX(' ', textfield) > 0

A: I would suggest something like this:
SELECT CASE
WHEN ISNUMERIC(SUBSTRING(YourNumber, 1)) THEN SUBSTRING(YourNumber, 1, len(YourNumber) -1)
WHEN ISNUMERIC(SUBSTRING(YourNumber, 2)) THEN SUBSTRING(YourNumber, 2, len(YourNumber) -2)
WHEN ISNUMERIC(SUBSTRING(YourNumber, 3)) THEN SUBSTRING(YourNumber, 3, len(YourNumber) -3)
WHEN ISNUMERIC(SUBSTRING(YourNumber, 4)) THEN SUBSTRING(YourNumber, 4, len(YourNumber) -4)
END
FROM TableName


text:
Q: Number of terms in a Polynomial Expansion For a binomial $(a + b)^n$, the number of terms is n + 1.
For a trinomial $(a + b + c)^n$, the number of terms is $\frac{(n+1)(n+2)}{(2)}$.
For a multinomial $(a + b + c +d)^n$, the number of terms is $\frac{(n+1)(n+2)(n+3)}{(6)}$.
I'm guessing that for $(a + b + c + d + e)^n$, the number of terms formula would include $(n+1)(n+2)(n+3)(n+4)$ on the numerator but I don't know what should be its denominator.
Question:

*

*What is the number of terms for $(a + b + c + d + e)^n$?

*Do we have a general formula for the number of terms of a polynomial expansion?

*What if the given is $(a^2 + a + b)^n$, can I still use the formula $\frac{(n+1)(n+2)}{(2)}$.when 2 terms in the expansion has the same variable?

*What if the given is $(a + b + Constant)^n$, would the constant affect the number of terms?

A: For a multinomial $(\sum_{i=1}^m x_i)^n$, the number of terms are ${{n+m-1} \choose {m-1}}$ or ${{n+m-1} \choose {n}}$
This is the same as n apples in m baskets. The combinations are ${{n+m-1} \choose
{m-1}}$ or ${{n+m-1} \choose {n}}$

A: for (a+b+c+d+e)^n it would be [(n+4)(n+3)(n+2)(n+1)]/24


text:
Q: Laravel Oauth2 Scopes and Routes I'm working on a Laravel API with Oauth2 (lucadegasperi/oauth2-server-laravel) that uses different scopes, lets say admin and user.
The API serves an emberjs application on the frontend. Obviously the user will have access to less resources than the admin.
My problem is that, ember will make requests to certain routes that should have the same name but that will use different controllers.
I would like to setup my api so that I could use a route of the same name, using different controllers in both scopes so I can separate things a bit. Because I would like to leave the ember app structure mostly as it is.
The problem is when I make a request as admin it throws a 403 saying that only user scope can use that route.
That wasn't what I thought would happen. I thought the filter would first check the scope and enter the route even if the same route exists in another scope. But from the looks of it, you have to either use different route names which would be bad for my Ember App or you filter what is sent to each role from each controller and methods and use the route filter "oauthOr" so both roles can access the controller.
In case there's no way to do what I'm trying (see code), is there a way to prevent the controller from executing certain methods based on user role/scope? Appart from manually "ifing and elseing" all over the place?
Below is an example that illustrates what I'm trying to accomplish.
    Route::group(array( 'prefix' => 'api/1', 'before' => 'oauth:admin' ), function(){

    Route::resource('cars', 'ApiAdminCarsController');
    Route::resource('bikes', 'ApiAdminBikesController');

});

Route::group(array( 'prefix' => 'api/1', 'before' => 'oauth:user' ), function(){

    Route::resource('cars', 'ApiUserCarsController');
    Route::resource('bikes', 'ApiUserBikesController');

});

A: In the Route::resource call you can do certain things like "only", "except" to limit which methods can be executed by which route.


text:
Q: Website being flagged by Virgin Media's "Web Safe" security feature I operate a private (login required) Wordpress site for a client who recently had an employee move to the UK.
Their ISP there, Virgin Media, is blocking the website. I realize the employee could simply edit their Virgin Media user settings as suggested in the screenshot below, but is there anything I can do as the administrator/developer to whitelist the site?
Edit: I should add that i've done the preliminary check on google and looked for documentation for developers on Virgin's site, but couldn't find a thing.
I have checked the site with Google's Safe Browsing checker and Qualys' SSL Labs and both came out clean.
What the employee sees:

A: You may want to start by seeing what your site report looks like using a tool like Blocked.org.uk, which will give you a rough idea on if it's a single ISP in the UK that's filtering your site, or the entire gamut. For a single one, you may be able to get an exemption. If your site is blocked by a majority of ISPs, it may be that there is a court order or similar compelling UK ISPs to filter your site for one reason or another (unlikely, but possible).
Next, Virgin's FAQs state you can try to get in touch with someone knowledgable on the subject by posting in their Help forum; search "whitelist" for a few samples of folks with similar issues to yours to get an idea on how to get a helpful response.
Finally, you may have to acknowledge an uphill battle in answering the "why" - it's a fact that these companies make money (directly or otherwise) by providing a service in which they use some form of proprietary data collection and/or heuristic analysis to determine what should be filtered versus what should be allowed to be passed through. Revealing the "secret sauce" of this filtering to answer your "why" is probably not at all beneficial to them in any way. As such you may find the effort of chasing this answer down quite futile (speaking anecdotally from my own experience with similar issues: it is).


text:
Q: Unsigned return type returns signed number C I'm currently going through K&R C, and I got to the section on bitwise operators with this example:
unsigned getbits(unsigned x, int p, int n) {
  return (x >> (p + 1 - n)) & ~(~0 << n);
}

I've been playing around with it, and I did the following:
unsigned getbits(unsigned x, int p, int n) {
   return (~0 << n);
}

I fed in n = 2, and the result I got was -4. The result in bit form should be this (for a 32 bit integer), if I'm not mistaken:
1111 1111 1111 1100
If the return type of the function wasn't unsigned, I can kind of see where the -4 would come from, but because the return type is unsigned, shouldn't this be returning an unsigned number? Why is it returning -4?
Thanks!

A: Even if the function declares it is returning unsigned, the actual use of the value after return determines how it is interpreted.
For example, printf("%d", x); interprets x as a signed int, even if it's declared as anything else.


text:
Q: Coldfusion Multi-Select box without CFSelect How would one go about building a multiselect box in Coldfusion without using CFForm or CFSelect?
This is to pull values from a DB so its not just a static select box it is dynamic.
This is my first time every trying to code in ColdFusion, I have always been a .Net person so this is a bit of a change for me.
The reason why I am needing this is because I've gotten hired into a department at work that uses Coldfusion but from what the Lead developer told me is they do not use CFForm and seeing as how CFSelect requires to be inside CFForm I need a different way of doing this.

A: Use plain old HTML, for example:
<cfquery name="qryUsers" datasource="datasourcename">
    SELECT [User].[UserID], [User].[FirstName]
    FROM [User]
</cfquery>

<cfoutput>
    <form ...>
        <select name="users" multiple="multiple">
            <option value="">- please select -</option>
            <cfloop query="qryUsers">
              <option value="#UserID#">#FirstName#</option>
            </cfloop>
        </select>
    </form>
</cfoutput>


text:
Q: Flutter AnimatedList still janky? I'm currently using an AnimatedList in my Flutter app and having problems with the way removed list items are animated out.  The animation itself works as expected but once the removed item finishes animating, it just disappears causing the other widgets to jump into its place. I had expected the other items to transition into the place of the removed item ...
I tried wrapping my list items with a ScaleTransition but that didn't help - the other list items still do not react to the removed item until it has finished the animation.
This kind of defies the purpose of AnimatedList, right? Or did I do something wrong? The "Widget of the week" video about AnimatedList clearly shows that list items react to newly inserted items by changing their position ...
Here is my code:
@override
Widget build(BuildContext context) {
  return AnimatedList(
    padding: EdgeInsets.only(top: REGULAR_DIM,
        bottom: REGULAR_DIM + kBottomNavigationBarHeight),
    initialItemCount: data.length,
    itemBuilder: (context, index, animation) {
      return MyCustomWidget(
          data: data[index],
          animation: animation,
          disabled: false
      );
    },
  );
}

class MyCustomWidget extends AnimatedWidget {
  final MyModel data;
  final bool disabled;

  MyCustomWidget({
    @required this.data,
    @required Animation<double> animation,
    this.disabled = false
  }) : super(listenable: animation);

  Animation<double> get animation => listenable;

  @override
  Widget build(BuildContext context) {
    final content = ... ;

    return ScaleTransition(
      scale: CurvedAnimation(
          parent: animation,
          curve: Interval(0, 0.25)
      ).drive(Tween(begin: 0, end: 1)),
      child: FadeTransition(
        opacity: animation,
        child: SlideTransition(
          position: animation.drive(
              Tween(begin: Offset(-1, 0), end: Offset(0, 0))
                  .chain(CurveTween(curve: Curves.easeOutCubic))),
          child: content,
        ),
      ),
    );
  }
}

And then somewhere in the MyCustomWidget I invoke this function:
void _remove(BuildContext context) async {
        final animatedList = AnimatedList.of(context);

        // obtain myModel asynchronously

        myModel.removeData(data);
        animatedList.removeItem(index, (context, animation) => MyCustomWidget(
          data: data,
          animation: animation,
          disabled: true,
        ), duration: Duration(milliseconds: 350));
      }

A: The key is to trigger two Transitions one SlideTranstion() and another SizeTransition to eliminate to jump when the item is removed
here is some sample code
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: Text('Update AnimatedList data')),
        body: BodyWidget(),
      ),
    );
  }
}

class BodyWidget extends StatefulWidget {
  @override
  BodyWidgetState createState() {
    return new BodyWidgetState();
  }
}

class BodyWidgetState extends State<BodyWidget>
    with SingleTickerProviderStateMixin {
  // the GlobalKey is needed to animate the list
  final GlobalKey<AnimatedListState> _listKey = GlobalKey(); // backing data
  List<String> _data = ['Horse', 'Cow', 'Camel', 'Sheep', 'Goat'];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        SizedBox(
          height: 400,
          child: AnimatedList(
            key: _listKey,
            initialItemCount: _data.length,
            itemBuilder: (context, index, animation) {
              return _buildItem(
                _data[index],
                animation,
              );
            },
          ),
        ),
        RaisedButton(
          child: Text(
            'Insert single item',
            style: TextStyle(fontSize: 20),
          ),
          onPressed: () {
            _onButtonPress();
          },
        ),
        RaisedButton(
          child: Text(
            'Remove single item',
            style: TextStyle(fontSize: 20),
          ),
          onPressed: () {
            _removeSingleItems();
          },
        ),
      ],
    );
  }

  Widget _buildItem(String item, Animation<double> animation, {direction: 0}) {
    return (direction == 0)
        ? SizeTransition(
            sizeFactor: animation,
            child: Card(
              color: Colors.amber,
              child: ListTile(
                title: Text(
                  item,
                  style: TextStyle(fontSize: 20),
                ),
              ),
            ),
          )
        : Stack(
            children: [
              SizeTransition(
                sizeFactor: animation,
                child: Card(
                  color: Colors.transparent,
                  child: ListTile(
                    title: Text(
                      item,
                      style: TextStyle(fontSize: 20),
                    ),
                  ),
                ),
              ),
              Align(
                alignment: Alignment.topCenter,
                heightFactor: 0,
                child: SlideTransition(
                  position: animation
                      .drive(Tween(begin: Offset(-1, 0), end: Offset(0, 0))),
                  child: Card(
                    color: Colors.red,
                    child: ListTile(
                      title: Text(
                        item,
                        style: TextStyle(fontSize: 20),
                      ),
                    ),
                  ),
                ),
              ),
            ],
          );
  }

  void _onButtonPress() {
    _insertSingleItem();
  }

  void _insertSingleItem() {
    String item = "Pig";
    int insertIndex = 2;
    _data.insert(insertIndex, item);
    _listKey.currentState.insertItem(insertIndex);
  }

  void _removeSingleItems() {
    int removeIndex = 2;
    String removedItem = _data.removeAt(removeIndex);
    // This builder is just so that the animation has something
    // to work with before it disappears from view since the
    // original has already been deleted.
    AnimatedListRemovedItemBuilder builder = (context, animation) {
      // A method to build the Card widget.

      return _buildItem(removedItem, animation, direction: 1);
    };
    _listKey.currentState.removeItem(removeIndex, builder);
  }

  void _updateSingleItem() {
    final newValue = 'I like sheep';
    final index = 3;
    setState(() {
      _data[index] = newValue;
    });
  }
}
enter code here

A: You need to test the performance with the release version of your app.


text:
Q: Best Way To Display Music Play Controls On Lock Screen iOS7 I have a music app. What is the best way to have the song info and music controls show up in the lock screen like SoundCloud - see (http://cl.ly/image/1a1H041A1Z34)
Thank you very much!

A: Pretty useful guide - Lock screen "Now Playing" with MPNowPlayingInfoCenter;
This only works with iOS 5+ and is done something like this.
- (void)setupNowPlayingInfoCenter:(MPMediaItem *)currentSong
{
    NSString *ver = [[UIDevice currentDevice] systemVersion];
    CGFloat version = 4.0;
    if ([ver length] >= 3)
    {
        version = [[ver substringToIndex:3] floatValue];
    }

    if (version >= 5.0)
    {
        MPMediaItemArtwork *artwork = [currentSong valueForProperty:MPMediaItemPropertyArtwork];

        MPNowPlayingInfoCenter *infoCenter = [MPNowPlayingInfoCenter defaultCenter];

        if (currentSong == nil)
        {
            infoCenter.nowPlayingInfo = nil;
            return;
        }

        infoCenter.nowPlayingInfo = [NSDictionary dictionaryWithObjectsAndKeys:
                [currentSong valueForKey:MPMediaItemPropertyTitle], MPMediaItemPropertyTitle,
                [currentSong valueForKey:MPMediaItemPropertyArtist], MPMediaItemPropertyArtist,
                [currentSong valueForKey:MPMediaItemPropertyAlbumTitle], MPMediaItemPropertyAlbumTitle,
                [currentSong valueForKey:MPMediaItemPropertyAlbumTrackCount], MPMediaItemPropertyAlbumTrackCount,
                [currentSong valueForKey:MPMediaItemPropertyAlbumTrackNumber], MPMediaItemPropertyAlbumTrackNumber,
                artwork, MPMediaItemPropertyArtwork,
                [currentSong valueForKey:MPMediaItemPropertyComposer], MPMediaItemPropertyComposer,
                [currentSong valueForKey:MPMediaItemPropertyDiscCount], MPMediaItemPropertyDiscCount,
                [currentSong valueForKey:MPMediaItemPropertyDiscNumber], MPMediaItemPropertyDiscNumber,
                [currentSong valueForKey:MPMediaItemPropertyGenre], MPMediaItemPropertyGenre,
                [currentSong valueForKey:MPMediaItemPropertyPersistentID], MPMediaItemPropertyPersistentID,
                [currentSong valueForKey:MPMediaItemPropertyPlaybackDuration], MPMediaItemPropertyPlaybackDuration,
                [NSNumber numberWithInt:self.mediaCollection.nowPlayingIndex + 1], MPNowPlayingInfoPropertyPlaybackQueueIndex,
                [NSNumber numberWithInt:[self.mediaCollection count]], MPNowPlayingInfoPropertyPlaybackQueueCount, nil];
    }
}

next time, try to use search:

*

*Changing iphone lock screen programmatically when app is running in background


text:
Q: how to compare the distance and duration strings returned by google directions api Since the directions google map api returns the drivind distance and time between origin and destinations. Now If I have to compare the time and distance value in java ,how can we do it.
eg : Distance1= 22km     Distance2= .98km
     Time1= 1hour 2 min  Time2 =  3 min
Now if I have to compare the time and distance string which is greater ,how we can do it?

A: You tagged this incorrectly. This is related to Javascript not Java. They are 'not' the same language.
As for your question. You can retrieve the values from the directions by accessing the json directly.
alert(JSON.stringify(response['routes'][0]));

That line put straight after your OK check should help get you started.

A: You'll need to convert those values to numbers, e.g. kilometers for the distance and minutes for the times - e.g. 22 and 0.98, resp. 62 and 3 for your examples. Then you can simply compare the numbers.
I don't know if the api returns the values always in kilometers and hours/minutes, you should make sure of that, and then "simply" parse the values you get. For the distances this would be something like so:
double distance1 = Double.valueOf("22km".replace("km,""));
double distance2 = Double.valueOf(".98km".replace("km,""));
if (distance1 < distance2) {
    System.out.println("distance1 is smaller");
} else if (distance2 < distance1) {
   System.out.println("distance2 is smaller");
} else {
   System.put.println("both distances are the same.");
}

For the time parts, the parsing will be a bit more complicated.
And yes, I know you can do this much more elegant using regular expressions but I'd have had to try around to get them right, so I went with the simple way.


text:
Q: GZIP for CSS and JS dosen't work in Google Chrome, but does in Firefox I have recently figured out how to enable GZIP (or Deflate) on my WAMP server that I will be using to serve my intranet application.
However, when testing in Google Chrome I see that the PHP file is compressed but Javascript files and CSS are not. The Response header shows that it is not compressed and Google Pagespeed confirms this.
Firefox on the other hand recives all files with compression without a problem.
Here are the headers for the main CSS file as an example:
Google Chrome
Date: Wed, 18 Jul 2012 14:48:43 GMT
Content-Length: 6533
Last-Modified: Wed, 18 Jul 2012 00:42:33 GMT
Server: Apache/2.2.21 (Win64) PHP/5.3.10
ETag: "a00000001509b-1985-4c50ff04b26ef"
Vary: Accept-Encoding
Content-Type: text/css
Accept-Ranges: bytes

200 OK

Firefox
Date: Wed, 18 Jul 2012 14:33:14 GMT
Server: Apache/2.2.21 (Win64) PHP/5.3.10
Last-Modified: Wed, 18 Jul 2012 00:42:33 GMT
Etag: "a00000001509b-1985-4c50ff04b26ef"
Accept-Ranges: bytes
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 1273
Content-Type: text/css

200 OK

Is this a problem with my WAMP setup, code, or is it just Google Chrome?
Thank you.

A: Google chrome does support JS/CSS gzip.
Request URL:http://d1o7y22ifnbryp.cloudfront.net/static/7793/css/all.min.css
Request Method:GET
Status Code:200 OK
Request Headersview source
Accept:text/css,*/*;q=0.1
Accept-Charset:GBK,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:zh-CN,zh;q=0.8
Connection:keep-alive
Host:d1o7y22ifnbryp.cloudfront.net
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5

Response Headers
Accept-Ranges:bytes
Cache-Control:max-age=604800
Connection:keep-alive
Content-Encoding:gzip
Content-Length:17933
Content-Type:text/css
Date:Wed, 18 Jul 2012 15:43:46 GMT
ETag:"805dc-19c87-4c4a305735340"
Expires:Wed, 25 Jul 2012 15:43:46 GMT
Last-Modified:Thu, 12 Jul 2012 14:45:57 GMT
Server:Apache/2.2.22 (Amazon)
Vary:Accept-Encoding

I think the problem should be in apache configuration.