text:
Q: how do integrate $\int_0^{2 \pi} \frac{d\theta}{2+\sin \theta +\cos \theta }$ in the complex plane How do I integrate $$\int_0^{2\pi} \frac{d\theta}{2+\sin \theta +\cos \theta }?$$
I know that sine and cosine can be written in the form
$$ \int_C \frac{dz}{2+\frac{e^{i\theta}-e^{-i\theta}}{2i}+\frac{e^{i\theta}+e^{-i\theta}}{2} ie^{i\theta}},$$
but once the operations are carried out, the remaining polynomial cannot find a way to relate it to the Cauchy integral formula.

A: Only meant to be a guide, you need to do the rest. You should be able to do this in an elementary fashion using $\sin \theta + \cos \theta = \sqrt 2 \sin(\theta + \frac {\pi} 4)$ and then applying Weierstrass substitution.


text:
Q: working with Permutationed list (making pass_word list) i want to create a pass_word list let's assume i have created a Permutationed list for example :
@@
@#
#@
##

and then i want to add another chars to it (for ex : a,b) a,b is named special chars in this code and #@ are added chars
so i want finally get this list :
ab@@ , ab@#,ab#@,ab## , ba@@, .... a@#b,...,b##a , ... , ba##

Note : I don't want any special characters get duplicated for ex i
  don't want aa@# or bb#@ (a,b can't be duplicated  because they are
  special chars #or @ can be duplicated because they are added chars )

codes :
    master_list=[]
l=[]

l= list(itertools.combinations_with_replacement('@#',2)) # get me this list :[(@,@),(@,#),(#,@),(#,#)]

for i in l:
 i = i+tuple(s)  # adding special char(1 in this example) to created list
 master_list.append(i)

print (master_list) # now i have this list : [(@,@,1),(@,#,1),....(#,#,1)

now if i can get all permutation of master_list my problem can be solved but i can't do that

A: i solved my problem , my idea : first of all i generate all posiable permutation of added chars**(#,@)** and save them to a list and then create another list and save specific chars (a,b) to it now we have to list just we need to merge them and in finally use permute_unique function
 def permute_unique(nums):
        perms = [[]]
        for n in nums:
            new_perm = []
            for perm in perms:
                for i in range(len(perm) + 1):
                    new_perm.append(perm[:i] + [n] + perm[i:])
                    # handle duplication
                    if i < len(perm) and perm[i] == n: break
            perms = new_perm
        return perms

   l= list(itertools.combinations_with_replacement(algorithm,3))

    for i in l:
     i = i+tuple(s) # merge
     master_list.append(i)

print(list(permute_unique))

A: You can just combine the combinations_with_replacement of the "added" chars with all the permutations of those combinations and the "special" characters:
>>> special = "ab"
>>> added = "@#"
>>> [''.join(p)
     for a in itertools.combinations_with_replacement(added, 2)
     for p in itertools.permutations(a + tuple(special))]
['@@ab',
 '@@ba',
 '@a@b',
 ...
 'a@b@',
 'ab@@',
 ...
 '#@ab',
 '#@ba',
 ...
 'ba##',
 'ba##']

If you want to prevent duplicates, pass the inner permuations through a set:
>>> [''.join(p)
     for a in itertools.combinations_with_replacement(added, 2)
     for p in set(itertools.permutations(a + tuple(special)))]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cordova Webview and Splashscreen dont work I installed Cordova plugin:
cordova-plugin-crosswalk-webview

Everything works fine with this plugin, but then I installed
cordova plugin add cordova-plugin-splashscreen

for creating splashscreen. In file config.xml in widget section I put this code:
<preference name="SplashScreen" value="screen" />
<preference name="SplashScreenDelay" value="5000" />
<preference name="AutoHideSplashScreen" value="true" />
<preference name="ShowSplashScreenSpinner" value="false" />

Build was successful. After start application it shows splashscreen (for 5 second), but when splashscreen is disappear, it shows just white page instead my app. After I remove webview plugin - everyting works fine. How can I fix that problem?


text:
Q: numpy version error when importing tensorflow I have executed pip install for tensorflow.
Under the python command line environment, when I tried
import tensorflow as tf

I met the following errors:
RuntimeError: module compiled against API version 0xa but this version of numpy is 0x9
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/__init__.py", line 23, in <module>
    from tensorflow.python import *
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/__init__.py", line 49, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 28, in <module>
    _pywrap_tensorflow = swig_import_helper()
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/pywrap_tensorflow.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow', fp, pathname, description)
ImportError: numpy.core.multiarray failed to import

I have checked my numpy version using print numpy.__version__. It showed "1.8.2". So, what should I do now? Thanks!

A: From the error, it looks like you're running python 2.7 from usr/local/bin. There is a mismatch problem between your numpy version and tensorflow installation. I'd recommend you to install anaconda since it will make sure that correct version of tensorflow that is compatible with your numpy version be installed.
Once you have anaconda, then do:
conda install -c conda-forge tensorflow


text:
Q: Can I make it so that a fanfare plays when my code compiles in Eclipse (Java)? I always feel so pleased when my code compiles and I've always dreamed of the Final Fantasy VII victory theme or Zelda treasure chest theme playing along with the successful compilation.
I've only been programming for two weeks (unless you include my 8 years of HTML on Neopets).  Please tell me what I need to do to make my dream come true.
Edit -- I know that many of you will probably think that this will become annoying after about three compiles, but trust me, it's fine. I've had Captain Falcon shout "YES" at me every time I've received a text for the past year and I still think it's hilarious.

A: I am not aware of a "native" way of having a music played after a successful build. However, if I really need to have that (you have to consider that after some work, it will be really annoying), I would consider the following ideas:
1: Trying to find a builder (Project properties > Builders) that allows specific task after the compilation of a project;
2: Use Ant to compile your project. Add a task, for example sound that will play a different song regarding the result of the build:
<target name="fun" if="fun" unless="fun.done">
  <sound>
    <success source="${user.home}/sounds/bell.wav"/>
    <fail source="${user.home}/sounds/ohno.wav" loops="2"/>
  </sound>
  <property name="fun.done" value="true"/>
</target>

3: Use an Continuous Integration server, such as Hudson (oops, Jenkins ;) ) and add a plugin to play a sound after a build.

Just a personal note: I think this can be a good idea to have a specific sound / music played after a failed build done by a IC server...

A: The problem is that eclipse does not have a real build cycle for java.

*

*Eclipse works on the abstract syntax tree of your java code

*The editor state is dumped into a .java and .class file on save

So "after compiling" would mean "every file save that doesn't cause the project to contain errors afterwards". I don't think there is an option for that.


text:
Q: REST API naming convention Given this URI:
/myapp/books/status/{status}

For example :
/myapp/books/status/new

This will return all books flagged with this status.
What would be a proper URI for return all books NOT flagged with a specific status?
/myapp/books/notstatus/new

I would like to return a collection of all books except the ones with a certain status..
Please advice...

A: I'd recommend using query parameters for filtering status for your books list resource:
myapp/books/?status=new
myapp/books/?status=not_new

Both queries return the same resource (a list of books), you're just filtering out the types you want in that list, so the use of a query param makes sense.  I use the not_ prefixed to the status to do inverse queries, but you can use whatever convention you want.
REST doesn't require you to avoid get parameters (it seems some people think get parameters are voodoo), just don't use them to make faux-RPC calls :)
The reason I like this method is it opens up your options later  when you might want to add a check for all books with multiple pieces of info such as ones that have a status of new and condition of good.
    myapp/books/?status=new&condition=good

If you try to break that down into url segments instead of query params, it gets messy very quickly.

A: As I know there are a couple of ways, and all of them are correct (from REST perspective):

*

*Query string parameters

myapp/books?status=new

*

*OData queries
http://www.odata.org/documentation/uri-conventions

myapp/books?$filter=status eq 'new'

*

*In URI, also good

myapp/books/status/{status}

Personally I prefer either Query string or OData.
OData is especially good when technology specific (ASP.NET Web API, WCF Data services, by non-Microsofts should also be equivalents) helps to avoid writing any code for such queries.
It allows to expose prefiltered collection and then filter it from client with such query. In such scenarios when exposing collections, I'm using OData queries.


text:
Q: Azure service bus fails connecting to kubernetes docker When I try to access my sb endpoint in my local machine/local docker it fetches the data without any issue but when I try to access it across kubernetes cluster(docker) the connection to socket fails.
Is there any SDK/configs/dependencies that I would have to install in my docker to access the SB. The error looks like below.
Found /start.sh, running...
Initializing Client...
[INFO] [2020-07-14 16:00:06] 'eventhub.pysdk-b0fab61b': Created the Event Hub client
[INFO] [2020-07-14 16:00:06] Connection b'bc610657-4dbf-4bc2-aa39-38b6889e6047' state changed from <ConnectionState.UNKNOWN: 999> to <ConnectionState.START: 0>
[INFO] [2020-07-14 16:00:16] b'Failure: select failure.' (b'/data/src/vendor/azure-uamqp-c/deps/azure-c-shared-utility/adapters/socketio_berkeley.c':b'wait_for_connection':370)
[INFO] [2020-07-14 16:00:16] b'wait_for_connection failed' (b'/data/src/vendor/azure-uamqp-c/deps/azure-c-shared-utility/adapters/socketio_berkeley.c':b'socketio_open':770)
[INFO] [2020-07-14 16:00:16] b'Closing tlsio from a state other than TLSIO_STATE_EXT_OPEN or TLSIO_STATE_EXT_ERROR'
[INFO] [2020-07-14 16:00:16] b'Invalid tlsio_state. Expected state is TLSIO_STATE_OPENING_UNDERLYING_IO.' (b'/data/src/vendor/azure-uamqp-c/deps/azure-c-shared-utility/adapters/tlsio_openssl.c':b'on_underlying_io_open_complete':760)
[INFO] [2020-07-14 16:00:16] b'Failed opening the underlying I/O.' (b'/data/src/vendor/azure-uamqp-c/deps/azure-c-shared-utility/adapters/tlsio_openssl.c':b'tlsio_openssl_open':1258)
[INFO] [2020-07-14 16:00:16] b'xio_open failed' (b'/data/src/vendor/azure-uamqp-c/src/saslclientio.c':b'saslclientio_open_async':1097)
[INFO] [2020-07-14 16:00:16] b'Opening the underlying IO failed' (b'/data/src/vendor/azure-uamqp-c/src/connection.c':b'connection_open':1344)
[INFO] [2020-07-14 16:00:16] Connection b'bc610657-4dbf-4bc2-aa39-38b6889e6047' state changed from <ConnectionState.START: 0> to <ConnectionState.END: 13>
[INFO] [2020-07-14 16:00:16] Connection with ID b'bc610657-4dbf-4bc2-aa39-38b6889e6047' unexpectedly in an error state. Closing: False, Error: None
[INFO] [2020-07-14 16:00:16] b'Begin session failed' (b'/data/src/vendor/azure-uamqp-c/src/link.c':b'link_attach':1282)
[INFO] [2020-07-14 16:00:16] b'Link attach failed' (b'/data/src/vendor/azure-uamqp-c/src/message_receiver.c':b'messagereceiver_open':381)
[INFO] [2020-07-14 16:00:16] b'AMQP management instance not open' (b'/data/src/vendor/azure-uamqp-c/src/amqp_management.c':b'amqp_management_close':1029)
[INFO] [2020-07-14 16:00:16] CBS for connection b'bc610657-4dbf-4bc2-aa39-38b6889e6047' completed opening with status: 1
[INFO] [2020-07-14 16:00:16] b'Failed opening message receiver' (b'/data/src/vendor/azure-uamqp-c/src/amqp_management.c':b'amqp_management_open_async':990)
/start.sh complete - exit status_code=1

A: while I can't claim deep familiarity with docker (Am however one of the ServiceBus sdk maintainers for Python) this appears to be in the broad category of "network totally unavailable" error.  I would first make sure that the standard AMQP ports (5671/15671) are open and properly exposed (potentially bidirectionally) for the container+local network.
Apologies if this would be better suited as a comment, karma makes me unable to do so, don't hesitate to shout if this doesn't seem to help.


text:
Q: How to swipe delete core data tableview in Swift 2.0 I have a table view within a VC. It is populated from a core data object using the following code:
// Variables
var allFruits: NSArray
var managedObjectContext: NSManagedObjectContext
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

func loadFruits(){
    // Try to load all of the Fruits from the core data.
    let fetchRequest = NSFetchRequest()

    let entityDescription = NSEntityDescription.entityForName("Fruit", inManagedObjectContext: self.managedObjectContext)

    fetchRequest.entity = entityDescription
    do{
        self.allFruits = try self.managedObjectContext.executeFetchRequest(fetchRequest)

        if self.allFruits.count == 0{
            print("No saved Fruits")
        }
    }
    catch
    {
        let fetchError = error as NSError
        print(fetchError)
    }
}

Then the table view is populated with this specific fruit data. I have got this method for deletion of the Fruits from the table
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    if (editingStyle == UITableViewCellEditingStyle.Delete) {
         // handle delete (by removing the data from your array and updating the tableview)
         managedObjectContext.deleteObject(allFruits[indexPath.row] as! NSManagedObject)

         // Attempt to save the object
         do{
             try appDelegate.managedObjectContext.save()
         }
             catch let error{
             print("Could not save Deletion \(error)")
         }

         // Remove the deleted item from the table view
         self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

         // Reload the fruits
         self.loadFruits()

         // Reload the table view
         tableView.reloadData()
    }
}

This instead just crashes the app every time I try to delete the Fruits.

'NSInternalInconsistencyException', reason: 'Invalid update: invalid
  number of rows in section 0.  The number of rows contained in an
  existing section after the update (5) must be equal to the number of
  rows contained in that section before the update (5), plus or minus
  the number of rows inserted or deleted from that section (0 inserted,
  1 deleted) and plus or minus the number of rows moved into or out of
  that section (0 moved in, 0 moved out).'

I am suspecting that there is some issue with the fact that I am using an NSArray as opposed to an NSMutableArray.
How can I fix this issue?
Thanks in advance.

A: First of all use a Swift array rather than a Foundation array
var allFruits = [NSManagedObject]()

This avoids a lot of type casting.
To keep Core Data and the table view in sync you have to delete the object in Core Data and in the model. The solution to completely reload both the model and the view is very expensive and not needed at all.
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
  if editingStyle == .Delete {

    let objectToDelete = allFruits[indexPath.row]
    allFruits.removeAtIndex(indexPath.row)
    managedObjectContext.deleteObject(objectToDelete)

    //Attempt to save the object
    do{
      try appDelegate.managedObjectContext.save()
      tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    }
    catch let error{
      print("Could not save Deletion \(error)")
    }
  }
}

deleteRowsAtIndexPaths includes updating the UI so reloading the table view is not needed.
If the model of the table view is NSManagedObject it's recommended to use NSFetchedResultsController

A: You should update data source before delete. Like this:
     //Reload the fruits
     self.loadFruits()

     //Remove the deleted item from the table view
     self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)

And if you're sure there's no other changes,it's no need to reload data because this costs a lot.

A: I fixed my code by simply changing this method:
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if (editingStyle == UITableViewCellEditingStyle.Delete) {

             // handle delete (by removing the data from your array and updating the tableview)
             managedObjectContext.deleteObject(allFruits[indexPath.row] as! NSManagedObject)

             //Attempt to save the object
             do{
             try appDelegate.managedObjectContext.save()
             }
             catch let error{
             print("Could not save Deletion \(error)")
             }

             //Reload the fruits
             self.loadFruits()

             //Reload the table view
             tableView.reloadData()

        }
    }

This successfully deletes the object from the core data as well as updating the table view.

A: Updated for Swift 3 Xcode 8 iOS 10
The following code snippet adds a 'swipe to delete' to your Table Row, and also saves the changes to CoreData.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

    if editingStyle == .delete {
         context.delete(tasks[indexPath.row] as NSManagedObject)
        //objects.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)

        //Save the object
        do{
            try (UIApplication.shared.delegate as! AppDelegate).saveContext()
        }
        catch let error{
            print("Cannot Save: Reason: \(error)")
        }

        //Reload your Table Data
        getData()

        //Reload the table view
        tableView.reloadData()

    } else if editingStyle == .insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}


text:
Q: windows 10 - change default windows browser to a portable app application, Firefox or Chrome Can you change Windows 10 default browser to a portable app, Firefox or Chrome/chromium portable from portableapps.com
In
Start (windows logo) > Settings > System > Default Apps > Web Browser > Click on Microsoft edge > select your favorite browser.
it only offers as options :
Microsoft Edge
Internet Explorer
Search for app in windows store

A: The best way is from the application itself at first.
Every browser leaves you the option to choose it as default in its own settings/parameters/options.
Doing so will create an entry in Registry that Windows Settings will read, and propose your portable browser in the list of candidates.
That's unless you've got a GPO in place on your PC to prevent you from choosing your own default browser, of course.


text:
Q: Alt-Gr key binding not working, Ubuntu 13.04 I'm using Compiz, but not sure if that's the problem or not.
My alt keys are working fine, but I'm trying to do something particular with the Alt-Gr key for a custom Russian keyboard layout.
Glad to provide specific information on request.
Any help would be greatly appreciated.
Steps already taken:

*

*I've gone into Keyboard Layout Settings --> Options, and made sure the correct Compose key option is set (at Right Alt).

*Chosen my custom keyboard layout (from the Keyboard Layouts section) and then brought up the onscreen keyboard which allows me to check which key is being pressed with onscreen feedback cue.

Doing this indicates that my Compose key is indeed the right alt, and it does flash when pressed.  It also indicates that in my custom keyboard layout is correct on the key that I want:  for the z key I have mapped 'З' (pronounced "ze") and for Alt-Gr + z I have mapped 'Ж' ('zhe').  This information shows up in the onscreen keyboard.  However, trying this key combination produces no text on the first press, and on subsequent (joint / combo) presses, this produces only the non-altered 'З', same as I'm expecting from the non-combo z press only.
In summary, the Compose key is mapped correctly, and the character I want is mapped correctly (all 4 options (2 letters each with upper and lower case) appear in the onscreen keyboard), but the combination does nothing (on first press) and then the non-altered thing subsequently.
This is what my \usr\share\X11\xkb\symbols\ru file looks like:
[...]
key <AB10> { [ U0417, U0437, U0416, U0436    ]   };
According to the documentation I've seen, the first two entries should be produced by pressing the z key and shift + z respectively (I'm working in Dvorak, so that's the key just to the left of the right-shift key), and the last two should be produced with the Compose + z and shift + Compose + z respectively.  But, as mentioned, the actual behaviour I'm getting with Alt-Gr is nothing and then the default z and shift+z behaviour only.

A: I think this is what you're looking for:

Choose your current keyboard layout:

A: You have modified \usr\share\X11\xkb\symbols\ru to follow a Dvorak layout, and you have modifed the key <AB10> section within the name[Group1]= "Russian" section by adding 2 additional keys.
Extra keys that are defined in the keyboard layout file in this way are not Compose key sequences. These keys are 3rd/4th-level keys.
In order to reach Ж that you defined in key <AB10>, you need to use a 3rd level chooser rather than the compose key. The 4th-level key is reached with 3rd-level-chooser+Shift
In the Keyboard Layout Options dialog, open Key to choose 3rd level, and choose whatever key works best for you.
I modified my Russian keyboard with the changes you indicate, set menu as the 3rd level chooser and menu+key-to-left-of-right-shift now correctly inserts Ж.
I chose menu because I never use it otherwise, and because I prefer Right-Alt as the Compose key.
The main point here is that the same key can't serve as both the Compose key and the 3rd level chooser. The system won't complain, but the 3rd level setting will have no effect.
If you prefer Right-Alt as the 3rd level chooser, be sure to select something else for the Compose key. When trying out different combinations, sometimes I've had to logout out before they took effect.
(Btw, you seem to have the capital/small letters in the swapped positions, unless that is what you want.)


text:
Q: How do I compute bootstrapped cross entropy loss in PyTorch? I have read some papers that use something called "Bootstrapped Cross Entropy Loss" to train their segmentation network. The idea is to focus only on the hardest k% (say 15%) of the pixels into account to improve learning performance, especially when easy pixels dominate.
Currently, I am using the standard cross entropy:
loss = F.binary_cross_entropy(mask, gt)

How do I convert this to the bootstrapped version efficiently in PyTorch?

A: Often we would also add a "warm-up" period to the loss such that the network can learn to adapt to the easy regions first and transit to the harder regions.
This implementation starts from k=100 and continues for 20000 iterations, then linearly decay it to k=15 for another 50000 iterations.
class BootstrappedCE(nn.Module):
    def __init__(self, start_warm=20000, end_warm=70000, top_p=0.15):
        super().__init__()

        self.start_warm = start_warm
        self.end_warm = end_warm
        self.top_p = top_p

    def forward(self, input, target, it):
        if it < self.start_warm:
            return F.cross_entropy(input, target), 1.0

        raw_loss = F.cross_entropy(input, target, reduction='none').view(-1)
        num_pixels = raw_loss.numel()

        if it > self.end_warm:
            this_p = self.top_p
        else:
            this_p = self.top_p + (1-self.top_p)*((self.end_warm-it)/(self.end_warm-self.start_warm))
        loss, _ = torch.topk(raw_loss, int(num_pixels * this_p), sorted=False)
        return loss.mean(), this_p

A: Addition to self answer by @hkchengrex (for future self and API parity with PyTorch);
one could implement functional version first (with some additional arguments provided in original torch.nn.functional.cross_entropy) like this (also I prefer reduction to be callable instead of predefined strings):
import typing

import torch

def bootstrapped_cross_entropy(
    inputs,
    targets,
    iteration,
    p: float,
    warmup: typing.Union[typing.Callable[[float, int], float], int] = -1,
    weight=None,
    ignore_index=-100,
    reduction: typing.Callable[[torch.Tensor], torch.Tensor] = torch.mean,
):
    if not 0 < p < 1:
        raise ValueError("p should be in [0, 1] range, got: {}".format(p))

    if isinstance(warmup, int):
        this_p = 1.0 if iteration < warmup else p
    elif callable(warmup):
        this_p = warmup(p, iteration)
    else:
        raise ValueError(
            "warmup should be int or callable, got {}".format(type(warmup))
        )

    # Shortcut
    if this_p == 1.0:
        return torch.nn.functional.cross_entropy(
            inputs, targets, weight, ignore_index=ignore_index, reduction=reduction
        )

    raw_loss = torch.nn.functional.cross_entropy(
        inputs, targets, weight=weight, ignore_index=ignore_index, reduction="none"
    ).view(-1)
    num_pixels = raw_loss.numel()

    loss, _ = torch.topk(raw_loss, int(num_pixels * this_p), sorted=False)
    return reduction(loss)

Also warmup can be specified as callable (taking p and current iteration) or int which allows for flexible or easy scheduling.
And making a class basing of _WeightedLoss and iteration incremented automatically during each call (so only inputs and targets have to be passed):
class BoostrappedCrossEntropy(torch.nn.modules.loss._WeightedLoss):
    def __init__(
        self,
        p: float,
        warmup: typing.Union[typing.Callable[[float, int], float], int] = -1,
        weight=None,
        ignore_index=-100,
        reduction: typing.Callable[[torch.Tensor], torch.Tensor] = torch.mean,
    ):
        self.p = p
        self.warmup = warmup
        self.ignore_index = ignore_index
        self._current_iteration = -1

        super().__init__(weight, size_average=None, reduce=None, reduction=reduction)

    def forward(self, inputs, targets):
        self._current_iteration += 1
        return bootstrapped_cross_entropy(
            inputs,
            targets,
            self._current_iteration,
            self.p,
            self.warmup,
            self.weight,
            self.ignore_index,
            self.reduction,
        )


text:
Q: A nil class when trying to initialize a deck of cards The following code is resulting in nil and I can't figure out why. Is there something wrong with my initialization?
class Card
    VALUES = %w(2 3 4 5 6 7 8 9 10 J Q K A)
    SUITS = %w(S H D C)

    def initialize(suit, value)
        @suit = suit
        @value = value
    end
end

class Deck
    attr_accessor :cards

    def initialize
        @cards = []
        Card::SUITS.each do |suit|
            Card::VALUES.each do |value|
                @cards << Card.new(suit, value)
            end
        end
    end
end

Deck.new

p @cards

A: @cards is not known outside the object. Outside the class Deck it is a instance variable of the top-level scope in Ruby.
You have to use the accessor method to get the content:
class Card
    VALUES = %w(2 3 4 5 6 7 8 9 10 J Q K A)
    SUITS = %w(S H D C)

    def initialize(suit, value)
        @suit = suit
        @value = value
    end
end

class Deck
    attr_accessor :cards

    def initialize
        @cards = []
        Card::SUITS.each do |suit|
            Card::VALUES.each do |value|
                @cards << Card.new(suit, value)
            end
        end
    end
end

deck = Deck.new  #<--- Store object in a variable

p deck.cards  #<--- Use accessor

A: or just:
my_deck = Deck.new

p my_deck.cards

A: In short, instance variables can only be seen by other methods from within the same class. I believe what you're trying to do is:
new_deck = Deck.new
p new_deck.cards

Calling the cards method on new_deck returns @cards.

A: You create a new object Deck.new, but you don't print the value of its cards - you print a @cards instance variable which in this context is nil.
You probably wanted something like p Deck.new.cards.

A: Currently your output for @cards array is difficult to read and contains object info. I thought I'd offer an alternative I've just conjoured up, hope it helps:
class Deck

  attr_writer :suits, :values
  attr_accessor :deck

  def initialize
    suits
    values
    generate_deck
    shuffle
  end

  def generate_deck
    @deck = []
    @suits.each do |suit|
      @values.each { |value| @deck << [suit, value] }
    end
  end

  def suits
    @suits  = ['Clubs', 'Diamonds', 'Hearts', 'Spades' ]
  end

  def values
    @values = ('2'..'10').to_a + ['J','Q','K','A']
  end

  #just in case you want to shuffle your deck
  def shuffle
    @deck.shuffle!
  end

end

require 'pp' #this makes the output prettier
new_deck = Deck.new
pp new_deck.deck #calls your current deck so you can see it

Output example:
$ ruby yourfilename.rb
[["Hearts", "K"],
 ["Spades", "5"],
 ["Clubs", "7"],

 #code omitted... (the rest of your cards would be here)

 ["Clubs", "K"],
 ["Hearts", "5"],
 ["Diamonds", "J"],
 ["Hearts", "7"]]


text:
Q: Django Template does not exist in production server but is working in :8000 Hi guys im having a problem with my own django server (at home), django can't find templates, my error code django is looking in the correct place (/var/www/project/templates) but nothing happen
Template does not exist but all path are fine.
but using test server :8000 all is fine, i dont know how ill fix this
edit
this is perfect for get the template:
/var/www/agricultura/templates/forms/registro_form.html

Template path
import os
TEMPLATE_DIRS = (
     os.path.join(os.path.abspath(os.path.dirname(__file__)),'templates'),
)

Template Loader Error:
Django tried loading these templates, in this order:
Using loader django.template.loaders.filesystem.Loader:
/var/www/agricultura/templates/forms/registro_form.html (File does not exist)
Using loader django.template.loaders.app_directories.Loader:
/usr/local/lib/python2.6/dist-packages/admin_tools/theming/templates/forms/registro_form.html (File does not exist)
/usr/local/lib/python2.6/dist-packages/admin_tools/menu/templates/forms/registro_form.html (File does not exist)
/usr/local/lib/python2.6/dist-packages/admin_tools/dashboard/templates/forms/registro_form.html (File does not exist)
/usr/local/lib/python2.6/dist-packages/django/contrib/admin/templates/forms/registro_form.html (File does not exist)
Using loader django.template.loaders.eggs.Loader:

Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/var/www/agricultura/registro/views.py" in registro_view
  71.                           context_instance=RequestContext(request))
File "/usr/local/lib/python2.6/dist-packages/django/shortcuts/__init__.py" in render_to_response
  20.     return HttpResponse(loader.render_to_string(*args, **kwargs), **httpresponse_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in render_to_string
  181.         t = get_template(template_name)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in get_template
  157.     template, origin = find_template(template_name)
File "/usr/local/lib/python2.6/dist-packages/django/template/loader.py" in find_template
  138.     raise TemplateDoesNotExist(name)

Exception Type: TemplateDoesNotExist at /registro/
Exception Value: forms/registro_form.html

Any idea?
thanks

A: Trivial, but I have seen instances where people forget to add the concerned application in the installed apps and get the template not found error.

A: there might be an error in the template. Have you got TEMPLATE_DEBUG = True in the settings? And you've set TEMPLATE_DIRS as well?
Try loading the template via the python shell on your server:
https://docs.djangoproject.com/en/dev/ref/templates/api/#the-render-to-string-shortcut
./manage.py shell
from django.template.loader import render_to_string
rendered = render_to_string('my_template.html', { 'foo': 'bar' })

It might throw an error and give you a further clue.

A: Add this to your settings file:
def findMyWay(*relativeComponents):
    return os.path.join(os.path.dirname(__file__), *relativeComponents).replace("\\","/")

TEMPLATE_LOADERS = (
    "django.template.loaders.filesystem.Loader",
    "django.template.loaders.app_directories.Loader",
)

TEMPLATE_DIRS = (
    findMyWay("templates"),
)

Working perfectly fine for me.


text:
Q: How do i Tokenize a string? I want my program to know if the string is a Noun, verb , adjective or etc. and it needs to be tokenized but how do i do that?
Do i need a Database for the definition of words? using Free context grammar?
Thank you.

A: It is much more complicated than that.
The answer to your immediate question is both.  You both look up words to see what part of speech they are, as well as analyze sentence structure to determine part of speech.
Check out http://wordnet.princeton.edu/ to see about looking up parts of speech.
I recommend GATE/Annie as a open source framework for NLP.  Apache has UIMA, although I haven't worked with it.  There is some compatibility between the projects, I believe.


text:
Q: Area highlight mouseout I have the following function:
<script type="text/javascript">
$("img[usemap]").mapify();

$(window).resize(function(){

  setTimeout(function(){
    $("#map area").eq(1).trigger("mouseenter.mapify").trigger("focus.mapify").trigger("touchend.mapify");
    $(".mapify-svg polygon").eq(1).css("stroke","#09f");
  },5000);

}).resize();
</script>

This functions highlights a specific area (using mapify) after 5 seconds using a stroke.
This is completely functional but I can't seem to find a way to adapt the function to include a mouseout functionality.
Basically, I need that after 5 seconds the area highlights, it stays highlighted for 2 seconds and then it goes out again, repeating itself.
I'm fairly new to JS and image mapping but I can provide any additional information that might help.
The project I'm working on is located at https://sporedev.ro/pleiade.

A: Use the following
function blinkIn() {
  setTimeout(function() {
    $("#map area").eq(1).trigger("mouseenter.mapify").trigger("focus.mapify").trigger("touchend.mapify");
    $(".mapify-svg polygon").eq(1).css("stroke", "#09f");
    blinkOut();
  }, 5000);
}

function blinkOut() {
  setTimeout(function() {
    $("#map area").eq(1).trigger('mouseout.mapify');
    blinkIn();
  }, 2000);
}

blinkIn();

But do not put in the .resize handler as that will fire multiple times while resizing and mess it up.


text:
Q: How to setup data properly for regression analysis to calculate price elasticity? I am working on a project to try understand Linear Regression a bit deeper (they say experimenting is key and getting lost is part of the process) :(
In this project, let's assume I have a watch shop. I want to calculate price elasticity of demand for my watches but how do I setup the data as in my mind there are two options:

*

*I have 100 watch styles and each have their own prices and quantity sold for a period of time, so the first setup looks like:

Watch Styles
Price
Quantity

Style 1
900
10

Style 2
1500
20

Style 3
1000
30

...
...
...

Style 100
2000
50

*Alternatively, I can set my data as a transactional time series (monthly for 2 years worth of data). Now the 'price' variable will be the average unit price of watches sold per month and 'quantity' will be the aggregated monthly figure.

Month
Avg Price per Month
Quantity

April 2019
1225
110

May 2019
1135
150

June 2019
1575
75

...
...
...

April 2021
2050
15

Which data setup is appropriate to run the regression analysis and why?
$$
ln(Quantity) = c + \beta\  ln(Price) + Error
$$
After reading some marketing research papers, it looks like the setup using (2) is favored for elasticity calculation. So how do we interpret the regression results if we use (1) instead?

A: I think you should be working out the price elasticity of one style of watch. If you look at multiple styles of watches you wouldn't be using linear regression.
I would set my data up to look something like this (but obviously include more weeks/months/years):

There's more information on this here:
https://www.statworx.com/de/blog/food-for-regression-using-sales-data-to-identify-price-elasticity/


text:
Q: Disable SSH remote tunneling I need to restrict SSH tunnel functions. Users should not be allowed to create remote tunnels but only tunnels to localhost. I tried to setup the whole thing in the SSH configuration but I can only turn off the TCPForwarding completely there. I guess this might only be possible with iptables then? Does anyone have experience and can help me out?

A: For OpenSSH you can use PermitOpen host:port to limit where users can tunnel to. To let them tunnel to MySQL that only listens locally on the default port:
PermitOpen LocalHost:3306

From the man page for sshd_config:

PermitOpen
Specifies the destinations to which TCP port forwarding is permitted.
  The forwarding specification must be one of the following forms:
PermitOpen host:port
PermitOpen IPv4_addr:port
PermitOpen [IPv6_addr]:port

Multiple forwards may be specified by separating them with white space.
  An argument of any can be used to remove all restrictions and permit
  any forwarding requests.  An argument of none can be used to prohibit
  all forwarding requests.  By default all port forwarding requests are
  permitted.


text:
Q: Convert string to double or any numerical type variable in C# I've got a program that reads xml files. I already have a code that reads specific elements and places it in a variable. The only thing missing is comparing an element(a number) to a double variable, but elements are considered as string. All I have seen in Google is conversion of double to string. How do you convert a string to double?
EDIT:
I've got it now, I can't answer my own question yet 'coz I still have low reputation. This is what I've come so far and it works:
string stringNum = "2";
double value = double.Parse(stringNum);

A: var number = double.Parse("2.5", CultureInfo.InvariantCulture);

See Double.Parse at MSDN
And just as a heads-up, you will probably want to take a look at Parse(String, IFormatProvider), because parsing XML means you will have to look into the format of your "number strings". It's common practice to specify the CultureInfo when using ToString or Parse methods. Look here for more information.

When a CultureInfo or System.IFormatProvider object is not supplied,
  the default value supplied by the overloaded member might not have the
  effect that you want in all locales. Also, .NET Framework members
  choose default culture and formatting based on assumptions that might
  not be correct for your code. To ensure the code works as expected for
  your scenarios, you should supply culture-specific information.

A: You can use Double.Parse, the 2nd parameter specifies the culture of the numbers in your file.
var newDouble = Double.Parse(theString, new CultureInfo("en-GB"));


text:
Q: Estimate total distance using Riemann sum based on data table We did not spend a lot of time in class on Riemann sum so I confused with this question.
Speedometer readings for a motorcycle at $12$-second intervals are given in the table below.
$$
\begin{array}{c|c|c|c|c}
t sec & 0 & 12 & 24 & 36 & 48 & 60 \\
\hline
v(t) ft/sec & 23 & 22 & 18 & 17 & 20 &23\\
\end{array}
$$
Estimate the total distance traveled during the time interval $[0,60]$ using a Riemann sum based on the table data.
I hope someone can help. Thanks.

A: The definition of a Riemann sum is as following:
Let $f$ be a function, $\Pi=\{x_0,\dots,x_n\}$ be a partition and $S=\{c_1,\dots,c_n\}$ a set of values such that $c_i\in[x_{i-1},x_i]$. The Riemann sum is
$$R(\Pi,S)=\sum_{i=1}^nf(c_i)(x_i-x_{i-1}).$$
You have a discrete function $f=v$ and you have a partition in first row of the table. Can you find the Riemann sum now?


text:
Q: iPhone init method return type Suppose we are writing a class (let's call it Class) in an iPhone program.  In all the samples out there, the init methods are typically declared like this:
-(id) initWithFoo: (Foo *) foo

My question is: would it be more logical to do the following?  Why or why not?
-(Class *) initWithFoo: (Foo *) foo

A: From Implementing an Initializer on Mac Dev Center

The reason for this is that id gives an indication that the class is purposefully not considered—that the class is unspecified and subject to change, depending on context of invocation. For example, NSString provides a method initWithFormat:. When sent to an instance of NSMutableString (a subclass of NSString), however, the message returns an instance of NSMutableString, not NSString. (See also, though, the singleton example given in "Combining Allocation and Initialization.")


text:
Q: Spring Boot - 504 gateway timeout I just created simple Spring starter project that contains a single controller and only one Rest API that print logs on the console. I don't see any exceptions/errors in the spring boot server startup, everything looks fine. but I get 504 Gateway timeout error when I access the rest API through Postman or Curl. here is my controller class.
Controller Class
import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

@RestController

@RequestMapping(path = "/test")

public class SampleController {

    private static final Logger LOG =
     LoggerFactory.getLogger(SampleController.class.getSimpleName());

    @GetMapping(value = "/method")
    public void saveEcu() {

        LOG.info("---> reached test/method----> ");

    }

}

Log console
2018-06-28 22:03:52.890  INFO 7040 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
2018-06-28 22:03:52.898 DEBUG 7040 --- [           main] o.s.w.c.s.StandardServletEnvironment     : Adding PropertySource 'Management Server' with lowest search precedence
2018-06-28 22:03:52.901  INFO 7040 --- [           main] o.s.c.support.DefaultLifecycleProcessor  : Starting beans in phase 0
2018-06-28 22:03:53.014 DEBUG 7040 --- [           main] o.s.w.s.resource.ResourceUrlProvider     : Looking for resource handler mappings
2018-06-28 22:03:53.014 DEBUG 7040 --- [           main] o.s.w.s.resource.ResourceUrlProvider     : Found resource handler mapping: URL pattern="/**/favicon.ico", locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/], class path resource []], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@3c744059]
2018-06-28 22:03:53.014 DEBUG 7040 --- [           main] o.s.w.s.resource.ResourceUrlProvider     : Found resource handler mapping: URL pattern="/webjars/**", locations=[class path resource [META-INF/resources/webjars/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@ab2dd851]
2018-06-28 22:03:53.015 DEBUG 7040 --- [           main] o.s.w.s.resource.ResourceUrlProvider     : Found resource handler mapping: URL pattern="/**", locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@c804fffb]
2018-06-28 22:03:53.042  INFO 7040 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 9091 (http)
2018-06-28 22:03:53.043 DEBUG 7040 --- [           main] o.s.w.c.s.StandardServletEnvironment     : Adding PropertySource 'server.ports' with highest search precedence
2018-06-28 22:03:53.047  INFO 7040 --- [           main] c.e.demo.NewStarterProjectApplication    : Started NewStarterProjectApplication in 3.822 seconds (JVM running for 5.088)


text:
Q: Check if meta key value already exists Let's say that I have few posts with meta key "videoid". Value of that meta key is different for every post (and has to be different). When adding new post, how can I check if videoid with that exact value already exist for some older posts? I used this as a refference for adding custom meta box to admin area of WP: http://codex.wordpress.org/Function_Reference/add_meta_box

A: Just do a query with WP_Query using the Custom Field parameters (meta_query) to look for posts with the meta key and the value - exemplary code:
 // args to query for your key
 $args = array(
   'post_type' => 'your_post_type',
   'meta_query' => array(
       array(
           'key' => 'videoid',
           'value' => $new_posts_videoid  // for example: '111'
       )
   ),
   'fields' => 'ids'
 );
 // perform the query
 $vid_query = new WP_Query( $args );

 $vid_ids = $vid_query->posts;

 // do something if the meta-key-value-pair exists in another post
 if ( ! empty( $vid_ids ) ) {
     // do your stuff
 }

There is no need to use query_post() - see:
When should you use WP_Query vs query_posts() vs get_posts()?
. If you need a complete array of post objects, not just the ids, remove 'fields' => 'ids'.

A: ialocin's answer incorrectly states that the wp_query stored as a variable would just spit out an array of ID's. Instead it gives the whole WP_Query object, so you have to use ->posts to get that array of post ID's.
// args to query for your key
 $args = array(
   'post_type' => 'YOUR_POST_TYPE',
   'meta_query' => array(
       array(
           'key' => 'YOUR_META_FIELD_NAME',
           'value' => '111'
       )
   ),
   'fields' => 'ids'
 );
 // perform the query
 $query = new WP_Query( $args );
 $duplicates = $query->posts;

 // do something if the key-value-pair exists in another post
 if ( ! empty( $duplicates ) ) {
     // do your stuff
 }

A: Or wrap it up in a function:
function meta_value_exists($your_meta_value) {
    $args = array(
        'post_type'   => 'YOUR_POST_TYPE',
        'post_status' => 'publish',
        'numberposts' => 1,
        'meta_key'     => 'your_meta_field',
        'meta_value'   => $your_meta_value,
    );
    $current_post = get_posts($args);
    if( $current_post ) {
        return true;
    } else {
        return false;
    }
}

So then you could just check on your meta value:
$video_id = 1234;
if(meta_value_exists($video_id){
   // do something if exists
} else {
   // do something if not exists
}

A: Found it:
$args = array(
    'meta_query' => array(
        array(
            'key' => 'videoid',
            'value' => $_POST['videoid']
        )
    )
);

$videoQuery = new WP_Query( $args );

if ( $videoQuery->have_posts() ) :
    while ( $videoQuery->have_posts() ) :
            $videoQuery->the_post(); ?>
    echo "
" . the_title() . "
";
    endwhile;
    endif;


text:
Q: Virtual Hosts w/ IIS 7.5.x Not Paying Attention to Path I have setup numerous linux web servers (using Apache) but I am new to IIS.  I am trying to setup two new vhosts, let's call them vhost1.domain.com and vhost2.domain.com for the purposes of this example.
I have added two new sites, one for each vhost and set their path to specific (and unique) directories.  Unfortunately when I pull the site up via vhost1.domain.com I just get the default IIS page saying:

It Works!
This is the default web page for this server.
The web server software is running but no content has been added, yet.

It seems that they aren't paying attention to their proper path.
Something worth noting is that I just installed PHP 5.3 on the server (Windows Server 2008) and I used the Microsoft Web Platform Installer to do so.  Everything went smoothly and I used all default settings.
If I need to supply more information/details please let me know, any insight that can be provided would be much appreciated.

A: Turns out that IIS was setup correctly and the problems I was having were all related to DNS.  Once we got the DNS stuff straightened out everything came together.


text:
Q: How to remove configure volumes in docker images I use docker run -it -v /xx1 -v /xx2 [image] /bin/bash to create a container.
Then commit to image and push to docker hub.
use docker inspect [image]
The Volumes detail is
"Volumes": {
            "/xx1": {},
            "/xx2": {}
        },

Now I want to remove volume /xx1 in this image.
What should I do?

A: I don't think this is possible with the Docker tools right now. You can't remove a volume from a running container, or if you were to use your image as the base in a new Dockerfile you can't remove the inherited volumes.
Possibly you could use Jérôme Petazzoni's nsenter tool to manually remove the mount inside the container and then commit. You can use that approach to attach a volume to a running container, but there's some fairly low-level hacking needed to do it.

A: There is a workaround in that you can docker save image1 -o archive.tar, editing the metadata json file, and docker import -i archive.tar. That way the history and all the other metadata is preserved.
To help with save/unpack/edit/load I have created a little script, have a look at docker-copyedit. Specifically for your question you would execute
./docker-copyedit.py from [image] into [image2] remove volume /xx1

A: An easy way to remove volumes is to export and then import the container image:

*

*docker run --name my-container -it [image] /bin/bash

*docker export my-container > tarball

*docker import tarball


text:
Q: The target file 'XXXX' is installed in 'YYYY' by two different components on an LFN system We recently upgraded DevExpress. Since we have a custom theme, we had to upgrade the custom theme too.
That was the easy part. Now I'm trying to upgrade the setup to match the new file.
So basically, I'm changing the <File .../> of one <Component  .../>:
From
  <Component Id="Lib_Various_Files" Guid="9C621EB0-12E6-4D1D-8B5B-4150A76E33AA" KeyPath="yes" SharedDllRefCount="yes">
    ...
    <File Id="DevExpress.Xpf.Themes.PreviousTheme.v17.1.dll" Name="DevExpress.Xpf.Themes.PreviousTheme.v17.1.dll" ReadOnly="yes" Vital="no" Compressed="default" DiskId="1" Source="$(var.DirLib)\PreviousTheme\DevExpress.Xpf.Themes.PreviousTheme.v17.1.dll" />
  </Component>

To:
  <Component Id="Lib_Various_Files" Guid="9C621EB0-12E6-4D1D-8B5B-4150A76E33AA" KeyPath="yes" SharedDllRefCount="yes">
    ...
    <File Id="DevExpress.Xpf.Themes.OurTheme.v17.2.dll" Name="DevExpress.Xpf.Themes.OurTheme.v17.2.dll" ReadOnly="yes" Vital="no" Compressed="default" DiskId="1" Source="$(var.DirLib)\OurTheme\.td\Publish\DevExpress.Xpf.Themes.OurTheme.v17.2.dll" />
  </Component>

Now I've an error in the setup, which seems to have no links to this line:

error LGHT0204: ICE30: The target file
  'qgikh9i6.dll|System.Windows.Interactivity.dll' is installed in
  '[TARGETDIR]\OurProduct\Bin\' by two different components on an LFN
  system: 'cmpF5730C92213BA3272DDA3A5657DFF782' and 'Lib_Prism'. This
  breaks component reference counting.
  [D:\ws\OurProduct-Nightly\SetupWix\SetupWix\SetupWix.wixproj]

We do reference this library, in the Lib_Prism component(which is then in another Lib_Various component, that reference Lib_Prism and Lib_Various_Files, but nowhere else.
Any idea what could be the issue?
So here is the complete components list of this file:
<?xml version="1.0" encoding="UTF-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
  <Fragment>
    <?include ..\Common.wxi?>

    <DirectoryRef Id="BIN">
      <Component Id="Lib_Various_Files" Guid="9C621EB0-12E6-4D1D-8B5B-4150A76E33AA" KeyPath="yes" SharedDllRefCount="yes">
        ...
        <File Id="DevExpress.Xpf.Themes.OurTheme.v17.2.dll" Name="DevExpress.Xpf.Themes.OurTheme.v17.2.dll" ReadOnly="yes" Vital="no" Compressed="default" DiskId="1" Source="$(var.DirLib)\OurTheme\.td\Publish\DevExpress.Xpf.Themes.OurTheme.v17.2.dll" />
      </Component>
      <Component Id="Lib_MicrosoftPractices" Guid="780097FD-40C9-417A-A2C3-7C2B44567BEC" KeyPath="yes" SharedDllRefCount="yes">
        <File ReadOnly="yes" DiskId="1" Source="$(var.DirPackages)\CommonServiceLocator.1.3\lib\portable-net4+sl5+netcore45+wpa81+wp8\Microsoft.Practices.ServiceLocation.dll" />
        <File ReadOnly="yes" DiskId="1" Source="$(var.DirPackages)\Unity.4.0.1\lib\net45\Microsoft.Practices.Unity.Configuration.dll" />
        <File ReadOnly="yes" DiskId="1" Source="$(var.DirPackages)\Unity.4.0.1\lib\net45\Microsoft.Practices.Unity.RegistrationByConvention.dll" />
        <File ReadOnly="yes" DiskId="1" Source="$(var.DirPackages)\Unity.4.0.1\lib\net45\Microsoft.Practices.Unity.dll" />
      </Component>
      <Component Id="Lib_Prism" Guid="0F937515-2248-4CD2-B2E9-3E121FA9D743" KeyPath="yes" SharedDllRefCount="yes">
        <File ReadOnly="yes" DiskId="1" Source="$(var.DirPackages)\Prism.Core.6.3.0\lib\net45\Prism.dll" />
        <File ReadOnly="yes" DiskId="1" Source="$(var.DirPackages)\Prism.Unity.6.3.0\lib\net45\Prism.Unity.Wpf.dll" />
        <File ReadOnly="yes" DiskId="1" Source="$(var.DirPackages)\Prism.Wpf.6.3.0\lib\net45\Prism.Wpf.dll" />
        <File ReadOnly="yes" DiskId="1" Source="$(var.DirPackages)\Prism.Wpf.6.3.0\lib\net45\System.Windows.Interactivity.dll" />
      </Component>
      <Component Id="Lib_MvvmValidation" Guid="8681DBA1-F83D-475B-BCB8-A54A1F05FF0A" KeyPath="yes" SharedDllRefCount="yes">
        <File ReadOnly="yes" DiskId="1" Source="$(var.DirPackages)\MvvmValidation.3.1.0\lib\netstandard1.0\MvvmValidation.dll" />
      </Component>
      <Component Id="Lib_Protobuf_Net" Guid="AEE6F4EB-78E3-4EC5-AA88-D5CC29D683D0" KeyPath="yes" SharedDllRefCount="yes">
        <File ReadOnly="yes" DiskId="1" Source="$(var.DirDotfuscated)\ProtobufNet.dll" />
      </Component>
    </DirectoryRef>

    <ComponentGroup Id="Lib_Various" >
      <ComponentRef Id="Lib_MicrosoftPractices" />
      <ComponentRef Id="Lib_Prism" />
      <ComponentRef Id="Lib_Various_Files" />
      <ComponentRef Id="Lib_MvvmValidation" />
      <ComponentRef Id="Lib_Protobuf_Net" />
    </ComponentGroup>

  </Fragment>
</Wix>

A: Looking at your source file there are several problems with your component reference counting outright. You should never install several binaries with one component - it is a direct violation of the component rules. This causes exactly the kind of problems the error message indicates.
I recommend using a single file per component because that solves a plethora of possible reference count issues and upgrade problems. The shared-dll ref counters can also cause some blues I think. Do you have a legacy installer that you are trying to be compatible with? If not, then there is no reason to enable this component option - it increments the legacy SharedDLL ref-counter used by older, non-MSI installer technologies.
Now, for the issue where you change a file name in an existing component. This is also a violation of the component rules. You can not change the absolute file name of a component's key path and keep the same component GUID - this breaks component referencing. There must be a 1-to-1 correspondence between an absolute installation path and a component GUID.
The component GUID doesn't follow the file around if it moves, and the file "moves" when you change its file name (its absolute installation path has changed). There is an explanation here with an example: Change my component GUID in wix? (recommended read - decode this MSI peculiarity and things will be clearer going forward).
If you change a file name you can either:

*

*Set your component GUIDs to auto-generate by deleting the whole GUID section in your source. The GUID will then be generated to be stable as long as the installation target path remains the same, and when you change the file name - for example - a new GUID will be generated for you auto-magically by WiX. See this answer for sample: Syntax for guids in WIX?

*Set a new, hard-coded GUID yourself for the components where you change the file name that is being installed. This can be easy to forget - hence the recommended auto-magic described in point 1.

*What you should actually do when file names change is to remove the old component and add a new one with the new file name. However, changing the GUID of an existing component and changing the file name has the same effect (same as deleting the old component and adding a new one).

With that said, there are bigger problems with this source as explained above. For future reliability you must split these components into one file per component. This causes interference between your old and new version and in order to clean this up, you can:

*

*Set a totally new installation path for your project and use a single component per file from now on and you can use WiX's auto-magic component generation feature as explained above. This will work. Setting a new main installation folder "breaks the link" to "past component referencing sins".

*Or you can uninstall the existing installation early during your major upgrade by moving RemoveExistingProducts early in the InstallExecuteSequence of your newest MSI version. This also wipes the slate clean of any component referencing issues and you can change your source to use one file per component going forward. If you use the MajorUpgrade element this change is easy - just set Schedule="afterInstallValidate". That should work (no time to test).

That should be it - if I have understood your scenario correctly.
Sample WiX extract for the proposed, new version:
<DirectoryRef Id="BIN">
  <Component Feature="Product">
    <File Source="$(var.DirLib)\OurTheme\.td\Publish\DevExpress.Xpf.Themes.OurTheme.v17.2.dll" />
  </Component>
  <Component Feature="Product">
    <File Source="$(var.DirPackages)\CommonServiceLocator.1.3\lib\portable-net4+sl5+netcore45+wpa81+wp8\Microsoft.Practices.ServiceLocation.dll" />
  </Component>
  <Component Feature="Product">
    <File Source="$(var.DirPackages)\Unity.4.0.1\lib\net45\Microsoft.Practices.Unity.Configuration.dll" />
  </Component>
  <Component Feature="Product">
    <File Source="$(var.DirPackages)\Unity.4.0.1\lib\net45\Microsoft.Practices.Unity.RegistrationByConvention.dll" />
  </Component>
  <...>
</DirectoryRef>

Notice the tersified source with all attributes that can be auto-generated left out and all components now containing a single file. There is also direct specification of what feature each component belongs to as an attribute of the Component element. I find that this yields the least complicated and most flexible WiX source files. Preferences vary - obviously.
I would not roll with your current "multiple binaries per component" setup going forward. There will be more trouble if you do - almost guaranteed. MSI bites back - sorry to say - there are many bear traps. MSI has aspects that border on anti-patterns. The problems are faced by almost everyone. There is a section towards the bottom here on potential anti-patterns and also on the great benefits MSI yields for corporate deployment (just for reference): How to make better use of MSI files.
I am not particularly keen on this chaotic write-up of common MSI problems, but here it is: How do I avoid common design flaws in my WiX / MSI deployment solution? Maybe it can help to avoid some very common problems.

A: I finally found the issue:
It appears that DevExpress bin directory packs the System.Windows.Interactivity.dll library. So before we were not copying it and we didn't had it in our Lib\DevExpress folder.
It appears that we generate a componet with all Dll contained in the Lib\DevExpress folder, and therefore the System.WIndows.Interactivity.dll was contained in 2 differents packages.
I removed it from the DevExpress folder and now everything works fine. Sorry for the trouble.


text:
Q: How to deploy entity framework code first for a standalone app I have just finished an standalone desktop application in C# and .Net. For the app, I need to access several existing SQL Server tables for various data. I accomplished it with Entity Framework 6 code first. My question is how I should update the connection string in app.config during a customer installation to reflect customer's SQL Server configurations. What steps are generally involved? What options are available to me? I'll use Inno Setup for the app installation.
Thank you.


text:
Q: ¿Cómo puedo pedir datos para un array separados por espacios? (JavaScript) Estoy estudiando Javascript y me he topado con un ejercicio el cual me pide que introduzca una serie de números separados por espacios y una vez haya terminado presionando el botón aceptar, almacene dichos valores en un array.
Sé introducir valores en un array siempre y cuando haya definido antes cuántos valores voy a introducir, pero en este caso no sé cómo se hace.
Es importante aclarar que se me solicita realizar el ejercicio haciendo uso de prompt.
Gracias.

A: Puedes usar el metodo split() sobre un string para obtener un array.
Funciona de la siguiente manera:
function stringToArray(){
  var texto = "valor1 valor2 valor3 valor4";
  var array = texto.split(' ');
  console.log(array);
}

Pues lo que hace split() es dividir una cadena por un separador y guardar los valores divididos en un array resultante, el metodo split() recibe el caracter separador. Si fuera una coma sería split(',').
Edit:
function promptToArray(){
  var texto = prompt("Introduzca los valores separados por espacios:");
  var array = texto.split(' ');
  console.log(array);
}


text:
Q: Lerp rotation angles clock or counter-clockwise I'm trying to find an implementation of angle lerp (linear interpolation) that allows you to specify direction (clock or counter-clockwise). Most implementations I found rely on the shortest path possible, for example:
https://gist.github.com/shaunlebron/8832585
I'd like to have a function like:
// from        = angle where to start
// to          = target angle
// direction   = wether to reach "to" clock or counter clock wise
// progress    = 0-1 progress range 0 = from value 1 = to value.

function angle_lerp(from, to, direction, progress) {}

Here are a couple of examples to further clarify the expected behavior of the function. All examples are based on a 0-360 degree range:
# clockwise (short path)
angle_lerp(from=350, to=10, direction=clockwise, progress=0) = 350
angle_lerp(from=350, to=10, direction=clockwise, progress=0.5) = 0
angle_lerp(from=350, to=10, direction=clockwise, progress=1) = 10

# counter-clockwise (long path)
angle_lerp(from=350, to=10, direction=counter, progress=0) = 350
angle_lerp(from=350, to=10, direction=counter, progress=0.5) = 180
angle_lerp(from=350, to=10, direction=counter, progress=1) = 10

# clockwise (short path)
angle_lerp(from=90, to=180, direction=clockwise, progress=0.33333) = 119.7
angle_lerp(from=90, to=180, direction=clockwise, progress=0.5) = 135
angle_lerp(from=90, to=180, direction=clockwise, progress=0.8) = 162

# counter (long path)
angle_lerp(from=90, to=180, direction=counter, progress=0.33333) = 0
angle_lerp(from=90, to=180, direction=counter, progress=0.66666) = 270

example where from is "ahead" of to:
# clockwise (long path)
angle_lerp(from=45, to=0, direction=clockwise, progress=0.1) = 76.5
angle_lerp(from=45, to=0, direction=clockwise, progress=0.5) = 202.5
angle_lerp(from=45, to=0, direction=clockwise, progress=0.95) = 344.25

# counter (short route)
angle_lerp(from=45, to=0, direction=counter, progress=0.1) = 40.5
angle_lerp(from=45, to=0, direction=counter, progress=0.5) = 22.5
angle_lerp(from=45, to=0, direction=counter, progress=0.95) = 2.25

A: Assuming the usual convention (angles increase in the counter-clockwise direction), here is a PHP solution.
$from and $to are normalized angles (between 0 and 360).
$cw is a boolean (true for clockwise, false for counter-clockwise).
$progress is between 0 and 1.
function angle_lerp($from, $to, $cw, $progress)
{
    if($cw)
    {
        // Clockwise
        if($from < $to)
            $to -= 360;
    }
    else
    {
        // Counter-clockwise
        if($from > $to)
            $to += 360;
    }
    return $from + ($to-$from)*$progress;
}

Examples:
echo angle_lerp(350, 10, true, 0.5); // 180
echo angle_lerp(350, 10, false, 0.5); // 360


text:
Q: Not sure where to post a networking/NAS question I have a question that pertains to networking and a Synology NAS. I'm not a network administrator, just the most tech savvy person at our small company. The question is mainly about an unusual network configuration on a Synology NAS.
Server Fault looked more advanced than this question but I couldn't find anything closer.

A: A Synology NAS is, as far as I know, mainly a consumer product. As such questions about these kind of products can be on-topic on Super User:

Super User is a question and answer site for computer enthusiasts and power users

A quick search reveals some related posts. If you're lucky you'll find your answer there or help you to bring the right focus to your question. Do check their help center and meta to verify if your actual question is indeed  a good fit.


text:
Q: PHP: letting your own function work with a while loop $qVraagGroepenOp = "SELECT * FROM $tabele WHERE $where";
    $rVraagGroepenOp = mysql_query ( $qVraagGroepenOp );
    $aVraagGroepenOp = mysql_fetch_assoc ( $rVraagGroepenOp )
and I converted that to a function
vraagOp("testtable","testtable_ID = $id");

function vraagOp($table,$where)
{
    $qVraagOp = "SELECT * FROM $table WHERE $where";
    $rVraagOp = mysql_query( $qVraagOp );
    $aVraagOp = mysql_fetch_assoc( $rVraagOp );

    return $aVraagOp;
}

only the problem is when i need more then one row i need to use a while loop
$qVraagGroepenOp = "SELECT * FROM testtable where testtype = test";
$rVraagGroepenOp = mysql_query ( $qVraagGroepenOp );
while ( $aVraagGroepenOp = mysql_fetch_assoc ( $rVraagGroepenOp ) )
{
     echo "testing
";
}

It wont work anymore is there a trick to make my function work with this while loop?
This won't work but I want to reach to something like it
while (vraagOp("testtable","testtype = test"))
{
   echo "testing
";
}

Is this possible?

A: This could be done with static variables in the function scope.
function vraagOp($table,$where)
{
    static $rVraagOp;
    if(!$rVraagOp){
        $qVraagOp = "SELECT * FROM $table WHERE $where";
        $rVraagOp = mysql_query( $qVraagOp );
    }
    return mysql_fetch_assoc( $rVraagOp );
}

That should do what you're after.

A: This function returns an array of rows - it's a generic pattern yu can use almost anywhere you get multiple rows from a query.
function vraagOp($table,$where)
{
    $sql= "SELECT * FROM $table WHERE $where";
    $query= mysql_query($sql);
    if ($query != false)
    {
        $result = array();
        while ( $row = mysql_fetch_assoc($query) )
            $result[] = $row;
        return $result;
    }

    return $false;
}
//usage
$rows = vraagOp($table,$where);
if ($rows)
{
    foreach ($rows as $row)
        use($row);
}

A: This function will 'cache' the mysql result resource from each unique $table/$where combination, and fetch the next result from it on each subsequent call.  It will return an associative array for each row, or false when there are no rows left.
function vraagOp($table, $where)
{
    // Holds our mysql resources in a map of "{$table}_{$where}" => resource
    static $results = array();

    $key = $table . '_' . $where;

    if (!isset($results[$key]))
    {
      // first call of this particular table/where
      $results[$key] = mysql_query("SELECT * FROM $table WHERE $where");
    }

    $row = mysql_fetch_assoc($results[$key]);

    if ($row === false)
      // remove this key so a subsequent call will start over with a new query
      unset($results[$key]);

    return $row;
}

// Usage

while ($row = vraagOp("table1", "where field > 7")) {
   print_r($row);
}

A: This
while (vraagOp("testtable","testtype = test"))
{
   echo "testing
";
}

will work if you change VraagOp() to return false when no matching record was found.
You would have to move the mysql_query() part out of VraagOp(), and just leave the mysql_fetch_assoc part in.
However, I can't really see what benefit there would be? You would just be building a (unnecessary) wrapper around mysql_fetch_assoc(), wouldn't you?

A: You'll need to turn vraagOp() into an iterator and then use foreach() in order to make this work.

A: Your example won't work because the condition is executed on every iteration. That means vraagOp("testtable","testtype = test") would be called with each iteration until it returns a falsely value. mysql_fetch_assoc does that but your function doesn't.

A: How can we call function inside while loop example is below :
$sql_gpfsF="SELECT * FROM emp_salary";

$result_gpfsF=mysql_query($sql_gpfsF);

while($row_gpfsF=mysql_fetch_assoc($result_gpfsF))
{

call_function();

}

function call_function()
{

echo " Function Called
";

}


text:
Q: How to get access of data from multiple key in two or more depth without looping I am using redis for get data from server.
I am creating stream for following which is having structure like this
Sadd user_following_key user1_id, user2_id, user3_id
#data which i want to access is stored like this
zadd user1_id_key  data1
zadd user2_id_key data2
#And data1 data2 ... are set which is stored like this
Set data1 some_data
set data2 some_data

I want to access data1 data2 ... and some_data without running loop over user_following_key return data and also if two or more key are same then only one should come.

A: Put differently, for each user_id in user_following_key, you want to access the relevant user_id key, retrieve the data key name from it and then fetch the value of the data key. In that case, you must loop over the contents of user_following_key (and over every multi-valued key) in this dereference chain and have multiple calls, per depth/length.
Note: in similar cases Lua could be used to reduce network traffic and latency, but since you'll be actually programmatically dealing with key names inside the script (i.e.g. user_id1), it will make the script unsafe in terms of Redis cluster and against best practices.


text:
Q: Handwritten character template matching in Matlab Working with template matching of handwritten data input but face some problems for being very new in Matlab. I want to match this template

with this one..

So far i did is:
function result=test(image1,image2)
%*********************************************************

    image1=rgb2gray(image1);
    image2=rgb2gray(image2);

% check which one is target and which one is template using their size

if size(image1)>size(image2)
    Target=image1;
    Template=image2;
else
    Target=image2;
    Template=image1;
end

% find both images sizes
[r1,c1]=size(Target);
[r2,c2]=size(Template);
% mean of the template
image22=Template-mean(mean(Template));

%corrolate both images
M=[];
for i=1:(r1-r2+1)
    for j=1:(c1-c2+1)
        Nimage=Target(i:i+r2-1,j:j+c2-1);
        Nimage=Nimage-mean(mean(Nimage));  % mean of image part under mask
        corr=sum(sum(Nimage.*image22));
        %warning off
        M(i,j)=corr/sqrt(sum(sum(Nimage.^2)));
    end
end
% plot box on the target image
result=plotbox(Target,Template,M);

For plotbox..
function result=plotbox(Target,Template,M)

%*********************************************************
[r1,c1]=size(Target);
[r2,c2]=size(Template);

[r,c]=max(M);
[r3,c3]=max(max(M));

i=c(c3);
j=c3;
result=Target;
for x=i:i+r2-1
   for y=j
       result(x,y)=255;
   end
end
for x=i:i+r2-1
   for y=j+c2-1
       result(x,y)=255;
   end
end
for x=i
   for y=j:j+c2-1
       result(x,y)=255;
   end
end
for x=i+r2-1
   for y=j:j+c2-1
       result(x,y)=255;
   end
end

And for testing i use..
% read Template image
im1=imread('C:\Users\Shuvro\Desktop\New folder\1.jpg');
% read Traget Image
im2=imread('C:\Users\Shuvro\Desktop\New folder\2.jpg');
% apply templete matching using power of the image
result1=test(im1,im2);
figure,
subplot(2,2,1),imshow(im1);title('Template');
subplot(2,2,2),imshow(im2);title('Target');
subplot(2,2,3),imshow(result1);title('Matching Result using tmp');

But this code often can't identify that template in the source image,not understanding what wrong was there.Anybody can help?
Basically when i input 2 images to the system,i want to make their height similar.Then i want to measure template image width and then i want to scan the source image according to that width and examine pixel values.When those pixel values of template will match with source image over 70% then i will give the result that it is found,otherwise not found.
This is what i am thinking to do this.Highly appreciated if anybody can help with above code by editing it or giving suggestions.

A: First of all I want to warn you that size(image1)>size(image2) is a vector comparison, usually you will not want to do it like that. (Perhaps with all or any).
That being said:
In this specific case the only way to figure out why your code doesn't do what you expect is to load inputs that it should match but doesn't. Then step through the code line by line untill you see any behavior that is unexpected.

Of course you could also just try to search for pattern matching functions for matlab, there should be some that you can find on google, or perhaps even on stackoverflow.


text:
Q: Why I am facing the condition problem in C? What is going wrong here? If I enter 4123456789098 then by dividing this number with 10^12 it should be equal to 4 but it is not?
My code:
#include <stdio.h>
#include <cs50.h>
#include <math.h>

int main(void)
{
    while (true)
    {
        long long int id = get_long("Number: ") ;
        int k = 0 ;
        while (id != 0)
        {
                id = id / 10 ;
                k++ ;
        }
        printf("%i\n", k) ;

        // VISA

        if (k == 13)
        {
            int x = id / pow(10 , 12) ;

            if (x == 4)
            {
                printf("VISA\n") ;
                break ;
            }

            else
            {
                printf("INVALID V\n") ;
            }
        }

        // AMEX

        else if (k == 15)
        {
            int y = id / pow(10 , 13) ;

            if (y == 34 || y == 37)
            {
                printf("AMEX\n") ;
                break ;
            }

            else
            {
                printf("INVALID A\n") ;
            }
        }

        // VISA or MASTERCARD

        else if (k == 16)
        {
            int z_M = id / pow(10 , 14) ;
            int z_V = id / pow(10 , 15) ;

            if (z_M >= 51 && z_V <= 55)
            {
                printf("MASTERCARD\n") ;
                break ;
            }

            else if (z_V == 4)
            {
                printf("VISA\n") ;
                break ;
            }

            else
            {
                printf("INVALID V or A\n") ;
            }

        }

    }
}

Output:
Number: 4123456789098
13
INVALID V

Expected Output:
Number: 4123456789098
13
VISA

A: You are modifying the value of original id variable. Then when you are trying to find first digit with int x = id / pow(10, 12). x will always be zero as id will always be zero. One thing you can do is to store the value of id in some temporary variable.
You can change this from
while (id != 0)
{
     id = id / 10 ;
     k++ ;
 }

to this:
long long temp = id;
while (temp != 0)
{
    temp = temp / 10 ;
    k++ ;
 }


text:
Q: How do the uniform_*_distribution classes in C++ get an equal distribution? I assume that the uniform_*_distribution classes produce a jitter-free equal distribution of all values if the random-generator feeding this classes produces "good" random values. But how does f.e. uniform_int_distribution guarantee a jitter-free equal distribution when feeded by a mt19937_64 ? With my current knowledge I would produce a solution that wouldn't be jitter-free beging feeded by result_type values.
[EDIT]: I have to clarify my wording of a jitter since this seems rather  uncommon for some people here. Jitter means that when you compress or expand a eange through integral division or multiplication, you don't get a clean equal distribution. So there must be another way to to that.

A: By discarding values.
Let's say, as a simple example, that you have a random generator that will give you integers between 0 and 7 (that is, it has a range of 8 values) and you want to use that with a uniform_int_distribution(0,3) which is supposed to output 0, 1, or 2 with equal probability.
The naive approach (and the one I think you were considering, given your "jitter" concept) would be to generate a single sample, multiply by 3.0/8.0, and round down. But this would yield 0 and 1 at a higher frequency than 2. And in fact, any approach which sampled the generator exactly once would be guaranteed to be biased, as can easily be demonstrated using the Pigeonhole principle.
Instead, the distribution will conditionally throw away some values which it gets from the generator, effectively reducing the generator's range to one which it can map to the appropriate distribution. In our example, the distribution could throw away values until it finds one in the range [0,6), and then return that value mod 3. So 0 and 3 would map to 0; 1 and 4 would map to 1; 2 and 5 would map to 2; and 6 and 7 would "not count".
[Particularly for continuous distributions, this may or may not be done in a way which leads to exactly unbiased probabilities for each value in the range... and in fact, for some common distributions it would be impossible to do so in a finite amount of time. Nevertheless, that's the basic approach.]


text:
Q: How to launch an EXE as an argument in java, but still with parameters I'm in a situation where I need to launch a .exe, but I meed to launch it with parameters, AND it needs to be launched as an argument itself, but cant be launched from a command line. I need to launch javaw itself, with my exe as an argument. For example:
"C:\Program Files\Java\jre7\bin\javaw.exe" -jar "PATH/TO/.exe"

However, "PATH/TO/.exe" needs -arg1 and -arg2. Placing the parameters inside of the path leads to java not finding them, whereas placing them outside leads to java thinking they belong to itself and trying to use them.
EDIT: I am running the exe with java because I am using a completely different program to start all this. I cannot use a different java program, all I have to work with is the target box. It is designed to start exe's, but I need to run the exe through java. ALL I have to use is the path area where you would usually type where the exe is located.

A: The basic trick is:
try {
    final Process p = Runtime.getRuntime().exec(ARRAY_OF_EXE_AND_ARGUMENTS);
    if (p == null) {
        // some error
        // probably command not found, abort.
    }

    try {
        final int retval = p.exitValue();
        if (retval == 0) {
            // Process ended immediately.
            // Probably a problem, abort.

        } else {
            // Process crashed, abort.

        }
    } catch (final IllegalThreadStateException itse) {
        // Process is running.
        // all is good
    }
} catch (final IOException e) {
    // Error running exe, abort.
}

Where ARRAY_OF_EXE_AND_ARGUMENTS is a String array, where first is path to the executable, and following are it's command-line arguments.
To pass the exe and argumetns to java, this is the common pattern:
java -jar MyJar.jar "/path/to/virus.exe argument1 argument2"

And then you split it by space or something.


text:
Q: Webservice - Use username in function after login I'm creating a web service with user authentication via HTTP. The authentication is done in @auth.get_password:
from flask.ext.httpauth import HTTPBasicAuth

@auth.get_password
def getPassword(user):
   if user == 'dummy':
       return password
   else:
       return None

Now I want to create a function where I can also use this given username, e.g. for changing user's password:
# Change password
@app.route('/users/change_password/', methods=['PUT'])
@auth.login_required
def changeUserPassword(user):
    return user + ", You want to change your password"

But there is no "user" variable. How can I pass the "user" to the function changeUserPassword() ? I do not want to start a session or something because I'm trying to build a RESTful web service.

A: With flask-httpauth, you can use auth.username() to get the current user
@app.route('/users/change_password/', methods=['PUT'])
@auth.login_required
def changeUserPassword(user):
    return auth.username() + ", You want to change your password"


text:
Q: Using Jaxb Marshalling how can I override the XML Element names at runtime In my code I have a class which is populated from a REST CALL like so:
    RestTemplate restTemplate = new RestTemplate();
    String JSONStr = restTemplate.getForObject(urlStr, String.class);
    Gson gson = new Gson();
    Products items = gson.fromJson(JSONStr, Products.class);

Then later I write the the list as XML
         JAXBContext jaxbContext = JAXBContext.newInstance(ProductsList.class);
     Marshaller productMarshaller2 = jaxbContext.createMarshaller();
     productMarshaller2.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
     OutputStream outputStream = new FileOutputStream("xml\\products.xml");

     for (int index = 0; index < items.size(); index++){
            System.out.println("Index = " + index);
         ProductsList productList = items.get(index);
         productMarshaller2.marshal(productList, outputStream);
     }
     outputStream.close();

This all works great and provides the expected output. The problem I have is that the JSON that I get has field names like "atr_203948" and I need to place them with names like "color" - but can not know the mapping between the names ahead of time. At runtime I have to execute a DB lookup to get the current map. The DB look up is easy and I have code that creates a HashMap with the oldName,newName pairs but I do not know inject that knowledge into the output of the Marshaller. Any help would be greatly appreciated.


text:
Q: Custom command definition in magnolia I created a custom command in a magnolia custom module using:
public class ExportToGitCommand extends BaseRepositoryCommand

and I configure it in JCR manually at the moment.
What is the best practice regarding the definition of a custom command in a custom module?
Where in the JCR structure should one define it? I am asking this so that I can use it later (eg. for the pages app).
Also how can I get the definition from JCR programatically in the custom module?

A: For best practices, best place to look at is the documentation. Typically, each module creates its own command catalogue (folder) to ensure there's no collision in name of commands and store custom commands it defines under such catalogue.
To use such command from an action in other app you just create new action in the desired app and reference the custom command you want to call.


text:
Q: Calculate average number of days between two dates for unique fields I need some help with a single formula in finding unique tasks and then getting the average between two dates.  Looking at the below example:

Task        Closed        Created
Task1  3/13/2018     1/1/2018
Task1  3/13/2018     1/1/2018
Task1  3/13/2018     1/1/2018
Task2  3/13/2018     2/1/2018
Task2  3/13/2018     2/1/2018
Task3  3/13/2018     3/1/2018

I need to take Task1 and subtract 3/13/2018 from 1/1/2018 to get 71
I need to take Task2 and subtract 3/13/2018 from 2/1/2018 to get 40
I need to take Task3 and subtract 3/13/2018 from 3/1/2018 to get 12
This gives me an average answer of 41

Is there a formula I can use to get this answer of 41?  I tried {=AVERAGE(B2:B6 - C2:C7)}, but I don't know how to have it first check if unique.  Something like {=If A2:A7 is Unique, AVERAGE(B2:B6 - C2:C7)}
To complicate things further, there are times when there will be no values in column B (Closed)

A: You can use this formula in an adjacent column to count the occurrences of each task:
=COUNTIF(A$1:A1,A1)
You need to put this into the first row and drag-to-fill it down the column. This causes it to transpose correctly to produce the desired result. The formula counts how many rows up to the current row contain the same value:
Task1   1
Task1   2
Task2   1
Task3   1
Task1   3
Task4   1
Task2   2
Task3   2

Then, use another formula in a new column to capture the date difference but only when the occurrence count equals 1:
=IF(D1=1,B1-C1,"")
Task1   1/01/2011   1/01/2010   1   365
Task1   1/01/2011   1/01/2010   2
Task2   4/01/2011   1/04/2010   1   278
Task3   6/01/2011   1/06/2010   1   219
Task1   1/01/2011   1/01/2010   3
Task4   10/01/2011  1/10/2010   1   101
Task2   4/01/2011   1/04/2010   2
Task3   6/01/2011   1/06/2010   2

Then average the last column.
You can of course combine the two formulae above - I simply provided both for explanation's sake.
Note that the dates don't affect the occurrence count - only the first occurrence will have the date calculation (so this assumes you don't allow different date ranges for different rows otherwise this can't work - your example shows duplicate date ranges).
You need to decide what you want to do with your empty column B. For example you can ignore non-closed tasks in the date difference formula as follows:
=IF(AND(NOT(ISBLANK(B4)),D4=1),B4-C4,"")


text:
Q: Shiny column formatting issue I am trying to horizontally align an actionButton with a textInput field.
Since the "next_question" actionButton and the "correct" textInput field are in the same fluidRow I thought they would be horizontally aligned. They are not.
Also, I thought choosing a higher column number for the "yup" box would move it further to the right. Again, not the case.
What am I missing?
library(shiny)

shinyApp(
  ui = fluidPage(

    sidebarLayout(
      sidebarPanel(

        textInput("answer", width = "50px", label = "Answer"),

        fluidRow(
          column(2, actionButton(inputId = "next_question", label = "Next")),
          column(8, textInput(inputId = "correct", width = 30, label = "yup"))
        )
      ),

      mainPanel(
        # Equation
        textOutput("equation")
      ))),

  server = function(input, output, session){}
)

A: The solution is to add a small css to display:inline-block.
library(shiny)

shinyApp(
  ui = fluidPage(

    sidebarLayout(
      sidebarPanel(

        textInput("answer", width = "50px", label = "Answer"),

        fluidRow(

                 actionButton(inputId = "next_question", label = "Next"),
                 tags$div(textInput(inputId = "correct", label = "yup"), style = "display:inline-block")

        )
      ),

      mainPanel(
        # Equation
        textOutput("equation")
      ))),

  server = function(input, output, session){}
)

Reference: https://www.w3schools.com/Css/tryit.asp?filename=trycss_inline-block_nav


text:
Q: Use SQL Group By or Window Function to analyse rows in time sequence? I have a table with data like the following:
+-----+--------+-------+--------+---------+----------------------+
| ID  |  Name  |  Lat  |  Long  |  Speed  |       DateTime       |
+-----+--------+-------+--------+---------+----------------------+
|  1  |  Test  |   121 |  2131  |      0  |  10-11-2018T12:00:00 |
|  1  |  Test  |   121 |  2131  |    100  |  10-11-2018T12:10:00 |
|  1  |  Test  |   121 |  2131  |      0  |  10-11-2018T01:00:00 |
|  1  |  Test  |   121 |  2131  |    102  |  10-11-2018T01:10:00 |
+-----+--------+-------+--------+---------+----------------------+

I need to get:
+---------+-----------------------+---------------------+
|         |         from          |         to          |
+---------+-----------------------+---------------------+
| stop    |  10-11-2018T12:00:00  | 10-11-2018T12:10:00 |
| moving  |  10-11-2018T12:10:00  | 10-11-2018T01:00:00 |
| stop    |  10-11-2018T01:00:00  | 10-11-2018T01:10:00 |
| moving  |  10-11-2018T01:10:00  | null                |
+---------+-----------------------+---------------------+

A: You can try to use ROW_NUMBER with CASE WHEN and lead window function to make it.
select CASE WHEN ROW_NUMBER() over( order by (SELECT NULL)) % 2 = 0 THEN 'Move' ELSE 'Stop' END,
       [DateTime] 'from',
       lead([DateTime]) over(order by (SELECT NULL)) 'to'
from t

sqlfiddle
But I think you might want to use order by DateTime
select CASE WHEN ROW_NUMBER() over(partition by ID order by DateTime) % 2 = 0 THEN 'Move' ELSE 'Stop' END,
      DateTime 'from',
      lead(DateTime) over(partition by ID order by DateTime) 'to'
from t

A: You can join the table on itself using ID and adjacent DateTime values. This considers the scenario where rows aren't always alternating between stopped and moving.
SELECT
    CASE WHEN t1.Speed <> 0 THEN 'moving'
    ELSE 'stop' END as 'movingStatus',
    t1.DateTime as 'from',
    t2.DateTime as 'to'
FROM MyTable t1, MyTable t2
WHERE
    t1.ID = t2.ID
    t2.DateTime = (SELECT MIN(DateTime) FROM MyTable WHERE DateTime > t1.DateTime)


text:
Q: element not found via xpath I have a button:
 <button type="submit" class="btn btn-default btn-auth">Anmelden</button>

nightwatch doesn't find it these ways:
browser.waitForElementPresent('//button[@class="btn btn-default btn-auth"]', 5000);
browser.waitForElementPresent('//button[contains(@class, "btn btn-default btn-auth")]', 5000);
browser.waitForElementPresent('//button[text()="Anmelden"]', 5000);
browser.waitForElementPresent('//button[contains(text(), "Anmelden")]', 5000);

but it is found this way:
browser.waitForElementPresent('.btn.btn-default.btn-auth');

Why are the 4 commands above not working? I have to checkout for text() because I have multiple buttons with the same class.

A: If you want to find element by XPath, instead of class/id try this:
browser.useXpath().waitForElementPresent('//button[contains(@class,"btn-auth") and contains(text(),"Anmelden")]', 5000);

A: Use this xpath;
//button[.="Anmelden"]


text:
Q: Can I guarantee all listeners have executed on the next line after dispatching an event? There's a few questions on stack overflow on this topic but I'm still unclear:
I know the flash engine is single threaded so when it receives an event, does it essentially break off, execute any registered event listeners (in no guaranteed order) then return to the current scope?
If I have this code:
addListener("stuff", function():void {
     // some stuff
});
addListener("stuff", someFunc);
dispatch(new Event("stuff"));
trace("Done.");

I want to know:
Can I guarantee that both listeners have executed by the time I reach the trace("Done"); line?
edit:
or
can I guarantee that the current function will complete before any of the event listeners execute? ie trace("Done"); will ALWAYS execute first.
or
Neither.

A: It is guaranteed that both event handlers will be called before trace because user code generated events are synchronous:
Does dispatching an event interrupt a function?

A: From what I know, when you dispatch an event it gets added to the event queue, but won't actually run until the currently-executing event finishes. In other words, you'll trace "Done.", then your function ends, control passes back to the event handler, and only then does it (maybe) start executing one of your events.

A: Yes, you can guarantee both assertions in this exact situation.
Meaning, that if adding your event listeners and dispatching your event is in the same code block it will happen in sequence. However, from a practical POV that's completely useless.
@kryoko: player events get precedence over user events, but they do not 'force' themselves through. Meaning that if user code is running, the player event handling is suspended. That's why it's possible to 'freeze' a flash movie with heavy, intensive code. (Or with a simple infinite loop, of course)


text:
Q: Ubuntu: Error NU1301 unable to load the service index for source I have created C# project using .Net 6.0 to run Event grid trigger azure function. It is running fine in windows.
I installed Windows subsystem for Linux(WSL) on my Windows 11 OS.
I am using Visual Studio Code. When I ran dotnet restore command on wsl terminal, it is giving error - /mnt/c/Code/Code/Test.csproj : error NU1301: Unable to load the service index for source https://microsoftit.pkgs.visualstudio.com/_packaging/**/nuget/v3/index.json.
I am using Ubuntu 18.04 distribution for Linux in WSL.
How can I solve this issue ?

A: This is a known issue when using .NET 6 Preview in WSL. The workaround is to add the Microsoft package source directly in your csproj file:
<PackageSource Include="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet6/nuget/v3/index.json" />

Then run dotnet restore again and it should work.
This issue will be addressed in a future preview update.
Note: You'll also need to install the dotnet-sdk-6.0 Preview in WSL, not just dotnet-sdk.
Update: This issue is now fixed in .NET 6 Preview 4, so you no longer need the workaround. Just install the latest preview and dotnet restore should work without manually adding the package source.


text:
Q: How make query with unique? I have query:
SELECT TOP 20 f.id_service AS f_id_service,
              f.id_city    AS f_id_city,
              f.name       AS f_name,
              f.address    AS f_address,
              f.business   AS f_business,
              f.web        AS f_web,
              f.phone      AS f_phone,
              f.id_firm    AS f_id_firm
FROM   Firm f
       LEFT JOIN Price p
         ON p.id_service = f.id_service
            AND p.id_city = f.id_city
            AND p.id_firm = f.id_firm
WHERE  f.name NOT IN (SELECT DISTINCT TOP 20 f.name
                      FROM   Firm f
                      WHERE  f.blocked = '0'
                             AND ( f.name LIKE 'АВТО%'
                                    OR f.phone LIKE 'АВТО%' )
                             AND ( f.phone != ''
                                    OR f.address != '' )
                             AND f.id_city = '73041'
                      ORDER  BY f.name ASC)
       AND f.dogovor = '1'
       AND f.blocked = '0'
       AND ( f.name LIKE 'АВТО%'
              OR f.phone LIKE 'АВТО%' )
       AND ( f.phone != ''
              OR f.address != '' )
       AND f.id_city = '73041

Tell me please how make this query that select only unique f.name ?

A: Change the SELECT to this
SELECT DISTINCT TOP 20
    f.name as f_name
FROM ...

You can't have all columns values but DISTINCT just one of them: it makes no sense.

A: Try this
SELECT DISTINCT
TOP 20
f.id_service as f_id_service,
f.id_city as f_id_city,
f.name as f_name,
f.address as f_address,
f.business as f_business,
f.web as f_web,

A: Use the DISTINCT keyword:
SELECT DISTINCT
TOP 20
f.id_service as f_id_service,
f.id_city as f_id_city,
f.name as f_name,
f.address as f_address,
f.business as f_business,
f.web as f_web,
f.phone as f_phone,
f.id_firm as f_id_firm FROM Firm f
left join Price p on p.id_service=f.id_service
AND p.id_city=f.id_city AND p.id_firm=f.id_firm
WHERE
f.name NOT IN (
SELECT DISTINCT TOP 20 f.name FROM Firm f
WHERE f.blocked='0'
AND (f.name LIKE 'АВТО%' OR f.phone LIKE 'АВТО%')
AND (f.phone !='' OR f.address != '') AND f.id_city='73041'
ORDER BY f.name ASC ) AND f.dogovor='1'
AND f.blocked='0' AND (f.name LIKE 'АВТО%' OR f.phone LIKE 'АВТО%')
AND (f.phone !='' OR f.address != '')
AND f.id_city='73041'

Because all your columns are from the one table, unless name is unique in the firm table, you can't use DISTINCT like this. You would need to decide on which firm is displayed in the case of duplicates then craft a complex query to achieve that.


text:
Q: stunnel : SSL alert (read): warning: close notify we have a stunnel proxy server running on the same box. Basically, our app connects to stunnel proxy server in un-encrypted fashion, and this stunnel proxy server then connects to a remote server ( that remote server belongs to a different company) over TLS.
the relevant configuration are :
client=yes
accept=9998
connect=x.y.z.w:nnnn
verify=level 1

Occasionally, ( once every 2-3 weeks), the connection is down after running a few hours, with following stunnel log :
2018.04.02 10:05:37 LOG7[197784:140586247849728]: SSL alert (read): warning: close notify
2018.04.02 10:05:37 LOG7[197784:140586247849728]: SSL closed on SSL_read
2018.04.02 10:05:37 LOG7[197784:140586247849728]: Socket write shutdown
2018.04.02 10:05:37 LOG7[197784:140586247849728]: Socket closed on read
2018.04.02 10:05:37 LOG7[197784:140586247849728]: SSL write shutdown
2018.04.02 10:05:37 LOG7[197784:140586247849728]: SSL alert (write): warning: close notify
2018.04.02 10:05:37 LOG6[197784:140586247849728]: SSL_shutdown successfully sent close_notify
2018.04.02 10:05:37 LOG5[197784:140586247849728]: Connection closed: 25757163 bytes sent to SSL, 937186 bytes sent to socket
2018.04.02 10:05:37 LOG7[197784:140586247849728]: FIX session XXXXXX-XXX finished (1 left)

I am not very clear is it caused by the remote server ( belonging to a different company ) terminating the connection first ?
Any advice ?
Thanks in advance,
Frank