text:
Q: SQL Server logins "un-sync" when Availability Group fails over I have 2 SQL Servers in an Availability Group.  The logins are manually synced – same SID, same Password Hash, etc. on both replicas – and the user can log in via the listener to the primary replica.  (Note: password policy & expiration policy are on.)
Later, the AG fails over to the other replica, and the user now gets a login failure.  The new Primary's sys.sql_logins table shows a different Password Hash and a different Modify_Date: the date / time of the login failure!    When the original Password Hash is re-migrated to the new Primary, the user can again log in successfully.
Can anyone tell me why the login's password hash "spontaneously" changes after failover at login time, and how to avoid this happening so the users can log in after a failover?
My hunch is that it has something to do with the password/expiration policy, but that's a requirement of our auditors so can't be turned off.

A: I don't know if this is still an issue for you, or if you've found a solution, but in case you haven't, a very powerful set of tools, and one specific to your issue, can be obtained from: https://dbatools.io. Specific to your issue, use "Copy-SqlLogin" and configure it as a scheduled task on each server (primary and all secondaries) in whatever configuration that will work for your needs. I used this solution at the last place I worked and scheduled it to run every hour, and never had an issue with logins after implementation.
If, for some reason, you cannot utilize dbatools, you will need to use sp_help_revlogin, devise some method to pick out the logins you want to "replicate" (store in a table??) and then execute the IF NOT EXISTS...CREATE LOGIN... on all relevant instances, which will have to be hard-coded. So, this second method is only slightly better than manual intervention. However, assuming DBAs are the only ones who can create logins, it would be easy enough to make a procedure for all DBAs to always add a new login to this process whenever a new one is created. One thing to keep in mind, wherever the login is obtained from, the User level permissions will be carried over to all replicas, so make sure the "source" login/user is configured correctly before implementing any sync solution.
IMHO, logins and SQL Agent jobs are the only thing lacking from AlwaysOn, and perhaps in a future release, Microsoft will add some automatic functionality--especially for logins, since it really breaks the whole purpose of automatic failover if the logins aren't sync'd.


text:
Q: Bloch's theorem and Bloch's state The question is not so much about the theorem, but more about what it means in this context: see this link.
So yes, because of Bloch's theorem the Hamiltonian eigenstates in a crystalline system can be written as
\begin{align}
\psi_{n,\vec{k}}(\vec{r})=e^{i\vec{k}\cdot\vec{r}}u_{n,\vec{k}}(\vec{r}),
\end{align}
and so the Berry connection can be defined:
\begin{align}
A_{n}(\vec{k})=i\langle n(\vec{k})|\nabla_{\vec{k}}|n(\vec{k})\rangle,
\end{align}
but what in the world is $|n(\vec{k})\rangle$?
I've read a few articles on topological insulators and they always seem to start off with the Bloch wavefunction $e^{i\vec{k}\cdot\vec{r}} u_k(\vec{r})$, and then somehow they magically get the ket $|u(\vec{k})\rangle$ from which the Berry connection is defined... is $|u(\vec{k})\rangle$ the column vector comprised of the Fourier coefficients of $u_\vec{k}(\vec{r})$ w.r.t. $e^{i\vec{G}\cdot\vec{r}}$ or what?

A: I have discussed this question with my friend, and he gives a satisfying answer:
the Bloch state is $|\psi_k\rangle$, then we define a new state $|u_k\rangle$ by :
$|u_k\rangle=e^{-ik\cdot\hat{r}}|\psi_k\rangle$. Notice that $\hat{r}$ in phase factor is the position operator, not a parameter in real space. You can use this definition and the Bloch theorem: $T(R)|\psi_k\rangle=e^{ik\cdot R}|\psi_k\rangle$ (where $T(R)=e^{i\frac{\hat{p}\cdot R}{\hbar}}$, $p$ is the momentum operator) to check the wavefunction of $|u_k\rangle$ is periodic.
The way to understand the definition is that: $e^{-ik\cdot\hat{r}}$ is a translation operator in momentum space, so if we use the wavefunction in momentum space, we will get :$u_k(k')=\psi_k(k'+k)$.
But one important thing to remember: $|u_k\rangle$ is not the eigenstate of the origional Hamiltonian $H$, but it's the eigenstate of the modified Hamiltonian: $H(k)=e^{-ik\hat\cdot{r}}He^{ik\cdot\hat{r}}$. When we talk about the band theory, we usually talk about Hamiltonian $H(k)$ and states $|u_k\rangle$.

A: First recall that when talking about Berry phases we are working in the adiabatic approximation where the Hamiltonian is allowed to be controlled by some slow varying variables, which in this case are $\vec{k}(t)$. In this case the underlying assumption is that all of the time dependence is encapsulated in these variables $H(\vec{r}, \vec{p}, \vec{k}(t))$.
$|n(\vec{k})\rangle$ are the eigenstates of the Hamiltonian which are allowed to depend on $\vec{k}$ since we are working in the adiabatic approximation. Recall now that in the Berry phases we look at accumulated phase from a cyclic process $\gamma(0) = \gamma(T)$, and assume w.l.o.g that we start with the eigenstate $n(\vec{k})$ which will not change under the adiabatic approximation. In this case the connection is given by the infinitesmal change of the state due to changes in $k$
\begin{equation}
i A_n(\vec{k}) = \langle n(\vec{k}) | \nabla_k | n(\vec{k})\rangle
\end{equation}

redpajama_set_name: RedPajamaStackExchange


text:
Q: grouping array of Strings by their first value using java 8 Stream I have a List of arrays containing two Strings:
List<String[]> pets = {["Alice", "dog"], ["Bob", "horse"], ["Alice", "cat"], ["Bob", "cat"]}

I want to turn them into a Map from String to List of Strings, like the following:
Map<String, List<String>>> pets = Map where
"Alice" maps to the List {"dog, "cat"}
"Bob" maps to the List {"horse", "cat"}

i.e. we take the first element of the array and group together all elements where the first elements are equal to each other. The imperative way of solving this would be to loop over the elements, and gradually building a Map. Is there any way to do this with java Streams, ie using a Collector or reduce?

A: Sure, you can!
You can group by the first element of each array which will be the map keys then apply the mapping collector to get the corresponding values.
 Map<String, List<String>> resultSet = pets.stream()
                .collect(groupingBy(array -> array[0],
                        collectingAndThen(mapping(e -> Arrays.copyOfRange(e, 1, e.length),
                                toList()),
                                f -> f.stream().flatMap(Arrays::stream)
                                .collect(toList()))));

or:
 Map<String, List<String>> resultSet = pets.stream()
                .collect(groupingBy(array -> array[0],
                flatMapping(e -> Arrays.stream(Arrays.copyOfRange(e, 1, e.length)),
                                    toList())));

Note, this solution uses the flatMapping collector which is only available as of JDK-9.


text:
Q: Enable remote connections to sql express with a script I am deploying an application with sql server express 2008. In the prerequisites section of my application I have included:

As a result when a user installs my application it will install sql express as well.
Then I will be able to connect to that database engine as:
        try
        {
            // database should be in the same network
            SqlConnection conn =
                new SqlConnection(@"Data Source=.\sqlexpress; Integrated Security=True");
            conn.Open();
            MessageBox.Show("Connection succesfull");
        }
        catch
        {
            MessageBox.Show("Unable to connect");
        }

Now when I install a different application(client version) I will like to be able to connect to that database engine. I managed to connect to it by doing something like:
        try
        {

            SqlConnection conn =
                new SqlConnection(@"Data Source=192.168.0.120\sqlexpress,22559; USER=sa; PASSWORD=*********");
            conn.Open();
            MessageBox.Show("Connection succesfull");
        }
        catch
        {
            MessageBox.Show("Unable to connect");
        }

In order for that code to work I had to do the following:

So my question is:
How could I configure this with code? When I deploy my application I want my application to install sql express like it does but I also whant to enable tcp/IP connections, enable some ports and lastly create a password for the account "SA" because I am not able to connect to the database remotly if the sa account does not have a password.
Or maybe I am asking to much and I am doing the wrong thing. perhaps I should do all this just for the database that I am planing on deploying not the database engine. whatever is easier. I have had a hard time deploying this maybe it will be eassier to deoploy a local database along with a wcf service in order to create CRUD operations on the local database remotely.
EIDT
I found this 3 links that claim on doing something similar and I still cannot make it work.
1) http://support.microsoft.com/kb/839980
2) http://social.msdn.microsoft.com/Forums/en-US/sqlexpress/thread/c7d3c3af-2b1e-4273-afe9-0669dcb7bd02/
3) http://www.sql-questions.com/microsoft/SQL-Server/34211977/can-not-connect-to-sql-2008-express-on-same-lan.aspx

A: downloaded sql server express 2008 (SQLEXPR32_x86_ENU.exe) and place it in the root of my c drive. then I install it with the following parameters:
C:\SQLEXPR32_x86_ENU.exe /q /hideconsole /action=Install /features=SQL /instancename=SQLEXPRESS /enableranu=1 /sqlsvcaccount="NT Authority\Network Service" /AddCurrentUserAsSqlAdmin /skiprules=RebootRequiredCheck /TCPENABLED=1
I add /TCPENABLED=1  in order to enable TCP/IP

A: I suggest you to create modified bootstrapper package to install Sql Server 2005 Express with customzation.
As an alternative, you can also use a custom action in your installer to change the targeted server using SMO.
Something like this:
Server server = new Server( "ServerName\\InstanceName" );
server.ConnectionContext.Connect();
server.Settings.LoginMode = ServerLoginMode.Mixed;
server.Settings.Alter();

We use SMO object to create user login and associate user to our created application database.. even run sql script to create database if database is not available..
Refer these links:
Configuring SQL Express During Installation
Configuring SQL Server when included as a requirement
Note: Create your sql server connection string settings in App.config file rather than putting hardcore in code.. this will help you customize application first run customization e.g. database creation.

A: These might be of some help, I've had it on my todo list for a while for the computers I have to setup for my app to run with Sql Server 2008 Express.  It's basically a way to setup a script that the SQL08exp installer will read and automate a lot of the setup according to what you set in the script.
http://digitalformula.net/articles/how-to-perform-an-unattended-installation-of-sql-server-2008-express/
http://blogesh.wordpress.com/2008/09/23/silent-install-of-sql-server-2008/


text:
Q: Windows Filtering Platform - How can I block incoming connections based on local port? I'm attempting to set up some filters using WFP to block inbound connections to a local server (for example, a webserver listening on port 8080).
I've got a filter working which can block based on Remote Port, so I can stop processes on my machine from establishing any connections to port 8080, but I can't figure out how to block incoming connections from another machine based on the local port 8080?
Here's my code which works to block based on remote port:
(It's C# using P/invoke but it's pretty much the same as if it were written in C++)
var RemotePort = 8080 # port to block

// connect to engine
var session = new Fwpm.FWPM_SESSION0 { flags = Fwpm.FWPM_SESSION_FLAG_DYNAMIC };
UInt32 engineHandle;
UnsafeNativeMethods.FwpmEngineOpen0(null, Fwpm.RPC_C_AUTHN_WINNT, IntPtr.Zero, session, out engineHandle

// create a subLayer to attach filters to
var subLayerGuid = Guid.NewGuid();
var subLayer = new Fwpm.FWPM_SUBLAYER0();
subLayer.subLayerKey = subLayerGuid;
subLayer.displayData.name = DisplayName;
subLayer.displayData.description = DisplayName;
subLayer.flags = 0;
subLayer.weight = 0x100;

UnsafeNativeMethods.FwpmSubLayerAdd0(engineHandle, subLayer, IntPtr.Zero)

var condition = new Fwpm.FWPM_FILTER_CONDITION0 {
    fieldKey = Fwpm.FWPM_CONDITION_IP_REMOTE_PORT,
    matchType = Fwpm.FWP_MATCH_TYPE.FWP_MATCH_EQUAL,
    conditionValue = {
        type = Fwpm.FWP_DATA_TYPE.FWP_UINT16,
        uint16 = RemotePort
    }
}

// create the filter itself
var fwpFilter = new Fwpm.FWPM_FILTER0();
fwpFilter.layerKey = Fwpm.FWPM_LAYER_ALE_AUTH_CONNECT_V4;
fwpFilter.action.type = Fwpm.FWP_ACTION_BLOCK;
fwpFilter.subLayerKey = subLayerGuid;

fwpFilter.weight.type = Fwpm.FWP_DATA_TYPE.FWP_EMPTY; // auto-weight.
fwpFilter.numFilterConditions = (uint)1;

var condsArray = new[]{ condition };
var condsPtr = SafeNativeMethods.MarshalArray(condsArray); // helper to create a native array from a C# one
fwpFilter.filterCondition = condsPtr;

fwpFilter.displayData.name = DisplayName;
fwpFilter.displayData.description = DisplayName;

// add the filter
UInt64 filterId = 0L;
UnsafeNativeMethods.FwpmFilterAdd0(engineHandle, ref fwpFilter, IntPtr.Zero, out filterId));

As mentioned above, this code does work to block connections with remote port of 8080. To block connections with Local Port 8080, I modified the code as follows:
var LocalPort = 8080;

var condition = new Fwpm.FWPM_FILTER_CONDITION0 {
    fieldKey = Fwpm.FWPM_CONDITION_IP_LOCAL_PORT,
    matchType = Fwpm.FWP_MATCH_TYPE.FWP_MATCH_EQUAL,
    conditionValue = {
        type = Fwpm.FWP_DATA_TYPE.FWP_UINT16,
        uint16 = LocalPort
    }
}

// create the filter itself
var fwpFilter = new Fwpm.FWPM_FILTER0();
fwpFilter.layerKey = Fwpm.FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4;

MSDN implies that FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4 is the right place to block inbound connections, however this doesn't work at all. I've tried FWPM_LAYER_ALE_RESOURCE_ASSIGNMENT_V4 as well as a few other layers, but no matter what I've tried, I am always able to establish connections from another machine to a server on port 8080 on my machine.
Any help would be much appreciated

A: You should be able to create that filter on any of the INBOUND or RECV layers that support the FWPM_CONDITION_IP_LOCAL_PORT condition, the resource to search for that is:
http://msdn.microsoft.com/en-us/library/windows/hardware/ff549939%28v=vs.85%29.aspx
However, not all traffic passes through every layer, I am by no means an expert but one approach is to add a filter like that to every applicable layer (a half dozen or so filers) and see if that works. If so you then remove the filters one at a time till you find the set that was actually needed. There were 4 layers I needed on a recent project to stop all the traffic I was interested in.
One big caveat that may be worth noting is that traffic on localhost may not go through any WFP layers (or perhaps it was only inbound layers it skipped, I don't remember). So you can use WFP to prevent a remote connection to the port, but a local connection may still go through.


text:
Q: Is accessing int as unsigned long undefined behavior? In a book called Programming Windows, in one of the examples, we have this line:
ReadFile (hFile, buffer, MAXREAD, &i, NULL) ;

i here was previously declared as int, but the 4th argument of ReadFile is LPDWORD, which is a typedef for DWORD*, and DWORD is a typedef for unsigned long. It's effectively type punning. On most systems unsigned long and int are the same size, but I think accessing a variable as if it were some other type is Undefined Behavior. Is this fine? Is this fine only if the sizes are the same? Is this UB? I checked a couple of errata websites and they don't seem to list this. Am I missing something?

A: If DWORD is defined as you describe, then the code contains a constraint violation which the compiler must diagnose , and the Standard no longer covers the behaviour of any executable generated.  There is no implicit conversion from int * to unsigned long *, regardless of the sizes of types.
If you don't see a compiler error message I would strongly recommend adjusting compiler settings so that an error message is shown. Some compilers default to showing a "warning" message for this mistake which can mislead the unwary into thinking there is no real problem.


text:
Q: Which Destiny-like FPS game is this picture from? I have only this picture of the game:

We thought it's the Destiny game, but GUIs are different.

A: Going by this image it seems that the HUD elements are quite similar. The one provided by the OP seems to have a little skew to it as if it were to be projected onto a curved screen. The armour of the players seem to be similar to Dust 514 as well.

A: It is a free to play game Dust 514 made by CCP Games. This game is only for Playstation 3 and it is heavily tied with Eve Online universe which is sci-fi mmo game.


text:
Q: Formula to calculate overtime hours not working consistently Edit: It now calculates overtime after implementing Vincent's solution in the comments
My girlfriend works from home 6 hours a day and gets to make her own hours. She asked me to make a time sheet for her that she can enter her start and end times into and will automatically calculate her hours. It calculates the total hours worked no problem (so long as they don't go pass midnight), but I wanted to also have it track overtime hours for her.
I have a formula that should work, but the problem is that if all the start and end times on a given day are both AM or both PM then it will not calculate the overtime hours no matter how much the total hours surpass 6 hours. However, as soon as you enter in a time value that starts at an AM time and ends at a PM time, such as 11:00 to 14:00, then it calculates the total overtime hours for the day just fine.
Here's a screenshot of the time sheet with times entered with total hours above 6, but no start and end time crossing from AM to PM:
Here's an example where the the last time entered on the first day now goes from an AM time to a PM time. Notice that the overtime hours are now being calculated accurately.
The VBA generating the formulas that calculates the hours looks like this:
Sub calcHours(ByVal numDays As Integer)
    Dim newWeekRow As Integer: newWeekRow = 0

    With Sheets("timesheet")
        'Add the formula to calculate hours for the day
        Range(Cells(5, 17), Cells(numDays + 4, 17)).FormulaR1C1 = _
        "=SUM((RC[-2] - RC[-3]) + (RC[-4] - RC[-5]) + (RC[-6] - RC[-7]) + (RC[-8] - RC[-9]) + (RC[-10] - RC[-11]) + (RC[-12] - RC[-13]))"

        'Add formula to calculate overtime hours
        Range(Cells(5, 19), Cells(numDays + 4, 19)).FormulaR1C1 = _
        "=IF(RC[-2]-(6/24) > 6/24, RC[-2]-(6/24), 0)"

        'Add the formula to calculate hours for the week
        For ctr = 1 To numDays
            If (Cells(4 + ctr, 2).Value = "Saturday") Then 'found the end of the week
                If (newWeekRow = 0) Then 'end of the first week
                    Cells(4 + ctr, 18).FormulaR1C1 = "=SUM(R5C[-1]:RC[-1])"
                    newWeekRow = 4 + ctr
                Else
                    Cells(4 + ctr, 18).FormulaR1C1 = "=SUM(R[-6]C[-1]:RC[-1])"
                    newWeekRow = 4 + ctr
                End If
            End If

            If (ctr = numDays) Then 'reached the end of the last week
                Cells(4 + ctr, 18).FormulaR1C1 = "=SUM(R" & newWeekRow + 1 & "C[-1]:RC[-1])"
            End If
        Next ctr

        'Add formula to calulate total hours for the month
        With Cells(5 + numDays, 17)
            .FormulaR1C1 = "=SUM(R[-" & numDays & "]C:R[-1]C)"
            .Font.Bold = True
        End With
    End With
End Sub

A: Currently your formula for suming the hours in the week is essentially:
=SUM(E5-D5,G5-F5,I5-H5,K5-J5,M5-L5, O5-N5)

The problem is that when you go past midnight you have no way of indicating that the time is the following day.  Since Time is stored as a decimal and date is stored as the integer, and by default, when only time is entered, 0 is the integer for the day.  All you need to do is add 1 to the time when they out time is less than the in time.  Going to cheat a bit and assume there will never be more than a 24 hour period between in and out.  So with that cheat in mind and that boolean True and False get converted to 1 and 0 respectively when going through a math operator, you could adjust your formula as follows:
=SUM(E5+(E5<D5)-D5,G5+(G5<F5)-F5,I5+(I5<H5)-H5,K5+(K5<J5)-J5,M5+(M5<L5)-L5, O5+(O5<N5)-N5)

Alternatively you could record the hours on the day they were worked on, not broken by the time you slept overnight as the delineater for the day.  Ie if you work from 2300 on monday to 0100 on tuesday, then record monday as time in 2300 and time out as 23:59, and Tuesday record time in as 00:00 and time out as 01:01. Note the added 1 minute to the time out.  This is to make up for the missing minute between 23:59 and 24:00 (which does not technically exist in excel but does work with some operations)
As for the overtime calculation see Vincent G's comment.  Another spin on that formula could be:
=MAX(Q5-6/24,0)

You will need to change the cell references to match your VBA programming needs.  Both formulas correct overtime issue calculation and start and end time crossing midnight.

A: First, if you go over midnight, here's what I would do:
Going over midnight means the hours will be negative. In that case, do an IF statement where if the result is a negative number, simply add 24 hours (or 1 day) to the result.
Second, couldn't you calculate the overtime without VBA by simply subtracting 6 hours from total working hours for the day?
I'm not too familiar with VBA, so if I'm missing something blatantly obvious, please forgive me.


text:
Q: how to apply pagination on search result from multiple fields using post method and $_SERVER['PHP_SELF'] i am new to PHP. i developed a new page which show all result from a table. i also place some filter on top of the page to show search results.after submit the search result, it show filtered result with proper pagination. but when i click on pagination no. 2nd or 3rd page, it again display all the results. i search a lot on stackoverflow sites or other sites but unable to do so. please help to sort this problem. i posted the code here
// single page for show result and submit query "allcustomerdetails.php"

<form name="frmnamesd" method="POST" action="<?php echo $_SERVER['PHP_SELF'];?>" onSubmit="return validated(this)" id = "frmnamesd" enctype="multipart/form-data">
                <fieldset class="row1">
                &nbsp   Search By:

                    Customer ID: &nbsp
                <input type="text" name="c_id" size = "8" onKeyPress="return isNumberKey(event)" value = "<?php echo isset($_POST['c_id']) ? $_POST['c_id'] : '';?>" />&nbsp
                Name: &nbsp
                <input type="text" name="c_name" size = "10" value = "<?php echo isset($_POST['c_name']) ? $_POST['c_name'] : '';?>" /> &nbsp
                Mobile: &nbsp
                <input type="text" name="c_mobile" onKeyPress="return isNumberKey(event)" size="10" value = "<?php echo isset($_POST['c_mobile']) ? $_POST['c_mobile'] : '';?>" /> &nbsp
                Customer Type:&nbsp &nbsp
                <select name="c_type">
                    <option value="<?php echo isset($_POST['c_type']) ? $_POST['c_type'] : '';?>" ><?php echo isset($_POST['c_type']) ? $_POST['c_type'] : "-select-";?></option>
                    <option value="IW">IW</option>
                    <option value="AMC">AMC</option>
                    <option value="SAC">SAC</option>
                    <option value="OW">OW</option>
                    <option value="PS">PS</option>
                </select>&nbsp
                Date From/To:&nbsp
                <input type="date" name="c_from" value = "<?php echo isset($_POST['c_from']) ? $_POST['c_from'] : '';?>">
                <input type="date" name="c_to" value = "<?php echo isset($_POST['c_to']) ? $_POST['c_to'] : '';?>" >

                &nbsp &nbsp&nbsp  Address: &nbsp  &nbsp  &nbsp  &nbsp
                <input type="text" name="c_address" size = "32" value = "<?php echo isset($_POST['c_address']) ? $_POST['c_address'] : '';?>" > &nbsp
                <input type="Submit" name="submit" value="Submit">&nbsp  <input type="reset" name="reset" value="reset">
                </fieldset>
                </form>

<?php

$limit = 100;
if (isset($_GET["page"])) {

    $page  = $_GET["page"];
    $page_offset = ($page-1) * $limit;
}
else {
$page_offset = 0;
$page = 1;
}

$query = "SELECT * FROM customer_details";
$querycount = "SELECT COUNT(*) FROM customer_details";
if(isset($_POST['submit'])) {
    // define the list of fields
    $fromdate = $_POST['c_from'];
    $todate  = $_POST['c_to'];
    $fields = array('c_id','c_name','c_mobile', 'c_type','c_address');
    $conditions = array();

    // loop through the defined fields
    foreach($fields as $field){
        //$abc = $_POST[$field];
        //die;
        // if the field is set and not empty
        if(isset($_POST[$field]) && $_POST[$field] != '') {
            // create a new condition while escaping the value inputed by the user (SQL Injection)
            $conditions[] = "`$field` LIKE '%" . mysqli_real_escape_string($con, $_POST[$field]) . "%'";
        }
    }
    if(isset($_POST['c_from']) && $_POST['c_to'] != '') {
    // builds the query
            $query .= " WHERE c_next_service between '$fromdate' and '$todate'";
            $querycount .= " WHERE c_next_service between '$fromdate' and '$todate'";

            if(count($conditions) > 0) {

                $query .= " AND" . implode (' AND ', $conditions);
                $querycount .= " AND" . implode (' AND ', $conditions);
                $query .= " order by c_id desc LIMIT $page_offset, $limit";
                $querycount .= " order by c_id desc";
            }
            else {
                $query .= " order by c_id desc LIMIT $page_offset, $limit";
                $querycount .= " order by c_id desc";
            }
        }
    // if there are conditions defined
    elseif(count($conditions) > 0) {
            $query .= " WHERE" . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
            $query .= " order by c_id desc LIMIT $page_offset, $limit" ;
            $querycount .= " WHERE" . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
            $querycount .= " order by c_id desc" ;
        }
    else {
        // append the conditions
            $query .= " order by c_id desc LIMIT $page_offset, $limit";
            $querycount .= " order by c_id desc";
        }
    }
else {
    $query .= " order by c_id desc LIMIT $page_offset, $limit";
    $querycount .= " order by c_id desc";
}

$result = mysqli_query($con, $query);
$resultcount = mysqli_query($con,$querycount);
$count = mysqli_fetch_row($resultcount);
$totalrows = $count[0];

<?php if($_POST) {?>

<button onClick="history.go(-1)">Go Back</button>

<?php
    }
$total_pages = ceil($totalrows/$limit);
$pagLink = "
";
for ($i=1; $i<=$total_pages; $i++) {
                $pagLink .= "    ".$i."";
};
    ?>

<?php echo $pagLink . "
";?>

A: after giving some clue by stackoverflow user, i am able to solve my problem some of the code i posted below:
<?php if(isset($_GET['msg'])) { ?>
<?php echo $_GET['msg'];}?>

All Customers Detail

                <form name="frmnamesd" method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>" onSubmit="return validated(this)" id = "frmnamesd" enctype="multipart/form-data">
                <fieldset class="row1">
                &nbsp   Search By:

                    Customer ID: &nbsp
                <input type="text" name="c_id" size = "8" onKeyPress="return isNumberKey(event)" value = "<?php echo isset($_GET['c_id']) ? $_GET['c_id'] : '';?>" />&nbsp
                Name: &nbsp
                <input type="text" name="c_name" size = "10" value = "<?php echo isset($_GET['c_name']) ? $_GET['c_name'] : '';?>" /> &nbsp
                Mobile: &nbsp
                <input type="text" name="c_mobile" onKeyPress="return isNumberKey(event)" size="10" value = "<?php echo isset($_GET['c_mobile']) ? $_GET['c_mobile'] : '';?>" /> &nbsp
                Customer Type:&nbsp &nbsp
                <select name="c_type">
                    <option value="<?php echo isset($_GET['c_type']) ? $_GET['c_type'] : '';?>" ><?php echo isset($_GET['c_type']) ? $_GET['c_type'] : "-select-";?></option>
                    <option value="IW">IW</option>
                    <option value="AMC">AMC</option>
                    <option value="SAC">SAC</option>
                    <option value="OW">OW</option>
                    <option value="PS">PS</option>
                </select>&nbsp
                Date From/To:&nbsp
                <input type="date" name="c_from" value = "<?php echo isset($_GET['c_from']) ? $_GET['c_from'] : '';?>">
                <input type="date" name="c_to" value = "<?php echo isset($_GET['c_to']) ? $_GET['c_to'] : '';?>" >

                &nbsp &nbsp&nbsp  Address: &nbsp  &nbsp  &nbsp  &nbsp
                <input type="text" name="c_address" size = "32" value = "<?php echo isset($_GET['c_address']) ? $_GET['c_address'] : '';?>" > &nbsp
                <input type="Submit" name="submit" value="Submit">      <input type="reset" name="reset" value="Clear">      <button>Refresh</button>
                </fieldset>
                </form>

<?php

$limit = 100;
if (isset($_GET["page"])) {

    $page  = $_GET["page"];
    $page_offset = ($page-1) * $limit;
}
else {
$page_offset = 0;
$page = 1;
}
//echo  $page_offset;
//die;

$query = "SELECT * FROM customer_details";
$querycount = "SELECT COUNT(*) FROM customer_details";
if(isset($_GET['submit'])) {
    // define the list of fields
    $fromdate = $_GET['c_from'];
    $todate  = $_GET['c_to'];
    $fields = array('c_id','c_name','c_mobile', 'c_type','c_address');
    $conditions = array();

    // loop through the defined fields
    foreach($fields as $field){
        //$abc = $_GET[$field];
        //die;
        // if the field is set and not empty
        if(isset($_GET[$field]) && $_GET[$field] != '') {
            // create a new condition while escaping the value inputed by the user (SQL Injection)
            $conditions[] = "`$field` LIKE '%" . mysqli_real_escape_string($con, $_GET[$field]) . "%'";
        }
    }
    if(isset($_GET['c_from']) && $_GET['c_to'] != '') {
    // builds the query
            $query .= " WHERE c_next_service between '$fromdate' and '$todate'";
            $querycount .= " WHERE c_next_service between '$fromdate' and '$todate'";

            if(count($conditions) > 0) {

                $query .= " AND" . implode (' AND ', $conditions);
                $querycount .= " AND" . implode (' AND ', $conditions);
                $query .= " order by c_id desc LIMIT $page_offset, $limit";
                $querycount .= " order by c_id desc";
            }
            else {
                $query .= " order by c_id desc LIMIT $page_offset, $limit";
                $querycount .= " order by c_id desc";
            }
        }
    // if there are conditions defined
    elseif(count($conditions) > 0) {
            $query .= " WHERE" . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
            $query .= " order by c_id desc LIMIT $page_offset, $limit" ;
            $querycount .= " WHERE" . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
            $querycount .= " order by c_id desc" ;
        }
    else {
        // append the conditions
            $query .= " order by c_id desc LIMIT $page_offset, $limit";
            $querycount .= " order by c_id desc";
        }
    }
else {
    $query .= " order by c_id desc LIMIT $page_offset, $limit";
    $querycount .= " order by c_id desc";
}

$result = mysqli_query($con, $query);
$resultcount = mysqli_query($con,$querycount);
$count = mysqli_fetch_row($resultcount);
$totalrows = $count[0];

using $_SERVER['PHP_SELF'] i changed POST method to GET method
<?php

$total_pages = ceil($totalrows/$limit);
$pagLink = "
";

if(isset($_GET['submit'])) { ?>

<button onClick="history.go(-1)">Go Back</button>
<?php
$url = "c_id=".$_GET['c_id']."&c_name=".$_GET['c_name']."&c_mobile=".$_GET['c_mobile']."&c_type=".$_GET['c_type']."&c_from=".$_GET['c_from']."&c_to=".$_GET['c_to']."&c_address=".$_GET['c_address']."&submit=".$_GET['submit'];
for ($i=1; $i<=$total_pages; $i++) {
                $pagLink .= "    ".$i."";
};
    ?>

<?php echo $pagLink . "
";?>

<?php
 }
 else {

for ($i=1; $i<=$total_pages; $i++) {
                $pagLink .= "    ".$i."";
};
 ?>

<?php echo $pagLink . "
"; }?>

work like a charm....

A: Its because  when you are in second page you doesn't get any post data and your query became SELECT * FROM customer_details order by c_id desc LIMIT $page_offset, $limit like this which gives you all records. you should store either all variables or query in session.
Read about session from here


text:
Q: Is the "or otherwise" here in this sentence correct or not? original sentence:
It is the contractor's responsibility to locate all trees adjacent to or otherwise affecting the works prior to the commencement of works.
clearly, the correct sentence should be:
It is the contractor's responsibility to locate all trees adjacent to prior to the commencement of works, otherwise they will affect the works.
I have two questions:

*

*In the above sentence, can 'otherwise' be substituted by 'or otherwise'?

*Can the complete "subject+verb+object" sentence after the 'otherwise' be simplified as a present participle phrase , i.e. Ving phrase?

A: The original sentence is correct.

It is the contractor's responsibility to locate all trees adjacent to or otherwise affecting the works prior to the commencement of works.

The highlighted words are a coordinated adjective phrase meaning
adjacent to the works
or
otherwise affecting the works.
Explaining further, it assumes that trees adjacent to the planned works will affect the works, but some trees that are not adjacent may still affect the works in another manner, that is, otherwise.
Neither of your questions can be answered because they apply to your ungrammatical substitute sentence.


text:
Q: Test-Connection with -asjob and -delay When running Test-Connection as a job it seems to completely disregard the -delay parameter.
For example when using "-delay 5" and "-count 10" it would be expected this should take roughly 50 seconds to complete.
When testing with Measure-Command this confirms that when run as a job this is not the case, as you can see the job took less that a second to complete, but when not run as a job took roughly 50 seconds as expected.
Measure-Command {Test-Connection google.co.uk -Count 10 -Delay 5 -AsJob | where {$_.Name = $Target}}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 26
Ticks             : 263563
TotalDays         : 3.05049768518519E-07
TotalHours        : 7.32119444444444E-06
TotalMinutes      : 0.000439271666666667
TotalSeconds      : 0.0263563
TotalMilliseconds : 26.3563

Measure-Command {Test-Connection google.co.uk -Count 10 -Delay 5}

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 45
Milliseconds      : 445
Ticks             : 454456692
TotalDays         : 0.000525991541666667
TotalHours        : 0.012623797
TotalMinutes      : 0.75742782
TotalSeconds      : 45.4456692
TotalMilliseconds : 45445.6692

I have tested using "-count 1000" with "-asjob" and even this has minimal impact on the time it takes to execute.
I have had a look around but could find no explanation for this and was curious if anyone can explain why this behaviour occurs?
Additionally is there another method to invoke test-connection with the -delay parameter to run parallel with the rest of my script retrieve the results of test-connection at the end?
Update #1
I can see from the responses my use of the Measure-Command is wrong, but regardless if you take the following snippet:
$start = Get-date
$target = "google.co.uk"
$count = 10
Test-Connection $target -Count $count -Delay 5 -AsJob | where {$_.Name = $target}
$result = Wait-Job $Target | Receive-Job
Remove-Job $target
$result
$end = Get-date
""
Write-host "Completed in: $($end - $start)"

This outputs
    Source        Destination     IPV4Address      IPV6Address
------        -----------     -----------      -----------
SURFACE       google.co.uk    216.58.204.3
SURFACE       google.co.uk    216.58.204.3
SURFACE       google.co.uk    216.58.204.3
SURFACE       google.co.uk    216.58.204.3
SURFACE       google.co.uk    216.58.204.3
SURFACE       google.co.uk    216.58.204.3
SURFACE       google.co.uk    216.58.204.3
SURFACE       google.co.uk    216.58.204.3
SURFACE       google.co.uk    216.58.204.3
SURFACE       google.co.uk    216.58.204.3

Completed in: 00:00:00.1170733

Whereas
$start = Get-date
$target = "google.co.uk"
$count = 10
Test-Connection $target -Count $count -Delay 5
$end = Get-date
""
Write-host "Completed in: $($end - $start)"

Returns
SURFACE       google.co.uk    216.58.206.131
SURFACE       google.co.uk    216.58.206.131
SURFACE       google.co.uk    216.58.206.131
SURFACE       google.co.uk    216.58.206.131
SURFACE       google.co.uk    216.58.206.131
SURFACE       google.co.uk    216.58.206.131
SURFACE       google.co.uk    216.58.206.131
SURFACE       google.co.uk    216.58.206.131
SURFACE       google.co.uk    216.58.206.131
SURFACE       google.co.uk    216.58.206.131

Completed in: 00:00:45.4695467

I'm not sure if there is some fundamental flaw in my methodology.
Maybe my original questions wasn't as clear as it could have been, The reason I was using Measure-Command was to try and quantify my observation.
I'm running the test-connection as a job to perform 120 pings 1 second apart, so I would expect that job to not be available for approx. 120 seconds. But I can return the job and output the results in just a few seconds. Which isn't what I am expecting.

A: That's because you're not actually waiting for the jobs to finish. It only takes a few milliseconds to spin up the individual jobs and return the PSJob objects.
Compare with:
Measure-Command {
    Test-Connection google.co.uk -Count 10 -Delay 5 -AsJob |Receive-Job -Wait
}
# and
Measure-Command {
    Test-Connection google.co.uk -Count 10 -Delay 5
}


text:
Q: setTimeout callback fired in same tick of event loop? Is it possible for the callback for a setTimeout call to fire in the same tick of the event loop that it was declared in?
for example we can call
setTimeout(function(){
   console.log('tic-tock');
}, 1);

it's possible that the event loop may be blocked for much more than 1ms, but I assume
setTimeout

callbacks are always pushed to the next tick of the JS event loop.

A: Callback given to setTimeout cannot be executed in the same tick of the event loop.
Take a look at the MDN. It says:
"It's important to note that the function or code snippet cannot be executed until the thread that called setTimeout() has terminated."


text:
Q: Compiling errors using RapidXML in C++ using Dev C++ I am parsing an XML file for my C++ project in Dev C++ and I have the following code in the rapidxml_iterators.hpp file:
typedef xml_node<Ch> value_type;
typedef xml_node<Ch> &reference;
typedef xml_node<Ch> *pointer;
typedef typename std:: ptrdiff_t difference_type;
typedef typename std:: bidirectional_iterator_tag iterator_category;

It is giving me these errors:
no class template named `ptrdiff_t' in `std'
ISO C++ forbids declaration of `difference_type' with no type
no class template named `bidirectional_iterator_tag' in `std'
ISO C++ forbids declaration of `iterator_category' with no type

Prior to getting these errors, the code above was as follows:
typedef typename xml_node<Ch> value_type;
typedef typename xml_node<Ch> &reference;
typedef typename xml_node<Ch> *pointer;
typedef std:: ptrdiff_t difference_type;
typedef std:: bidirectional_iterator_tag iterator_category;

Which gave me the nested-name specifier errors like this:
expected nested-name-specifier
`xml_node<Ch>' specified as declarator-id
two or more data types in declaration of `xml_node<Ch>'
expected `;' before "value_type"

In my main file, which is where I'm doing the parsing, I have the following includes:
#include <iostream>
#include "rapidxml.hpp"
#include "rapidxml_iterators.hpp"
#include "rapidxml_print.hpp"
#include "rapidxml_utils.hpp"
#include <iterator>
#include <istream>
#include <cstdlib>
#include <string>
#include <queue>
#include <vector>
#include <streambuf>
#include <cstddef>

I have already looked around this website for similar posts and I have followed their
advice but none of them have so far solved my problem. Is it a problem with Dev C++ or with my code? Thank you

A: Before you do anything else, try and remove the line:-
#include "rapidxml_iterators.hpp"

It's not normally necessary - you can use rapidxml perfectly without it, and from what I recall it's a source of much pain and weird compiler errors.


text:
Q: How to read one json object I want to read a json object in one go.The code I have written is reading json but not in same order.
My data in json is:
 {
    "protocolDate":"2014-09-08",
    "spName":"UL",
    "testId":"123",
    "productDescription":"Refrigerator-Freezer",
    "protocolType":"Test Protocol Template",
    "sampleSize":"1",
    "protocolName":"Refrigerator-Freezer"}

My code is:
JSONParser parser = new JSONParser();
Object obj = parser.parse(new FileReader("./NewTestImport.json"));

JSONObject jsonObject = (JSONObject) obj;
String protocolDate = (String) jsonObject.get("protocolDate");
String spName = (String) jsonObject.get("spName");
String testId = (String) jsonObject.get("testId");
String productDescription = (String) jsonObject.get("productDescription");
String protocolType = (String) jsonObject.get("protocolType");
String sampleSize = (String) jsonObject.get("sampleSize");
String protocolName = (String) jsonObject.get("protocolName");
List<Map<String,String>> data= new ArrayList<Map<String,String>>();
data.add(jsonObject);

I dont want to initialize each json object explicitly.

A: I just modified your code,
        Map<String,String>jso = new LinkedHashMap<String,String>();
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(new FileReader("./NewTestImport.json"));

        JSONObject jsonObject = (JSONObject) obj;
        jso.put("protocolDate", (String) jsonObject.get("protocolDate"));
        jso.put("spName", (String) jsonObject.get("spName"));
        jso.put("testId", (String) jsonObject.get("testId"));
        jso.put("productDescription", (String) jsonObject.get("productDescription"));
        jso.put("protocolType", (String) jsonObject.get("protocolType"));
        jso.put("sampleSize", (String) jsonObject.get("sampleSize"));
        jso.put("protocolName", (String) jsonObject.get("protocolName"));

        List<Map<String,String>> data= new ArrayList<Map<String,String>>();
        data.add(jso);

        System.out.println(data);

Output:
[{protocolDate=2014-09-08, spName=UL, testId=123, productDescription=Refrigerator-Freezer, protocolType=Test Protocol Template, sampleSize=1, protocolName=Refrigerator-Freezer}]

*

*I used linked hash map so it will store the values in order.

*I hope this is the output you are looking for.

*In case of any clarifications please leave a comment below.

A: You can use Gson here is a good link gson api
Here you can see simple example
Gson gson = new Gson();
// 1. JSON to Java object, read it from a file.
Staff staff = gson.fromJson(new FileReader("D:\\file.json"), Staff.class);
// 2. JSON to Java object, read it from a Json String.
String jsonInString = "{'name' : 'mkyong'}";
Staff staff = gson.fromJson(jsonInString, Staff.class);
// JSON to JsonElement, convert to String later.
JsonElement json = gson.fromJson(new FileReader("D:\\file.json"), JsonElement.class);
String result = gson.toJson(json);


text:
Q: ImageAreaSelec: It wont preview the pre-selection on init this is how I am preselecting  (thanks to this question/answer ImageAreaSelect: preselect biggest thumbnail possible respecting aspectRatio)
var thwidth = $('#thumbnail').width();
    var thheight = $('#thumbnail').height();
    var aspectRatio = <?php echo $thumb_height/$thumb_width;?>;

var selWidth = 640;

var photo = $('#thumbnail'),
   photoWidth = parseInt($('#thumbnail').width()),
   maxWidth = Math.min(selWidth, photoWidth),
   maxHeight = maxWidth * aspectRatio,
   yTop = parseInt(photo.height()) / 2 - maxHeight / 2;

var thumbsel = $('#thumbnail').imgAreaSelect({
    x1: photoWidth / 2 - maxWidth / 2,
    y1: yTop,
    x2: (photoWidth / 2 - maxWidth / 2) + maxWidth,
    y2: yTop + maxHeight,
    aspectRatio: '1:<?php echo $thumb_height/$thumb_width;?>',
    onSelectStart: function(){
        $('#filters li').first().find('a').click();
    },
    onSelectChange: preview,
    onInit: preview,
    handles: true,
    resizable:true,
    show:true
});

But the preview method it doesn't seem to be loaded on Init. User needs to re-select, resize or at least dragg current selection so it's previewed:
The preview method (taken from their site)
function preview(img, selection) {
    $('#filters li').first().find('a').click();
    var scaleX = <?php echo $thumb_width;?> / selection.width;
    var scaleY = <?php echo $thumb_height;?> / selection.height;

    $('#uploaded_file').css({
        width: Math.round(scaleX * <?php echo $current_large_image_width;?>) + 'px',
        height: Math.round(scaleY * <?php echo $current_large_image_height;?>) + 'px',
        marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
        marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
    });
    $('#x1').val(selection.x1);
    $('#y1').val(selection.y1);
    $('#x2').val(selection.x2);
    $('#y2').val(selection.y2);
    $('#w').val(selection.width);
    $('#h').val(selection.height);
}

I tried with this on the init function:
$('.imgareaselect-selection').mouseup();

But with no much success...
But I believe that the solution would be in re-producing the selection dragged or something similar?
-EDIT-
If you checkout this screenshot:

you can see that the preselection has been successfully done, but the prevew didn't..
If I just click/move the selection: then it's previewed

So the question would be:
How can I reproduce the selection changed? vía plugin methods or DOM events
JSFiddle
-EDIT2-
Well I came out with this solution, why not running preview function after the plugin init?
var my_options = {
        x1 : photoWidth / 2 - maxWidth / 2,
        y1 : yTop,
        width : (photoWidth / 2 - maxWidth / 2) + maxWidth - photoWidth / 2 - maxWidth / 2,
        height : yTop + maxHeight - yTop
}
preview('',my_options);

A: You were on the right track trying to construct the selection object manually, but I'd guess it didn't work because you didn't populate the x2, y2 fields. Here's a working example for the preview displaying on page load: JSFiddle
HTML

Previsualiza el resultado

        <form method="post" action="/picture_recipe.php" class="save_recipe_image" name="thumbnail">
            <input type="hidden" id="x1" value="" name="x1" />
            <input type="hidden" id="y1" value="" name="y1" />
            <input type="hidden" id="x2" value="" name="x2" />
            <input type="hidden" id="y2" value="" name="y2" />
            <input type="hidden" id="w" value="" name="w" />
            <input type="hidden" id="h" value="" name="h" />
            <input type="hidden" value="206" id="id_recipe" name="id_recipe" />
            <input type="text" value="" id="effectApplied" name="effectApplied" style="display: none;" />
        </form>

jQuery
function preview(img, selection) {
    $('#filters li').first().find('a').click();
    var scaleX = 640 / selection.width;
    var scaleY = 380 / selection.height;

    $('#uploaded_file').css({
        width: Math.round(scaleX * 550) + 'px',
        height: Math.round(scaleY * 412) + 'px',
        marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
        marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
    });

    $('#x1').val(selection.x1);
    $('#y1').val(selection.y1);
    $('#x2').val(selection.x2);
    $('#y2').val(selection.y2);
    $('#w').val(selection.width);
    $('#h').val(selection.height);
}

$(function () {
    var photo = $('#thumbnail'),
        selWidth = 640,
        aspectRatio = 0.59375,
        photoWidth = parseInt(photo.width()),
        maxWidth = Math.min(selWidth, photoWidth),
        maxHeight = Math.floor(maxWidth * aspectRatio),
        yTop = parseInt(photo.height()) / 2 - maxHeight / 2,
        selection = {
            x1: photoWidth / 2 - maxWidth / 2,
            y1: yTop,
            x2: (photoWidth / 2 - maxWidth / 2) + maxWidth,
            y2: yTop + maxHeight
        };

    selection.height = selection.y2 - selection.y1;
    selection.width = selection.x2 - selection.x1;

    var thumbsel = photo.imgAreaSelect({
        x1: selection.x1,
        y1: selection.y1,
        x2: selection.x2,
        y2: selection.y2,
        aspectRatio: '1:0.59375',
        onSelectStart: function () {
            $('#filters li').first().find('a').click();
        },
        onSelectChange: preview,
        onSelectEnd: preview,
        handles: true,
        resizable: true,
        show: true
    });

    preview(null, selection);
});


text:
Q: What is the AWT equivalent to JFrame.setDefaultCloseOperation? We are using the setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) method of JFrame.
I want to support the native look and feel, and thus I have to use AWT instead of Swing.  So what is the AWT method equivalent to setDefaultCloseOperation?
Am I correct in thinking that in order to support the native look and feel we should use AWT instead of Swing?

A: There isn't a one method equivalent in AWT, but you can build it yourself.
myFrame.addWindowListener(
  new WindowAdapter(){
    public void windowClosed(WindowEvent e) { System.exit(0); }
  }
);

You can get close to native fidelity without using AWT.  Instead, set the default Look & Feel using UIManager.
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeel());

You must do this before displaying any UI, or things can get a little hairy.

A: Java provides an interface in awt as well as in swing to handle window events naming window listener
We use setDefaultCloseOperation() method just to escape from lengthy coding in swing
Window listener overrides 7 methods
Naming
  public void windowOpened(WindowEvent e)        {   }
  public void windowClosed(WindowEvent e)         {   }
  public void windowActivated(WindowEvent e)     {   }
  public void windowDeactivated(WindowEvent e) {   }
  public void windowIconified(WindowEvent e)      {   }
  public void windowDeiconified(WindowEvent e)   {   }
 public void windowClosing(WindowEvent e)

{   }
We have to put our exit code in last method as it deals with window closing
Alternatively we can use adapter classes.
Using an adapter class is advantageous over a listener that allows us to override only one or two abstract methods we require and not compulsorily all the abstract methods of a listener. But the problem with adapters is they are designed as abstract classes and thereby we cannot extend to our class as the class extends already Frame (Java does not support multiple inheritance).
For example use following code in your program
Frame f = new Frame();
f.addWindowListener(new WindowListener ()
{
    public void windowClosing(WindowEvent we)
    {
        System.exit(0);
    }
});

A: Alternatively to setting up L'n'F in the code, one could use java/javaw parameter -Dswing.defaultlaf.
For example, under Windows one could specify
-Dswing.defaultlaf=com.sun.java.swing.plaf.windows.WindowsLookAndFeel
More information can be found here.


text:
Q: Xcode's code sense and syntax coloring only work for some files in the project
Possible Duplicate:
xcode code sense color/completion not working
Code loses syntax color in Xcode 4

In my project, some files have syntax coloring and completions, but in some files (both .h and .m), it's not working. Any ideas?

A: Go to your organizer and in the projects tab find your project and click "Delete Derived Data" this forces XCode to reindex everything and does not hurt anything.   It usually does the trick for me although sometimes XCode is just troublesome.

A: Either those files are newly created files and you forgot to add them to a target (your app's target) to them while adding them to your project or it's Xcode's usual index problems.
For case 1:
Select one of those unindexed files and open the File Inspector. Below on target membership, check the box of your target. Clean and build. Restarting Xcode won't hurt.
For case 2:
Refer to Dancreek's answer.


text:
Q: Preorder traversal using Python generators with a mechanism to ignore subtrees I've written the following code to do a pre-order traversal of a Python dict which may contain other dicts:
def preorder_traversal(obj):
    yield obj
    if isinstance(obj, dict):
        for k, v in obj.iteritems():
            for o in preorder_traversal(v):
                yield o

Here are a few examples of its behavior:
> list(preorder_traversal({}))
[{}]
> list(preorder_traversal({'a': 1, 'b': 2}))
[{'a': 1, 'b': 2}, 1, 2]
> list(preorder_traversal({'a': {'c': 1}, 'b': 2}))
[{'a': {'c': 1}, 'b': 2}, {'c': 1}, 1, 2]

It's possible that the tree could get very large, so I'd like to add a mechanism whereby the consumer of the pre-order traversal can abort the search on an entire subtree.
Here's the code I came up with, including a nose test case. The test fails, as described below.
class IgnoreSubtree(Exception):
    pass

def preorder_traversal(obj):
    try:
        yield obj
    except IgnoreSubtree:
        return

    if isinstance(obj, dict):
        for k, v in obj.iteritems():
            iterator = preorder_traversal(v)
            for o in iterator:
                try:
                    yield o
                except IgnoreSubtree as e:
                    try:
                        iterator.throw(e)
                    except StopIteration:  # WHY?
                        pass

def test_ignore_subtree():
    obj = {'a': {'c': 3}, 'b': 2}
    iterator = preorder_traversal(obj)
    out = []
    for o in iterator:
        out.append(o)
        if o == {'c': 3}:
            iterator.throw(IgnoreSubtree)

    eq_([obj, {'c': 3}, 2], out)

The test fails with the following error:
AssertionError: [{'a': {'c': 3}, 'b': 2}, {'c': 3}, 2] !=
                [{'a': {'c': 3}, 'b': 2}, {'c': 3}]

i.e. the IgnoreSubtree has also aborted the iteration over k/v pairs in the top-level object, it hasn't just pruned out the {'c': 3} subtree.
What's wrong with this code? And why is StopIteration being thrown in the commented location above? Is this a reasonable way to implement subtree pruning for this function, or is there a better way to go about it?

A: As audiodude mentioned, your iterator.throw(IgnoreSubtree) returns iterator's next value (glossing over the complicated exception handling for a moment), so it is consuming the 2 that you were expecting to see appended to out on the next iteration of the loop in test_ignore_subtree.
You also asked about why the StopIteration is being thrown; the sequence of Exceptions being thrown/caught is:

*

*iterator.throw(IgnoreSubtree) throws an IgnoreSubtree that is caught in the inner loop of preorder_traversal

*that IgnoreSubtree is routed into the inner iterator with iterator.throw(e)

*the IgnoreSubtree is caught at except IgnoreSubtree: and return is called; however, iterator.throw(e) wants to get the next value from that inner iterator, which has just returned, hence a StopIteration is raised.

*before the original iterator.throw(IgnoreSubtree) returns, it goes once more through the outer loop in preorder_traversal, because it wants to return the next value from iterator.

I hope this helps!
Update
Here is an implementation of this basic scheme that I would use, along with passing nosetest:
from nose.tools import eq_

def preorder_traversal(obj, ignore_only_descendents_of=None, ignore_subtrees=None):
    if ignore_subtrees and obj in ignore_subtrees:
        return

    yield obj

    if ignore_only_descendents_of and obj in ignore_only_descendents_of:
        return

    if isinstance(obj, dict):
        for k, v in iter(sorted(obj.iteritems())):
            iterator = preorder_traversal(v, ignore_only_descendents_of, ignore_subtrees)
            for o in iterator:
                yield o

def test_ignore_subtree():
    obj = {'a': {'c': 3}, 'b': 2, 'd': {'e': {'f': 4}}, 'g': 5, 'h': 6}
    ignore_only_descendents_of = [{'e': {'f': 4}}]
    ignore_subtrees = [{'c': 3}, 5]

    iterator = preorder_traversal(obj, ignore_only_descendents_of, ignore_subtrees)
    out = []

    for o in iterator:
        out.append(o)

    expected = [obj, 2, {'e': {'f': 4}}, 6]
    eq_(expected, out)

Things to note:

*

*your example allows for excluding the descendents of {'c':3} while including {'c':3} itself; I found this a little confusing, as I would expect you to typically want to exclude a whole subtree including its root, so I've changed preorder_traversal to take two optional lists of things to exclude in each manner.

*moving the subtrees to skip into the iterator itself seems cleaner; you can avoid using Exceptions to control flow altogether.

*more complicated example demonstrating the two types of subtree-exclusions.

A: First of all, why is StopIteration raised. Your definition of preorder_traversal starts with:
try:
    yield obj
except IgnoreSubtree:
    return

In a generator a plain return statement is equivalent to raise StopIteration. In python3.3+ you can actually use return value and it is equivalent to raise StopIteration(value).
So, you are throwing in a certain exception, it is being caught by the generator which executes the return and hence raises a StopIteration. Whenever you call send, next or throw a StopIteration may be raised if the generator ends its execution without finding a yield, so the code you are using in the test is doomed to raise a StopIteration whenever skipping a subtree will end the iteration.
In other words your test is flawed because the throw call can raise an exception even if you have a correct implementation of your generator. So you should either wrap that call in a try statement:
try:
    iterator.throw(IgnoreSubtree)
except StopIteration:
    break

Alternatively you can use the suppress context manager to suppress the StopIteration:
with suppress(StopIteration):
    for o in iterator:
        ...
        iterator.throw(IgnoreSubtree)

If you aren't using python3.4 you can easily reimplement this context manager using the @contextmanager decorator (it's available since python 2.6):
def suppress(*exceptions):
    try:
        yield
    except exceptions:
        pass

Your code is basically correct. If you were using python3.3+ you could simplify it to:
def preorder_traversal(obj):
    try:
        yield obj
    except IgnoreSubtree:
        return
    else:
        if isinstance(obj, dict):
            for k, v in obj.items():
                yield from preorder_traversal(v)

Your implementation doesn't raise any error for me, once the StopIteration is suppressed for the outer throw. Also the result is what you expect.
Unfortunately without the yield from I don't see any way to simplify the control flow.

A: I think the other answers are overcomplicating things. The generator is correct! The problem is this line in the test:
iterator.throw(IgnoreSubtree)

Instead, it should be this:
out.append(iterator.throw(IgnoreSubtree))

The iterator is behaving just as expected. But as others have noted, it.throw returns the next value. You're throwing out the value that follows the subtree pruning because you aren't saving the result of throw in your test! You'd also actually need to catch StopIteration in case sending IgnoreSubtree ends the iterator completely. But it looks to me like no other changes are required.
Here's the code that shows the difference:
def test_ignore_subtree(obj, halt, expected):
    iterator = preorder_traversal(obj)
    out = []
    for o in iterator:
        out.append(o)
        if o == halt:
            out.append(iterator.throw(IgnoreSubtree))

    print expected
    print out

def test_ignore_subtree_wrong(obj, halt, expected):
    iterator = preorder_traversal(obj)
    out = []
    for o in iterator:
        out.append(o)
        if o == halt:
            iterator.throw(IgnoreSubtree)

    print expected
    print out

print "Test 1"
obj = {'a': {'c': 3}, 'b': 2}
halt = {'c': 3}
expected = [obj, {'c': 3}, 2]
test_ignore_subtree(obj, halt, expected)
test_ignore_subtree_wrong(obj, halt, expected)
print "Test 2"
obj = {'a': {'c': 3, 'd': 4}, 'b': 6, 'c': 5, 'd': 7}
halt = 3
expected = [obj, {'c': 3, 'd': 4}, 3, 5, 6, 7]
test_ignore_subtree(obj, halt, expected)
test_ignore_subtree_wrong(obj, halt, expected)
print "Test 3"
obj = {'a': {'c': 3, 'd': 4}, 'b': 2}
halt = 3
expected = [obj, {'c': 3, 'd': 4}, 3, 2]
test_ignore_subtree(obj, halt, expected)
test_ignore_subtree_wrong(obj, halt, expected)
print "Test 4"
obj = {'a': {'c': 3, 'd': 4}, 'b': 2, 'c': 5, 'd': 7}
halt = 3
expected = [obj, {'c': 3, 'd': 4}, 3, 5, 2, 7]
test_ignore_subtree(obj, halt, expected)
test_ignore_subtree_wrong(obj, halt, expected)

And the output (note how the first value after the pruned part of the tree is missing for all the "wrong" outputs:
Test 1
[{'a': {'c': 3}, 'b': 2}, {'c': 3}, 2]
[{'a': {'c': 3}, 'b': 2}, {'c': 3}, 2]
[{'a': {'c': 3}, 'b': 2}, {'c': 3}, 2]
[{'a': {'c': 3}, 'b': 2}, {'c': 3}]
Test 2
[{'a': {'c': 3, 'd': 4}, 'c': 5, 'b': 6, 'd': 7}, {'c': 3, 'd': 4}, 3, 5, 6, 7]
[{'a': {'c': 3, 'd': 4}, 'c': 5, 'b': 6, 'd': 7}, {'c': 3, 'd': 4}, 3, 5, 6, 7]
[{'a': {'c': 3, 'd': 4}, 'c': 5, 'b': 6, 'd': 7}, {'c': 3, 'd': 4}, 3, 5, 6, 7]
[{'a': {'c': 3, 'd': 4}, 'c': 5, 'b': 6, 'd': 7}, {'c': 3, 'd': 4}, 3, 6, 7]
Test 3
[{'a': {'c': 3, 'd': 4}, 'b': 2}, {'c': 3, 'd': 4}, 3, 2]
[{'a': {'c': 3, 'd': 4}, 'b': 2}, {'c': 3, 'd': 4}, 3, 2]
[{'a': {'c': 3, 'd': 4}, 'b': 2}, {'c': 3, 'd': 4}, 3, 2]
[{'a': {'c': 3, 'd': 4}, 'b': 2}, {'c': 3, 'd': 4}, 3]
Test 4
[{'a': {'c': 3, 'd': 4}, 'c': 5, 'b': 2, 'd': 7}, {'c': 3, 'd': 4}, 3, 5, 2, 7]
[{'a': {'c': 3, 'd': 4}, 'c': 5, 'b': 2, 'd': 7}, {'c': 3, 'd': 4}, 3, 5, 2, 7]
[{'a': {'c': 3, 'd': 4}, 'c': 5, 'b': 2, 'd': 7}, {'c': 3, 'd': 4}, 3, 5, 2, 7]
[{'a': {'c': 3, 'd': 4}, 'c': 5, 'b': 2, 'd': 7}, {'c': 3, 'd': 4}, 3, 2, 7]

I had to massage the expected values to get the sequence right because dictionaries iterate in an unpredictable order. But I think the results are sound.

A: Implementing subtree pruning by throwing an exception to the iterator results in messy, error-prone code, both in the generator and in the function that consumes it. Looking at some of the answers here makes me think that a filter callback function is a saner approach.
This would be a generalization of Ryan's answer:
def preorder_traversal(obj, bailout_fn=None):
    yield obj
    if bailout_fn and bailout_fn(obj):
        return

    if isinstance(obj, dict):
        for k, v in obj.iteritems():
            for o in preorder_traversal(v, bailout_fn):
                yield o

And here are some nose tests that demonstrate how it's used:
def test_ignore_subtree():
    obj = {'a': {'c': 3}, 'b': 2}
    eq_([obj, {'c': 3}, 3, 2], list(preorder_traversal(obj)))

    iterator = preorder_traversal(obj, lambda o: o == {'c': 3})
    out = list(iterator)
    eq_([obj, {'c': 3}, 2], out)

def test_ignore_subtree2():
    obj = {'a': {'c': 3, 'd': 4}, 'b': 2}
    eq_([obj, {'c': 3, 'd': 4}, 3, 4, 2],
            list(preorder_traversal(obj)))

    iterator = preorder_traversal(obj, lambda o: o == {'c': 3, 'd': 4})
    out = list(iterator)

    eq_([obj, {'c': 3, 'd': 4}, 2], out)

A: I've never posted a second answer before, but I think in this case it's appropriate. The first section of this answer discusses a way to cleaning up the generator interface. The second section discusses when it's most appropriate to use this fix, and when it's more appropriate to replace throw with another construct.
Cleaning the Interface
There are two key problems with the generator as it stands. Neither of them have to do with correctness -- it behaves as expected. They have to do with interface. So fix the interface problems with a wrapper function.
The first problem is that throw returns an important value that the current test discards. So write a wrapper that returns an unimportant value when IgnoreSubtree is called. And the second problem is that when IgnoreSubtree is thrown, sometimes it exhausts the iterator completely. So write a wrapper that catches StopIteration and handles it gracefully. This does both:
def ptv_wrapper(obj):
    pt = preorder_traversal(obj)
    while True:
        try:
            o = pt.next()
            while True:
                try:
                    yield o
                except IgnoreSubtree as e:
                    yield
                    o = pt.throw(e)
                else:
                    break

        except StopIteration:
            return

Your above code will work as-is if you use the above as a wrapper around preorder_traversal.
When to Use throw; When to Use Callbacks; When to Use send
The question of whether to use throw in this case is a difficult one. As danvk has pointed out, this exception-based method uses some pretty complex (and exotic) techniques, and the extra complexity may not be worth it. Additionally, there's something a little fishy about using exceptions for control flow. Generators already do it internally (using StopIteration) so there must be some justification, but it's worth thinking about what that justification is.
The first question is whether using throw increases or decreases the complexity of the code that already exists. If your use-case does not involve tight coupling between the generator and the consumer, then you're probably better off using callbacks. (And if your code is tightly coupled but doesn't have to be, you should refactor!) However, in some cases, tight coupling is unavoidable. In those cases, using throw (or send -- see below) probably doesn't increase complexity, and might decrease it. Indeed, if you use callbacks in a situation where those callbacks depend on a lot of external state to do what they need to do, then you are probably writing code that has tight coupling and low cohesion -- the worst of both worlds! By using throw or send, you're ensuring that the generator and the state that controls it are close together; coupling will be high, but so will cohesion, which will probably result in less-complex code.
The second question is whether to use throw or send. The second option ought to be under consideration here, because it's another way for the consumer to signal the generator that something's up. You might think of send as the LBYL to throw's EAFP. Doing so helps provide some intuitions about when to use one or the other. It depends on whether you anticipate passing signals back and forth between generator and consumer frequently. EAFP code that rarely throws exceptions will generally be faster than corresponding LBYL code. But EAFP code that frequently throws exceptions will be much slower than the corresponding LBYL code. This helps to explain why Python iterators use StopIterator instead of tests: in the overwhelming majority of cases, StopIterator will only ever be thrown once! So the cost of that catch and throw becomes fixed overhead that is quickly overwhelmed by other performance bottlenecks.
This means that if your use of IgnoreSubtree is infrequent (more like Python's use of StopIterator) then you're probably justified in using throw. Otherwise, consider using send.

A: I would direct you to the docs for generator.throw:
https://docs.python.org/2/reference/expressions.html#generator.throw
To quote:

Raises an exception of type type at the point where generator was paused, and returns the next value yielded by the generator function. If the generator exits without yielding another value, a StopIteration exception is raised.

There's no way to "prune out" the {'c': 3} subtree using generator.throw, because the value has already been generated by the time you can do a comparison with it. Additionally, the documentation of generator.throw tells you that it tries to yield a "final" value, so to speak, or else it raises StopIteration if there is no final value that is yielded.


text:
Q: Exoplayer video does not scale when SurfaceView is scaled I'm using Exoplayer library to create video player application. I'm trying to make a feature like youtube: drag video player to bottom and i will be scaled to smaller size. To do that, i have used ViewDragHelper. When player is dragging, i scale it size like this:
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
            mTop = top;

            mDragOffset = (float) top / mDragRange;

            mVideoView.setPivotX(mHeaderView.getWidth());
            mVideoView.setPivotY(mHeaderView.getHeight());
            mVideoView.setScaleX(1 - mDragOffset / 2);
            mVideoView.setScaleY(1 - mDragOffset / 2);

            mDescView.setAlpha(1 - mDragOffset);
            requestLayout();
        }

mVideoView is a SurfaceView, and player take SurfaceView to render it content. The SurfaceView scale correctly but it's content doesn't.
Question: how can scale SurfaceView and it's content too?

A: Finally, i have found a solution for my question. I used TextureView instead SurfaceView, now it worked perfect.

A: You can use TextureView instead of SurfaceView like this:
<com.google.android.exoplayer2.ui.PlayerView
        android:id="@+id/play_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:surface_type="texture_view"/>

A: It's a little late as an answer, but another solution would be to wrap the SurfaceView with a FrameLayout. Then modify the layout params or the correct properites of the FrameLayout instead of directly modifying the SurfaceView.
Note: a custom Layout can also be used and in some cases might be the better approach.

A: If you have to stick with SurfaceView because you're using a third party library or whatnot, a workaround would be to scale it down using the scale animation and AFTER the animation has finished, update the layoutparams of the SurfaceView by giving the the correct size and position to where the scaled position is. It's not perfect, but should be good for those who have no other choice.


text:
Q: Teradata CLI / ODBC Login authentication : DBA Database administration / configuration / connectivity / ODBC / CLI We moved from LDAP authentication to Active directory from MS. So right now instead of using a separate TD password we will use our workstation password.
I'd like to know the why of this rather than how , which I already seemed to have.
I am using Teradata 15.00.xx ODBC driver ( we are on 15.1xxx Server )  and these are the available logon as per doc .On my ODBC settings I dont not have a drop-down for NTLM% rest of 'em are there
mechanisms

Mechanism

Specify the desired security checking mechanism.

Apple OS X supports only TD2 and LDAP.

Kerberos (KRB5), Kerberos Compatibility (KRB5C), NT LAN Manager (NTLM), and NT LAN Manager Compatibility (NTLMC).

Valid Mechanism values are:

•

Empty - the same as omitting the keyword.

•

TD1 - selects Teradata 1 as the Authentication Mechanism. Username and password are required.

•

TD2 - selects Teradata 2 as the Authentication Mechanism. Username and password are required.

•

LDAP - selects Lightweight Directory Access Protocol (LDAP) as the Authentication Mechanism. The application provides the username and password.

•

KRB5 - selects Kerberos (KRB5) on Windows clients working with Windows servers. To logon using KRB5, the user needs to supply a domain, username, and password. The domain is specified by setting the username to MyUserName@MyDomain.

•

NTLM - selects NTLM on Windows clients working with Windows servers. The application provides the username and password.

When we were on LDAP - we chose LDAP from the drop down and stuck in a TD user/pass  & all was well.After moving to MS active directory we still do have to use LDAP  followed by workstation username / password  and it will work fine. Question was even after we migrated to  MS active directory why does the drop-down for LDAP still apply. Other mechanisms wont work.Some of em give Invalid credential errors while others will give spit out some weird byte code and quit

A: NTLM has been replaced by Windows Kerberos. NTLM in the Teradata client is provided for backward compatibility. Active Directory can be configured to use either LDAP or Kerberos as the protocol used to complete authentication tasks. In your environment, LDAP is the protocol being used to query the directory services provided by Active Directory.


text:
Q: special value set error in oracle ebs form When I define the special value set on validation set and define the pl/sql in the special validation routines. Then, try to click the list of val to select the record but the result is fail. Then, the error message "APP-FND-01564 ORACLE error 6550 in fdxpls".
oracle ebs form R12.2.5
FND PLSQL "DECLARE
  v_sec_inv VARCHAR2(15);
   BEGIN

     SELECT msi.SECONDARY_INVENTORY_NAME
     INTO v_sec_inv
   FROM MTL_SECONDARY_INVENTORIES msi,
       ( SELECT rcvt.TRANSACTION_ID,
                rcvt.LAST_UPDATE_DATE,
                rcvt.RECEIPT_NUM,
                rcvt.attribute1,
                rcvt.attribute2
           FROM rcv_transactions rcv, apps.RCV_VRC_TXS_VENDINT_V rcvt
            WHERE rcv.TRANSACTION_ID = rcvt.TRANSACTION_ID
             AND rcv.ATTRIBUTE_CATEGORY = 'EXP'
             AND rcv.PROJECT_ID IS NOT NULL
         ) a
      WHERE  msi.SECONDARY_INVENTORY_NAME = a.attribute1
         AND NVL(msi.subinventory_type, 1)  = 1
         AND NVL(msi.disable_date, SYSDATE + 1) > TRUNC(SYSDATE)
         AND msi.SECONDARY_INVENTORY_NAME = v_sec_inv
     ;

   EXCEPTION
   WHEN OTHERS
    THEN

     fnd_message.set_name('ABC_EXP_SUBINV_NEW','FLEX_VALIDATE_ERROR');
      fnd_message.set_token('VAL','Please enter the vaild subinventory');
        fnd_message.raise_error;
     END;"

The result is fail and show the below of error message:
APP-FND-01564: ORACLE error 6550 in fdxpls
Casue: fdxpls fail due to ORA-06550: line 1, column 1183:
  PLS-00103: Encountered the symbol "end-of-file" when expecting one of the following:
;'


text:
Q: findById returning a list of documents instead of a single result I'm trying to get an item object via its object Id from mongodb, but when i tried to call that route in postman it gives me a list of every single object in the database (total of 4 objects) instead of the expected one object.
Here's the function i created for getting one object from the database
getEvent : function(id,callback)
{
   EventModel.findById(id,callback);
},

And Below is my routes
router.get('/events/:id',function(req,res)
{
    var id = req.params.id;
    db.getEvent(id,function(err,event)
    {
        if(err)
        {
            console.log("Error processing data");
        }
        else{
            console.log("get one event is called");
            res.send(event)`enter code here`;
        }
    })
});

And Finally Below is the result
Postman Test Result

A: The code is correct, the way you are making request is wrong
Your Format :
http://localhost:3000/events?id=someid

id = someID in the URL represents a GET query parameter.
If you are using wildcard parameters like :id in the route, then the request URL should be :
http://localhost:3000/events/someid

someid will now be present in req.params.id
You are getting all the objects is because the variable id is undefined in your case, undefined parameters are omitted by default. So it is same as calling :
EventModel.findById({}, callback)
Thanks

A: You can try calling Model.findOne() instead of Model.findById
EventModel.findOne({id}, callback)


text:
Q: Implementing queued tasks that start based on conditions I am looking for the ideal/thread safe implementation of a task queue that will start each task based on an internal condition (which i also only want to be checked at a timed interval), but also check that there aren't too many other tasks running. I also want a way to return progress of each task in the queue.
To give some background, I have a FileSystemWatcher that sends an event on a new folder being made. I then want to put this into a queue to process the folder, when it is no longer locked. But at the same time I want to guard against too many instances of the Process task from running.
Heres some pseudo-code of what I am after.
    private static void EventToQueue(object sender, EventArgs e)
    {
        ProcessQueue.Enqueue(Task, condition);
    }

    private static async void NewQueueObject(object sender, QueueObject e)
    {
        if (e.Condition && ProcessQueue.ActiveTask < 4)
        {
             var progress = new Progress<int>();

             progress.ProgressChanged += ( s, e ) =>
             {
                 UpdateProgress(e.Value);
             };
             await LongProcess(e, progress);
        }
        else
        {
            e.Delay(30);
        }
    }


text:
Q: Overflow with ellipsis ruins flex's children sizes I'm displaying response in rows, each of the rows is a flex container with 3 children, split by the flex-basis property. I've added a text to the first child in which I wanted to use an ellipsis in case it's too long. However adding the text completely ruins the view by extending the first flex child (each row has different sizes, the second and third children are not directly underneath each other). It looks like the text length has impact on how much the first child will be extended.
Here's what the code looks like (more or less):

.parent-flex {
    display: flex;
    justify-content: space-between;
    align-content: center;
    margin: 0 10px;

    .child-1 {
        min-width: 0;
        display: flex;
        flex-direction: column;
        flex-basis: 45%;
    }

    .child-1-text {
        display: flex;
        flex-wrap: nowrap;
    }

    .child-2 {
        min-width: 0;
        flex-basis: 35%;
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-start;
        align-content: center;
    }

    .child-3 {
        min-width: 0;
        flex-basis: 20%;
        display: flex;
        flex-wrap: wrap;
        justify-content: flex-end;
        align-items: flex-end;
        flex-direction: column;
    }
}

.text-with-ellipsis {
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
}

            Text Additional text

            Text to be shortened with ellipsis.

            X

            Some more text

...

...

I was looking through different cases related to flex and overflow but nothing seemed to work for me. I've tried wrapping the div with the ellipsis with another div, adding min-width: 0 to it, flex-shrink and flex-grow but it didn't help (but maybe I was inserting them into wrong places).
When I remove white-space: nowrap from the styles the children ratio is back to normal, but obviously the text isn't wrapped.
I can confirm that the wrapped text div width is dependent on the length of the text inside - the longer it is, the bigger the div gets (ignoring it's parent size). Like the clientWidth (or scrollWidth maybe) is calculated based on the text, not on the desired width.

A: Do this. I used a table instead of divs but you have to add the classes ".first, .second and .third" on your own. The UI is very similar and the third column auto resizes.
THE CODE SNIPET IS BELOW

table {
  --first: 45vw;
  /*width of the first column*/
  --second: 20vw;
  /*width of the second column*/
  --third: clac(abs(100vw - var(--first) - var(--second)));
  /*third column: auto resize*/
  width: 100%;
}

td {
  text-align: left;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.first {
  width: calc(var(--first) - 16px);
  max-width: calc(var(--first) - 16px);
}

.second {
  width: calc(var(--second) - 16px);
  max-width: calc(var(--second) - 16px);
}

.third {
  width: calc(var(--third) - 16px);
  max-width: calc(var(--third) - 16px);
}

      Title1
      Title2
      Title3

      Text Additional text
      Some more text
      Dummy text

      Text to be shortened with ellipsis
      Nice to meet you
      See you soon

A: You had a couple syntax errors in your CSS which I have fixed below. This fixes the issue with the elements extending beyond the bounds set by flex-basis

.parent-flex {
  display: flex;
  justify-content: space-between;
  align-content: center;
  margin: 0 10px;
}

.child-1 {
  min-width: 0;
  display: flex;
  flex-direction: column;
  flex-basis: 45%;
}

.child-1-text {
  display: flex;
  flex-wrap: nowrap;
}

.child-2 {
  min-width: 0;
  flex-basis: 35%;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-content: center;
}

.child-3 {
  min-width: 0;
  flex-basis: 20%;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  align-items: flex-end;
  flex-direction: column;
}

.text-with-ellipsis {
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

    Text Additional text

    Text to be shortened with ellipsis.

    X

      Some more text

...

...

A: You should add width to the .text-with-ellipsis class. I also changed flex-basis with width and max-width.

.parent-flex {
  display: flex;
  justify-content: space-between;
  align-content: center;
  margin: 0 10px;

  .child-1 {
    min-width: 0;
    display: flex;
    flex-direction: column;
    width: 45%;
    max-width: 45%;
  }

  .child-1-text {
    display: flex;
    flex-wrap: nowrap;
  }

  .child-2 {
    min-width: 0;
    width: 35%;
    max-width: 35%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-start;
    align-content: center;
  }

  .child-3 {
    min-width: 0;
    width: 20%;
    max-width: 20%;
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-end;
    align-items: flex-end;
    flex-direction: column;
  }
}

 .child-1 .text-with-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 70%;
}

            Text Additional text

            Text to be shortened with ellipsis.

            X

            Some more text

...

...

A: The only solution I have right now is setting the width of the .text-with-ellipsis to a defined size. I used media queries to help it scale up and down  for different screen sizes. So something like this:

.text-with-ellipsis {
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    width: 500px;

    @media (max-width: 1400px) {
        width: 400px;
    }
}


text:
Q: How to make executable run in background using python? My problem is that I don't know how to release a resources using python.
I'm using Ubuntu Linux and trying to call some application, but when it is called, it doesn't release resources, it just hangs. I know about & but it gets passed as argument to application, it doesn't execute application in background.
My code:
import os, subprocess

path_to_app = os.path.join('/', 'usr', 'bin', 'firefox')

subprocess.Popen([path_to_app], '&')

print("Something..") # Hangs until app is closed

How to just run application and move on, without hanging ?

A: I solved it somehow using:

subprocess.Popen([path_to_app], shell=True)


text:
Q: Duplicate Formula Dynamically in PhpExcel I am new to PHPExcel. I wanted to duplicate the formula with updated cell values. For example,
In cell C1 the formula is (A1 * B1).
I am copying the rows from cell range A1:C1 to A5:C5.
The cell values are getting copied successfully. But The formula is not updating. I wanted to update the formula as (A2 * B2), (A3 * B3) etc..
Note: I cannot update the formula manually. The only way I can do is, Read the formula, parse it and then update the cell values accordingly.
I have tried this,
How to improve formula calculation with PHPExcel?
I have changed the private processTokenStack function to public, But it is throwing "Call to Undefined method PHPExcel_Calculation::processTokenStack() " error.
Kindly guide me.
Thank You

A: PHPExcel provides functionality for this in the PHPExcel_ReferenceHelper class (the same functionality that adjusts cell references when you insert/delete rows and columns).
The method is updateFormulaReferences(), which has the following signature:
/**
 * Update references within formulas
 *
 * @param     string    $pFormula    Formula to update
 * @param     string    $pBefore    Insert before this cell
 * @param     int       $pNumCols    Number of columns to insert
 * @param     int       $pNumRows    Number of rows to insert
 * @param     string    $sheetName  Worksheet name/title
 * @return    string    Updated formula
 * @throws    PHPExcel_Exception
 */

As an example of use:
$formula = '=(A1 * B1)';
echo $formula, PHP_EOL;

$referenceHelper = PHPExcel_ReferenceHelper::getInstance();

$adjustedFormula = $referenceHelper->updateFormulaReferences($formula, 'A1', 0, 1);

echo $adjustedFormula, PHP_EOL;

which will output
=(A1 * B1)
=(A2 * B2)


text:
Q: fixed point to find root of a²+a³=392 but report OverflowError I tried to find the root of a²+a³=392 with fixed_point introduced by SICP 1.1.3 functions as general method
#+BEGIN_SRC scheme :session sicp
(define tolerance 0.00001)

(define (fixed-point f first-guess)
  (define (close-enough? v1 v2)
    (< (abs (- v1 v2))
       tolerance))
  (define (try guess)
    (let ((next (f guess)))
      (if (close-enough? guess next)
          next
          (try next))))
  (try first-guess))
#+END_SRC

I rewrite it in python as:
#+begin_src ipython :session sicp :results output :tangle pySrc/sicp_fixedpoint.py
import math
tolerance = 0.00001

import math

def fixed_point(f, guess):
    while True:
        nex = f(guess)
        if abs(guess-nex) < tolerance:
            return nex
        else:
            guess = nex

def f(x):
    return 392 / (x + x**2)
fixed_point(f, 1)
#+end_src

It report error:
 OverflowError: (34, 'Numerical result out of range')

What's the problem?

A: I think this problem is not well suited for solving via a fixed-point procedure. If you print the (abs (- next guess)) for each iteration, you'll see that the value is increasing between iterations, it'll never converge to the specified tolerance - hence the Numerical result out of range error.


text:
Q: Suggest to make tag [c1x] a synonym of [c11] (or merge?), now the Standard is officially released Now that the official C Standard "ISO/IEC 9899:2011" has been released, all questions tagged with c1x to indicate the next official C release would refer to this official version. In addition, I found two questions tagged with c11 already, with a rising tendency, I'd assume.
Since I haven't got the required reputation, I'd suggest either a merge or adding a synonym.
I hope this is the way to do it, if not, please enlighten me.
EDIT: I've re-tagged all (11) questions using c1x to using c11, see the comments below. But I still think a synonym would be helpful, otherwise we'd have to recheck for c1x regularly, and re-tag those manually every time. Can anyone provide a link or some information on what went wrong with c++1x vs. c++11? What would we need to avoid?


text:
Q: How to save a picture to a specific file after using OpenCV to take it? I use Python 3 and Windows. Currently, all my program can do is take a picture and display it, but I want to be able to save it to a specific destination. Here is the program:
# import the opencv and numpy libraries
import cv2
import numpy as np

# define a video capture object
cap = cv2.VideoCapture(0)
ret, frame = cap.read()

while(True):

    cv2.imshow('img1',frame)
    if(cv2.waitKey(1) and 0xFF == ord('y')):
        cv2.imwrite('images/c1.png', frame)
        cv2.destroyAllWindows()
        break

cap.release()

Edit: BTW I'm new to Python and OpenCV so this code is mostly someone else's (forgot who so I can't cite, sorry).

A: You are currently writing the image to a file 'images/c1.png'. You can change this to an absolute path where you want to save the image i.e. C:/Users/User/Pictures/c1.png or you can set the current working directory to a different folder with os.chdir('desired location') so that it saves all images to that particular location (in this case it will save the image as 'images/c1.png' in that location).


text:
Q: How to show for a linear ODE system, the solution can be given as the linear relation $p(t)=K(t)x(t)+s(t)$?? Suppose we have the following ode system:
$$\begin{bmatrix} \dot x(t) \\ \dot p(t) \\ \end{bmatrix} = \begin{bmatrix} a_{11} && a_{12} \\ a_{21} && a_{22} \\ \end{bmatrix}\begin{bmatrix} x(t) \\ p(t) \\ \end{bmatrix}
+\begin{bmatrix} r_1(t) \\ r_2(t) \\ \end{bmatrix};$$
is it always correct to suppose $p(t)=K(t)x(t)+s(t)$? How can we show this relation holds?

A: Assuming $p(t) = Kx(t)+s(t)$. If your coefficients are constant, then:
$$\frac{dp}{dt} = K\frac{dx}{dt} + s'(t) = a_{21}x+a_{22}p + r(t)$$
implies that:
$$Ka_{11} = a_{21}, Ka_{12} = a_{22}.$$
If your coefficient matrix is not constant, you can work the same.


text:
Q: cross-compilation FFTW for cortex-a15 failure: co-processor offset out of range I am trying to cross-compil FFTW 3.3.3 for cortex-a15 ARM processor with neon support but I get this error:
/tmp/ccsNpqyK.s: Assembler messages:
/tmp/ccsNpqyK.s:1035: Error: co-processor offset out of range
Here is my configuration:
./configure --prefix=/usr/fftw_3_float_neon_ARNDALE --with-slow-timer --host=arm-linux-gnueabi --target=arm-linux-gnueabi --enable-float --enable-neon "CC=/usr/bin/arm-linux-gnueabi-gcc-4.6 -mfloat-abi=softfp -mcpu=cortex-a15 -mtune=cortex-a15 -O3 -mfpu=neon -ftree-vectorize -ftree-vectorizer-verbose=2 -mvectorize-with-neon-quad -funsafe-math-optimizations"
I tried to remove -O3 option but I got the same error.
The cross-compilation works for ARM cortex-a9.
Could anyone help me to fix that problem ?
Thanks in advance for your help,
Guix

A: Try to turn off auto vectorization.


text:
Q: code for order list in SAS / schedule order list I use SAS EG, and am trying to schedule some daily work.

*

*is there a way to schedule a order list instead of scheduling the whole process flow?

*if not, I looking for a code that can execute order list, so that I can only schedule on that program...

A: http://support.sas.com/kb/19/020.html
By design, the option to Schedule an Ordered List is not enabled. To
circumvent the problem, select and copy the objects from the project and
paste them into a new Process Flow. Then arrange them in the order you
wish and, finally, schedule the Process Flow.
For details on all the ways you can schedule jobs in EG, these two papers have excellent details. :
http://blogs.sas.com/content/sasdummy/2012/04/17/doing-more-with-sas-enterprise-guide-automation/
http://support.sas.com/documentation/onlinedoc/guide/examples/SASGF2012/Hemedinger_298-2012.pdf

A: If you're willing to do a bit of scripting, either in VBScript or Powershell or .Net, this is possible.  It's not recommended, though, because as Keni notes, SAS explicitly didn't make this possible, and says so (as opposed to just forgetting to do it).  So I am not sure why that is - and so it's possible this could lead to problems.
However: it is possible.  The hooks in the API exist to run an ordered list, at least from a technical standpoint.  Again - I don't know if this risks conflicts or anything else, and you might want to consider posting in the SAS Community forum to see if Chris H or one of the other folks on that forum can clue you in as to why it's not made possible in the IDE.
Basically, you can access the Ordered List through the API via the ContainerCollection that is part of the project.  Inside that container collection is a container called "Ordered Lists".  Inside that container is a container for each ordered list in the project.  So, you might access that through project.ContainerCollection.Item(i).Items.Item(j), where i seems to be 0 consistently in my initial testing (but don't rely on that, I'm not sure if it's always 0) and j is the number of the particular ordered list you're running.
To do this, I created a copy of the VBScript that EGuide produces when you ask it to schedule a process flow, and tweaked it to find the ordered list.  This is very kludgy - in part because my VBScript knowledge is mediocre and old, and in part out of a desire to get this done faster.  You may have to make changes to make this work (other than adjusting the path to project and project file name in the prjName variable and the containerName variable (which should be your Ordered Lists's name).
What it does is cycles through all Containers in the ContainerCollection, and tests if they're named "Ordered Lists".  Then it cycles through the containers in that container, and tests if they're named whatever you put in the containerName variable (your Ordered List's name).  When it finds one that is, it exits the for loop and runs that container (i.e., runs that ordered list).
This can then be scheduled, or run directly (either by double clicking in Windows, or using cscript.exe in console). If you're running EG in a non-Windows environment, it's possible this still could work (if you have a VBScript compiler), but I'm not sure if the API works the same way or not.  (Your SAS environment shouldn't matter, just the EG environment.)
Option Explicit
Dim app         ' As SASEGuide.Application

Call dowork

'shut down the app
If not (app Is Nothing) Then
    app.Quit
    Set app = Nothing
End If

Sub dowork()
    On Error Resume Next
    '----
    ' Start up Enterprise Guide using the project name
    '----
    Dim prjName     ' As String
    Dim prjObject   ' As SASEGuide.Project
    Dim containerName     ' As String
    Dim containerObject   ' As SASEGuide.Container
    Dim containerColl     ' As SASEGuide.ContainerCollection
    dim orderedListObject ' as SASEguide.Container

    prjName = "\\pathtoproject\test project.egp" ' Project Name
    containerName = "My Ordered List" ' Name of the Ordered List

    Set app = CreateObject("SASEGObjectModel.Application.7.1")
    If Checkerror("CreateObject") = True Then
        Exit Sub
    End If

    Set prjObject = app.Open(prjName,"")
    If Checkerror("App.Open") = True Then
        Exit Sub
    End If

    '-----
    'Get The Container Collection and Object
    '-----
    Set containerColl = prjObject.ContainerCollection
    If Checkerror("Project.ContainerCollection") = True Then
        Exit Sub
    End If

    Dim i        ' As Long
    Dim j        ' As Long
    Dim count    ' As Long
    Dim count_OL ' as Long
    count = containerColl.count
    For i = 0 To count - 1
        Set containerObject = containerColl.Item(i)

        If Checkerror("ContainerCollection.Item") = True Then
            Exit Sub
        End If

        If (containerObject.Name = "Ordered Lists") Then
            count_OL = containerObject.items.count
            For j = 0 to count_OL - 1
                If Checkerror("ContainerCollection.Item") = True Then
                    Exit Sub
                End If
                Set orderedListObject = containerObject.items.item(j)
                If (orderedListObject.name = containerName) then
                    exit for
                Else
                    Set orderedListObject = Nothing
                end if
            Next
            Exit For
        Else
            Set containerObject = Nothing
            Set orderedListObject = Nothing
        End If
    Next

    If not (orderedListObject is nothing) Then
        '----
        ' Run the Container
        '----
        orderedListObject.Run
        If Checkerror("Container.Run") = True Then
            Exit Sub
        End If
    Else
        wscript.echo "Not Found"

    End If

    '-----
    ' Save the new project
    '-----
    prjObject.Save
    If Checkerror("Project.Save") = True Then
        Exit Sub
    End If

    '-----
    ' Close the project
    '-----
    prjObject.Close
    If Checkerror("Project.Close") = True Then
        Exit Sub
    End If

End Sub

Function Checkerror(fnName)
    Checkerror = False

    Dim strmsg      ' As String
    Dim errNum      ' As Long

    If Err.Number <> 0 Then
        strmsg = "Error #" & Hex(Err.Number) & vbCrLf & "In Function " & fnName & vbCrLf & Err.Description
        MsgBox strmsg  'Uncomment this line if you want to be notified via MessageBox of Errors in the script.
        Checkerror = True
    End If

End Function