text:
Q: ITK Filter Error: "Inputs do not occupy the same physical space" after affine registration I'm attempting to perform diffeomorphic demon registration of two MRI images. The processing pipeline has been this so far:

*

*Skull-stripping

*Anisotropic Diffusion (smoothing)

*Histogram Matching

*Affine registration

*Diffeomorphic Demons Registration

I didn't come up with the process, just fixing and cleaning up a Slicer software tool several researchers have built. I'm a summer student and quite unfamiliar with domain, however I've started to more less understand what's going on. The problem I've been unable to solve for the past several weeks is this error:
itk::ExceptionObject (0x1231130)
Location: "void itk::ImageToImageFilter<TInputImage, TOutputImage>::VerifyInputInformation() [with TInputImage = itk::Image<itk::Vector<float, 3u>, 3u>; TOutputImage = itk::Image<itk::Vector<float, 3u>, 3u>]"
File: /home/parallels/Desktop/Slicer-SuperBuild/ITKv4/Modules/Core/Common/include/itkImageToImageFilter.hxx
Line: 241
Description: itk::ERROR: DiffeomorphicDemonsRegistrationFilter(0x13870b0): Inputs do not occupy the same physical space!
InputImage Origin: [7.9639916e+01, -1.1042095e+02, -1.0426932e+02], InputImageMovingImage Origin: [-8.8678563e+01, -1.4923204e+02, 1.2193930e+02]
    Tolerance: 1.5000000e-05
InputImage Spacing: [1.5000000e+01, 1.5000000e+01, 1.9199951e+01], InputImageMovingImage Spacing: [1.5154560e+01, 1.5108180e+01, 1.9319538e+01]
    Tolerance: 1.5000000e-05
InputImage Direction: 1.5926319e-08 1.4070701e-08 -1.0000000e+00
9.9237583e-01 -1.2324859e-01 1.4070700e-08
1.2324859e-01 9.9237583e-01 1.5926320e-08
, InputImageMovingImage Direction: -0.0000000e+00 5.5205551e-10 1.0000000e+00
5.5205551e-10 1.0000000e+00 -5.5205553e-10
-1.0000000e+00 5.5205551e-10 0.0000000e+00

    Tolerance: 1.0000000e-06

From what I understand, the diffeomorphic registration relies on the two images being coincident, hence the affine registration step beforehand. For some reason though, the affine transformation doesn't line up the two images properly. As a result, they don't occupy the same physical space. I'm clearly missing something but can't seem to figure out what it is.
The affine registration is performed with this file (I made some edits on my local copy to comply with the Slicer module's way of input/output but they're nearly identical). The transform that was created had the following characteristics:
Optimizer stop condition: RegularStepGradientDescentOptimizerv4: Step too small after 33 iterations. Current step (9.76563e-05) is less than minimum step (0.0001).
 Result =
 Center X      = -1.95155
 Center Y      = 11.6381
 Center Z      = 36.5165
 Translation X = 1.09423
 Translation Y = 0.021133
 Translation Z = -0.0154539
 Iterations    = 34
 Metric value  = 8974.52
 Scale 1         = 1.15384
 Scale 2         = 1.08962
 Angle (degrees) = -5.6116

The following code was used to save the transform to a file:
  // Write the transform to a file
  itk::TransformFileWriter::Pointer transformWriter = itk::TransformFileWriter::New();

  transformWriter->SetInput( registration->GetOutput()->Get() );
  transformWriter->SetFileName( outputMatrix.c_str() );
  transformWriter->Update();

And the demon registration is performed with this file (Made a few edits but mostly the same as well). The affine transform is loaded at line 799.
Reading transform from transform input file.
Found: AffineTransform (0x1e0c0b0)
  RTTI typeinfo:   itk::AffineTransform<double, 3u>
  Reference Count: 3
  Modified Time: 1322
  Debug: Off
  Object Name:
  Observers:
    none
  Matrix:
    1.01338 0.0887047 0.0223631
    -0.11891 1.09423 0.021133
    -0.0154539 0.0302253 1.14062
  Offset: [-0.256888, -34.7809, -17.895]
  Center: [-1.95155, 11.6381, 36.5165]
  Translation: [1.56597, -32.6804, -12.3781]
  Inverse:
    0.977286 -0.0787352 -0.0177019
    0.105999 0.905809 -0.0188607
    0.0104321 -0.0250698 0.876975
  Singular: 0

Edit: Commenting out the following line does not change anything in the resulting output. ie the initial displacement is not being applied at all. Still don't know why.
typedef typename itk::MultiResolutionPDEDeformableRegistration <ImageType, ImageType, DeformationFieldType, PixelType >   MultiResRegistrationFilterType;
typename MultiResRegistrationFilterType::Pointer multires = MultiResRegistrationFilterType::New();

// Commenting out this line doesn't change anything
multires->SetArbitraryInitialDisplacementField ( inputDefField );

A: It looks like the Diffeomorphic Demons Registration code you are using requires that Fixed and Moving images have the same physical space, meaning:

*

*Origin

*Spacing

*Dimensions

Did you try to resample your moving image to the fixed image space, and then call the Diffeomorphic Demons Registration with this resampled moving image and fixed image?
I didn't know this EZminc code but it looks like it requires both inputs to be in the same space somehow.


text: Q: Dotspatial SpatialToolStrip buttons disabled I have a stand alone map application that uses the DotSpatial.Controls.SpatialToolStrip control, when I added it to the form, only the 'Print' button is enabled, while all others are disabled. I went in to "Edit Item..." and set Enabled to True for all buttons, but when I run the application, all buttons are still disabled. How to turn them on?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pack a Togl widget (using Tcl script) underneath a Tkinter Frame? I am working on a project which requires me to build a Tkinter UI, with a high demanding graphical display.
After several trails, I have decided to use pyOpenGL(Togl) for graphical rendering.
Note that because of performance issues, I have decided to run OpenGL in C++ instead of using the pyOpenGL wrapper in Python.
My problem is, seems like Togl in display.tcl doesn't recognize the wid which I sent from Tkinter. Instead, display.tcl will create a new Togl widget named with given wid.
Can anyone help me on this?
Moreover, is there a better way to due with high demanding graphical display with Tkinter UI.
In Tkinter UI:
from Tkinter import *
import Tkinter as tk

class Layout(ttk.Frame):
    def __init__(self, *args, **kwargs):
        self.Frame = tk.Frame(self, relief=tk.RAISED, container = "True")
        self.Frame.grid()
        top = Toplevel(use=self.Frame.winfo_id())

        self.display = tk.Tk()
        self.display.tk.eval("source {/path/display.tcl}')
        self.display.tk.eval('setup ' + str(top.winfo_pathname(top.winfo_id())) )

In display.tcl
load [file dirname [info script]]/display[info sharedlibextension]

proc setup {wid}
{
     display $wid
}

proc newRot {wid}
{
    togl $wid -width 200 -height 200  -rgba true  -double true  -depth true
    pack $wid -expand true -fill both
}


text:
Q: Does the client have to query the server for each new piece of data in RTSP communication? I'm trying to figure out how RTSP works, when the handshake is complete.
Does the client have to query the server for each new piece of data? Or the server sends data all the time and doesn't care how the client receives the data?
The reason why I ask this is my Gstreamer pipeline receiving RTSP stream from IP camera:
uridecodebin -> nvstreammux -> queue1 -> nvinfer -> queue2 -> fakesink

The IP camera has 30FPS but the nvinfer element can process only 10FPS. So I assumed that pending frames are stored in queue1 element waiting to be processed. However the current number of buffers of the queue1 is 1 all the time.
So one possible answer is that frames or packets are queued in one of the elements of uridecodebin element, but I did not find any such element there. Next it can mean that the IP camera was informed by uridecodebin to decrease FPS. Or if the uridecodebin element has to ask for each new piece of data, it just means that it asks for new data only when all frames are processed in the pipeline.
Do you have any idea?

A: First it is worth mentioning that RTSP is a control protocol - the actual video media is usually sent over RTP protocol in most 'RTSP' video streaming cases.
RTSP is a streaming control protocol, to control streaming servers (whoami's remote control analogy here is nice: https://stackoverflow.com/a/43045354/334402)  It defines how to package data to stream it and how both ends of the connection should behave to support the protocol.
So RTSP does not actually transport the media data itself - as mentioned above it is usually RTP (Real Time Transport) that does this.
Back to your question - RTCP and RTP can be transferred over UDP or TCP in IP Networks. In the former case, a socket is opened a stream established and the client can sit back and wait for the packets to arrive. In the latter case, the client requests each packet as you outline.
In practice you will likely find TCP is more commonly used, even if it is not necessarily the best match for streamed video, because it is more suited to traversing the many firewalls and NAT's on the internet.
In fact it gets more complicated sometimes with the RTSP data interleaved with RTP and RTCP  (Real Tine Control Protocol that collects statistics about the flow) packets over TCP - you can see most detail by looking at the IEFT RFC: https://datatracker.ietf.org/doc/html/rfc2326


text:
Q: Formatting Pascal's Triangle in Python I'm taking my first programming class and I'm a little lost as to how to finish off this code.  I'm trying to construct a Pascal's triangle with n rows. I got the lines to print, each on their own row, but I'm having trouble formatting them into a triangle. Below is what I've got so far. Thanks in advance!
def print_pascal_triangle(n):
    # problem0_pascal.pascal_triangle(n) provides the rows in a list of lists
    rows = problem0_pascal.pascal_triangle(n)

    # Now print the rows, one by one, CALLING  digits_in_biggest_number
    # and  print_row  as appropriate.
    for k in range(len(rows)):
        spaces = digits_in_biggest_number(rows[k])
        print_row(rows[k], spaces)

def digits_in_biggest_number(row):
    """
    Returns the number of digits in the biggest number in the
    given list of numbers.
    """

    largest = 0
    for k in range(len(row)):
        if row[k] > largest:
            largest = row[k]

    digits = int(math.log10(largest)) + 1
    return digits

def print_row(numbers, spaces_per_number):
    """
    Prints the numbers in the given list of numbers.
    Each number is printed using the given number of spaces, except
    for the first number (1) which is printed with a single space.
    """
    line = ''
    for k in range(len(numbers)):
        line += str(numbers[k]) + (spaces_per_number * ' ')

    print(line)

A: Since you're trying to learn, I won't give you a solution, but will make some suggestions...
In print_row, consider what your objective is. You have a docstring saying you're printing the number "using the given number of spaces". Is that what you want?
Think about it. You want this:

        1
       1 1
      1 2 1
     1 3 3 1
      ...

In all the rows, you want them centered, based on the longest row (the last one, right?). For the last row you don't need any indentation, in other rows, you want them indented.
So maybe you have a function that figures out the longest line and then figure out the length of other lines and how much to indent, based on the difference in length.
If you're not using python in interactive mode (or using IDLE), consider doing that, so you can explore with the functions you have. With that, you can then run the functions individually, to see what they are doing.
For example, you can type in your functions, and then enter:
print_row([1, 2, 1], 10)

And see if the output matches what you expect. You can do this on each function to help verify what you expect for different inputs.
A more advanced technique, BTW, is to do Test Driven Development, where you write tests that call functions and verify they do what is expected. If you want to learn about that more Google on TDD and Python for some cool info on coding.


text:
Q: Paypal IPN listener always returns INVALID, yet transaction is successful in live paypal I'm working with the paypal adaptive payments and my IPN listener worked fine in the sandbox, but now that we're testing live transactions, it always returns "INVALID", but the actual money has been transferred.
Any help on why I always receive "INVALD" is appreciated.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Paypal_ipn extends CI_Controller {

    public function index() {

        log_message('error', '');
        log_message('error', '');
        log_message('error', '##################');
        log_message('error', '##################');

        // read the post from PayPal system and add 'cmd'
        $req = 'cmd=_notify-validate&'.file_get_contents("php://input");
        $header = null;

        // post back to PayPal system to validate

        $header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
        $header .= "Host: www.sandbox.paypal.com\r\n";  // this line is needed for sandbox, but may not be needed for prod.
        $header .= "Content-Type: application/x-www-form-urlencoded\r\n";
        $header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
        $fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);

        $raw_post = file_get_contents("php://input");
        $post_array = $this->decodePayPalIPN($raw_post);

        log_message('error', "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        $log1 = var_export($post_array, true);

        log_message('error', $log1);
        log_message('error', "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
        log_message('error', "sender_email = ".$post_array['sender_email']);
        if(isset($post_array['sender_email'])) {

            $sender_email = $post_array['sender_email'];
        }
        if(isset($post_array['status'])) {
            $status = $post_array['status'];
        }
        if(isset($post_array['payment_request_date'])) {
            $payment_request_date = $post_array['payment_request_date'];
        }
        if(isset($post_array['transaction'][0]['receiver'])) {
            $receiver0 = $post_array['transaction'][0]['receiver'];
        }
        if(isset($post_array['transaction'][1]['receiver'])) {
            $receiver1 = $post_array['transaction'][1]['receiver'];
        }
        if(isset($post_array['transaction'][0]['id'])) {
            $id0 = $post_array['transaction'][0]['id'];
        }
        if(isset($post_array['transaction'][1]['id'])) {
            $id1 = $post_array['transaction'][1]['id'];
        }
        if(isset($post_array['transaction'][0]['invoiceId'])) {
            $invoiceId0 = $post_array['transaction'][0]['invoiceId'];
        }
        if(isset($post_array['transaction'][1]['invoiceId'])) {
            $invoiceId1 = $post_array['transaction'][1]['invoiceId'];
        }
        if(isset($post_array['transaction'][0]['amount'])) {
            $amount0 = $post_array['transaction'][0]['amount'];
        }
        if(isset($post_array['transaction'][1]['amount'])) {
            $amount1 = $post_array['transaction'][1]['amount'];
        }
        if(isset($post_array['transaction'][0]['status'])) {
            $status0 = $post_array['transaction'][0]['status'];
        }
        if(isset($post_array['transaction'][1]['status'])) {
            $status1 = $post_array['transaction'][1]['status'];
        }
        if(isset($post_array['transaction'][0]['id_for_sender_txn'])) {
            $id_for_sender_txn0 = $post_array['transaction'][0]['id_for_sender_txn'];
        }
        if(isset($post_array['transaction'][1]['id_for_sender_txn'])) {
            $id_for_sender_txn1 = $post_array['transaction'][1]['id_for_sender_txn'];
        }
        if(isset($post_array['transaction'][0]['status_for_sender_txn'])) {
            $status_for_sender_txn0 = $post_array['transaction'][0]['status_for_sender_txn'];
        }
        if(isset($post_array['transaction'][1]['status_for_sender_txn'])) {
            $status_for_sender_txn1 = $post_array['transaction'][1]['status_for_sender_txn'];
        }
        if(isset($post_array['transaction'][1]['pending_reason'])) {
            $pending_reason0 = $post_array['transaction'][1]['pending_reason'];
        }
        if(isset($post_array['transaction'][1]['pending_reason'])) {
            $pending_reason1 = $post_array['transaction'][1]['pending_reason'];
        }

        if (!$fp) {
            log_message('error', 'Problem with !$fp');
            // HTTP ERROR
        } else {
            $counter = 0;
            fputs ($fp, $header . $req);

            $res = '';

            while (!feof($fp)) {

                $res .= fgets ($fp, 1024);

                log_message('error', "res = $res");

                if (strcmp ($res, "VERIFIED") == 0) {

                    log_message('error', 'we verified');
                    if($status0 == "Completed") {
                        log_message('error', 'we completed');
                        $this->load->model('customer_model');
                        $results = $this->customer_model->get_invoice_info($invoiceId0);

                        if($results != false) {
                            log_message('error', 'results is NOT false');
                            foreach($results as $row) {
                                if($row->amount_verified != 1) {
                                    log_message('error', 'row->amount_verified is NOT equal to 1');
                                    log_message('error', "row->amount = ".$row->amount);

                                    if($row->amount == $amount0) {
                                        //log_message('error', 'row->amount is equal to amount0');
                                        if($this->customer_model->verify_amount($invoiceId0)) {
                                            $subject = 'Successful transaction';
                                            $message = 'There was a successful transaction. View the log for details /public_html/application/logs';
                                            $this->_send_email($subject, $message);
                                        }
                                    } else {
                                        //log_message('error', 'we in the else');
                                        //log_message('error', 'invoiceId0 = '.$invoiceId0);
                                        if($this->customer_model->update_amount_and_verify($invoiceId0, $row->amount)) {
                                            //log_message('error', 'we inside update_amount_and_verify');
                                            $subject = 'Successful transaction';
                                            $message = 'There was a successful transaction. View the log for details /public_html/application/logs';
                                            $this->_send_email($subject, $message);
                                        }
                                    }
                                }
                            }
                        } else {
                            $subject = 'Results Equal False';
                            $message = 'View the log for details /public_html/application/logs';
                            $this->_send_email($subject, $message);
                        }
                    } else {
                        $subject = 'Status NOT Complete!';
                        $message = 'View the log for details /public_html/application/logs';
                        $this->_send_email($subject, $message);
                    }

                    log_message('error', "sender_email = $sender_email");
                    log_message('error', "payment_request_date = $payment_request_date");
                    log_message('error', "status = $status");
                    log_message('error', "receiver0 = $receiver0");
                    log_message('error', "receiver1 = $receiver1");
                    log_message('error', "id0 = $id0");
                    log_message('error', "id1 = $id1");
                    log_message('error', "invoiceId0 = $invoiceId0");
                    log_message('error', "invoiceId1 = $invoiceId1");
                    log_message('error', "amount0 = $amount0");
                    log_message('error', "amount1 = $amount1");
                    log_message('error', "status0 = $status0");
                    log_message('error', "status1 = $status1");
                    log_message('error', "id_for_sender_txn0 = $id_for_sender_txn0");
                    log_message('error', "id_for_sender_txn1 = $id_for_sender_txn1");
                    log_message('error', "status_for_sender_txn0 = $status_for_sender_txn0");
                    log_message('error', "status_for_sender_txn1 = $status_for_sender_txn1");
                    log_message('error', "pending_reason0 = $pending_reason0");
                    log_message('error', "pending_reason1 = $pending_reason1");

                    // check the payment_status is Completed
                    // check that txn_id has not been previously processed
                    // check that receiver_email is your Primary PayPal email
                    // check that payment_amount/payment_currency are correct
                    // process payment
                    $counter++;
                }
                else if (strcmp ($res, "INVALID") == 0) {
                    log_message('error', 'WE INVALIDDDDDDDDDDDDDDDDDD');
                    $test = var_export($res, true);
                    $test = str_replace(array("\r","\n"), '', $test);

                    log_message('error', $test);
                    log_message('error', "Problem with IPN. res = $test");
                }

            }
            fclose ($fp);
        }

    }

    function decodePayPalIPN($raw_post)
    {
        //log_message('error', "testing");
        if (empty($raw_post)) {
            return array();
        } # else:
        $post = array();
        $pairs = explode('&', $raw_post);
        foreach ($pairs as $pair) {
            list($key, $value) = explode('=', $pair, 2);
            $key = urldecode($key);
            $value = urldecode($value);
            # This is look for a key as simple as 'return_url' or as complex as 'somekey[x].property'
            preg_match('/(\w+)(?:\[(\d+)\])?(?:\.(\w+))?/', $key, $key_parts);
            switch (count($key_parts)) {
                case 4:
                    # Original key format: somekey[x].property
                    # Converting to $post[somekey][x][property]
                    if (!isset($post[$key_parts[1]])) {
                        $post[$key_parts[1]] = array($key_parts[2] => array($key_parts[3] => $value));
                    } else if (!isset($post[$key_parts[1]][$key_parts[2]])) {
                        $post[$key_parts[1]][$key_parts[2]] = array($key_parts[3] => $value);
                    } else {
                        $post[$key_parts[1]][$key_parts[2]][$key_parts[3]] = $value;
                    }
                    break;
                case 3:
                    # Original key format: somekey[x]
                    # Converting to $post[somkey][x]
                    if (!isset($post[$key_parts[1]])) {
                        $post[$key_parts[1]] = array();
                    }
                    $post[$key_parts[1]][$key_parts[2]] = $value;
                    break;
                default:
                    # No special format
                    $post[$key] = $value;
                    break;
            }#switch
        }#foreach

        return $post;
    }#decodePayPalIPN()

    private function _send_email($subject, $message) {
        //log_message('error', 'we in send_email');
        $this->load->library('email');

        $this->email->from('do-not-reply@mysite.com', 'Title');
        $this->email->to('myemail@gmail.com');

        $this->email->subject($subject);
        $this->email->message($message);

        $this->email->send();
        //log_message('error', 'email error = '.$this->email->print_debugger());
    }
}

A: If you are now testing live transactions your code is still showing for sandbox -
$header .= "Host: www.sandbox.paypal.com\r\n";  // this line is needed for sandbox, but may not be needed for prod.
...
$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);

Make sure that you change to -
// $header .= "Host: www.sandbox.paypal.com\r\n"; line removed, not needed
...
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);

A: did not had a chance to try your code but can you try the code sample we have here on X.com https://www.x.com/developers/PayPal/documentation-tools/code-sample/216623 ? We actually recommend using curl than socket io.


text:
Q: How to Inject String property to javax.jms.TextMessage in Spring Integration I wanted to know is there any way to add properties to JMS text Message in Spring Integration.
For example if we use normal JMS code we can always set properties to it using the below code.
message.setStringProperty( "AuctionType", "Reverse" );

Edit
I tried to add the header as given in Spring document but now i am getting same message Id for each message, but as i am intended to use it as ID, so i need it to be different for each message.
Below is my snapshot of Spring configuration.
<bean class="com.learn.util.RandomMsgId" id="randomMsgId" factory-method="getRndMsgId" scope="prototype"/>

<int:header-enricher input-channel="xmlToJMS"
    output-channel="xmltoJMSwithId">
    <int:header name="MsgId" ref="randomMsgId"/>
</int:header-enricher>

A: Use a <header-enricher/> to add custom headers to the spring integration message and they will be mapped to JMS headers.
See the documentation and here.


text:
Q: Is the countable union of disjoint compact sets compact? Is the countable union of $\textbf{disjoint}$ compact sets compact?
I can't think of any counterexamples and it seems intuitively true...

A: The answer is not in general. Take for instance the sets $[2n, 2n+1]$ for $n=1,2,3,...$. These include $[0,1], [2,3], [4,5],..., \text{etc.}$. They are disjoint, and their union is unbounded. Thus the union is not compact.
If you want a counter example where the union is still bounded, consider $\left[ \frac{1}{2n}, \frac{1}{2n+1} \right]$ for $n=1,2,3,...$. The intervals are compact and disjoint. The union is still bounded. However the union is not closed. You can see this by taking the sequence of lower endpoints of the intervals. Notice that sequence converges to $0$, but this is not in the union.


text:
Q: Date comparison in XSLT using Java I am using the below code snippet to fetch the current date in XSLT:
<xsl:variable name="currentDate">
    <xsl:variable name="datePattern">yyyy-MM-dd'T'HH:mm:ss Z</xsl:variable>
    <xsl:value-of select="java:format(java:java.text.SimpleDateFormat.new($datePattern), java:java.util.Date.new())" />
</xsl:variable>

Requirement is, to check if ShippedDate attribute value is equal to today's date, then include <Monitor> element, else exclude.
<Order>
    <Monitors>
        <Monitor ShippedDate="2015-11-10T00:00:00-05:00"/>
        <Monitor ShippedDate="2015-12-03T00:00:00-05:00"/>
    </Monitors>
</Order>

Can somebody please help me with what function needs to be used to achieve this?

A:
Requirement is, to check if ShippedDate is equal to today's date, then
  include <Monitor> element, else exclude.

I would suggest you do it this way:
XSLT 1.0 (+EXSLT)
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:date="http://exslt.org/dates-and-times"
extension-element-prefixes="date">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Monitors">
    <xsl:copy>
        <xsl:apply-templates select="Monitor[substring(@ShippedDate, 1, 10) = substring(date:date(), 1, 10)]"/>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

Test input:
<Order>
   <Monitors>
      <Monitor ShippedDate="2015-12-01T00:00:00-05:00"/>
      <Monitor ShippedDate="2015-12-02T00:00:00-05:00"/>
      <Monitor ShippedDate="2015-12-03T00:00:00-05:00"/>
   </Monitors>
</Order>

Result, when applied on December 2, 2015:
<?xml version="1.0" encoding="UTF-8"?>
<Order>
   <Monitors>
      <Monitor ShippedDate="2015-12-02T00:00:00-05:00"/>
   </Monitors>
</Order>

Note:

*

*This requires a processor that supports the EXSLT date:date() extension function (e.g. Xalan or Saxon 6.5);

*Only the date component is compared. If you are running the transformation in a time zone that's different from the time zone used in the input, the result may be inaccurate. If you want to also consider the time zone, then there's more work to do.

Added:

As a continuation of this, if none of the ShippedDate satisfies
  condition, then no output must be transformed by XSLT.

Try:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:date="http://exslt.org/dates-and-times"
extension-element-prefixes="date">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/Order">
    <xsl:variable name="current" select="Monitors/Monitor[substring(@ShippedDate, 1, 10) = substring(date:date(), 1, 10)]"/>
    <xsl:if test="$current">
        <Order>
            <Monitors>
                <xsl:copy-of select="$current"/>
            </Monitors>
        </Order>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>


text:
Q: C# Get client information before server accept I search over the internet without any luck.
What im trying to do is get the client ip address that is attempting to connect to remote server before connecting the client, to prevent unauthorised access to the server.
Im using tcp protocol and .net winforma, linux not allowed to be authorised.
Is it possible? If it is, how would i do that
I need to be able to check if the client is authorized to access the server before the server connect him


text:
Q: Forked Children Initialization Sempahore Blocking My goal is to synchronize forked processes by a common int value.
I need to fork a number of children but also semaphore block them until all the children have been forked.
This variable (init_num) must first become equal to the number of processes I have and then the processes can continue with their functions.
My code :

    pid_t pid;
    key_t key;
    sem_t *sem;
    sem_t *sem2;
    int shmid;

    int main(int argc , char* argv[])
    {
        if (argc < 2){
            printf("Incorrect number of arguments given!\n");
            exit(-1);
        }

        int num_strings = argc - 2;
        int reps = atoi (argv[1]);

        //  SHARED MEMORY  //

        key = 9876;

        shmid = shmget( key , sizeof(int) , 0644 | IPC_CREAT);
        if ( shmid < 0 ){
            perror("shmget\n");
            exit(-1);
        }

        // SHARED MEMORY INITIATED //

        int *init_num;
        init_num = shmat ( shmid , NULL , 0);
        *init_num = 0;

        // SEMAPHORES TIME //

        sem = sem_open("TheSem", O_CREAT | O_EXCL , 0644 , 1);

        sem2 = sem_open("TheSem2", O_CREAT | O_EXCL , 0644 , 0);

        // SEMAPHORE DONE //

        int i;
        // FORKS //
        for (i=0; i<num_strings; i++){
            pid = fork();

            if (pid < 0) {
                        printf ("Fork error.\n");

                sem_unlink("TheSem");
                sem_close(sem);

                sem_unlink("TheSem2");
                sem_close(sem2);
                }
                else if ( pid == 0)
                        break;
            }

        // FATHER //
        if ( pid !=0 && pid!=-1 ){
            int status;
                    while(pid = waitpid (-1,NULL,0)){
                            if(errno == ECHILD)
                                    break;
                    }
            shmdt (init_num);
            shmctl (shmid, IPC_RMID, 0);

            sem_unlink("TheSem");
            sem_close(sem);

            sem_unlink("TheSem2");
            sem_close(sem);
            }

        int n;
        //CHILDREN //
        if( pid == 0){
            sem_wait(sem);
                init();
                *init_num++;
            sem_post(sem);

            if (*init_num < num_strings ){
                sem_wait(sem2);
            }else{
                for(n=0 ; n <=num_strings-1; n++){
                    sem_post(sem2);
                }
            }

            // DISPLAY //
            for(n=0; n < reps; n++){
                sem_wait(sem);
                    display(argv[2+i]);
                sem_post(sem);
            }

        }
    return(0);
    }

And *init_num is in shared memory space.
The problem is after all of the processes have done init() and *init_num should be equal to processes my program deadlocks and stops right there.
Output :
STARTING: pid 1268, tid 1157203712
STARTING: pid 1270, tid 1157203712
STARTING: pid 1269, tid 1157203712
STARTING: pid 1271, tid 1157203712
STARTING: pid 1272, tid 1157203712
STARTING: pid 1273, tid 1157203712
STARTING: pid 1274, tid 1157203712
STARTING: pid 1275, tid 1157203712  // these are init()

A: Enable warnings, and you will see
warning: expression result unused [-Wunused-value]
        *init_num++;
        ^~~~~~~~~~~

which immediately shows your problem. The children do not increment the value: they increment the pointer. Technically it is UB, but realistically they all read 0. Change it to
        (*init_num)++;


text:
Q: Let and memory allocation I was searching for a Objective-C define equivalent in Swift and a lot of people told me to use let.
I need a lot of constants in one class and I need to create a lot of objects from this class so I think that I will waste too much memory using let instead of define
Am I wrong? Maybe let works in a different way.
Is there a way to achieve this without wasting memory?

A: Generally, let should waste a lot less memory (and other resources) than #define. Because imagine you have
#define SOME_PATH [[[@"/" stringByAppendingPathComponent:@"foo"] stringByAppendingPathComponent:@"bar"] stringByAppendingPathComponent:@"buz"]

Everywhere, you'll use SOME_PATH, it will redo the calculation and create a new NSString * for that (plus some temporary ones).
By using
let SOME_PATH = "foo".stringByAppendingPathComponent("bar").stringByAppendingPathComponent("buz")

it will do the calculation to build the string exactly once and it will only need one chunk of memory (whilst building the string there'll be some temporary objects created that are discarded quickly).
So you can use your let constant for free as often as you want. The #defined macro will have costs every time you use it.
Remember you can use let in global scope. So let doesn't just work within functions or classes, you can also define a global constant with let.


text:
Q: Add something after the "n" element using jQuery For a markup like

div 1

div 2

div 3

div 4

how do add some markup after the second DIV for instance?

A: Try the CSS selector :nth-child():
$("#holder > div:nth-child(2)").after("
foobar
");

See also the example on the jQuery page of the :nth-child() selector.

A: Use insertAfter(selector)
.insertAfter()

A: use the :eq(index) or :nth-child(index/even/odd/equation) selector in combination with the append(content) or after(content) function.
for example, assuming this code:

div 1

div 2

div 3

div 4

using append like this$("#holder>div:eq(1)").append("
inserted div
");or this$("#holder>div:nth-child(2)").append("
inserted div
");will give you

div 1

div 2
inserted div

div 3

div 4

while using after like this$("#holder>div:eq(1)").after("
inserted div
");or this$("#holder>div:nth-child(2)").after("
inserted div
");will give you

div 1

div 2

inserted div

div 3

div 4

using :nth-child can be useful as it enables you to set content every n amount of elements.
also, the index of :nth-child starts at 1 while the index of :eq starts at 0
for example, using$("#holder>div:nth-child(2n)").after("
inserted div
");will give you

div 1

div 2

inserted div

div 3

div 4

inserted div

A: $("#holder div:eq(1)") will select the second child div of the #holder div.  (:eq() selector info).  Then use the .after() function to append content.

A: use this
 $("ul li:nth-child(4n)").add('ul li:last').after("

");

A: Try it like this:
$("#holder > div:nth-child(2n)").after("
insert here
");

It will insert the
insert here
 after every 2nd row:
$("#holder > div:nth-child(2)").after("
insert here
");


text:
Q: ALAssetsLibrary doesn't retrieve image URL's in physical iOS 4.1 iPod device? I am trying to access iPhone's photo album photo images through ALAssetsLibrary. I could access all the photo albums and get the asset URL of each images on Simulator, via the following code:
- (void)viewDidLoad
{
    [super viewDidLoad];

    void (^assetEnumerator)(struct ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {
        if(result != NULL) {
            NSLog(@"See Asset: %@", result);

            // assets is a NSMutableArray..
            [assets addObject:result];

            // Here storing the asset's image URL's in NSMutablearray urlStoreArr
            NSURL *url = [[result defaultRepresentation] url];
            [urlStoreArr addObject:url];
        }
    };

    void (^assetGroupEnumerator)(struct ALAssetsGroup *, BOOL *) =  ^(ALAssetsGroup *group, BOOL *stop)
    {
        if(group != nil) {
            [group enumerateAssetsUsingBlock:assetEnumerator];
        }

        [self.activity stopAnimating];
        [self.activity setHidden:YES];
    };

    assets = [[NSMutableArray alloc] init];
    library = [[ALAssetsLibrary alloc] init];

    [library enumerateGroupsWithTypes:ALAssetsGroupAlbum usingBlock:assetGroupEnumerator failureBlock: ^(NSError *error) {
        NSLog(@"Failure");
    }];

    urlStoreArr = [[NSMutableArray alloc] init];
}

-(void) GetURLImages
{
    for (int i=0; i<[urlStoreArr count]; i++)
    {
        // To get the each image URL here...
        NSString *str = [urlStoreArr objectAtIndex:i];
        NSLog(@"str: %@",str);
    }
}

It works as expected on iOS 4.0 Simulator, i.e, getting all the images URL's (ex: assets-library://asset/asset.JPG?id=1000000002&ext=JPG). But it doesn't retrieve image URL's on iPod 4.1 device. What could be the problem here? Can someone please help me fix so the code could also work on iPod? I'm totally confused.
Thank you!

A: Try what I mentioned in my comment or the following
library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos

It also depends what photos you want.

A: void (^assetGroupEnumerator)(struct ALAssetsGroup *, BOOL *) =  ^(ALAssetsGroup *group, BOOL *stop)
{
if(group != nil) {
    [group enumerateAssetsUsingBlock:assetEnumerator];
}
[self.activity stopAnimating];
[self.activity setHidden:YES];

/* make */ group=nil;//otherwise it is enumerated thrice.
};


text:
Q: using $.post() jQuery method for button click event I have a mini-web application that populates contents of a JavaScript object as the user interacts with the page. I've added a on('click', function() {})
event handler to a button element on the page.
I want to use $.post method in the event handler to post/submit the JavaScript object to a PHP backend and asynchronously update a 'Div' element with the data/message received from the PHP server/script.
console.log verifies the JavaScript object is OK, but I can't even receive a 'Hello World' string back from the PHP script, let alone processing the JavaScript object.
Here is my code:
HTML:
<button id="sbButton" type="button">Submit </button>

`

JS:
$(function() {
    // populates name:value pairs as user interacts on the web page
    var vInfo = {};
    $('#sbButton').on('click', function() {

        $.post('http://localhost/ReceptionVisitorKiosk/response.php', vInfo, function(data) {
            console.log("Response Info " + data);
            $('#output').text(data);
        });
    });
}

PHP: Tried both as suggested by kyshel and robert in their replies to no help.

A: You must check these first:

*

*does JavaScript has syntax error? (check console)

*does your PHP has syntax or logic error?(Ex:In CentOS 7,input command#tail -f /var/log/httpd/error_log)

If there is no error, try code below, it works fine on my server:
Example
index.html
<button id="foo">Click</button>

post.php
<?php
echo '
' . var_export($_POST, true) . '
';

echo "hello,world~";

result:

A: try following snippet:
var objectToSend = {name:"Some Name", lastName:"Some last name"};
    $.post('url_to_php.php', objectToSend , function(response){
       console.log(response);
    });

accessing variables in php.
$name = $_POST["name"];
$lastName = $_POST["lastName"];
$data = //some object you are returning
header('Content-Type: application/json');
echo json_encode($data);

EDIT:
I've tested following snippet on http://phpfiddle.org/. I could not save it cause it requires registration, but you can re-paste it.
<?php
if(isset($_POST["name"]))
{
    $name = $_POST["name"];
    $data = "Thank you $name";
    header('Content-Type: application/json');
    echo json_encode($data);
    return false;
}
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>
            PhpFiddle Initial Code
        </title>

            <button id="mybutton" type="button">Click to See</button>


text:
Q: Robokassa на Node JS Всем здравствуйте. Возникла проблема с Робокассой. Пользовался библиотекой node-robokassa. Использую в качестве сервера Express. Генерирую ссылку  и проверяю тестовую оплату для success через этот код:
const outSum = 52.79;
const invDesc = 'Test Transaction';

const options = {
    invId: 14893,
    isTest: true,
    userData: {
        productId: '14893',
        username: 'Mikhail'
    }
}

const paymentUrl = robokassaHelper.generatePaymentUrl(outSum, invDesc, options);
console.log(paymentUrl);

app.post('/success', (req, res) => {
    robokassaHelper.handleResultUrlRequest(req, res, (values, userData) => {
        res.send('userData')
    });
});
app.listen(3000);

Потом смотрю в Postman, отправляю post запрос на localhost:3000/success и вижу:

Cannot read property 'OutSum' of undefined

Если кто-то встречался с проблемой, надеюсь на помощь. Заранее спасибо.

A: Проблема первая. Судя по этому кусочку кода, вы принимаете POST-запрос, но не обрабатываете его данные на сервере. В express это делается так:
const app = express();

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.post('/success', (req, res) => { ... });

Потенциальная вторая проблема.

Оповещение об оплате на ResultURL
ResultURL предназначен для получения Вашим сайтом оповещения об успешном платеже в автоматическом режиме.
В случае успешного проведения оплаты ROBOKASSA делает запрос на
ResultURL (см. раздел Технические настройки) с указанием параметров
OutSum, InvId и SignatureValue.

Перед тем как делать запрос из Postman, вам понадобится внимательно прочитать в документации ROBOKASSA как именно они вычисляют SignatureValue запроса (OutSum:InvId:Пароль#2 и 100.26:450009:Пароль#2:Shp_login=Vasya:Shp_oplata=1) и вычислить чексумму вашего запроса, иначе вы просто будете получать сообщение об ошибке:

Incorrect signature value

Понятно, что сама ROBOKASSA обратиться к вашему localhost не сможет, хотя ngrok может помочь решить эту проблему.


text:
Q: Waiting for promise before returning value I am creating a node server which helps me managing a database. I am creating an overview of how many elements are inside a certain queue-table in the database, for that I am using the following function:
var getRowCount = function(table) {
    var result = 0;
    new sql.Request()
        .query('SELECT COUNT(*) AS count FROM Queue_' + table)
        .then(function(recordset) {
            result = recordset[0].count;
        })
        .catch(err => console.dir(err));

    return result;
};

Note: I am using ES6 but am transpiling with Babel, that is why I am not using template literations for the SQL query.
My issue is, that this function always returns 0 when sending the information to my client (via socket.io). How do I wait for the promise of the query before returning the result?
For the SQL I am using node-mssql

A: sql query is a promise, so simply handle it correctly:
var getRowCount = function(table) {
    return new sql.Request().query('SELECT COUNT(*) AS count FROM Queue_' + table);
};

Then, from the outside, you'd use it in the following way:
   getRowCount(myTable).then(
     function (recordset) {
        //  send result here
     },
     function (err) {
       // send error here
     }
   );

This is the common practice with IO and promises/async code in general in node.js


text:
Q: Get latest tweets of specific user I need to get the latest tweets of specific user using javascript. I've found some script for that. Here is it:

but i get an error, that says Status Code:401 Unauthorized. I've changed the version code to 1.1, but the same error. So, I want to know, how can I pass the application id or application key to this url. And more, is there any javascript lib which works with the newest twitter api. Thanks a lot

A: The quick answer to this is version 1.0 is no longer active and version 1.1 requires OAuth for almost every api endpoint url.


text:
Q: How do i hide a layer from layerlist in ArcGIS 4.x Javascript API though i still want it to show up in the map? I would like to remove Facilities in the layerlist, but still have it show up in the map.

var manned_facilities_back = new MapImageLayer({
    url: "http://dotdevgisiis02:6080/arcgis/rest/services/DOT_MAP_PORTAL/Facilities/MapServer",

    sublayers: [
    {
      id: 1,
      popupTemplate: templateFT,

    },
    {
      id: 0,
      popupTemplate: templateMF,

    },

    ]

I've attempted to add
 listmode: hide

or
display: none

under where i have url, but it didn't work. I figure this should be really simple.

A: Setting the property Layer.listMode to "hide" should work as expected. In your example, make sure you use the correct casing:
var layer = new MapImageLayer({
  url: "http://dotdevgisiis02:6080/arcgis/rest/services/DOT_MAP_PORTAL/Facilities/MapServer",
  listMode: "hide"
});

Here's a live demo hiding one of the layers from the loaded WebScene:
https://codepen.io/arnofiva/pen/eb198c9b4050b892759ef433e8664fac


text:
Q: What happens when breaking simultaneity leads to different outcomes? Consider the classic example to show that simultaneity does not hold:
Have a photon gun firing two counter-propogating photons from the center of a moving train. The observer inside the train sees both photons hit the ends of the train simultaneously, whereas an outside observer sees the photon hit the rear-end of the train first.
Now if you modify the experiment by adding two photosensitive devices on the end of the train, and have an explosion that occurs when both photosensitive devices are triggered simultaneously.
From the reference frame inside the train, since the photons hit both ends simultaneously, the explosion will occur and the train will blow up.
However, from the reference frame outside, since the events are not simultaneous, nothing happens.
Clearly you cannot have two possible outcomes to the same event, but how do you resolve this apparent paradox?

A: //Answering my own question with a modified version of my comment
The key is that the devices are defined to only explode when hit simultaneously from the reference frame of the moving train. However, what is simultaneous inside the train is not necessarily simultaneous to an outside observer. Hence to an outside observer the device will appear to be defined as triggering when the events are not simultaneous (as governed by the lorentz transformations). So the device will indeed trigger in both reference frames due to their respective definitions in those frames.


text:
Q: how to grab the not equal row from joined table in mysql? i have two tables as following

user_job_applied

company_viewed_user

i want to take rows which are not in company_viewed_user table for relevant job_id in user_job_applied table.
i wrote the following query for it but it's not grabbed
SELECT
    `user_job_applied`.user_id
FROM
    `user_job_applied`
LEFT JOIN
    `company_viewed_user`
ON
    `company_viewed_user`.user_id ON `company_viewed_user`.user_id = `user_job_applied`.user_id
WHERE
    `company_viewed_user`.user_id IS NULL AND
    `company_viewed_user`.emp_id IN (SELECT user_id
                                     FROM company_user
                                     WHERE company_id='1')
AND
    `user_job_applied`.job_id = '1';

The output should be as following

A: You can use below query
SELECT uja.user_id
FROM `user_job_applied` AS uja
LEFT JOIN `company_viewed_user` AS cvu ON cvu.user_id = uja.user_id
WHERE cvu.user_id IS NULL;

If you want to add any other filter then you can include your own or let me know.
Added new conditions
SELECT uja.user_id
FROM `user_job_applied` AS uja
JOIN company_user AS cu ON cu.user_id=uja.emp_id
LEFT JOIN `company_viewed_user` AS cvu ON cvu.user_id = uja.user_id
WHERE uja.job_id=1 AND cu.company_id=1 AND cvu.user_id IS NULL;

Note: If job_id and company_id is not Int type then enclosed in quotes.

A: want to move emp_id condition to left join statement from in where clause
SELECT
`user_job_applied`.user_id
FROM
`user_job_applied`
LEFT JOIN `company_viewed_user` ON `company_viewed_user`.user_id = `user_job_applied`.user_id AND
                                                                `company_viewed_user`.emp_id IN (SELECT user_id FROM company_user WHERE company_id='1')
WHERE
`company_viewed_user`.user_id IS NULL AND
`user_job_applied`.job_id = '1';


text:
Q: Why is BeautifulSoup's findAll returning an empty list when I search by class? I am trying to web-scrape using an h2 tag, but BeautifulSoup returns an empty list.
<h2 class="iCIMS_InfoMsg iCIMS_InfoField_Job">

html=urlopen("https://careersus-endologix.icims.com/jobs/2034/associate-supplier-quality-engineer/job")
bs0bj=BeautifulSoup(html,"lxml")
nameList=bs0bj.findAll("h2",{"class":"iCIMS_InfoMsg iCIMS_InfoField_Job"})
print(nameList)

A: The content is inside an iframe and updated via js (so not present in initial request). You can use the same link the page is using to obtain iframe content (the iframe src). Then extract the string from the script tag that has the info and load with json, extract the description (which is html) and pass back to bs to then select the h2 tags. You now have the rest of the info stored in the second soup object as well if required.
import requests
from bs4 import BeautifulSoup as bs
import json

r = requests.get('https://careersus-endologix.icims.com/jobs/2034/associate-supplier-quality-engineer/job?mobile=false&width=1140&height=500&bga=true&needsRedirect=false&jan1offset=0&jun1offset=60&in_iframe=1')
soup = bs(r.content, 'lxml')
script = soup.select_one('[type="application/ld+json"]').text
data = json.loads(script)
soup = bs(data['description'], 'lxml')
headers = [item.text for item in soup.select('h2')]
print(headers)

A: The answer lays hidden in two elements:

*

*javascript rendered contents: after document.onload

*in particular the content managed by js comes after this comment and it's, indeed, rendered by js. The line where the block starts is: "< ! - -BEGIN ICIMS - - >" (space added to avoid it goes blank)

As you can imagine the h2 class="ICISM class here" DOESN'T exist WHEN you call the bs4 methods.
The solution?
IMHO the best way to achieve what you want is to use selenium, to get a full rendered web page.
check this also
Web-scraping JavaScript page with Python


text:
Q: If both masses are moving then why only calculate the gravitational potential energy of only one mass though both are acted by the conservative forces Suppose a two mass $M$ and $m$ are acted upon by the gravitational force, so both has conservative force that is doing a work, but we only take one conservative force and simply calculate the work done by one of the conservative forces, why?
Why dont we calclate potential forces for each mass as both act upon by the conservative forces and add up the value.

A: The gravitational potential energy is associated with the gravitational field.  If you were to count this energy twice, you would not observe conservation of energy as your system evolves.
Consider your masses $M>m$ initially at rest with some separation $r_1$, so total mechanical energy
$$
E_1=-\frac{GMm}{r_1}$$
They fall towards each other, and later have
$$
E_2=\frac{P^2}{2M}+\frac{p^2}{2m}-\frac{GMm}{r_2}$$
Conservation of momentum gives $\vec P=-\vec p$.  In the limit $M\gg m$, such as when one mass is the Earth and the other is a piece of toast, you can see that "all" of the kinetic energy is acquired by the low-mass object, and that therefore including the potential energy twice would mispredict whether the toast lands buttered-side-down.  As you approach $M\approx m$, there is no point where it suddenly becomes appropriate to double the potential energy.

A:
Why dont we calclate potential forces for each mass

We do! If the gravitational potential of the two-mass system is $\Phi(r_1, r_2)$ then the gravitational forces on those masses are
$$F_1=-\frac{\partial \Phi}{\partial r_1}$$
$$F_2=-\frac{\partial \Phi}{\partial r_2}$$

as both act upon by the conservative forces and add up the value.

Again, we do! If we want to calculate the total force that acts on the two-mass system, we add the individual forces together. But conservative as they are, the sum of all forces is zero, which is nothing but momentum conservation of the system.
Getting zero might seem less interesting than you thought, but actually null results are the most interesting in all science because zero can be measured to arbitrary relative precision. If anything in free space starts accelerating ever so small, you just need to wait a sufficiently long time to notice the effect. Thus, by waiting long enough next to a system at rest, and never seeing any movement, you can make sure that momentum conservation holds true to really fantastic accuracy.


text:
Q: Elasticserch merge logs I use Fleet and Security on a ElasticSearch and Kibana dashboard. I received logs for a period of time from a hostname "X", for which I would like to change its name now to "Y". Doing this would generate two hostnames ("X" and "Y") in the dashboard filters, for example, even though the data refers to the same host. "X" appears to stop sending data at the moment when "Y" starts to send it - obviously.
I was not able to find and clean solution to create something like an alias, or to "rewrite" the previous ones in order to have the same continuity of the data ...
Any ideas would be welcomed.


text:
Q: c# - save values from 1000s of xmls to excel My C# application loops over 5000 files and then writes the values of xpaths to cells in an excel sheet. It is quite slow processing 40files a second.
After profiling I discovered that this line accounts for over 50% of all time used:
XmlDocument.Load(filename);

To write to excel i loop over each xpath of each file and do:
worksheet.Cells[row, col] = value;

Would it be more beneficial in terms of speed to load all the xmls into memory at once (they are less than 20kb each) then store them in a collection then transpose them all to excel?
I understanding that multi-threading would possibly reduce performance rather than improve it as the process is IO-bound.

A: It might not be IO bound. Most of the time is spent constructing the XML DOM. However, multi-threading would introduce a possible issue, depending on where you're writing the results to Excel. I don't know for sure, but I wouldn't be surprised if you could only access the Office objects from a single thread.
You would have to add an additional step of collecting the results before writing to the Excel object. This would have to be some sort of synchronized collection, with either another thread dedicated to writing to Excel, or do it after all of the files are processed.
Now, going back to the first point: Most of the time is spent loading the DOM. Based on the results from http://www.nearinfinity.com/blogs/joe_ferner/performance_linq_to_sql_vs.html If you still need DOM related methods, I would look at using XDocument instead. The interface isn't that far off XmlDocument, so it should be an easy adaption.
For the most speed processing XML, look into XmlReader. However, this does not get you any DOM functions, and can be harder to deal with than the two DOM based methods.
So, in short, first try converting to the XDocument methods, that might roughly double your speed. I would then look at converting the processing to multithreaded (perhaps using PLINQ over the list of files). Finally, if performance is still not enough, try using the XmlReader interface.
EDIT in response to collection types to use:
I see two basic options for this, depending on how long it takes to process the XML files. If it is a small percentage of the overall process (most time is spent dealing with Excel), just have a List<T> where T is some representation of the data you need to write to excel (It could even be a string if that's all you need), with the .Add methods surrounded by lock's. Then once XML processing is complete, the Excel writer iterates over this collection.
Another option if XML processing takes awhile, and you're on .Net 4, look at the ConcurrentQueue class. This will provide thread safety on it's own (and really now that I look, one of the Concurrent collections could be used in the first case too, either ConcurrentQueue or BlockingCollection). You would then have threads running processing XML, and then a consumer thread that writes out to Excel.
A few other things. Expanding a comment on a question, if you're doing nothing that needs Excel specific functions, you could just write out to CSV. The library here http://www.codeproject.com/Articles/86973/C-CSV-Reader-and-Writer is rather straightforward to use, and handles embedded commas. The downside of this is the Big Scary Dialogs excel throws up if you try to save a CSV. These might be overcome with user training, however.
Another option would be to use the OpenXML library to generate Excel files if you're targeting at least Excel 2007 (Although Excel 2003 can read xlsx files with an addin), provided you aren't already. I imagine that, since this library manipulates XML it would be faster than dealing with Excel interop, and also safer (no dialogs from Excel, no zombie processes, etc).

A: It looks to me as if most of the time is being spent in XML parsing, and there is no way of doing this without parsing the XML. So I don't think there's an easy answer.


text:
Q: Form is being cleared before data is submitted to database I am using asp.net mvc and I am trying to enter data into a form then submit the values to the database. I would the form to be cleared after data has been submitted to the database but unfortunately it seems that the form is being cleared before the submission.
Here is my form
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "applicationForm" ,@name= "applicationForm", @class = "applicationForm" }))
{
    @Html.AntiForgeryToken()

            @*
Order
*@
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

                        First Name

                        @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { id = "firstName", placeholder = "Enter first name", @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })

                        Middle Name

                        @Html.EditorFor(model => model.MiddleName, new { htmlAttributes = new { id = "middleName", placeholder = "Enter middle name", @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.MiddleName, "", new { @class = "text-danger" })

                        Last Name

                        @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { id = "lastName", placeholder = "Enter last name", @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })

                <input type="submit" value="Submit" id="submitButton" class="btn btn-warning" onclick = "submitForm()" />

}

Here is my script at the top of the html form which contains the form


text:
Q: ORACLE LIKE with multiple values I have the below query in ORACLE which takes a really long time to run because of the OR in between the 2 likes.
select pat_mrn_id,surgery_date, proc_name
from or_log_all_proc, or_proc, or_log, patient
where
upper(proc_name) like ('%CRANIOTOMY ANEURYSM%') OR upper(proc_name) like
('CLIPPING%ANEURYSM')

Any help in writing the query efficiently would be appreciated.
Thanks!
JH

A:
from or_log_all_proc, or_proc, or_log, patient

Your SELECT contains no join criteria so it's going to generate a product of all the records from three of those tables and the result set of whichever table is filtered by the LIKE clauses. That is the root of your performance issue.
The solution is quite simple. Join the tables correctly using the appropriate key columns.
Incidentally this is a benefit of using the ANSI 92 join syntax. By making the type of join explicit we have to actually write CROSS JOIN if we really do want to generate a product, and prevents us from doing it accidentally.

Expecting LIKE '%anything%' to be quick is also futile

Up to a point. Most likely it's a Full Table Scan, but it's an indexed column then we might get a Full Fast Scan. Even if it is just an FTS that's not necessarily catastrophic, especially if the table is small or narroe. As with most tuning tasks, it really depends on the details.

A: Instead of LIKE, use regular expressions.  But more importantly, you are missing JOIN conditions:
select pat_mrn_id,surgery_date, proc_name
from or_log_all_proc join
     or_proc
     on ???? join
     or_log
     on ????
     patient
     on ????
where regexp_like(upper(proc_name), '(CRANIOTOMY ANEURYSM)|(CLIPPING.*ANEURYSM)');

It is much more likely that the performance issue is due to the lack of JOIN conditions than the LIKE.

A: LIKE will be slow anyway, won't it? Though, if you're sure that it is OR that causes problems, try UNION, e.g.
select pat_mrn_id,surgery_date, proc_name
from or_log_all_proc, or_proc, or_log, patient
where upper(proc_name) like ('%CRANIOTOMY ANEURYSM%')
union all
select pat_mrn_id,surgery_date, proc_name
from or_log_all_proc, or_proc, or_log, patient
where upper(proc_name) like ('CLIPPING%ANEURYSM')

Also, I guess that this isn't query you really use - there are 4 tables in the FROM clause, without any joins - a Cartesian product isn't the best choice.

A: Try union all instead of or for better performance
 select pat_mrn_id,surgery_date, proc_name
 from or_log_all_proc, or_proc, or_log, patient
 where
 upper(proc_name) like ('CLIPPING%ANEURYSM')
 union all
 select pat_mrn_id,surgery_date, proc_name
 from or_log_all_proc, or_proc, or_log, patient
 where upper(proc_name) like ('%CRANIOTOMY ANEURYSM%')

Also I think you forgot to connect the tables using unique IDs


text:
Q: How to play audio file in Safari without letting anyone to directly download it? I want to play audio files in the browser and don't want to let anyone
 can directly download them from URL.
Currently, It works fine in google browser, but Safari can't even play the audio files through mine way.
I set the audio tag resource to the controller that get the audio file content through Storage::get($filename).
<audio controls="controls">
    <source src="http://localhost:8000/audio/getAudio/{{ $filename }}">
</audio>

public function getAudio($filename)
{
    return Storage::get($filename);
}

None error message shown in the Safari console, so it's hard for me to debug.
Maybe there is another way to achieve what I want to, like using .htaccess
to prevent users to download any other audio files that not shown in the current webpage so I don't need to hide the audio files in the storage folders.
I never use .htaccess before, it may take me a while to learn it.

A: To avoid file being downloaded, you need to add the proper headers to your response.
Something like this :
public function getAudio($filename)
{
    $file = Storage::get($filename);
    return (new Response($file, 200))
           ->header('Content-Type', 'audio/aac');
}

You can specify the MIME type of your file in your response.
More here : MIME Types


text:
Q: How to define the address in the endpoint for hirarchical relationship of classes in wcf?     class MyCalculator : IScientificCalculator
    {
         public int Add(int arg1,int arg2)
         {
             return arg1 + arg2;
         }

         public int Multiply(int arg1,int arg2)
         {
            return arg1 * arg2;
         }
    }

In the given hierarchy if i have the relation ship parent1:child1-->child1:child2-->child2:child3
how to define the address? Whether to define the address for each class in the endpoint?
But at the last derived class have all the operation contracts which are in the base class because of Inheritance. Can I define only the address for the base class?
like
<service name = "MyCalculator">
<endpoint
address = "http://localhost:8001/MyCalculator/"
binding = "basicHttpBinding"
contract = "IScientificCalculator"
/>
</service>

A: What i was looking for
[ServiceContract]
interface ISimpleCalculator
{
  [OperationContract]
   int Add(int arg1,int arg2);
}
   [ServiceContract]
  interface IScientificCalculator : ISimpleCalculator
  {
    [OperationContract]
     int Multiply(int arg1,int arg2);
}

When it comes to implementing a contract hierarchy, a single service class can implement
the entire hierarchy, just as with classic C# programming:
class MyCalculator : IScientificCalculator
{
public int Add(int arg1,int arg2)
{
return arg1 + arg2;
}
public int Multiply(int arg1,int arg2)
{
return arg1 * arg2;
}
}

The host can expose a single endpoint for the bottommost interface in the hierarchy:
<service name = "MyCalculator">
<endpoint
address = "http://localhost:8001/MyCalculator/"
binding = "basicHttpBinding"
contract = "IScientificCalculator"
/>
</service>


text:
Q: Spotlight pop-up effects I saw someone with a Macbook Pro using the Spotlight feature several times, and every time the Spotlight opened, it used a certain effect that's not like what I see in other Macs (I use Leopard).
The effect I'm talking about is like a vanishing "teleport" effect, it opens up starting with a thin, long horizontal bright line which shortens and expands in height until it reveals the Spotlight. To see a similar effect, use a recent version of Safari with several tabs open, and drag one of the tabs down as if you're going to break it off into a new window.
Does this effect happen to be OS based, or exist from a third-party tool (Something like Compiz, but for Mac)?

A: It sounds to me like you may be describing Quicksilver, which is, among other things, an application launcher.
http://qsapp.com/index.php
I use it daily and it can look very much the way you have just described.  It has several different interfaces.
However...  It is definitely not spotlight, and it doesn't use any spotlight like icon...
Mine also pops up in the middle of the screen, not the top right like spotlight....
Does this sound like what you may have been looking at?


text:
Q: Why do view controllers in my Storyboard keep disappearing? The View Controllers in my Storyboard file keep disappearing.
As of now I have to press the up arrow and highlight over every single item to reinstate my view controllers.
What can I do to get rid of this problem and is there something else I can do to reinstate these disappearing view controllers onto my storyboard?

A: This is a bug... Usually i'm able to fix it by closing the storyboard and re-opening it.

A: I was able to fix mine by resetting xcode completely. Try this: http://www.developers-life.com/uninstallresetting-xcode.html


text:
Q: wpflocalizeextension refer to a .resx file in another project I am trying to centralise my localisation in a multi project solution.
A decision was made to use the extension which works well in the code behind, but not in the xaml. The .resx file was working sitting in the local project properties directory
lex:ResxLocalizationProvider.DefaultAssembly="Project1"

lex:ResxLocalizationProvider.DefaultDictionary="Strings"

But I can't seem to get it to consume the propeties in a different project
for example
lex:ResxLocalizationProvider.DefaultAssembly="clr-namespace:Localisation;assembly=Localisation.Properties"

 lex:ResxLocalizationProvider.DefaultDictionary="Strings"

and iterations of the same, is this possible?

A: As it turns out the solution was to create linked files to the other project's resx files rather than a direct reference from within the xaml bit clunky but a solution.


text:
Q: If tests are failing w/ 'Internal Salesforce Error' in Summer '18, what will happen to deployed version when Production upgrades? I've been building out queueable processes in our Sandbox on Summer '18, and I was able to deploy some of the functionality last week to Production (Spring '18), and now those tests in Sandbox are failing with 'Internal Salesforce Error'.
I have two immediate concerns -

*

*Is it likely, then, that the tests (and possibly the processes themselves) will start failing when Production is upgraded, and

*If the sandbox was upgraded ~ a week ago, and I was able to run tests last week in the upgraded sandbox, what's going on?

I don't see any issues on Trust at the moment for my Sandbox instance; not sure what my next steps ought to be to move forward on these projects, since the similar tests for phase two are also failing w/ the same(?) internal errors.

A: Before each release, Salesforce runs the Apex Hammer Test, which basically means it runs all of your tests in the current release and the next release, and logs any differences in behaviors (e.g. failures, Internal Server Errors, etc). If there is a difference, these differences are given high priority to be patched before the next release hits.
So, what likely happened is that the AHT ran against your org, the error was logged, a bug was generated, and it was patched. This all happens invisibly behind the scenes so customers don't have to worry about it. As far as I can tell, no customer anywhere ever has had a test that passed in one release and fail in the next purely because of regression; Salesforce is really good at catching those errors.
However, if you're really concerned, you can contact support. The most likely course of action is that they'll forward your case to R&D (Research & Development) to get it fixed, or advise you on how you can fix your code so it won't be impacted in Summer '18.


text:
Q: Overloading + operator in Arduino's String class In the Arduino String class, the + operator is overloaded many times. I'm porting this code to a Silicon Labs EFM32 part (using ARM GNU) and getting problems. With reference to the header in the link, these are the lines that are giving me grief:
friend StringSumHelper &operator+(const StringSumHelper &lhs, const String &rhs);
friend StringSumHelper &operator+(const StringSumHelper &lhs, const char *cstr);
friend StringSumHelper &operator+(const StringSumHelper &lhs, char c);
friend StringSumHelper &operator+(const StringSumHelper &lhs, unsigned char num);

friend StringSumHelper & operator + (const StringSumHelper &lhs, short num);
friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned short num);

friend StringSumHelper & operator + (const StringSumHelper &lhs, int num);
friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned int num);
friend StringSumHelper & operator + (const StringSumHelper &lhs, long long num);
friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned long long num);

When compiling, I get the following two error types:
C:\arduino_string.h:176:83: error: declaration of C function 'StringSumHelper& operator+(const StringSumHelper&, long long int)' conflicts with
 friend StringSumHelper & operator + (const StringSumHelper &lhs, long long num);

C:\arduino_string.h:155:29: error: previous declaration 'StringSumHelper& operator+(const StringSumHelper&, char)' here
 friend StringSumHelper &operator+(const StringSumHelper &lhs, char c);
                         ^

I get a pair of these errors for each overload.
I have commented out the entirety of the corresponding C++ file. I have also removed #include <avr/pgmspace.h> from the header, because I'm not using this architecture.
I don't use friend methods much, and as the first comment says, they don't have a this pointer, so having two parameters for an overload+ as a member function now makes sense. But it seems to me like this actually may not be the case during compilation? In any case, I don't know what the problem is!


text:
Q: If $\{a_n\}$ is a sequence in which $a_n \geq c$ for some constant $c$ and $a_n \rightarrow a$ then $a \geq c$ If  $\{a_n\}$ is a sequence in which $a_n \geq c$ for some constant $c$  and $a_n \rightarrow a$ then $a \geq c$
I just wanted some feedback on whether my proof of the claim is sound.
Proof
Let $\epsilon > 0$  and $ a < c$. Now $a_n \rightarrow a$ means:
$$\forall \  \epsilon >0,\ \exists \ N\in \mathbb{N} \ s.t.\ \forall \ n \geq N \ |a_n - a| < \epsilon \\ \Leftrightarrow \\ \ a-\epsilon \leq a_n \leq a + \epsilon$$
Consider $\epsilon = \frac{c-a}{2}$
$$\Rightarrow c \leq a_n \leq a + \frac{c-a}{2} = \frac{a+c}{2} < \frac{c + c}{2} = c$$
$c < c$ is a contradiction. Therefore $a \geq c$ for the statement to hold.

A: The idea is fine but:

*

*You should not begin with "Let $\varepsilon>0$". You fix $\varepsilon$ later, not at this point.

*You should write that you are assuming that $a<c$, in order to get a contradiction. You can't just say "Let […] $a<c$", because $a$ and $c$ are fixed from the start.

A: Your proof seems legitimate to me, but it is a proof by contradiction, so here is an alternate way to do it directly. I will start with what you have.
$$\forall \  \epsilon >0,\ \exists \ N\in \mathbb{N} \ s.t.\ \forall \ n \geq N \ |a_n - a| < \epsilon \\ \Leftrightarrow \\ \ a-\epsilon \leq a_n \leq a + \epsilon$$
Now, this implies that for any $\epsilon > 0$, $a_n \leq a+\epsilon$ for some $n \in \Bbb{N}$. Also, $c \leq a_n$, so we get $c\leq a+\epsilon$ for any $\epsilon > 0$. Thus, $c\leq g$ for all real numbers $g$ in the interval $(a, \infty)$. It is well known that $a$ is the greatest lower bound for $(a, \infty)$, so this implies $c \leq a$.


text:
Q: Setting InheritanceFlags vs PropagationFlags in Powershell I'm trying to find the right combination of the InheritanceFlags and PropagationFlags so that my new folder will not inherit the folder's permissions before it, but will propagate the rights to the folders/files contained in the new folder... I tried swapping the two from what I have below, but that only gave the new folder the same permissions as the one above it and didn't apply my new groups...
How do I set the flags correctly to only apply the permissions to all files/folders below this folder and not pull from the parent folder?
I found this table, but it doesn't seem to do what I'm wanting...
function New-Ace {
  [CmdletBinding()]
  Param(
    [Parameter(Mandatory=$true, Position=0)]
    [Security.Principal.NTAccount]$Account,
    [Parameter(Mandatory=$false, Position=1)]
    [Security.AccessControl.FileSystemRights]$Permissions = 'ReadAndExecute',
    [Parameter(Mandatory=$false, Position=2)]
    [Security.AccessControl.InheritanceFlags]$InheritanceFlags = 'ContainerInherit,ObjectInherit',
    [Parameter(Mandatory=$false, Position=3)]
    [Security.AccessControl.PropagationFlags]$PropagationFlags = 'None',
    [Parameter(Mandatory=$false, Position=4)]
    [Security.AccessControl.AccessControlType]$Type = 'Allow'
  )

  New-Object Security.AccessControl.FileSystemAccessRule(
    $Account, $Permissions, $InheritanceFlags, $PropagationFlags, $Type
  )
}

$domain = 'TestDomain'

$administrators = ([wmi]"Win32_Sid.Sid='S-1-5-32-544'").AccountName

$acl = Get-Acl $path

$administrators, "$domain\Domain Admins" | ForEach-Object {
  $acl.AddAccessRule((New-Ace $_ 'FullControl'))
}
$acl.AddAccessRule((New-Ace $ADNameRW 'Modify'))
$acl.AddAccessRule((New-Ace $ADNameRO 'ReadAndExecute'))

Set-Acl $path $acl

A: Calling $acl.SetAccessRuleProtection($true, $false) should prevent that directory or file from inheriting permissions from its parent directory, with the second parameter specifying that the previously-inherited permissions should be removed.  Enabling protection = disabling inheritance.
In your New-Ace function, InheritanceFlags specifies to which type of child object (files, directories, or both) the permissions can apply, and PropagationFlags controls whether the permissions apply to this object and/or only immediate children.  Neither of these properties affects how this file or directory inherits from its parent.
By the way, PowerShell is built on .NET so the same classes, methods, etc. are available to you, and in some instances the only way to accomplish something that isn't covered by a cmdlet.


text:
Q: Visual Studio 2013 is unable to open the Test Window When I open Visual Studio 2013 and load my solution I'm greeted by an error message telling me the Test Window is unable to load.
The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.

1) Cannot compose part 'Microsoft.VisualStudio.TestWindow.Controller.TestsServiceInternal' because a cycle exists in the dependencies between the exports being composed. To break this cycle, consider changing some imports from constructor to property injection.
Element: Microsoft.VisualStudio.TestWindow.Controller.TestsServiceInternal -->  Microsoft.VisualStudio.TestWindow.Controller.TestsServiceInternal

Resulting in: Cannot get export 'Microsoft.VisualStudio.TestWindow.Controller.TestsServiceInternal (ContractName="Microsoft.VisualStudio.TestWindow.Data.TestsService+ITestsServiceInternal")' from part 'Microsoft.VisualStudio.TestWindow.Controller.TestsServiceInternal'.
Element: Microsoft.VisualStudio.TestWindow.Controller.TestsServiceInternal (ContractName="Microsoft.VisualStudio.TestWindow.Data.TestsService+ITestsServiceInternal") -->  Microsoft.VisualStudio.TestWindow.Controller.TestsServiceInternal

The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.

1) An operation is not legal in the current state. (Exception from HRESULT: 0x80131509)

Resulting in: An exception occurred while trying to create an instance of type 'Microsoft.VisualStudio.TestWindow.VsHost.TestWindowHost'.

Resulting in: Cannot activate part 'Microsoft.VisualStudio.TestWindow.VsHost.TestWindowHost'.
Element: Microsoft.VisualStudio.TestWindow.VsHost.TestWindowHost -->  Microsoft.VisualStudio.TestWindow.VsHost.TestWindowHost

Resulting in: Cannot get export 'Microsoft.VisualStudio.TestWindow.VsHost.TestWindowHost (ContractName="Microsoft.VisualStudio.TestWindow.Controller.IOpenResult")' from part 'Microsoft.VisualStudio.TestWindow.VsHost.TestWindowHost'.
Element: Microsoft.VisualStudio.TestWindow.VsHost.TestWindowHost (ContractName="Microsoft.VisualStudio.TestWindow.Controller.IOpenResult") -->  Microsoft.VisualStudio.TestWindow.VsHost.TestWindowHost

Resulting in: Cannot set import 'Microsoft.VisualStudio.TestWindow.Controller.TestsServiceInternal..ctor (Parameter="openResult", ContractName="Microsoft.VisualStudio.TestWindow.Controller.IOpenResult")' on part 'Microsoft.VisualStudio.TestWindow.Controller.TestsServiceInternal'.
Element: Microsoft.VisualStudio.TestWindow.Controller.TestsServiceInternal..ctor (Parameter="openResult", ContractName="Microsoft.VisualStudio.TestWindow.Controller.IOpenResult") -->  Microsoft.VisualStudio.TestWindow.Controller.TestsServiceInternal

Resulting in: Cannot get export 'Microsoft.VisualStudio.TestWindow.Controller.TestsServiceInternal (ContractName="Microsoft.VisualStudio.TestWindow.Data.TestsService+ITestsServiceInternal")' from part 'Microsoft.VisualStudio.TestWindow.Controller.TestsServiceInternal'.
Element: Microsoft.VisualStudio.TestWindow.Controller.TestsServiceInternal (ContractName="Microsoft.VisualStudio.TestWindow.Data.TestsService+ITestsServiceInternal") -->  Microsoft.VisualStudio.TestWindow.Controller.TestsServiceInternal

Visual Studio is unable to run tests at all. Closing an re-opening the test window shows the same error.

A: This seems to be caused by a corruption in the Component Model Cache.
Close all instances of Visual Studio, then navigate to folder and delete it.

%LOCALAPPDATA%\Microsoft\VisualStudio\12.0\ComponentModelCache

Now restart Visual Studio and it should work again.

A: Deleting solution.v12.suo and solution.suo can help resolve the problem as well.

A: I tried to best answer (navigate to folder and delete it.    %LOCALAPPDATA%\Microsoft\VisualStudio\12.0\ComponentModelCache) and it didn't work BUT, based on this method I found the solution which works for me :
navigate to folder and delete it :
%LOCALAPPDATA%\Microsoft\WDExpress\11.0\ComponentModelCache
Hope I can help some people this way

A: Just close and re-open Visual Studio (2015) may help.


text:
Q: como configurar um componente drawer para que ela empurre todo o conteúdo do site para o lado e ainda não seja afetada pelo scroll? A ideia era empurrar todos os outros conteúdo da outra Box para a direita quando o drawer estivesse, porem ele fosse imune ao scroll do mouse deixando o conteúdo dela sempre visivel
  <Box>
    <Sidebar onClose={(data) => {
      setOpen(data);
    }} open={open} />
  </Box>

  <Box>
    <Navbar onOpen={(data) => {
      setOpen(data);
    }} />

    <Perfil />
    <AboutMe />
    <DevSkills />
    <Services />
    <Experience />
    <Qualificacoes />
    <Footer />
  </Box>

</Box>


text:
Q: Gridview event is not firing for some rows I am displaying a summary page inside the Gridview. Everything is working fine except the last 3 rows of the gridview rowcommand event is not firing when i click on it.
Below is the aspx code which i used for commandargument.
<asp:LinkButton ID="lnkUnpaid" runat="server"  Text='<%# Convert.ToDouble(Eval("Unpaid_Claims")).ToString("#,##0.00") %>'

CommandArgument='<%# Eval("Companyid")+ ";" +Eval("TypeOf")+ ";" +Eval("BranchID")+ ";" +Eval("CategoryID") %>' CommandName="Unpaid"></asp:LinkButton>

Below is the code generate inside HTML

        预付手机费

        5,620.00

        5,620.00

        0.00

        200.00

        5,420.00

        预支薪金

        5,075.00

        5,075.00

        0.00

        5,075.00

        0.00

Below is screen shot.The area which marked in Red is not firing upon click.
![Error in Griddiew   1
Any help is really appreciated.


text:
Q: how to convert .docx and .pdf to .txt file I am working on an application for which i need to convert .docx and .pdf file to .txt
file with basic formatting. I searched it in internet but couldn't find any free third party dlls. Can any one suggest me best way and some dlls reference for this.
Thanks in Advance

A: http://support.microsoft.com/kb/316383 describes what you want to do with .docx files very well.
http://visualbasic.about.com/od/quicktips/qt/disppdf.htm describes the same, but with .pdf files.
Once you have read files into your code, output to a txt file using VB.NET's built in file writing functions.

A: The code below will handle the job for you. It is something I wrote for the big boss haha. I hope it helps. The code reads the first cell in the work sheet as the folder where docx files are present and then converts them to txt files one by one saving in the same folder.
Const wdFormatText = 2

If Not Len(Cells(1, "A").Value) > 0 Or Dir(Cells(1, "A").Value, vbDirectory) = "" Then
    MsgBox ("Invalid Folder")
    Exit Sub
End If

Dim StrFile As String

    StrFile = Dir(Cells(1, "A").Value & "\*.docx")
    Do While Len(StrFile) > 0
        Set objWord = CreateObject("Word.Application")
        Set objDoc = objWord.Documents.Open(Cells(1, "A").Value & "\" & StrFile, False, True)
        objDoc.SaveAs Cells(1, "A").Value & "\" & StrFile & ".txt", wdFormatText
        objWord.Quit
        StrFile = Dir
    Loop


text:
Q: How to share photos to Facebook from Windows 8 Picture Library? Maybe this is trivial and I just can't see it, but when I open Picture Library and try the Share charm to share or upload photos it only brings up the Mail and SkyDrive. No Facebook or People option.
However if I open the SkyDrive and try to share a photo the People option shows up.
My Facebook account is already linked and has all the permissions:

A: There is a workaround for this by installing the Share Photo application available at the store.


text:
Q: git pull and clone failed; The remote end hung up unexpectedly RPC failed; Hi I wanted to pull a project which I was working on it about a month ago. After one month I wanted to get the latest updates of the project with git pull but it won't work and had this error:
The remote end hung up unexpectedly RPC failed; HTTP 500 curl 22 The requested URL returned error: 500 Internal Server Error

Then I wanted to clone this project. So I get the link and clone it with intellij but it did not work again and the error was the same as before.
What should I do???
P.S: my OS is windows 64-bit
Solved: the problem was from the SSH Key. I set SSH Key for the repository and it works fine right now.

A: I think you should use following command
Try this one first
git config http.postBuffer 524288000
and then run this one
$ git remote add origin git@github.com:username/project.git
after that clone your project.
Your problem should be resolved.

A: Solved: the problem was from the SSH Key. I set SSH Key for the repository and it works fine right now.


text:
Q: "db:migrate rake aborted" error due to uninitialized constant Rake::FileUtilsExt I'm new to Ruby on Rails, and I've been trying to deploy a simple Cappuccino app with Ruby on Rails on to Heroku for the last three days, and every time I initialize (heroku rake db:migrate) I keep get the following error.
(in /app)
rake aborted!
uninitialized constant Rake::FileUtilsExt
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2482:in `const_missing'
/app/Rakefile:15:in `<module:RakeFileUtils>'
/app/Rakefile:14:in `<top (required)>'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2373:in `load'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2373:in `raw_load_rakefile'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2007:in `block in load_rakefile'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2058:in `standard_exception_handling'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:2006:in `load_rakefile'
/usr/ruby1.9.2/lib/ruby/1.9.1/rake.rb:1991:in `run'
/usr/ruby1.9.2/bin/rake:31:in `<main>'

I have updated all the required gems and bundles.
Here is my gem list for your reference:
*** LOCAL GEMS ***

abstract (1.0.0)
actionmailer (3.0.9, 3.0.8, 3.0.7, 3.0.5)
actionpack (3.0.9, 3.0.8, 3.0.7, 3.0.5, 2.3.8)
activemodel (3.0.9, 3.0.8, 3.0.7, 3.0.5)
activerecord (3.0.9, 3.0.8, 3.0.7, 3.0.5)
activeresource (3.0.9, 3.0.8, 3.0.7, 3.0.5)
activesupport (3.0.9, 3.0.8, 3.0.7, 3.0.5, 2.3.8)
arel (2.1.1, 2.0.10, 2.0.9)
builder (3.0.0, 2.1.2)
bundler (1.0.15)
capistrano (2.6.0, 2.5.20)
configuration (1.2.0)
daemons (1.1.3, 1.1.0)
dnssd (2.0)
erubis (2.7.0, 2.6.6)
eventmachine (0.12.10)
fastthread (1.0.7)
fcgi (0.8.8)
heroku (2.3.0, 2.2.8 ruby)
highline (1.6.2, 1.6.1)
hpricot (0.8.4)
i18n (0.6.0, 0.5.0)
jk-ferret (0.11.8.3)
launchy (0.4.0)
libxml-ruby (2.0.6, 1.1.4)
mail (2.3.0, 2.2.19, 2.2.15)
mime-types (1.16)
net-scp (1.0.4)
net-sftp (2.0.5)
net-ssh (2.1.4, 2.1.3)
net-ssh-gateway (1.1.0, 1.0.1)
polyglot (0.3.1)
rack (1.3.0, 1.2.3)
rack-mount (0.8.1, 0.7.1, 0.6.14)
rack-test (0.6.0, 0.5.7)
rails (3.0.9, 3.0.8)
railties (3.0.9, 3.0.8)
rake (0.9.2, 0.8.7)
rdoc (3.6.1)
RedCloth (4.2.7)
rest-client (1.6.3)
ruby-openid (2.1.8)
rubygems-update (1.8.5, 1.6.2)
sequel (3.24.1, 3.20.0)
sinatra (1.2.6, 1.0)
sqlite3 (1.3.3)
sqlite3-ruby (1.3.3)
taps (0.3.23)
term-ansicolor (1.0.5)
thin (1.2.11)
thor (0.14.6)
tilt (1.3.2)
treetop (1.4.9)
tzinfo (0.3.28, 0.3.25)
xmpp4r (0.5)

And here is the Bundle list:
    {Gems included by the bundle:
      * abstract (1.0.0)
      * actionmailer (3.0.8)
      * actionpack (3.0.8)
      * activemodel (3.0.8)
      * activerecord (3.0.8)
      * activeresource (3.0.8)
      * activesupport (3.0.8)
      * arel (2.0.10)
      * builder (2.1.2)
      * bundler (1.0.15)
      * erubis (2.6.6)
      * i18n (0.5.0)
      * mail (2.2.19)
      * mime-types (1.16)
      * polyglot (0.3.1)
      * rack (1.2.3)
      * rack-mount (0.6.14)
      * rack-test (0.5.7)
      * rails (3.0.8)
      * railties (3.0.8)
      * rake (0.9.2)
      * sqlite3 (1.3.3)
      * thor (0.14.6)
      * treetop (1.4.9)
      * tzinfo (0.3.28)}

I've tried everything, and I am at my personal EOL. I've spent a good deal of time exploring the questions here and trying everything available.

A: I am receiving the same error on a new Heroku server with a new, tiny Rails application and have not received it before. Perhaps this is a new Heroku issue?
Pushing the local database with taps worked as a quick-fix, but is neither a scalable nor reasonable long-term solution:
$ sudo gem install taps
$ heroku db:push

A: There is a known problem with the version of Rake. Try rolling your Rake version back to 0.8.7.
See the Twitter remark from DHH (2011-05-21): Rake 0.9, which was released yesterday, broke Rails (and others). While we wait for a fix, you'll want to have gem 'rake', '0.8.7' in your Gem file.

A: How to fix the uninitialized constant Rake::DSL problem on Heroku? sounds similar.
Maybe try
require 'rake/file_utils'

in Rakefile before require 'rake'?


text:
Q: NavigationService error in WP8 app I'm trying to implement simple code, that allows user to go to another app-page with transferring parameter/variable "Totall" to next page:
 Private Sub HyperlinkButton_Click(sender As Object, e As RoutedEventArgs)
        NavigationService.Navigate(New Uri("/Mainpage.xaml?totall=" & Totall, UriKind.Relative))

        Me.Frame.Navigate(GetType(MainPage))
    End Sub

But I get an error "NavigationService is not declared". Why is happening?
This is WP8.1 app on Framework 4.5
This is not a Silverlight app.
Yes, I have declared Imports Windows.UI.Xaml.Navigation
Thank you!

A: NavigationService is not available in WinRT. To pass parameters while navigating, you can use the second line in your method and just add the parameter:
Me.Frame.Navigate(GetType(MainPage), Totall)

To retrieve this parameter on the target page, override the OnNavigatedTo method like in the following example:
Protected Overrides Sub OnNavigatedTo(ByVal e As NavigationEventArgs)
    total1 = e.Parameter as Integer
End Sub

If you want to use NavigationService, you'd need to switch to a Windows Phone Silverlight app...


text:
Q: Not able to replicate CouchDB databases with admin and self signed SSL certificate My local and remote CouchDB SSL server configuration
cert_file   /etc/couchdb/cert/couchdb.pem
key_file    /etc/couchdb/cert/privkey.pem
port        6984
ssl_certificate_max_depth   1
verify_ssl_certificates false

Whenever i create a document in _replicator database of my local couch db like this
{
   "_id": "181361e45e43f9363612b9dec1005a78",
   "_rev": "6-87e9881fd3fecb26e906bb38b8e00a2f",
   "source": "https://adminname:pass@localhostName:6984/DatabaseFromReplicate/",
   "target": "https://adminname:pass@remotehostName:6984/DatabaseToReplicate/",
   "continuous": true,
   "owner": "Admin Name"
}

My document gets revised to
{
  "_id": "181361e45e43f9363612b9dec1005a78",
  "_rev": "7-87e9881fd3fecb26e906bb38b8e00a2f",
  "source": "https://adminname:pass@localhostName:6984/DatabaseFromReplicate/",
  "target": "https://adminname:pass@remotehostName:6984/DatabaseToReplicate/",
  "continuous": true,
  "owner": "Admin Name",
  "_replication_state": "error",
  "_replication_state_time": "2018-05-02T07:23:07-06:00",
  "_replication_state_reason": "timeout",
  "_replication_id": "f236397473a906778fd8edbe63dbe59d"
}

DatabaseFromReplicate is present at local couchDb and DatabaseToReplicate is present at Remote couchDb
My CouchDB log shows:

Retrying HEAD request to https://admin:*****@remotehost:6984/DatabaseToReplicate/ in 0.25 seconds due to error {conn_failed,{error,closed}}

Update:
  If the document created in _replicator database target key value is changed from https to http and port number from 6984 to 5984 then the replication starts in my remote database on https with 6984 port why is that.
My couchdb config for local and remote:
For replicator

connection_timeout           30000
db                          _replicator
http_connections             20
max_replication_retry_count  10
retries_per_request          10
socket_options               [{keepalive, true}, {nodelay, false}]
ssl_certificate_max_depth    3
verify_ssl_certificates      false
worker_batch_size            500
worker_processes             4

For httpd

allow_jsonp                  false
authentication_handlers      {couch_httpd_oauth, oauth_authentication_handler}, {couch_httpd_auth, cookie_authentication_handler}, {couch_httpd_auth, default_authentication_handler}
bind_address                 0.0.0.0
default_handler              {couch_httpd_db, handle_request}
enable_cors                  false
log_max_chunk_size           1000000
port                         5984
secure_rewrites              true
socket_options               [{recbuf, 262144}, {sndbuf, 262144}]
vhost_global_handlers        _utils, _uuids, _session, _oauth, _users

For couch_httpd_auth

allow_persistent_cookies     false
auth_cache_size              50
authentication_db            _users
authentication_redirect      /_utils/session.html
iterations                   10
require_valid_user           true
secret                       ***************************
timeout                      600

For couch_httpd_oauth

use_users_db                 false

For ssl

cert_file                    /etc/couchdb/cert/couchdb.pem
key_file                     /etc/couchdb/cert/privkey.pem
port                         6984
ssl_certificate_max_depth    1
verify_ssl_certificates      false

My _users database just contains the design document.
My couchDb version is 1.6.1

A: In the document you put into /_replicator you have:
"source": "https://adminname:pass@host:6984/DatabaseFromReplicate/",
"target": "https://adminname:pass@host:6984/DatabaseToReplicate/",

For both source and target you're using host, shouldn't it be something like localHost for source and remoteHost for target? I mean, shouldn't they be different?
I'm not sure, maybe that's just a typo in your question.


text:
Q: Alternating columns in a datagrid I have a silverlight datagrid like this
<data:DataGrid x:Name="productsDataGrid">
            <data:DataGrid.Columns>
                <data:DataGridTextColumn Header="Desc" Binding="{Binding SmallDesc}"/>
                <data:DataGridTemplateColumn>
                    <data:DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Image Width="50" Height="50" Source="{Binding SmallPhotoLoc}"></Image>
                        </DataTemplate>
                    </data:DataGridTemplateColumn.CellTemplate>
                </data:DataGridTemplateColumn>
            </data:DataGrid.Columns>
</data:DataGrid>

That will get me this pattern of data like this:
Text    Image
Text    Image
Text    Image
Text    Image
Can anyone please advice on how to get the following pattern:
Text  Image
Image  Text
Text  Image
Image  Text

A: Use a listbox with a DataTemplateSelector
here is an example
http://geekswithblogs.net/tkokke/archive/2009/09/28/datatemplateselector-in-silverlight.aspx


text:
Q: postgresql and django - No unique identifier for this row Two entries on my Django postgresql database are causing me a world of trouble when I go a-querying to create reports. When I try to delete these entries (via phpPgAdmin), I get the error "No unique identifier for this row." There are no duplicate IDs. I've tried updating all the fields. I've tried getting rid of these using the delete button and manual SQL commands. I'm out of ideas. Anyone know hot to give a row a unique identifier so I can get rid of it?
Thanks!

A: Look up the row by the special ctid system column and then delete by that value.  ctid's are unique.

A: The rows you are going to delete may be referenced in another table.
remove them or refer them to something else and, then try to remove your given rows.


text:
Q: number of Lattice paths from origin to diagonal after removing vertices i am stuck with the following problem:
consider the quarter plane $\mathbb{N}_0^2$ with vertices $(i,j)\in\mathbb{N}_0^d$ and edges from each vertex $(i,j)$ to $(i+1,j)$ and $(i,j+1)$, i.e. one "right" edge and one "up" edge.
Now you can turn each vertex off or on. How many different possibilites are there such that
$i\in\{1,2,\ldots,\frac{(N+1)(N+2)}{2}-1\}$ vertices are turned off and there is no path from the origin to the diagonal $(n,k)$ satisfying $n+k=N\in\mathbb{N}$ left?
I figured that with $N=2$ you have $5$ vertices and the number of possibilities turning $i$ vertices off and having no path left is $(0,0,1,6,5,1)$, i.e. turning off none or one there is always a path left, turning two off there is one possibility that no path is left, turning three off there are 6 possibilites and so on.
For $N=3$ there are 9 vertices and I calculated the number as $(0,0,1,10,45,x,76,36,9,1)$ where x is unknown. So it seems that the corresponding coefficients of the pascal triangle are added up, i.e. 1,9,36.
However, I am not experienced in combinatorics and have no clue how to get a general formula. It would help me if you point out some literature dealing with this kind of setting! Thank you