text:
Q: valid and invalid syntax for representing the size of array during initialisation I'm currently studying c array and is confused about what can and can't be used to represent the size of the array during initialisation.
Am I right to assume
#define SIZE 5

and
const int SIZE = 5;

are fundamentally different to one another?
They have their difference and one particular example that confuses me is
#define SIZE 5
int arr[SIZE] = {11, 22, 33, 44, 55};

is valid syntax, but
const int SIZE = 5;
int arr[SIZE] = {11, 22, 33, 44, 55};

is not valid syntax. Though interestingly,
const int SIZE = 5;
int arr[SIZE];

is valid syntax.
What's the logic behind whether a particular syntax is valid or invalid?

A: The standard explains it 6.7.9p3

The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.

In the second case it's a VLA but in the first case it is not. After preprocessing it is same as int arr[5] = {..}.
In the VLA case, the compiler doesn't know the size of a VLA when it's defined, so it can't check validity of an initializer. That's why this initialization is not allowed.
By the way, using const doesn't mean that it is a compile time constant - it just means it can't be changed.
Also from 6.7.6.2p4 there is a clear distinction about when it is VLA and when it is not:-

...If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type.

A: #define SIZE 5 define SIZE an integer constant expression. While const int SIZE = 5; defines SIZE as a variable expression that's value shall not be modified. const qualifier doesn't make it an integer constant expression (in c++ it does so).
Standard says
n1570-§6.7.6.2 (p4):

[...] If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type. [...]

When you do
#define SIZE 5
int arr[SIZE] = {11, 22, 33, 44, 55};

it declare arr as an array which is not a variable length array (VLA). While
const int SIZE = 5;
int arr[SIZE];

declares arr as a variable length array because SIZE is not a integer constant expression, but a variable expression. But same declaration fails with initializer list and that's because there is a restriction on VLA's is they can't be initialized using list intializers.
§6.7.9 (p2 and p3):

No initializer shall attempt to provide a value for an object not contained within the entity being initialized.
The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.

A:
Am I right to assume
#define SIZE 5
  and
  const int SIZE = 5;
are fundamentally different to one another?

Yes, you are right.
#define is simply a textual replacement. Basically, the C preprocessor is going a "find and replace" for you during the compilation process (processing stage). Whereas, const qualified  object means "the thing stored at this location can't changed" - roughly equivalent to saying it's "read-only".

#define SIZE 5
     int arr[SIZE] = {11, 22, 33, 44, 55};
is valid syntax.

This is exactly equivalent to writing:
int arr[5] = {11, 22, 33, 44, 55};

yourself. The compiler simply does the replacement job for you when you use define.

const int SIZE = 5;
int arr[SIZE] = {11, 22, 33, 44, 55};
is not valid syntax.

It's invalid but the reason could be more than one. If arr has static storage duration (i.e., the object arr is alive throughout the program execution) then it's invalid. Because C requires that the size of an array object with static storage duration to be a constant expression:

If the size is an integer constant expression and the element type has a known constant size, the array type is not a variable length array type; otherwise, the array type is a variable length array type.

So, the following program is not valid:
const int SIZE = 5;
int arr[SIZE] = {11, 22, 33, 44, 55};
int main(void)
{
}

because SIZE doesn't qualify as a "constant expression" in C. Note that this is totally valid in C++ where SIZE qualifies as a constant expression (the two languages differ here).
Another reason is C standard doesn't allow initializing variable-length arrays. If you have the definition inside a function such as:

The type of the entity to be initialized shall be an array of unknown size or a complete object type that is not a variable length array type.

So if you don't have the initializer then it becomes valid:
int main(void)
{
    const int SIZE = 5;
    int arr[SIZE];  /* This is OK */
}

Similarly, you can do without the const as well:
int main(void)
{
    int SIZE = 5;
    int arr[SIZE]; /* Thi is OK too. */
}

In both of the above snippets, arr is simply a variable-length array.

Though interestingly,
const int SIZE = 5;
  int arr[SIZE];
is valid syntax.

It's valid only if it's inside a function (as above) - it's a VLA. But if you make it have static storage duration such as:
const int SIZE = 5;
int arr[SIZE]; /* arr has static storage duration just as
                 all objects defined at file scope */

int main(void)
{
}

it's invalid because as noted above, SIZE is not a "constant expression" in C.
Similarly,
int main(void)
{
    const int SIZE = 5;
    static int arr[SIZE]; /* arr has static storage duration */
}

is invalid for the same reason, despite arr being inside a function, because arr has static storage duration.

However, if you have:
enum {SIZE = 5};
int arr[SIZE] = {11, 22, 33, 44, 55};
 int arr2[SIZE]; /* Valid without initializer too. */

int main()
{
}

it's valid. Why? Because enum constants qualify as "constant expressions" in C.


text:
Q: flatten_array function from multidimensional array - undefined i am trying to flat out a multidimensional array to a simple array. I tried searching for answers and used some functions i found here. But i am stuck on adding variables inside foreach loop after flatting array out:
This is my function:
public function create_order_direct($order_data) {
    $result = MarathonUtil::flatten_array($order_data);
    foreach ($result as $data) {
        $media_id = $data['media_id'];
        $headline = $data['headline'];
        $client_contact = $data['client_contact'];
        $plan_number = $data['plan_number'];
        $insertion_date = $data['insertion_date']; //NOW();?
        $start_date = $data['insertion_start_date'];
        $end_date = $data['insertion_end_date'];
        $PO_number = $data['PO_number'];
        $price_code = $data['price_code'];
        $gross = $data['gross'];
    }
}

MarathonUtil::flatten_array is this:
static function flatten_array($array) {
    $prefix = '';
    $result = array();
    foreach($array as $key=>$value) {
        if(is_array($value)) {
            $result = $result + self::flatten_array($value, $prefix . $key . '.');
        }
        else {
            $result[$prefix . $key] = $value;
        }
    }
    return $result;
}

So when running example echo $media_id, it says undefined. When i return $result, all data is available but not inside foreach? I only get the data $price_code and $gross (those are the deepest in array, see under)
The array looks like this before flatting out:
[{
    "media_id": "FACE",
    "headline": "FACEBOOK FEBRUAR 2018",
    "agreement_id": "REDP",
    "client_contact": "Asim Tariq",
    "order_id": 4710,
    "plan_number": 407,
    "insertion": {
        "insertion_date": "2018-09-25",
        "start_date": "2018-09-25",
        "end_date": "2018-10-10",
        "PO_number": 150,
        "price_row": {
            "price_code": "000",
            "gross": 10002345
        }
    }
}]

so a simple echo $data['media_id'] won't work inside foreach or either print_r($result) that gives me only price_code and gross

A: <?php
$json=<<<JSON
[{
    "media_id": "FACE",
    "headline": "FACEBOOK FEBRUAR 2018",
    "agreement_id": "REDP",
    "client_contact": "Asim Tariq",
    "order_id": 4710,
    "plan_number": 407,
    "insertion": {
        "insertion_date": "2018-09-25",
        "start_date": "2018-09-25",
        "end_date": "2018-10-10",
        "PO_number": 150,
        "price_row": {
            "price_code": "000",
            "gross": 10002345
        }
    }
}]
JSON;

$out = [];
$data = json_decode($json, TRUE);
array_walk_recursive($data, function($v, $k) use (&$out) {
    $out[$k] = $v;
});
var_export($out);

Output:
array (
    'media_id' => 'FACE',
    'headline' => 'FACEBOOK FEBRUAR 2018',
    'agreement_id' => 'REDP',
    'client_contact' => 'Asim Tariq',
    'order_id' => 4710,
    'plan_number' => 407,
    'insertion_date' => '2018-09-25',
    'start_date' => '2018-09-25',
    'end_date' => '2018-10-10',
    'PO_number' => 150,
    'price_code' => '000',
    'gross' => 10002345,
  )

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I correctly launch a process and forward stdin/stdout/stderr? I'm using CreateProcess to launch an interactive script interpreter and would like to transparently forward stdin/stdout/stderr from/to the interpreter.
My first attempt was to setup the STARTUPINFO structure passed to CreateProcess like
STARTUPINFOA si = { sizeof( si ) };
si.hStdError = ::GetStdHandle( STD_ERROR_HANDLE );
si.hStdOutput = ::GetStdHandle( STD_OUTPUT_HANDLE );
si.hStdInput = ::GetStdHandle( STD_INPUT_HANDLE );
si.dwFlags |= STARTF_USESTDHANDLES;

I.e. I tried to make the script interpreter process use the very same handle for reading/writing as my launcher process uses. That didn't seem to work though (I'm not even sure those standard handles can be inherited).
A second idea, based on the Creating a Child Process with Redirected Input and Output example is to setup three pipes to forward all data written to any of the pipes. Since I don't know how to wait for data to be written to more than one file (WaitForMultipleObjects cannot synchronize on pipes), I was considering to have three threads, each of which doing a blocking ReadFile call on a pipe.
I suspect that this might be overkill though so I'm wondering: is there some easier way to do this? I don't need to do any kind of processing of the data passed from/to the script interpreter at all.
As a side note, on Linux I'm using execvp to just replace the current process with the script interpreter process, but on Windows I need to launch the script interpreter with the main thread in suspended state (so that I can do some bytecode patching) - so even since _execvp seems to be availble on Windows, I apparantly have to use CreateProcess.

A: In order to wait for I/O on more than one file or pipe, you issue asynchronous I/O requests on each of those files, then wait for completion of said requests. Something along these lines (untested):
HANDLE file1, file2; // initialized somehow

HANDLE events[2];
events[0] = CreateEvent(NULL, TRUE, FALSE, NULL);
events[1] = CreateEvent(NULL, TRUE, FALSE, NULL);

OVERLAPPED overlapped1 = {0};
overlapped1.hEvent = events[0];
OVERLAPPED overlapped2 = {0};
overlapped2.hEvent = events[1];

ReadFile(file1, buffer1, size1, NULL, &overlapped1);
ReadFile(file2, buffer2, size2, NULL, &overlapped2);

WaitForMultipleObjects(2, events, FALSE, INFINITE);

ReadFile and WaitForMultipleObjects would need to be called in a loop. You check the return value of WaitForMultipleObjects to know which operation has completed, use GetOverlappedResult to discover the outcome of that operation (whether it succeeded, and if so, how many bytes it retrieved), process the data, call ReadFile for that handle again if you want to read some more from it, then get back to waiting. This is somewhat similar to a loop of non-blocking I/O driven by select in Linux.
Still more advanced technique is I/O completion ports. This allows one to have a thread pool handling lots of asynchronous I/O. Commonly used in Web servers and such, probably overkill for your case.

A: Popuplating the STARTUPINFO as shown by the OP works fine if you make sure to not pass the CREATE_NO_WINDOW argument in the dwFlags argument of CreateProcess.


text:
Q: How can I get static html page using post method by springboot In the springboot, when I get resource by post method, I will receive 'Request method 'POST' not supported', I've konwn how to solve it in the spring mvc, I can add support methods 'POST' in ResourceHttpRequestHandler, but I don't konw how to solve it in the springboot, so hope someone to sovle my problem, thanks very much.

A: I solved it, here is my solution.
@PostConstruct
public void addSupportType() {
    SimpleUrlHandlerMapping handlerMapping = applicationContext.getBean("resourceHandlerMapping", SimpleUrlHandlerMapping.class);
    Map<String, ResourceHttpRequestHandler> urlMap = (Map<String, ResourceHttpRequestHandler>) handlerMapping.getUrlMap();
    for (Map.Entry<String, ResourceHttpRequestHandler> entry : urlMap.entrySet()) {
        entry.getValue().setSupportedMethods("GET", "POST");
    }

}


text:
Q: MySQL + PHP query with date causing issues I use this code, which should return me total amount (sum) of clients registrered/joined in last 7 days (sun-sat).
  require '../dbconnect.php';

  $result = full_query ('SELECT COUNT(*) FROM tblclients WHERE date between \'' . date ('Y-m-d', mktime (0, 0, 0, date ('m'), date ('d') - 7, date ('Y'))) . '%\' AND \'' . date ('Y-m-d') . '%\'');
  $data = mysql_fetch_array ($result);
  echo $data;

For some reasson, I get no results. Please help.

A: For one, you're trying to echo an array. Try print_r($data)

A: familarize yourself with the
       now()

function in mysql
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_now


text:
Q: Bench mark old rails application 2.3.5 Is there an application that could benchmark or check what pages makes my application slow and causing high cpu usage?

A: Try Bullet. It's a rails plugin/gem to kill N+1 queries and unused eager loading.


text:
Q: Fail to use "locate" I have a file named Fubini's_theorem.html under some directory. But both
locate "Fubini's_theorem"

or
locate Fubini

do not return anything.
The file has been there for months, and I am sure it is already in the database used by locate. So I wonder why the search is not successful? Thanks!
My OS is Ubuntu 10.10.

A: You could also use the find utility:
find / -name Fubini 2> /dev/null
/ to search starting from /
-name Fubini look for a file with "Fubini" in it's name
2> /dev/null redirect errors to /dev/null.
The redirect is useful when searching from root because /proc directories aren't really there. /proc is a virtual filesystem and finding through it is ... well just not right :)

A: You can use the following command to update the database of file indexes
/usr/bin/updatedb -e /mnt/data,/mnt/files,...

Theoretically this command should be in your crontab so that it's executed periodically. You could check your crontab by running
crontab -l

If it isn't in there you could add it manually.


text:
Q: Why did the crewman have to be in an ion pod in Star Trek "Court Martial"? I just watched "Court Martial" in which Kirk is accused of negligence, resulting in the death of a crew member. Said crew member had to report to an "ion pod" to take readings during an ion storm, and the pod had to be jettisoned in order to save the ship.
What purpose did the ion pod serve, i.e. why did the crewman have to be in it during the storm?
And why did the pod have to be jettisoned?

A: The pod was a place to mount the instruments to measure the ion storm without having to drill holes in the skin and armor of the ship.
The crewmember had to be present to run the tests. Star Trek wasn't big on automation.
The pod had to be ejected because, IIRC, it was picking up a charge and was becoming a danger to the ship as a whole.  The crewmember was given warning to get out - but when the court martial trial read back the records, the warning was not in the recording!

A: In the remastered "Court Martial", the Ion pod is shown as being mounted near the rear of the main body of the ship. It is described by Memory Alpha as a;

"Sensory component of Constitution-class starships...deployed in times
  when a starship was expected to encounter an ion storm...
Manually operated by one crewmember, the pod took readings (from "ion plates") that were otherwise not
  available to conventional sensors in the course of the storm."

As far as the reason why the pod had to be able to be jettisoned, Hanson tells Kirk that the pod is causing;

"Natural vibrations, force two, Captain....Force three."

at which point it seems to be standard practice to eject the pod, presumably to prevent the vibrations from causing damage to the hull of the ship.


text:
Q: Shell script to find and move files and delete the affected folders Is it possible to create a shell script that finds files in and below a folder of a specific type, and move them to another folder (this part is already solved*). And then remove all folders where files were moved from?
I guess it should be somehow possible to write the path/folder name into an array or file and then read from there to "rm" them.
finding files example:
find . \( -name "*.mpeg" – o –name "*.mkv" –o –name "*.avi" –o –name "*.mov" \) –size +536870912c –exec mv  -n –v {} /my/favorite/folder/ \;

second part where those folders from which was moved need to be deleted is still missing.

A: If you din't mind using another executables, you can do it like:
find . \( -name "*.mpeg" – o –name "*.mkv" –o –name "*.avi" –o –name "*.mov" \) –size +536870912c | \
gawk -F'/[^/]*$' '{print "echo mv " $0 " /WHERE/TO/MOVE" ; dirstoremove[$1]++ }
       END       {for (d in dirstoremove) {print "echo rmdir " d } }' | \
bash

*

*First find your items

*Then gawk creates the list of removable files and store their path in an array and after processing all the files prints the rmdir for every element in the array

*And sends it output to bash which executes it.

Note: the above won't remove anything just echoes what should be done. If you are satisfied with the result and want to execute it you can remove the two "echo" or simply add one more | bash to the end.

A: If you like one-liners (like I do), you can extend your command as follows:
<your find command> -print | xargs -l dirname | sort -u | xargs rmdir

-print echoes the path of the file that has been moved.
xargs -l dirname strips off the filenames, resulting in a list of directory names.
sort -u reduces the list of directory names by removing duplicates.
xargs rmdir removes the directories.


text:
Q: Is a policy $\pi(s)$ on Markov decision process a random variable? Citing Wikipedia:

The goal in a Markov decision process is to find a good "policy" for
the decision maker: a function $\pi$  that specifies the action
$\pi(s)$ that the decision maker will choose when in state $s$.   Once
a Markov decision process is combined with a policy in this way, this
fixes the action for each state and the resulting combination behaves
like a Markov chain (since the action chosen in state $s$ is
completely determined by $\pi(s)$ and $\Pr(s_{t+1}=s'\mid
> s_{t}=s,a_{t}=a)$ $\Pr(s_{t+1}=s'\mid s_{t}=s,a_{t}=a)$   reduces to
$Pr(s_{t+1}=s'\mid s_{t}=s)$ $Pr(s_{t+1}=s'\mid s_{t}=s)$, a Markov
transition matrix).

A policy that maximizes the function above is called an optimal policy and is usually denoted $\pi^*$. A particular MDP may have multiple distinct optimal policies. Because of the Markov property, it can be shown that the optimal policy is a function of the current state, as assumed above.
Can the policy be considered a random variable?

A: The policy is a function you define to act in an environment, it's not a random variable.


text:
Q: Dictionary returning same value for every key only when value is also an enumerable or custom i am a noob, so please take this question with that in mind. Here is very simple piece of code:
Sub main()
{
Dim m_Dictionary as new Dictionary(Of Integer, List(Of String))
Dim workingList as new List(Of String)
Dim workingKey as Integer
Dim keyStash as List(Of Integer)
Dim workingDict as new Dictionary(Of Integer, String)

For i=0 to 9
    Do
      workingKey = RandomInteger()
    Loop While workingList.ContainsKey(workingKey)

    For n=0 to 4
      workingList.Add(RandomString())
    Next
    keyStash.Add(workingKey)
    workingDict.Add(workingKey, workingList)

 Next
 ' now I just want to play back the generators of random data

 For each Key As Integer in keyStash

    For each Entry as String in workingDict(Key).Value

           Line(Entry)

     Next

   Next

Instead of everything playing back nicely as one might expect, I am left with a fully accurate stash of keys for the dictionary. However, the values for strings inside each list instance are ALL THE SAME FOR EVERY KEY. Those values are equal to the values in the last loop of random data generation. So instead of playing back 50 uniques entries, it writes out 9 times the last loop. I looked inside - everything looks good. Get this. All lists, collections, hash-tables, all of iterated types and also custom types demonstrate this behavior. I found the solution, but it does not explain anything. Can anyone help explaining this, please!??

A: The variable that keeps the strings generated by RandomString is created outside the loop. Inside that loop you add continuosly new strings to the same instance and add the same list instance to every new integer key. At the end of the loop every integer key added has its value pointing to the same reference of the list. Of course they are identical....
A first fix to your code could be
Dim m_Dictionary as new Dictionary(Of Integer, List(Of String))
Dim workingKey as Integer

For i=0 to 9

    ' Internal to the loop. so at each loop you get a new list
    ' to use for the specific key generated in the current loop
    Dim workingList as new List(Of String)

    Do
        workingKey = RandomInteger()
    Loop While m_Dictionary.ContainsKey(workingKey)

    For n=0 to 4
        workingList.Add(RandomString())
    Next
    m_Dictionary.Add(workingKey, workingList)
Next
For each k in m_Dictionary
    For each Entry in k.Value
        ' Line(Entry)
        Console.WriteLine("Key=" & k.Key & " Values = " & Entry)
    Next
Next

Please, remember to use Option Strict ON, the current code treats quietly strings as if they were numbers, and this is not a good practice. Option Strict ON will force you to think twice when you work with different type of data.


text:
Q: Внедрение php в c++ проект Есть необходимость использовать php - интерпретатор для обработки php страниц с php-кодом в Qt C++ проекте. Запускаю php.exe, пишу туда текст, получаю вывод. Это работает, но довольно медленно. На обработку ~300 страниц уходит 30 секунд. Нет ли библиотек для подключения к своему проекту, чтоб обработка происходила по вызову функции, а не запуска внешнего приложения?

A: Попробуйте FastCGI совместно с php-fpm. Подобно как работают с PHP nginx и прочите сервера с поддержкой FastCGI.


text:
Q: How safe is to set relationships to delete on cascade? I have this big database on mysql (104 tables), where almost every single table has a FK pointing to a single table, like the master table.
There a huge web of relationships, and when I need to delete a record from the 'master' table, obviosly, there a lot of errors because of the relationships. All of them are set to 'Do nothing' on delete, so my question is, really, how safe is to change them (the relatioships) to delete on cascade instead of delete 'by hand' every single record on all of the tables affected?
I'm usyng MySql, last version (don't remmember exactly which one), and, if it works, PHP 5.2 and codeigniter.
Thanks a lot

A: It's all about businessrules.
If it is in your businessrules that a cascade delete should happen, I don't see why you program it by hand?
Of course, when programming by hand you can built in extra validations, but If you are not, deleting by hand only make thins more error-prone.
For one thing, when deleting 'by built in cascade' , the transaction is for free, you don't risk to leave orphans.


text:
Q: Redux-Form V6 - I can't access to form props in react-native I don't understand how can I access to form props. I used formValueSelector as suggested the documentation, but doesn't work. Where is my mistake? I'm using the latest version of redux-form.
LoginForm.js
'use strict';

import React from 'react';
import { Field, reduxForm, formValueSelector } from 'redux-form';
import { TextInput, View, TouchableHighlight, Text } from 'react-native';
import { connect } from 'react-redux';

class LoginForm extends React.Component {

    handeSubmit(email, password){ alert(`email: ${email} and password: ${password}`)};

    render() {

        return (
            <View>
                <Field
                    name="email"
                    component={TextInput}
                    placeholder="Email"
                />
                <Field
                    name="password"
                    component={TextInput}
                    placeholder="Password"
                    secureTextEntry={true}

                />
                <TouchableHighlight onPress={() => this.handeSubmit(this.props.email, this.props.password)}>
                    <Text>Submit</Text>
                </TouchableHighlight>
            </View>
        );
    }
}

LoginForm = reduxForm({
    form: 'loginForm'
})(LoginForm);

const selector = formValueSelector('loginForm');

function mapStateToProps(state){
    return {
        email: selector(state, 'email'),
        password: selector(state, 'password'),
    }
}

LoginForm = connect(mapStateToProps)(LoginForm);

export default LoginForm;

LoginPage.js
'use strict';

import React from 'react';
import {View} from 'react-native';
import Container from '../../components/Container';
import LoginForm from '../../components/forms/LoginForm';

class LoginPage extends React.Component {
  render() {
    return (
        <Container>
            <LoginForm/>
          </Container>
    );
  }
}

export default LoginPage;

Result:

I use alert(this.props) onPress button and this is the output. There aren't email and password.

and this is the output for
<TouchableHighlight onPress={() => alert(JSON.stringify(test))}>
                    <Text>Submit</Text>
 </TouchableHighlight>

function mapStateToProps(state){
    return {
        test: state.form.loginForm
    }
}

A: I found the solution. TextInput doesn't work with redux-form as it is. It need a component than pass the redux-form props like this:
TextField.js
class TextField extends React.Component {
      render(){
        const { input: { value, onChange } } = this.props; <----add this!!!
        return (
                <TextInput
                    style={[styles.textInput]}
                    onChangeText={(value) => onChange(value)} <----add this!!!
    add this!!!---> value={value} underlineColorAndroid="transparent" selectTextOnFocus={true} {...this.props}
                />
        );
    }
}

Instead of import TextInput inside the forms, import the custom TextField.


text:
Q: What's the Gauss-Greens-Theorem actually saying? Watching a video about harmonic functions I've seen the "Gauss-Greens-Theorem" written as:
$$\int_{B(a,b)}\text{div}\,F\,\mathrm{dx\,dy} = \int_{\partial B(a,b)}F_x\,\mathrm{dy}-F_y\,\mathrm{dx}$$
with $F$ a vector field: $F = \left(\begin{array}{c}F_x\\ F_y\end{array}\right)$ and $B$ a ball around it at position $(a,b)$
What's confusing me is the actual state of that Theorem, because it  seems to blend two claims:
$$\begin{align}
&\text{Greens Theorem:} \int_A \partial_x\,F_y
-\partial_y\,F_x \,\mathrm{dx\,dy} = \int_C F_x\,\mathrm{dx}+F_y\,\mathrm{dy} \\\\
&\text{Gauss Theorem:} \int_A \text{div}\,F\,\mathrm{dV} = \int_{\partial_A} \langle F, N\rangle\,\mathrm{dS}
\end{align}$$
I don't see how those come together.

A: The way you've phrased the Gauss/divergence theorem looks like it is in $3$D, but the situation here is one dimension less. Anyway, note that if we define $G=(-F_y,F_x)$, then we can apply Greens theorem as you have stated, but this time apply it to $G$ to obtain
\begin{align}
\int_{\partial B(a,b)}F_x\,dy-F_y\,dx&=\int_{\partial B(a,b)}G_y\,dy+G_x\,dx\\
&=\int_{B(a,b)}(\partial_xG_y-\partial_yG_x)\,dx\,dy\\
&=\int_{B(a,b)}\partial_xF_x+\partial_yF_y\,dx\,dy\\
&=\int_{B(a,b)}\text{div}(F)\,dx\,dy.
\end{align}


text:
Q: How to simplify query from excel to sqlite? How to achieved the same result in sqlite?
In excel I have this which count the headcount base on assigned letter code per day:

Here's my excel formula: =SUMIF(G$2:G$5,E9,$E$2:$E$5)

In my Sqlite database I have 3 tables:
TABLE 1
+----------------+---------------+--------+
| ID | status_name | status_code | status |
+----+-------------+-------------+--------+
| 1  | Available   | A           | true   |
+------------------+-------------+--------+
| 2  | HalfDay     | H           | true   |
+------------------+-------------+--------+
| 3  | On Leave    | OL          | true   |
+------------------+-------------+--------+
| 4  | Restday     | R           | true   |
+------------------+-------------+--------+
| 5  | Vacation    | V           | true   |
+------------------+-------------+--------+

TABLE 2
+--------------+-------+-------+------+----------+
| EmployeeName | Site  | Shift | Team | JobTitle |
+--------------+-------+-------+------+----------+
| Steve        | Bldg1 | Night | N1   | Doctor   |
+--------------+-------+-------+------+----------+
| Dave         | Bldg1 | Night | N2   | Nurse    |
+--------------+-------+-------+------+----------+
| Jack         | Bldg1 | Night | N2   | Nurse    |
+--------------+-------+-------+------+----------+
| Jacob        | Bldg2 | Day   | D1   | Doctor   |
+--------------+-------+-------+------+----------+
| Noah         | Bldg2 | Day   | D2   | Nurse    |
+--------------+-------+-------+------+----------+
| MAX          | Bldg2 | Day   | D2   | Nurse    |
+--------------+-------+-------+------+----------+

TABLE 3
+----------+-------+-------+------+-----+-----+-----+-----+-----+-----+-----+
| JobsType | Site  | Shift | Team | SUN | MON | TUE | WED | THU | FRI | SAT |
+----------+-------+-------+------+-----+-----+-----+-----+-----+-----+-----+
| Doctor   | Bldg1 | Night | N1   | A   | H   | A   | A   | OL  | A   | A   |
+----------+-------+-------+------+-----+-----+-----+-----+-----+-----+-----+
| Nurse    | Bldg1 | Night | N2   | A   | H   | H   | A   | A   | A   | A   |
+----------+-------+-------+------+-----+-----+-----+-----+-----+-----+-----+
| Doctor   | Bldg2 | Day   | D1   | H   | A   | H   | H   | A   | A   | OL  |
+----------+-------+-------+------+-----+-----+-----+-----+-----+-----+-----+
| Nurse    | Bldg1 | Night | N2   | A   | H   | H   | A   | A   | A   | A   |
+----------+-------+-------+------+-----+-----+-----+-----+-----+-----+-----+

By using the 3 tables above how could I achieved this result in query?
+--------------+-----+-----+-----+-----+-----+-----+-----+
| STATUS TYPES | SUN | MON | TUE | WED | THU | FRI | SAT |
+--------------+-----+-----+-----+-----+-----+-----+-----+
| Available    | 5   | 4   | 4   | 5   | 5   | 6   | 5   |
+--------------+-----+-----+-----+-----+-----+-----+-----+
| HalfDay      | 1   | 5   | 5   | 1   | 0   | 0   | 0   |
+--------------+-----+-----+-----+-----+-----+-----+-----+
| On Leave     | 0   | 0   | 0   | 0   | 1   | 0   | 1   |
+--------------+-----+-----+-----+-----+-----+-----+-----+
| Restday      | 0   | 0   | 0   | 0   | 0   | 0   | 0   |
+--------------+-----+-----+-----+-----+-----+-----+-----+
| Vacation     | 0   | 0   | 0   | 0   | 0   | 0   | 0   |
+--------------+-----+-----+-----+-----+-----+-----+-----+

So far I've come this;

    SELECT DISTINCT M.status_name, M.status_code, A.SUN, count(*),count(*) FROM TABLE3 M LEFT join TABLE2 A ON M.status_code= A.SUN LEFT join TABLE2 B ON (A.Team = B.Team AND A.Shift = B.Shift AND A.Site = B.Site)
WHERE M.product_status = 1
GROUP BY M.status_name;

A: First step, generate a test database (With a couple of helpful indexes):
CREATE TABLE status(id INTEGER PRIMARY KEY, status_name TEXT, status_code TEXT, status TEXT);
INSERT INTO status VALUES(1,'Available','A','true');
INSERT INTO status VALUES(2,'HalfDay','H','true');
INSERT INTO status VALUES(3,'On Leave','OL','true');
INSERT INTO status VALUES(4,'Restday','R','true');
INSERT INTO status VALUES(5,'Vacation','V','true');
CREATE TABLE employees(EmployeeName TEXT, Site TEXT, Shift TEXT, Team TEXT, JobTitle TEXT);
INSERT INTO employees VALUES('Steve','Bldg1','Night','N1','Doctor');
INSERT INTO employees VALUES('Dave','Bldg1','Night','N2','Nurse');
INSERT INTO employees VALUES('Jack','Bldg1','Night','N2','Nurse');
INSERT INTO employees VALUES('Jacob','Bldg2','Day','D1','Doctor');
INSERT INTO employees VALUES('Noah','Bldg2','Day','D2','Nurse');
INSERT INTO employees VALUES('MAX','Bldg2','Day','D2','Nurse');
CREATE TABLE schedule(JobsType TEXT, Site TEXT, Shift TEXT, Team TEXT, SUN TEXT, MON TEXT, TUE TEXT, WED TEXT, THU TEXT, FRI TEXT, SAT TEXT);
INSERT INTO schedule VALUES('Doctor','Bldg1','Night','N1','A','H','A','A','OL','A','A');
INSERT INTO schedule VALUES('Nurse','Bldg1','Night','N2','A','H','H','A','A','A','A');
INSERT INTO schedule VALUES('Doctor','Bldg2','Day','D1','H','A','H','H','A','A','OL');
INSERT INTO schedule VALUES('Nurse','Bldg1','Night','N2','A','H','H','A','A','A','A');
CREATE INDEX employees_idx ON employees(JobTitle, Site, Shift, Team);
CREATE INDEX status_idx_code ON status(status_code);

This query:
SELECT st.status_name, st.status_code
     , sum(sc.SUN = st.status_code) AS SUN
     , sum(sc.MON = st.status_code) AS MON
     , sum(sc.TUE = st.status_code) AS TUE
     , sum(sc.WED = st.status_code) AS WED
     , sum(sc.THU = st.status_code) AS THU
     , sum(sc.FRI = st.status_code) AS FRI
     , sum(sc.SAT = st.status_code) AS SAT
FROM status AS st
JOIN schedule AS sc ON st.status_code IN (sc.SUN, sc.MON, sc.TUE, sc.WED
                                        , sc.THU, sc.FRI, sc.SAT)
JOIN employees AS e ON sc.JobsType = e.JobTitle AND sc.Site = e.Site
                   AND sc.Shift = e.Shift AND sc.Team = e.Team
GROUP BY st.status_name, st.status_code
ORDER BY st.status_name, st.status_code;

will produce
status_name  status_code  SUN         MON         TUE         WED         THU         FRI         SAT
-----------  -----------  ----------  ----------  ----------  ----------  ----------  ----------  ----------
Available    A            5           1           1           5           5           6           5
HalfDay      H            1           5           5           1           0           0           0
On Leave     OL           0           0           0           0           1           0           1

How it works:
For each row in the status table, join each row in the schedule table that has that status for at least one day, and then join all rows from the employee table that match each schedule row's type of job (With this sample data, that results in a total of 14 rows being generated). Then group all the rows on the status, and for each day, add up the number of rows in that group where the schedule code for that day matches the status.


text:
Q: TableLayout divide space without stretching the button? I want the buttons to be their original size (wrap content), but them to be aligned in that logical cell location. Is that possible? I mean, I want something like,
|[Lisa]_______|[Simpson]____|

not,
|[___Lisa____]|[__Simpson__]|

or,
|[Lisa]|[Simpson]___________|

The following code did not work.
<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TableRow>
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Lisa"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Simpson"/>
    </TableRow>

A: TableLayout centers its items by default. What you can use is a LinearLayout, like this:
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Lisa"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="Simpson"/>

</LinearLayout>

This divides the space of the two buttons evenly, but does not center each button. This is how it looks.


text: Q: Any examples of using material Autocomplete in material table rows in Angular 4 I am trying to build a page with  material  table with  material Autocomplete coming in every row. I don't know any sample code that does that. Can you provide me any references on how to implement this?


text:
Q: How do I find this span with selenium in python? Just wondering how to get the span text out of this div when using selenium in python.
<div class="clsFrameworkElement"
id="ManagedQuestionViewer.brdrQuestion1.QuestionRenderer.MultiChoiceQuestionViewer.sp.StackPanel.RadioTextRegionViewer2.LayoutRoot.Panel.text.sp.rich.LayoutRoot.TextBlock" style="overflow: visible; display: inherit; text-shadow: white 0px 1px; left: 46px; top: 105px; border-width: 0px; width: 186px; height: 15px; text-align: left; color: rgb(0, 0, 0); font-family: Tahoma; font-weight: normal; font-size: 9.6pt; text-overflow: clip; overflow-wrap: break-word; white-space: normal; user-select: none;">
Get a non-disclosure agreement.

Thanks.

A: You can use xpath to get the span element.
Please see below snippet:
from selenium import webdriver

driver =  webdriver.Chrome()
html_content = """

         <div class="clsFrameworkElement" id="ManagedQuestionViewer.brdrQuestion1.QuestionRenderer.MultiChoiceQuestionViewer.sp.StackPanel.RadioTextRegionViewer2.LayoutRoot.Panel.text.sp.rich.LayoutRoot.TextBlock" style="overflow: visible; display: inherit; text-shadow: white 0px 1px; left: 46px; top: 105px; border-width: 0px; width: 186px; height: 15px; text-align: left; color: rgb(0, 0, 0); font-family: Tahoma; font-weight: normal; font-size: 9.6pt; text-overflow: clip; overflow-wrap: break-word; white-space: normal; user-select: none;">
            Get a non-disclosure agreement.

"""

driver.get("data:text/html;charset=utf-8,{html_content}".format(html_content=html_content))

node = driver.find_element_by_xpath("//div[@class='clsFrameworkElement']/span")
print(node.text)

This will print :
Get a non-disclosure agreement.

You can read more about xpath here: https://selenium-python.readthedocs.io/locating-elements.html


text:
Q: Can Virtual Classes in C++ have Member Variables? Suppose I have a purely virtual class, can I do something like this in C++:
class ITreatable
{
    public:
       bool hasBeenTreated;           // <- Can this be here?
       virtual bool Treat() = 0;
};

And if not, how can I ensure that classes which inherit ITreatable have a member variable called hasBeenTreated? Is that possible? Is there some kind of best practice that avoid having to do this / advises against it?
Thanks
Edit: Also how would I define a constructor for such a class?
Edit2: I understand that public member variables are bad practice, I'm just wondering if the design in general is a good idea in C++ or not.

A: Acordingly to MSDN an interface has these characteristics:

*

*An interface class (or struct) must be declared within a namespace
and may have public or private accessibility. Only public interfaces
are emitted to metadata.

*The members of an interface can include properties, methods, and
events.

*All interface members are implicitly public and virtual.

*Fields and static members are not permitted.

*Types that are used as properties, method parameters, or return
values can only be Windows Runtime types; this includes the
fundamental types and enum class types.

So I would response to your question with

NO if you want an interface

and

Yes if you just use abstract classes, but as the others say, make them private and use public getters and setters

A: Absolutely.
Strictly speaking, there is no such thing as a "virtual class". I understand that you are using the term to mean a class constructed of only data members and virtual member functions.
Consider that only functions can be virtual; if you wish for data members to be accessed polymorphically, you must do this through functions. Thus, use virtual getter/setter functions, and keep your data members private.

A: Yes.
There is no concept of a "pure virtual" class in C++, merely abstract classes with virtual members.
As for whether there is a best practice, I would say that the biggest practice that should be followed in this example is not to use public variables. Rather, have a setter/getter defined in the base class that modifies a private variable.

A: That is possible. C++ doesn't have interfaces enforced by the language, so your example acts like normal class definition without any special rules.
It's considered bad practice to declare variables as public in classes. You might want to make it private and declare accessor/mutator for it or declare it as protected.


text:
Q: Create guest order in the backend with magento Is it possible to create an order for guests in the backend without the customer email?
I know how to create orders for registered or new users but most of the time I need to create an order without knowing the customer's email.
Thanks

A: Without making changes to the code, you could achieve this by using an internal convention (similar to @Joseph's answer but a little cleaner) e.g.
firstname.lastname@guest.insertstoredomainnamehere.com
You could configure your mail server or MX records to drop emails sent to the "guest." subdomain.

A: Magento requires an email address to complete an order (and uses that email address elsewhere, depending on it entirely). You could hack it by using some store email address or a temporary email address, but you'll have to enter one.

A: If you remove the javascript required field validation from the email address when placing admin orders, Magento will generate a dummy email address for the customer.
This functionality looks to be deprecated as of 1.4.0.0 so test this on your version.


text:
Q: Migrating SAS Reports Into SSRS I am very new to working with SAS, have not worked with it before. My current workplace is asking me to migrate reports over from SAS and rework them using SSIS/SSRS. I'm not sure how would be the best way to go about this or where even to start. Any help would be appreciated.
Thanks!

A: You will need to look at the data sources and the report outputs and figure out what is required to manually recreate the reports from scratch in SQL and SSRS.  There is no conversion tool available.


text:
Q: Windows versus Mac specific fonts in Java GUI It turns out that the font as well as bounds I've used to create my GUI on my Mac are completely different than those of a Windows computer.
So the GUI on my Mac looks completely different than when run on a Windows computer.
Is there any way at all to fix this issue, while still using my preferred font?


text:
Q: How can I reverse certain letters in a string using excel function I have a very simple request, please help.
Currently I have the following string in excel "17-May-10", and I need it to be "10-May-17". So as you can see just reverse the 17 and 10. Can someone let me know how to do this by only using excel functions? Thanks in advance!
G

A: If you want to make actual change and not just visual:
=RIGHT(A1,LEN(A1)-FIND("@",SUBSTITUTE(A1,"-","@",(LEN(A1)-LEN(SUBSTITUTE(A1,"-",""))))))&"-"&MID(A1,FIND("-",A1)+1,FIND("@",SUBSTITUTE(A1,"-","@",(LEN(A1)-LEN(SUBSTITUTE(A1,"-","")))))-FIND("-",A1)-1)&"-"&LEFT(A1,2)

A: What about using REPLACE
=REPLACE(REPLACE(A2,1,2,(RIGHT(A2,2))),(LEN(A2)-1),2,LEFT(A2,2))
see this example:

data used:
input       output
17-May-10   10-May-17

A: This one formula would work for both the cases, when the date is entered as a string or as a date itself,
=TEXT(A1,"yy-mmm-dd")
As Date:

As String:


text:
Q: Relative paths using requirejs in combination with Typescript and AMD There are several Javascript files, organized in folders Scripts/folder1, Scripts/folder2, ...
With requirejs.config.baseUrl a folder is defined as the default, for example Scripts/folder1. Then in requirejs.config.paths some files are addressed with just the filename, and some are addressed with a relative path (like ../folder2/blabla).
When coding the Typescipt file folder2/blabla.ts we need the module "math" from folder1. So we write
import MOD1 = module("../folder1/math");

Regarding Typescript, anything is fine with that. It can find the module. However, with requirejs there is a problem. It does not know the module "../folder1/math", it only knows "math".
The problem seems to be that the import statement expects a filename, being adressed by starting from the current directory. However, this isn't the module id that requirejs knows about.
Using absolute paths anywhere, both in the requirejs configuration and the import statement in Typescript, solves the problem.
Am I doing this wrong? Or are absolute paths the way to go?

A: Specify a baseUrl to be equivalent to the root folder of your Typescript files:
require.config({
    baseUrl: './scripts',
 }
)

Then when you use relative paths starting from the scripts folder you can just do import like you normally do in typescript and requirejs will be using the same base path.
Update: This presentation should should answer all your url / using js from Typescript questions: http://www.youtube.com/watch?v=4AGQpv0MKsA with code : https://github.com/basarat/typescript-amd/blob/master/README.md

A: In you require configuration specify paths for each module. That should solve paths problem:
require.config({
    paths: {
        jquery: 'libs/jquery-1.7.1.min',
        jqueryui: 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min'
        // Other modules...
    }
});


text:
Q: How is the output 47? #include<stdio.h>
#include<conio.h>
#define FIRST_PART 7
#define LAST_PART 5
#define ALL_PARTS FIRST_PART+LAST_PART
 int main()
 {
    printf ("The Square root of all parts is %d", ALL_PARTS * ALL_PARTS) ;
    getch();
    return(0);
}

In the above code the FIRST_PART is defined as 7
LAST_PART is defined as 5
and ALL_PARTS is initialized as FIRST_PART+LAST_PART (which is ideally 12)
but when i am printing ALL_PARTS * ALL_PARTS is giving me 47 as the output!(But i thought answer would be 144)
Please can anyone explain me how ?

A: The answer should be 47
FIRST_PART + LAST_PART * FIRST_PART + LAST_PART

MULTIPLICATION HAS MORE PRECEDENCE

SO 7 + 5 * 7 + 5

 7 + 35 + 5

47


text:
Q: keys virtually "stuck" after remapping /situation
I'm on this problem since several days, and to the point of considering switching back to Windows (which would make me sad, as i haven't used it since... 2010, iirc - but WoW Classic is coming, guys, i just can't pass that).
I'm not tech-savvy. I use something *buntu related since forever (currently Xubuntu), and it's usually good enough for me.
So, even if i'm a linux user since nearly a decade, please, eli5.
/configuration
I use a keyboard, a mice (currently Roccat Nyth), and a Tartarus Chroma v2 (a sort of mini keyboard for just one hand). And other input peripherals non related to my problem.
When i play WoW, it's with Tartarus+mice. I barely touch the keyboard.
The Tartarus, by default, is mapped as a regular keyboard, which is unsuitable for my needs.
It don't have any usable driver for linux (openrazer have an open issue for the Tartarus since years, so i don't expect it to work soon, if ever).
But it can be remapped with xkbcomp, as i learned on this page: https://lampjs.wordpress.com/2015/06/26/remapchange-your-secondaryusb-keyboard-keys/
There is my dump (without remapping) xkb file: https://pastebin.com/XpR9RDPd
There is my remapped file: https://pastebin.com/3pXSKiWX
It seem to work: checking with xev, i can confirm i have the remapped keys i want on the Tartarus, while the regular keyboard keys are unchanged.
/problem
When i use any key of the Tartarus with any modifier (shift, ctrl, alt), it switch back to it's unmapped state, and became "stuck" in that state until i press the physical key who is bind to that unmapped state (usually on my regular keyboard, but it also work with the Tartarus), to "unstuck" it (and it also make it switch back to it's mapped state).
If i unmap the Tartarus, i can't reproduce the problem, so i highly suspect my configuration file to be bad. But i have no idea what's wrong in it... I read the Arch Wiki page about xkbcomp, but barely understood it.
Help! ^^

A: Can you try using evtest in terminal first? After that
sudo apt-get install evtest

and then select the USB device. This will get the raw USB input.
I like this idea and I want to remap the keyboard via MIDI signal and patchbank/encryptions to prevent keyloggers.
It may have something to do with the IRQ interrupt request for keyboard input.


text:
Q: Is it a best practice to refactor an Interface method -- extracting a code fragment of a Interface method to create a new wrapping method? From MSDN, I got an example as follows:
IEnumerator IEnumerable.GetEnumerator()
{
   return (IEnumerator) GetEnumerator();
}

public PeopleEnum GetEnumerator()
{
    return new PeopleEnum(_people);
}

Why did the author do like this? Is it a best practice?
--------EDIT---------
MSDN article link : http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx
Why didn't the author do as follows:
 IEnumerator IEnumerable.GetEnumerator()
 {
        return new PeopleEnum(_people);
 }

I tried,  it still works.
======= SECOND EDIT ==========
using System;
using System.Collections;

namespace MyEnumerableEnumerator
{
    class Person
    {
        public Person(string name, int age)
        {
            Name = name;
            Age = age;
        }

        public string Name { get; set; }
        public int Age { get; set; }
    }

    class PeopleEnumerator : IEnumerator
    {
        int Position { get; set; }
        Person[] People { get; set; }
        int Length { get; set; }

        public PeopleEnumerator(Person[] people)
        {
            People = people;
            Position = -1;
            Length = people.Length;
        }

        public bool MoveNext()
        {
            Position++;
            return Position < Length;
        }

        public void Reset()
        {
            Position = -1;
        }

        public object Current
        {
            get
            {
                try
                {
                    return People[Position];
                }
                catch (IndexOutOfRangeException)
                {
                    throw new InvalidOperationException();
                }
            }
        }
    }

    class People : IEnumerable
    {
        Person[] Persons { get; set; }

        public People(Person[] people)
        {
            Persons = new Person[people.Length];

            for (int x = 0; x < people.Length; x++)
                Persons[x] = people[x];
        }

        //public IEnumerator GetEnumerator()
        //{
        //    return new PeopleEnumerator(Persons);
        //}

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }

        private IEnumerator GetEnumerator()
        {
            return new PeopleEnumerator(Persons);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {

            Person[] persons = { new Person("Mark", 1), new Person("Siva", 2) };

            People people = new People(persons);

            foreach (Person person in people)
            {
                Console.WriteLine("Name: {0}, Age: {1}", person.Name, person.Age);
            }

        }
    }
}

A: They did as they did because they wanted a typed iterator for a non-generic collection.
Edit
foreach works since the compiler does some "magic"
Try this with your changed code:
        var enumerator = peopleList.GetEnumerator();
        while (enumerator.MoveNext())
            Console.WriteLine(enumerator.Current.firstName); //compile error.

It will not compile, you have to cast the enumerator to PeopleEnum or change back the return type.
Edit 2
You can read about foreach's implicit type casting here:
http://www.dev102.com/2009/07/28/pay-attention-to-the-foreach-implicit-casting/
http://csharpindepth.com/ViewNote.aspx?NoteID=1
And in the specification: http://msdn.microsoft.com/en-us/library/bb308966.aspx
Scroll down to last section in 26.1

A: Instead you can simply alter the code To:
IEnumerator IEnumerable.GetEnumerator()
   {
      return new PeopleEnum(_people);
   }

OR  To:
public IEnumerator GetEnumerator()
{
   return new PeopleEnum(_people);
}

Since, there the IEnumerable interface is being imherited, we cant omit the implementaion for GetEnumerator() method.

A: Thats actually explicit interface implementation


text:
Q: The connection does not support MultipleActiveResultSets error while saveChanges in.net Core I have exceptionMiddleware. And it logging all errors to database. But, when working firstly it working perfectly but at second try gave me error during SaveChangesAsync to database. What can be the reason of this error.
Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency
 injection and then later trying to use the same context instance elsewhere in your application. This may occur if you
 are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection,
 you should let the dependency injection container take care of disposing context instances.
Object name: 'MyDbContext'.
'The connection does not support MultipleActiveResultSets.'
MyDbContext.cs
public class MyDbContext : DbContext
{
    private readonly IAuditHelper auditHelper;

    public MyDbContext(DbContextOptions<MyDbContext> options, IAuditHelper auditHelper)
        : base(GetOptions())
    {
        this.auditHelper = auditHelper;
    }

    private static DbContextOptions GetOptions()
    {
        return SqlServerDbContextOptionsExtensions.UseSqlServer(new DbContextOptionsBuilder(), "server=asdf; database=asdf; user id=asdf; password=asdf").Options;
    }

    public async Task<int> SaveChangesWithoutAuditAsync(CancellationToken cancellationToken = default(CancellationToken))
    {
        return (await base.SaveChangesAsync(true, cancellationToken));
    }
}

Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpContextAccessor();
    services.AddScoped<IUnitOfWork, UnitOfWork>();
    services.AddScoped<IJwtHelper, JwtHelper>();
    services.AddScoped<IAuditHelper, AuditHelper>();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    services.AddDbContext<MyDbContext>();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IHttpContextAccessor httpContextAccessor)
{
    app.ConfigureCustomExceptionMiddleware();

    app.UseHttpsRedirection();
    app.UseMvc();
}

ExceptionMiddleware.cs
public class ExceptionMiddleware
{
    private readonly RequestDelegate _next;

    public ExceptionMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext httpContext, IUnitOfWork unitOfWork, IJwtHelper jwtHelper)
    {
        try
        {
            await _next(httpContext);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(httpContext, ex, unitOfWork, jwtHelper);
        }
    }

    private Task HandleExceptionAsync(HttpContext context, Exception exception, IUnitOfWork unitOfWork, IJwtHelper jwtHelper)
    {
        Log log = new Log();
        log.UserIp = jwtHelper.GetValueFromToken("UserIp");

        unitOfWork.LogRepo.AddOrUpdate(log);
        unitOfWork.CompleteAsync();

        return context.Response.WriteAsync(exception.Message);
    }
}

A: I found the problem. Problem is HandleExceptionAsync method. It must added aync and await like this:
  private async Task HandleExceptionAsync(HttpContext context, Exception exception, IUnitOfWork unitOfWork, IJwtHelper jwtHelper)
    {
        Log log = new Log();
        log.UserIp = jwtHelper.GetValueFromToken("UserIp");

        unitOfWork.LogRepo.AddOrUpdate(log);
        await unitOfWork.CompleteAsync();
        await context.Response.WriteAsync(exception.Message);

        return ;
    }


text:
Q: Individually Identifying JButtons in a GridLayout I have been creating a system by which I am listing various seats on a train within a GUI. I had decided to use a simple grid layout with numbered JButtons representing the seats and the seatNo and empty JLabels to represent empty space (I realise this may be trivial but it was simple). I have used a Gridlayout and I have created the Buttons and Labels as shown below.
I have an List (compArray2) in a separate class that consists of 0s and 1s and a direction that represent where there should be a seat and where the shouldn't be a seat. the .getNum gets the value either 0 for empty space or 1 for a seat and the .getDir gets the direction the seat will be facing.
public JPanel rowPanelCreation(int type, int rowNo, int width){

    theNoOfSeats=0;
    JPanel panel = new JPanel();
    panel.setLayout(new GridLayout(0,width));

    List<seatLayout> layout = new ArrayList<>();
    layout = ModelConstants.compArray2;

    for (seatLayout isit : x2){

        buttonEna = new JButton();
            buttonEna.setFont(new Font("Sans Serif", Font.BOLD , 14));
            buttonEna.setBorderPainted(false);
        buttonDis = new JLabel();

        if (isit.getNum()==0){
            if (isit.getDir()=='x'){
            panel.add(buttonDis);
            }
        }

        else if (isit.getNum()==1){

            theNoOfSeats++;

            if (isit.getDir()=='N'){
                image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultN.png");
                buttonEna.setIcon(image);
                buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
                buttonEna.setHorizontalTextPosition(JButton.CENTER);
                buttonEna.setVerticalTextPosition(JButton.CENTER);
                panel.add(buttonEna);
                }
            else if (isit.getDir()=='E'){
                image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultE.png");
                buttonEna.setIcon(image);
                buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
                buttonEna.setHorizontalTextPosition(JButton.CENTER);
                buttonEna.setVerticalTextPosition(JButton.CENTER);
                buttonEna.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){JOptionPane.showMessageDialog(null,"You have chosen : ");}});
                panel.add(buttonEna);
                }
            else if (isit.getDir()=='S'){
                image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultS.png");
                buttonEna.setIcon(image);
                buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
                buttonEna.setHorizontalTextPosition(JButton.CENTER);
                buttonEna.setVerticalTextPosition(JButton.CENTER);
                panel.add(buttonEna);
                }
            else if (isit.getDir()=='W'){
                image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultW.png");
                buttonEna.setIcon(image);
                buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
                buttonEna.setHorizontalTextPosition(JButton.CENTER);
                buttonEna.setVerticalTextPosition(JButton.CENTER);
                panel.add(buttonEna);
                }
        }
    }
    return panel;
}

the main problem I am having is that when I press one of the seat buttons I want a message to appear telling me the seatNo of the seat I have selected is. However when I do this it simply displays the very last seatNo. Is there a better way I could do this ? I'm assuming that as all the buttons are fundamentally the same, there is no way to differentiate between them ?

A:
"I want a message to appear telling me the seatNo of the seat I have selected is. However when I do this it simply displays the very last seatNo."

Here's your problem. It's a reference problem. In the end, all the buttons will have the same JButton and JLabel reference. So all the buttons and labels will get the last button and label reference created, hence "displays the very last seatNo."
buttonEna = new JButton();
buttonEna.setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
buttonDis = new JLabel();

You need to create a new JButton and new JLabel reference each iteration
JBUtton buttonEna = new JButton();
buttonEna.setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
JLabel buttonDis = new JLabel();

Another approach would be to have an array of JButton, loop to set the buttons, and add them to the Panel. Say you have a GridLayout(2, 2). You then would need a array of 4 JButtons
JButton[] buttons = new JButton[9];
...
for (int i = 0; i < 4; i++){
    buttons[i] = new JButton();
    buttons[i].setFont(new Font("Sans Serif", Font.BOLD , 14));
    buttonEna.setBorderPainted(false);
    // set other properties for button
    panel.add(buttons[i]);
}


text:
Q: Who played Hedwig? In the Harry Potter movies, was their a specific owl, or owls that played Hedwig? What are their name/names and in what movies did they appears?

A: There were actually at least eight different animal actors used to portray Hedwig throughout the Harry Potter movies, but Gizmo seems to have been the primary animal actor.
This article about animals in the HP movies explains:

Seven were needed to play Hedwig, the owl Hagrid purchased for the young wizard prodigy: named Gizmo, Kasper, Oops, Swoops, Oh Oh, Elmo and Bandit.

This other article mentions an eigth - White Terror Of The North. Why he was not mentioned in the other article is not clear, but he did not appear in The Sorcerer's Stone.

He starred in all the Harry Potter movies but the first

This same article mentions that there were nine owls used, but does not identify the others by name.

He was the more enthusiastic of the 9 owl actors that played Hedwig

The book The Animal Movies Guide mentions that Gizmo was the primary animal actor during The Sorceror's Stone.

Harry's own owl familiar is a snow named Hedwig, who was played mainly by Gizmo (Gizmo was doubled by Kasper, Oops, Swoops, Oh-Oh, Elmo, and Bandit).

This interview with the animal trainer for two of the HP movies backs this up

Q: For Harry's owl—Hedwig#151how many owls played Hedwig, or did you use just one?
Gary: There really is just one Hedwig—his real name is Gizmo. He has a couple of helpers that help him out with the different things. We have a lighting stand-in, so he doesn't have to do all of the lighting. And we have a couple of owls that will help him with his flying shots, so he doesn't have to do all of the flying shots himself.

HP Wikia mentions the possible ninth owl, Sprout, but the linked source does not actually make any mention of an owl by that name.


text:
Q: Why don't .swiper-button-prev and .swiper-button-next work? js Fiddle: https://jsfiddle.net/rfbvL4gj/7/
I have slider with images inside it. And when I click on the one of the images, all content is hidden, and it's shown .layer element with second big-scaled slider with the same images.
But there's one problem: when I click on .swiper-button-next and .swiper-button-prev of the big-scaled slider nothing happens. I've no idea what's wrong.
JS:
let album_images_slider = new Swiper("#album_images_slider", {
    direction: "horizontal",
    slidesPerView: 1,
    loop: true,
    allowTouchMove: false,
    speed: 600,
    autoplay: {
        delay: 3000
    },

    navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev"
    }
});

let album_images_slider_scale = new Swiper("#album_images_slider_scale", {
    direction: "horizontal",
    slidesPerView: 1,
    loop: true,
    allowTouchMove: false,
    speed: 600,
    autoplay: {
        delay: 3000
    },

    navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev"
    }
});

$("#album_images_slider").click(function(e) {
        if (e.target.nodeName == "IMG") {
            $("body *").hide();
            $("body").prepend(`<div class="layer"></div>`);
            $(".layer").append(`

Slide 1

Slide 2

Slide 3

Slide 4

            `);
        }
    });

    $("body").on("click", ".layer", function(event) {
        let target = event.target;
        if (!($(".swiper-container").has(target).length || $(target).hasClass("swiper-container")))                 {
            $(".layer").remove();
            $("body *").show();

        }
        if ($(target).hasClass("swiper-button-next")) {
            console.log("next");
        }
        else if ($(target).hasClass("swiper-button-prev")) {
            console.log("prev");
        }
    });

A: JavaScript is Synchronous
If you want to insert specified content (Swiper HTML in your case) and than "do somehing" related to this content the order should be:

*

*Jquery append()

*"do something" on the append DOM node ("swiper slider" in your case).

Not working:
$("b").css("background-color", "yellow");
$("p").append(" Appended text.");

Working:
$("p").append(" Appended text.");
$("b").css("background-color", "yellow");

Broken code example.

In your case, the order is 2 then 1.
Related:
jQuery function after .append
Hello world example

$(".layer").append(`

Slide 1

Slide 2

`);

var swiper = new Swiper('.swiper-container', {
  navigation: {
    nextEl: '.swiper-button-next',
    prevEl: '.swiper-button-prev',
  }
});

<link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css">


text:
Q: Custom view embeed in a Navigation Bar I'm trying to create a navigation bar that looks like (and with the same behaviour) of the Apple one used in the Calendar App.
In particular (see pictures below):

Starting navigation bar

Ending navigation bar (after push)

I have tried to subclass the UINavigationBar and override the sizeThatFits(rect:CGrect)method. This will increase the bar hight but the result with the custom view is not ok, as well as the animation between the "pop/push" and the button alignments (the button stay aligned down instead of up). That solution seems to be a real mess.
Do you now a better solution to embed a custom view in the navbar (exactly how is represented in the images) and make this view part of the navbar animation as well?
edit
I also find these olds questions that may be useful:
Change iPhone navigation bar's height,
Change UINavigationBar Height,
Also the resizable-navigation-bar that you can find here on GitHub can be useful
Better solutions are welcome

A: I maybe found a good solution provided by Apple itself to fix this "problem".
HERE you can find a sample code about how customise UINavigationBar without interfere too much with orientation, retrocompatibility etc..
Just download the sample code and see the Extended Navbar Example.
If few words they create a custom view attached to the navigation bar that looks like the navbar itself. Apple explain clearly:
This example demonstrates placing a custom view underneath the navigation bar in such a manner that view appears to be part of the navigation bar itself.  This technique may be used to create an interface similar to the iOS Calendar app.
I still don't understand how to achieve the correct push animation with this solution but it could be a good starting point. Anyway, this is NOT an embed view.


text:
Q: Dirichlet integral integrates to $\pi$ I think the question has been asked several times on MSE since seems a standard fourier analysis fact, but I don't find any reference for it.
Let's consider the Dirichlet Kernel as $$D_n(x) := \sum\limits_{\lvert k \rvert \leq n}e^{ikx}$$
In a further proposition I think it's used something like $$\int_0^{\pi} D_n(x)dx = \pi$$
Is this true? I tried to computed this explicitly or using $$D_n(x) = \frac{\text{sin}\left(\left(n+\frac{1}{2}\right)x\right)}{\text{sin}(\frac{x}{2})} \hspace{0.2cm} \forall x\ne 0 \hspace{0.2cm} \text{mod} 2\pi$$
But I got stuck since the integral of the part relative to $\text{cos}$ is $0$, since integrate to $\text{sin}$, and the part relative to $\text{cos}$ depends on $k$ but the $i$ term remains.
Where is my mistake? And how to prove $$\int_0^{\pi} D_n(x)dx = \pi$$ if true
?

A: The truncated Fourier series $S_n(x)$ for a function $f$ on $[-\pi,\pi]$ is given by
\begin{align}
            S_N(f)(x)&=      \sum_{n=-N}^{N}\frac{1}{2\pi}\int_{-\pi}^{\pi}f(y)e^{-iny}dy e^{inx} \\
      &=\frac{1}{2\pi}\int_{-\pi}^{\pi}f(y)\sum_{n=-N}^{N}e^{in(x-y)}dy \\
      &=\frac{1}{2\pi}\int_{-\pi}^{\pi}f(y)D_N(x-y)dy
\end{align}
That defines the Dirichlet kernel $D_N (x)=\sum_{n=-N}^{N}e^{inx}$. Notice that $D_N(x)=D_N(-x)$ is an even function, and $\int_{-\pi}^{\pi}D_N(x)dx=2\pi$ because it gives you $2\pi$ times the truncated Fourier series of $1$, which is $2\pi$ for $N \ge 1$. So,
$$
 \int_0^\pi D_N(x)dx=\frac{1}{2}\int_{-\pi}^{\pi}D_N(x)dx=\frac{2\pi}{2}=\pi.
$$


text:
Q: PyTorch, AttributeError: module 'shape' has no attribute '' I'm just trying to run the MNIST code on a GPU. The version for python in my conda environment is 3.8 and for PyTorch it's 1.8, so they are both pretty updated. The example_data is the MNIST dataset, and I was able to get torch.Size([1000, 1, 28, 28]) as the result for example_data.shape on Jupyter Lab.
So what could be the reason that I'm getting this error message? Thanks!
Traceback (most recent call last):
  File "MNIST5.py", line 45, in <module>
    example_data.shape
AttributeError: 'torch.FloatTensor' object has no attribute 'shape'

Here is the part of the code that caused the problem. I got it from a tutorial online, and it basically just downloaded the datasets and try to get the shape of it.
train_loader = torch.utils.data.DataLoader(
  torchvision.datasets.MNIST('/files/', train=True, download=True,
                             transform=torchvision.transforms.Compose([
                               torchvision.transforms.ToTensor(),
                               torchvision.transforms.Normalize(
                                 (0.1307,), (0.3081,))
                             ])),
  batch_size=batch_size_train, shuffle=True)

examples = enumerate(test_loader)

batch_idx, (example_data, example_targets) = next(examples)
example_data.shape


text:
Q: TabsListener not working as it should be I am new to Android so please explain in detail
I want to build a basic Android app which uses Tabs.
I have built a TabListener.
But it is showing me an error. How can i fix it?
Here is the code:
package com.adhish.tabs1;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.support.v7.app.ActionBar.TabListener;
import android.support.v7.app.ActionBar.Tab;
import android.widget.Toast;

@SuppressLint("NewApi")
public class MyTabsListener implements TabListener {

public Fragment fragment;

//Create fragment for Activity
public MyTabsListener(Fragment fragment)
{
    this.fragment = fragment;
}

public void onTabReselected(Tab tab, FragmentTransaction transaction)
{
    Toast.makeText(ActionBarImpl.myContext, "You have clicked again !", Toast.LENGTH_SHORT).show();
}

public void onTabSelected(Tab tab, FragmentTransaction transaction)
{
    transaction.replace(R.id.actionbar, fragment);
}

public void onTabUnselected(Tab tab, FragmentTransaction transaction)
{
    transaction.remove(fragment);
}
}

The error is in the declaration of this class:
Class MyTabsListener must be declared either Abstract or implement Abstract method
'onTabSelected(Tab, FragmentTransaction)' in 'TabListener'.

Please help me to workaround this issue.


text:
Q: put three div next to each other but left and right divs must repeat to edge of browser http://dentaliran.ir/back-final-mata.gif
above image is for header of a website,
as you can see it's 3 part
left
center
right
how can we put this three part in 3 div but left and right part must repeated to the edge of browser?
for fixed width we can put three die next to each other like this:
#wrapper
{
    width:1000px;
    margin:0 auto;

}
#left
{
     background:url(pics/left.jpg) repeat-x;
     height:192px;
     width:100px;
     float:left;
}
#center
{
    background:url(pics/center.gif) no-repeat;
    height:178px;
    width:800px;
    float:left;

}
#right
{
     background:url(pics/right.jpg) repeat-x;
     height:192px;
     width:100px;
     float:left;
}

but what about when left and right haven't fixed width and must be repeated unlimited?
thanks a lot

A: use min-width instead of width

A: Some absolute positioning would sort it.
You could apply the left background image repeated to the body tag
the right background, I'd put it in a div, position absolute to the top,
body {
    background:url(pics/left.jpg) repeat-x;
}

#right{
    background:url(pics/right.jpg) repeat-x;
    position: absolute;
    top: 0px;
    right: -50%;
    height: 100px;
    width:100%;
    z-index: -1;
}

A: You should change this a bit: http://jsfiddle.net/maximgladkov/6GE3x/1/
HTML

CSS
div {
    height: 100px;
}

#wrapper {
    display: table;
    table-layout: fixed;
    width: 100%;
}

#left, #center, #right {
    display: table-cell;
}

#center {
    width: 200px;
}

#left {
    background: url(http://upload.wikimedia.org/wikipedia/commons/thumb/2/29/MARPAT_woodland_pattern.jpg/50px-MARPAT_woodland_pattern.jpg) repeat-x;
}

#center {
    background: url(http://3.bp.blogspot.com/-Q11tJy3fAhA/UUnEu5Q3BtI/AAAAAAAAFEQ/TPBl0Sd5V9I/s1600/dark-brown-wood-pattern.jpg) no-repeat center center;
    background-size: cover;
}

#right {
    background: url(http://upload.wikimedia.org/wikipedia/commons/thumb/2/29/MARPAT_woodland_pattern.jpg/50px-MARPAT_woodland_pattern.jpg) repeat-x;
}


text:
Q: how to expand multiple properties when output contains @{, }? I know there's a number of posts about expanding a single property and hopefully this is an easy one but my output looks like this as a result of a
select-string -simplematch

@{Brand=Volkswagen; Model=Passat}
@{Brand=Ford; Model=Mondeo}

But how do I expand both properties and get the output to look like this please?

Volkswagen, Passat
Ford, Mondeo

When I do a select-object * I get the below but I cant seem to get just the values

IgnoreCase : True
Linenumber : 1
Line : @{Brand=Volkswagen; Model=Passat}
Filename : InputStream
Path : InputStream
Pattern : @{Brand=Volkwagen; Model=Passat}
Context :
Match : {}}
IgnoreCase : True
Linenumber : 2
Line : @{Brand=Ford; Model=Mondeo}
Filename : InputStream
Path : InputStream
Pattern : @{Brand=Ford; Model=Mondeo}
Context :
Match : {}}

A: Don't do select-string on a collection of PsObjects, because that cmdlet is designed for finding text in strings and files..
Select-Object -ExpandProperty lets you expand one property, not all.
If you want output like that, loop over the objects in the array and combine the properties the way you want them into a string.
Assume your array is like this:
$theCarCollection = [PsCustomObject]@{Brand='Volkswagen'; Model='Passat'},
                    [PsCustomObject]@{Brand='Ford'; Model='Mondeo'}

Then format the output by looping over the objects and selecting the properties you need
($theCarCollection | ForEach-Object { '{0}, {1}' -f $_.Brand, $_.Model }) -join [environment]::NewLine

which will output:
Volkswagen, Passat
Ford, Mondeo

A: may be somthing lie this :
Select-String -Path "C:\temp\test.txt" -Pattern "test" | select line -ExpandProperty line

A: To complement Theo's helpful answer:
tl;dr:
# Note the use of -PipelineVariable obj and the use of $obj later.
PS> Write-Output -PipelineVariable obj (
      [pscustomobject] @{ Brand = 'Volkswagen'; Model = 'Passat' },
      [pscustomobject] @{ Brand = 'Ford'; Model = 'Mondeo' }
    ) |
      Select-String -SimpleMatch wagen |
        ForEach-Object { $obj.psobject.Properties.Value -join ', ' }

Volkswagen, Passat

The Write-Output command is just a stand-in for the actual command that produces the input objects for Select-String in your code, such as Import-Csv.

*

*Your Select-String output implies that [pscustomobject] instances served as its input, such as output by Import-Csv, for instance.

*

*E.g., your output implies an input object such as
[pscustomobject] @{ Brand = 'Volkswagen'; Model = 'Passat' }

*As Theo notes, Select-String is designed to operate on strings, not on objects with properties.

*

*When Select-String receives such objects, it creates a string representation for them and searches that.

*What makes this particularly unhelpful is that this string representation is not the same you would see in the terminal (console), where PowerShell's rich output formatting is used; instead, simple .ToString() stringification is performed, which with [pscustomobject] instances results in representations such as '@{Brand=Volkswagen; Model=Passat}' (perhaps confusingly, this resembles - but is not the same as - a hashtable literal).

*

*GitHub issue #10726 proposes changing Select-String to instead operate on the rich display-formatting representations.

*Additionally, if you do let Select-String operate on such objects, its output (Microsoft.PowerShell.Commands.MatchInfo instances) no longer contain the input objects, only their string representations, which means that in order to extract the values Volkswagen and Passat, you'd have to perform string parsing, which is both cumbersome and not robust.

To filter input objects with properties based on property values, Where-Object is the better choice; e.g.:
PS> [pscustomobject] @{ Brand = 'Volkswagen'; Model = 'Passat' },
    [pscustomobject] @{ Brand = 'Ford'; Model = 'Mondeo' } |
      Where-Object Brand -eq Volkswagen

Brand      Model
-----      -----
Volkswagen Passat

That said, using Select-Object can still be helpful if you don't know what properties the input objects have, and want to locate a value somewhere in the object, via its string representation:
PS> [pscustomobject] @{ Brand = 'Volkswagen'; Model = 'Passat' },
    [pscustomobject] @{ Brand = 'Ford'; Model = 'Mondeo' } |
      Select-String -SimpleMatch wagen

@{Brand=Volkswagen; Model=Passat}

The above is what you tried, but, as stated, this effectively outputs just the string representation of the entire object, with no (easy) ability to extract property values afterwards.
The solution is to use the common -PipelineVariable parameter on the input-object-producing command, which allows access to the object at hand in a later pipeline segment's (ForEach-Object) script block, which allows you to create the desired comma-separated list of property values easily (even without knowing the property names):
# Note the use of -PipelineVariable obj and the use of $obj later.
PS> Write-Output -PipelineVariable obj (
      [pscustomobject] @{ Brand = 'Volkswagen'; Model = 'Passat' },
      [pscustomobject] @{ Brand = 'Ford'; Model = 'Mondeo' }
    ) |
      Select-String -SimpleMatch wagen |
        ForEach-Object { $obj.psobject.Properties.Value -join ', ' }

Volkswagen, Passat

$obj.psobject.Properties.Value uses the hidden, intrinsic .psobject property that PowerShell provides for all objects, which is a rich source of reflection and in this case allows easy access to all property values, via member-access enumeration.


text:
Q: JavaFX Value in thumb of slider I have a slider here that displays a number on the slider thumb. Whenever I drag the slider, the number increments or decrements. I want the thumb to display an integer instead of a double.
import javafx.application.Application;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;

public class SliderWithLabeledThumb extends Application {
    public void start(Stage ps) {
        Slider s = new Slider();

        StackPane root = new StackPane(s);
        root.setPadding(new Insets(5));
        s.setOrientation(Orientation.VERTICAL);
        s.setMin(49);
        s.setMax(99);
        s.setValue(51);
        s.setMinorTickCount(0);
        s.setMajorTickUnit(1);

        Scene scene = new Scene(root);

        s.applyCss();
        s.layout();
        Pane p = (Pane) s.lookup(".thumb");
        Label l = new Label();
        l.textProperty().bind(s.valueProperty().asString("%.1f").concat(" °"));

        p.getChildren().add(l);

        ps.setScene(scene);
        ps.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

When I change the argument for asString() from "%.1f" to a "%d", I get an exception
l.textProperty().bind(s.valueProperty().asString("%d").concat(" °"));

Error Message:
Exception in Application start method
Exception in thread "main" java.lang.RuntimeException: Exception in Application start method
    at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.util.IllegalFormatConversionException: d != java.lang.Double
    at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
    at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2793)
    at java.util.Formatter$FormatSpecifier.print(Formatter.java:2747)
    at java.util.Formatter.format(Formatter.java:2520)
    at java.util.Formatter.format(Formatter.java:2455)
    at java.lang.String.format(String.java:2940)
    at com.sun.javafx.binding.StringFormatter$4.computeValue(StringFormatter.java:196)
    at javafx.beans.binding.StringBinding.get(StringBinding.java:152)
    at com.sun.javafx.binding.StringFormatter.format(StringFormatter.java:207)
    at javafx.beans.binding.Bindings.format(Bindings.java:4846)
    at javafx.beans.binding.NumberExpressionBase.asString(NumberExpressionBase.java:319)
    at embeddedwebview.SliderWithLabeledThumb.start(SliderWithLabeledThumb.java:29)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)

Here is my CSS File:
.slider .track {
    -fx-pref-height: 10px;
    -fx-pref-width: 20px;
}

.slider .thumb {
    -fx-pref-height: 30;
    -fx-prefer-width: 30;
}

Current output so far:

A: This question ends up being pretty much a duplicate of:

*

*Problem with System.out.printf command in Java
So you can't use %d to format a double value, you must use %f.  If you only want to display the integer portion of the double value, you can let %.0f (as recommended in comments by Hypnic Jerk) do the rounding to zero decimal places (the decimal point will not be displayed).  According to the formatting javadoc, the round half up algorithm is used.
import javafx.application.Application;
import javafx.geometry.*;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;

public class SliderWithLabeledThumb extends Application {
    public void start(Stage ps) {
        Slider s = new Slider();

        StackPane root = new StackPane(s);
        root.setPadding(new Insets(5));
        s.setOrientation(Orientation.VERTICAL);
        s.setMin(49);
        s.setMax(99);
        s.setValue(51);
        s.setMinorTickCount(0);
        s.setMajorTickUnit(1);

        Scene scene = new Scene(root);

        s.applyCss();
        s.layout();
        Pane p = (Pane) s.lookup(".thumb");
        Label l = new Label();
        l.textProperty().bind(s.valueProperty().asString("%.0f").concat(" °"));

        p.getChildren().add(l);

        ps.setScene(scene);
        ps.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}


text:
Q: Get number of likes Facebook I'm trying to get the number of likes of a post with the help of fb sdk for c#.
Below is the code I'm trying
FacebookClient fb = new FacebookClient(page_access_token);
var like = fb.Get(post_id+"/likes");

But, I'm getting the below text in reply:

{"data":[] }

I'm using the sdk for other things like posting on page, etc and its working perfectly.
Just having trouble getting the no. of likes.
Am I making a wrong Get request?

A: Points where this could go wrong:

*

*The page access token has no permissions to view the post you are requesting

*The post itself has no likes

See

*

*https://developers.facebook.com/docs/graph-api/reference/v2.5/object/likes/
As in these docs, you need to add a summary=true parameter to the request:
var like = fb.Get(post_id+"/likes?summary=true");


text:
Q: How do I fix 'Warning: Cannot modify header information' error?
Possible Duplicate:
PHP Fix Warning: Cannot modify header information - headers already sent
"Warning: Headers already sent" in PHP

I had a nice website that worked perfectly. The first page is header.php and the first line was:
<?xml version="1.0" encoding="utf-8"?>

Then one day it started to say parse error line 1. So I did some research on the web and changed the first line into this:
<?php echo '<?xml version="1.0" encoding="utf-8"?>' ?>

And the parse error problem vanished. But then another problem appeared:
Warning: Cannot modify header information - headers already sent by (output started at /Volumes/raid/Web/Sites/*******.com/header.php:1)

So I decided to remove this first line from the code (and to be honest I had no idea what was it's purpose). Then a new error appeared :
Warning: Cannot modify header information - headers already sent by (output started at /Volumes/raid/Web/Sites/*******.com/header.php:25)

And here's the code where I can't find any error (no blanks at end of lines, for sure)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1  /DTD/xhtml1-transitional.dtd">
<html lang="fr" dir="ltr" xml:lang="fr" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <link href="/css/bootstrap.css" rel="stylesheet">
    <link href="/css/style.css" rel="stylesheet">
    <link type="image/x-icon" href="./img/lions_icon" rel="icon">
    <link type="image/x-icon" href="./img/lions_icon" rel="shortcut icon">
    <link href="/css/jquery.ui.all.css" rel="stylesheet">
    <title>Lions</title>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
    <script src="/js/jquery.js"></script>
    <script src="/js/jquery-1.8.2.js"></script>
    <script src="/js/jquery.ui.core.js"></script>
    <script src="/js/jquery.ui.widget.js"></script>
    <script src="/js/jquery.ui.datepicker.js"></script>
    <script src="/js/bootstrap.js"></script>
    <script>
     $(function() {
      $( "#date" ).datepicker();
      $( "#date" ).datepicker( "option", "dateFormat", "yy-mm-dd");
      });
   </script>
</head>
<?php
 // beggining of the php code,
 ....
?>
<body>
...

The line 25 is the one where the php begins.

A: somewhere in your code you are using header() if you output anything before that code your page wil return that error. Plus be certain you have no spaces before <?php and after ?> what will result the page to be reder the space as html before sending the header();

A: You cant send the header after you've done anything. If you place the header function you use on line 1, the problem is fixed ;).

A: Well the problem ist you send already data to the browser before you execute
    <?php echo '<?xml version="1.0" encoding="utf-8"?>' ?>

may you get an E_NOTICE or E_WARNING. Have you tried to activate error reporting ?
    error_reporting(-1); ini_set('display_errors', 1);

A: The error is inside the php tags, probably you use something like Header Location. In html there is no error.

A: (If you use php frameworks == true)
{
This situation can exists, when you have some output like example echo in controller.
}


text:
Q: How to turn a recorded Macro into an automated Macro in VBA when data come from another sheet? I have recorded the following macro to sort data in the range "B3:U47" based on the values of the column "C3:C47".
Sub Sorting_Finance()
    ActiveWorkbook.Worksheets("Finance").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Finance").Sort.SortFields.Add2 Key:= _
        Range("C3:C47"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption _
        :=xlSortNormal
    With ActiveWorkbook.Worksheets("Finance").Sort
        .SetRange Range("B3:U47")
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

Every time I want to sort the data, I press Control+n. In order to get it done automatically when a new value is entered in the column C, I tried the following code:
Private Sub Worksheet_Change(ByVal Target As Range)
if not (intersect(target, Range("C3:C47")) is nothing) then
    call Sorting_Finance
end if
end sub

But the fact is that the data in the column "C3:C47" come from another sheet, so it doesn't work. Is there anything I can do for this?

A: There are two methods of VBA sorting. The recorded version is the 'longhand' version. You can use the 'shorthand' version and set the primary sort order column while adapting the range to suit current data.
BTW, you should know whether you have a header row or not. xlGuess should be replaced with either xlYes or xlNo I've used xlYes.
In Module1:
Option Explicit

Sub Sorting_Finance()

    With ThisWorkbook.Worksheets("Finance")
        'range B3 to column U down to the last row with data in C
        With .Range(.Cells(3, "B"), .Cells(.Rows.Count, "C").End(xlUp).Offset(0, 18))
            .Sort Key1:=.Columns(2), Order1:=xlAscending, _
                  Header:=xlYes, Orientation:=xlTopToBottom
        End With
    End With

End Sub

In the Finance worksheet code sheet, use the same method to define the Intersect range.
Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range(Cells(3, "C"), Cells(Rows.Count, "C").End(xlUp))) Is Nothing Then
        Application.EnableEvents = False
        Call Sorting_Finance
        Application.EnableEvents = True
    End If
End Sub

Since you are changing the values as you re-sort them, disable event handling so one iteration doesn't run on top of another.


text:
Q: Can you give the first part of a std::pair a more symbolic name? typedef std::pair<std::string, std::string> FooPair;
typedef std::map<FooPair, std::string> FooMapper;

FooMapper mapper;
for(FooMapper::const_iterator i=mapper.begin(); i != mapper.end(); ++i) {
    std::cout <<  i->first.first << "," << i->first.second << ": " << i->second;
}

Is it possible to change i->first.first into something that makes more sense to the programmer, a way to alias .first to a meaningful name  like say i->first.countrycode while still taking advantage of the std::pair.

A: No, you can't.
Make your own class if you want the members to have hand-picked names.


text:
Q: How to forcibly update a file if left unchanged after 55 minutes? I need a log file to be updated if it has been left unchanged during 55 minutes. For example, say it is now 19:00 and IOstatDisk2.log hasn't changed since 18:00:
 solaris1a:/var/tmp ROOT # ls -ltr IOstatDisk2.log
 -rw-r--r--   1 root    other       6 Aug  2 18:00 IOstatDisk2.log

So in this case I will append the line
echo "new cycle - forced update after 55 min." >> IOstatDisk2.log

But if the last time stamp was less than 55 minutes ago then I will not append the line.

A: GNU find or BSD find will do the trick for you:
find <DIRECTORY> -type f -amin +55 -name \*<PATTERN>\* -print

this will print all files with name PATTERN in DIRECTORY which where accessed greater than 55 mins ago.

A: You can test it (and operate on the file if test holds true) in this way:
if [ $(((`date +%s` - `stat -c %Y IOstatDisk2.log`) / 60)) -ge 55 ]
then
   echo "File was modified more than 55 minutes ago"
   # do something with the file...
fi


text:
Q: How can I generate html from Java object? I have a rest resource with a method that should return some data as html. We're talking about a list of Reports, which is a simple class consisting of 6 string member variables.
I am asking because the prospect of appending elements and values to a string seems slow and error prone, and I would really prefer to do it in an object oriented way.

A: For simple HTML, generate it directly as text. The other suggestions of serializing, XML, and transformations are all overkill.
There are Java libraries to help with generating HTML, such as these:

*

*jwebutilsA library for creating HTML 5 markup using Java. It also contains support for creating JSON and CSS 3 markup.

*Jakarta Element Construction Set (ECS)A Java API for generating elements for various markup languages it directly supports HTML 4.0 and XML. Now retired, but some folks really like it.

But if you learn the basics of valid HTML, you can write your own routines.
As for speed, the StringBuilder class was added for the purpose of faster string manipulation. The tradeoff is no synchronization. That means not thread-safe. Depending on how your program is structured, you might use synchronization around the outside of the code doing the HTML rendering.
Here is an example class I just cooked up in Java 6, and a little app to run it. This code is just a proof of concept, not ready for prime time production.
package com.example;

/**
 * @author Basil Bourque
 *         © 2012 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
 */
public class ListToHtmlTransformer {

    /**
     * @param collection
     *            of report titles.
     * @return string containing source code for HTML5.
     */
    public String render( java.util.Collection< String > reports ) {
        // This source code is not yet tested or made bullet-proof. Only meant for demonstrating concepts.
        // Warning: This code is not thread-safe. Changes must be made before serious use.
        // Warning: This code should be modified to produce proper HTML, such as escaping certain characters.
        // This code generates minimal HTML5 as suggested here: http://www.brucelawson.co.uk/2010/a-minimal-html5-document/
        // Big tip: Note that HTML allows the use of apostrophe (single-quote) in place of double-quote. Mixes better with Java source code.
        // The backslash + 'n' is an escape sequence in Java to generate a linefeed (Ascii/Unicode 10) for use here as a NewLine.
        // In real life, you woud test your rendered HTML with an HTML validator such as:
        // • http://html5.validator.nu/
        // • http://validator.w3.org/
        StringBuilder html = new StringBuilder();
        html.append( "<!doctype html>\n" );
        html.append( "\n" );

        html.append( "\n" );
        html.append( "<meta charset='utf-8'>\n" );
        html.append( "<title>Report of Reports</title>\n" );
        html.append( "\n\n" );

        html.append( "\n" );
        html.append( "
List of Reports
\n" );
        // Make a list in HTML
        html.append( "
\n" );
        // Loop the list of reports passed as argument.
        for ( String report : reports ) {
            html.append( "
" + report + "
\n" );
        }
        html.append( "
\n" );
        html.append( "\n\n" );

        html.append( "" );

        return html.toString();
    }

}

And an app to run it.
package com.example;

import java.util.ArrayList;

/**
 *
 * @author Basil Bourque
 *         © 2012 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
 */
public class App {

    /**
     * @param args
     */
    public static void main( String[] args ) {
        ArrayList< String > listOfReports = new ArrayList< String >();
        listOfReports.add( "Some report #1" );
        listOfReports.add( "Some report #2" );
        listOfReports.add( "Some report #3" );
        listOfReports.add( "Some report #4" );
        listOfReports.add( "Some report #5" );
        listOfReports.add( "Some report #6" );

        ListToHtmlTransformer renderer = new ListToHtmlTransformer();
        String renderedHtml = renderer.render( listOfReports );

        System.out.println( "The following HTML was rendered: " + new java.util.Date().toString() );
        System.out.println( renderedHtml );
        System.out.println( "*** End of HTML ***" );
    }

}

I tried to post the rendered HTML here, but StackOverflow tried to interpret it as HTML rather than display it.
Bonus tip: You can use single-quote (APOSTROPHE Unicode 39) rather than double-quote (QUOTATION MARK Unicode 34) in your HTML & CSS for delimiting attribute values and such. Browsers handle both well. The single-quote makes coding so much easier in your Java code, eliminating the need to escape the double-quote marks. Notice my usage in code above, such as the 'en' and 'utf-8'.

A: The normal way of generating HTML for a web response is to use a JSP or a Java templating engine like Velocity or FreeMarker.
If you are currently returning responses as XML, another approach would be to use XSLT to transform the XML to HTML.  The XSLT processing can be done on the client side (in the browser) if you include an appropriate "processing" instruction in the XML that links to the XSLT resource.

I used to think that bashing strings together was a reasonable solution, but then I came to realize that that results in you hard-wiring your HTML layout into your Java code.  The JSP, templating and transformation approaches all avoid this, allowing you to adjust the generated HTML later in the development cycle; e.g. at system integration time, or even post deployment.

A: You can serialize object to XML, and then provide XLST to generate HTML output.
But if it's just 6 stings I would go ahead and just concatenate the strings.