Q:

Cannot resolve Mockito dependency in a Tycho project

Possible Duplicate:
How to reference mockito within tycho?

I am trying to get a test feature project building with Tycho, but it fails to resolve dependencies listed in my pom from the Maven central repository that is listed in my parent pom. Here is the relevant part from my parent pom:
    <properties>
            <tycho-version>0.12.0</tycho-version>
    </properties>

    <repositories>
            <repository>
                    <id>helios</id>
                    <layout>p2</layout>
                    <url>http://download.eclipse.org/releases/helios/</url>
            </repository>
    </repositories>

    <pluginRepositories>
            <pluginRepository>
                    <id>central</id>
                    <name>Maven Plugin Repository</name>
                    <url>http://repo1.maven.org/maven2</url>
                    <layout>default</layout>
                    <snapshots>
                            <enabled>false</enabled>
                    </snapshots>
                    <releases>
                            <updatePolicy>never</updatePolicy>
                    </releases>
            </pluginRepository>
    </pluginRepositories>

    <build>
            <plugins>
                    <plugin>
                            <groupId>org.eclipse.tycho</groupId>
                            <artifactId>tycho-maven-plugin</artifactId>
                            <version>${tycho-version}</version>
                            <extensions>true</extensions>
                    </plugin>
                    <plugin>
                            <groupId>org.eclipse.tycho</groupId>
                            <artifactId>target-platform-configuration</artifactId>
                            <version>${tycho-version}</version>

                            <configuration>
                                    <pomDependencies>consider</pomDependencies>

                                    <resolver>p2</resolver>

                                    <environments>
                                            <environment>
                                                    <os>linux</os>
                                                    <ws>gtk</ws>
                                                    <arch>x86_64</arch>
                                            </environment>
                                            <environment>
                                                    <os>win32</os>
                                                    <ws>win32</ws>
                                                    <arch>x86</arch>
                                            </environment>
                                    </environments>
                            </configuration>
                    </plugin>
            </plugins>
    </build>

and here my feature pom:
    <modelVersion>4.0.0</modelVersion>
    <parent>
            <artifactId>parent</artifactId>
            <groupId>com.example</groupId>
            <version>1.0.0-SNAPSHOT</version>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>com.example.testing.feature</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>eclipse-feature</packaging>

    <dependencyManagement>
            <dependencies>
                    <dependency>
                            <groupId>org.mockito</groupId>
                            <artifactId>mockito-all</artifactId>
                            <version>1.8.5</version>
                    </dependency>
            </dependencies>
    </dependencyManagement>

    <dependencies>
            <dependency>
                    <groupId>org.mockito</groupId>
                    <artifactId>mockito-all</artifactId>
            </dependency>
    </dependencies>

when I run mvn clean package on my feature project, I get the following:
[INFO] Adding repository http://download.eclipse.org/releases/helios/
[INFO] Adding repository http://download.eclipse.org/releases/helios/
[DEBUG] Added p2 repository helios (http://download.eclipse.org/releases/helios/
)
[DEBUG] Ignoring Maven repository central (http://repo1.maven.org/maven2)
and then my build fails, because my dependency cannot be resolved. Am I missing something? Is this because of the p2 resolver configured for target-platform-configuration?

A:

Indeed it seems you are correct.
First, create a Target Definition file (.target) and put it inside a Maven project, see here for example target: https://github.com/eclipsesource/com.eclipsesource.tycho.aspectj.demo/blob/master/platform/indigo.target
You need to attach the .target file to the artifact, using the build helper:
<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>1.3</version>
    <executions>
        <execution>
            <id>attach-artifacts</id>
            <phase>package</phase>
            <goals>
                <goal>attach-artifact</goal>
            </goals>
            <configuration>
                <artifacts>
                    <artifact>
                        <file>indigo.target</file>
                        <type>target</type>
                        <classifier>indigo</classifier>
                    </artifact>
                </artifacts>
            </configuration>
        </execution>
    </executions>
</plugin>

(from https://github.com/eclipsesource/com.eclipsesource.tycho.aspectj.demo/blob/master/platform/pom.xml )
Then, in the parent POM or the plug-in projects that use that target definition file, you need to configure the "target" of target-platform-configuration Maven plugin, for example:
<plugin>
    <groupId>org.eclipse.tycho</groupId>
    <artifactId>target-platform-configuration</artifactId>
    <version>${tycho-version}</version>
    <configuration>
        <resolver>p2</resolver>
        <ignoreTychoRepositories>true</ignoreTychoRepositories>
        <target>
            <artifact>
                <groupId>com.eclipsesource.sandbox.weaving.demo</groupId>
                <artifactId>com.eclipsesource.sandbox.weaving.demo.platform</artifactId>
                <version>0.1.0-SNAPSHOT</version>
                <classifier>indigo</classifier>
            </artifact>
        </target>
        <environments>
            <environment>
                <os>${build.os}</os>
                <ws>${build.ws}</ws>
                <arch>${build.arch}</arch>
            </environment>
        </environments>
    </configuration>
</plugin>

(taken from https://github.com/eclipsesource/com.eclipsesource.tycho.aspectj.demo/blob/master/releng/pom.xml )
Then your project(s) should build very nicely using Tycho. :-) If your .target references remote p2 repositories and not already in the p2 bundle pool, the necessary artifacts will be downloaded automatically.
Good luck!
Known Issue:
[WARNING] Target location type: Profile is not supported

As of Tycho 0.12.0, It means the "Eclipse Installation" target source type cannot be used with Tycho (yet?), along with "Directory" and "Features".
Solution: Use the "Update Site" target source.
If you don't have yet an update site, here's to generate an update site from an Eclipse (or from any folder containing bundles, for that matter):
/opt/eclipse_rcp/eclipse -consolelog -nosplash -verbose \
  -application org.eclipse.equinox.p2.publisher.FeaturesAndBundlesPublisher \
  -metadataRepository file:/home/ceefour/p2/bonita/ \
  -artifactRepository file:/home/ceefour/p2/bonita/ \
  -source /home/ceefour/BOS-5.5.1/studio/ \
  -publishArtifacts

Note:

change /opt/eclipse_rcp to your own Eclipse SDK installation
metadataRepository and artifactRepository is the folder where the new update site will be created
source is --you guessed it-- the folder/installation containing the original bundles


Q:

Show menu bar during page load

today I visited the website https://www.wienerprivatbank.com/ (it's german, but if you visit it, you will get the point). I realised, that when I click on a link, the menu bar shows the whole time during loading and building the new page. How do I achieve this?
In my opinion, this looks really sweet and I'd like to implement that as well.
Cheers

A:

They are using CSS for Fade-in transition. You need to add class '.fade-in' and once content is loaded then add another class '.anim' to show content. See example below:

setTimeout(function() {
  document.getElementById('target').classList.add('anim');
}, 1000);
.fade-in.anim {
  opacity: 1;
  -webkit-transition: all 0.4s ease-in-out;
  -moz-transition: all 0.4s ease-in-out;
  -ms-transition: all 0.4s ease-in-out;
  -o-transition: all 0.4s ease-in-out;
  transition: all 0.4s ease-in-out;
}

.fade-in {
  opacity: 0;
}

estibulum semper, odio in scelerisque luctus, ex urna tristique purus, nec auctor lectus tellus pharetra nisl. Nam vehicula quis odio in ornare. Phasellus pulvinar, justo vitae tempus porta, nulla nibh suscipit ipsum, vel scelerisque metus ex ut magna.
  Morbi facilisis nisi eget nisi sollicitudin auctor. Proin lacinia turpis a porttitor varius. Maecenas eu ante et arcu vulputate iaculis eget non metus. Morbi elementum magna a facilisis pellentesque. Etiam sodales euismod imperdiet. Sed blandit vitae
  leo ut condimentum.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vehicula mauris dui, a consectetur nunc volutpat ultrices. Nam dapibus sagittis diam eu ultricies. Cras et pharetra nisi. Duis vel nisl et tellus venenatis laoreet ut sit amet purus. Pellentesque
  ullamcorper augue nulla, sit amet scelerisque eros condimentum quis. Vivamus sit amet felis gravida, consectetur purus eu, aliquet nunc. Nam nec mauris ut eros malesuada iaculis in a diam. Nunc imperdiet leo id sapien iaculis, a pretium est pharetra.
  Integer convallis erat nec velit lobortis pharetra. Curabitur sed metus interdum, vulputate ipsum quis, blandit quam. Etiam odio leo, semper sed varius ut, luctus at augue. Mauris viverra, mauris id rhoncus posuere, ex purus sollicitudin mi, ut aliquam
  augue felis ac elit. Mauris tincidunt eleifend orci elementum rutrum. Donec ultricies lorem at imperdiet efficitur. Mauris condimentum euismod enim, ut pulvinar tortor hendrerit ac.

I will recommend you to view the source code of the website in debugger and learn :)


Q:

jquery adapter and ckeditor issue

I am doing some php programming with jquery adapter and ckeditor on my page. Let me show what I have. The page I am working on is index.php
A jquery adapter:
    function sendid(id)
     {
    jQuery('#mydiv').showLoading();
    $.ajax({
        type: "POST",
        url: "",
        data: id,
        error: function(){

          alert('error');
      },
      success: function(data){
        jQuery('#mydiv').hideLoading();
            $('#mydiv').html(data);
  }
  });
}
}

This function sends an id to index.php . Whith this Id I am fetching my database and get some records. With the record I got, I am displaying it via ckeditor like this:
          <?php
            $ckeditor = new CKEditor();
            $ckeditor->basePath  = 'ckeditor/' ;
            CKFinder::SetupCKEditor( $ckeditor, 'ckfinder/' ) ;
            $config['height'] = '300';
            $initialValue = $queryresult['content'];
            $ckeditor->editor('FCKeditor1', $initialValue, $config);
        ?>

Whenever I click the button which calls sendid() function ckeditor appears above the list of ids. The first time when I call sendid() function it works ok and puts the record into ckeditor. However second time I call the sendid() function ckeditor disappears.
I found a topic in this link:
CKEditor instance already exists
but it becomes very hard for me, where to place the codes mentioned in the link. As far as I understood I have to kill or destroy the editor everytime I click the button for sending the id to sendid() function. But whenever I put destroy or kill ckeditor into sendid() function it did not work.
Could you please help me on this.

A:

Please, download the latest CKEditor from http://ckeditor.com/download. Unpack it on your server so you can run it, for example http://localhost/ckeditor_test/ (anywhere you like).
Now, save the following code in the same directory where all the editor files have been unpacked (ckeditor.js, ckeditor_php5.php and so on) as index.php.
Open the webiste and enjoy clicking the button. This sample (sandbox, actually) will let you understand how to replace an editor dynamically and destroy existing instances to avoid conflicts.
<?php if ( $_SERVER[ 'REQUEST_METHOD' ] === 'POST' ): ?>
    <?php
        include( 'ckeditor_php5.php' );

        $ckeditor = new CKEditor();
        $ckeditor->editor( $_POST[ 'id' ], 'This is my initial value!', array(
            'height' => '300'   // Config to be used
        ));
    ?>
<?php else: ?>

    <!DOCTYPE html>
    <html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
    </head>
    <body>
        <div id="mydiv" style="outline: 2px dashed orange; padding: 20px; margin: 0 0 20px;">
            This is where the editor will be loaded.
        </div>
        <button id="load" type="submit">Load the editor via AJAX!</button>
        <script>

            (function( $ ) {
                var id = 'idOfTheEditor';

                $( '#load' ).on( 'click', function() {
                    $.ajax({
                        type: 'POST',
                        url: 'index.php',
                        data: {
                            id: id
                        },
                        error: function(){
                            console.log( 'Error?' );
                        },
                        success: function( data ) {
                            if ( window.CKEDITOR && CKEDITOR.instances[ id ] ) {
                                console.log( 'Desytroying an existing instance!' );
                                CKEDITOR.instances[ id ].destroy();
                            }
                            $( '#mydiv' ).html( data );
                        }
                    });
                });

            })( jQuery );

        </script>
    </body>
    </html>
<?php endif ?>

You can eventually wrap $( '#mydiv' ).html( data ) in setTimeout closure like this to see your code working in "slow motion":
setTimeout( function() {
        $( '#mydiv' ).html( data );
}, 1000 );

Have fun!


Q:

Reasonable precautions for lake bacteria

I've read quite a lot online about bacteria you can be infected with by swimming in freshwater lakes. Anecdotally I've had friends tell me that when swimming in a lake you should keep your head over water.
In many cases, avoiding submersion isn't an option, and you're going to freestyle swim anyway. Is it common for people to use earplugs or noseplugs or anything like that? If industrial pollution isn't a particular concern where you're swimming, would you take any precautions?

A:

If you're swimming from a public beach or park, the first thing you should do is find out if/where water quality test results are posted.  There are generally higher E.coli readings after heavy rains or when waves churn the sediment from the bottom, and they can also be higher downwind from river and stream outlets.  Beaches just a few miles apart can have vastly different bacteria levels due to these factors, so it's good to be aware of them.
I'm probably more on the cautious side, since I always wear goggles and (usually) earplugs if I'm planning to be submerged, but it's as much for comfort as anything else.  I might consider plugging my nose if I lived in a warmer region, but in places similar to the deep South of the United States, you're probably in much more danger from alligators and snakes while swimming in fresh water than a 1-in-10-million deadly amoeba.
Respecting the local hazards and using any available resources to stay up-to-date on the water quality is probably much more effective than any personal precaution you could take.


Q:

Java Type Hierarchy in Eclipse shows "Source not found"

I am finding Java classes by using ctrl + shift + t, I click on the class I wish to see (example Scanner or Random in java.Utils) the type hierarchy for and it opens a tab that says, "Source not found." I read an answer that said my build path was not correct, but my programs uses these with no problem. Can I fix this so I can start to study type hierarchy or am I doing something wrong? Page after I click the class in menu

A:

Your IDE can find the compiled Java classes, but not the Java source.
You may find a src.zip in your JDK folder - try to attach that in Eclipse's JRE/JDK setting.


Q:

How zsh/sh/bash check signal SIGTTIN for command "cat &" launched from a c++ program

I can't understand How the terminal knows if a binary used stdin in background mode?
I have a C++ program that must run commands like /bin/cat in the background, but I DONT get the error message:

cat is stopped because it used stdin and got SIGTTIN

A:

So. After two days trying and crying now I solve this problem. If you want give your child process SIGTTIN you should call setpgid() in parent process.


Q:

How to handle User Audit Logs (or other frequent client-side actions) in a Web App?

Architectural question here. I have a Web App (HTML5/Javascript/AngularJS) which logs user activity into a Backend DB via Web API. This function runs quite frequently on events such as Menu and button Clicks throughout the app. Making an API call for each such event seems expansive, and I was wondering what are best practices for these kind of updates, Or, How is that being implemented with a service such as Google Analytics on their client scripts?

A:

I've been looking at something very similar where I work. First you really want the data sent to your API as small as possible so that sending all of these events doesn't use to much bandwidth. The next thing we realised was to use a queue of some sort, RabbitMQ, Azure Service Bus, MSMQ or Amazon SQS or something similar.
The API endpoint should just take the data and put it on the queue. Then have another program or service that then reads the messages on the queue at it's own pace and does any inserts into databases.
At peak times you shouldn't then see any dip in performance from the API, the only thing that will happen when your system is being hammered is that the data may take a few seconds to a few minutes to be inserted into the DB.
You're essentially batching up on the queue and don't have to worry about batching client side


Q:

unlimited (wraparound) 3d terrain

How can I create a wrap around unlimited 3D terrain:
To make it clear:
If I step out of terrain in (1) or (A) I want to get to (2) resp. (B)
        |B
        V
     +----------+
2 -->|          |--> 1
     |          |
     |          |
     +----------+
        |A
        V

I do not know how to wrap around the terrain and all the items which are on the terrain(NPCs etc) I thought of portals, but then I have problems on the corners of the terrain.
In 2D it is quite simple(even trivial), but on 3D I cannot find a solution..
Any advice or tutorial ailable?

A:

Have a matrix of chunks that make up the visible area around the camera. The chunks will use modulo, just like in 2D, to determine which chunk of your wrapped 3D world they should contain.

Each dimension is like a conveyor belt, loading and unloading chunks as the camera moves along its axis.
Now, when it comes to drawing, you just reference the chunks loaded around your camera. If the wrap of the world was small, there would be duplicate chunks referenced in the chunk matrix. The view frustum doesn't need to know anything about where the world wraps, it just looks at the loaded chunks.


Q:

Lock a choice in PyQt4 QComboBox using a QCheckBox

I am beginning to write a GUI using PyQt4. This is my first experience with GUIs (and also oo-programming is somewhat new to me). Part of that GUI will be like 4 to 5 instances of QComboBox. As many choices are to be made, I want the user to be able to lock a choice, such that is not being changed unintenionally later. For one QComboBox I can solve the problem with this code that I wrote:
import sys
from PyQt4 import QtGui, QtCore

class MyGui(QtGui.QWidget):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        self.resize(250, 50)

        # vertical layout for widgets
        self.vbox = QtGui.QVBoxLayout()
        self.setLayout(self.vbox)

        # Create a combo box with some choices
        self.combo_color = QtGui.QComboBox()
        self.vbox.addWidget(self.combo_color)
        items = 'Red Yellow Purple'.split()
        self.combo_color.addItems(items)
        self.connect(self.combo_color, QtCore.SIGNAL('activated(QString)'), self.use_choice)

        # add a checkbox next to the combobox which (un-)locks the the combo-choice
        self.checkbox_color = QtGui.QCheckBox('Lock Choice', self)
        self.vbox.addWidget(self.checkbox_color)
        self.connect(self.checkbox_color, QtCore.SIGNAL('stateChanged(int)'), self.lock_choice)

    def use_choice(self, text):
        # do something very useful with the choice
        print 'The current choice is: {choice}'.format(choice=text)

    def lock_choice(self):
        if self.checkbox_color.isChecked():
            self.combo_color.setEnabled(False)
            print 'Choice {choice} locked'.format(choice=self.combo_color.currentText())
        else:
            self.combo_color.setEnabled(True)
            print 'Choice unlocked'

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    mygui = MyGui()
    mygui.show()
    app.exec_()

This code does what it should, but I am very unhappy with its design, because the method lock_choice is hard-coded to only lock the choice of the QComboBox combo_color. What if I now want to do the same thing for another QComboBox (say combo_name) and a second QCheckBox (say checkbox_name) which could be realized by appending the following code to the classes __init__(self) code block:
    # create second combo box with some other choices
    self.combo_name = QtGui.QComboBox()
    self.vbox.addWidget(self.combo_name)
    items = 'Bob Peter'.split()
    self.combo_name.addItems(items)
    self.connect(self.combo_name, QtCore.SIGNAL('activated(QString)'), self.use_choice)

    # add a checkbox next to the combobox which (un-)locks the the combo-choice
    self.checkbox_name = QtGui.QCheckBox('Lock Choice', self)
    self.vbox.addWidget(self.checkbox_name)
    self.connect(self.checkbox_name, QtCore.SIGNAL('stateChanged(int)'), self.lock_choice) # <-- obviously wrong, as it (un-)locks color choice at the moment

Both QComboBoxes can share the method use_choice() right now, but they cannot share the method lock_choice(), as both checkboxes lock the color-choice. I want the checkbox checkbox_name to lock the name-choice, without copy and pasting the current  lock_choice()-method and switching the hardcoded combobox.
I am sure there is an easy way, like passing the target-combobox to the method, which i just don't know yet. Help would be appreciated!

A:

Try partial functions-
from functools import partial

with the connect signal, pass the QWidget name:
self.connect(self.checkbox_color, QtCore.SIGNAL('stateChanged(int)'), partial(self.lock_choice, self.combo_color))

And in your method, you may add an argument.
We'll add an argument in the method like below, to handle the QWidget(QComboBox) that we'll pass through the partial function above.
def lock_choice(self, combos):
    if combos.isEnabled(True):
        combos.setEnabled(False)
        print 'Choice {choice} locked'.format(choice=combos.currentText())


Q:

iPad orientation issue in iOS 5

I have UISplitViewController in StoryBoard that is initial view and I want the app to work only in Landscape mode.
I have restricted orientation to landscape only, and even put in plist Initial interface orientation to Landscape (right home button).
In iOS 6 everything works fine, it shows master and detail view only, but in iOS 5 it is stuck in Portrait mode and only shows Detail view.
Please help me with this, I am stuck with it for last 2 hours...

A:

You need to implement shouldAutorotateToInterfaceOrientation in the view controllers you have contained in the UISplitViewController:
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return UIInterfaceOrientationIsLandscape(toInterfaceOrientation);
}


Q:

NuGet Package restore failed for project

I'm a new xamarin developer.
I ran into an error while running my first project:
NuGet Package restore failed for project Project.Droid: Unable to find version '2019' of package 'syncfusion.xamarin.linq.Android' not found.

A:

Please follow these steps:

Close Visual Studio.

Open the .csproj in Notepad  and manually remove all entries related to the Package

Open packages.config in Notepad and remove the entry for the NuGet Package

Go to packages/ folder in Windows Explorer and delete the package folder

end
you can open a solution.


Q:

Closed form of the following Recurrence Relation

Let $L\colon\mathbb{N}^3 \to \mathbb{N}$ satisfy the following recurrence relationship,
$$
L(a,b,c) = 1 + \sum_{i=0}^{a-1} \sum_{j=0}^{b-1} \sum_{k=0}^{c-1} L(i,j,k),
$$
With "initial conditions" $L(0,a,b) = L(c,0,d) = L(0,e,f) = 0$.  I am interested in knowing a closed form of $L$.
Work I have done:
I have investigated a simpler case
$
G\colon \mathbb{N}^2\to \mathbb{N}
$, satisfying
$$G(a,b) = 1 + \sum_{i=0}^{a-1} \sum_{j=0}^{b-1} G(i,j)$$
with similar "initial conditions" and can obtain $$G(a,b) = \binom{a+b-2}{a-1}= \binom{a+b-2}{b-1}= \frac{(a-b-2)!}{(a-1)!(b-1)!},$$ so I would have guessed that $$L(a,b,c) = \frac{(a+b+c-3)!}{(a-1)!(b-1)!(c-1)!}, $$ but this isn't correct.  I would appreciate any hints on how to find a closed form solution for this.

A:

Continuing according to Fred's very clever deduction of the multiple z-tranform
 ( the credit should go to him, so I invite him to post it, and votes to be casted on it as well)
$$
F(x,y,z) = \frac{{\frac{{x\,y\,z}}
{{\left( {1 - x} \right)\left( {1 - y} \right)\left( {1 - z} \right)}}}}
{{1 - \frac{{x\,y\,z}}
{{\left( {1 - x} \right)\left( {1 - y} \right)\left( {1 - z} \right)}}}} = \sum\limits_{1\, \leqslant \,n} {\left( {\frac{{x\,y\,z}}
{{\left( {1 - x} \right)\left( {1 - y} \right)\left( {1 - z} \right)}}} \right)^{\,n} }
$$
and considering that
$$
\frac{{z^n }}
{{\left( {1 - z} \right)^n }} = \sum\limits_{0\, \leqslant \,k} {\left( \begin{gathered}
  n - 1 + k \\
  k \\
\end{gathered}  \right)\,\,z^{\,n + k} }  = \sum\limits_{0\, \leqslant \,j} {\left( \begin{gathered}
  j - 1 \\
  j - n \\
\end{gathered}  \right)\,\,z^{\,j} }
$$
then we have
$$
\begin{gathered}
  \sum\limits_{1\, \leqslant \,n} {\left( {\frac{{x\,y\,z}}
{{\left( {1 - x} \right)\left( {1 - y} \right)\left( {1 - z} \right)}}} \right)^n }  =  \hfill \\
   = \sum\limits_{0\, \leqslant \,a,\;b,\;c\;} {\left( {\sum\limits_{1\, \leqslant \,n\,\left( { \leqslant \,\min \left( {a,b,c} \right)} \right)} {\left( \begin{gathered}
  a - 1 \\
  a - n \\
\end{gathered}  \right)\left( \begin{gathered}
  b - 1 \\
  b - n \\
\end{gathered}  \right)\left( \begin{gathered}
  c - 1 \\
  c - n \\
\end{gathered}  \right)} } \right)x^{\,a} \,y^{\,b} \,z^{\,c} }  \hfill \\
\end{gathered}
$$
i.e.
$$
\begin{gathered}
  L(a,b,c) = \sum\limits_{1\, \leqslant \,n\,\left( { \leqslant \,\min \left( {a,b,c} \right)} \right)} {\left( \begin{gathered}
  a - 1 \\
  a - n \\
\end{gathered}  \right)\left( \begin{gathered}
  b - 1 \\
  b - n \\
\end{gathered}  \right)\left( \begin{gathered}
  c - 1 \\
  c - n \\
\end{gathered}  \right)}  =  \hfill \\
   = \sum\limits_{1\, \leqslant \,n\,\left( { \leqslant \,\min \left( {a,b,c} \right)} \right)} {\left( \begin{gathered}
  a - 1 \\
  n - 1 \\
\end{gathered}  \right)\left( \begin{gathered}
  b - 1 \\
  n - 1 \\
\end{gathered}  \right)\left( \begin{gathered}
  c - 1 \\
  n - 1 \\
\end{gathered}  \right)}  \hfill \\
\end{gathered}
$$
Note that:

in 1D it becomes $L(a,b,c) = 2^{\,a - 1} $
in 2D
$$
\begin{gathered}
  L(a,b) = \sum\limits_{1\, \leqslant \,n\,\left( { \leqslant \,\min \left( {a,b} \right)} \right)} {\left( \begin{gathered}
  a - 1 \\
  a - n \\
\end{gathered}  \right)\left( \begin{gathered}
  b - 1 \\
  b - n \\
\end{gathered}  \right)}  =  \hfill \\
   = \sum\limits_{1\, \leqslant \,n\,\left( { \leqslant \,\min \left( {a,b} \right)} \right)} {\left( \begin{gathered}
  a - 1 \\
  n - 1 \\
\end{gathered}  \right)\left( \begin{gathered}
  b - 1 \\
  b - n \\
\end{gathered}  \right)}  = \left( \begin{gathered}
  a + b - 2 \\
  b - 1 \\
\end{gathered}  \right) \hfill \\
\end{gathered}
$$
but in 3D I do not know if there is a closed form.

Addendum
Again thanks to Fred's hint, actually $L(a,b,c)$ can also be expressed in terms of Hypergeometric Function, as
$$
\begin{gathered}
  L(a,b,c) = \sum\limits_{1\, \leqslant \,n\,\left( { \leqslant \,\min \left( {a,b,c} \right)} \right)} {\left( \begin{gathered}
  a - 1 \\
  a - n \\
\end{gathered}  \right)\left( \begin{gathered}
  b - 1 \\
  b - n \\
\end{gathered}  \right)\left( \begin{gathered}
  c - 1 \\
  c - n \\
\end{gathered}  \right)}  =  \hfill \\
   = \sum\limits_{0\, \leqslant \,n\,\left( { \leqslant \,\min \left( {a,b,c} \right) - 1} \right)} {\left( \begin{gathered}
  a - 1 \\
  n \\
\end{gathered}  \right)\left( \begin{gathered}
  b - 1 \\
  n \\
\end{gathered}  \right)\left( \begin{gathered}
  c - 1 \\
  n \\
\end{gathered}  \right)}  =  \hfill \\
   = \sum\limits_{0\, \leqslant \,n\,\left( { \leqslant \,\min \left( {a,b,c} \right) - 1} \right)} {\left( { - 1} \right)^{\,n} \left( \begin{gathered}
  n - a \\
  n \\
\end{gathered}  \right)\left( { - 1} \right)^{\,n} \left( \begin{gathered}
  n - b \\
  n \\
\end{gathered}  \right)\left( { - 1} \right)^{\,n} \left( \begin{gathered}
  n - c \\
  n \\
\end{gathered}  \right)}  =  \hfill \\
   = \sum\limits_{0\, \leqslant \,n\,\left( { \leqslant \,\min \left( {a,b,c} \right) - 1} \right)} {\frac{{\left( {1 - a} \right)^{\,\overline {\,n\,} } \left( {1 - b} \right)^{\,\overline {\,n\,} } \left( {1 - c} \right)^{\,\overline {\,n\,} } }}
{{1^{\,\overline {\,n\,} } \;1^{\,\overline {\,n\,} } }}\frac{{\left( { - 1} \right)^{\,n} }}
{{n!}}}  =  \hfill \\
   = {}_3F_{\,2} \left( {\left( {1 - a} \right),\left( {1 - b} \right),\left( {1 - c} \right);\;\;1,1;\;\; - 1} \right) \hfill \\
\end{gathered}
$$
although, having the variable $z$ fixed at $-1$, we are not much exploiting that function.


Q:

How to say this in an idiomatic way when we decide to go to someone's house for a while when we are going past their house?

How can we say this in an idiomatic way?

When I am going past someone’s house and I stopped at their house and decided to go to their house for a while.

A:

I would say:

I was in the neighbourhood, and I thought I’d stop by.

Stop by:

to visit someone for a short time, usually on the way to another place

Source: Cambridge Dictionary


Q:

Как получить стандартные иконки файловой системы из приложения под iOS?

Хочу написать что-то типа файлового браузера для iOS - нужны стандартные иконки файловой системы (открытая папка, закрытая папка, файл, и т.д.). Как мне их вставить в UIImage или использовать каким-либо другим образом в своем приложении? Под стандартными имею ввиду изображения из System/Library/CoreServices/...

A:

Что вроде такой

По моему в iOS нету стандартных ресурсов папок.
Особено указаного по ссылке. Но зато они есть OSX:
[NSImage imageNamed:@"NSFolder"]

Ты можешь выдрать их через проект Cocoa под OSX и импортировать их уже в свой iOS проект.
Только не знаю как руководство apple будет к этому относиться

Полный список системных `image'ов:
    NSQuickLookTemplate,
    NSBluetoothTemplate,
    NSIChatTheaterTemplate,
    NSSlideshowTemplate,
    NSActionTemplate,
    NSSmartBadgeTemplate,
    NSPathTemplate,
    NSInvalidDataFreestandingTemplate,
    NSLockLockedTemplate,
    NSLockUnlockedTemplate,
    NSGoRightTemplate,
    NSGoLeftTemplate,
    NSRightFacingTriangleTemplate,
    NSLeftFacingTriangleTemplate,
    NSAddTemplate,
    NSRemoveTemplate,
    NSRevealFreestandingTemplate,
    NSFollowLinkFreestandingTemplate,
    NSEnterFullScreenTemplate,
    NSExitFullScreenTemplate,
    NSStopProgressTemplate,
    NSStopProgressFreestandingTemplate,
    NSRefreshTemplate,
    NSRefreshFreestandingTemplate,
    NSFolder,
    NSTrashEmpty,
    NSTrashFull,
    NSHomeTemplate,
    NSBookmarksTemplate,
    NSCaution,
    NSStatusAvailable,
    NSStatusPartiallyAvailable,
    NSStatusUnavailable,
    NSStatusNone,
    NSApplicationIcon,
    NSMenuOnStateTemplate,
    NSMenuMixedStateTemplate,
    NSUserGuest,
    NSMobileMe,
    NSMultipleDocuments,
    NSUser,
    NSUserGroup,
    NSEveryone,
    NSBonjour,
    NSDotMac,
    NSComputer,
    NSFolderBurnable,
    NSFolderSmart,
    NSNetwork,
    NSUserAccounts,
    NSPreferencesGeneral,
    NSAdvanced,
    NSInfo,
    NSFontPanel,
    NSColorPanel,
    NSIconViewTemplate,
    NSListViewTemplate,
    NSColumnViewTemplate,
    NSFlowViewTemplate;


Q:

How to stack two background images over each other

I have been recently been trying to make a very simple but nice looking page to host a tic-tac-toe game for my up coming science fair as I am in 8th grade.I come across a design when I put an background-image under an background-color as it looks good. When I try to recreate the sinario in my gitlab repo it keeps on doing not what I thought. If you didn't understand by now I am quite a newbie.
If someone could give me a snipit of code or an idea of how to do it it would be appreciated.
I checked all over stack but I can't find a question similar so if it is repeated my appologies.
EDIT:Take out the source code

A:

body {
  margin: 0;
  background-color: rgba(100,0,0,.75);
}

div {
  width: 100vw;
  height: 100vh;
  background-image: url("https://media.starwars.ea.com/content/starwars-ea-com/en_US/starwars/galaxy-of-heroes/news/_jcr_content/ogimage.img.jpg");
  opacity: .5;
  background-repeat: no-repeat;
  background-size: cover;
}

I was not able to find a solution without at least one HTML element, but I hope this demonstrates clearly enough the ability to stack background-images and background-colors with opacity values.


Q:

ZF | New on ZF | Autoloader why seem to not working?

The downloaded version is the ZF 2.1
I have enter the following code in my basic file of my appliction, and it seems to be not corect:
$path   =   dirname(__FILE__) . DIRECTORY_SEPARATOR . 'library' . DIRECTORY_SEPARATOR . 'Zend';
ini_set(
    'include_path',
    ini_get('include_path') . PATH_SEPARATOR . $path
);

require_once('/Loader/StandardAutoloader.php');
$loader = new \Zend\Loader\StandardAutoloader(
    array(
        'Zend' => $path,
    )
);
$loader->register();

$m = new \Zend\Mail\Message();

The error I am getting is the following:
Fatal error: Class 'Zend\Mail\Message' not found in PathToMyFile
Any idea on what is it wrong with that ?
Is there any good tutorial to start with Autoloading in Zend Framework ?

A:

You just want:
$path   =   dirname(__FILE__) . DIRECTORY_SEPARATOR . 'library'

in your include path.
However, I would guess that this is in your index.php, which is in your public directory, and what you really want is to go up one dir from there, then into the library dir:
$path   =   dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR .'library'


Q:

Show directories Intellij Idea

All at once directories became invisible. What is wrong with my project?
How to get IntelliJ IDEA to display directories?
That didn`t help. I need to change something in settings, but I don`t know what exactly.

A:

It will happen, when .idea folder is deleted or conflicted.
The best way is create new project, so .idea folder will create & all will work fine.
I have also faced same probel, when .idea folder is conflicted or deleted.
To easily create a module for your project and therefore show the folder structure -
Go to File menu -> New -> Project...
Select Static Web. Note: it does not matter if your project is "web" or not!
Hit next, then fill in the same Project Name: and Project location: as you have already.
IntelliJ will say "File Already Exists" - "Would you like to overwrite it?" - answer Yes.


Q:

Select element value is string

I am sending select element selected value through ajax to Laravel controller action and validated the value as required in controller.
The problem is I am getting select element value as string not integer. So when first option is selected which has value 0, it goes as a string ("0") to controller and does not validated as required in action method.
The options to the select element is added dynamically.
Here is my code
HTML
var row_data = {
    'lob_id': lob_id,
    'sub_lob_id': sub_lob_id,
    'product_id': product_id,
};

$.ajax({
    url: '{{route('
    getProductThreshold ')}}',
    type: 'get',
    dataType: 'json',
    data: row_data,
    success: function (response) {
        loader(true);
        console.log(response);
    }
});

Laravel Controller
$validators = Validator::make($request->all(), [
            'lob_id' => 'required',
            'sub_lob_id' => 'required',
            'product_id' => 'required',
        ]);

Controller Request

How should I use laravel validator if value is being sent as string in request?

A:

I added another laravel validation i.e not_in:0 and that worked for me. Simply its check for request parameter if zero whether parameter is string or integer
$validators = Validator::make($request->all(), [
            'lob_id' => 'required|not_in:0',
            'sub_lob_id' => 'required|not_in:0',
            'product_id' => 'required|not_in:0',
        ]);


Q:

Right aligning a button in a dialog

What is the best way to right align a button in a dialog window, regardless of the window's WindowSize?
Here is a resizable window to test on:
CreateDialog[
 Column[{"Here's some text text text text text text text",
         ChoiceButtons[]}],
 WindowFrameElements -> {"ResizeArea"},
 WindowFrame -> "Normal"]

I would like the button to always be right aligned.
Some unsatisfactory solutions I thought of:

Put the button in an Item and right align.  Then the right margin is determined by the Column size which can't easily be set in pixels.
Put the button in a Panel, right align it, and set a fixed size on the panel.  Again, the size is determined by the panel size, not the window size.

Use case:
Suppose we need to create an alternative to MessageDialog.  This new function, myMessageDialog, should take the WindowSize option, and the created notebook should respond to SetOptions[nb, WindowSize -> ...]  The dialog buttons should always be aligned to the right edge of the window regardless of the window size.

A:

This is unrefined, but I'll put it up as a proof of concept:
CreateDialog[
  Column[{
   Row[{"Here's some text text text text text text text"},
     ImageSize -> Dynamic[CurrentValue["WindowSize"] /. {x_, _} :> x - 15]],
   Item[ChoiceButtons[], Alignment -> Right]
   }],
  WindowFrameElements -> {"ResizeArea"}, WindowFrame -> "Normal"
]


Q:

Is there a solution for $xy=a, xy=b$?

As per title.
I have a system of equations where:
$$\left\{\begin{aligned}Axy = B\\
Cxy = D
\end{aligned}\right.$$
$A,B,C,D$ are constants. Is there a solution to this equation?

A:

Depends on the constants.
From $Axy=B$ you get two possibilities.
1. if $A \neq 0 \Rightarrow xy = \frac{B}{A} $.
Then, if $x \neq 0 \Rightarrow y = \frac{B}{Ax} $.
Putting this into the second education gives you $Cx \frac{B}{Ax} = D $, so $ C \frac{B}{A} = D $.
 If it is true, that $CB=AD$ then any $x \in \mathbb{R}$ and $y= \frac{B}{Ax} $ solve the system.
Else, if $x=0$, the solution is $x=0, y \in \mathbb{R}$.

And if $A = 0 \Rightarrow B=0$. So you basically have only one equation. If also $C$ or $D$ is equal to $0$, than any $x, y \in \mathbb{R}$ are good.
In other case the best you can do, is say $y = \frac{D}{Cx} $, if $x \neq 0$.


Q:

Calling Q Promise on the basis of conditional logic

Below is my condition
if abc is true
    call async func1, func2
else
    call async func1

function test(): Q.Promise<boolean> {
    if(abc)
       Q.all([func1,func2])
    else
       Q.all([func1])
    //if failed throw reject reason all the way in the chain
}

As shown, it can be done using if and else clause, is there a better way to call promise conditionally?
How to throw back error from any one of the promises?

A:

I would put promises in array and append new one depending on condition:
function test(): Q.Promise<Boolean[]> {
    const promises = [func1()]
    if (abc) promises.push(func2())
    return Q.all(promises)
}

I corrected type signature a little, because Q.all resolves with array of values (Boolean in your case) from each underlying promises. You also need to call func1 and func2. And finally, don't forget to return from test function.


Q:

How to write a conditional redirect rule in htaccess file

I have WordPress blog which is registered under a sub domain URL (something like http://news.main.co.uk). The blog's client decided to then adopt the following URL;
www.main.co.uk/news.
The owner of the domain set up a redirect so www.main.co.uk/news loads the blog hosted on http://news.main.co.uk.
The problem we now have is that traffic is coming via two different URLs. I would like to redirect users who arrive via the older URL (http://news.main.co.uk) to be redirected to the newer one http://www.main.co.uk so it appears that traffic is coming from one URL.
I am trying to write a rule to an existing htaccess file so that only IP addresses from the newer URL http://www.main.co.uk/news load the blog. How do I write a rule to that directs users from http://news.main.co.uk to http://www.main.co.uk/news, baring in mind that http://www.main.co.uk/news is using the old URL to load the blog?
Appreciate any help!
Here is the existing contents of the .htaccess file:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Here is my attempt to implement the mentioned rules (results in a 500 error):
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{REMOTE_ADDR} != xx.xxx.xx.xxx
RewriteCond %{REMOTE_ADDR} != xx.xx.xxx.xxx
RewriteRule .*http://www.main.co.uk/news/$ [R=301,L]

RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

A:

You can do an IP redirect like this:
RewriteCond %{HTTP_HOST} ^123\.45\.67\.89
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

BUT...It sounds like you're creating two problems here: 1) a redirect loop, and 2) attempting to rewrite a domain name that doesn't exist at the host.
If I'm reading this right, you want:
http://news.main.co.uk to rewrite as http://www.main.co.uk/news at a different host
while maintaining the current redirect of:
http://www.main.co.uk/news ----> http://news.main.co.uk
You can't rewrite the news. subdomain at another host to "appear" as www. because www is a subdomain itself and is likely already assigned to your primary host. You can unassign it, but you'd be creating a big mess for yourself.
If you're good with the /news subdirectory redirecting and resolving as news., then you're golden (but that doesn't sound like what you want). The only way you'll be able to accomplish what you want is to move the blog to the same host and into a subdirectory.
On another point, your client's decision may be due to SEO concerns. A subdomain essentially functions like a different website, whereas a subdirectory functions under the same parent domain and is therefore considered "part" of the same website as the parent. So, all information in the subdirectory is collected and indexed by search engines as contributing to the same whole of the parent website.
Subdomains (such as mobile.) are often constructed and, therefore, treated as separate websites altogether, though Google constantly changes its mind about these things.
Just an FYI...


Q:

Passing array of pointers to another class

I am trying to do the following:
in main.cpp:
// Create an array of pointers to Block objects
Block *blk[64];
for (i=0; i<8; i++) {
  for (j=0; j<8; j++) {
    int x_low = i*80;
    int y_low = j*45;
    blk[j*8+i] = new Block(30, x_low+40.0f, y_low+7.5f, &b);
  }
}

And then I am trying to pass it to the graphics object I have created:
Graphics g(640, 480, &b, &p, blk[0], number_of_blocks);

the graphics constructor looks like:
Graphics::Graphics(int width, int height, Ball *b, Paddle *p, Block *blk, int number_of_blocks) {

if I look at what is contained in the array from the graphics object, only the first item exists and then all the other items are in hyperspace:
for (int i=0; i<64; i++) {
  printf("for block %d, %f, %f ", i, (_blk+(sizeof(_blk)*i))->_x_low, (_blk+(sizeof(_blk)*i))->_y_low);

  printf("blah %d\n", (_blk+(sizeof(_blk)*i)));

}

and if I look at the addresses, they are different (6956552 rather than 2280520 when I examine the addresses in the main  class using:
printf(" blah %d\n", &blk[j*8*i]);

I am sure there must be something subtle I am doing wrong as its like I have copied the first item from the blk array to a new address when passed to the graphics object.
Does this make sense?  Any ideas?
Cheers,
Scott

A:

If you want to pass the whole array, the constructor should look like this:
Graphics::Graphics(int width, int height, Ball *b, Paddle *p,
    Block **blk, int number_of_blocks)

and you should pass the array like this:
Graphics g(640, 480, &b, &p, blk, number_of_blocks);


Q:

Width and height of imageview when loading images from sdcard

I am loading images from sdcard in the imageview. Right now I have set the width and height to wrap_content. How should I set my imageview width and height so the image doesn't looks stretched. There are some images which are also really small when loaded in the imageview if I let the width and height to be wrap_content. What would be the right approach to this?.Thanks

A:

You can try doing
android:scaleType="fitXY"

in your imageview and try giving fix height and width.


Q:

Quick way to extract simple strings from Excel xlsx files

Where I work I have a few hundred xlsx files (created with Office 2010 Starter) that I need to extract information from. This is a one time job only, so the question is which way is the quickest. Existing tool? Programming a solution?
The information is just strings, formatting does not matter. These files contain customer data. One file for each customer. And before you ask, yes, it's a silly system - and we are abandoning it. Because we are now moving to a new system, we need to export the existing customer data to a CSV file that can be imported in the new system.
If I were to write a computer program to do this, I would need to be able to access the first worksheet in each file, and be able to read the contents of any given cell (A1, C5 etc.). That's it.
Since an xlsx-file is just some zipped XML files, one approach would be to write code that unzips and parses the XML files. That smells like a very time consuming solution so I would rather use a free library if one exists.
Of the languages that could be useful here, I am best at C++ and C, but have done some C#, VB6 and VB.NET, as well as a tiny bit of Python.

A:

Put all your Excel files in a single folder if they aren't already and follow these steps:

Open a blank workbook
Open VBA Editor Alt + F11
Add a module:  Insert --> Module
Add the code below into the module (change the directory string to point to the directory where your to-be-converted Excel files live)
Step through a few files to make sure it's doing what you expect
F5 to run on all files
Say good-bye to your old system

code:
    Option Explicit

    Sub ExportAllToCSV()
        Dim Directory As String
        Dim i As Long
        Dim file As String
        Directory = "C:\workbooks\"
        i = 1

        Application.DisplayAlerts = False
        Application.ScreenUpdating = False

        ' Get the first file
        file = Dir(Directory, vbReadOnly + vbHidden + vbSystem)

        Do While file <> ""
            If Right(file, 4) = "xlsx" Then ' change to right(file ,3) = "xls" if you have xls files instead of xlsx
                Workbooks.Open Filename:=file
                ActiveWorkbook.SaveAs Filename:="C:\workbooks\file" & i & ".csv", FileFormat _
                            :=xlCSV, CreateBackup:=False
                ActiveWorkbook.Close
                i = i + 1
            End If

            ' Get the next file
            file = Dir()
        Loop

        Application.DisplayAlerts = True
        Application.ScreenUpdating = True
    End Sub


Q:

FreeRTOS Task Notification

Quick Architecture Question...
There are 4 producers and 1 consumer for a message queue. Each of the 4 producers have their own task and are there to service incoming data from 4 specific hardware communications references.
Should the Consumer task have a wait function for each one or can I use task notification where each task notifies the Consumer that a message has arrived?

A:

Just setup the consumer task to wait on the queue. When there is data in the queue from any of the producers it will wake up and you can process the data.


Q:

How to integrate SQLite with AngularJS?

I'm doing an angularjs app using google maps api v3 and a plugin called ng-map. But I want to store some coordinates in a SQLite database and then retrieve from the app.

A:

Basically, you can not.
But you can use a SQLite cordova plugin if you are developing a hybrid mobile application.
http://ngcordova.com/docs/plugins/sqlite/ is one of the best SQLite plugins for cordovajs.


Q:

NUnit TestCaseSource with parameters?

I have multiple test classes that implement an empty interface (ITest, expanded with IEnumerable).
Interface:
public interface ITest : IEnumerable
{
}

TestDataSource with a description:
[Description("TestSourceName")]
public class MyTests : ITest
{
    public IEnumerator GetEnumerator()
    {
        yield return "123";
        yield return "456";
    }
}

TestDataProvider class that will be used as TestDataSource in NUnit,
I'm using reflection to get the right TestDataSource object:
public class TestDataProvider : IEnumerable
{
    public string Name { get; set; }
    public IEnumerator GetEnumerator()
    {

        if (string.IsNullOrEmpty(Name))
            yield break;

        var testdata = System.Reflection.Assembly.GetExecutingAssembly()
                .GetTypes()
                .Where(mytype => mytype.GetInterfaces().Contains(typeof(ITest)))
                .Where(mytype => ((DescriptionAttribute)mytype.GetCustomAttributes(typeof(DescriptionAttribute), false)[0])
                .Description.ToLower() == Name.ToLower());

        yield return ((IEnumerable)testdata).GetEnumerator();

    }

        public IEnumerator GetEnumerator(string name)
        {
            Name = name;
            return GetEnumerator();
        }
    }

Now I wonder how I can pass TestSourceName to the TestDataSource for NUnit?
[TestCaseSource(typeof(TestDataProvider)), TestCaseSourceAttribute("TestSourceName")]
public void TestTestDataProvider()
{
    // here we will have the TestDataSource object given by TestDataProvider
    // using parameter/attribute? "TestSourceName"
}

A:

One approach you could take is to use NUnit TheoryAttribute.  Theories are still part of the upcoming 3.0 release as well.
Roughly based on the examples you gave, here is an example of a working Theory based test which uses the data from the DataPointsAttribute as parameters to the test method.
[Description("TestSource2")]
public class TestData1 : ITest
{
    public IEnumerator GetEnumerator()
    {
        yield return "123";
        yield return "456";
    }
}

[Description("TestSource1")]
public class TestData2 : ITest
{
    public IEnumerator GetEnumerator()
    {
        yield return 33;
        yield return 44;
    }
}

public class TestDataProviderFixture
{
    [Datapoints]
    public string[] SourceNames = {"TestSource1", "TestSource2"};

    [Theory]
    public void TestTestDataProvider(string sourceName)
    {
        var provider = new TestDataProvider();
        var data = provider.GetEnumerator(sourceName);

        if (sourceName == "TestSource1")
        {
            while (data.MoveNext())
            {
                //Do Stuff
            }
        }
        else if (sourceName == "TestSource2")
        {
            while (data.MoveNext())
            {
            //Do Stuff
            }
        }
        else
        {
            Assert.Fail();
        }
    }
}


Q:

Выборка по массиву

Доброго времени суток.
Есть некий массив:
$array = array(
    "foo" => "bar",
    "bar" => "foo",
    "один"   => -100,
    "два"  => 100,
);

Причем известно, что ключи на английском языке - это служебная информация, а ключи на русском - это та информация, которая должна выводиться.
Вопрос: можно ли вывести значение так:

"один"

"-100"

"два"

"100"

при этом неизвестно, сколько будет ключей на английском языке, и какие символы будут использоваться, тоже неизвестно, но, скорее всего, они будут начинаться на знаке нижнее подчеркивание.

A:

пробегаем по массиву foreach смотрим ключ, если первая буква английская или нижнее подчеркивание - пропускаем, иначе выводим.
P.S. проверка букву регуляркой (preg_match)


Q:

Прузи, пружина и прыгать — этимологически однокоренные?

Относятся ли слова прузи, пружина и прыгать к этимологически однокоренным?

A:

Если Вы имеете  в виду прузи  -  мн.ч. от пруг (южный диалект прус) - вид саранчи,( ст.-слав. прѫгъ"саранча"; см. Преобр. II, 139), то вполне возможно, ведь саранча прыгает, пружиня. Но в академической науке об этом нигде прямо не говорится, видимо, пока нет общего мнения.
Даже насчёт "пружина" и "прыгать" нет общего мнения.
Слово пружина все характеризуют как общеслав. суф. производное от пруга (*prǫga) , однокоренное с "упругий".2004  http://my-dict.ru/dic/etimologicheskiy-slovar-russkogo-yazyka/1374550-pruzhina
Семёнов возводит прыгать к общеславянскому  pryg.

В древнерусских и старославянских памятниках литературы глагол
  «прыгать» обнаружен не был. Это слово является только русским, т.к. в
  других славянских языках для обозначения стремительного отталкивания
  ногами от опоры используется глагол «скакать». Исследователи русского
  языка предполагают, что от глагола «прыгать» могло произойти слово
  «пружина» (или наоборот), поскольку оба слова имеют один и тот же
  индоевропейский корень.Производные: прыгнуть, прыжок, прыгун.

http://www.terminy.info/russian-language/etymological-dictionary-of-the-russian-language-semenova/prygat
Шанский (вслед за Фасмером) пишет:

Упругий - искон. преф. производное (с усилительным у-) от утраченного
  пругыи, того же корня, что диал. пруга «пружина», сербохоров. пруг
  «растянутый», чешск. pruh «полоса», нем. springen «прыгать». См.
  пружина, запрячь.

Школьный этимологический словарь русского языка. Происхождение слов. — М.: Дрофа Н. М. Шанский, Т. А. Боброва 2004   http://endic.ru/rusethy/Uprugi-4894.html
Мнение Крылова:

Пружи́на. Общеславянское слово, образованное от существительного пруга
  — «пружина», восходящего к той же основе, что и впрягать, упругий.
  Отметим и родственное английское spring — «пружина».

https://krylov.lexicography.online/%D0%BF/%D0%BF%D1%80%D1%83%D0%B6%D0%B8%D0%BD%D0%B0
А вот Галина Цыганенко не считает слова прыгать и пружина однокоренными: пружина - от утраченного "пруга" (др-рус.глаг пругати (стрелять), пружитися - напрягаться), а "прыгать" - от утраченного сущ. прыгъ из праслав. prъgъ (ъ - ы)- скачок.
В любом случае, в далёком прошлом слова обозначали одно и то же - движение с напряжением.


Q:

trouble when deleting sublist from list in java

I have a function in java like
void remove(List<Var> vars, List<List<Value>> vals) {
    int index = calculateIndex();
    vars.removeAll(vars.subList(index, vars.size()));
    vals.removeAll(vals.subList(index, vals.size()));

}
always both lists have the same number of elements before enter the method, but, after removeAll  vars  have one element more than vals, index is between zero and the size of the lists, why could this be happening?

A:

If I understand correctly what you're trying to do, the code to remove the sublists should look like
int index = calculateIndex();
vars.subList(index, vars.size()).clear();
vals.subList(index, vals.size()).clear();

removeAll isn't the right tool for the job.  The purpose of removeAll is to look at all the elements in collection A, and remove elements in collection B that are equal to any element in collection A.  I believe it uses .equals to determine which elements are equal, not reference equality, which means that you could be removing some elements you don't intend to remove.  Furthermore, since the collection A in this case would be a sublist of collection B, so that they overlap, I wouldn't count on removeAll to function correctly anyway, although it might; using overlapping lists in this situation could lead to havoc.


Q:

Constraint and Index Declaration in Spring Data Neo4j 4.0.0

I just want to clarify of what I read in the Spring Data Neo4j 4.0.0 documentation. So, the provided way to configure index & unique constraint is just by defining it directly in the web console using Cypher query, and no more inside the application (like what @indexing tag does previously). Is it correct?
Thank you in advance and your response would be really appreciated!

A:

That's right. Index maintenance and configuration is not the responsibility of the OGM or Spring Data. It can be configured as you said via the shell, or you can use the Session/Neo4jTemplate.execute with your Cypher statement.


Q:

Is there a function to create appointment with Outlook Web add-ins?

I've created a form to select specific meeting hours. I call my add-ins from AppointmentOrganizerCommandSurface extension point. My form is in a displayDialog. When the user confirm his choice (time, date, details, ...), the dialog close and all his information are copied in Outlook Appointment composer form.
Is there a function I can call to create appointment when the dialog box close and the add-ins call event.completed()? To avoid the need to confirm the appointment again.

A:

(moving previous comment to an answer)
No, there's no JS API to 'send' the item from the addin. Generally, we want to let the user send from the native UI.
This is not what you asked, but would the on-send docs.microsoft.com/en-us/office/dev/add-ins/outlook/… be applicable in your scenario in that you trigger your dialog when user sends? REST/EWS is a possibility, but on desktop Outlook, what you set and save in the composer will take time to sync to the server.


Q:

Why doesn't Safe Haskell support Template Haskell?

The documentation for Safe Haskell states:

[...] Unfortunately Template Haskell can be used to subvert module boundaries and so could be used gain access to this constructor. [...] The use of the -XSafe flag to compile the Danger module restricts the features of Haskell that can be used to a safe subset. This includes disallowing unsafePerfromIO, Template Haskell,[...]

Used as a macro system that translates an AST to another AST, should it not be possible to simply restrict TH to the safe subset of Haskell, and also restrict the resulting AST to this subset?

A:

A bit further down on the page you linked:

TemplateHaskell — Is particularly dangerous, as it can cause side effects even at compilation time and can be used to access abstract data types. It is very easy to break module boundaries with TH.

The concern about side effects comes from the fact that TH allows you to run arbitrary IO computations at compile time using runIO. This would throw any hope of safety right out the window.
Breaking module boundaries means that using TH you can for example access data constructors even though a module did not export them.
See this repository for many examples of things that would be unsafe to allow in Safe Haskell, including an example of breaking module boundaries.
It might be possible that Template Haskell could be made safe if these features were disabled, however it would require significant changes to TH.


Q:

Jquery dialog box closes when I remove a table row

I am currently trying to remove a table row from a dialog box within jQuery, but whenever I try to delete the row, the dialog box closes immediately. Currently the PHP page generates the table and rows for the dialog box. Now to note, this code works perfectly fine without the PHP page call, but by adding the PHP aspect, the dialog box fails to stay open and remove the table row.
I'm not too sure how to tackle this as my experience with jQuery is very limited and I haven't been able to find something on the internet with a similar issue. Any pointers and suggestions are welcome. The ultimate goal is to be able to post from the dialog box form to a database and any help would be appreciated.
The code has been simplified so that the mysql query is not being used, but ultimately I want to be able to pass an unordered list of data into the php page to build a dynamic query and allow the user to submit the form thereafter.
Below is the code separated into two files...

PHP

   <!doctype html>

    <meta charset="utf-8" />
    <title>jQuery UI Dialog - Modal form</title>
      <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css" />

    <input type=button id="opener" value="PRESS BUTTON!" onclick="showTable('NOTHING', 'dialog', '2pass.php')">

pass.php

    <?php
echo "<form method = 'post'>";
echo "

        Name
        Notes
        Delete

";

echo "
";

      echo "
";
          echo "<input type='text' id='Name' value='Name' disabled>	";
          echo "<input type='text' name='notes'>	";
          echo 'Delete	';
      echo "
";

      echo "
";
          echo "<input type='text' id='Name' value='Name' disabled>	";
          echo "<input type='text' name='notes'>	";
          echo 'Delete	';
      echo "
";

      echo "
";
          echo "<input type='text' id='Name' value='Name' disabled>	";
          echo "<input type='text' name='notes'>	";
          echo 'Delete	';
      echo "
";

echo "
";
echo "
";
echo "</form>";
    ?>

A:

I figured it out. Firstly, you need to remove the show/hide components of the first function and then create a button instead of using the hyperlink reference. You will then need to set tr with an id.

Then a function in javascript to remove the row when you click the button.
   $(document.getElementById(row)).remove();

After that you should be all set.


Q:

What subquery can I use to filter data depending on strings?

I have created the following tables:
create table Person (

    id_person int,
    name varchar(255),
    primary key (id_person)
);

create table Picture (

    id_picture int,
    id_person int,
    country varchar(255),    //Shows in what country the picture has been taken
    primary key(id_picture),
    foreign key (id_person) references Person (id_person)
);

I want to execute a SELECT clause that filters the persons that just have taken pictures on the UK and in SPAIN. Not in other countries.
For example:
Table person
   id       name
-------------------
   1        Andrew
   2        Javi
   3        Kevin

Table picture
   id_picture      id_person      country
------------------------------------------------
      1               1           BELGIUM
      2               3           USA
      3               1           UK
      4               2           UK
      5               3           NORWAY
      6               2           SPAIN
      7               1           USA
      8               2           UK
      9               3           DENMARK

As the tables show, just the Person with the id_person = 2 has taken pictures just in UK and SPAIN.
How can I show the Persons that has taken pictures just on UK AND (not OR) SPAIN?
Following the example above, the output I would like to get would be:
    id_person      name
-------------------------------
      2            Javi

A:

try like below using distinct count()
select id_person,name from person p join picture p1 on p.id=p1.id_person
 where country in ('uk','spain')
 group by id_person,name
having count(distinct country)=2


Q:

How to View multiple images which retrieve with explode from a single row of table

I am using this below code to retrieve image name and explode and  to display. but the problem is the output. in out put view one extra blank image is displaying at the end in this below 75 id it consist of only 2 image name but it displaying 2 image with one blank image. Any help to solve this problem will be appreciate.
<?php
mysql_connect("localhost","root","");
mysql_select_db("test");
?>

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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>

<?php
$sql1=mysql_query("Select * from multiimg WHERE id=75");

$result=mysql_fetch_array($sql1);
/*$images = explode(",",$result['image']);

if(sizeof($images) > 0 ){
  foreach($images as $image){
   echo '' ;
   echo "
";
  }
}*/

$temp = explode(',',$result['image'] );

foreach($temp as $image){
    $images[]="photo/".trim( str_replace( array('[',']') ,"" ,$image ) );

}

//now your array of images cotaines to full source to each image

foreach($images as $image){
  echo "";
}
?>

A:

There are three things you can do to get around this. One is to trim/remove the comma at the end of your image inputs in your table and the others are:
EDIT Add a trim() first:
// (I don't think you have to escape the comma, but I do anyway)
$result['image'] = trim($result['image'],'\,');

// Explode array
$temp = explode(',',$result['image'] );

// use array_filter() to remove empty key/values
// I had this filtering $images, but probably best to
// filter the original exploded array $temp
$temp = array_filter($temp);

foreach($temp as $image){
    $images[]="photo/".trim( str_replace( array('[',']') ,"" ,$image ) );
}

foreach($images as $image){
  // Use an if here...you could use a root directory if defined previously.
  // Use whatever you like to check if the file exists
  if(is_file(ROOTDIR.$image))
      echo "";
}


Q:

Inconsistent UTF-8 encoding error HTML5

I have a problem with my HTML5 webpage that I haven't been able to research an answer for. Im using swedish letters in the text (åäö) and started out by using UTF-8 encodig as such:
<!DOCTYPE html>
<html lang = 'sv'>

<head>
    <title> </title>
    <meta charset='utf-8'>
    <meta name="description" content=' '>
    <link rel = 'stylesheet' href = './css/auroracss.css'>
</head>

This doesn't work for displaying the swedish letters in 3 out of 4 of my HTML5 pages, as I get the � chars when I preview. However, for the fourth page, using exactly the same head tag, the characters are displayed properly.
When I  switch out UTF-8 to ISO-8859-1 the opposite is true - displaying the characters will work fine for 3 out of 4 pages but the same one which displayed properly with UTF-8 will show
� chars when the ISO enconding is applied.
Everything validates.
I would like to stick to only one encoding choice here and not mix them even though that may be a quick fix. What is the cause for the problem?

A:

The 3 out of 4 pages are, in fact, ISO-8859-1 encoded (or maybe windows-1252). Assuming that the server does not announce character encoding in HTTP headers (as it seems, since your meta tag takes effect), you simply need to a) declare <meta charset=windows-1252> for them instead of claiming them to be UTF-8 encoded, or b) convert them to UTF-8 encoded.
The conversion, which is generally preferable (UTF-8 is widely regarded as the way to go, even declared as the only allowed encoding in some “living standards”). You can use e.g. Notepad++; using it, you simply open a file, use the program command to convert to UTF-8, and save the file.


Q:

How to install/deinstall a Windows service in win32?

I am trying to create a Win32 program that could delete temporary files in a specific path.
But I am actually in trouble with the install/uninstall functions in my code.
I'm working on Visual Studio 2012 and when I launch the debug process to test my code the debug window is closed immediately.
Maybe the problem is not coming from VS 2012 but from my code?
Here it is:
/*
** INCLUDES
*/
#include <Windows.h>
#include <stdio.h>

/*
** MACROS
*/
# define MY_SERVICE_NAME "DiskCleaner"
# define MY_SERVICE_DISPLAY_NAME "Nettoyeur de disque"
SERVICE_STATUS my_ServiceStatus;
SERVICE_STATUS_HANDLE my_ServiceStatusHandle;
BOOL bRunning;
BOOL InstallMyService();
BOOL DeleteMyService();
void WINAPI ServiceCtrlHandler(DWORD Opcode);
void WINAPI ServiceMain(DWORD argc, LPTSTR *argv);

/* INSTALL THE SERVICE */
BOOL InstallMyService()
{
    char strDir[MAX_PATH];
    SC_HANDLE hSCManager;
    SC_HANDLE hService;
    LPCTSTR lpBinaryPathName;

    GetCurrentDirectory(MAX_PATH, strDir);
    strcat(strDir, "\\AutoClean.exe");

    hSCManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS);

    if (hSCManager == NULL)
        return (FALSE);

    lpBinaryPathName=strDir;

    hService = CreateService(
        hSCManager,                             MY_SERVICE_NAME,
        MY_SERVICE_DISPLAY_NAME,                SERVICE_ALL_ACCESS,
        SERVICE_WIN32_OWN_PROCESS,
        SERVICE_AUTO_START,
        SERVICE_ERROR_NORMAL,
        lpBinaryPathName,
        NULL,
        NULL,
        NULL,
        NULL,
        NULL);

    if (hService == NULL)
        return (FALSE);

    CloseServiceHandle(hService);
    return (TRUE);
}

/* DELETE THE SERVICE */
BOOL DeleteMyService()
{
    SC_HANDLE hSCManager;
    SC_HANDLE hService;

    hSCManager = OpenSCManager (NULL, NULL, SC_MANAGER_ALL_ACCESS);

    if (hSCManager == NULL)
        return (FALSE);

    hService = OpenService (hSCManager, MY_SERVICE_NAME, SERVICE_ALL_ACCESS);

    if (hService == NULL)
        return (FALSE);

    if (DeleteService(hService) == NULL)
        return (FALSE);

    if (CloseServiceHandle(hService) == NULL)
        return (FALSE);

    return (TRUE);
}

/* SERVICE EVENT HANDLER */
void WINAPI ServiceCtrlHandler(DWORD Opcode)
{
    switch (Opcode)
    {
    case SERVICE_CONTROL_PAUSE:
        my_ServiceStatus.dwCurrentState = SERVICE_PAUSED;
        break;
    case SERVICE_CONTROL_CONTINUE:
        my_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
        break;
    case SERVICE_CONTROL_STOP:
        my_ServiceStatus.dwWin32ExitCode = 0;
        my_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
        my_ServiceStatus.dwCheckPoint = 0;
        my_ServiceStatus.dwWaitHint = 0;
        SetServiceStatus (my_ServiceStatusHandle, &my_ServiceStatus);
        bRunning = FALSE;
        break;
    case SERVICE_CONTROL_INTERROGATE:
        break;
    default:
        break;
    }
    return;
}

/* SERVICE ENTRY POINT */
void WINAPI ServiceMain(DWORD argc, LPTSTR *argv)
{
    DWORD Status;
    DWORD SpecificError;

    my_ServiceStatus.dwServiceType = SERVICE_WIN32;
    my_ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
    my_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
    my_ServiceStatus.dwWin32ExitCode = 0;
    my_ServiceStatus.dwServiceSpecificExitCode = 0;
    my_ServiceStatus.dwCheckPoint = 0;
    my_ServiceStatus.dwWaitHint = 0;
    my_ServiceStatusHandle = RegisterServiceCtrlHandler(MY_SERVICE_NAME, ServiceCtrlHandler);

    if (my_ServiceStatusHandle == (SERVICE_STATUS_HANDLE)0)
    {
        return;
    }

    my_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
    my_ServiceStatus.dwCheckPoint = 0;
    my_ServiceStatus.dwWaitHint = 0;
    SetServiceStatus(my_ServiceStatusHandle, &my_ServiceStatus);
    bRunning = TRUE;

    while (bRunning)
    {
        printf("\nOK just to test if this part works well before implementing my cleaning part\n");
    }
    return;
}

/* ENTRY POINT */
int main(int argc, char* argv[])
{
    if (argc > 1)
    {
        if (strcmp(argv[1], "-i"))
        {
            if (InstallMyService())
                printf("\nService successfully installed\n");
            else
                printf("\nService installtion unsuccessfull\n");
        }
        else if (strcmp(argv[1], "-d"))
        {
            if (DeleteMyService())
                printf("\nService successfully deleted\n");
            else
                printf("\nService delete unsuccesfull\n");
        }
        else
            printf("\nUsage incorrect\n");
    }
    else
    {
        SERVICE_TABLE_ENTRY DispatchTable[]={{MY_SERVICE_NAME, ServiceMain}, {NULL, NULL}};
        StartServiceCtrlDispatcher(DispatchTable);
    }

    return (EXIT_SUCCESS);
}

A:

I've corrected my code and it works now. This is the entire solution :
#include <Windows.h>
#include <stdio.h>

/*
** MACROS
*/
# define MY_SERVICE_NAME "DiskCleaner"
# define MY_SERVICE_DESCRIPTOR "Nettoyeur de fichiers temporaires"
# define MY_SERVICE_BIN_NAME "DiskCleaner.exe"

/*
** GLOBALS
*/
SERVICE_STATUS g_ServiceStatus;
SERVICE_STATUS_HANDLE g_ServiceStatusHandle;

/*
** INSTALL THE SERVICE
*/
BOOL InstallMyService()
{
  char strDir[MAX_PATH + 1];
  SC_HANDLE schSCManager;
  SC_HANDLE schService;
  LPCTSTR lpszBinaryPathName;

  GetCurrentDirectory(MAX_PATH, strDir);
  strcat(strDir, "\\"MY_SERVICE_BIN_NAME);
  if ((schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)) == NULL)
    return (TRUE);
  lpszBinaryPathName = strDir;
  schService = CreateService(schSCManager, MY_SERVICE_NAME, MY_SERVICE_DESCRIPTOR,
                             SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS,     SERVICE_AUTO_START, SERVICE_ERROR_NORMAL,
                             lpszBinaryPathName, NULL, NULL, NULL, NULL, NULL);
  if (schService == NULL)
    return (FALSE);
  CloseServiceHandle(schService);
  return (TRUE);
}

/*
** DELETE THE SERVICE
*/
BOOL DeleteMyService()
{
  SC_HANDLE schSCManager;
  SC_HANDLE hService;

  if ((schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS)) == NULL)
return (FALSE);
  if ((hService = OpenService(schSCManager, MY_SERVICE_NAME, SERVICE_ALL_ACCESS)) == NULL)
    return (FALSE);
  if (!DeleteService(hService))
    return (FALSE);
  if (!CloseServiceHandle(hService))
    return (FALSE);
  return (TRUE);
}

/*
** SERVICE EVENT HANDLER
*/
void WINAPI ServiceCtrlHandler(DWORD Opcode)
{
  switch (Opcode)
  {
    case SERVICE_CONTROL_PAUSE:
       g_ServiceStatus.dwCurrentState = SERVICE_PAUSED;
       break;
    case SERVICE_CONTROL_CONTINUE:
       g_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
       break;
    case SERVICE_CONTROL_STOP:
       g_ServiceStatus.dwWin32ExitCode = 0;
       g_ServiceStatus.dwCurrentState = SERVICE_STOPPED;
       g_ServiceStatus.dwCheckPoint = 0;
       g_ServiceStatus.dwWaitHint = 0;
       SetServiceStatus (g_ServiceStatusHandle, &g_ServiceStatus);
       break;
    case SERVICE_CONTROL_INTERROGATE:
       break;
    default:
       break;
   }
}

/*
** SERVICE MAIN ENTRY
*/
void WINAPI ServiceMain(DWORD argc, LPTSTR *argv)
{
  g_ServiceStatus.dwServiceType = SERVICE_WIN32;
  g_ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
  g_ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
  g_ServiceStatus.dwWin32ExitCode = 0;
  g_ServiceStatus.dwServiceSpecificExitCode = 0;
  g_ServiceStatus.dwCheckPoint = 0;
  g_ServiceStatus.dwWaitHint = 0;
  g_ServiceStatusHandle = RegisterServiceCtrlHandler(MY_SERVICE_NAME, ServiceCtrlHandler);
  if (g_ServiceStatusHandle == (SERVICE_STATUS_HANDLE)0)
    return;
  g_ServiceStatus.dwCurrentState = SERVICE_RUNNING;
  g_ServiceStatus.dwCheckPoint = 0;
  g_ServiceStatus.dwWaitHint = 0;
  SetServiceStatus(g_ServiceStatusHandle, &g_ServiceStatus);

}

/*
** MAIN ENTRY
*/
int main(int argc, char* argv[])
{
  if (argc > 1)
  {
    if (!strcmp(argv[1], "-i"))
       if(InstallMyService())
           printf("\nService correctly installed\n");
   else
       printf("\nService uncorrectly installed\n");

    else if (!strcmp(argv[1], "-d"))
       if(DeleteMyService())
       printf("\nService correctly deleted\n");
   else
       printf("\nService uncorrectly deleted\n");
  }
  else
  {
     SERVICE_TABLE_ENTRY DispatchTable[]={{MY_SERVICE_NAME, ServiceMain}, {NULL, NULL}};
 StartServiceCtrlDispatcher(DispatchTable);
  }
  return (EXIT_SUCCESS);
}


Q:

Real solutions of the polynomial

Let $a, b, c$ be distinct real numbers. Then find the number of real solutions of
$(x − a)^5 + (x − b)^3 + (x − c)$
I can't understand how there will be any solution. The polynomial is not equated with anything.

A:

Assuming you equated it to $0$,
$$\lim_{x\to -\infty}f(x)=-\infty \text{ and }  \lim_{x\to \infty}f(x)=\infty$$
$$f'(x)=5(x-a)^4+3(x-b)^2+1>0\implies \text{Exactly one real root }$$
This is because the function is strictly increasing. It shall cross $x$-axis only one time.
Therefore, only one solution is possible. Perhaps a graph would help.
It is highly likely that this is the case.


Q:

Ag-grid - disabling Side button

fairly Simple question regarding the new balham theme on Ag-grid.
Id like to disable the side button and the tool panel completely as shown in the link below:
https://www.ag-grid.com/javascript-grid-tool-panel/
I can hide the tool panel, but cannot hide the side button labelled 'Columns' and was wondering if there was a simple way to do so? Many thanks

A:

set the property showToolPanel to false in ag-grid
[showToolPanel]="false"

<ag-grid-angular
    #agGrid
    style="width: 100%; height: 100%;"
    id="myGrid"
    class="ag-theme-balham"
    [columnDefs]="columnDefs"
    [defaultColDef]="defaultColDef"
    [enableSorting]="true"
    [showToolPanel]="false"
    [enableFilter]="true"
    (gridReady)="onGridReady($event)"
    ></ag-grid-angular>

and if you completely want to remove the columns tool panel then you can override the css
.ag-theme-balham .ag-tool-panel{
    visibility: hidden;
}


Q:

Black Holes and Einstein Field Equations

I recently watched a video where Michio Kaku argues that there must be something fundamentally wrong with the theory of General Relativity because it gives time t=0 as a solution at the centre of a Black Hole. He calls this non-sense and also says that Einstein's Field Equations break down when applied to Black Holes. What exactly does he mean by this?
As far as I've read, Einstein's Field Equations govern relativistic gravity. Why do I also read in multiple articles that they aren't good for Black Holes?

A:

General relativity is a theory that tells us the geometry of spacetime. However it predicts that in some situations the geometry of spacetime is undefined - this happens when we get a singularity. There is a singularity at the centre of a black hole, and the Big Bang was also a singularity.
So we have the odd situation that the theory of general relativity predicts that there are cases where general relativity doesn't work (because a singularity occurs). Because of this it is widely believed that general relativity is an effective theory i.e. it is an approximation to some (even!) more complicated theory. It's widely believed that this deeper theory will be some form of quantum gravity. However we don't know what that new theory is, though there are several contenders.
But this doesn't mean that general relativity is nonsense. It just means there are circumstances in which GR will give a nonsensical description (i.e. singularities), and that happens when we've tried to push general relativity beyond its limits. If we stay away from singularities we expect GR to work eseentially perfectly.
The vast majority of our physical theories are effective theories - indeed I can't think of a single exception. All theories are based on some approximations, and when those approximations break down the theory ceases to be useful. For example Newtonian mechanics is an approximation to special relativity, and special relativity is an approximation to general relativity. However Newtonian mechanics is still extremely useful in everyday life (which is why it's taught at school).


Q:

переменная принимает предыдущее значение

Пишу скрипт,который бы принимал первым параметром путь к папке и копировал ее содержимое в другую,заданную потом.Есть командные символы для первого параметра, это "/?" по которому выводится краткая информация о задаче,проверка на существование и собственно часть кода,где разбирается путь,если он существует и введен правильно.Если первый параметр точка,то работаем с текущей папкой.
@echo off

setlocal
set flag=false

if "%1" EQU "" (
    set flag=true

    echo Не задан основной параметр. Введите /? для справки
    )

if "%1" EQU "/?" (
    set flag=true
    echo командный файл копирования файлов заданного типа с помощью команды copy_   из одной папки в другую.
    echo В качестве первого обязательного параметра должно быть задано имя исходной папки
    echo для текущей папки задается символ ".". Вторым необязательным параметром является тип файла
    echo image - для файлов изображений с расширениями .bmp , .gif, .jpg и .png
    echo prog - для программных файлов с расширениями .com и .exe
    echo text - для текстовых файлов с расширениями .doc и .txt
    echo all - для всех файлов.
    echo Если второй параметр не задан, для него предполагается значение all.
    echo В командном файле выдается запрос на ввод имени папки, в которую будут копироваться файлы
    echo для текущей папки задается символ "." Имена исходной папки и папки, в которую будет производиться копирование
    echo не должны совпадать. Если папка с заданным именем не существует, она создается с помощью команды mkdir.
    echo Для значений параметров image, prog или text должно быть выведено общее количество
    echo скопированных файлов соответствующего типа изображений, программных или текстовых
    )

 if "%1" NEQ "." (
    echo "%flag%"
    if "%flag%" EQU "false" (
        if exist "%1" (
            echo Путь существует и не равен командным символам
        )else (
            echo Путь не существует
            )
        )
)else (
    echo Текущий путь %cd%
    set/p namefolder="Введите полное имя дериктории для копирования"
    echo %namefolder%
    if exist "%namefolder%" (
        echo Путь существует
    )else (
        echo Пути не существует
        )

)

endlocal

У меня странно работает переменная вот тут set/p namefolder="Введите полное имя дериктории для копирования", если первый аргумент точка.  Когда вызываю bat в первый раз, ввожу строку,например "www", то значение namefolder пустое, а если вызываю второй раз,то какую бы строку не ввел,переменная принимает предыдущее значение - "www". И так по кругу,в нее почему то записывается не текущее значение,которое я ввел в консоль, а значение,полученное на предыдущей итерации вызова. Совсем не понимаю,почему так это работает(.Помогите пожалуйста

A:

Вложенные if - зло, еще большее зло - сами командные сценарии, так как уже давным-давно существуют более функциональные средства вроде PowerShell или на худой конец WSH. Но раз уж пошла такая пьянка, то стоит сделать еще несколько замечаний.Отказ от процедурного стиля в данном случае превращает код в "портянку". Во-вторых, стоит отметить: есть одно общее условие, при котором должны копироваться все файлы, а именно а) при отсутствии второго аргумента, передаваемого командному сценарию и б) при указании all. Учитывая все это, код можно представить так:
@echo off
  setlocal enabledelayedexpansion
    set "argc=0" % rem : счетчик аргументов сценария
    for %%i in (%*) do set "argv.!argc!=%%~i" && set /a "argc+=1"
    rem условия вывода справки или выхода за пределы допустимого количества аргументов
    if "!argv.0!" equ "/?" goto:man
    if !argc! lss 1 goto:man
    if !argc! gtr 2 goto:man
    rem если все условия соблюдены, вызываем процедуру копирования файлов
    if !argc! equ 1 call:copyFiles
    if !argc! equ 2 call:copyFiles !argv.1!
  endlocal
exit /b

:man
  echo:Собственно, здесь помещается справочное руководство.
exit /b

:copyFiles
  if not exist "!argv.0!\*" echo:Неправильный путь.&goto:eof
  set /p "dest=Укажите папку назначения: "
  if "!argv.0!" equ "!dest!" echo:Невозможно копировать путь в самого себя.&goto:eof
  if "%~1" equ "" xcopy "!argv.0!" "!dest!" /i>nul
  if /i "%~1" equ "all" xcopy "!argv.0!" "!dest!" /i>nul
  rem прочие условия
  set "image=.BMP;.GIF;.JPG;.PNG"
  set "prog=.COM;.EXE"
  set "text=.DOC;.TXT"
  for %%i in (image prog text) do (
    if /i "%~1" equ "%%~i" set "found=true"
  )
  if not defined found echo:Непредусмотренный тип данных.&goto:eof
  for %%i in ("!%~1:;=";"!") do xcopy "!argv.0!\*%%~i" "!dest!" /i 2>nul >nul
exit /b


Q:

Оттого/от того, неважно/не важно и тире перед "не"

Как правильно пишется в приведённых ниже случаях:

Тяжело удержать себя от того, чтобы не... (сделать что-то).

Вопрос: "от того" или "оттого"?

У всех нас была компания. Дворовая ли, школьная ли, университетская ли – не важно.

Как здесь будет правильно: "не важно" или "неважно"? Насколько уместно тире?

A:

Тяжело удержать себя (от чего?) от того, чтобы не (см.
"Оттого" или "от того"?)
Ваш вариант корректен (см. "Это неважно" или "Это не важно")


Q:

How can users write a bio on their profile page?

I'd like my users to be able to write a bio on their profile page. Therefore, I added a long text field called 'Bio' to the user accounts. I created a view that shows the user's bio and wanted to add a link to only let the user edit his/her bio. Unfortunately, I only found a link that redirects the user to a page where he/she can edit his/her whole profile - which isn't exactly what I want.
Did I miss something?
I tried to solve this in another way. I created a content type called 'Bio' and a rule that creates a 'Bio' node with title My bio automatically when a user is created. Users don't have permission to add another bio, but they can edit their own 'standard' one. Now, I don't want the title field to be displayed on the edit form, because I'd like the titles to remain My bio.
How can I do this?

A:

Re: the second/existing option, if you have a custom module already, could do a form_alter() on the node form to remove the title field.  Or, you could look into the auto_nodetitle module that does this for you:

"auto_nodetitle" is a small and efficient module that allows hiding of
  the content title field in the form. To prevent empty content title
  fields one can configure it to generate the title by a given pattern.
When the token module is installed it's possible to use various node
  data for the auto generated title - e.g. use the text of a CCK field
  (since 5.x).
Advanced users can also provide some PHP code, that is used for
  automatically generating an appropriate title.

If instead you wanted to stay/go back to the first option, you could create a menu link/path like user/%/edit/bio that presents the user_profile_form that has been form_alter()ed to show only the bio field based upon the fact that it was called from this new path.


Q:

How to pass extra parameter on AJAX call of jQuery DataTable

I pass the parameters using the following code as indicated on DataTable Documentation.

View:
$('#example').dataTable( {
      "ajax": {
           "url": "/Student/GetStudents",
           "data": function ( d ) {
               d.test= "some data";
           }
      }
});

Controller:
public ActionResult GetStudents(JQueryDataTableParamModel param, string test)
{
    //code omitted for brevity

    return Json(new
    {
        sEcho = param.sEcho,
        iTotalRecords = allRecords.Count(),
        iTotalDisplayRecords = filteredRecords.Count(),
        aaData = result
    },
    JsonRequestBehavior.AllowGet);
}

Although the "test" parameter is passed to the Controller, the values in the "param" parameter are null or 0 and that causing the datatable returns null data. On the other hand, if I use the following line instead of AJAX call in datatable parameters, all the values of param are passed to the Controller properly (but using AJAX call and this line also causes error). I need to pass extra parameter to the Controller and have to use AJAX call. How can I pass it while passing param values?
"ajaxSource": "/Student/GetStudents",

A:

Your javascript code:
$('#example').dataTable( {
      "ajax": {
           "url": "/Student/GetStudents",
            type: 'GET',
            data: {
                    test1: "This test1 data ",
                    test2: "This test2 data"
                }
        }
});

public ActionResult GetStudents(JQueryDataTableParamModel param, string test)
{
    //code omitted for brevity

     //printing in params in controller with asp.net code.
     print_r("Data from" ,param.test1 ,param.test2);

    return Json(new
    {
        sEcho = param.sEcho,
        iTotalRecords = allRecords.Count(),
        iTotalDisplayRecords = filteredRecords.Count(),
        aaData = result
    },
    JsonRequestBehavior.AllowGet);
}

A:

Finally I solved the problem by using fnServerData method as shown below.
"ajaxSource": "/Student/GetStudents",

//fnServerData used to inject the parameters into the AJAX call sent to the server-side
"fnServerData": function (sSource, aoData, fnCallback) {
    aoData.push({ "name": "test", "value": "some data" });
    $.getJSON(sSource, aoData, function (json) {
        fnCallback(json)
    });
},

...

Anyway, thanks a lot for the useful answers. Voted+ the useful ones...


Q:

VB.NET linq extension methods such as ToList not working with generics

In a VB.NET class file, I'm trying to use extension methods such as ToList(), where the generic parameter is populated with what I know to be the subclass, in this context.
Dim specificOrders = request.Orders _
.Where(Function(x) x.GetType().Equals(GetType(SpecificOrderType))) _
.ToList(Of SpecificOrderType)()

However, I'm getting the error message "extension method is not generic or has no type parameters available". Any ideas as to why this is?
This method should be in the System.Linq namespace - I have it open and referenced in the file.

A:

You don't use Where to filter by type. That's what the OfType method is for. It filters and casts:
Dim specificOrders = request.Orders.
                             OfType(Of SpecificOrderType)().
                             ToList()

In that case, OfType returns an IEnumerable(Of SpecificOrderType) and calling ToList on that returns a List(Of SpecificOrderType).  That's how ToList works.  It simply create a List(Of T) with the same generic type as the IEnumerable(Of T) that it's called on.
If you were going to use Where, you would use Cast to go from the base type to SpecificOrderType:
Dim specificOrders = request.Orders.
                             Where(Function(x) x.GetType().Equals(GetType(SpecificOrderType))).
                             Cast(Of SpecificOrderType)().
                             ToList()

One point to note about OfType is that it will match any item that can be cast as the specified type. That is usually what you want and probably the result that your original code would produce but it's worth noting that any item that was of a type that inherited SpecificOrderType would be excluded by your original code but included using OfType.


Q:

Odd even number printing using thread

Odd even number printing using thread.Create one thread class, two instance of the thread. One will print the odd number and the other will print the even number.
I did the following coding. But it comes to dead lock state. Can some one please explain what might be the reason for that?
public class NumberPrinter implements Runnable{
private String type;
private static boolean oddTurn=true;

public NumberPrinter(String type){
    this.type=type;
}
public void run() {
    int i=type.equals("odd")?1:2;
    while(i<10){
        if(type.equals("odd"))
            printOdd(i);
        if(type.equals("even"))
            printEven(i);
        i=i+2;
    }

}

private synchronized void printOdd(int i){
    while(!oddTurn){
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    System.out.println(type + i);
    oddTurn=false;
    notifyAll();
}

private synchronized  void printEven(int i){
    while(oddTurn){
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    System.out.println(type + i);
    oddTurn=true;
    notifyAll();

}

public static void main(String[] s){
    Thread odd=new Thread(new NumberPrinter("odd"));
    Thread even=new Thread(new NumberPrinter("even"));
    odd.start();
    even.start();

}
}

Out Put:
odd1
even2

then comes to deadlock!!!!!!
Thanks for your help.

A:

You're waiting and notifying different objects (monitors).
The idea is that you can call obj.wait() to wait for someone to do obj.notify(), while you're doing objA.wait() and objB.notify().
Change your printOdd method to something like
private void printOdd(int i) {
    synchronized (lock) {                        // <-------
        while (!oddTurn) {
            try {
                lock.wait();                     // <-------
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println(type + i);
        oddTurn = false;
        lock.notifyAll();                        // <-------
    }
}

and the printEven method similarly.
Then provide the NumberPrinter with a lock object:
Object lock = new Object();
Thread odd = new Thread(new NumberPrinter("odd", lock));
Thread even = new Thread(new NumberPrinter("even", lock));

Output:
odd1
even2
odd3
even4
odd5
even6
odd7
even8
odd9

A:

There are a lot of bugs in the code.
First of all, the synchronized statements have no effect whatsoever. You create two thread instances, and each calls only its own methods. synchronized is only useful if another thread can call a method.
Then notifyAll() has no effect for the same reasons. odd.notifyAll() doesn't reach even hanging in the wait().
So what you need is another object which contains the state and which both threads can see and use. Use synchronized, wait() and notifyAll() on that third instance.


Q:

filter divs by class - jquery

there are several list filters in jquery (quicksand, filterprojects, etc.), but I am looking to filter divs by class.
I want the same functionality of the above - you select a menu item attached to a class and the other items fade out.
Anyone seen anything like this anywhere?

A:

I ended up using:
    $("#box").click(function() {
$(".box").fadeIn();

});
$("#logo").click(function() {
 $(".box").fadeIn();
$(".box:not(.logo)").fadeOut();

});
$("#print").click(function() {
 $(".box").fadeIn();
$(".box:not(.print)").fadeOut();

});
$("#web").click(function() {
 $(".box").fadeIn();
$(".box:not(.web)").fadeOut();

});
and then:

All

Logo

Print

Web

Illustration

Which works great, except due to the jquery.masonry.js layout, the areas where the div fades out, there is now an empty spot. I need to figure out how to reload masonry for each onclick so that the remaining items are shuffled into a new layout.
thoughts on that?
and thanks for the help!


Q:

Сложности с переходом с python 2.x на python 3.x

def _load_config(self):
    for fn in CONFIG_FILES:
        fn = os.path.expanduser(fn)
        if os.path.exists(fn):
            raw = open(fn, "rb").read().strip().decode("utf-8")
            items = [[x.strip() for x in line.split("=", 1)] for line in raw.split("\n")]
            return dict(items)
    return None

Есть данная функция, написана на python 2.x,возникла задача переписать на 3.
При открытии файла выбивает ошибку, я переписал данную строку вот так
raw = open(bytes(fn, "rb").read().strip().decode("utf-8"))

Дело в том что Лутца я поверхностно пробежал и чтоб разобраться что к чему уйдет еще пара дней, кто может подсказать по этому вопросу?
Пару моих вопросов:
 1. Правильно ли приводить к битам, когда работаешь с файлами(в данном случаи файл содержит только текст) и сокетом?
 2. Второй вопрос по поводу кодировки, если я по умолчанию указал кодировку
# encoding=utf-8

Нужно ли делать декодирование при открытии, если файл имеет иную кодировку?

A:

Хорошая новость: первый пример кода, который вы привели, работает как есть как на Python 2 так и 3.
Плохая новость: все последующие примеры показывают наличие искажённого понимания с вашей стороны как с текстом в Питоне работать—это хуже чем, если бы вы ничего не знали. Например, декларация кодировки типа # -*- coding: utf-8 -*- наверху Питон-файла не имеет никакого отношения к кодировке других файлов—если вы не смотрите на буквальные не-ascii буквы (такие как u"абв") в вашем исходном коде (*.py файлы), то забудьте о ней:

если это текст во внешнем файле—она не имеет отношения
если текст пришёл из сети—она не имеет отношения
если текст передали как параметр в функцию—она не имеет отношения
если значение в переменной—она не имеет отношения
итд

При открытии файла выбивает ошибку

Если приведённый код (open(fn, "rb")) не выбрасывает ошибку на Питоне 2, то этот код не будет выбрасывать ошибку на Питоне 3. То есть у вас может быть проблема с тем как CONFIG_FILES определяется, но сам по себе код open(fn, "rb") должен работать на Питоне 2 и 3 без изменений (внутренняя реализация поменялась, но снаружи это не должно быть в данном случае заметно).