text:
Q: PHP: Strip link before storing into MySQL database (Regex stripping?) new to PHP so i'm still learning how to do certain stuff.
I am trying to store a Youtube link into my database. the code i use is valid and stores my form into the database without problems.
My Question: I don't want to store the entire Youtube link, but just the ID of the link.
For example: i enter this link into my forminput: http://www.youtube.com/watch?v=sIkhewd69SE
The only thing i want to store is: sIkhewd69SE
This because i want to embed the entries later in other pages.
Here's the HTML of the form:
<form action="uploadcomplete.php" method="post">

                                Paste a Youtube link:
                                <input size="50%" id="link" class="form-text" name="link"type="text"/>

                                Enter the title:
                                <input size="30%" id="title" class="form-text" name="title" type="text"/>

                                Enter the artist:
                                <input size="30%" id="artist" class="form-text" name="artist" type="text"/>

                                <input id="submit" class="submit" type="submit" name="submit" value="Upload!" />

                        </form>

Here's PHP-function called on by the form (UPLOAD COMPLETE.PHP) :
$errors = array()

if (isset($_POST['link']) && isset($_POST['title']) && isset($_POST['artist'])) {
  if (strlen($_POST['link'])<3) $errors[] = 'Uw naam moet minstens 3 letters bevatten';
  if (strlen($_POST['title'])<6) $errors[] = 'De naam van uw bedrijf moet minstens 3 letters bevatten';
  if (strlen($_POST['artist'])<6) $errors[] = 'Uw nummer moet minstens 9 nummers bevatten';

  if(count($errors)<1) {
    $conn = new mysqli('localhost', 'root', '', 'silentbeats');

    if (mysqli_connect_errno()) {
      exit('Connectie gefaald: '. mysqli_connect_error());
    }

    $adds['link'] = $conn->real_escape_string($_POST['link']);
    $adds['title'] = $conn->real_escape_string($_POST['title']);
    $adds['artist'] = $conn->real_escape_string($_POST['artist']);

    $sql = "INSERT INTO `tbltracks` (`link`, `title`, `artist`)
    VALUES ('". $adds['link']. "', '". $adds['title']. "', '". $adds['artist']. "')";

    if ($conn->query($sql) === TRUE) {
      echo 'Uw gegevens werden opgeslagen, bedankt!';
      echo "
Terug naar de hoofdpagina";
    }
    else {
      echo 'Error: '. $conn->error;
    }

    $conn->close();
  }
  else {
    echo "";
    echo "";
  }
}
else {
  echo 'Geen data ontvangen van formulier';
}
?>

How do i store only the ID tag of this?
Any help would be appreciated, i'm really stuck on this one.

A: This should do what you want, even if there are more parameters in your url:
$ytLink = 'http://www.youtube.com/watch?v=sIkhewd69SE';
$ytId = preg_replace('/^.+v=(\w+)&*.*$/', '$1', $ytLink);
echo $ytId;

A: list($query, $arg) = (explode('=', parse_url($_POST['link']))['query']));

The value you're looking for will be in $arg


text:
Q: PHP How do i check to see if the both emails match before i can submit the form? I have the below code, I want to validate the form to make sure both emails match before the for gets submitted.
The emails are on line 24 & 26
Thanks in advance.
<?php
include_once 'includes/config.php';
$pageTitle = 'Members';
include HEADER;
?>

<?php
$fname  = "";
$lname  = "";
$email1 = "";
$email2 = "";
?>

To create an account with us please fill out the form below

<form action="sendRegister.php" method="get">
    First Name: <input name="new[fname]" type="text">

    Last Name: <input name="new[lname]" type="text">

</form>

Email : <input name="new[email1]" required="" type="email" value="<?php echo $email1;?>">

Re-Enter Email : <input name="new[email2]" required="" type="email" value="<?php echo $email2;?>">

Password: <input name="new[password1]" type="password">

Re-enter password:<input name="new[password2]" type="password">

Gender: <select name="new[gender]">
    <option value="Male">
        Male
    </option>

    <option value="Female">
        Female
    </option>
</select>

State of Residence:<select name="new[states]">
    <option value="NY">
        New York
    </option>

    <option value="NJ">
        New Jersey
    </option>
</select>

<?php
if(isset($email1) != $email2){
echo 'please correct your email';
}
?>
<input type='submit' value='submit'>
</form>
<?php
include FOOTER;
?>

A: try:
if(isset($email1, $email2)) {
  if($email1 != $email2){
    echo "Bad Email"
    ....
  }
}

You can also use javascript to do this (http://www.w3schools.com/js/js_form_validation.asp)

A: I think it's best to use JavaScript for this, especially if you want it validated prior to submission, as (afaik) PHP would have to do the check upon submission, whereas you can use JavaScript to check as the submit button is clicked and depending on the result of the validation carry on.
Take a look at: W3Schools JS Form Validation

A: If you want to check before you submit the form, you must do it with javascript.
A second possibility is: put your submitted form-values as defauld value e.g.:
<?php
$pass1=$_POST["pass1"];
$pass2=$_POST["pass2"];
if (isset($pass1,$pass2) && $pass1!=$pass2) echo 'Your password confirmation is not equal to your password';
echo '<form ....>';
echo '<input type="text" name="pass1" value="'.$pass1.'">';
echo '<input type="text" name="pass2" value="'.$pass2.'">';
echo '</form>';
?>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Embedded a Lua interactive prompt window in C# I tried to provide some script features in my C# App.
   After some searches, The Lua and LuaInterface looks like a reasonable way to do it.
   By embedding a Lua VM in my C# code, I can load a Lua script and process methods
   defined in the C# class without any problems.
However, I wonder is there a way to not only execute a lua script file in
   my c# program, but also to have a lua interactive prompt in my program?
   Thus I can type commands and see the returns immediately.
Any hint about where I should start to work on it will be very helpful!
Best Regards

A: Lua's debug module contains a very basic interactive console: debug.debug() (the Lua manual suggests this module should be used only for debugging).
If that doesn't meet your needs, it's easy enough to implement one yourself. If you were to write it in Lua itself, the absolute bare bones console would be:
while true do
   io.write("> ")
   loadstring(io.read())()
end

That'll crash on either a syntax or runtime error. A slightly less minimal version, which captures (and ignores) errors:
while true do
   io.write("> ")
   local line = io.read()
   if not line then break end -- quit on EOF?
   local chunk = loadstring(line)
   if chunk then
      pcall(chunk)
   end
end

This could be enhanced by displaying syntax errors (second return value from loadstring on failure), runtime errors (second return value from pcall on failure), return values from evaluated code ([2..N] return values from pcall on success), etc.
If you want to get really fancy, you can allow people to enter multi-line statements. Look at src/lua.c in the source distro to see how this is done.


text:
Q: Dynamically set class attribute in html with ionic framework and angular js I've got two types of diagrams chart chart-line and chart chart-barand I want to create an html tag like this
                        <canvas class="category.diagramType"
                            chart-data="category.data"
                            chart-labels="category.labels"
                            chart-legend="true"
                            chart-series="category.series"></canvas>

category is definded in the controller. But setting the class attribute dynamically doesn't work. After Exchanging category.diagramType with chart chart-bar the diagram appreas.
The Question now is: How can i get class="category.diagramType" getting to work?

Just for information: In my real code im using ng-repeat to iterate through a list

angular.module('starter.controllers', [])

    .controller('ProfileCtrl', function ($scope, $http) {
        $scope.categories = [
            {
                title: 'Zeit',
                id: 1,
                labels: ["January", "February", "March", "April", "May", "June", "July"],
                series: ['Series A', 'Series B'],
                data: [[65, 59, 80, 81, 56, 55, 40], [28, 48, 40, 19, 86, 27, 90]],
                diagram: 'chart chart-bar'
            },
            {
                title: 'G-Kräfte', id: 2,
                labels: ["January", "February", "March", "April", "May", "June", "July"],
                series: ['Series A', 'Series B'],
                data: [[65, 59, 80, 81, 56, 55, 40], [28, 48, 40, 19, 86, 27, 90]],
                diagram: "chart chart-bar"
            },
            {
                title: 'Unfälle', id: 3,
                labels: ["January", "February", "March", "April", "May", "June", "July"],
                series: ['Series A', 'Series B'],
                data: [[65, 59, 80, 81, 56, 55, 40], [28, 48, 40, 19, 86, 27, 90]],
                diagram: "chart chart-bar"
            },
            {
                title: 'Tanken', id: 4,
                labels: ["January", "February", "March", "April", "May", "June", "July"],
                series: ['Series A', 'Series B'],
                data: [[65, 59, 80, 81, 56, 55, 40], [28, 48, 40, 19, 86, 27, 90]],
                diagram: "chart chart-line"
            },
            {
                title: 'Lautstärke', id: 5,
                labels: ["January", "February", "March", "April", "May", "June", "July"],
                series: ['Series A', 'Series B'],
                data: [[65, 59, 80, 81, 56, 55, 40], [28, 48, 40, 19, 86, 27, 90]],
                diagram: "chart chart-line"
            },
            {
                title: 'Spenden', id: 6,
                labels: ["January", "February", "March", "April", "May", "June", "July"],
                series: ['Series A', 'Series B'],
                data: [[65, 59, 80, 81, 56, 55, 40], [28, 48, 40, 19, 86, 27, 90]],
                diagram: "chart chart-bar"
            }
        ];

    })
<ion-view view-title="Fahrerprofil">
    <ion-content>
        <ion-list>
            <ion-item ng-repeat="category in categories" href="#/app/categories/{{category.id}}">

{{category.title}}

                        <canvas ng-class="category.diagram"
                                chart-data="category.data"
                                chart-labels="category.labels"
                                chart-legend="true"
                                chart-series="category.series"
                                chart-options="{showTooltips: false}"></canvas>

            </ion-item>
        </ion-list>

    </ion-content>
</ion-view>

A: You should use ng-class instead of class so change the code such this
   <canvas ng-class="category.diagramType"
                        chart-data="category.data"
                        chart-labels="category.labels"
                        chart-legend="true"
                        chart-series="category.series"></canvas>

A: If you just want two classes then you can use ng-class in the following way:

    ....

Where you expression will be something like category.diagramType == 'chart chart-bar'
If you need this for multiple classes then follow the below style:

    ....


text:
Q: Telerik RADListBox with CheckBox - How to trigger a checked item in checkbox to call its RADListBox SelectedValue event I am having a UI problem with RadListBox and checking items in a Checkbox.  The issue is that my selection in the checkbox wont trigger an event since its the selection in the RADListBox that triggers it.  And the user needs to check the Checkbox and then select (click) the item in the radlistbox to trigger the SelectedValue event of it.  I would like to have it so that when the user checks a checkbox the Selectedvalue event of the RadListBox gets called too.  Here is my WPF code:

<telerik:RadListBox  Grid.Row="1" x:Name="ExportersList" ItemsSource="{Binding Exporters}" Style="{StaticResource ModalListBoxStyle}"
           Visibility="{Binding ExportComplete, Converter={StaticResource InverseBoolToVisibilityConverter}}"
           SelectedValue="{Binding ExportFormatName, Mode=TwoWay}" SelectedValuePath="Name" SelectionMode="Multiple">
            <telerik:RadListBox.ItemTemplate>
                <DataTemplate DataType="{x:Type interfaces:BaseTourSheetExporterType}">
                    <StackPanel Orientation="Horizontal">
                        <CheckBox IsChecked="{Binding IsExporterChecked}" />
                        <TextBlock Text="{Binding Name}"  Margin="5" />
                    </StackPanel>
                </DataTemplate>
            </telerik:RadListBox.ItemTemplate>
        </telerik:RadListBox>

Please note that the event SelectedValue is bound to a property in my class and when it gets/sets I am enabling/disabling another button.  I don't know how to get my Checkbox IsChecked event (when a user checks or unchecks the checkbox) to trigger the selectedvalue event of the radlistbox and basically allowing my user to just check/uncheck a Checkbox that triggers another get/set property (ExportFormatName).  So this way the user can do it without selecting the item again in the radlistbox (clicking outside the checkbox) to trigger that get/set property event. Please help me with this WPF part.
Just to note aside of this, I'm purposely binding the CheckBox IsChecked to a class called BaseTourSheetExporterType that is holding a member Boolean value (IsExporterChecked).  This determines whether its been checked or not (this class and member is required to remember my changes for when I'm re-opening the window).

A: I resolved the issue now by modifying the onclick event of the checkbox.  Here is the updated version of the function (please note last line) where I force a call to selectedvalue and my RadListBox:
private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
    {
        var cb = sender as CheckBox;
        if (cb == null)
        {
            return;
        }

        var item = cb.DataContext;
        this.ExportersList.SelectedItem = item;
        this.ExportersList.SelectedValue = this.ExportersList.SelectedItem.GetType().GetProperty("Name").GetValue(this.ExportersList.SelectedItem, null);
    }


text:
Q: IB TWS API has a SocketException when calling eDisconnect() on the EClientSocket which occurs at java.io.DataInputStream.readInt(EClientSocket) To use the Interactive Brokers (IB) TWS API, I need to write a class that implements EWrapper.  I am having trouble properly disconnecting my socket in that class, even when using the built-in eDisconnect() method provided by IB.
Whenever I write a class that implements EWrapper, calling eDisconnect() on the EClientSocket instance throws an Exception (which is passed to error(Exception e)...more details below).  I would like to be able to disconnect properly, so that I can connect and disconnect serially within the same program.
Consider the following example:
public class ConnectionTest {
    public static void main(String[] args) {
        // Create Contract
        Contract contract = new Contract();
        contract.symbol("IBM");
        contract.secType("STK");
        contract.exchange("NYSE");

        TWSCounter twsCounter = new TWSCounter(); // Class I wrote that simply keeps track of ID request numbers
        APIClient apiClient = new APIClient(twsCounter);

        apiClient.connect();
        apiClient.reqContractDetails(contract);
        //apiClient.disconnect(); // commented out for first example
    }
}

public class APIClient implements EWrapper {
    private TWSCounter twsCounter;
    private EClientSocket clientSocket = null;
    private EJavaSignal signal = new EJavaSignal();

    private EReader reader;

    // Constructor
    public APIClient(TWSCounter twsCounter) {
        this.twsCounter = twsCounter;
    }

    public void connect() {
        // Create a new EClientSocket object
        clientSocket = new EClientSocket (this, signal);

        // Connect to the TWS
        clientSocket.eConnect("127.0.0.1", 7497, 0);

        // Pause here for connection to complete
        try {
            while (! (clientSocket.isConnected()));
        }
        catch (Exception e) {
            e.printStackTrace();
            System.err.println("Error trying to connect to TWS API");
            System.exit(1);
        }

        reader = new EReader(clientSocket, signal);
        reader.start();

        // Based on IB sample code in Test.java
        new Thread(() -> {
            while (clientSocket.isConnected()) {
                signal.waitForSignal();

                try {
                    reader.processMsgs();
                } catch(Exception e) {
                    error(e);
                    System.err.println("Error while trying reader.processMsgs()");
                }

            }
        }).start();

    }

    public void disconnect() {
        clientSocket.eDisconnect();
    }

    public void reqContractDetails(Contract contract) {
        clientSocket.reqContractDetails(twsCounter.getNextNumber(), contract);
    }

    @Override
    public void contractDetails(int reqId, ContractDetails contractDetails) {
        System.out.println("conID: " + contractDetails.conid());
    }

    // More methods...

When I run ConnectionTest, I correctly get the output, conID: 8314.  The program continues to run indefinitely, however, until I terminate it manually in eclipse by pushing the 'stop' button.
If I "uncomment" apiClient.disconnect() at the end of ConnectionTest, then the program disconnects, however an exception is thrown.
How one chooses to override the error methods in the APIClient affects what happens.  If they are not overridden, the process terminates silently, despite the Exception.
If, however, public void error(Exception e) is overridden as follows, we get the following stack trace:
public void error(Exception e) {
    e.printStackTrace();
}

java.net.SocketException: Socket closed
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.socketRead(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.io.DataInputStream.readInt(Unknown Source)
    at com.ib.client.EClientSocket.readInt(EClientSocket.java:233)
    at com.ib.client.EReader.readSingleMessage(EReader.java:119)
    at com.ib.client.EReader.putMessageToQueue(EReader.java:79)
    at com.ib.client.EReader.run(EReader.java:57)

I believe issue is that the EReader (EReader extends Thread) calls putMessageToQueue() even after the socket is disconnected.  From EReader:
    @Override
    public void run() {
        try {
            // loop until thread is terminated
            while (!isInterrupted()) {
                if (!putMessageToQueue())
                    break;
            }
        }
        catch ( Exception ex ) {
            //if (parent().isConnected()) {
                if( ex instanceof EOFException ) {
                    eWrapper().error(EClientErrors.NO_VALID_ID, EClientErrors.BAD_LENGTH.code(),
                            EClientErrors.BAD_LENGTH.msg() + " " + ex.getMessage());
                }
                else {
                    eWrapper().error( ex);
                }

                parent().eDisconnect();
            //}
        }

        m_signal.issueSignal();
    }

Modifying the APIClient.disconnect() method to interrupt the EReader, doesn't seem to help however:
    public void disconnect() {
        reader.interrupt();
        clientSocket.eDisconnect();
    }

For the most part, I've been able to get by without solving this issue properly.  What I would really like to be able to do, however, is connect and disconnect serially, as in this simplified example:
public class ConnectionTest {

    public static void main(String[] args) {
        // Create Contracts
        Contract contract = new Contract();
        contract.symbol("IBM");
        contract.secType("STK");
        contract.exchange("NYSE");

        Contract contract2 = new Contract();
        contract2.symbol("KO");
        contract2.secType("STK");
        contract2.exchange("NYSE");

        TWSCounter twsCounter = new TWSCounter();
        APIClient apiClient = new APIClient(twsCounter);

        apiClient.connect();
        apiClient.reqContractDetails(contract);

        try {
            Thread.sleep(1000);
        } catch (Exception e){
            System.err.println("Couldn't sleep");
            System.exit(1);
        }

        apiClient.disconnect();

        try {
            Thread.sleep(1000);
        } catch (Exception e){
            System.err.println("Couldn't sleep");
        }

        apiClient.connect();
        apiClient.reqContractDetails(contract2);

        try {
            Thread.sleep(1000);
        } catch (Exception e){
            System.err.println("Couldn't sleep");
        }

        apiClient.disconnect();
    }
}

Running this, as is, will sometimes correctly give conID: 8314 and conID: 8894 along with two stack traces the same as above, but will also sometimes give conID: 8314 and Connection Message: -1, 507, Bad Message Length null.  Error message 507 is:

Bad Message Length (Java-only)
Indicates EOF exception was caught while reading from the socket. This can occur if there is an attempt >to connect to TWS with a client ID that is already in use, or if TWS is locked, closes, or breaks the >connection. It should be handled by the client application and used to indicate that the socket
connection is not valid.
IB Message Codes

For what it's worth, I've been completely frustrated by this problem off and on for two years.  (I'm not a professional programmer.)  I've searched for solutions online and even paid a programmer to help me, all to no avail (although I have learned much more java in the process).  I've also downloaded the latest version of the IB API (v 9.76).  The same problem occurs with multiple versions of the IB API.


text:
Q: IntelliJ Idea Package does not exist I had an error building a jar from my project (where an external library was not being found), so I followed a Stackoverflow answer to Delegate IDE build/run actions to Maven.
Then the jar was successfully built.
I have since added a tiny bit of code and tried to recompile, however now IntelliJ cannot find my basic classes, it says package X does not exist. I only used two classes to amend my code, and both of these classes say "does not exist" during build/compilation/run. (I use 400 classes and only the two I have recently use are saying "does not exist".
I have tried to reverse all settings changes, and disabled "delegate IDE build actions to Maven", but it still says package does not exist for both of these classes.
I have even removed the JDK entirely and installed a fresh copy, but same error.
What has gone wrong, and what can I do?


text:
Q: Date time error for character vector I have a dataframe that has a datetime column like this
When <- c("09/13/2016 11:29:00 AM", "09/13/2016 07:20:00 AM")
df <- data.frame(When)
df$When <- as.character(df$When)

I try to convert this to the format that I want
df$When <- format(strptime(df$When, "%m/%d/%Y %I:%M:%S"), "%m/%d/%Y %I:%M:%S %p")

The above doesn't get converted to Date time format.
I have a function that I use to check dateformat
checkDate <- function(date, dateFormat){

  d <- try( as.Date( date, format = dateFormat))

  if( class( d ) == "try-error" || any(is.na( d )) ){
    stop( paste0("DATETIME: Need a valid DATETIME in format ", dateFormat) )
  }

}

df$When <- checkDate(df$When, "%d/%m/%Y %I:%M:%S %p")

I get an error

Error in checkDate(df$When, "%d/%m/%Y %I:%M:%S %p") :
        DATETIME: Need a valid DATETIME in format %d/%m/%Y %I:%M:%S %p

I am not understanding on how I could solve this issue. Is it the character format that is causing the error? Could someone help me point in the right direction?

A: Two minor changes and I think it should work for you:

*

*Add explicit return for d in you function

*Change your format to start with %m instead of %d.

This gives us:
checkDate <- function(date, dateFormat){

  d <- try( as.Date( date, format = dateFormat))

  if( class( d ) == "try-error" || any(is.na( d )) ){
    stop( paste0("DATETIME: Need a valid DATETIME in format ", dateFormat) )
  }

  return(d)##Added
}

df$When <- checkDate(df$When, "%m/%d/%Y %I:%M:%S %p")

df$When
#[1] "2016-09-13" "2016-09-13"

A: Using lubridate (mdy_hms) to extract timestamp and then date function to extract date
> When <- c("09/13/2016 11:29:00 AM", "09/13/2016 07:20:00 AM")
    > df <- data.frame(When)
    > df$When <- as.character(df$When)
    > df
                        When
    1 09/13/2016 11:29:00 AM
    2 09/13/2016 07:20:00 AM
> str(df)
'data.frame':   2 obs. of  1 variable:
 $ When: chr  "09/13/2016 11:29:00 AM" "09/13/2016 07:20:00 AM"
> library(lubridate)

Attaching package: 'lubridate'

The following object is masked from 'package:base':

    date

> df$When <- mdy_hms(df$When)
> df$Date=date(df$When)
> df
                 When       Date
1 2016-09-13 11:29:00 2016-09-13
2 2016-09-13 07:20:00 2016-09-13


text:
Q: create numbered, ordered list of section header elements from html using xPath I want to parse some HTML to create a nested navigation (ordered list for a table of contents) based on the section headings elements (H1,H2,H3,H4,H5,H6) using XPath. For exampe, if I have a structure like this:

Header 1.

Header 2.

SubHeader 2.1

SubHeader 2.1.1

Header 3.

SubHeader 3.1

SubHeader 3.2

I would like xPath to find all of the above header tags, or any other header tags, and parse them so I get an ordered list / menu like this:
Header 1.
Header 2.
  SubHeader 2.1
  SubHeader 2.1.1
Header 3.
  SubHeader 3.1
  SubHeader 3.2

I guess there is recursion involved to nest the elements properly. I found the following code that I tried to modify in order to extract the headings, but I just can't get my head around it:
$headers =<<<EOT

Header 1.

Header 2.

SubHeader 2.1

SubHeader 2.1.1

Header 3.

SubHeader 3.1

SubHeader 3.2

EOT;

function extractH ($level, $xpath, $dom, $position = 0, $number='')  {
    global $headerCount;
    $prevLevel = $level-1;
    $headings = $xpath->query("//*/h{$level}[count(preceding-sibling::h{$prevLevel})={$position}]");

    foreach ($headings as $key => $heading)   {
        $sectionNumber = ltrim($number.".".($key+1), ".");
        $headerCount--;
        echo "
#: ".$headerCount." ".$heading->nodeValue." [key= ".($key)."], [level= ".($level)."]
"; /* NEW */

        if ($headerCount >0) {
            $children = extractH($level+1, $xpath, $dom, $key+1, $sectionNumber); // original
        }

        if (!empty($children))    {
            $headerCount = $headerCount-1;
             echo "
No.: ".$headerCount." ".$child->nodeValue." [key= ".($childKey)."], [level= ".($level)."]
"; /* NEW */
        }

    }
}

$dom2 = new DomDocument();
$dom2->loadHTML($headers);
$xpath = new DomXPath($dom2);
$headerCount=$xpath->evaluate("count(//*[self::h1 or self::h2 or self::h3 or self::h4 or self::h5 or self::h6])");
echo "headerCount: ".$headerCount;
$output = extractH(2, $xpath, $dom2);

If I apply the above code, I get the following (header count, key and level is for testing purposes;
styling, i.e. , links etc., not inlcuded since the order of headers does not work yet).
headerCount: 7
#: 6 Header 1. [key= 0], [level= 2]
#: 5 Header 2. [key= 1], [level= 2]
#: 4 SubHeader 2.1 [key= 0], [level= 3]
#: 3 SubHeader 2.1.1 [key= 0], [level= 4]
#: 2 Header 3. [key= 2], [level= 2]
#: 1 SubHeader 3.1 [key= 0], [level= 3]
#: 0 SubHeader 2.1.1 [key= 0], [level= 4] // This should not be there
#: -1 SubHeader 3.2 [key= 1], [level= 3]

A: You could simply loop over the header elements and open/close
s when appropriate:
$previousLevel = 0;

echo '
';

foreach ($xpath->query('//*[self::h1 or self::h2 or self::h3 or self::h4]') as $headerElement) {
  // Grab the level number (1, 2, 3 or 4)
  $level = $headerElement->nodeName[1];
  // Add
 when the level increases (should only increase one by one)
  if ($level > $previousLevel && $previousLevel > -1) {
    echo '
';
  }
  // Close as many levels as needed when the level decreases
  elseif ($level < $previousLevel) {
    echo str_repeat('
', $previousLevel - $level);
  }
  // Display the header text in a list item
  echo '
', $headerElement->textContent, '
';
  // Store the current level for next iteration
  $previousLevel = $level;
}

// Close remaining levels
echo str_repeat('
', $level ?? 0);

Demo: https://3v4l.org/vt3oR - click the little "eye" button next to the output to see it formatted as HTML, since the markup is in one line.
Notes:

*

*a better approach would probably be to store your header tree in some kind of PHP structure first, then pass it over to a view to display, instead of doing it all at once,

*this is obviously over-commented for the purpose of this answer :)


text:
Q: two-byte operating system does not what I want I created a floppy boot image from an example, it should:

*

*disable all interrups

*reboot

However, once I start it with bochs, it consumes 100% CPU until I kill it.
Here is the floppy image:

$ hd floppy.img
00000000  fa f4 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
00000010  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
*
000001f0  00 00 00 00 00 00 00 00  00 00 00 00 00 00 55 aa  |..............U.|
00000200  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  |................|
*
00168000

Disassembled image:

$ objdump -b binary -D floppy.img -m i386

floppy.img:     file format binary

Disassembly of section .data:

00000000 :
       0:   fa                      cli
       1:   f4                      hlt
    ...
     1fe:   55                      push   %ebp
     1ff:   aa                      stos   %al,%es:(%edi)

Bochs output (pastebin).
bochsrc.txt:

romimage:    file=/usr/share/bochs/BIOS-bochs-latest, address=0xe0000
vgaromimage: file=/usr/share/bochs/VGABIOS-lgpl-latest
floppya: 1_44=floppy.img, status=inserted
boot: a
log: OSDev.log
mouse: enabled=0
megs: 32
display_library: sdl

I run bochs this way:
However, once I start it with bochs, it consumes 100% CPU until I kill it.
$ bochs -f bochsrc.txt

Bochs version: 2.4.6-4, running on ubuntu 12.04 i686.
What am I doing wrong?

A: hlt does not reboot; that's not what it's for. It pauses the processor until an interrupt arrives, and since you've disabled interrupts, it will just sit there doing nothing forever.
As to why the emulator consumes 100% CPU, that's probably due to the way the emulator is implemented. On (some versions of) Linux, hlt is used to idle the processor until the next timeslice, so of course it doesn't make the processor busy-wait. :-)

A: CLI will not disable NMI (not maskable interrupts) so, following code is still better:
.loop:
    cli
    hlt
    jmp .loop

It is not clear why Bochs gives 100% CPU load. How you are checking this load? By the real CPU load, or Bochs has it's own virtual CPU load indicator?
I would suggest trying with another virtual machine, like QEMU.
So, the above code will boot and then sleep. If the intention is to reboot the computer, following code should do cold restart
    jmp $ffff:$0000

For warm restart:
    mov  [$472], 1234h
    jmp  $ffff:$0000


text:
Q: Extra page on Crystal Reports I am using Crystal Reports and when I print a report from my end it is not printing an extra page, but when the customer tries printing it prints an extra page on some of the reports. "New Page After" is checked and greyed out and it won't let me click X-2, but I don't think that is the issue. Very frustrating that I cannot recreate the issue to fix it.

A: Most likely this is because the client's printer forces larger page margins, causing content on the right to spill to a next page.
So change your report design to have bigger page margins.
hth.

A: Check Design and make sure everything in on the white paper
Also check the header and footer for  groups and ensure you don't have anything unnecessary Check Page footer section so ensure there is not any thing on the grey section
Suppress any unwanted header or footer section
Go to file and page set up and make sure you are using the correct size of the paper and you have the same paper installed on the printer.
Change the orientation to landscape to check if that help.
Also as MilletSoftware mentioned check of margins

A: In that case, the next suspect is record inflation due to table joins. In other words, a record that you believe is joined to only a single record in another table is actually joining to 2 records, causing a repeat of the information.


text:
Q: How do I simplify my code? I just finished creating my first major application in C#/Silverlight.  In the end the total line count came out to over 12,000 lines of code. Considering this was a rewrite of a php/javascript application I created 2 years that was over 28,000 lines I am actually quite proud of my accomplishment.
After reading many questions and answers here on stackoverflow and other sites online, I followed many posters advice:  I created classes, procedures, and such for things that I would have a year ago copied and pasted; I created logic charts to figure out complex functions; making sure there are no crazy hidden characters (used tabs instead of spaces); and a few others things; place comments where necessary (I have lots of comments).
My application consists of 4 tiles laid out horizontally that have user controls loaded into each slice.  You can have between one and four slices loaded at anytime.  If you have once slice loaded, the slice takes up the entire artboard...if you have 2 loaded, each take up half, 3 a third, 4 a quarter.
Each one of these slices represent (for the sake of this example) a light control.  Each slice has 3 slider controls in it.  Now when I coded the functionality of the sliders, I used a switch/case statement inside of a public function that would run the command on the specified slice/slider.  This made for some duplicate code but I saw no way around it as each slice was named differently.  So I would do slice1.my.commands(); slice2.my.commands(); etc.
My question to you is how do I clean up my code even futher?  (Sadly I cannot post any of my code).  Is there any way to take this repetion out of my code?

A: Writing less code shouldn't be your goal. In the end it's all about TCO (Total cost of ownership).
While owning less code can improve the TCO, there is one factor that has a much greater impact for TCO: maintainability. You should write the most maintainable code. Start by reading Robert Martin's Clean Code.
Update:
Also you say "I have lots of comments". This is a point where you might improve your code. As you will learn from Martin's book, good code hardly needs any comments. Martin says that "comments are lies" and "should be reserved for technical notes about the code and design.".
Update 2:
While I'm add it, here are my favorite quotes from Robert Martin's book:

*

*"a class or module should have one, and only one, reason to change [Single Responsibility Principle]" [page 138]

*"More than three [method arguments] is very questionable and should be avoided with prejudice." [page 288]

*"The First rule of functions is that they should be small. The second rule of functions is that they should be smaller than that." [page 34]

*"Functions should hardly ever be 20 lines long" [page 34]

*"The statements in a function should all be written at the same level of abstraction" [page 304]

*"Comments should be reserved for technical notes about the code and design." [page 286]

A: I tend to agree with Steven. Writing less code, or fewer lines, is not always the goal. Thinking back to some of the stories of Steve Wozniak he used to make very compact hardware, putting tons of logic into a very small package, but very few people could follow what he did, maintain it, or manufacture it.
That being said, I suggest you get very familiar with Design Patterns. They may not lessen your lines of code but they may make you code easier to write, maintain, and understand. And a lot of times they do reduce the number of lines you have. Here are some resources:
DoFactory Design Patterns Reference
Wikipedia Design Pattern Acticle

A: Interfaces and abstract classes are a very strong part of the .net platform.
An interface is nothing more than a contract requirement on a class. That is: an interface is a defined set of methods and/or properties that a class implementing that interface must have. An interface is just a contract declaration.
An abstract class is really powerful because you can carry logic 'into' classes that implement that abstract class. But that is a whole other ball game.
Consider:
public interface ISlice
{
    bool DoStuff(string someParameter);
}

public class MySpecificSliceOfType : ISlice
{
    // this must have a method implementation for the [bool DoStuff(string)] method
    public bool DoStuff(string mySpecificParameter)
    {
       // LOGIC in the Specific class
       return(true);
    }
}

public class MyOtherSliceOfType : ISlice
{
    // this must have a method implementation for the [bool DoStuff(string)] method
    public bool DoStuff(string myOtherParameter)
    {
       // LOGIC in the Other class
       return(true);
    }
}

Whilst this is a heavily oversimplified example, declaring the Interface implentation of the ISlice interface on both the classes 'MySpecificSliceOfType' and 'MyOtherSliceOfType' means that the requisite DoStuff() method is regardless of which one you have because you can do things like:
bool sliceReturn = ((ISlice)currentSlice).DoStuff(currentStringParameterValue);

This can save you working through in things like:
bool sliceReturn = false;
switch(typeofSlice)
{
    case "other" :
        sliceReturn = MyOtherSliceOfType.DoStuff(currentStrignParamterValue);
        break;
    case "specific" :
        sliceReturn = MySpecificSliceOfType.DoStuff(currentStrignParamterValue);
        break;
}

The point being illustrated here is even stronger when you have > 2 different types.
And interfaces and abstract classes combine nicely with the C# type checking stuff too.
Interfaces are a fundamental in Reflection ... something to be used very sparingly but understodd because it can save so much in specific cases ... and in Serialisation (a.k.a. Serialization) which can really help you fly.

A: What you need is an interface with your friend the Strategy pattern.  For example:
public interface ISlice
{
    public Slider Slide {get;set;}
}

public class Slice1 : ISlice
{
    public Slider Slide { get; set; }
}

public static class SliceSlider
{
    public static void DoSomethingCoolWithTheSliceSlide(ISlice slice)
    {
        slice.Slide.LookitMeIAmLearningDesignPatterns();
    }
}

A: Since you can't really post any of your code, I might as well throw out a random thought. Can you put these slices into an array? If so you might be able to get rid of some of the redundant code by having each of the controls set a variable (I'll call it whichSlice). so the controls all set whichSlice to the proper number 1-4 and then you run a normal switch and call slices[whichSlice].my.commands();


text:
Q: Android exception - Unknown origin (possibly widget) I have the following Android exception. It is reported by Bugsense and I cannot find out where it comes from as there is no reference to any class of my app.

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
  at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
  at java.util.ArrayList.get(ArrayList.java:304)
  at android.widget.HeaderViewListAdapter.isEnabled(HeaderViewListAdapter.java:164)
  at android.widget.AbsListView$ListItemAccessibilityDelegate.onInitializeAccessibilityNodeInfo(AbsListView.java:2512)
  at android.view.View.onInitializeAccessibilityNodeInfo(View.java:4849)
  at android.widget.LinearLayout.onInitializeAccessibilityNodeInfo(LinearLayout.java:1768)
  at android.view.View.createAccessibilityNodeInfo(View.java:4812)
  at android.view.AccessibilityInteractionController$AccessibilityNodePrefetcher.prefetchDescendantsOfRealNode(AccessibilityInteractionController.java:825)
  at android.view.AccessibilityInteractionController$AccessibilityNodePrefetcher.prefetchDescendantsOfRealNode(AccessibilityInteractionController.java:848)
  at android.view.AccessibilityInteractionController$AccessibilityNodePrefetcher.prefetchDescendantsOfRealNode(AccessibilityInteractionController.java:848)
  at android.view.AccessibilityInteractionController$AccessibilityNodePrefetcher.prefetchDescendantsOfRealNode(AccessibilityInteractionController.java:848)
  at android.view.AccessibilityInteractionController$AccessibilityNodePrefetcher.prefetchDescendantsOfRealNode(AccessibilityInteractionController.java:848)
  at android.view.AccessibilityInteractionController$AccessibilityNodePrefetcher.prefetchAccessibilityNodeInfos(AccessibilityInteractionController.java:734)
  at android.view.AccessibilityInteractionController.findAccessibilityNodeInfoByAccessibilityIdUiThread(AccessibilityInteractionController.java:205)
  at android.view.AccessibilityInteractionController.access$400(AccessibilityInteractionController.java:49)
  at android.view.AccessibilityInteractionController$PrivateHandler.handleMessage(AccessibilityInteractionController.java:985)
  at android.os.Handler.dispatchMessage(Handler.java:99)
  at android.os.Looper.loop(Looper.java:137)
  at android.app.ActivityThread.main(ActivityThread.java:4867)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:511)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
  at dalvik.system.NativeStart.main(Native Method)

I do suspect it has something to do with updating a widget. Any ideas on how to trace?

A: Got similar Nullpointer with a Google map view.
try and turn off any accessibility options enabled on your phone?
And there is a another accessibility bug reported on the Android Issues tracker here
It looks like there is no easy way to turn of accessibility from code, except for overriding the addChildrenForAccessibility method in a custom view. (see above link)


text:
Q: CSS Data not changing according to value (Beginner) Hey so right now I'm learning Mainly JS but that also comes with HTML and CSS so I guess that too. I followed a great tutorial from Web Dev Simplified on how to make a snake game (https://www.youtube.com/watch?v=QTcIXok9wNY&t=1781s). so now I wanted to expand my knowledge and start adding features to the game. So I wanted to add a Score feature. The only thing is that when I change the the text-align or the font-size bigger then it already is, nothing changes, is there anything externally locking this data?
Index.html:


text:
Q: IndexError: list index out of range graph diameter this is my code:
class Graph(object):

def __init__(self, graph_dict={}):
    self.__graph_dict = graph_dict

def vertices(self):
    return list(self.__graph_dict.keys())

def find_all_paths(self, start_vertex, end_vertex, path=[]):
    graph = self.__graph_dict
    path = path + [start_vertex]
    if start_vertex == end_vertex:
        return [path]
    if start_vertex not in graph:
        return []
    paths = []
    for vertex in graph[start_vertex]:
        if vertex not in path:
            extended_paths = self.find_all_paths(vertex,
                                             end_vertex,
                                             path)
            for p in extended_paths:
                paths.append(p)

    return paths

def diameter(self):

    v = self.vertices()
    pairs = [ (v[i],v[j]) for i in range(len(v)) for j in range(i+1, len(v)-1)]
    smallest_paths = []
    for (s,e) in pairs:
        paths = self.find_all_paths(s,e)
        smallest = sorted(paths, key=len)[0]
        smallest_paths.append(smallest)

    smallest_paths.sort(key=len)

    diameter = len(smallest_paths[-1])
    return diameter

When I run the comand:
if __name__ == "__main__":

from collections import defaultdict
g = defaultdict(list)
with open("/Volumes/City_University/data_mining/Ecoli.txt") as f:
    for line in f:
        key, val = line.split()
        g[key].append(val)
for k, v in g.items():
    print(k, v)

    graph = Graph(g)

print("Vertices of graph:")
print(graph.vertices())
print(graph.find_all_paths("0", "3"))

print(graph.diameter())

I get this error:
File "", line 70, in
    print(graph.diameter())
File "", line 40, in diameter
    smallest = sorted(paths, key=len)[0]
IndexError: list index out of range
The graph is a very big one. It has 3633 edges.
Any reason why I get this error?
Is there another function I can use to calcute the diameter of this graph?


text:
Q: How many adders needed in order to implement $y=x^2$? We are given a natural number $x\in\mathbb{N}^+$, and $x-1$ adders. An adder in our case would be a component with two inputs $x_1,x_2$ and a single output $y$ such that $y=x_1+x_2$. Our goal is to design a system that has $x$ as its single input, and $x^2$ as its single output. No constants are available to use.
Define $n:\mathbb{N}^+\to\mathbb{N}$ such that $\forall x\in\mathbb{N}^+$, $n(x)$ is the minimum amount of adders needed in order to implement such system that calculates $x^2$. What is $n(x)$ precisely?
For example: In order to calculate $7^2$ efficiently:

*

*First step: we only have $7$, so we must do $7+7=14$. (1 adder)

*Second step: Now we also have $14$, so we can calculate $7+14=21$ and $14+14=28$ (2 adders; 3 overall)

*Final step: Now we have $21$ and $28$, so we can calculate $21+28=49$ (1 adder; 4 overall) and we're done.

It needs to be proven now that $7^2$ can't be calculated using $3$ adders or less (pretty intuitive), and then it can be concluded that $n(7)=4$.

It is clear that $n(x)\leq x-1$. I was able to show that $n(x)$ is not increasing (for instance - $n(7)=4$ while $n(8)=3$), but I think I did manage to find a tighter upper bound - which is $n(x)\leq2\lfloor\log_2(x)\rfloor$. I'm having trouble with finding the exact expression for $n(x)$.
This was my way of thinking. For every $m\in\mathbb{N}^+$, define the group of natural numbers $A_m$ s.t.:
$$A_m\triangleq \{x\in\mathbb{N}^+|\lceil\log_2(x)\rceil=m\}$$
So for example, $A_3=\{5,6,7,8\}$. It is clear that $x_m\equiv2^m-1\in A_m$. This demands proof, but I tend to believe that out of all the integers of $A_m$, $x_m$ requires the greatest amount of adders. Pay attention that:
$$x_m^2=x_m(2^{m-1}+2^{m-1}-1)=2^{m-1}x_m+\sum_{k=0}^{m-2}2^kx_m$$
You can efficiently calculate $2^{m-1}x_m$ using $m-1$ adders. When you do that, you have the input $2^kx_m$ available, for every $k\in[1,m-1]_\mathbb{N}$. So $\sum_{k=0}^{m-2}2^kx_m$ can be calculated with $m-2$ adders. Then, a final adder is needed in order to calculate $x_m^2$. So overall:
$$n(2^m-1)=2m-2$$
Given that $x_m^2$ cannot be calculated using $2m-3$ adders or less. Pay attention that for $m=3$, we get $n(7)=4$, as before.

I tried to do the same thing with different patterns, but I didn't manage to conclude the general form. Some help would be appreciated :)
Note: This question can be rephrased in a clearer way. Suppose you initially have a set $S=\{1\}$, each time you can pick up two (can be duplicate) numbers in $S$ and put the sum of those two numbers in $S$. What is the least number of steps, or $|S|$, that is needed such that $n\in S$? (The question is not the same, but the answers are (I believe) the same, since all my equations can simply be divided by $x_m$). (Thank you @JetfiRex for this)

A: Not really an answer, but you can refer to wiki page  and oeis to find the thing you need...
Also, this is the result by running the python code below:
import time
sets = {(1,)}
prev_union = {1}
union_11 = set()
ans = {1:0}
for i in range(1,11):
    if i<10:
        print("numbers that need",i,"adders to go")
        aux=set()
        union=set()
        for s in sets:
            for first in range(i):
                for second in range(first+1):
                    s1 = set(s)|{s[first]+s[second]}
                    if len(s1)==i+1:
                        aux.add(tuple(sorted(s1)))
                        union|=s1
        print(union-prev_union)
        prev_union=union
        sets=aux
    elif i==10:
        print("numbers that need",i,"adders to go")
        aux=set()
        union=set()
        for s in sets:
            for first in range(i):
                for second in range(first+1):
                    new = s[first]+s[second]
                    s1 = set(s)|{new}
                    if len(s1)==i+1:
                        aux.add(tuple(sorted(s1)))
                        union|=s1
                        union_11|=set(new+third for third in s1)
        print(union-prev_union)
        print("numbers that need 11 adders to go")
        print(union_11-union)

The result is here: (covers at least 1 to 378)
numbers that need 1 adders to go
{2}
numbers that need 2 adders to go
{3, 4}
numbers that need 3 adders to go
{8, 5, 6}
numbers that need 4 adders to go
{7, 9, 10, 12, 16}
numbers that need 5 adders to go
{32, 11, 13, 14, 15, 17, 18, 20, 24}
numbers that need 6 adders to go
{64, 33, 34, 36, 40, 48, 19, 21, 22, 23, 25, 26, 27, 28, 30}
numbers that need 7 adders to go
{128, 29, 31, 35, 37, 38, 39, 41, 42, 43, 44, 45, 46, 49, 50, 51, 52, 54, 56, 60, 65, 66, 68, 72, 80, 96}
numbers that need 8 adders to go
{256, 129, 130, 132, 136, 144, 160, 47, 53, 55, 57, 58, 59, 61, 62, 63, 192, 67, 69, 70, 73, 74, 75, 76, 77, 78, 81, 82, 83, 84, 85, 86, 88, 90, 92, 97, 98, 99, 100, 102, 104, 108, 112, 120}
numbers that need 9 adders to go
{512, 71, 79, 87, 89, 91, 93, 94, 95, 101, 103, 105, 106, 107, 109, 110, 111, 113, 114, 115, 116, 117, 118, 119, 121, 122, 123, 124, 125, 126, 131, 133, 134, 135, 137, 138, 140, 145, 146, 147, 148, 149, 150, 152, 153, 154, 156, 161, 162, 163, 164, 165, 166, 168, 170, 172, 176, 180, 184, 193, 194, 195, 196, 198, 200, 204, 208, 216, 224, 240, 257, 258, 260, 264, 272, 288, 320, 384}
numbers that need 10 adders to go
{1024, 513, 514, 516, 520, 528, 544, 576, 127, 640, 139, 141, 142, 143, 151, 155, 157, 158, 159, 167, 169, 171, 173, 174, 175, 177, 178, 179, 181, 182, 183, 185, 186, 187, 188, 189, 190, 197, 199, 201, 202, 203, 205, 206, 207, 209, 210, 211, 212, 213, 214, 215, 217, 218, 219, 220, 221, 222, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 236, 238, 241, 242, 243, 244, 245, 246, 248, 249, 250, 252, 255, 768, 259, 261, 262, 265, 266, 268, 270, 273, 274, 276, 280, 281, 289, 290, 291, 292, 293, 294, 296, 297, 298, 300, 304, 306, 308, 312, 321, 322, 323, 324, 325, 326, 328, 330, 332, 336, 340, 344, 352, 360, 368, 385, 386, 387, 388, 390, 392, 396, 400, 408, 416, 432, 448, 480}
numbers that need 11 adders to go
{2048, 1025, 1026, 1536, 515, 517, 518, 1028, 1032, 521, 522, 524, 1040, 529, 530, 532, 536, 540, 1056, 545, 546, 548, 552, 553, 560, 561, 562, 1088, 577, 578, 579, 580, 581, 582, 584, 585, 586, 588, 592, 594, 596, 600, 608, 612, 616, 624, 1152, 641, 642, 643, 644, 645, 646, 648, 650, 652, 656, 660, 664, 672, 680, 688, 191, 704, 720, 223, 736, 235, 237, 239, 247, 251, 253, 254, 1280, 769, 770, 771, 772, 774, 263, 776, 267, 780, 269, 271, 784, 275, 277, 278, 279, 792, 282, 283, 284, 285, 286, 287, 800, 295, 299, 301, 302, 303, 816, 305, 307, 309, 310, 311, 313, 314, 315, 316, 317, 318, 319, 832, 327, 329, 331, 333, 334, 335, 337, 338, 339, 341, 342, 343, 345, 346, 347, 348, 349, 350, 351, 864, 353, 354, 355, 356, 357, 358, 359, 361, 362, 363, 364, 365, 366, 367, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 380, 381, 382, 896, 389, 391, 393, 394, 395, 397, 398, 399, 401, 402, 403, 404, 405, 406, 409, 410, 411, 412, 413, 414, 415, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 428, 429, 430, 433, 434, 435, 436, 437, 438, 440, 441, 442, 444, 447, 960, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 462, 464, 466, 468, 472, 476, 481, 482, 483, 484, 485, 486, 488, 489, 490, 492, 495, 496, 498, 500, 504, 510}


text:
Q: R - How to compare two words sentence if order is not same? Lets take example
z <- "Dikesh Faldu"
y <- "Faldu Dikesh"

I want to get process both of this variable and give me same output as "DikeshFaldu"
lets put another example
i have one variable that has all this values like
[1] dikesh faldu
[2] xyz abc
[3] faldu dikesh
[4] anything like
[5] but only
[6] two words
[7] only but

.........
then i want output like
[1] dikeshfaldu
[2] xyzabc
[3] dikeshfaldu
[4] anythinglike
[5] butonly
[6] twowords
[7] butonly

or
[1] faldudikesh
[2] xyzabc
[3] faldudikesh
[4] anythinglike
[5] onlybut
[6] twowords
[7] onlybut

A: As per the inputs by @zx8754 , @Dirty Sock Sniffer and @RHertel, you can try,
sapply(strsplit(charvec, " "), function(x) paste(sort(x), collapse=""))

#[1] "dikeshfaldu"  "abcxyz"       "dikeshfaldu"  "anythinglike" "butonly"
#[6] "twowords"     "butonly"

where
charvec <- c("dikesh faldu", "xyz abc", "faldu dikesh", "anything like",
              "but only", "two words", "only but")

A: For the first case, match one or more spaces (\\s+) and replace it with "" in sub
sub("\\s+", "", z)
#[1] "DikeshFaldu"

and for second case, capture the non-white space as a group and rearrange the backreference.
sub("(\\S+)\\s+(\\S+)", "\\2\\1", y)
#[1] "DikeshFaldu"

If the sort is based on alphabetic ordering, then we use stri_extract from stringi to extract the words, sort it and paste together
library(stringi)
vapply(stri_extract_all(c(z,y), regex = "\\w+"), function(x)
            paste(sort(x), collapse=""), character(1))
#[1] "DikeshFaldu" "DikeshFaldu"

Using the updated vector in OP's post
vapply(stri_extract_all(charvec, regex = "\\w+"),
       function(x) paste(sort(x), collapse=""), character(1))
#[1] "dikeshfaldu"  "abcxyz"       "dikeshfaldu"  "anythinglike"
#[5] "butonly"      "twowords"     "butonly"

data
charvec <- c("dikesh faldu", "xyz abc", "faldu dikesh", "anything like",
           "but only", "two words", "only but")

A: Here's the R code that you're looking for. Same as what zx8754 mentioned.
z <- "Dikesh Faldu"
y <- "Faldu Dikesh"

sort(unlist(strsplit(z,split=' '))) == sort(unlist(strsplit(y,split=' ')))

[1] TRUE TRUE


text:
Q: What's the appropriate granularity for Backbone.js Views? I'm adopting Backbone.js to render a small corner of an existing large web app. If this goes well, I can see Backbone.js growing to encompass the whole of the app, lending some much-needed structure to an organically-grown application. That's the preface. Now for the problem:
I have a select box which allows the user to select a reading plan. When the selection changes, the view updates some descriptive text, a calendar interface, and a little widget for marking today's readings as complete. The widget will have a checkbox for each reading (one or more) in today's entry and a button for continuing to the next day's reading. (You can see the current, non-Backbone version of this interface (minus the completion scheme) on the right-hand side of the existing app.
What is the appropriate granularity for each View? I've identified the following "fiddly bits":

*

*The Tab itself, which encompasses all the contained controls.

*The select box

*The descriptive text, which responds to the select box

*The calendar, which responds to the select box

*The readings widget, which responds to the select box, and contains:

*

*Optionally, a "Start" button, which activates the current plan.

*When activated, one or more checkboxes corresponding to individual readings within today's entry.

*When activated, a "Next" button which completes today's entry and displays the next.

Should each of these bullet points get its own View? Just the major pieces (tab, select box, widget)? The first will result in quite a few Views. The first seems like it could lead to overcomplicated View implementations. What's best?
Note: I realize this could be interpreted as a wildly-subjective question, but I'm still wrapping my head around Backbone.js and Javascript/DOM MVC patterns, and I'm hoping that there is a narrow "this is what's intended/works best" from more experienced Backbone.js practitioners. Thanks!

A: There is no definitive answer to your question. You can have a look at the granularity of sproutcore for exemples.
You can also watch http://vimeo.com/17186379 where Yehuda Katz illustrate the difficulties of updating different pieces of the page.
One way of looking at it would be to check which part should be refreshed with different model change/events and try to minimize the re rendering.
Sorry no good answers as you pointed out ;)

A: In general, the granularity of your views will depend on finding a balance between the complexity of the particular piece of UI, and over-fragmentation of views into little pieces. I probably would not use a view for something as small as a button (a CSS class is all you really need for that).
In your particular case, I'd probably have a view for the calendar widget -- so it can be easily reused in other places in the app -- and a view for the entire Devotions tab. The rest can be done through event binding.
Regarding model updates and re-rendering, the whole idea with Backbone is to separate that concern from the views. Models emit "change" events when their attributes change, and whatever views happen to be on the page at the time, and are displaying that particular model's data, will be notified of the change, and can update themselves.


text:
Q: Finding admob owners email id Is there anyway I can find my admob owner account email by the AdMob App id?
for example my app id is following and I need to locate the original email id that is being used for this AdMob
ca-app-pub-234124123412354/3412341234
I used two different email ids for Developer Account and AdMob Account. Due to the app failure in making revenue I didn't focus on the AdMob for long period and now I can't even recall the email id.


text:
Q: Maximizing Rademacher average of vector norm I ran across the following claim in page 5 of this paper, but could not figure out how to prove it. Changing notation a bit for clarity, the claim is:

Let $x_1, \dots, x_n$ be elements of a separable Banach space $(X, \| \cdot \|)$, and suppose $\alpha_1, \dots, \alpha_n$ are scalars with
  $|\alpha_i| \leq 1$. Then $$\mathbf{E} \biggl\| \sum \epsilon_i \alpha_i x_i \biggr\| \leq \mathbf{E} \biggl\| \sum \epsilon_i x_i \biggr\|$$ where the expectation is taken over the IID Rademacher
  random variables $\epsilon_1, \dots, \epsilon_n$  (i.e., $\epsilon_i$
  takes values $\pm 1$ with equal probability).

I tried assocating every term in the LHS with a term in the RHS that dominates it, but this approach does not seem to work.


text:
Q: Use of window() function in TensorFlow Dataset to access more than one row I've got a problem with transforming the dataset read from .csv files by tf.data.experimental.CsvDataset into "timeseries".
What I'm trying to do is to access more than one row of the dataset at once in order to append features of previous 2 rows to the current row and keep the label of the current row. I'd like to do it for every row (apart from the first two). I thought that applying window() function is the right approach but now I'm not so sure.
The original dataset consisting of approximately 300 columns is created by reading a set of .csv files like this:
ds = tf.data.experimental.CsvDataset(
            filenames,
            [tf.float32] * len(columns_indices_to_parse),
            header=True,
            select_cols=columns_indices_to_parse
        )

For reproducibility I'm using the combination of Dataset.from_tensor_slices() and Dataset.zip():
import tensorflow as tf

tf.enable_eager_execution()

with tf.Graph().as_default(), tf.Session() as sess:
    # Simulate what's being returned from CsvDataset():
    feature_1_ds = tf.data.Dataset.from_tensor_slices([1., 3., 5., 7., 9.])
    feature_2_ds = tf.data.Dataset.from_tensor_slices([2., 4., 6., 8., 10.])
    label_1_ds = tf.data.Dataset.from_tensor_slices([1.0, 1.0, 0.0, 1.0, 0.0])

    ds = tf.data.Dataset.zip((feature_1_ds, feature_2_ds, label_1_ds))

    # Do transformations to obtain "timeseries" data.
    def _parse_function_features(*row):
        features = tf.stack(row[:2], axis=-1)
        return features

    def _parse_function_labels(*row):
        labels = tf.stack(row[2:], axis=-1)
        return labels

    def _reshape(x):
        # Flatten rows into one.
        return tf.reshape(x, shape=[-1])

    ds_features = ds.map(_parse_function_features).window(3).flat_map(lambda x: x.batch(3)).map(_reshape)
    ds_labels = ds.map(_parse_function_labels).skip(2)
    ds = tf.data.Dataset.zip((ds_features, ds_labels))

    iter = ds.make_one_shot_iterator().get_next()
    # Show dataset contents
    print('Result:')
    while True:
        try:
            print(sess.run(iter))
        except tf.errors.OutOfRangeError:
            break

I'm still getting my head around window() transformation, I saw this GitHub issue but it doesn't solve my problem.
What I'm getting now is:
(array([1., 2., 3., 4., 5., 6.], dtype=float32), array([0.], dtype=float32))
(array([ 7.,  8.,  9., 10.], dtype=float32), array([1.], dtype=float32))

The problem is that it behaves like batch - processes rows in triples. What I'd like to achieve is the following:
(array([1., 2., 3., 4., 5., 6.], dtype=float32), array([0.], dtype=float32)) # with label of the third row
(array([3., 4., 5., 6., 7., 8.], dtype=float32), array([1.], dtype=float32)) # with label of the fourth row
(array([5., 6., 7., 8., 9., 10.], dtype=float32), array([0.], dtype=float32)) # with label of the fifth row

I'm stuck a bit, I'm not sure if using window() function for accessing more than one row of the dataset is even the right approach. I've asked very similar question previously but I deleted it as I think I've included too much details, here I've tried to keep it as lean as possible. Any help would be appreciated, thanks!

A: Ok after tackling the problem from many sides I've finally managed to achieve the required result. I've got two solutions: one that processes features and labels as separate datasets and the one which appies transformations to the dataset in one go. Both might be useful depending on the use case.

*

*Process features and labels as separate datasets:

import tensorflow as tf

tf.enable_eager_execution()

with tf.Graph().as_default(), tf.Session() as sess:
    # Simulate what's being returned from CsvDataset():
    feature_1_ds = tf.data.Dataset.from_tensor_slices([1., 3., 5., 7., 9.])
    feature_2_ds = tf.data.Dataset.from_tensor_slices([2., 4., 6., 8., 10.])
    label_1_ds = tf.data.Dataset.from_tensor_slices([1.0, 1.0, 0.0, 1.0, 0.0])

    ds = tf.data.Dataset.zip((feature_1_ds, feature_2_ds, label_1_ds))

    # Do transformations to obtain "timeseries" data.
    def _parse_function_features(*row):
        features = tf.stack(row[:2], axis=-1)
        return features

    def _parse_function_labels(*row):
        labels = tf.stack(row[2:], axis=-1)
        return labels

    def _reshape(x):
        # Flatten rows into one.
        return tf.reshape(x, shape=[-1])

    ds_features = ds.map(_parse_function_features).window(3, shift=1).flat_map(lambda x: x.batch(3)).map(_reshape)
    ds_labels = ds.map(_parse_function_labels).window(3, shift=1).flat_map(lambda x: x.skip(2))
    ds = tf.data.Dataset.zip((ds_features, ds_labels))

    iter = ds.make_one_shot_iterator().get_next()
    # Show dataset contents
    print('Result:')
    while True:
        try:
            print(sess.run(iter))
        except tf.errors.OutOfRangeError:
            break

*Transform the dataset in one go:

import tensorflow as tf

tf.enable_eager_execution()

with tf.Graph().as_default(), tf.Session() as sess:
    # Simulate what's being returned from CsvDataset():
    feature_1_ds = tf.data.Dataset.from_tensor_slices([1., 3., 5., 7., 9.])
    feature_2_ds = tf.data.Dataset.from_tensor_slices([2., 4., 6., 8., 10.])
    label_1_ds = tf.data.Dataset.from_tensor_slices([1.0, 1.0, 0.0, 1.0, 0.0])

    ds = tf.data.Dataset.zip((feature_1_ds, feature_2_ds, label_1_ds))

    # Do transformations to obtain "timeseries" data.
    def _parse_function(*row):
        features = tf.stack(row[:2], axis=-1)
        labels = tf.stack(row[2:], axis=-1)
        return features, labels

    def _reshape(features, labels):
        # Flatten features into one row.
        return tf.reshape(features, shape=[-1]), labels

    ds = ds.map(_parse_function)
    ds = ds.window(3, shift=1)
    ds = ds.flat_map(lambda x, y: tf.data.Dataset.zip((x.batch(3), y.skip(2))))
    ds = ds.map(_reshape)

    iter = ds.make_one_shot_iterator().get_next()
    # Show dataset contents
    print('Result:')
    while True:
        try:
            print(sess.run(iter))
        except tf.errors.OutOfRangeError:
            break

For both of these the output is:
Result:
(array([1., 2., 3., 4., 5., 6.], dtype=float32), array([0.], dtype=float32))
(array([3., 4., 5., 6., 7., 8.], dtype=float32), array([1.], dtype=float32))
(array([ 5.,  6.,  7.,  8.,  9., 10.], dtype=float32), array([0.], dtype=float32))


text:
Q: rmongodb: substract date in aggregation After finally figuring out how to parameterize an aggregation pipeline with a date using mongo.bson.from.list(), I've been wrangling with the snippet below to get the $min for the date difference below, but keep getting
 Error in mongo.aggregation(m, collection , aggregation_pipeline ) :
   mongoDB error: 10. Please check ?mongo.get.err for more details.

which means that my BSON group expression, although acceptable to mongo.bson.from.list(), is rejected by mongo.aggregation().
I've tried using list() rather than c(), and cod rather than its ISODate definition, with various quoting variations.
 cod <- as.POSIXct("2015-01-01 00:00:00" , tz = "GMT" )

 grouparg_bson1 <- mongo.bson.from.list(
   list( '$group' = list( '_id'     = list('ID'        = '$dcmt.cid') ,
                          'dtdiff'  = list('$min'      = list('$subtract' = c('$dcmt.orddt','ISODate("2015-01-01T00:00:00Z")' )) ),
                          'tota'    = list('$sum'      = '$dcmt.A' ),
                          'list'    = list('$addToSet' = '$dcmt.B' )
   ))
 )

I am using mongo's latest stable release, version 3.2.4.

A: Trial & error: the following works.
 grouparg_bson1 <- mongo.bson.from.list(
   list( '$group' = list( '_id'     = list('ID'        = '$dcmt.cid') ,
                          'dtdiff'  = list('$min'      = list('$subtract' = list('$dcmt.orddt', cod )) ),
                          'tota'    = list('$sum'      = '$dcmt.A' ),
                          'list'    = list('$addToSet' = '$dcmt.B' )
   ))
 )


text:
Q: Format GPX.writeFeatures doesn't write feature nodes I'm attempting to generate a gpx from a LineString feature with ol/format/GPX.writeFeatures() but only get the gpx header:
<gpx xmlns="http://www.topografix.com/GPX/1/1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd" version="1.1" creator="OpenLayers"/>

with none of the feature's nodes.
As a test, I've added:
let gpx = new GPX();
console.log(features[0]);
console.log(gpx.writeFeatures(features[0]));

to the GPX Data Example index.js in the displayFeatureInfo function.
Am I missing something?


text:
Q: Problem on limit of sequences
I started solving the question by taking  $b_{n}=\frac{(1^{1^{^{p}}}2^{2^{p}}...(n+1){^{(n+1)^{p}}})^{\frac{1}{(n+1)^{p+1}}}}{  (1^{1^{^{p}}}2^{2^{p}}...(n){^{(n)^{p}}})^{\frac{1}{(n)^{p+1}}}}$
 where  $\lim _{n \to \infty }b_{n}=e^{\frac{-2}{(p+1)^{2}}}$ and
$lim_{n \to \infty } x_{n}=(1^{1^{^{p}}}2^{2^{p}}...(n){^{(n)^{p}}})^{\frac{1}{(n)^{p+1}}}(b_{n}-1)$ . But I don't know how to solve it further can someone please  help  me with a hint or suggest some other method for solving this question

A: Let $x_n=y_{n+1}-y_n$ where
$$
y_n=\left(1^{1^p}\cdot 2^{2^p} \cdots n^{n^p}\right)^{\frac1{n^{p+1}}}.
$$
Then
$$
\begin{align}\ln y_n&=\frac1{n^{p+1}}\sum_{i=1}^n i^p \ln i=\frac1n\left(\sum_{i=1}^n (\frac in)^p \left( \ln \frac in +  \ln n\right)\right)\\
&=\frac1n \sum_{i=1}^n (\frac in)^p \ln \frac in + \left(\frac1n \sum_{i=1}^n (\frac in)^p \right)\ln n\\
&=\int_0^1 x^p \ln x dx + O(\frac1n) + \left( \int_0^1 x^p dx + O(\frac 1n)\right) \ln n\\
&=\frac{x^{p+1}}{p+1}\ln x \bigg\vert_0^1-\int_0^1 \frac{x^p}{p+1} dx +\frac{\ln n}{p+1} +O(\frac{\ln n}{n})\\
&=-\frac1{(p+1)^2}+\ln n^{\frac1{p+1}}+O(\frac{\ln n}n)
\end{align}
$$
Thus,
$$
y_n=e^{-\frac1{(p+1)^2}}n^{\frac1{p+1}}\left(1+O(\frac{\ln n}n)\right)=e^{-\frac1{(p+1)^2}}n^{\frac1{p+1}}+O(\frac{\ln n}{n^{\frac p{p+1}}})
$$
For $p>0$, we have by Mean Value Theorem, there is $c_n\in (n,n+1)$ such that
$$
y_{n+1}-y_n = e^{-\frac1{(p+1)^2}} \frac1{p+1} c_n^{-\frac p{p+1}}+O(\frac{\ln n}{n^{\frac p{p+1}}})\xrightarrow[n\rightarrow\infty]{} 0.
$$
For $p=0$,
$$
\ln y_n=\frac1n \sum_{i=1}^n \ln i=\frac1n (n\ln n - n + \frac12\ln (2\pi n)+O(\frac1n))=\ln n -1 +\frac{\ln (2\pi n)}{2n}+O(\frac1{n^2}).
$$
This gives
$$
y_n= e^{-1} n (2\pi n)^{\frac1{2n}}\left(1+O(\frac{1}{n^2})\right)=e^{-1} n (2\pi n)^{\frac1{2n}}+O(\frac1n).
$$
Therefore, by Mean Value Theorem, there is $c_n\in (n,n+1)$ such that
$$
y_{n+1}-y_n = e^{-1} \left((2\pi c_n)^{\frac1{2c_n}}+c_n (2\pi c_n)^{\frac1{2c_n}}\frac{2-2\ln(2\pi c_n) }{4c_n^2}\right)+O(\frac1n)\xrightarrow[n\rightarrow\infty]{} e^{-1}.
$$


text:
Q: Как изменить знаки элементов предыдущей строки в матрице на противоположные при определённом условии? Проверить, есть ли в матрице хотя бы одна строка, содержащая элемент, равный нулю, и найти её номер. Знаки элементов предыдущей строки изменить на противоположные.
Я только знаю, как сделать первую часть. Как изменить знаки элементов предыдущей строки на противоположные?
Например: строка [7, 2, 0] содержит хотя бы один нулевой элемент, тогда в строке [-5, -6, 2] необходимо изменить знаки.
Пожалуйста, как можно сделать?
matrix = [[-5, -6, 2], [7, 2, 0], [8, 4, -9]]

row = 0
for i in range(len(matrix)):
    for j in range(len(matrix[i])):
        if matrix[i][j] == 0:
            row = i
            print("The row", row," has at least one zero element.")

A: Вот так:
matrix = [[-5, -6, 2], [7, 2, 0], [8, 4, -9]]

prev_arr = None

for curr_arr in matrix:
    for elem in curr_arr:
        if elem == 0:
            if prev_arr:
                for i in range(len(prev_arr)):
                    prev_arr[i] *= -1
            break
    prev_arr = curr_arr

print str(matrix) # выведет [[5, 6, -2], [7, 2, 0], [8, 4, -9]]

A: Разбиваем задачу на подзадачи: сначала находим индекс строки хотя бы с одним элементом, равным нулю, потом меняем знак элементов предыдущей строки.
matrix = [[-5, -6, 2], [7, 2, 0], [8, 4, -9]]

def get_zero_line(m):
     for i, line in enumerate(m):
         if any(x == 0 for x in line):
             return i
     return None  # Ни в одной строке нет нулевого элемента

i = get_zero_line(matrix)
if i is not None and i > 0:
    prev_line = matrix[i-1]
    for j, _ in enumerate(prev_line):
        prev_line[j] *= -1

Обратите внимание, как можно использовать enumerate(x) вместо range(len(x)).


text:
Q: Prerendering causes a SyntaxError: Cannot use import statement outside a module I'm trying to execute prerender.ts as seen here to prerender my Angular code, but when I try and execute it using ts-node prerender.ts, I get the error:

import 'zone.js/dist/zone-node';
      ^^^^^^
SyntaxError: Cannot use import statement outside a module
  at Module._compile (internal/modules/cjs/loader.js:892:18)

What is the proper way to execute this from NodeJS? Here is what prerender.ts looks like:
import 'zone.js/dist/zone-node';
import * as path from 'path';
import * as fs from 'fs';
import { enableProdMode } from '@angular/core';
import { renderModuleFactory } from '@angular/platform-server';
import { AppPrerenderModuleNgFactory } from './dist-prerender/main.bundle';

const distFolder = './dist';
const index = fs
    .readFileSync(path.resolve(__dirname, `${distFolder}/index.html`), 'utf8')
    .toString();

// we could automate this based on the app.routes.ts file but
// to keep it simple let's just create an array with the routes we want
// to prerender
const paths = [
    '/about',
    '/brews',
    '/consultancy'];
enableProdMode();

// for every route render the html and save it in the correct folder
paths.forEach(p => renderToHtml(p, distFolder + p));

// don't forget to overwrite the index.html as well
renderToHtml('/index.html', distFolder);

function renderToHtml(url: string, folderPath: string): void {
  // Render the module with the correct url just
  // as the server would do
  renderModuleFactory(AppPrerenderModuleNgFactory, {
    url,
    document: index
  }).then(html => {
    // create the route directory
    if (url !== '/index.html') {
    fs.mkdirSync(folderPath);
    }
    fs.writeFile(folderPath + '/index.html', html,  (err =>  {
      if (err) {
        throw err;
      }
      console.log(`success`);
    });
  });
}

Update: I found that if I used tsc to transpile prerender.ts to JavaScript first and then executed that with node, I could get past this error. However, I started getting an error which I think is indicative of this code not running within the context of ngZone. So the code is still not right.

A: As stated here:

Current node.js stable releases do not support ES modules. Additionally, ts-node does not have the required hooks into node.js to support ES modules. You will need to set "module": "commonjs" in your tsconfig.json for your code to work.

Thus, pass below compiler option:
ts-node --compiler-options '{"module": "commonjs"}' prerender.ts
Of course, you can just include "module": "commonjs" in your (root) tsconfig.json file under "compilerOptions". This way you only have to execute:
ts-node prerender.ts


text:
Q: python function that logs time & error when a script failed I'm using python3. I want to print the time a script fails, as well as the corresponding exception in one line. Referring to this link & this one, I tried something like this, but the function didn't execute. Am I doing something wrong here? Would appreciate suggestions.

import atexit
import datetime

#define function to log when script ends due to error/failure
def f_log(date_and_time, error):
    try:
        print("")
    except:
        print('Script ended at date/time: %s with error %s.' % (date_and_time, error))

import atexit
atexit.register(f_log, date_and_time=datetime.datetime.now(), error=Exception)

print "Deliberate error" # Simple example of an error that should be caught & printed along with time when script fails.

# main body of script continues here
#
#

A: Your script has multiple problems. (datetime not imported, useless try/except in f_log, ...) The main issue is that a SyntaxError can't be handled. Try this version instead:
import atexit
import datetime

#define function to log when script ends due to error/failure
def f_log(date_and_time, error):
    print('Script ended at date/time: %s with error %s.' % (date_and_time, error))

atexit.register(f_log, date_and_time=datetime.datetime.now(), error=Exception)

1/0 # Simple example of an error that should be caught & printed along with time when script fails.


text:
Q: angular js app not working this is my first time trying angular. I have created an app using angular but it doesn't seem to load. could someone take a look over my code and see if I am missing something simple here. Thanks. Greg
<!DOCTYPE html>

<meta charset=utf-8 />
<title>Angular JS Demo</title>

{{rows.length}} Friend{{plural(rows)}} ? (only {{rows.length-1}} actually....)

<form class="form-horizontal">

<input id="add" type="text" placeholder="Another one ?" ng-model="addName" ng-change="addTemp()"/>
<input type="submit" class="btn btn-primary" ng-click="addRow()" ng-show="addName" value="+ add"/>

<input type="text" class="span2"  placeholder="Search" ng-model="search">
<button type="submit" class="btn btn-inverse" ng-click="search=''" ng-show="search" value="+ add"></button>

</form>

  {{$index+1}}
  {{row}}

  <button class="btn btn-danger btn-mini" ng-click="deleteRow(row)" ng-  hide="isTemp($index)"></button>

A: You forgot to declare your controller to your App
At the end of your code add :
myApp.controller('ctrl', ctrl);

A: Here is the working copy of your code:
<!DOCTYPE html>

<meta charset=utf-8 />
<title>Angular JS Demo</title>

{{rows.length}} Friend{{plural(rows)}} ? (only {{rows.length-1}} actually....)

<form class="form-horizontal">

<input id="add" type="text" placeholder="Another one ?" ng-model="addName" ng-change="addTemp()"/>
<input type="submit" class="btn btn-primary" ng-click="addRow()" ng-show="addName" value="+ add"/>

<input type="text" class="span2"  placeholder="Search" ng-model="search">
<button type="submit" class="btn btn-inverse" ng-click="search=''" ng-show="search" value="+ add"></button>

</form>

  {{$index+1}}
  {{row}}

  <button class="btn btn-danger btn-mini" ng-click="deleteRow(row)" ng-  hide="isTemp($index)"></button>

the issue was you forgot to declare the controller in your app.


text:
Q: Update MySQL record from PHP using AJAX & modal Iam trying to make update option with modal form, I already made "ADD New" - works fine, but have alot problems with Update - I want to see actual data on modal form to edit this. Can u maybe help me with this one? I need help only with function part.
Thats my code for Add New one:
  public function dodajAction()
{
    $request = $this->getRequest();
    $jsonModel = new JsonModel();

    if ($request->isPost()) {
        $dane = $request->getPost();

        $formDodaj = new FormAdm\OfertaForm();
        $formDodaj->setData($dane);

        if ($formDodaj->isValid()) {
            // dodaj
            $this->oferta->dodaj($dane);

            $jsonModel->setVariables(['wynik' => true]);
        } else {
            // w razie błędu renderuj formularz
            $viewModel = new ViewModel(['form_dodaj' => $formDodaj]);
            $viewModel->setTerminal(true);
            $viewModel->setTemplate('admin/oferty/dodaj');

            $jsonModel->setVariables(['wynik' => false, 'html' => $this->renderer->render($viewModel)]);
        }
    }

    return $jsonModel;
}

And thats modal form:

Dodaj ofertę

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

                <?=$this->partial('admin/oferty/dodaj', ['form_dodaj' => $this->form_dodaj]) ?>

                <button type="button" class="btn btn-primary" id="btnDodajOferte">Dodaj</button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Zamknij</button>

A: Just an advice from a fellow Pole, PLEASE!!! use english words in your code. This improves readability, especially that later on you might find tools that help you by using defaults if you follow naming standards. e.g. $form->offer->add() is way more readable to anyone on stack overflow, than our native ->oferta->dodaj().
Coming back to the question though, you have not supplied us with any way to see how the update is performed on the system
I believe that
if ($formDodaj->isValid()) {
        // dodaj
        $this->oferta->dodaj($dane);

        $jsonModel->setVariables(['wynik' => true]);

is responsible for sending the actual data to the database, however code for updating that should be completely in a different function, same for viewing.
It sounds more like an XY problem here, so you might need to rethink what you actually need us to help you with.


text:
Q: How to input,copy and paste into different file specific lines from millions in Emeditor? What i am looking to achieve is simple, but i am a noob in this and i have tried to get that done.
I am used to copy in excel but in Emeditor i feel there is a better way of doing that, afterall it opens more file.
I do not want to be copying-down specific line range like i do in excel.
For instance, if i have a file that is 20million lines, and i need to copy only specific range, maybe between 1-2M or from 2M to 5M, without having to highlight and copydown, how do i go about it?
I will appreciate your responses.

A: *

*Press F8 (or Ctrl+F8 to select whole lines) to mark the
beginning point of a selection.

*Press Ctrl+G and specify the destination line number/column to jump to the ending  point.

*Press Ctrl+C to copy the selection.


text:
Q: PHP Calculate total document saves per day I'm trying to get the total document saves per day. But i don't have any idea how.
Here are the Columns along with their data in my Database.
report_id    doc_date   total_doc
- 1          2017-06-06  1
- 2          2017-06-23  1
- 3          2017-06-14  1
- 4          2017-06-12  1
- 5          2017-06-16  1
- 6          2017-06-21  1
- 7          2017-06-14  1
- 9          2017-06-13  1
- 10         2017-06-21  1
- 11         2017-06-12  1
- 12         2017-06-18  1
- 13         2017-06-12  1
.....

Above, there are similar date, for example,
- 3          2017-06-14  1
- 7          2017-06-14  1

I need a sql query which would calculate and show the total document saves per day. So for 14 of June 2017, the total would be 2.
Any idea guys?
FYI the total_doc is automatically equal to 1.
Updated:
And show the total document saves in that day.

A: Try this (set table_name to the name of your table):
SET @row_count = 0;
SELECT (@row_count:=@row_count+1) AS totalSaves FROM table_name WHERE doc_date='2017-06-14'

The first line defines a variable, row_count, and sets it to 0.
The second line goes through the database, finds all rows where the date is 2017-06-14, and for each one increments row_count.
Then, we SELECT the final number stored in row_count as a single row in a column labeled as totalSaves.
Set table_name to the name of your table

A: SELECT doc_date, sum(total_doc) AS total
FROM table_name
GROUP BY doc_date

Change table_name with your table name.
If you just want show 1 date :
SELECT doc_date, sum(total_doc) AS total
FROM table_name
WHERE doc_date = '2017-06-14'
GROUP BY doc_date

A: SELECT
    doc_date,
    count(doc_date) AS saves
FROM documents
GROUP BY doc_date
ORDER BY doc_date ASC;

OR
SELECT
    doc_date,
    sum(total_doc) AS saves
FROM documents
GROUP BY doc_date
ORDER BY doc_date ASC;

Notices:
1) If you are using the first option, then you can remove the column total_doc. That would also be my advice. You have a good mysql format of the date values in the doc_date column, so you can make solid operations on it.
2) You can sort the records in a descending order by doc_date, if you wish.
3) Don't forget to alias (like I did with AS saves) the columns when using functions like count or sum. Because then you can use a HAVING filter also. So something like this - all documents with more than one save per day:
SELECT
    doc_date,
    count(doc_date) AS saves
FROM documents
GROUP BY doc_date
HAVING saves > 1
ORDER BY doc_date ASC;

And then you can also filter by only one saved document on a specified day:
SELECT
    doc_date,
    count(doc_date) AS saves
FROM documents
WHERE doc_date = "2017-06-12"
GROUP BY doc_date
HAVING saves > 1
ORDER BY doc_date ASC;

4) Or you can also just ignore HAVING and doc_date if you wish. That would give you the documents saved on a specified day.
SELECT count(doc_date) AS saves
FROM documents
WHERE doc_date = "2017-06-12"
GROUP BY doc_date
ORDER BY doc_date ASC;


text:
Q: SQL - GROUPBY query I have data that looks like this. There are different buckets, that have multiple IDs, and some of those IDs have data and some don't. For e.g. A6, L1 and L2 are all in the same bucket (Bucket1), and A6 has data but L1 and L2 don't.

I'm trying to write a query that sums the distinct number of IDs in a bucket that have data (TRUE volume), and also sum the count of IDs that don't have data (FALSE volume), and then it adds the 2 volumes to create total volume. You can see the addition below:

This is what I have till now:
select
Buckets,
case
    when Date is not null then count(distinct Data)
    end as TRUE_Vol,
case
    when Date is null then 0
    end as FALSE_Vol

from #temptable
group by Buckets, Date, Data

But this code is not giving me what I want. I think I need to group it differently, but I can't figure that out. Any help is appreciated.
Thank you

A: When you use conditional aggregation, the case goes inside the aggregation function.
Based on your description, you want:
select Buckets,
       count(distinct case when Date is not null then Data end) as TRUE_Vol,
       sum(case when Date is null then 0 else 1 end) as FALSE_Vol
from #temptable
group by Buckets;

A: You could use a selective group by
select
Buckets,
sum ( case  when Date is not null then 1 else 0 end) as TRUE_Vol,
sum ( case  when Date is null then 1 else 0 end) as FALSE_Vol

from #temptable
group by Buckets


text:
Q: Jquery slidedown first child level elements I have one class of divs ('open') the contain another class of divs ('items') like this:

    this is a test 1

    this is a test 2

What I'm looking to do is a slidedown of all the 'item' class divs that are in the 'open' class that's clicked.
So far I have
$(document).ready(function () {

    $('.open').click(function () {

        $(this).find(':first-child').slideDown('1000');

    });

but it's not working.
Any suggestions?
Thanks,
John

A: Instead of :first-child you want immediate children, which you can get in this case using .children(), like this:
$('.open').click(function () {
  $(this).children().slideDown('1000');
});

:first-child is for getting the first child element at each level  (and in each "branch"), .children() or the child selector (>) are for getting all immediate/"first level" children.

A: How about
$(".open").click(function() {
    $(this).children().slideDown(1000);
});

A: First, I assume that you're actually closing off the $(document).ready, since in the code block you posted, it's not closed. Make sure you're doing so in your code.
Second, aren't you just looking for children() of .open? In which case you want
$(document).ready(function() {
  $('.open').click(function() {
    $(this).children('.item').slideDown('1000');
  });
});

Edited: Thanks to comments, I've removed the live() suggestion.


text:
Q: gcc and the order of operation in C if statement I have a line of code that looks like this:
if ((!s2->lines[i]->flags & ML_TWOSIDED) || (s2->lines[i]->backsector == s1))
and gcc gives me saying:
warning: suggest parentheses around operand of '!' or change '&' to '&&' or '!' to '~' [-Wparentheses]
So, I'm curious as since it does compile, what is gcc doing? Is it not-ing the entire first segment, or only s2->lines[i]->flags?
In other words, is gcc assuming:
if (!(s2->lines[i]->flags & ML_TWOSIDED) || (s2->lines[i]->backsector == s1))
or
if (((!s2->lines[i]->flags) & ML_TWOSIDED) || (s2->lines[i]->backsector == s1))
or perhaps something else?

A: Yes, gcc is assuming you meant
if (((!s2->lines[i]->flags) & ML_TWOSIDED) || (s2->lines[i]->backsector == s1))

since that's what the precedence rules of the language say.  But since that's almost certainly not what you want, gcc is suggesting that you write
if ((!(s2->lines[i]->flags & ML_TWOSIDED)) || (s2->lines[i]->backsector == s1))

instead.

A: Unary operators always have higher precedence than binary ones, meaning that GCC sees your expression as
((!s2->lines[i]->flags) & ML_TWOSIDED) || (s2->lines[i]->backsector == s1)

And GCC is puzzled by the fact that you used a logical subexpression (! operator) as an operand of bitwise expression (& operator). While there's nothing illegal in this (and the behavior is well defined), this is still not something that is used very often. When bitwise and logical semantics is mixed, usually it is bitwise at lower level and logical at higher level, not the other way around.
For this reason GCC asks you to confirm your intent with some extra parenthesis. And it appears that GCC's concern is justified: this is indeed not what you wanted to write.

A: what is gcc doing?  It is only suggesting a course of action based on some observed ambiguities and unconventional operator usage:
Your original statement:
if ((!s2->lines[i]->flags & ML_TWOSIDED) || (s2->lines[i]->backsector == s1))

The GCC warning:
warning: suggest parentheses around operand of '!' or change '&' to '&&' or '!' to '~' [-Wparentheses]
~ and & are bitwise operators
!, || and && are logical operators
The warning is recognizing that you are using a bitwise and logical operator together in a way that is unconventional.  Although legal, and it will compile this way, GCC is asking if you meant to do that, and offering suggestions resulting from its analysis in the form of three options:
1) warning: suggest parentheses around operand of '!'
if ((!(s2->lines[i]->flags & ML_TWOSIDED)) || (s2->lines[i]->backsector == s1))
      ^                                 ^

2) or change '&' to '&&'
if ((!s2->lines[i]->flags && ML_TWOSIDED) || (s2->lines[i]->backsector == s1))
                          ^^

3)  or '!' to '~'
  if ((~s2->lines[i]->flags & ML_TWOSIDED) || (s2->lines[i]->backsector == s1))
       ^     to match       ^

Only you know what was intended.  My guess is a combination of 1) & 2):
if ((!(s2->lines[i]->flags && ML_TWOSIDED)) || (s2->lines[i]->backsector == s1))
      ^                    ^^            ^


text:
Q: How to animate moving ball I am attempting to do a very simple animation and move a ball from one position to another. I have attempted to create a ball class and method to move the ball given a velocity, position and time.
However, the output does not update the ball position as predicted but stays in the same position.
The code can be seen below:
import pylab as pl
import numpy as np
pl.matplotlib.use('Qt5Agg')

class ball:
    def __init__(self,pos,vel,r=1,m=1):
        self._pos = np.array(pos,dtype="float64")
        self._vel = np.array(vel,dtype="float64")
        self._r = r
        self._mass = m
        self._patch=pl.Circle((self._pos),self._r, fc='red',ec='black')

    def move(self,dt):
        newpos = self._pos + self._vel*dt
        self._pos = newpos
        self._patch = pl.Circle((self._pos),self._r,fc='red',ec='black')
        return self

k=ball([0,0],[7,9])
f=pl.figure()
ax = pl.axes(xlim=(-10, 10), ylim=(-10, 10),aspect='1')
ax.add_patch(k._patch)
print(k._patch)
pl.pause(5)
k.move(1)
pl.pause(5)
pl.show()

I have tried figuring out what is wrong but self._patch is updating it's position and if I ax.add_patch the new patch then it appears - however, there are then two balls on the plot. Any help would be very much appreciated.

A: When I ran the code I noticed that the patch wasn't updating on the plot but the position of the ball was changing as expected - to get around this I added 2 lines to the move(self, dt) function. The first removes the old patch, and the second adds the new patch with the updated position.
import pylab as pl
import numpy as np
pl.matplotlib.use('Qt5Agg')

class ball:
    def __init__(self,pos,vel,r=1,m=1):
        self._pos = np.array(pos,dtype="float64")
        self._vel = np.array(vel,dtype="float64")
        self._r = r
        self._mass = m
        self._patch=pl.Circle((self._pos),self._r, fc='red',ec='black')

    def move(self,dt):
        newpos = self._pos + self._vel*dt
        self._pos = newpos
        self._patch.remove()
        self._patch = pl.Circle((self._pos),self._r,fc='red',ec='black')
        ax.add_patch(self._patch)
        return self

k=ball([0,0],[7,9])
f=pl.figure()
ax = pl.axes(xlim=(-10, 10), ylim=(-10, 10),aspect='1')
ax.add_patch(k._patch)

print(k._patch)
pl.pause(5)
k.move(1)
pl.pause(5)

pl.show()


text:
Q: Debugging Linux machine freezes I have 15 identical Linux RH 4.7 64-bit severs. They run cluster database (cluster is application level). On occasion (every month or so) a random box (never the same though) freezes.
I can ping the box and ping works. If I try to ssh in the box I get:
ssh_exchange_identification: Connection closed by remote host

SSH is set up properly.
When I go to the server room, and try to login directly to console, I can switch consoles with Alt+Fn, I can enter a username, and characters do show, but after pressing Enter, nothing happens. I waited 8 hours once and it didn't change.
I set up syslog to log everything to a remote host, and there is nothing in those logs. When I reboot the machine, it works without a problem. I have run HW tests - everything is ok, and nothing is in the logs. The machines are also monitored with NAGIOS, and there is no unusual load or activity prior to freeze.
I have run out of ideas; what else can I do or check?

A: It sounds like your kernel panicked in some way such that sshd couldn't send the server keys.  Possibly, the kernel was wedged in such a way that the network stack was still up, but the vfs layer was unavailable.
When I experienced similar problems on a RHEL4 system, I set up the netdump and netconsole services, and a dedicated netdump and syslog server to catch the crash dumps and kernel panic information.  I also set the kernel.panic sysctl to 10.  That way, when a system panics, you get both the kernel trace and a copy of the memory on that system, to which you could analyse with the 'crash' utility.
You would certainly also benefit from setting up a serial console for the hosts, so you could see the console out put and potentially hit the magic sysrq keys.  Also, if you're willing to set up the networking and you have hardware that supports it, you can use IPMI to remotely poweroff,poweron,restart, and query the hardware.
(for what it's worth, RHEL5 has a similar functionality with kexec/kdump, only the crash dump is stored locally)

A: I will bet dollars to donuts that you are running out of memory. The system is grinding to a halt as it tries to figure out where to get some from. It may be happening so quickly that your monitoring doesn't catch it. I'd step up monitoring, including remote logging of memory usage. Check in the logs for OOM messages as well.
(You may even just want to have some ssh windows open running top.)

A: To me this sounds like the system is out of resources so the process needed by the server side of ssh cannot be allocated.
The actual bottleneck can vary - out of processes or out of memory - and the only way to be sure is to look at the logs and console to see if anything is present there.  You may want to set up a scenario of pre-started ssh-jobs - one to each machine - simply to be prepared next time it happens.
If it is really bad, then you may want to consider starting another shell with more built-in commands so you can investigate more without having to start an extra process as this may not be possible.  Also "tail -f /var/log/*" may be very useful.
Good luck.

A: The only time I've seen anything similar was where a KVM switch was used and a keyboard hot-key (e.g. alt+n) was used to switch between servers. It didn't happen every time and it was the server being switched away from that was affected - so it wasn't immediately noticeable. No lock-ups would occur if a physical button on the KVM switch itself was used to switch between servers. If the hot-key was often used, occasionally a server would not allow new logins. Existing SSH sessions were unaffected.


text:
Q: UITableView with JSON Error I have an app and it's using JSON and an UITableView.
When I try to build/run my app it says: No known class method for selector 'JSONRequestOperationWithRequest:success:failure
This is my code:
http://hastebin.com/axaxumosam.m
The error occurs on line 48.
Hope that you can help me.
Greetings Rik

A: It seems you are trying to use older delegate on the newer version of the API:
AFNetworking 2.0 Migration Guide

One of the most significant changes in AFNetworking 2.0 is its new
  architecture for content negotiation and serialization. Previously,
  response validation and serialization was delegated to
  AFHTTPRequestOperation and its subclasses, with content-specific logic
  scattered throughout implementations for
  setCompletionBlockWithSuccess:failure: and other properties. In 2.0,
  all of this logic is encapsulated in a serializer object that conforms
  to AFURLResponseSerialization.


text:
Q: regexp to match a pattern I don't know enough regexp to write the code, but I know that regexp is the right way to do it.
Input: "2. Some text"
Output "%%2.|Some text"

Input: "[12] some text"
Output: "%%[12]|some text"

Input: "(a)       this is great"
Output: %%(a)|this is great"

The matching should be done only if the beginning of the string starts with:
A number ("1", "25", "234");
A number followed by a dot ("1.", "25.", "234.");
A number in brackets ("[1]", "[25]", "[234]");
A number in parenthesis ("(1)", "(25)", "(234)");
A roman number in parenthesis ("(i)", "iv", "viii");
A roman number in brackets ("[i], "[iv]", "[viii]");
A single letter followed by a dot ("a.", "B.");
A single letter in parenthesis ("(a)", "(B)");
A single letter in brackets ("[a]", "[B]")

Then followed by at least one space

Then followed by text

Output:
%%
followed by the number/letter in the same formatting as it was found
followed by a pipe "|"
followed by the rest of the string (stripping all spaces between the number/letter and the rest of the text).

A: You need to use this regex for search:
^(?:<([ib])>)?([\[(]?\w+[\])]|\w+\.)(?:<\/\1>)?\s+

And use this for replacement:
%%\1|

Online Demo: http://regex101.com/r/vD6oX7

A: You can try this:
$pattern =<<<'LOD'
~
(?(DEFINE)
    (?<roman> m{0,4}(?:cm|cd|d?c{0,3})(?:xc|xl|l?x{0,3})(?:ix|iv|v?i{0,3}) )
)
^
(   \( (?: [0-9]+ | \g<roman> | [a-z] ) \)
  | \[ (?: [0-9]+ | \g<roman> | [a-z] )  ]
  | [0-9]+ \.? | [a-z] \.
) \h*
~xi
LOD;

$result = preg_replace($pattern, '%%$2|', $txt);

A: This should work -
$regex = "/^((?:[0-9]+\.)|(?:[a-zA-Z]\.)|(?:\[[0-9]+\])|(?:\[M{0,4}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})\])|(?:\[[a-zA-Z]+\])|(?:\([a-zA-Z]\))|(?:\([0-9]+\)))\s*(.*)$/";
    $replacement = "%%$1|$2";
    $arr=   Array(
                "2. Some text",
                "a. Some text",
                "[12] some text",
                "[iii] some text",
                "[a] some text",
                "(a)       this is great",
                "(1)       this is great"
            );
    foreach($arr as $str){
        var_dump(preg_replace($regex, $replacement, $str));
    }

The output-
/*
    OUTPUT
*/
string '%%2.|Some text' (length=14)
string '%%a.|Some text' (length=14)
string '%%[12]|some text' (length=16)
string '%%[iii]|some text' (length=17)
string '%%[a]|some text' (length=15)
string '%%(a)|this is great' (length=19)
string '%%(1)|this is great' (length=19)