text:
Q: JavaFX with Google Maps - Outstanding resource locks detected: D3D Vram Pool: I'm writing a program that displays Google Map in JavaFX application. Below is a code:
public class Window  {

    private static JFXPanel fxContainer;
    MyBrowser myBrowser;
    double lat;
    double lon;
    WindowGPSServer windowsgpsserver;

    public static void main(String[] args) throws IOException {

        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {

                new Window().init();
            }
        });

   }

   public void init() {
      fxContainer = new JFXPanel();
      windowsgpsserver = new WindowGPSServer(fxContainer);
      windowsgpsserver.setVisible(true);

    // create JavaFX scene

      Platform.runLater(new Runnable() {
      @Override
        public void run() {
        //javaFX operations should go here
            createScene();
        }
      });

  }
   private void createScene() {
      myBrowser = new MyBrowser();
      myBrowser.setCache(false);
      Scene scene = new Scene(myBrowser);

      fxContainer.setScene(scene);
      this.windowsgpsserver.setMyBrowser(myBrowser);
  }
 }

and:
public class MyBrowser extends Pane {
double lat;
double lon;
MyBrowser myBrowser;
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();

    public MyBrowser() {
        Toolkit tk = Toolkit.getDefaultToolkit();
        int xSize = ((int) (tk.getScreenSize().getWidth()));
        int ySize = ((int) tk.getScreenSize().getHeight());
        xSize= new Double(xSize*0.75).intValue();
        ySize= new Double(ySize*0.90).intValue();

        webView.setPrefSize(xSize, ySize);
        final URL urlGoogleMaps = getClass().getResource("demo.html");

        webEngine.load(urlGoogleMaps.toExternalForm());
        webEngine.setOnAlert(new EventHandler<WebEvent<String>>() {
            @Override
            public void handle(WebEvent<String> e) {
                System.out.println(e.toString());
                System.out.println(e.getData());
                System.gc();
            }
        });

        getChildren().add(webView);

    }
    public void ChangeLocation(String latit, String longi) {
        lat = Double.parseDouble(latit);
        lon = Double.parseDouble(longi);
        webEngine.executeScript("" +
                    "window.lat = " + lat + ";" +
                    "window.lon = " + lon + ";" +
                    "document.goToLocation(window.lat, window.lon);"
        );
    }
}

and demo.html file:
    <body style="height: 100%;" onload="mapaStart()">

    <script type="text/javascript">
    var map;
    function mapaStart() {
        //document.map = new google.maps.Map(document.getElementById("mapcanvas"));
        var latlng = new google.maps.LatLng(35.857908, 10.598997);
        var Options = {
            zoom: 15,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("mapcanvas"), Options);
        //var carMarkerImage = new google.maps.MarkerImage('resources/images/car.png');
        var marker = new google.maps.Marker({
            position: new google.maps.LatLng(35.857908, 10.598997),
            map: map,
            draggable: false,
    //icon: carMarkerImage,
            title: "",
            autoPan: true

        });
        var infobulle = new google.maps.InfoWindow({
            content: "Aktualna pozycja"
        });
        google.maps.event.addListener(marker, 'mouseover', function() {
            infobulle.open(map, marker);
        });

        document.goToLocation = function(x, y) {
            alert("goToLocation, x: " + x +", y:" + y);
            var latLng = new google.maps.LatLng(x, y);
            marker.setPosition(latLng);
            map.setCenter(latLng);
        }
    google.maps.event.addListener(map, 'zoom_changed', function() {
            alert("ZOOM");
        var MapOptions = {
                    scrollwheel: false
            };
        map.setOptions(MapOptions)
            setTimeout(aaa, 1000);

    });

    }
    function aaa() {
            var MapOptions = {
                    scrollwheel: true
            };
        map.setOptions(MapOptions)

    }
    </script>

<div id="mapcanvas" style="width: 100%; height: 90%; border: 1px solid black; background: gray;">

</div>
</body>
</html>

fxContainer is added to JPanel and displayed in Swing application.
After starting program everything works just fine. But after zooming in and out a couple of times, program becomes unresponsive (hards to zoom, move map to sides) and following error is displayed:
"Outstanding resource locks detected:
D3D Vram Pool: 268 433 488 used (100,0%), 268 433 488 managed (100,0%), 268 435 456 total
39 total resources being managed
average resource age is 0.1 frames
0 resources at maximum supported age (0,000000)
35 resources marked permanent (89,700000)
2 resources have had mismatched locks (5,100000)
2 resources locked (5,100000)
35 resources contain interesting data (89,700000)
0 resources disappeared (0,000000)"
Can anybody help me to solve this problem?
Thank you
Martin

A: It is a known issue. Could you upvote this https://javafx-jira.kenai.com/browse/RT-36649.
Thanks ! :)


text:
Q: Keyword not supported: 'data source' web.config I cant seem to see where the problem is in my connection string, where you have the " in the string I've even tried adding single quotes as advised on stackoverflow but it still doesn't seem to do anything.
Below is my connection strings, taken out and renamed the actual information for security reasons;
<connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=IP ADDRESS;Initial Catalog=DB NAME;integrated security=False;Persist Security Info=True;User ID=USERID;Password=PASSWORD" providerName="System.Data.SqlClient" />
    <add name="ENTITYNAME" connectionString="metadata=res://*/ModelName.csdl|res://*/ModelName.ssdl|res://*/ModelName.msl;provider=System.Data.SqlClient;provider connection string=IPADDRESS"Data Source=IP ADDRESS;initial catalog=DB NAME;integrated security=False;MultipleActiveResultSets=True;App=EntityFramework;User ID=USERNAME;Password=PASSWORD"" providerName="System.Data.EntityClient" />
</connectionStrings>

A: This part of your connection string appears to be the source of the problem:
...provider connection string=IPADDRESS"Data Source=IP ADDRESS;...

The IPADDRESS"Data should simply be "Data. Your IP ADDRESS value appears twice; one of which (the one before the quote ["""]) is making the connection string invalid.
Your web.config entry should be:
<add name="ENTITYNAME" connectionString="metadata=res://*/ModelName.csdl|res://*/ModelName.ssdl|res://*/ModelName.msl;provider=System.Data.SqlClient;provider connection string="Data Source=IP ADDRESS;initial catalog=DB NAME;integrated security=False;MultipleActiveResultSets=True;App=EntityFramework;User ID=USERNAME;Password=PASSWORD"" providerName="System.Data.EntityClient" />

A: IP ADDRESS looks wrong, normally if using say sqlexpress the connection string would be:
"Data Source=.\SQLEXPRESS ....
for the local version or you may need to replace the "." with the machine name or local ip-address (assuming a development environment)

redpajama_set_name: RedPajamaStackExchange


text:
Q: TYPO3: How to create backend view with Standalone. (Custom Content Elements) How can i create a backend view template but as HTML for custom content elements.
I know i have to use the Standalone class but i do not know how.
System: TYPO3 v9
Mode: Composer Mode
Target: Custom Content element

A: The first steps are described here perfectly: First steps
After that you will have to include some classes
namespace Vendor\YourExtensionName\Hooks\PageLayoutView;

use TYPO3\CMS\Backend\View\PageLayoutViewDrawItemHookInterface;
use TYPO3\CMS\Backend\View\PageLayoutView;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManager;
use TYPO3\CMS\Fluid\View\StandaloneView;
use TYPO3\CMS\Core\Database\ConnectionPool;

Then you have the following:
class MyPreviewRenderer implements PageLayoutViewDrawItemHookInterface
{
    /**
     * Preprocesses the preview rendering of a content element of type "Your CType"
     *
     * @param \TYPO3\CMS\Backend\View\PageLayoutView $parentObject Calling parent object
     * @param bool $drawItem Whether to draw the item using the default functionality
     * @param string $headerContent Header content
     * @param string $itemContent Item content
     * @param array $row Record row of tt_content
     *
     * @return void
     */
    public function preProcess(
        PageLayoutView &$parentObject,
        &$drawItem,
        &$headerContent,
        &$itemContent,
        array &$row
    )
    {

    }

Fetch objects
In the preProcess function we have to first fetch the objects. Do not forget. The &parentObjects is mapped to the tt_content table and the &row holds the information on the current tt_content entry and not the information of your CType which is saved on yourTable table. So we have to create an SQL query to get these information. To do so we have the following:
$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('yourTable');
    $foo = $queryBuilder
     ->select('*')
     ->from('yourTable')
     ->where(
         $queryBuilder->expr()->eq('tt_content', $queryBuilder->createNamedParameter($row['uid'], \PDO::PARAM_INT)),
         $queryBuilder->expr()->eq('hidden', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)),
         $queryBuilder->expr()->eq('deleted', $queryBuilder->createNamedParameter(0, \PDO::PARAM_INT)),
         )
      ->execute()
      ->fetchAll();

What we did here, is to get all the objects that have a relation with the tt_content's uid. Note that the tt_content is a field in the yourTable which holds the uid of the tt_content's table entry.
Define template
Now that we have all the objects in hand, we have to define the path to the backend template.
$objectManager = GeneralUtility::makeInstance(ObjectManager::class);
$standaloneView = $objectManager->get(StandaloneView::class);
$templatePath = GeneralUtility::getFileAbsFileName('EXT:yourExtension/Resources/Private/Templates/Backend/Backend.html');

Now we have to assign the objects to a variable in order to pass them to the fluid template.
$standaloneView->setFormat('html');
$standaloneView->setTemplatePathAndFilename($templatePath);
$standaloneView->assignMultiple([
                'foo' => $foo,
                'cTypeTitle' => $parentObject->CType_labels[$row['CType']],
                ]);

And finally render the template:
$itemContent .= $standaloneView->render();
$drawItem = false;

Additional information:
It is recommended, that you wrap all your code (inside the preProcess function) in the CType that it belongs to. To do so you ll have to wrap it like this:
if ($row['CType'] === 'yourCTypeName')  {
    //...
}


text:
Q: Loading numpy into IronPython I've recently installed Ironpython + tools and having trouble loading external modules (numpy).
this is my test code:
import numpy
numpy.test()

when writing my simple test, intellisense can find numpy, however when it's run from vs2010, I get:
ImportException was unhandled by user code:
No module named numpy

IronPython Console output (shortened):
numpy\__init__.py line 141
numpy\add_newdocs.py line 9
numpy\lib\__init__.py line 4
numpy\lib\type_check.py line 8
numpy\core\__init__.py line 5
ImportError: No module named multiarray

the file multiarray.pyd is present in numpy\core.
I have numpy installed in my python 2.6 folder, (working). In an attempt to use it within ironpython, Following the instructions of numerous sources:
I've added "C:\Python26\Lib\" as a Search path to the project.
I've copied the site-packages, libs, include and DLLs folders from C:\Python26\ to C:\Program Files (x86)\IronPython 2.6 for .NET 4.0\
and I've added:
sys.path.append(r"C:\Python26\Lib")

to the IronPython site.py file.
I've also tried this with both x86 and AMD64 installs, including a complete reinstall of both python versions and ironpython.
Having run completely out of ideas (and the somewhat lackluster google results), I was hoping that someone here may have some suggestions.
Thanks
Rabit

A: I have used the Numpy implementation for IronPython from Enthough. It works so far, but I have not tested it enough.
I have blogged about it here
Numpy for .NET is implemented though wrappers to native calls.
In my blog post I used this tutorial.

A: I don't believe Numpy is supported for IronPython: http://en.wikipedia.org/wiki/IronPython
Unless it's changed since that update. :(
Update: Apparently there are projects underway to get support for some of the CPython stuff which in turn would help support Numpy http://www.resolversystems.com/news/?p=17
Update 2: Apparently you can use numpy with some other open source product: http://ironpython-urls.blogspot.com/2008/08/ironclad-05-released-use-numpy-from.html
Update 3: Official link to Ironclad => http://code.google.com/p/ironclad/
Sorry, I'm not sure if this is of much help :(

A: update 3: wrong twice, ip tools and ip are frustratingly bundled together... which vs2010 doesn't like. Getting closer though.. Currently working with 2.6 for .net4 in ipy console
http://code.google.com/p/ironclad/issues/detail?id=28
^^ explains that frames support is required for ironclad (something not mentioned too clearly)
also that this is potentially not fixed within the new 2.6 for .net 4, going to play with "frames" settings and/or try an older still version of ip


text:
Q: Access actor methods in modules? Probably very simple, but can't figure it out.
How can you use methods from tests/_support/AcceptanceTester.php inside your helper modules?
For example when I'm in tests/_support/Helper/Acceptance.php I cannot reference any of the methods in tests/_support/AcceptanceTester.php
I'm assuming because one is an actor and the other is a module?
I read https://codeception.com/docs/06-ModulesAndHelpers but I still don't understand how this works.
Update
Saw a discussion on github that deals with this situation and it was suggested to use StepObjects
I managed to put both helper methods and actor methods into a StepObject class method, but that still doesn't work. It doesn't allow me to execute both from one place.

A: After a few hours of trying to find an 'elegant' solution to this problem such as using StepObjects injecting dependencies etc. it's much easier to just pass the $I object to whichever helper class method you're using..
It's more verbose, but it works.
If anyone has a better solution, I'll gladly accept it instead.


text:
Q: Get C# DateTime Ticks from html  of type DateTime I was hoping one of you guys might be able to help me. I am a bit stuck and I am very new to javascript.
I need to post a DateTime value (as c# ticks) to a webservice call from a mobile application. The mobile application is written in html/javascript.
Currently I have code that works for a normal Date. It is as follows.
function getTicksFromDatePicker(value) {
    var dateparts = value.split("-");
    //date format(Fullyear,month,date)
    var startDate = new Date(dateparts[0], (dateparts[1] - 1).toString(),
              (dateparts[2]).toString());
    var ret = ((startDate.getTime() * 10000) + 621355968000000000);
    if (isNaN(ret)) {
        ret = 1;
    }
    return ret;
}

This code works perfectly if I use a normal html < input type="date" > and pass its value to my function.
I need to write a function which takes the value from an input of type="datetime" and convert it into c# ticks. I am having trouble doing so. I googled around but I did not find anything on how to. I would greatly appreciate any help you guys can provide me with.

A: var startDate = new Date(dateparts[0], (dateparts[1] - 1).toString(),
              (dateparts[2]).toString());

This above statement returns only the date and where the time 00:00:00
So what you have to  do is to add time to startDate.

A: Ok. So my new solution is as follows. If anyone can provide a better solution, I will be willing to accept it. :)
function toCsharpticks(value)
{
   var dateRet = Date.parse(value);
   dateRet = (dateRet * 10000) + 621355968000000000
   return dateRet
}

There are 621355968000000000 epoch ticks for javascript from Ist Jan 1900 to Ist Jan 1970. And here 10000 are the ticks per milliseconds.
If anyone has a more elegant solution. I am more than happy to accept it instead. :)


text:
Q: Insertion sort C code not working correctly, it only sorts top two elements I am not able to figure out the mistake in this code, this code is error free but it doesn't give correct results.
#include <stdio.h>

int main(int argc, const char *argv[])
{

    int a[10], n, i, j, k, value_to_insert, hole_pos;
    printf("Enter the total no: of elements in an array");
    scanf("%d", &n);

    for (i = 0; i < n; i++) {
        scanf("%d", &a[i]);
    }

    for (j = 1; j <= n; j++) {
        value_to_insert=a[j];
        hole_pos=j;

        while (j > 0 && value_to_insert < a[hole_pos - 1]) {
            a[hole_pos]=a[hole_pos-1];
            hole_pos=hole_pos-1;
        }

        a[hole_pos] = value_to_insert;
    }

    printf("Sorted Array \n");
    for (k = 0; k < n; k++)
        printf("%d\n", a[k]);

    return 0;
}

A: Instead of the loop condition j <= n there should be j < n
Instead of j > 0 there should be hole_pos > 0
If you write code, you should know how and what it does. Why would you write j > 0 in that while loop, when j wasn't even getting decremented in the loop?

A: There is a error in the line
for (j = 1; j <= n; j++)
value_to_insert=a[j];
When the value of j is equal to n you are crossing the boundary of the array.
so it should be
for (j = 1; j < n; j++)value_to_insert=a[j];
Another error is in the line
while (j > 0 && value_to_insert < a[hole_pos - 1])
Here the condition j>0 is always true because j starts from 1.
This line should be written as
while (hole_pos > 0 && value_to_insert < a[hole_pos - 1]).
Each time you decrement hole_pos you should check it before you enter loop. Hope this helps.


text:
Q: spring security 3.1. custom authentication-failure-url with url parameters I googled and tried lot of variants for some hours but without any success.
Please help me to find a solution.
Spring version: Spring 3.1
I have login page. Login page depends on URL parameter:
/login?code=client1

or
/login?code=client2

So client1 and client2 has different login pages.
security.xml:
<sec:form-login login-page="/login" default-target-url="/start" authentication-failure-url="/login"/>

So if user make wrong authentication I show him /login page...
But point is I have to show login page with corresponding code parameter.
What should I do? Have tyou examples please?
Thanks a lot for advance.
UPDATE #1:
I created FailureHandler class:
public class GRSAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler implements AuthenticationFailureHandler {

@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) {

}

}

What should I write inside to get redirect to needed URL?
Please if you can give me more details.
Thanks a lot!

A: You could use the SimpleUrlAuthenticationFailureHandler and implement a different RedirectStrategy which redirect to the configured URL and adds the original query string to the redirected URL.
public class QueryStringPropagateRedirectStrategy extends DefaultRedirectStrategy {

    public void sendRedirect(HttpServletRequest request,
            HttpServletResponse response, String url) throws IOException {
        String urlWithOriginalQueryString = url + "?" + request.getQueryString();
        super.sendRedirect(request, response, urlWithOriginalQueryString );
    }

}

Authentication failure handler configurations

<bean id="authenticationFailureHandler" class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
    <property name="redirectStrategy" ref="queryStringPropagateRedirectStrategy" />
    <property name="defaultFailureUrl" value="/login" />
</bean>

<bean id="queryStringPropagateRedirectStrategy" class="...QueryStringPropagateRedirectStrategy" />


text:
Q: How `sklearn.neighbors.KernelDensity` deal with overflow when high-dimensional datas? And how can I mimic this boundary feature in tensorflow? I'm trying to mimic "gaussian kernel density" computation of sklearn.neighbors.KernelDensity by tensorflow. There is no doubt that the computation will be accelerated by tf.function, if all operations can be converted to graph. Here is my relatively successful codes:
import tensorflow as tf
import numpy as np
from sklearn.neighbors import KernelDensity

tf2pi = tf.constant(2*np.pi,dtype=tf.float64)
def log_gauss_norm(h,d):
    return -0.5*d*tf.math.log(tf2pi)-d*tf.math.log(h)
def gauss(x,d,h):
    y = log_gauss_norm(h,d)-0.5*tf.reduce_sum(x**2,axis=-1)
    return tf.math.exp(y)
@tf.function
def my_kde(x,data_array,bandwidth=2.):
    n_features = tf.cast(float(data_array.shape[-1]),tf.float64)
    bandwidth = tf.cast(bandwidth,tf.float64)
    assert len(x.shape)==2
    x = x[:,tf.newaxis,:]
    y = gauss((x-data_array)/bandwidth,d=n_features,h=bandwidth)
    y = tf.reduce_mean(y,axis=-1)
    return tf.math.log(y)
# succeed
np.random.seed(0)
basic = np.array(np.random.normal(0,1.0,size=[10000,40]),dtype=np.float64)
kde = KernelDensity(kernel='gaussian',bandwidth=2).fit(basic)
y1 = my_kde(basic[0:2],basic)
tf.print(y1) # [-73.09079498452077 -71.975842500329691]
y2 = kde.score_samples(basic[0:2])
print(y2)  # [-73.09079498 -71.9758425 ]
assert all(np.isclose(y1-y2,0.0))

# overflow
np.random.seed(0)
basic = np.array(np.random.normal(0,1.0,size=[10000,800]),dtype=np.float64)
kde = KernelDensity(kernel='gaussian',bandwidth=2).fit(basic)
y1 = my_kde(basic[0:2],basic)
tf.print(y1) # [-inf -inf]
y2 = kde.score_samples(basic[0:2])
print(y2) # [-1298.87891138 -1298.87891138]

The problem is, if deal with high-dimensional datas, such as 800 in above codes, my mimic got -inf while sklearn.neighbors.KernelDensity still work and just goto a meaningful lower bound. I want to mimic the lower bound feature. Even though I try to dig the source code and find the critical code is writed in _kde_single_breadthfirst() function in source codesklearn\neighbors\_binary_tree.pxi, I cannot understand this function. So, I draw here for help.

A: I'm sorry that due to my lack of basic computer knowledge, at the beginning, I didn't understand that when estimating density, why to store data in tree structure. But now, I can classify this problem as how to mimic a kd-tree or ball-tree in tensorflow and then searching, calculating and dealing with boundary.


text:
Q: Get Hidden Parameter Value Using Jquery I have following html.

    <input type="hidden" value="ABC" class="skuhidden">

<input type="button" class="minus" value="-">

Now i want to access value of hidden parameter with class name skuhidden on click of button with classname minus. There are multiple parameter with same class name so i want the closest hidden value to the button within the class minus.
I tried this
$(.minus).siblings('.skuhidden').val()
but it is not working. Please Help me.

A: As skuhidden element is not a sibling of minus element thus your code doesn't work.
You can use .closest() to find td then you can use .find() to locate skuhidden element
$('.minus').closest('td.product-quantity').find('.skuhidden').val();

OR
Find parent div and then use siblings().
$('.minus').closest('.quantity').siblings('.skuhidden').val()

A: // Get all form fields that are hidden
var hidden_fields = $( this ).find( 'input:hidden' );

// Filter those which have a specific type
hidden_fields.attr( 'text' );

try this .i hope  it help you


text:
Q: Failed to create user in Oracle 19 C I'm getting an error during the installation of Oracle 19C. Cannot create a new Windows user.
"Failed to Create  Oracle Home User"
Please help me to resolve this issue.
error


text:
Q: set image resources in imageview in android I am new android developer ,set image from drawable folder.
see belove image:

output:

when image is rectangle ,  set image view rectangle and image is square then set image view square.
how to achieve this type of functionality ?
please help me

A: Answered based on Comments
Try this
Place your images in res/drawable folder and then
 <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/rectangle" />      <-- your image in drawable


text:
Q: Hibernate, bidirectional relation when using MapStruct Sample code to represent my problem.
Let's say there are entity classes like that
public class User {
    ...
    @ManyToOne
    @JoinColumn(name = "users_statuts_id", referencedColumnName = "id", nullable = false)
    private UserStatus status;

}

public class UserStatus {
    ...
    @OneToMany(mappedBy = "status")
    private List<User> users = new LinkedList<>();

}

This works as expected but, problem starts when I want to use MapStruct generated mapper and DTO object. I will get StackOverflowError becouse of Cyclic references User->UserStatus->List< User>-> .....
And take into account that not necessary it will be in pattern A->B->A (User->UserStatus->User)
sometimes it will be User->ClassA->ClassB->...->User
I tired adding Context (CycleAvoidingMappingContext) to mapper as stated in other threads to break cycle but I failed and still get StackOverflowError. Tried too with AfterMappings and Mapping(ignore)  but still not worked and I would like to avoid settings manually nulls to break the cycle.
I wonder if is possible to break cycle similar to @JsonIdentityInfo but on Hibernate level ?
My classes are a bit more complicated and bidirectional relation would help a lot later. Someone have some tips how should I make it done to work properly ?


text:
Q: Pointer to a string and the difference between assignment and dereferencing In the following code:
#include <stdio.h>

int main(void) {
    char* message = "Hello C Programmer!";
    printf("%s", message);

    return 0;
}

I don't fully understand why it wasn't necessary to prepend an '*' to message in the printf call. I was under the assumption that message, since it is a pointer to a char, the first letter in the double quoted string, would display the address of the 'H'.

A: The %s format operator requires its corresponding argument to be a char * pointer. It prints the entire string that begins at that address. A string is a sequence of characters ending with a null byte. That's why this prints the entire message.
If you supply an array as the corresponding argument, it's automatically converted to a pointer to the first character of the array. In general, whenever an array is used as an r-value, it undergoes this conversion.
You don't need to use the * operator because the argument is supposed to be a pointer. If you used *message you would only pass the 'H' character to printf(). You would do this if you were using the %c format instead of %s -- its corresponding argument should be a char.

A: You're right that message is a pointer, of type "pointer to char", or char *.  So if you were trying to print a character (an individual character), you would certainly have needed a *:
printf("first character: %c\n", *message);

In a printf format specifier, %c expects a character, which is what *message gives you.
But you weren't trying to print a single character, you were trying to print the whole string.  And in a printf format specifier, %s expects a pointer to a character, the first of usually several characters to print.  So
printf("entire string: %s\n", message);

is correct.

A: The conversion specifier %s is used to output strings (a sequence of characters terminated with the zero character '\0') pointers to first characters of which are passed to the function printf as an argument.
You can imagine that the function internally executes the following loop
for ( ; *message != '\0'; ++message )
{
    printf( "%c", *message );
}

If you will supply the expression *message then it has type char and the function printf will try to interpret its value that is character 'H' as a value of a pointer. As result the function call will have undefined behavior.
To output the value of the pointer message  you should use the conversion specifier %p like
printf( "%p", message );

Or as an integer value as for example
#include <stdio.h>
#include <inttypes.h>

int main(void)
{
    char *message = "Hello C Programmer!";

    printf( "The value of the pointer message is %" PRIiPTR "\n", ( intptr_t )message );

    return 0;
}

A: In addition, a pointer must be used here.
If you passed a character, it would be passed by value, and printf would lose the original address of the character. That means it would no longer be possible to access the characters that come after the first.
You need to pass a pointer by value to ensure you're retaining the original address of the head of the string.


text:
Q: Regex to match css class name when multiple used I am trying to make a regex to find any element that has a specific class.
For example

For which I came up with this:
\s*class\s*=\s*('|")\s*float\s*('|")\s*

But then of course you can have multiple CSS declared

I am not sure how you would make everything else optional.

A: Maybe \s*class\s*=\s*('|")[\w\s]*\bfloat\b[\w\s]*('|")\s*?
In between the quotes it looks for float with a word boundary on either side, possibly surrounded by further word characters and/or spaces (i.e. other CSS classes).

A: Regex rgx = new Regex("\"float.*\"");
Will match "float anything here but ends with the closing quote"

A: This code will look for the class=" and " as a non matched anchor. Then it will take each of the attribute values found and put each of them into a named capture group called Assignements.
Then linq will extract out the just those named capture(s) and then look for a single "Float" item from the captured group and return true or false.
string data = @"";

string pattern = @"(?:class\s*=\s*\x22)((?<Assignments>[^\s\x22]+)(?:\s?))+(?:\x22)";

var containsFloat =
   Regex.Matches(data, pattern, RegexOptions.Multiline)
      .OfType<Match>()
      .Select(mt => mt.Groups["Assignments"].Captures
                                             .OfType<Capture>()
                                             .Select(c => c.Value))
      .SelectMany(assignments => assignments) // is an IEnumerable<string> = { "float", "align", "cssnames" } at this point
      .Any(assignment => assignment == "float"); // True!


text:
Q: Operator new in C# vs C++ Coming from C++, I am confused as to the use of the new keyword in C#.
I understand that it doesn't work like C++'s new in the sense that you do not have to manually control the lifetime of the object, as C# has garbage collection.
However, when reading over other peoples C# code I notice statements like in code snippet 1. Wouldn't it be far easier to avoid the use of new altogether, like in code snippet 2?
Snippet 1
Foo fooInstance = new Foo();

Snippet 2
Foo fooInstance;

My question is, what are the differences between snippet 1 and snippet 2, and why should I prefer one over the other?

A: Assuming Foo is a reference type like a class, the second code snippet basically just allocates a pointer. The equivalent C++ code would be
Foo* fooInstance;

Your snippets one and two are simply not equivalent.

A: We must discriminate between three cases:

*

*local variables

*(non-static) fields inside structs

*fields inside classes

For local variables, that is variables declared inside a method (or inside a constructor, or property/indexer/event accessor), the two are not equivalent:
class C
{
  void M()
  {
    Foo fooInstance = new Foo();
    // the variable is "definitely assigned" and can be read (copied, passed etc)
    // consider using the 'var' keyword above!
  }
}

class C
{
  void M()
  {
    Foo fooInstance;
    // the variable is not "definitely assigned", you cannot acquire its value
    // it needs to be assigned later (or can be used as 'out' parameter)
  }
}

For instance fields (non-static fields) inside a struct, only one of the "snippets" is allowed:
struct S
{
  Foo fooInstance = new Foo(); // compile-time error! cannot initialize here
}

struct S
{
  Foo fooInstance; // OK, access level is 'private' when nothing is specified
}

For fields inside a class (and static fields of a struct), the situation depends on whether Foo itself is a reference type (class) or a value type (struct or enum). The default value default(Foo) of a reference type is null, the reference that does not refer anything. The default value default(Foo) or a value type is the "instance" of the type where all fields have their default values. For value types (struct and enum), new Foo() (no arguments) and default(Foo) is the same thing. Therefore:
class C
{
  Foo fooInstance = new Foo(); // OK, private
}

class C
{
  Foo fooInstance; // OK, private
  // equivalent to 'Foo fooInstance = null;' if 'Foo' is a reference type (class, interface, delegate, array)
  // equivalent to 'Foo fooInstance = new Foo();' is 'Foo' is a value type (struct, enum)
}

It should be noted that if Foo is a reference type, the expression new Foo() is only allowed if the type actually has a constructor that takes 0 arguments, and if that constructor is accessible.
In (1) we disregarded the silly case where Foo is a struct with no instance fields.

A: The Second Creates Object of type Foo points to null in memeroy.
The First points to new object using default constructor.
If you use the second and say fooInstance.SomeProperty = something. This will throw an exception as fooInstance points to null.

A: Snippet 2 is simply declaring the reference. You haven't instantiated the object yet. If you tried to access the reference in Snippet 2 you would get a compiler error saying the value hasn't been initialized. This is different from C++ where Snippet 2 would declare a constructed object on the stack.

A: If you use
Foo fooInstance;

...in C#, you're just creating a reference variable on stack which points to nothing; no default constructor is called (like it would be in C++).

A: The first snippet
Foo fooInstance = new Foo();

will, as has been said, create a new instance of Foo and place a reference to it in the variable fooInstance.
For the second snippet
 Foo fooInstance;

it depends on where it is placed:
 public class MyClass
 {
     Foo m_foo = null; // member, the "= null" part is redundant and not needed
     Foo m_foo = new Foo(); // member, initialized as part of the constructor call
     void Bar()
     {
          Foo f; // Local variable
          f.MyMethod(); // Compile time error: f is not initialized
          Foo f2=null;
          f2.MyMethod(); // Runtime error: Nullreference exception
     }
 }

Extra caution should be taken if Foo is not declared as class but as struct. Although it is also initialized using new, the instance is actually created on the stack then.


text:
Q: CVS in cmd/gui works only the third time I run a command I'm using CVS in the command line. I'm in my repository folder. When I call a CVS command, I get...
cvs [log aborted]: unrecognized auth response from localhost: -f [pserver
aborted]: /opt/cvs/XXXXXX: no such repository

...2 times. The third time I run the command, it works with no problems. I tried to use a GUI client (CrossVC) and the same problem occurs. I tried inside gVim and Vim using VCSCommand and I'm having the same issues as well.
I've tested with different times between each command, but I still have the same problems.
I'm using a CVS configuration with stunnel. Why am I having problem with this setup? Why every time just the third time that I try to run the command that actually works? Can this be a concurrency bug or something in stunnel?
Each test took different time pauses between each call: sometimes it was 10s, 1 minute, and everytime, just the third time it worked.

A: It was a problem in my stunnel.conf.
There are 3 ports definitions to 3 different machines, and it called two wrong machines before the right one (even if the correct one is above all the other in the file normal sequence).
I still don't have a complete solution to this problem, but the workaround is to comment all servers instead of the one you exactly need.


text:
Q: CORS blocks LinkedIn share API I try to post new content using LinkedIn share API through JavaScript from AngularJS application as given below.
var xml = "<share><comment>" + content + "</comment><visibility>anyone</visibility></share>";

var req = {
   method: 'POST',
   url: 'https://api.linkedin.com/v1/people/~/shares?oauth2_access_token=' + account.token,
   headers: {
       'Content-Type': 'text/plain'
   },
   data: xml
};

$http(req).success(function(data) {
   console.log(data);
   console.log('published to linkedin');
}).error(function() {
   console.log(arguments);
   console.log('failed to publish to linkedin');
});

I can successfully POST this data. However the browser blocks the response from being read because the response doesn't have an 'Access-Control-Allow-Origin' header.

But, I have given the http://localhost:3000 and 'https://localhost:3000' domains in LinkedIn application settings.

And the request/response in Chrome looks like this.

Any thoughts on how to be able to read the response and not let the browser block it?
I think the problem is the missing Access-Control-Allow-Origin header in the LinkedIn API response?

A: Looks like LinkedIn's REST API doesn't support CORS. They suggest to use REST API from the backend and not from browser. JS-SDK must be used from the browser.
https://developer-programs.linkedin.com/forum/cors


text:
Q: What is an 'aliased local shared_ptr' in this example I have a question about an example in the Cpp Core Guidelines. In R.37: Do not pass a pointer or reference obtained from an aliased smart pointer there is the following example:
// global (static or heap), or aliased local ...
shared_ptr<widget> g_p = ...;

void f(widget& w)
{
    g();
    use(w);  // A
}

void g()
{
    g_p = ...; // oops, if this was the last shared_ptr to that widget, destroys the widget
}

And I don't understand what is meant with 'aliased local' in the first comment. Is it connected to aliasing pointer types like
using WidgetPtr = std::shared_ptr<widget>;

or am I completely on the wrong track? I think I understand this example for global shared_ptr, but not for aliased local.

A: std::shared_ptr will automatically destroy the object it points to when all the std::shared_ptr that point to the object are destroyed or reassigned to something else.
This means that if you store a pointer or a reference to an object managed by a std::shared_ptr (this is an aliased pointer), it may suddenly becomes dangling if the std::shared_ptr managing it is destroyed or modified.
You left the most important part of the example out, but in a case like this:
std::shared_ptr<int> shared = std::make_shared<int>(7);
int& ptr = *shared;
shared = nullptr;

When shared is set to nullptr, the objects it pointed to is immediately destroyed, meaning that any pointer to it (like ptr) is now dangling, and reading or writing to it will result in UB.

A: const shared_ptr<widget>& alias = g_p; is an alias for g_p. There is no aliased local shared_ptr in the code, they just mention it for completeness: You can't side-step this issue by creating a reference or pointer to the global variable (more or less just giving it a different name - an alias - in local scope).
It has nothing to do with type aliases like your WidgetPtr (although one could of course use type aliases in creating a local alias to a global shared_ptr, but that's orthogonal).
In other words: If this is bad code:
void bad_code()
{
    // BAD: passing pointer or reference obtained from a nonlocal smart pointer
    //      that could be inadvertently reset somewhere inside f or it callees
    f(*g_p);

    // BAD: same reason, just passing it as a "this" pointer
    g_p->func();
}

Then this is also bad code:
void also_bad_code(bool maybe)
{
    const auto& maybe_g_p_alias = maybe ? g_p : someOtherValue; // Potentially aliases g_p

    f(*maybe_g_p_alias);

    maybe_g_p_alias->func();
}

A: "alias" in this case means "another name for the same object".
f takes a reference widget& w as parameter. So if you call it with f(g_p) then inside f both g_p and w refer to the same object g_p. w is an alias for g_p. The guidelines say that you should not call f(g_p) (g_p being a global object) and you should also not call f(w) (w being an aliased local/a local alias to the global object).


text:
Q: How can I detect when it is safe to upgrade my windows service? I have a windows service that polls a database and will do things depending on the records it finds.
I want to set up Azure Devops to automatically deploy an upgrade to this service.
In order to deploy the upgrade I need to stop the service.
Is there a way that I can tell whether this would interrupt it processing?
In my release pipeline, with a command task, I use
sc stop MyService

[Update]
Here is my simplified code
static class Program
{
    static void Main()
    {
        ServiceBase.Run(new ServiceBase[] { new Hoster() });
    }
}

  public sealed class Hoster : ServiceBase
{
    private IMyEngine _engine;
    private readonly EventHandler<EngineProgressEventArgs> _progressHandler;
    public Hoster()
    {
            _progressHandler = TrapEngineProgress;
    }

    protected override void OnStart(string[] args)
    {
        try
        {
            _engine = MyFactory.Create();
            _engine.Progress += _progressHandler;
            _engine.StartupEngine();
        }
        catch (Exception ex)
        {
            _logger.Error("OnStart failed", ex);
        }
    }

    protected override void OnStop()
    {
        if (_engine == null) return;
        _engine.Dispose();
        _engine.Progress -= _progressHandler;
        _engine = null;
    }

    private void TrapEngineProgress(object sender, EngineProgressEventArgs e)
    {
        switch (e.Type)
        {
            case ProgressType.Changed:
                Trace("Changed: " + e.Filename);
                break;
            case ProgressType.Created:
                Trace("Created: " + e.Filename);
                break;
            case ProgressType.Trace:
                Trace(e.Message);
                break;
            case ProgressType.Error:
                Error(e.Error, e.Message);
                break;
        }
    }
}

A: When you issue the SC STOP command, you are merely making a request for the service to stop itself. When the service receives the request, it can stop immediately or wait until it has finished important tasks — whatever it wants to do. Your service is in control.
To avoid inappropriate interruption, your service's "stop workflow" should look like this:

*

*A request is made to stop the service (via SC STOP, NET STOP, etc.)

*The service's "listener thread" receives the request to stop

*The thread sets a flag that a stop has been requested and sets the service's state to SERVICE_STOP_PENDING

*The "processing thread" periodically checks the flag (at convenient times — likely between jobs)

*If the flag is set, the processing loop exits when convenient

*And since all processing is done, the service status is set to SERVICE_STOPPED and the entire service exits.

With that approach, your service will never be interrupted in a "bad" place.


text:
Q: Spring Boot 1.5.3 transitive dependency not resolved I have updated to Spring Boot 1.5.3 and as part of upgrade I have replaced spring-boot-starter-ws.jar to spring-boot-starter-web-services.jar in my pom.xml. But I am having issue with one of the transitive dependency spring-ws-core.jar. Below is the screenshot

Following is the dependency hierarchy

Don't know why it is not able to find the classes of this dependency. Any suggestions?
<dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
    </dependency>

    <!--
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <scope>test</scope>
    </dependency>
     -->

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>

    <!-- for SpringDispatcher Servlet -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
    </dependency>

    <!-- for HttpInvoker -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
    </dependency>

    <!-- JSP -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
    </dependency>

    <!-- Spring Security -->
    <!--
      <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-web</artifactId>
      </dependency>

      <dependency>
      <groupId>org.springframework.security</groupId>
      <artifactId>spring-security-config</artifactId>
      </dependency>
    -->

    <!-- for Object Relational Mapping (JPA/Hibernate) -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-orm</artifactId>
    </dependency>

    <!-- Hibernate EntityManager for JPA (implementation) -->
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-entitymanager</artifactId>
    </dependency>

    <!-- Database -->
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>

    <dependency>
      <groupId>org.flywaydb</groupId>
      <artifactId>flyway-core</artifactId>
    </dependency>

    <!-- hibernate -->
    <dependency>
      <groupId>org.hibernate.javax.persistence</groupId>
      <artifactId>hibernate-jpa-2.1-api</artifactId>
    </dependency>
    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib</artifactId>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
    </dependency>

    <!-- CXF for REST and Webservices -->
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-frontend-jaxws</artifactId>
      <exclusions>
        <exclusion>
          <groupId>asm</groupId>
          <artifactId>asm</artifactId>
        </exclusion>
      </exclusions>
    </dependency>

    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-frontend-jaxrs</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-rs-client</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-rs-service-description</artifactId>
    </dependency>

    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-transports-http</artifactId>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.jaxrs</groupId>
      <artifactId>jackson-jaxrs-json-provider</artifactId>
    </dependency>

    <!-- Web Sockets -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-websocket</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-messaging</artifactId>
    </dependency>

    <!-- Tests -->
    <dependency>
      <groupId>org.springframework.batch</groupId>
      <artifactId>spring-batch-test</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>io.oasp.java.modules</groupId>
      <artifactId>oasp4j-test</artifactId>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>javax.el</groupId>
      <artifactId>javax.el-api</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-security</artifactId>
    </dependency>

    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
      <version>2.10.4</version>
    </dependency>

    <!--
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-ws</artifactId>
    </dependency>
     -->

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web-services</artifactId>
      <version>1.5.2.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>com.mysema.querydsl</groupId>
      <artifactId>querydsl-apt</artifactId>
      <version>3.4.3</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>com.mysema.querydsl</groupId>
      <artifactId>querydsl-jpa</artifactId>
      <version>3.7.1</version>
    </dependency>

    <dependency>
      <groupId>org.skyscreamer</groupId>
      <artifactId>jsonassert</artifactId>
      <version>1.3.0</version>
    <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <configuration>
          <excludes>
            <exclude>config/application.properties</exclude>
          </excludes>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>

A: If your company policy does not prevent you from defining <parent> then you can add:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.3.RELEASE</version>
</parent>

The effect will be that your POM will have a parent spring-boot-starter-parent which reference the spring-boot-dependencies which defines common dependencies and their associated versions.
So the following will be automatically added for you:
        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-ws-core</artifactId>
            <version>${spring-ws.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>commons-logging</groupId>
                    <artifactId>commons-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

where spring-ws.version is defined as:
<properties>
    ...
    <spring-ws.version>2.4.0.RELEASE</spring-ws.version>
    ...
</properties>

Documentation: is available here.
If you are not allowed to set a <parent> then you can follow these instructions.


text:
Q: How can I remove the last empty space from my string inside array? I am creating a array from a file:
$handle = fopen("inputfile.txt", "r");
if ($handle) {
    while (($str = fgets($handle)) !== false) {
           if (strlen($str) && $str[0] == '#') {
                    $pdate = substr($str, 1);
                    $date = rtrim($pdate);
                    $formatted = DateTime::createFromFormat('* M d H:i:s T Y',$date);
                }
                rtrim ($str, "\n");
                $exp = explode ('=', $str);
                if(count($exp) == 2){
                    $exp2 = explode('.', $exp[0]);
                    if( count($exp2) == 2 ) {
                        if($exp2[1] == "dateTime"){
                            $s = str_replace("\\","",$exp[1]);
                            $d = strtotime($s);
                            $dateTime = date('Y-m-d H:i:s', $d);
                            $properties [$exp2[0]][$exp2[1]] = $dateTime;
                        } else {
                            $properties [$exp2[0]][$exp2[1]] = $exp[1];
                        }
                    } else {
                        $properties [$exp[0]] = $exp[1];
                    }
                }
    }
    var_dump($properties);
    fclose($handle);
} else {
    // error opening the file.
}

var_dump($properties);

But in my result array there are always white spaces at the end of the values and I cannot get rid of them:
array(5) {
  ["folder"]=>
  array(5) {
    ["dateTime"]=>
    string(19) "2016-10-12 19:46:25"
    ["one"]=>
    string(47) "abc def
"
    ["two"]=>
    string(33) "ghi jk
"
    ["three"]=>
    string(150) "lm no
"
    ["four"]=>
    string(8) "pqr st
"
  }
}

A: You're missing to assign the result of rtrim ($str, "\n");. So your variable $str is not changed.
$str = rtrim($str, "\n");

Or, by default, to remove all whitespace characters (" \t\n\r\0\x0B"):
$str = rtrim($str);

A: You can Use the rtrim() function to remove white spaces at beginning and end of your strings, but it is used one by one.
You can also reffere to the response to this post : How can I trim all strings in an Array?
Tha says that you can use array_map and trim as this :
$result = array_map('rtrim', $source_array);


text:
Q: setField to a repeating group In quickfix (C++ lib), we have:
class Group : public FieldMap

I call setField() to add a member to a repeating group (for example Parties) and in theory the call could throw exception of RepeatedTag. How to interpret this exception? Or for a Group object, it will never throw RepeatedTag?
The document (http://www.quickfixengine.org/quickfix/doc/html/repeating_groups.html) seems not worrying about this situation neither.

A: It won't throw a RepeatedTagException.  (Where did you get that idea?)
RepeatedTagException is only thrown when the engine is reading an incoming message.


text:
Q: Apply pre-commit only on the local repository? Using Git, I have a pre-commit hook that I filled with mvn clean install.
I aim to test if this command executes without error before pushing to the remote repo.
The problem is that this command applies to my current directory, not to the local git repository (that consists of only the added files). So, sometimes I got an error because on some files that I did not add, while there is no error without these files.
So my question is how can I apply a pre-commit of mvn clean install that applies only on the added files to the local repo ?

A: Example of pre-commit hook shell script: https://gist.github.com/dahjelle/8ddedf0aebd488208a9a7c829f19b9e8
Notice line 3:
$(git diff --cached --name-only | grep -E '\.(js|jsx)$')

This grabs the files of a git commit ... piped to filter only .js or .jsx files. You can modify this script and remove the piping.
On line 5: modify the node_modules/... line with your mvn clean install.
Modify the script as needed.
EDIT:
Here's an example that might match your use case more clearly: https://eing.github.io/technology/2016/01/28/Git-Pre-Commit-Hooks-Part1/
{ echo "
git stash -q --keep-index
# Using "mvn test" to run all unit tests and run plugins to assert
#   * code coverage threshold >= 85% (using surefire, enforcer plugins)
#   * FindBugs at low threshold errors (using findbugs-maven-plugin)
#   * Checkstyle has 0 errors (using maven-checkstyle-plugin)
mvn clean install test
RESULTS=\$?
# Perform checks
git stash pop -q
if [ \$RESULTS -ne 0 ]; then
  echo Error: Commit criteria not met with one or more of the following issues,
  echo 1. Failure\(s\) in unit tests
  echo 2. Failure to meet 85% code coverage
  echo 3. Failure to meet low FindBugs threshold
  echo 4. Failure to meet 0 Checkstyle errors
  exit 1
fi
# You shall commit
exit 0"
} > pre-commit.sh
pushd .git/hooks
ln -s ../../pre-commit.sh pre-commit
chmod u+x pre-commit
popd


text:
Q: How to dynamically compile Java classes in Google App Engine In answers to this question, I learned that it is not possible to invoke the Java Compiler in javax.tools from a GAE app.

*

*Does this limitation still apply?

*If so, what are my options for compiling Java source code into loadable class files "on the fly"?

A: No, javax.tools is still not on the Appengine's JRE Class Whitelist.
The options you have are:

*

*Compile somewhere else and than transfer and load .class files on appengine.

*Try using one of embeddable Java compilers: Janino, JDT.

*If you can live without Java, than you might try using BeanShell for Appengine.


text:
Q: data not storing in database django My first issue is data is not going in database.it is not showing any error but not storing as well.
and my second issue is that i am pre-populating the form field with query set in a drop-down but it is showing me the id(primary key) and i want show some other field.how can i do this?
my view
def payment(request):
    #form = jobpostForm_first()
    #country_list = Country.objects.all()
    if request.POST:
        form = jobpostForm_detail(request.POST)

        if form.is_valid():
            if '_Submit' in request.POST:
              form.save()
              return HttpResponseRedirect('/thanks/')
    else:
        form = jobpostForm_detail()
        #form.fields['country'].queryset = Country.objects.all()

    c = {}
    c.update(csrf(request))

    return render_to_response('portal/display.html',{
        'form':form
    },context_instance=RequestContext(request))

my modelform:
class jobpostForm_detail(ModelForm):
    class Meta:

        model = payment_detail
        fields = ('payment_type','country')

    def __init__(self, *args, **kwargs):
        super(jobpostForm_detail, self).__init__(*args, **kwargs)

        self.fields['country'].queryset = Country.objects.all()
        self.fields['payment_type'].queryset = Payment_types.objects.all()

        self.helper = FormHelper()
        self.helper.form_class = 'horizontal-form'
        self.helper.form_id = 'id-jobpostform'
        self.helper.form_class = 'blueForms'
        self.helper.form_method = 'post'

        self.helper.add_input(Submit('submit_addcontent', 'Pay'))

        super(jobpostForm_detail, self).__init__(*args, **kwargs)

My template:
<form method="post" action="/portal/next/post/" class="blueForms" id="id-jobpostform">

    {% csrf_token %}

    {% crispy form %}

    </form>

A: Why are you checking for "_Submit" in your view?
I suggest you read how to use a form in a view, especially the comments:
...
def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
...

In your case, you just need to call form.save() after form.is_valid()
Question for you: can you please explain this bit of code in your form class? typo, I suppose?
widgets = {

        }),

}


text:
Q: On hover another layer move if that layer mose hover then hover stop Hover is kind of funny as in this code a new layer .hide which get appear when hover as it transition it response differently  I try diffent thing like hide:hover +img{} and other if anybody know about it please help is there is any hack in this issue.
Thing is there is two layer first layer should fade Opacity and another layer transition with animation that is only word. Which is .hide Class that but if then i hover on .hide class which transition when hover cause issue.,
Right Now i using with z index different But then Text hide behind the back of image.

.catalog {
  overflow:hidden;
  width:300px;
  height:300px;
  margin:2px;
}

.catalog img:hover{

  transition: transform 500ms , opacity 500ms 0ms ease-in-out;
  transform: scale(1.3);
  opacity: 0.3;
}
.hide{
  z-index:0;
  display:block;
  font-size: 10px;
  position:relative;
  top:-50px;
  transition: font-size 500ms , top 500ms 0ms ease-in-out;
  width:100%;
  background: #6c6c934d;
background-size: 300px 300px;
color: #13436c;
}
.catalog img:hover + .hide {
  font-size:50px;
  top:-300px;
  padding-bottom:50px;
}

     Refrigerator

A: This issue happens because you add the styles on img:hover, simply, by default, these events are triggered for the selector itself or one of its children, in this case, the image and the div.hide are siblings, to avoid this behavior you can update your code to add these styles on catalog:hover, which is a parent of both, so whenever you hover on of them, you will be hovering the parent too

.catalog {
  overflow:hidden;
  width:300px;
  height:300px;
  margin:2px;
}

.catalog:hover img{

  transition: transform 500ms , opacity 500ms 0ms ease-in-out;
  transform: scale(1.3);
  opacity: 0.3;
}
.hide{
  z-index:0;
  display:block;
  font-size: 10px;
  position:relative;
  top:-50px;
  transition: font-size 500ms , top 500ms 0ms ease-in-out;
  width:100%;
  background: #6c6c934d;
background-size: 300px 300px;
color: #13436c;
}
.catalog:hover .hide {
  font-size:50px;
  top:-300px;
  padding-bottom:50px;
}

     Refrigerator


text:
Q: cannot access php json decoded multi dimensional array values curl when i execute the below code to access koinex ticker api , I am getting an array but how can i display only certain values :
echo $response[0][0][1];

echo $response['prices']['BTC'][0];

code :
<?php

$getCurrency = "inr";
$displayArrayOutput = true;

// Get cURL resource
$curl = curl_init();
// Set some options - we are passing in a useragent too here
curl_setopt_array($curl, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'https://koinex.in/api/ticker',
    CURLOPT_USERAGENT => 'Something here'
));
// Send the request & save response to $resp
$response = curl_exec($curl);
// Close request to clear up some resources
$err = curl_error($curl);
curl_close($curl);

if ($err) {
} else {
    if($displayArrayOutput){
        $response = json_decode($response, true);
        print_r($response);

    }
    else{
        header("Content-type:application/json");
        echo 'touine';
    }
}

echo $response[0][0][1];
echo $response['prices']['BTC'][0];

?>

sorry a little new to php , open to any other kind of approach for decoding json


text:
Q: .npmrc failed to replace env in config Me and my colleagues have a problem with .npmrc
Most of us are on Mac OSx and this works
@REGISTRY_NANME:registry=https://gitlab.com/api/v4/packages/npm/ //gitlab.com/api/v4/packages/npm/:_authToken=${NPM_TOKEN}
But for me it don't work, but without {} like below, it works for me
@REGISTRY_NANME:registry=https://gitlab.com/api/v4/packages/npm/ //gitlab.com/api/v4/packages/npm/:_authToken=$NPM_TOKEN
What could cause that? How can I have the same behaviour than my colleagues?
I tried with zsh and .zhsrc, with bash and .bash_profile too.
I tried with npm and yarn
Using quoted and unquoted export NPM_TOKEN="<token>"
Tried to remove the {} in my .npmrc
Tried with a .yarnrc file
Thank you for your help!


text:
Q: How do I load a COM instance in C# I have the COM idl definition file, and i have a VB project that demonstrate how to communicate thru an application thru COM.
unfortunately, i cannot straight up port the VB code to C#.
The COM is written in C++ and is reference by its program id
How can I instantiate the COM from C# and call functions from there?
here is the vb code
  Dim DrCephPatient As Object
  SampleCom = CreateObject("Sample.SampleCOM")

  SampleCom.Attribute1= "Hello"
  SampleCom.Method1(1)

Also, since i have the IDL definition, i have the UUID i can use to access.
Any resources I need to read to make this work?

A: You just need to add a COM reference to your C# project.

The COM tab of the Add Reference dialog window lists all COM components that are available for referencing. If you want to add a reference to a registered COM DLL that contains an internal manifest, unregister the DLL first. Otherwise, Visual Studio adds the assembly reference as an ActiveX control instead of as a native DLL.
If a project type doesn't support COM, the tab doesn't appear in the Reference Manager dialog box. Read more about that in the How to: Add or remove references by using the Reference Manager article.
After adding a COM reference you can use your component as a regular .net classes (using the interop library generated automatically behind the scene).

A: Using C#, you can quasi get it to perform like VB script code by using Type.GetTypeFromProgID(),  the Activator class, and using the dynamic type. I wouldn't necessarily prefer this, though. It's better to add the COM reference to your project. In my example I'm using, Word which runs out of process (is an .exe) so it will work with 32-bit or 64-bit versions of the runtime. However, for an in process server (.dll), the bitness of your code and the server need to match (either both 32- or 64-bit). However, for a quick test, this sometimes will do the job.
using System;

class Test {
   public static void Main(string[] args) {

      Type t = Type.GetTypeFromProgID("Word.Application");

      dynamic word = Activator.CreateInstance(t);

      Console.WriteLine("Word title:" + word.Name);

      word.Quit(); // otherwise hanging reference ... is Word API specific
   }
}

A: You can use the SerialPort Class
https://learn.microsoft.com/en-us/dotnet/api/system.io.ports.serialport?view=dotnet-plat-ext-5.0
Basically works with Open, Write/Read and Close functions but it's in C#, I guess it's not exactly what you look for
Also there is this list of articles about VB that could help you
https://learn.microsoft.com/en-us/dotnet/visual-basic/developing-apps/programming/computer-resources/accessing-the-computer-s-ports


text:
Q: Please Suggest a good blog to learn Angular-2 Lifecylce I am learning angular2 and have been trying to get understand the Angular2 Lifecycle. Can someone please suggest a good blog post?

A: I will suggest you to read instructions before asking opinion based questions.
For your answer , You can follow below links to learn about angular2.
Official Site For angular2
EggHead Tutorials for angular2
Sitepoint for Angular2
Thoughtram Blog for angular2


text:
Q: Jquery Carousel - like plugin / Customization I'm on a project that will have a slider to show some content, like a carousel.
I remember some time ago (like 2 years back, I think) there was a plugin just like described in the image below. And it made developers fellows life much nicer:

That is: a carousel with a limited number of items showing on the viewport and the centered item was put in evidence with a class or something.
I've searched for hours and coundn't find that plugin anymore. I wonder if someone can remember its name or point me to a similar solution: It needs to be like the image (aligned to the top and mark the centered/active item with a class, so I can style it as needed.
The only one I could find is Sky jQuery Touch Carousel http://www.skyplugins.com/sky-jquery-touch-carousel/default_skin.html. It is pretty good, but it is not quite what I'm looking for, and it is not free.
Any help would be great. Thanks in advance!
EDIT --
So, my question was market as off topic, even though there is lots of questions with similar subjects here in the community and none of them was treated as such, but whatever... I decided to change the subject a little. I will maintain the original text, so the first answers make sense.
I'm trying to edit jCarousel plugin, to supply this funcionality I need. I have binded a click event to the li element, to insert a class on it and successfully styled it.
Now, everything I have to do is to find a way to center the selected li on click, in order to make the element just like the image above.
I have no much experience with the slider logic, so any help would be welcome.

A: This page has links to a lot of good plugins.  I had a quick look through.  I'm not sure exactly what you are after but quite a few of them seemed liked the right sort of thing
It could be the case that the plugin you used to use no longer exists or is no longer supported, especially as it was free.


text:
Q: How to add row in datagridview from another form? i have 2 forms. form1 contains the datagridview. the second(form2) form contains textboxs. when i click Ok button in form2, the values should get added in datagridview as new row. This is the code i am trying to use to pass the data,but its neither showing error nor result.
Form2
private void btnOk_Click(object sender, EventArgs e)
{
  form1.datagridview.Rows.Add("firstname", "lastname", "Success", "Userid", DateTime.Now.ToString());
}

A: put this on Form1
  private void button1_Click(object sender, EventArgs e) {
        Form2 f2 = new Form2(this);
        f2.Show();
  }

put this on Form2
    private Form1 form1;

    public Form2(Form1 form1) {
        InitializeComponent();
        this.form1 = form1;
    }

    private void button1_Click(object sender, EventArgs e) {
        form1.dataGridView1.Columns.Add("FirstName", "First Name");
        form1.dataGridView1.Columns.Add("LastName", "Last Name");
        form1.dataGridView1.Columns.Add("UserId", "Userid");
        form1.dataGridView1.Columns.Add("Success", "Success");

        object[] row = new object[] {"1","Product 1","1000",DateTime.Now.ToString()};

        form1.dataGridView1.Rows.Add(row);
    }

that should do it
and datagridview Modifier should be public

A: You need to add a reference to your form1 somewhere in form2 a somewhat easy way of doing this is to add this to form2 on top
public Form1 form1 {get;set;}

And then when you create your form2 with i suppose something like this from form1
Form2 form2 = new Form2();
form2.ShowDialog();

You add this right after ShowDialog() or before
form2.form1 = this;

Then you can use form1 as a variable inside of form2 to reference to form1

A: This is easiest way I can suggest you:

*

*Create public method on Form 2 to add rows to data grid view

*Create instance of Form 2 on button click and call method of Form 2

Form 1
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var firstName = txtFirstName.Text;
        var lastName = txtLastName.Text;
        var success = txtSuccess.Text;
        var userId = txtUserId.Text;

        var frm2 = new Form2();
        frm2.AddGridViewRows(firstName, lastName, success, userId);
    }

Form 2
    public Form2()
    {
        InitializeComponent();
    }

    public void AddGridViewRows(string firstName, string lastName, string success, string userId)
    {
        // Add rows to grid view.
        dataGridView1.Rows.Add(firstName, lastName, success, userId);

        // Refresh the grid
        dataGridView1.Update();
    }


text:
Q: SetEnv in htaccess applying to internal folder I am working on a website having Apache as webserver, using PHP. There are an folder in public_html by the name of "teacher". The .htaccess file in public_html file has this line
SetEnvIf Request_URI "\.pdf$" requested_pdf=pdf
Header add Content-Disposition "attachment" env=requested_pdf

now as expected these are also applying in "teacher" folder which i don't want to do. I tried by adding an blank .htaccess file in "teacher" folder so that it pick this htaccess, however it is not working.
I tried to search but didn't fine anything relevant as per my knowledge. So can anyone help me out so that these set headers does not apply to "teacher" folder.
Thanks in Advance.

A: Place this value in teacher/.htaccess:
Header unset Content-Disposition


text:
Q: How to disable dropdown button in WPF RibbonSplitButton control I am using WPF Ribbon 4. I have a RibbonSplitButton control with dropdown menu of menu items.
When I set IsEnabled property of RibbonSplitButton to false only top button becomes disabled, not the button which opens dropdown menu.
Thanks in advance.

A: I solved this problem by creating my own split button, inheriting from RibbonSplitButton and adding an dependency property that I can bind to for enabling or disabling the split button alone.
public class MyRibbonSplitButton : RibbonSplitButton
{
    public MyRibbonSplitButton()
        : base()
    {
    }

    /// <summary>
    /// Gets or sets a value indicating whether the toggle button is enabled.
    /// </summary>
    /// <value><c>true</c> if the toggle button should be  enabled; otherwise, <c>false</c>.</value>
    public bool IsToggleButtonEnabled
    {
        get { return (bool)GetValue(IsToggleButtonEnabledProperty); }
        set { SetValue(IsToggleButtonEnabledProperty, value); }
    }

    /// <summary>
    /// Identifies the <see cref="IsToggleButtonEnabled"/> dependency property
    /// </summary>
    public static readonly DependencyProperty IsToggleButtonEnabledProperty =
        DependencyProperty.Register(
            "IsToggleButtonEnabled",
            typeof(bool),
            typeof(MyRibbonSplitButton),
            new UIPropertyMetadata(true, new PropertyChangedCallback(MyRibbonSplitButton.ToggleButton_OnIsEnabledChanged)));

    /// <summary>
    /// Handles the PropertyChanged event for the IsToggleButtonEnabledProperty dependency property
    /// </summary>
    private static void ToggleButton_OnIsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        var button = sender as MyRibbonSplitButton;

        var toggleButton = button.GetTemplateChild("PART_ToggleButton") as RibbonToggleButton;
        toggleButton.IsEnabled = (bool)e.NewValue;
    }
}

and in XAML:
   <local:MyRibbonSplitButton Label="New" Command="{Binding SomeCommand}"
                          LargeImageSource="Images/Large/New.png"
                          ItemsSource="{Binding Templates}"
                          IsToggleButtonEnabled="{Binding HasTemplates}"/>

A: You can simply add a DropDownOpened="RibbonMenuButton_OnDropDownOpened" to the WPF and then
    private void RibbonMenuButton_OnDropDownOpened(object sender, EventArgs e)
    {
        var rsb = sender as RibbonSplitButton;
        if (rsb == null) return;
        if (DataContext is GameCardViewModel vm)
        {
            rsb.IsDropDownOpen = vm.EasyInputMode;
        }
    }


text:
Q: Replacing whitespace in all column names in spark Dataframe I have spark dataframe with whitespaces in some of column names, which has to be replaced with underscore.
I know a single column can be renamed using withColumnRenamed() in sparkSQL, but to rename 'n' number of columns, this function has to chained 'n' times (to my knowledge).
To automate this, i have tried:
val old_names = df.columns()        // contains array of old column names

val new_names = old_names.map { x =>
   if(x.contains(" ") == true)
      x.replaceAll("\\s","_")
   else x
}                    // array of new column names with removed whitespace.

Now, how to replace df's header with new_names

A: As best practice, you should prefer expressions and immutability.
You should use val and not var as much as possible.
Thus, it's preferable to use the foldLeft operator, in this case :
val newDf = df.columns
              .foldLeft(df)((curr, n) => curr.withColumnRenamed(n, n.replaceAll("\\s", "_")))

A:   var newDf = df
  for(col <- df.columns){
    newDf = newDf.withColumnRenamed(col,col.replaceAll("\\s", "_"))
  }

You can encapsulate it in some method so it won't be too much pollution.

A: In Python, this can be done by the following code:
# Importing sql types
from pyspark.sql.types import StringType, StructType, StructField
from pyspark.sql.functions import col

# Building a simple dataframe:
schema = StructType([
             StructField("id name", StringType(), True),
             StructField("cities venezuela", StringType(), True)
         ])

column1 = ['A', 'A', 'B', 'B', 'C', 'B']
column2 = ['Maracaibo', 'Valencia', 'Caracas', 'Barcelona', 'Barquisimeto', 'Merida']

# Dataframe:
df = sqlContext.createDataFrame(list(zip(column1, column2)), schema=schema)
df.show()

exprs = [col(column).alias(column.replace(' ', '_')) for column in df.columns]
df.select(*exprs).show()

A: You can do the exact same thing in python:
raw_data1 = raw_data
for col in raw_data.columns:
  raw_data1 = raw_data1.withColumnRenamed(col,col.replace(" ", "_"))

A: In Scala, here is another way achieving same  -
    import org.apache.spark.sql.types._

    val df_with_newColumns = spark.createDataFrame(df.rdd,
StructType(df.schema.map(s => StructField(s.name.replaceAll(" ", ""),
s.dataType, s.nullable))))

Hope this helps !!

A: Here is the utility we are using.
 def columnsStandardise(df: DataFrame): DataFrame = {
    val dfcolumnsStandardise= df.toDF(df.columns map (_.toLowerCase().trim().replaceAll(" ","_")): _*)
    (dfcolumnsStandardise)
  }

A: I wanted to add also this solution
import re
for each in df.schema.names:
    df = df.withColumnRenamed(each, re.sub(r'\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*','',each.replace(' ', '')))

A: I have being using the answer given by @kanielc to trim the leading and trailing spaces in the column headers and that works great when the number of columns are less. I had to load one csv file which had around 600 columns and execution of the code took a sufficient amount of time and was not meeting our expectations.
Earlier Code:
val finalSourceTable = intermediateSourceTable.columns
.foldLeft(intermediateSourceTable)((curr, n) => curr.withColumnRenamed(n, n.trim))

Changed Code:
val finalSourceTable = intermediateSourceTable
.toDF(intermediateSourceTable.columns map (_.trim()): _*)

The changed code worked like a charm and it was also fast compared to the earlier code.
Also we are maintaining the immutability by not using var variables.


text: Q: Highlight Button in Webpage If Login User Has not Clicked On Looking for a way to highlight buttons that the User has not visited in case of changes the content of the views that are redirected when these buttons are clicked. The solution should be in the ASP.net MVC CSS framework.


text:
Q: Changing selection Manytomany field in Django I have a ManyToManyField named alphabet, which contains fields A, B, C and D - whether selected or unselected. How would it be possible to change queries that have selected letter 'A' into 'B'?
class Alphabet(models.Model):
    id = models.AutoField(primary_key=True)
    letter = models.CharField(max_length=100, null=True, blank=True)

    def __str__(self):
        return self.letter

class Chapter(models.Model):
    letter = models.ManyToManyField(Alphabet, blank=True)

class Section(models.Model):
    def somefunction:
        jobs = Chapter.objects.filter(letter__letter='A')
        for i in jobs:
            #change those selected with A to B

A: You are looking to change the Chapter objects with letter A to B for example? Try using update.
jobs = Chapter.objects.filter(letter__letter='A')
jobs.update(letter=Alphabet.objects.get(letter='B'))


text:
Q: For $p$ prime, $p = a^2 + b^2$, why must $a$ or $b$ be a square? If p prime and if $p = 1 \pmod{4}$, then $p = a^2 + b^2$; why must $a$ or $b$ be a square mod $p$?

A: One of $a$ or $b$ is odd.  Assume it is $a$.
Then $$\left(\frac{a}{p}\right)=(-1)^{\frac{p-1}2\frac{a-1}2}\left(\frac{p}{a}\right) =\left(\frac{p}{a}\right) = \left(\frac{b^2}a\right) = 1$$
Where we are using general Jacobi symbols, rather than Legendre symbols.

A: This answer adds a small amount of detail to the one by @Thomas Andrews, but uses exactly the same idea.
Suppose that $p=a^2+b^2$.  Let $a$ have the prime power factorization
$$a=p_1^{a_1}p_2^{a_2}\cdots p_k^{a_k}.$$
Suppose first that $a$ is odd.
Then $p\equiv b^2 \pmod{p_i}$, so $p$ is a quadratic residue modulo $p_i$ for every $i$.  It follows that the Legendre symbols $(p/p_i)$ are all equal to $1$, and therefore by Reciprocity so are the Legendre symbols $(p_i/p)$. Thus $a$, and indeed every factor of $a$, is a quadratic residue of $p$.
Suppose next that $a$ is even.  By the same argument as the one above, every odd factor of $a$ is a quadratic residue of $p$.  If $p$ is of the shape $8t+1$, then $(2/p)=1$, and therefore $a$, and every factor of $a$, is a quadratic residue of $p$. Finally, suppose that $p$ is of the shape $8t+5$. Then $a \equiv 2\pmod{4}$. Since $2$ is not a quadratic residue of $p$, it follows that $a$ is not a quadratic residue of $p$.


text:
Q: Single photon polarization measurement setup I am studying experiments testing local realism through the violation of Bell's inequality. In particular, I am trying to understand the setup of the so called loophole-free experiment carried out in 2015 (Ref: M. Giustina et al., Phys. Rev. Lett. 115, 250401 (2015)).
I'll go directly to my problem. Two entangled photons are emitted from a source and are delivered to two measuring stations, where a measurement of polarization takes place. Studying the inequality and the experiment, I imagined the measurement as something like this:

The photon arrives at the polarizer and it can pass, or not, with a probability deending on its polarization state and predictable with quantum mechanics. The detector is there only to count the times the photon passes the polarizer. This is clearly an idealization and must be translated in a true experimental setup.
Now, in the cited article, the proposed setup looks like this:

The photon first meets an half-wave plate, so its polarization is rotated of 90°. Then, an electro optical modulator which is used to choose the direction of polarization measurement. Finally, a polarized beam splitter, in which one of the two output channels is closed, while in the other a detector waits.
What I think to have understood until now is this: in a setup like the first picture, the polarizer's orientation is changed when choosing a specific measurement, while the approaching photon polarization is fixed. In the second picture, instead, the polarization of the photon is modified through the EOM, while the PBS is clearly fixed. The two methods should give the same results.
Now my questions: did I understand the functioning of the setup correctly? And if it is so, what is the function of the HWP (Half-wave plate)?
Furthermore, there is one more complication. In the other measuring station, the other entangled photon faces the same setup, also its polarization is changed, but of a different angle. How can entanglement be preserved in this way?

A: You've understood the configuration correctly. Both setups are basically optically equivalent, with two core changes:

*

*Using a polarizing beam splitter instead of a linear polarizer allows you to do a projective measurement on both polarization outcomes instead of discarding one of the two.

*More importantly, the second configuration allows you to choose which angle you want to measure by re-tuning the voltages on the electro-optical modulator, instead of by mechanically moving a polarizer. In loophole-free Bell-inequality measurements, time is of the essence (as you need to pull off the entire protocol in spacelike-separated events) and mechanical changes are just too slow. Instead, you use the HWP-plus-EOM combination, which is much faster.

As for this,

In the other measuring station, the other entangled photon faces the same setup, also its polarization is changed, but of a different angle. How can entanglement be preserved in this way?

that's not a a concern. Local unitaries do not destroy entanglement, so long as they are strictly controlled and you know exactly what their effect is. They will change which precise entangled state you have, but they will not reduce the amount of entanglement.


text:
Q: Adding custom attributes to the SiteMap of ASP.NET MVC I am using built in asp.net sitemap in asp.net mvc with the following schema

http://schemas.microsoft.com/AspNet/SiteMap-File-1.0

I have the following attributes, resourcekey, title & description. I would like to add few more attributes to the sitemapNode, kindly let me know if it is possible to add new attribute in sitemap file and then read it via the sitemap class.

A: The SiteMap schema supports custom attributes and they can be accessed via the indexer property of the SiteMapNode class.
For example if the following node was defined in the Web.sitemap file with custom tooltip attribute:
<siteMapNode url="~/Default.aspx" title="Home" tooltip="My Home Page" />

It can then be accessed via the SiteMapNode indexer e.g.
string tooltip = siteMapNodeInstance["tooltip"];

More information on customising SiteMaps is available here


text:
Q: Could not receive AJAX POST data in PHP I'm trying to post a variable as an object to my PHP file, but it doesn't receive any data. I tried window.alert(u.un) to test whether the data is being passed from AJAX call, and it works fine and there are no errors in my console. But still I'm not getting data in PHP file, there are no errors either.
This is my AJAX function
function getfulldetails(n)
{
var u={un:n};  window.alert(u.un);
var locationto= "getfull.php";
$.ajax({
   type: "POST",
   url: locationto,
   data: u,
   processData: false,
   contentType: false,
   success: function(response)
      {
        window.alert(response);
      }
   });
   return false;
}

This is my PHP file
<?php
session_start();
if($_SERVER['REQUEST_METHOD']==='POST')
{
    if(isset($_REQUEST["un"]))
     {
        function validate_data($data)
        {
             require 'connectcred.php';
             $data = trim($data);
             $data = stripslashes($data);
             $data = strip_tags($data);
             $data = htmlspecialchars($data);
             $data = mysqli_real_escape_string($conn,$data);
             return $data;
        }
        $u=validate_data($_REQUEST["un"]);
        echo $u;
     }
     else
     {
         echo "something's wrong";
     }
}
?>

I'm getting result only from the else part.
I've used AJAX using the code below many times to get data from Form and it worked like a charm, but its not working when I assign an object myself.

A: Don't set Content-Type / contentType to false. You also need to send an actual query string.
For now, this should fix it:
$.post(locationto, u, (response) => {
    window.alert(response);
});

Alternatively, use data: "un=" + n
Also, in your PHP, use only $_POST.


text:
Q: inheritance of Has-a relation I was reading about Has-a and Is-a relation in here: What do "has-a" and "is-a" mean? [duplicate]

. What I understand is that my data members of the class follow the Has-a relation. Let's say that I inherit data members from the Base class. Are they still going to follow Has-a relation?
in this example: Car is-a vehicle. Is it still going to have a steering wheel?
class SteeringWheel
{};

class Vehicle
{

public:
SteeringWheel  sWheel;
virtual void doStuff() = 0;

};

class Car: public Vehicle
{

virtual void doStuff();

};

A: Yes, both is-a and has-a relations are transitional. That means, you cannot say, for example, that
Car is-a Vehicle (which has-a SteeringWheel) except it does not have-a SteeringWheel.
or
Car is-a Vehicle (which is-a Machine) except it is-not-a Machine.
Having to implement the above examples would mean that your design is flawed. This would essentially go against the Open-closed principle in SOLID - you simply should not take away from a base class (or ignore the existence of some of its parts), only extend it by inheritance.


text:
Q: SignalR on HTTPS I am trying to use SignalR client side libraries on HTTPS server. It works fine on normal server but on HTTPS server, it is throwing an exception.
try
{
...
hubConnection = new HubConnection(signalUrl);
proxy = hubConnection.CreateHubProxy("SignalRConnect");
hubConnection.Start().Wait(); // throws an exception at this line
...
 }
catch (Exception ex) {
I am getting exception - "The remote certificate is invalid according to the validation procedure."
}
Does anybody has an idea how to configure client side SignalR?
Thank you in advanced.
Medha

A: If your server requires custom client certificates then you can use SignalR 1.1 beta to add an  x509certificate to the connection before the request is made.

A: Issue is resolved. I removed the code of creating proxy from the controller and add code on client side and get context of the hub from controller code.
var hubContext = GlobalHost.ConnectionManager.GetHubContext();
and use hubContext for client notification.


text:
Q: Is there any existing function to convert a docstring to dict? Does anyone have the similar experience to print assigned information for different objects?
For instance, the following docstring printed from getattr(obj,'__doc__')
__doc__
Keyword arguments
-----------------
name : str
     (default "")
description : str
     (default "")
_id : str
     (default "")
script : str
     (default "")
dependencies : List[Dependency]
cyclic : bool
     (default False)
feature : str
     (default "")
index : int
  (default -1)

or set it in a variable docstr as
docstr = '\n    Keyword arguments\n    -----------------\n    name : str\n         (default "")\n    description : str\n         (default "")\n    _id : str\n         (default "")\n    script : str\n         (default "")\n    dependencies : List[Dependency]\n    cyclic : bool\n         (default False)\n    feature : str\n         (default "")\n    index : int\n         (default -1)\n    '
is to be converted to:
adict = {'name' : str,
         'description' : str,
         '_id' : str,
         'script' : str,
         'dependencies' : List[Dependency],
         'cyclic' : bool,
         'feature' : str,
         'index' : int,
        }

A: While waiting for answer, I figured one regex solution which at least can work for the current purpose.
s = '\n    Keyword arguments\n    -----------------\n    name : str\n         (default "")\n    description : str\n         (default "")\n    _id : str\n         (default "")\n    script : str\n         (default "")\n    dependencies : List[Dependency]\n    cyclic : bool\n         (default False)\n    feature : str\n         (default "")\n    index : int\n         (default -1)\n    '
keys = re.findall("(?<=\s)_?[a-z]+(?=\s:)", s)
vals = re.findall("(?<=:\s)\w+", s)
pair = {a:b for a, b in zip(keys, vals)}


text:
Q: Issue setting up a django database migration for an app with a model that has a relationship to another app in the same project I'm trying to setup two related apps in a django project, where one app's model references the other in a foreign key relationship. This is normally a simple thing, but I'm running into some collisions with app names (one of my apps is called 'account' and that's not unique in my installation) and my subsequent fix to that by adding in specific name/label definitions in a custom AppConfig may also be contributing to the problem.
A little background on my environment:

*

*Django 1.8.3

*Python 2.7.6

*Postgres 9.4.0

*using this template for my project structure: https://github.com/pydanny/cookiecutter-django.  Thanks pydanny!

I setup a simple project using this template to demonstrate the problem: https://github.com/rishikumar/django_test_model
Here are the relevant parts to the tree:
test/ (project app)
/config ()
/test (main django app)
    /account
        __init__.py
        apps.py
        models.py (Has a model called "Account")
    /schedule
        __init__.py
        apps.py
        models.py (Has a model called "Schedule" which has a ForeignKey relationship to the Account table)

Here is the first model class, under the test/account app
class Account(models.Model):
    class Meta:
        db_table = 'test_account'

After putting this in place, I added this project to the INSTALLED_APPS as "test.account". I ran makemigrations next.
./manage.py makemigrations test.account

I was expecting this to uniquely identify the account package underneath the test project, but its only looking for the "account" part of the name. (I couldn't find any documentation explaining why this is the case)
django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: account

To work around this problem I setup a custom AppConfig for this.  in test/test/account/init.py I added the following:
default_app_config = 'test.account.apps.AppConfig'

And to test/test/account/apps.py I added:
class AppConfig(apps.AppConfig):
    name = 'test.account'
    label = 'test.account'

Now I can run make migrations as I originally intended and it works as expected.
./manage.py makemigrations test.account

Incidentally, I gave the model a specific table name because it was specifying "test.account_account" by default and that causes some headaches in the postgres CLI - I have to quote the entire table name to reference it.
I setup the second app the same way - added a default app config and setup the name and label of the app config to be "test.schedule"
Here is the models.py in the schedule app:
from test.account.models import Account

class Schedule(models.Model):
    class Meta:
        db_table = 'test_schedule'

    account = models.ForeignKey(Account)

Now I run makemigrations on this app:
./manage.py makemigrations test.schedule

I get the following error:
ValueError: Lookup failed for model referenced by field test.schedule.Schedule.account: test.schedule.test.account.Account

Notice that the Account class that its trying to access says "test.schedule.test.account.Account" when it should referencing "test.account.Account"
I'm not sure if my solution for the AppConfig entry was the right choice - perhaps there is a better way to uniquely identify an app within the django installation?
I'm guessing that I'm making a bad decision about how to name things in my AppConfig, but I'm not sure how to reconcile the fact that I need to specify an AppConfig to avoid having duplicate application labels while still being able to avoid confusing the lookup for the foreign key reference that the migration tool is using.


text:
Q: MVC Web Framework and Mono I work in a shop that has a number of very good C# developers who have been using ASP.NET WebForms and would like to move to a MVC framework. To make things more complicated, we would also like to be able to run this under mono.
So my question is, are there any good MVC frameworks for mono, that have been tried and tested in the real world or are we better with Windows Server and IIS?

A: I've used Castle Monorail in Mono 2.0, and haven't had any problems.

A: I'm pretty sure you can run django with ironpython under mono. I haven't ever tried it but maybe you should check it out.
Sorry if this was unhelpful as you mentioned C# which django is not...

A: Give a look to http://netfluid.org/ it's a new interesting .net web server and it works on mono


text:
Q: Exporting individual custom post type post for deployment? Sometimes for deployment I will have a user named "exporter" that I assign a post to. I then export all posts by that user and then import them into the live site (easy migration).
I'd love to be able to do this with custom post type posts as well (exporting by user). The only solutions I've found are by use of plugins, which I'm looking to avoid at (almost) all costs.
I can export all of the custom post type, and then edit the XML file which is pretty plain and simple to do, but it's still somewhat of a manual process.
Anyone have a better solution for this?
Thanks


text:
Q: Quicker way to hardening with CIS Benchmark on Windows Server 2016 I'm hardening new Windows 2016 servers manually with CIS Benchmark
Since I've got a couple of 'em and can't copy/duplicate the VM for some "reasons". I need to extract the secpol and copy it on another server with M̺̬̘á̗̯̥̜̺g̮̼̮̪̰͘i̸͙̦̬̱̲͍̭c͕̳̭̠̪̮.
Since I'm no magician I first figurred out that I could extract it with :
secedit /export /cfg c:\secpol.cfg

Then I got confuse avout how I could import it on my new machine
I foud this here on stack:
secedit /configure /db c:\windows\security\local.sdb /cfg c:\secpol.cfg /areas SECURITYPOLICY
rm -force c:\secpol.cfg -confirm:$false

However the folder does not hold the local.sdb is there something I'm missing?
** If you guys have better ways of doing it I'm all ears! **