text:
Q: how to use custom ip address to browse a web page c#/.net i am trying to browse web page using custom(user provided) ip address but it's not working. webBrowser1 loads web page successfully but it's not using custom ip address, it loads page with real ip address.
please tell me how to make this work successfully.
this is my code:
private void Form1_Load(object sender, EventArgs e)
    {
        IPAddress addr1 = IPAddress.Parse("192.168.1.100");
        webBrowser1.ScriptErrorsSuppressed = true;
        webBrowser1.Navigate("www.whatismyip.com");
    }

A: You can't change your IP like this. Your code obviously doesn't work, because you've just created a variable of type IPAddress and assigned some value to it. If you want a different IP address that you currently have assigned from your internet provider, you need to use a Proxy or TOR if you can't achieve a change of your IP by restarting your modem. However, it won't obviously allow you to use whatever IP you'd like.


text:
Q: I am using an INI file format to create a Zend Form but I cannot seem to get the options array filled in from the ini Is there a way I can get my the following function ported correctly to the the Zend_Form_Element? I have a custom element and i am passing my own options in for the details of what I am working on: below is the PHP and following will be the INI
$html = $this->helper->formBlah(array(
                'name'=>'foo',
                'value'=>'bar',
                'attribs'=>array('id'=>'boom','rows'=>10),
                'options'=>array(
                        'setup'=>array('mode'=>'exact')
                        )
        ));

now using this functions does the work perfect fine :-) but converting it to an ini is where I get lost in translations:
simple.elements.foo.type = "custom"
simple.elements.foo.options.label = "foo"
simple.elements.foo.id=boom
simple.elements.foo.options.attribs.rows = 10
simple.elements.foo.options.setup.mode = exact

now when I examine my object it looks as if it takes  all options as attribs!
any assistance with this specific problem would be appreciated greatly :-D
Thanks a bunch!!

A: Try:
simple.elements.foo.type = "custom"
simple.elements.foo.options.label = "foo"
simple.elements.foo.id=boom
simple.elements.foo.options.attribs.rows = 10
simple.elements.foo.multiOptions.setup.mode = exact

And here for the related issue http://framework.zend.com/issues/browse/ZF-2711

redpajama_set_name: RedPajamaStackExchange


text:
Q: Timers and threads I have a function which should be called with an interval of 0.5 seconds in its own thread.
Is there a feature in boost or another library which allows to connect a timer which works in callback-like mode and runs callback for a given time interval?

A: You can use boost::asio::deadline_timer for that.

A: I use JUCE for timers. It allows you to subclass the timer class using multiple inheritance, set a timer running, and then define a callback function to handle the timer events extremely easily.
http://www.rawmaterialsoftware.com/
There are probably many libs that offer similar functionality.

A: sounds more like you want a repeating timer with a callback
you can normally do this with boost and binding...here is a good walk though
http://www.boost.org/doc/libs/1_40_0/doc/html/boost_asio/tutorial/tuttimer3.html


text:
Q: How do I compute the CDF and PDF of the following R.V. Let the sample space be $[0,1]$ with the Borel sigma algebra and the probability dx:
$X(\omega)=1/(1-\omega)$.
Am I able to compute the CDF and PDF of that R.V. how? It looks like it is continuous so it should have a pdf. But I can't understand how to compute it.
Edit
Here is my attempt:
By the definition of CDF, we have $P(X \leq x)= P(\frac{1}{1-\omega} \leq x)=P(\frac{1}{x} \leq 1-\omega)=P(\omega \leq 1-\frac{1}{x})$
But because $\omega$ is uniform in [0,1], I can use its Cdf to claim that $P(\omega \leq 1-\frac{1}{x})=1-\frac{1}{x}$ so that $P(X\leq x)=1-\frac{1}{x}$. Am I right?


text:
Q: _iob_func and VS 2015 porting of third party libraries with no source code I am porting a project from VS2013 to VS2015. It links with a third party library Y.lib statically. Unfortunately, we do not have source code of this library.
In final linking stage, i get linker error as
unresolved external symbol __iob_func in X.lib"

where X uses Y.lib.
Breaking changes documentation of VS2015 states that :
If the library is a third-party library for which source is not available, you should either request an updated binary from the third party or encapsulate your usage of that library into a separate DLL that you compile with the older version of the Visual C++ compiler and libraries.
So, my question is whether their is some other workaround that people facing the same problem have figured out ?


text:
Q: typescript: meta on an interface fields i'm trying to create a framework that would allow me to have meta on interface fields. something like this:
function path(path) {}

interface ITwoProps {
  @path('some/path') stringProp: string;
  @path('different/path') boolProp: boolean;
}

class Impl1 implements ITwoProps {
  get stringProp() {
    return 'abc';
  }
  get boolProp() {
    return !!'abc';
  }
}

playground link
unfortunately, this does not even compile. error message is a bit obscure, but the idea is that decorators are implicitly disabled on interfaces. it does make sense, since interfaces do not make it into transpiled code, so there won't be transpiled code to attach decorator to.
i also tried another approach, where i would define meta and interface with schema-like objects and extract interfaces from it:
const Schema = {
  boolProp: {
    type: Boolean,
    path: 'some/path'
  },
  stringProp: {
    type: String,
    path: 'different/path'
  },
};

type PropertyDef<T> = {
  type: (...args: any[]) => T,
  path?: string;
};

type ExtractType<X> = X extends PropertyDef<infer T> ? T : never;

type ObjectInterface<T extends {[key: string]: PropertyDef}> = {
  [P in keyof T]: ExtractType<T[P]>;
}

class Impl2 implements ObjectInterface<typeof Schema> {
  get foo() {
    return !!'abc';
  }
}

playground link
this does not work either, because PropertyDef requires a parameter. also this would probably be harder to support for more complex cases than just an interface.
the question is - how does one combine interface with meta in typescript?
while i mostly interested in making 1st approach work, i'm open to different suggestions, maybe even with transformers that use Compiler API .

A: The approach of decorators on interfaces does not have language support, and as
@Daniel-Rosenwasser hints it probably will not have support. An alternative could be to use abstract classes, you can use implements with classes to just retain the interface of the class and not the code, although it might be a bit confusing.
I would suggest you look at your second approach again though. It only requires an extra <any> to make it work. And it might actually prove more flexibility since you have full control of the metadata system. I played around with creating more complex types using a system similar to this and it can be done. In your case this would work :
const Schema = {
  boolProp: {
    type: Boolean,
    path: 'some/path'
  },
  stringProp: {
    type: String,
    path: 'different/path'
  },
};

type PropertyDef<T> = {
  type: (...args: any[]) => T,
  path?: string;
};

type ExtractType<X> = X extends PropertyDef<infer T> ? T : never;

type ObjectInterface<T extends { [key: string]: PropertyDef<any> }> = {
  [P in keyof T]: ExtractType<T[P]>;
}

class Impl2 implements ObjectInterface<typeof Schema> {
  get boolProp() {
    return !!'abc';
  }
  get stringProp() {
    return '';
  }
}

A: Decorators actually have runtime emit, and are given data based on the declarations they are decorating. Interfaces, on the other hand, have no runtime emit, there's nothing to feed to a decorator other than the name.
So really, the issue you're running into is that TypeScript isn't allowing you to place decorators on interface members because it wouldn't make sense in the absence of a build tool.


text:
Q: How to check if field on desktop application is empty or filled, and if it's filled mark as exception, and if it's empty proceed? I am new to UI path and am trying to build a workflow/sequence to check if a field in my desktop application is filled or not.
If the field is empty then I want to proceed with the process, and if it is filled I want it to be marked as an exception.
I currently have it so the flow goes as follows:
1. Identified element
2. used Text Exists activity for that field, and I inputed "" as the Text
What are the next steps?

A: It would be better if you used Get Text command, and using if condition, check if the text is null or empty and take action.

A: First you want to use Get text on the Text box to extract its contents and store this in a variable in UiPath (Note: if you create the variable from the side properties panel it will give it the type GenericValue, you'll want to change this to String)
Next depends an what you mean by filled:
If you want to accept spaces as been filled then you can use  String.IsNullOrEmpty(YOUR_VARIABLE)
If you want the filed to be filled with characters that aren't spaces you can use
String.IsNullOrWhiteSpace(YOUR_VARIABLE)
for your exception it will depend on weather you want to throw it as an

*

*Application exception (new System.Exception("EXCEPTION MESSAGE"))

or

*

*Businessexception (new UiPath.Core.BusinessRuleException("EXCEPTION MESSAGE"))

So your workflow will want to look something like this


text:
Q: read cell excel win32com My problem is that the price when printing does not move
The price I took from excel

I want to read a cell then print the prices and keep changing
enter code here
from win32com import client as client
import time
excel = client.dynamic.Dispatch("Excel.Application")
excel.Visible= True
wz=excel.Workbooks.Add()
def m():
wp=wz.Worksheets.Add()
   wp.Name = "hihuih"
   time.sleep(10)
   return wp
x=m()
while True:
  p=x.Range("A1:A1").Value
  time.sleep(0.1)
print(p)


text:
Q: What happens if I use the travel system to access DLC content before I unlock the travel system in the plot? I'm at the second playthrough for my level 43 Soldier and my mission log says I'm at the "Getting Lucky" mission. I could do that, or I could access my DLC by using the fast travel system.
...except I haven't unlocked the fast travel system yet in the plot!

This looks eerily like a one-way trip... or is it? What happens if I take the plunge?

A: It's not a one way trip - the fast travel nodes in the DLC content are always enabled, regardless of your progress in the main story line, as the DLC is treated as completely separate from the story line with only a few minor restrictions (like level) in order to access them.
For example, I created a new character and went off to Mad Moxxie's Underdome, not only was I allowed to travel to the Underdome (even though I hadn't unlocked the fast travel system and my fast travel list looked like your screenshot but with all of the DLC travel points in it) and travel back using the fast travel system at the Underdome.


text:
Q: ionic 2 : variable is modified but doesn't change in the view HTML I'm new to ionic 2 and I have a problem you guys might think it's easy to handle, but i'm blocked on it.
I have a variable that I want to show in my page (on the smartphone screen), I put that variable between {{ myVar }} and it is display by the HTML on the screen. Till here, no problem. When the value of myVar change because i press a button, the value is updated to the screen too. But when a function does modify the value of myVar, the value of myVar is update in the code (i saw it on console.log) but not in the view of the screen.
Can you guys help me out please, I didn't find any information about this problem. Maybe there is a tutorial somewhere that explain how it works?
Thank you
EDIT : Sorry, I wasn't sure if my source code would help, but here we go :
My code go like this, I scan devices around with BLE. And it display the result of all the devices with BLE available, I connect to the one I need and display all the services that the device provides. (I use cordova plugin BLE)
This is the HTML view of all the service that the device i am connected to provides.
<ion-header>
 <ion-navbar>
  <ion-title>{{device.name}}</ion-title>
 </ion-navbar>
</ion-header>
<ion-content>
 <ion-buttons>
  <button ion-button (click) = "disconnect(device.id)" block>Disconnect</button>
 </ion-buttons>
 <ion-card *ngFor="let characteristic of characteristics">
 <ion-card-header>UUID: {{characteristic.characteristic}}</ion-card-header>
<ion-card-content>

Properties: {{characteristic.properties}}

    Service: {{characteristic.service}}

  <ion-buttons end>
    <button *ngIf="displayNotifyButton(characteristic.properties)== true" ion-button (click)="startNotify(device.id, characteristic.service, characteristic.characteristic)" round>Notify</button>
  </ion-buttons>
</ion-card-content>
</ion-card>

AMOUNT OF MONEY : {{money}}

What it's important here, is the button Notify that runs the function startNotify(...). and the paragraph  AMOUNT OF MONEY : {{money}}
{{money}} is the variable that get modified but does not change in HTML view.

Here is the function startNotify :
startNotify(deviceID, serviceUUID, characteristicUUID) {
   this.isNotify = true;
   this.ble.startNotification(deviceID, serviceUUID, characteristicUUID).subscribe(buffer => {
   var dataView = new DataView(buffer);
   var coin = dataView.getUint8(0);
   console.log("## NOTIFY VALUE ## " + coin);
   this.sortCoin(coin);
   console.log('## MONEY ## '+ this.money);
   }, error => {
   console.log("## NOTIFY ERROR ## " + error);
   });
 }

Here it's the constructor :
  constructor(public navCtrl: NavController, public navParams: NavParams, private ble: BLE) {
    this.device = this.navParams.get('device');
    console.log("## DEVICE INFORMATION ##" + JSON.stringify(this.device));
    this.connecting = true;
    this.isNotify = false;
    this.connect(this.device.id);
    this.money = 0;
    }

And here it's the sortCoin method, that is only a switch and modify the value of variable money
sortCoin(value){
 switch (value){
  case 1:
    this.money += 0.1;
    break;
  case 2:
    this.money += 0.2;
    break;
  case 4:
    this.money += 0.5;
    break;
  case 8:
    this.money += 1;
    break;
  case 16:
    this.money += 2;
    break;
  case 32:
    this.money += 5;
    break;
  case 65:
    this.money -= 0.1;
    break;
  case 66:
    this.money -= 0.2;
    break;
  case 68:
    this.money -= 0.5;
    break;
  case 72:
    this.money -= 1;
    break;
  case 80:
    this.money -= 2;
    break;
  case 96:
    this.money -= 5;
    break;
 }
}

So my problem is : When a notification is done by the device, it send an array buffer which I interpret and send it to the method sortCoin. In the method sortCoin, the value of the variable money is modified (I can see it with the console log) but the amount doesn't change in the HTML view, which still show 0, because money is set to 0 in the constructor.
I hope my source code will help you to figure my problem out :)
Thank you

A: Ok, I solved my problem with NgZone
this.zone.run(() => {
      this.getValueOf2 = data.amount;
    });


text:
Q: array manipulation with circshift octave / matlab 1) I'm trying to shift an array's (outer cells) first and last cell  inward at the same time.  Here's an inward animation of what I'm trying to do with the array
inward animation.  As you can see the outer cells are moving inward (from the ends) at the same time
Here's a pic but the animation shows it much better please note the array could have either an even or odd amount of cells
Inner rotation steps
1 2 3 4 5 6 7
4 1 2 3 6 7 5
3 4 1 2 7 5 6

2) I'm trying to shift an array's middle cells outward using circshift (which I think is fastest) at the same time.
Here's an outward animation of what I'm trying to do also
outward animation.  As you can see the middle of the signal is moving outward (left and right) at the same time.
Here's a pic but the animation shows it much better please note the array could have either an even or odd amount of cells
Outer rotation steps
1 2 3 4 5 6 7
2 3 4 1 7 5 6
3 4 1 2 6 5 7

Example: inward
a = (1:7)
y=circshift(A,[0 -2]) %shift end of array inward
3   4   5   6   7   1   2

a = (1:7)
y=circshift(A,[0 2]) %shift beginning of array inward
6   7   1   2   3   4   5

Not to sure how to do the middle cells shifting outward using circshift or the outer cells shifting inward at the same time
I'm not sure about how to start circshift from the center and move the array outwards / inwards to get this effect.
Please note I'm not trying to get this equation I'm just trying to get the arrays to move in the same way.  I'm using octave 3.8.1 which is compatible with matlab.

A: A = 1:7;

split = ceil(numel(A)/2);

n = 2;
A(1:split) = circshift(A(1:split), [0, n]);
A(split+1:end) = circshift(A(split+1:end), [0, -n]);

Put the last three lines in a loop if you like. Also just change the signs of n for inwards or outwards

A: what about constructing new indices instead of using circshift:
A = 1:7;

halfLen = ceil(length(A)/2); % or use ceil to
idcsOutward = [2:halfLen,1,length(A),(halfLen+1):(length(A)-1)];

B1 = A(idcsOutward)
B2 = B1(idcsOutward)

% and inward:
idcsInward = [halfLen,1:(halfLen-1),(halfLen+2):length(A),halfLen+1];

C1 = A(idcsInward)
C2 = C1(idcsInward)

Result is:
B1 =
     2     3     4     1     7     5     6

B2 =
     3     4     1     2     6     7     5

C1 =
     4     1     2     3     6     7     5

C2 =
     3     4     1     2     7     5     6


text:
Q: Loading Gif Page Does not load background images I have a gif that appears as my site is loading however the gif dissapers and the page appears after everything has loaded except the background images called via css.
How could I have the gif fade away only after the background images have loaded.
I am using this code for the loader:
html:

css:
html {
    -webkit-transition: background-color 1s;
    transition: background-color 1s;
}
html, body {
    /* For the loading indicator to be vertically centered ensure */
    /* the html and body elements take up the full viewport */
    min-height: 100%;
}
html.loading {
    /* Replace #333 with the background-color of your choice */
    /* Replace loading.gif with the loading image of your choice */
    background: #333 url('loading.gif') no-repeat 50% 50%;

    /* Ensures that the transition only runs in one direction */
    -webkit-transition: background-color 0;
    transition: background-color 0;
}
body {
    -webkit-transition: opacity 1s ease-in;
    transition: opacity 1s ease-in;
}
html.loading body {
    /* Make the contents of the body opaque during loading */
    opacity: 0;

    /* Ensures that the transition only runs in one direction */
    -webkit-transition: opacity 0;
    transition: opacity 0;
}

javascript
// IE10+
document.getElementsByTagName( "html" )[0].classList.remove( "loading" );

// All browsers
document.getElementsByTagName( "html" )[0].className.replace( /loading/, "" );

// Or with jQuery
$( "html" ).removeClass( "loading" );

Thank you

A:

tested ! => http://jsfiddle.net/3m3S8/


text:
Q: pd.to_numeric() returns TypeError: 'Series' objects are mutable, thus they cannot be hashed On a given dataframe I'm creating a new column based on values from different columns and another dataframe.
code that creates the new column:
df['normalized_value'] = df.apply(lambda x:
                                      x['value'] / rates_df.loc[rates_df['date'] == x['date'], 'EUR']
                                      if
                                      x['currency'] != 'EUR'
                                      else
                                      x['value'],
                                      axis=1)

after the column is created it looks like this:
0        45500
1        32500
2        25000
3        33000
5        19000
         ...
61790    60000
61791    57000
61792    50999
61793    66500
61794    67000
Name: normalized_value, Length: 59951, dtype: object

I then try to convert it to float type using the following code:
df['normalized_value'] = pd.to_numeric(df['normalized_price'])

The following error is returned:
TypeError: 'Series' objects are mutable, thus they cannot be hashed

What am I doing wrong here?

A: After further investigation it turns out the problem was in the application's underlying code.
The external dataframe (rates_df) did not contain some of the required data and for some reason it returned a string instead of throwing an error. This caused some of the values in df['normalized_value'] to be actual strings containing the actual type of the value it was expecting.
Once the problem with rates_df was solved the convertion took place without any problems.


text:
Q: Calling Webservice with consistent behavior in android I know how to save states and restore them, but I just get confused when I have to do work with the Web services and to update UI. For times I was using the AsyncTask but then I came to point where I loose my activity/fragment context for example when I rotate the device. So in this way, I am thinking how other apps are handling such situations.
If I use the IntentService and call my web service from there, then I came to think that for each web service I have to make IntentService differently, and update the UI of each activity and fragment I have to make the BroadcastReceiver for each activity and fragments.
So what is a good practice for calling web service from the activity and the fragments?
How can I Update UI when the service return arrives (or call next service based on first services results)?

A: If you want your data to be instantly available through configuration changes (which you do), then you probably want to use Loaders.
It gives the developer a mechanism of loading data asynchronously for an activity or fragment. Since loaders are specifically designed to solve the issue of async loading, one does not have to spend too much time designing async tasks to handle all different scenarios efficiently.
Good article about Loaders https://medium.com/google-developers/making-loading-data-on-android-lifecycle-aware-897e12760832

A: Try using retrofit. It's a great networking libraries for Android apps and it's easy to use.
The entire network call + JSON/XML parsing is completely handled by it (with help from Gson for JSON parsing). Documentation is great and the community is huge.
check out this sample.

A: I noticed a comment you made:

...and my webservices are soap and I cant change them

The way I'm currently calling my web service, which is also SOAP, is via an Intent. I do this by passing in the data that I'm submitting to the Web service with putExtra then receiving it on my WebService, as you probably do right now. I then get the result from that web call and process it inside an AsyncTask, the async task will then utilize EventBus to post to Results as needed which are received on my MainThread via ThreadMode.Main.
So with that said, I highly recommend the use of a library called EventBus from Greenrobot.

You greatly simplify communication between Activities and Fragments, You can get started immediately using a default EventBus instance available from anywhere in your code. For example, you can do the following.
EventBus.getDefault().post(new ModelForOtherActivityToSee(data));

In the model, you can include anything you want, and react accordingly when received.
The best part is that when received, EventBus handles how the data will be executed by either running ASYNC, MAIN, BACKGROUND

*

*ASYNC - Event handler methods are called in a separate thread. This is always independent from the posting thread and the main thread. Posting events never wait for event handler methods using this mode. Event handler methods should use this mode if their execution might take some time, e.g. for network access. Avoid triggering a large number of long-running asynchronous handler methods at the same time to limit the number of concurrent threads. EventBus uses a thread pool to efficiently reuse threads from completed asynchronous event handler notifications.

*Background - Subscribers will be called in a background thread. If posting thread is not the main thread, event handler methods will be called directly in the posting thread. If the posting thread is the main thread, EventBus uses a single background thread that will deliver all its events sequentially. Event handlers using this mode should try to return quickly to avoid blocking the background thread.

*MAIN -Subscribers will be called in Android's main thread (sometimes referred to as UI thread). If the posting thread is the main thread, event handler methods will be called directly (synchronously like described for ThreadMode.POSTING). Event handlers using this mode must return quickly to avoid blocking the main thread.
An example of receiving an event broadcasted from EventBus:
//ThreadMode can be ASYNC, MAIN, BACKGROUND
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(ModelForOtherActivityToSee eventModel) {
   /* Do something with eventModel received, this runs on UI thread */
};

Full example on how to use EventBus:
1 - Open your build.gradle for the app and set your dependency for EventBus:
dependencies { compile 'org.greenrobot:eventbus:3.0.0'}
2 - Create your first model to use in publishing an EventBus, I will use a very simplistic example of a model:
package com.myapp.models.eventbusmodels;

public final class EventBusMyModel {
    private final String dataRaw

    public EventBusMyModel(final String rawData) {
        this.dataRaw = rawData;
    }

    public String getRawData() {
        return this.dataRaw;
    }
}

3 - Now all that's left is pushing out a broadcast by using from anywhere.
EventBus.post(new EventBusModel("My Data here"));

4 - To enable Activities/Fragments to receive events from EventBus you must attach and detach, this is what I mean. From inside an Activity on the onResume() and onStop() overrides:
public class SomeActivity {
    @Override
    protected void onResume() {
        if(!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    @Override
    protected void onStop() {
        if(EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().unregister(this);
        super.onStop();
    }
}

5 - The final thing to do is receive that broadcast, you can receive it in Any Fragment, Activity, or in all your fragments/activities. Here's an example from inside the SomeActivity:
@Subscribe(threadMode = ThreadMode.MAIN)
public void eventThisNameDoesNotMatter(final EventBusMyModel resultModel) {
   String receivedData = resultModel.getRawData();
   //Do whatever with receivedData. Since we are on ThreadMode.MAIN, this is on the UI thread.
}


text:
Q: Sendkeys Ctrl+Alt+Shift+F6 (Deep Freeze) I tried to send key combination of Shift+Ctrl+Alt+F6 to bring up Deep Freeze workstation configuration screen
SendKeys.Send("+^%{F6}");
And SendKeys.Send("+^%({F6})");
But neither one worked
Deep Freeze doesn't have any window to show until after that sent
In AutoIT version, I can use Send("+^!{F6}") and that worked
Could someone point me to the right direction? Thanks in advance

A: Thanks for trying to help.
Found out Sendkeys.Send will only work if it has target, if not then it just send to it self app. Deep Freeze setting console has no GUI until after the combination keys show it, that's why I cannot use it.
AutoIT's Send function doesn't need target, it just act like physical keyboard work.
I temporarily used NuGet InputSimulator to get the job done. Hate to have the dll in executable folder for it to work though, so will look into convert to native PostMessage or SendInput once I learn more about those to understand.
Right now my code is simply as:
s.Keyboard.ModifiedKeyStroke(
            new[] { VirtualKeyCode.CONTROL, VirtualKeyCode.MENU,
VirtualKeyCode.SHIFT },
            new[] { VirtualKeyCode.F6 }
            );


text:
Q: Properties in Command Pattern How do we handle simple public property setters in Command Pattern to make them undoable? Do I need to create a separate command for every property?
Details
My application (WPF/MVVM/C#) currently implements undo/redo functionality by maintaining a stack of "state snapshots". These snapshots are created upon every undoable action and pushed to the stack. While this approach has worked correctly so far, the size of undo stack keeps swelling, making application less responsive.
I'm now considering the prospects of moving to standard Command Pattern. Since I'm already using MVVM Light, I'd just extend RelayCommand to create UndoableRelayCommand and then push these to my undo stack instead of the snapshots. So far so good.
The problem however is that a lot of VM-level objects are bound directly to UI controls (through standard WPF Binding) and therefore get set directly without involving any RelayCommand. Setting of these properties needs to be an undoable action. How do I fit this requirement into standard Command Pattern, while keeping my Bindings intact?

A: I'd advise you to still copy values into the command, because otherwise older commands will go out of sync with the state of the binding at the moment when they happened.
I presume that you are already only taking the snapshot of the affected value, not the entire form (that would be a blunder).
I do not understand what does it mean that the application is becoming unresponsive. All operations on undo/redo stack should be O(1). If your implementation is more complex than O(1) then that might be the direction for you to investigate before redesigning the mechanism.
Anyway, with the undo/redo stack, there is one practical trick usually applied in larger applications. Bound the size of the stack. With more items pushed, let it "forget" the oldest ones. Another practical trick also used around is to purge the stack every time the state is persisted, and only keep the last command to redo. Those are the performance tweaks I saw this far.


text:
Q: How to create Spring Cache KeyGenerator that allows no caching for specified key I just want to disable cache for users that are admins. So I write a method to generate keys as below that returns null for admins. But I get

java.lang.IllegalArgumentException: Null key returned for cache
  operation
  exeption.

Is there any way achieve that?
//a method that generates a menu for each user
@Cacheable(cacheNames = "topmenu", keyGenerator = "uiComponentKey")
@Override
public String renderResponse() {...}

//method used by a key generator to generate cache keys.
@Override
public Object getCacheKey() {
    if (user.isAdmin()) {
        return null;
    }
    return user.getUser().getLogin() + "@" + "topmenu";
}

A: I guess you can achive that using conditional caching feature. Smth like this:
@Cacheable(cacheNames = "topmenu", condition="#user.isAdmin()")
@Override
public String renderResponse(User user) {...}

Note, that you're going to have to pass user object to this method in this case.


text:
Q: Change `max` or `min` dynamically in html5 with jquery i've problem with change max in <input type='number'> . this is my code for sample :

$(document).ready(function(){

  var total = 5;
  $(.foo).attr('max', total);
  $(.bar).attr('max', total);
  $(.ext).attr('max', total);

});

  <input type='number' name='foo' class='foo'>

  <input type='number' name='bar'  class='bar'>

  <input type='number' name='ext'  class='ext'>

How to make the max must be not > total ?
example : if i input 2 on foo and input 1 on bar, on ext must not be greater than 2 .
thanks

A: As mentioned in the comment by Chris, it should be '.foo' instead of .foo. Also as a shorthand you can have them in one single statement as below like, $('.foo, .bar, .ext') if all have the same max.

$(document).ready(function(){

  var total = 5;
  $('.foo, .bar, .ext').attr('max', total);

});

  <form action="http://stackoverflow.com">
  <input type='number' name='foo' class='foo'>

  <input type='number' name='bar'  class='bar'>

  <input type='number' name='ext'  class='ext'>

  <input type='submit' value='Submit' >
  </form>

A: I assume you want to limit the total of any combination of the three inputs to 5.  Here's one way to do that:

$(document).ready(function(){

  var total = 5;
  var remain;

  var $foo = $("#foo");
  var $bar = $("#bar");
  var $ext = $("#ext");

  recalculateMax = function(el)
  {
    switch (el) {
      case $foo[0]:
        remain = total - $bar.val() - $ext.val();
        remain = remain < 0 ? 0 : remain
        $foo.val(($foo.val() <= remain) ? $foo.val() : remain);
        break;
      case $bar[0]:
        remain = total - $foo.val() - $ext.val();
        remain = remain < 0 ? 0 : remain
        $bar.val(($bar.val() <= remain) ? $bar.val() : remain);
        break;
      case $ext[0]:
        remain = total - $foo.val() - $bar.val();
        remain = remain < 0 ? 0 : remain
        $ext.val(($ext.val() <= remain) ? $ext.val() : remain);
        break;
    }
  }

});

  <input id="foo" type='number' name='foo' onChange="recalculateMax(this)">

  <input id="bar" type='number' name='bar' onChange="recalculateMax(this)">

  <input id="ext" type='number' name='ext' onChange="recalculateMax(this)">


text:
Q: All Teams Recordings to go to a designated Sharepoint folder I am aware of the recent change to how Teams stores recorded meetings.
Is there anything we can do so instead of having group meetings recordings being stored in the Personal OneDrive for Business (under "Recordings") to have them just stored in a folder in SharePoint?
At the moment its a manual job to move them I was hoping there is something a bit more automated to get them into SharePoint.
I have setup a recurring PowerAutomate Flow (https://powerusers.microsoft.com/t5/Building-Flows/Move-files-in-folder-from-OneDrive-to-Sharepoint-into-a-newly/td-p/673833#) to do it, but this ONLY works for me.
Any ideas or insight will be appreciated.


text:
Q: Javascript IF ELSE statement stopping short So we have here my code for a GPA calculator. Ive got everything in line but I cant seem to figure out why my IF ELSE statement is stopping short and converting all letter grades to a value of "4".
I have tried putting the statement outside of the for loop that is handling the grades and pushing them to to gVals[] I have tried putting them completely outside of the function in their own function. I have tried alot of different things except apparently the thing that works.
I know there are simple ways of doing this but I am trying to execute this app with a minimalist mentality.
The code:
    function calcGPA() {
    //Variable Sections
    var grades = document.querySelectorAll("#letGrade input[type=text]");
    var contacts = document.querySelectorAll("#conHours input[type=text]");
    var gVals = [];
    var cVals = [];
    var failGrade = "The Letter Grade input may only be capitol letters A,B,C,D or F";
    var failHours = "The Contact Hours input may only be 1, 2, 3, 4 or 5";
    var checkGrade = /^[ABCDF]/;
    var checkhours = /^[12345]/;
    //Grab the Letter grades and process them
    //Should validate all inputs in the letGrade div to capitol A, B, C, D or F
    //Should Convert all inputs in the LetGrade div to A = 4,B = 3,C = 2,D = 1,F = 0
    //Should push resulting conversion to gVals[]
    for (var i = 0; i < grades.length; i++) {
        if (!checkGrade.test(grades[i].value)) {
            alert(failGrade);
            return false;
        }
             if (grades[i].value == "A"){
                gVals.push("4");
            }
            else if (grades[i].value == "B"){
                gVals.push("3");
            }
            else if (grades[i].value == "C"){
                gVals.push("2");
            }
            else if (grades[i].value == "D"){
                gVals.push("1");
            }
            else if (grades[i].value == "F"){
                gVals.push("0");
            }
        //Should validate all inputs in the conHours div to 1, 2, 3, 4 or 5
        //Should push all resulting values to cVals[]
        if (!checkhours.test(contacts[i].value)) {
            alert(failHours);
            return false;
        }
        cVals.push(contacts[i].value);
    }
    console.log(gVals, cVals);
    document.getElementById("cumGPA").innerHTML = (gVals[0] * cVals[0]);
};

The issue I am having is that the IF ELSE statement to do the conversion from letter grade to quality point value is returning everything back as 4 instead of matching it with its resulting letter grade componant.
Thank you for any help with this in advanced and please if you could dont answer the question outright please explain where I went wrong so I can learn from this.
EDIT: ADDED HTML FOR PROSPERITY! AND "FIXED" JAVASCRIPT!

    <form id="calc" name="calc" onsubmit="calcGPA(); return false;">

            <input tabindex="1" type="text" maxlength="1" placeholder="Letter Grade..." />
            <input tabindex="3" type="text" maxlength="1" placeholder="Letter Grade..." />
            <input tabindex="5" type="text" maxlength="1" placeholder="Letter Grade..." />
            <input tabindex="7" type="text" maxlength="1" placeholder="Letter Grade..." />
            <input tabindex="9" type="text" maxlength="1" placeholder="Letter Grade..." />
            <input tabindex="11" type="text" maxlength="1" placeholder="Letter Grade..." />
            Cumulative GPA:<output id="cumGPA" type="text" />

            <input tabindex="2" type="text" maxlength="1" placeholder="Contact Hours..." />
            <input tabindex="4" type="text" maxlength="1" placeholder="Contact Hours..." />
            <input tabindex="6" type="text" maxlength="1" placeholder="Contact Hours..." />
            <input tabindex="8" type="text" maxlength="1" placeholder="Contact Hours..." />
            <input tabindex="10" type="text" maxlength="1" placeholder="Contact Hours..." />
            <input tabindex="12" type="text" maxlength="1" placeholder="Contact Hours..." />
            <input type="submit" value="Calculate" />

    </form>

A: You want to change single = to == for comparison
if (grades[i] == 'A'){

Something like this in your code:
    if (grades[i] == 'A'){
            gVals.push("4");
        }
        else if (grades[i] == 'B'){
            gVals.push("3");
        }
        else if (grades[i] == 'C'){
            gVals.push("2");
        }
        else if (grades[i] == 'D'){
            gVals.push("1");
        }
        else if (grades[i] == 'F'){
            gVals.push("0");
        }

Note:-
Double equality == is used for comparison and single = is used for assignment in Javascript.
Also as Andy well pointed that in comments that your both the for loops are using the same index i which may cause problem to you(atleast not a good practice). It would be better if you create a new variable for second for loop. It is unclear what you want to achieve with both the for loops but I think that it can be done with single for loop also.

A: The reason why it's not working is because in your if statement, you're using a single equals. A single equals is setting grades[i] equal to 'A' - it's not actually evaluating grades[i] == 'A'.

A: As it was pointed in other answers you should use comparison operator == instead of assign operator = in if conditions, and also don't forget that grades[i] are DOM objects and not some plain values - so you have to compare with some property of this objects (if you want to compare with input's text use value property)
      if (grades[i].value == "A"){
            gVals.push("4");
        }
        else if (grades[i].value == "B"){
            gVals.push("3");
        }


text:
Q: Non-trivial $\operatorname{Hom}_R(M;N)$ In K. Conrad's handout on dual modules(https://kconrad.math.uconn.edu/blurbs/linmultialg/dualmod.pdf), there is the following theorem-exercise 2.11, which states:
Let $R$ be an integral domain with fraction field $K$. For two nonzero $R$-modules $M$ and $N$ in $K$, the $R$-module $\operatorname{Hom}_R(M, N)$ is isomorphic to $\{c ∈ K : cM ⊂ N\}$.
If $M$ and $N$ admit a common denominator from $R$ then so does $\operatorname{Hom}_R(M, N)$. Equivalently,
if $M^∨$ and $N^∨$ are nonzero then $\operatorname{Hom}_R(M, N) \neq 0$.
I'm struggling with proving the second-third part on my own, it seems that the proof of the similar statement when $N$ is equal to the base ring $R$ (that is given in the notes) doesn't work, or at least I don't see how.
Any hint, full solution, link are weLcome.

A: Let me restate the second statement in a clearer way (to reflect better the fact that it is equivalent to the last statement):

For $M$ and $N$ be nonzero modules in $K$, each has a common denominator, then $\text{Hom}_R(M, N)$ is also nonzero.

We only have to prove the second statement. To do this, let $d$ be a common denominator of $M$ and $d'$ be a common denominator of $N$. Since $N$ is nonzero, there exists $c\in R, c\neq 0$ such that $c/d'\in N$. Denote $k=\frac{cd}{d'}\in K$. The map $x\mapsto kx$ belongs to $\text{Hom}_R(M, N)$ since it takes $\frac{m}{d}\in M$ to $\frac{cm}{d'}=m\frac{c}{d'}\in N$.


text:
Q: how to insert using join in query i have a table like this
registrationId | standardId | courseId | marks
===============================================
5001           |     1      |    1     |   67
5001           |     1      |    2     |    87

and so on my question is the standard name and course name come from different tables so while updating i have to use 3 diffent queries 1st to get standardId according to standard name courseid acording to coursename and later update into this table. can it be done in one query?

A: Punctuation exists for a reason; you should use it. Without it, such a long sentence is difficult to read and understand.
Title says "insert", body says "update"; which one is it?
For UPDATE, something like this might do what you need:
update this_table tt set
  tt.standardid = (select s.standardid
                   from standard s
                   where s.standard_name = :some_unique_standard_name
                  ),
  tt.courseid   = (select c.courseid
                   from course c
                   where c.course_name = :some_unique_course_name
                  )
where tt.registrationid = :some_registration_id;

For INSERT:
insert into this_table
  (registrationid, standardid, courseid, marks)
select
  :some_registration_id,
  (select s.standardid
   from standard s
   where s.standard_name = :some_unique_standard_name
  ),
  (select c.courseid
   from course c
   where c.course_name = :some_unique_course_name
  ),
  :marks_value
from dual;

*

*in both cases, subqueries must return a single value

*colon (:) represents a variable whose value you need to provide

*syntax is based on Oracle; your database might differ (especially for INSERT, as there's probably no DUAL table elsewhere).


text:
Q: How do I get HTTP_ORIGIN in javascript? I'm aware you can get the referrer in Javascript runtime in a browser with document.referrer... but how do get the HTTP_ORIGIN that I see passed in the headers?

A: https://developer.mozilla.org/en-US/docs/Web/API/Document/origin
Looks like Chrome is the only browser that lets you get that.


text:
Q: can windows service enumerate desktop top level windows I'm trying to enumerate top level windows from a service coded in c++
I want to find a particular program which there are multi instances of it running but I want a particular one which have some unique words in its window title
so I'm using this code :
 auto desktop = OpenInputDesktop( 0, FALSE, DESKTOP_READOBJECTS);
 if (!desktop) log_file << "[*] OpenDesktopA failed with error : " << GetLastError() << endl;
BOOL rs = EnumDesktopWindows(desktop, EnumProc, 0);
if (!rs) log_file << "[*] EnumDesktopWindows failed with error : " << GetLastError() << endl;

the EnumDesktopWindows  fails without calling the EnumProc so GetLastError returns zero
the same code works in non sevice program
is it possible to do this in a service but I'm doing something wrong ?
or I can't achieve this ?

A: the final solution seems to make a helper process which will list the windows and find the id of the required windows the send it to the service through pipes or sockets or other communication techniques

A: found one of the problems above , it was the access right
I should use this access instead :
auto desktop = OpenInputDesktop(0, 0, GENERIC_ALL); // GENERIC_READ also enough
EnumDesktopWindows(desktop, EnumProc, 0);

however I got only two windows : HPSISVC , Default IME
while running this code in an ordinary program prints all the windows titles


text:
Q: Read in rows from a CSV using data.table's fread BY GROUP I have a very large CSV file containing millions and millions of rows, it is a combined dataset from multiple sources. I have a character column/variable that indicates the source of the row/observation, and I'd like to read in a subset of rows from each group using data.table's fread.
Right now I'm trying to read in 20,000 rows to test out my code but the first few million rows are all from one source so I can't get rows from multiple sources. Is there a way to say read in 20,000 rows from each SOURCE level? So basically reading in 20,000 rows from each BY GROUP (source)?

A: One potential solution is to use the vroom package to read in only the "group" column, i.e.
library(tidyverse)
library(vroom)
df <- vroom("file.csv", col_select = group)

Then sample the rownumbers, grouped by group, in 'blocks':
df2 <- df %>%
  mutate(rownumber = row_number()) %>%
  group_by(group) %>%
  slice_head(n = 20000) %>%
  ungroup() %>%
  select(rownumber)

Then use this approach to select the rows in each block (one call to fread per block) and rbind them together, i.e.
library(data.table)
s <- df2$rownumber
v <- (1:1e5 %in% s)
idx  <- c(0, cumsum(seq$lengths))[which(seq$values)] + 1
indx <- data.frame(start=idx, length=seq$length[which(seq$values)])
result <- do.call(rbind,apply(indx,1, function(x) return(fread("test.csv",nrows=x[2],skip=x[1]))))

I don't have any huge files to test this, but if this approach doesn't work for you I can help troubleshoot. It might also be worth looking at an external program (e.g. AWK) as a workaround if your dataset is too large.

A: I wonder if doing something outside of R might be better. Using awk for instance, using this data in awkgroup.csv:
"something","group"
1,"A"
2,"A"
3,"A"
4,"A"
5,"A"
6,"B"
7,"B"
8,"B"
9,"B"
10,"B"
11,"C"
12,"C"
13,"C"
14,"C"
15,"C"
16,"D"
17,"D"
18,"D"
19,"D"
20,"D"

We can do
$ awk -F, '$2==inp{line++;if(line<3)print($0)}; $2!=inp{inp=$2;line=0;print($0)};' awkgroup.csv > newdata.csv
$ cat newdata.csv
"something","group"
1,"A"
2,"A"
3,"A"
6,"B"
7,"B"
8,"B"
11,"C"
12,"C"
13,"C"
16,"D"
17,"D"
18,"D"

Basic walk-through (though I do not consider myself an awk wizard by any account):

*

*$2==inp (and similarly $2!=inp) tests if the second column (our grouping variable) has changed since the previous row. The inp is initially uninitialized so will default to the empty string.
NB: this assumes the data is ordered by-group.

*line++;if(line<3)print($0) is the majority of work, where it tests if line (our method of tracking lines within the current group) is less than 3 (we use a 0-based line here) and prints if so. This gives us the top 3 lines per group.

*inp=$2;line=0;print($0) is similar, but is run on the first line within a group; it resets the line counter, sets what we think the current group is by assigning to inp, and always prints (since this is the first line within a group).
I couldn't get this to work well in fread(cmd="..."), likely because it (for some reason) uses shell in lieu of the admittedly-also-broken (but not here) system. One can use system and control where the output goes, then read that normally, perhaps
system2("awk", c("-F, '$2==inp{line++;if(line<3)print($0);};$2!=inp{inp=$2;line=0;print($0)};'",
                 "awkgroup.csv"),
        stdout="awkout.csv" )
fread("awkout.csv")
#     something  group
#         <int> <char>
#  1:         1      A
#  2:         2      A
#  3:         3      A
#  4:         6      B
#  5:         7      B
#  6:         8      B
#  7:        11      C
#  8:        12      C
#  9:        13      C
# 10:        16      D
# 11:        17      D
# 12:        18      D

FYI, system2 is not really any better than system: it just concatenates the quoted (good!) command= with all unquoted args (bad!):
  command <- paste(c(shQuote(command), env, args), collapse = " ")

which is why I'm able to cheat a little and combine all of awk's args= into a vector.
From here, you need to control two things about this:

*

*change $2 (in three places) to the column number of your grouping variable;

*change < 3 to be whatever limit you want (recall that it is 0-based, so < 3 gives you 3 entries, not 2).


text:
Q: Array Comprehension with a random output in Julia This question is an extension if one I asked earlier today. Basically, I am trying to write an array comprehension in Julia that calls a function f(x) whose output is a random number. When a random number less than 0.5 is reached, I want it to kill the function. I was able to write the following code:

X=[f(i) for i in 1:1:100 if (j=f(i) ;j < 0.5 ? false: j>0.5)]

The problem with this is that this calls two separate instances of f(x), and because f(x) is random every time, the above won't kill the for loop at the correct instance. I tried

X=[J=f(i) for i in 1:1:100 if (J < 0.5 ? false: J>0.5)]

As an attempt to save that particular random number, but then it tells me J is not defined. Is there any way to save this particular random number to perform my array comprehension?

A: Insisting on a one-line solution and inspired by @TasosPapastylianou, a fast solution would be :
X = ( r=Vector{Float64}() ;
  any(i->(v=f(i) ; v>0.5 ? ( push!(r,v) ; false) : true), 1:100)
  ; r )

[ the one-line is split to three because it is a little long ;) ]
Since, f is missing, to test this copy-paste this version with rand:
(r=ones(0); any(i->(v=rand(); v>0.5 ? (push!(r,v); false) : true), 1:10); r)

It benchmarks about 10% slower than Fengyang's function. The clever bit is leveraging any's short-circuit implementation.
ADDENDUM: To generalize here is a version of Fengyang's takewhile to abstract the answer to this question:
collectwhilecond(f,cond,itr) = begin
    r=Vector{typeof(f(first(itr)))}()
    all(x->(y=f(x); cond(y) ? (push!(r,y);true):false),itr)
    return r
end

Now, we can implement the answer above as (with joker as f):
julia> joker(i) = 1.0 + 4*rand() - log(i)

julia> collectwhilecond(joker, x->x>=0.5, 1:100)
3-element Array{Float64,1}:
 4.14222
 3.42955
 2.76387

collectwhilecond is also type stable if Julia infers f's return type.
EDIT: Using @tim's suggested method of inferring return type of f without pulling an element of itr and without risking an unstable f generating an error, the new collectwhilecond is:
collectwhilecond(f,cond,itr) = begin
    t = Base.promote_op(f,eltype(itr))  # unofficial and subject to change
    r = Vector{t}()
    all( x -> ( y=f(x) ; cond(y) ? (push!(r,y) ; true) : false), itr )
    return r
end

A: What you're trying to do is essentially a simple filter operation:
filter(x -> x >= 0.5, [f(i) for i in 1:10])

This is basically what we used to rely on in the first place before the if part was implemented in list comprehensions in julia before v0.5

EDIT: As Dan pointed out, you may be after keeping all elements until the first element that is <0.5 instead, e.g.:
L = [f(i) for i in 1:10]; L[1 : findfirst(L.<0.5) - 1]

However, in this case, as others have pointed out, you might as well go for a normal for loop. A list comprehension will always process the whole list first, so it will not be faster. You could use a generator, but then you'd have to create your own special mechanism to make it stop at the right state (as Fengyang has suggested with takewhile).
So to answer the question in the comment, the fastest thing you could do in this case is a normal for loop that breaks appropriately. Furthermore, it is best wrapped in a function rather than evaluated globally, and it will speed up even further if you specify the type of your variables.

A: You can do this with what's usually called takewhile on a generator
X = collect(takewhile(x -> x ≥ 0.5, Generator(f, 1:100)))

which requires an implementation of takewhile, such as the one in this blog post, or your own (it's not too hard to do). takewhile has a reasonably easy name to read and is as concise as you might like.
However I think often it's both more readable and more convenient to write a loop:
X = Float64[]
for i = 1:100
    j = f(i)
    if j < 0.5
        break
    else
        push!(X, j)
    end
end

A: As suggested, using a loop is the right way to go. But if trying 'other' solutions, the following is short and confusing and educational about Channels which are seldom mentioned in Stack Overflow:
collect(Channel(c->begin
        i=1
        while true
            v = rand()
            if v<0.5 || i>100 return else put!(c,v) end
            i+=1
        end
    end, ctype=Float64))

Replace rand() with f(i) as appropriate.
And BTW don't use this solution because it is 1000x slower than a simple loop. Perhaps of value if Channel is a RemoteChannel and f(i) is some big stochastic simulation.

A: If you want to squeeze the maximum possible performance, I'd say there are two options depending on which is the bottleneck.

*

*f is very fast, but allocations are an issue. The following code computes f twice but saves on the allocation part (as push! will sometimes reallocate memory, see here ):

i = findfirst(t -> f(t) > 0.5, 1:100)
w = f.(1:(i-1))

*f is very slow and computing it twice is too expensive. Then just do a loop with push! as already recommended. You may want to look at sizehint! to further improve performance.

In general, you don't need to ask what is slower and what is faster: ypu can simply benchmark your particular use case with the excellent BenchmarkTools package.


text:
Q: Remapping Keys and Mouse I have a CAD application where I need to remap some mouse and keyboard combinations.
Does anyone have any idea what I can use for this, preferably freeware if possible.
Thanks

A: Update:
Since there seem to be a bug with ahk itself rather than your script.
Here are some other key remapping softwares you can try:
http://www.randyrants.com/sharpkeys/
http://webpages.charter.net/krumsick/
http://www.softarium.com/keyremapper/
Not free (trials):
http://atnsoft.com/keymanager/
http://www.inchwest.com/hotkeycontrol/downloads
The hardcore way is registry editing :
http://msdn.microsoft.com/en-us/windows/hardware/gg463447.aspx
Input manipulation software using scripting (like autohotkey):
http://www.autoitscript.com/site/autoit/
http://sikuli.org/
https://sites.google.com/site/carlkenner/glovepie
Old post:
First of all. Have look around in the settings for your cad application to make sure there is no way to rebind hotkeys from within the application.
A very popular macro and keybinding software is auothotkey
http://www.autohotkey.com/download/
Here is a guide for remapping keys.
http://www.autohotkey.com/docs/misc/Remap.htm
There should definitely be a way to start both your remaping script and application for the same time...
A batch script could actually do the trick however.


text:
Q: How to apply topojson's projection to a voronoi in d3? I've noticed that straight lines are curved to the projection, but the Voronoi regions are in straight lines.

Is it possible to "force" the Voronoi region to also be curved and applied to the topojson's projection like the straight lines and lat/lon coordinates?
The original map: http://bl.ocks.org/mbostock/7608400
A section of my code:
var projection = d3.geo.kavrayskiy7()
    .center([center_lon, center_lat])
    .scale(zoom)
    .translate([width / 2, height / 2])

var graticule = d3.geo.graticule();

var path = d3.geo.path()
    .projection(projection);

var voronoi = d3.geom.voronoi()
    .x(function(d) { return d.x; })
    .y(function(d) { return d.y; })
    .clipExtent([[0, 0], [width, height]]);

var svg = d3.select(that.el).append("svg")
    .attr("width", width)
    .attr("height", height);

svg.append("path")
    .datum(graticule)
    .attr("class", "graticule")
    .attr("d", path);

svg.append("path")
    .datum(graticule.outline)
    .attr("class", "graticule outline")
    .attr("d", path);

d3.json("/static/app/custom_vizs/components/voronoi/readme-world.json", function(error, world) {
    var countries = topojson.feature(world, world.objects.countries).features,
        neighbors = topojson.neighbors(world.objects.countries.geometries);

    svg.selectAll(".country")
        .data(countries)
        .enter().insert("path", ".graticule")
        .attr("class", "country")
        .attr("d", path);

    var format = d3.format(",");

    var get_points_by_id = d3.map(),
        positions = [];

    var src = _(data).chain().groupBy(src_field).each(function(v, k, o) { o[k] = v; }).value();
    var dst = _(data).chain().groupBy(dst_field).each(function(v, k, o) { o[k] = v; }).value();

    var uniques = _(dst).extend(src);

    var max = 0;

    var points = _(uniques).map(function(v, k) {
        var o = {};

        o.id = k;
        o.value = _(v).pluck(count_field).reduce(function(memo, num) { return memo + parseFloat(num); }, 0);

        max = Math.max(max, o.value);

        if(v[0][src_field] === k) {
            o.lat = v[0][src_lat_field];
            o.lon = v[0][src_lon_field];
        }
        else {
            o.lat = v[0][dst_lat_field];
            o.lon = v[0][dst_lon_field];
        }

        return o;
    });

    points.forEach(function(d) {
        get_points_by_id.set(d.id, d);
        d.outgoing = [];
        d.incoming = [];
    });

    data.forEach(function(connection) {
        var source = get_points_by_id.get(connection[src_field]),
            target = get_points_by_id.get(connection[dst_field]),
            link = {source: source, target: target};
        source.outgoing.push(link);
        target.incoming.push(link);
    });

    points = points.filter(function(d) {
        if (d.count = Math.max(d.incoming.length, d.outgoing.length)) {
        d[0] = +d.lon;
        d[1] = +d.lat;
        var position = projection(d);
        d.x = position[0];
        d.y = position[1];
        return true;
        }
    });

    voronoi(points)
        .forEach(function(d) { d.point.cell = d; });

    var point = svg.append("g")
        .attr("class", "points")
        .selectAll("g")
        .data(points.sort(function(a, b) { return b[count_field] - a[count_field]; }))
        .enter().append("g")
        .attr("class", "point");

    point.append("path")
        .attr("class", "point-cell")
        .attr("d", function(d) { return d.cell.length ? "M" + d.cell.join("L") + "Z" : null; });

    point.append("g")
        .attr("class", "point-arcs")
        .selectAll("path")
        .data(function(d) { return d.outgoing; })
        .enter().append("path")
        .attr("d", function(d) { return path({type: "LineString", coordinates: [d.source, d.target]}); });

    point.append("circle")
        .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
        .attr("r", function(d, i) { return d.value/max*max_circle_size; });

    point.append("title")
        .text(function(d) {
            return d.id + ": " +
                format(d.outgoing.length) + " distinct outgoing, " +
                format(d.incoming.length) + " distinct incoming, " +
                format(d.value) + " total";
        });
});

A: I don't think so. The graticules (curved lines) has a start and end point. How would you define that for the voronoi diagram? Maybe for each cell? I don't think it would work.


text:
Q: Variadic Template Parameter Packs with Alternating Types I was wondering if it is possible to capture an alternating parameter pattern using a parameter pack.  For example,
template<typename T, size_t U, typename... Args>
class foo<T, U, Args...>
{
   public:
     foo() : my_T(nullptr), my_U(U) {}

   private:
     T* my_T;
     size_t my_U;
     foo<Args...> my_next_foo;
}

So this doesn't work since Args is a parameter pack of only types.  Is there a way to modify this so that the typename T, size_t U pattern can be properly captured in a variadic template?  Thanks

A: Values as template parameters are second class citizens, in my experience.
Upgrade them to first class with an alias:
template<std::size_t n>
using size = std::integral_constant<std::size_t, n>;

then pattern match:
template<class...>
struct foo;
template<>
struct foo<> {
  // empty
};
template<class T, size_t U, typename... Args>
struct foo<T, size<U>, Args...> {
  foo() : my_T(nullptr), my_U(U) {}

private:
  T* my_T;
  size_t my_U;
  foo<Args...> my_next_foo;
};

and bob is your uncle.
Note, however, that taking U as a template parameter, then storing it as a run time value, is highly questionable.
Users of foo must do:
foo< Chicken, size<3>, Dog, size<17> >

instead of
foo< Chicken, 3, Dog, 17 >

A: Sure, just write your own pair:
template <typename T, size_t U>
struct foo_pair { };

And have a pack of those:
template<typename T, size_t U, typename... Pairs>
class foo<foo_pair<T, U>, Pairs...> {
    ...
};

Which would be instantiated like:
foo<foo_pair<int, 4>, foo_pair<char, 17>, ...> f;

A: You can pass Args to foo as an std::tuple.  Use std::integral_constant for U instead of passing an integral constant as a template parameter to the std::tuple.  Then the Args parameters pack contains all the pairs of types and sizes.
For example, when instantiating foo you would do so with a type like this:
Foo<std::tuple<int, std::integral_constant<size_t, 5> >,
    std::tuple<char, std::integral_constant<size_t, 3> > >

When implementing foo, you should pass your parameter pack to another std::tuple and use std::tuple_element to select the Nth element of the tuple.
This is just one possible approach, you may find it easier to implement foo if you use type lists.

A: You might create a class representing the data container T* my_T with size_t my_U. Having that, you can implement your template:
#include <array>

using std::size_t;

template<typename... Args>
struct foo;

template<typename T, size_t N>
struct foo<std::array<T, N>>
{
    std::array<T, N> array;
};

template<typename T, size_t N, typename... Args>
struct foo<std::array<T, N>, Args...>
{
    std::array<T, N> array;
    foo<Args...> next_array;
};

int main() {
    foo<std::array<char, 1>, std::array<short, 2>, std::array<int, 4>> foos;
}

Note: I am using std::array as an replacement for the data container.


text:
Q: Running an executable through PowerShell and having it properly return the executable'^s error code I am attempting to run a executable with arguments from a remote computer in PowerShell, and while I have gotten the PowerShell command to work, it is not properly handling errors that the executable throws.
So the below script executes as expected as long as the file $filename points to exists, but the script will also appear to execute successfully if the file does not, which leads to problems in the scheduler I am trying to tie this into. My expectation would be that PowerShell throws an error such as "File not found", but that is not happening. So is there anything I can add to this script to make that behavior happen?
$ErrorActionPreference = "stop"
$rSession = New-PSSession -ComputerName ServerName
$fileName = c:\file.txt
Invoke-Command -ScriptBlock {Start-Process -FilePath "D:\CAMRA\PFX\PFLNS.EXE" -ArgumentList " /SD:\CAMRA\CAMINI\Z_PRODNP_SQL_TEST.INI GLSWEEP 50 {DN}~$fileName~{T}" -Wait} -Session $rSession
Remove-PSSession $rSession

It is also possible that I am not calling the .exe correctly through PowerShell to do what I am looking to, so I would be open to any suggestions on how I cam modify this script.
Thanks,
Phil

A: I think that this is something like what you want.
First off, I broke off the command into a separate script block so that we could add in some extra code to catch the bad exit code.
Second, in order to capture the exit code, your Start-Process needs to have the -PassThru parameter. Once we can capture the exit code, we will evaluate it, and if it is not 0 (good) throw an error that will crash the higher up Invoke-Command.
Third, we have to use the special $? variable to catch whether or not the previous command (Invoke-Command) was successful, and if it was unsuccessful, it will throw an error, which could be caught by the scheduling program.
$ErrorActionPreference = "stop"
$rSession = New-PSSession -ComputerName ServerName
$arg = "c:\file.txt"

$ScriptBlock = {
     param ([String]$fileName)
     $output = Start-Process -FilePath "D:\CAMRA\PFX\PFLNS.EXE" -ArgumentList " /SD:\CAMRA\CAMINI\Z_PRODNP_SQL_TEST.INI GLSWEEP 50 {DN}~$fileName~{T}" -Wait -PassThru
     if ($output.ExitCode -ne 0) {
          throw $output.ExitCode
     }
}

Invoke-Command -ScriptBlock $ScriptBlock -ArgumentList $Arg -Session $rSession
if (!$?) {
     #Failure Throw an error code
     throw 123
}

Remove-PSSession $rSession

A: Are you passing the argument to the script block? Replace $FileName with $($Args[0]) and add -ArgumentList $FileName to the parameters for Invoke-Command.
... GLSWEEP 50 {DN}~$($args[0])~{T}" -Wait} -ArgumentList $FileName -Session $rSession


text:
Q: Add a cookie in a Play Framework 2.x filter? Is it possible to add a cookie in the Play Framework's doFilter method in the Global class?
I've tried:
override def doFilter(action: EssentialAction): EssentialAction = EssentialAction { request =>
  if (request.queryString.contains("q")) {
    action.apply(request).map(_.withCookies(
      Cookie("q", request.queryString.get("q").get(0), 3600)
    ))
  }
}

but the cookie doesn't get sent to the browser.

A: I'm using Playframework 2.2 and use a similar thing:
import play.api.mvc._
import play.api._
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global

object ResponseFilter extends Filter {
  def apply(next: (RequestHeader) => Future[SimpleResult])(rh: RequestHeader) = {
    next(rh).map(_.withHeaders("Access-Control-Allow-Origin" -> "*").as("application/json; charset=utf-8"))
  }
}

And my Global object looks like this:
import play.api._
import play.api.mvc._
import service.ResponseFilter

object Global extends WithFilters(ResponseFilter) with GlobalSettings

This works fine for me. So I suppose you could replace the _.withHeaders(...) part with the _.withCookies(...) part and that would work for you as well.
Please note that things are a bit different in earlier versions of playframework


text:
Q: SQLite Query not working when dates are compared in where clause I want to Fetch records between two dates from SQLite table, But it doesn't work when Dates are compared in where clause, actually it works for other String column used as condition or when no where clause is specified, so is there any other way to use dates in where clause.
cursor = db.rawQuery("SELECT min(activity_date), max(activity_date) FROM tbl_activity_details" , null);
if(cursor != null) {
    itemsList.clear();
    while(cursor.moveToNext()) {
        itemsList.add(cursor.getString(0));
        itemsList.add(cursor.getString(1));
    }
    cursor.close();
    try {
        fromDate = sdf.parse(itemsList.get(0));
        toDate = sdf.parse(itemsList.get(1));
    } catch(Exception e) {
        e.printStackTrace();
    }

    try {
        Toast.makeText(this, "here "+sdf.format(fromDate)+"  "+sdf.format(toDate), 5000).show();
        //Toasts 2015-04-23 2015-05-01
        String fd = sdf.format(fromDate);
        String td = sdf.format(toDate);

        cursor1 = db.rawQuery("SELECT * FROM tbl_activity_details WHERE activity_date BETWEEN '"+fd+"' AND '"+td+"'", null);
        Toast.makeText(this, "here 1"+cursor1.getCount(), 5000).show();
        //Toasts here 1 10
        if(cursor1 != null) {
            while(cursor1.moveToNext()) {
                Toast.makeText(this, "here 2"+cursor1.getString(0), 5000).show();
            }

        } else {
            Toast.makeText(this, "No Record Found", 5000).show();
        }
        cursor1.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        db.close();
    }

A: I've asked a similar question and the answer might help you out, here's the question.
A quick snippet from the answer that could be relevant to you:
If you're use String as Data type in SQLite, you have to format System.currentTimeMillis() into Date format "yyyy/MM/dd". If you use other formats such as M/d/yyyy --> You will have date String comparing issues. See issue below for M/d/yyyy format:
"5/15/2015".compareTo("11/30/2015") ---> Return 4 > 0
--> means "5/15/2015" > "11/30/2015" --- Wrong

A: Date can be compared like this.. This may help you.
   select *  from MyTable
   where mydate >= Datetime('2000-01-01 00:00:00')
   and mydate <= Datetime('2050-01-01 23:00:59')


text:
Q: Login to Bluemix VM suddenly asks for password I have created a VM with a public ssh key.
Once is it created, I am able to login with the private ssh key:
ssh -i cloud.key ibmcloud@129.41.xxx.xx

After some successful logins, suddenly when trying to login with the same command I am asked for a password:
$ ssh -i cloud.key ibmcloud@129.41.xxx.xx
ibmcloud@129.41.133.80's password:

Do you know why is this happening?
I have removed and recreated the VM with same behaviour. After some successful logins, it started to ask for a password.
[EDITED] Added -vv verbose info:
.........
.........
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit: none,zlib@openssh.com
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: mac_setup: setup umac-64-etm@openssh.com
debug1: kex: server->client aes128-ctr umac-64-etm@openssh.com none
debug2: mac_setup: setup umac-64-etm@openssh.com
debug1: kex: client->server aes128-ctr umac-64-etm@openssh.com none
debug1: sending SSH2_MSG_KEX_ECDH_INIT
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug1: Server host key: ECDSA 12:05:44:27:ab:c9:98:5f:45:ab:1d:d7:e0:ca:ba:3a
debug1: Host '129.41.xxx.xx' is known and matches the ECDSA host key.
debug1: Found key in /home/xxxx/.ssh/known_hosts:11
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: cloud.key (0x6000686e0), explicit
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering RSA public key: cloud.key
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey,password
debug2: we did not send a packet, disable method
debug1: Next authentication method: password

Thanks!

A: Make sure that there are no typos in your command . For example a typo in the IP address can inadvertently point you to another VM where your key would not work and it would fallback to using a password.    If that's not the case then your best bet is to get more details about why you're being prompted for a password. Try the following command:
$ ssh -vv -i cloud.key ibmcloud@129.xxx.xxx.xxx

The will give a detailed trace of the command  as it's negotiating with  your VM  and give you some indication of why it's bypassing your keyfile and falling back to using a password instead. If the cause of the behavior  is still not clear after you try this,  post the output of the command above.

A: Answering my own question....  the issue was a colleague changed home directory permissions to 777 and for some reason SSH thinks that is not secure and doesn't authenticate although -vv parameter doesn't say anything about it.
Hope this helps others.

A: ssh ibmcloud@129.xxx.xxx.xxx

That should work. If it doesn't, generate a new ssh key, copy it to clipboard with xclip or pbcopy, then paste it in Bluemix (Create a VM > new SSH key > Import > paste ssh key).


text:
Q: Subobjects in Locally Presentable categories. Take a proper subobject $m: A \to B$ in a locally presentable category.
Since the category is locally presentable, $B = \text{colim} B_i$ where $B_i$ are presentables. Under which hypothesis m factors through a $B_i$? Can you show me some counterexamples of when it does not?!

A: A simple example is to take $\text{Vect}$. $\text{Vect}$ is locally finitely presentable with generators given by the finite-dimensional vector spaces; every vector space is a filtered colimit of finite-dimensional vector spaces. But most subspaces of an infinite-dimensional vector space are also infinite-dimensional.


text:
Q: concurrentConsumers for an ActiveMQ queue I try to consume messages from an ActiveMQ queue in grails. I've configured some spring beans for the connection and everything works great so far.
The problem starts when I try to set the concurrentConsumers above 8. It seems that 8 is set as maximum for one client - if I configure more than 8, the ActiveMQ explorer still shows 8 consumers for the queue. If I configure two listeners for different queues with more than 8 concurrentConsumers, the number of consumers shown by ActiveMQ oszillate, but the sum is always 8.
What am I doing wrong? Configuration examples show concurrentConsumers of up to 50...
Here is my configuration, written as groovy DSL, I guess it is no problem to read it...
jmsFactory(org.apache.activemq.pool.PooledConnectionFactory) { bean ->
    bean.destroyMethod = "stop"
    connectionFactory = { org.apache.activemq.ActiveMQConnectionFactory cf ->
        brokerURL = "tcp://localhost:61616"
    }
}
jmsTemplate(org.springframework.jms.core.JmsTemplate) {
    connectionFactory = jmsFactory
}
jmsMessageListener(org.springframework.jms.listener.adapter.MessageListenerAdapter, ref("messageService")) {
    defaultListenerMethod = "onMessage"
}
jmsContainer(org.springframework.jms.listener.DefaultMessageListenerContainer) {
    connectionFactory = jmsFactory
    concurrency="10"
    concurrentConsumers="15"
    destinationName = "demoQueue"
    messageListener = jmsMessageListener
    transactionManager = ref("transactionManager")
    autoStartup = false
}
jmsMessageListener2(org.springframework.jms.listener.adapter.MessageListenerAdapter, ref("messageService")) {
    defaultListenerMethod = "onMessage2"
}
jmsContainer2(org.springframework.jms.listener.DefaultMessageListenerContainer) {
    connectionFactory = jmsFactory
    destinationName = "demoQueue2"
    messageListener = jmsMessageListener2
    transactionManager = ref("transactionManager")
    autoStartup = false
}

A: Since Petter pointed out that it can't be a problem with the ActiveMQ or Spring configuration, I created a spring consumer in java and tried to find the difference to my grails consumer.
The java consumer works as expected, but doesn't use a transaction manager. So I removed the transaction manager from my grails confid and it works!
I then googled a little bit and found a hint to the cacheLevel setting: http://static.springsource.org/spring/docs/2.0.8/api/org/springframework/jms/listener/DefaultMessageListenerContainer.html#setCacheLevel%28int%29
The cacheLevel is set to none when a transaction manager is used - bingo! If I now set the cacheLevel to CACHE_CONSUMER, everything works as expected...


text:
Q: How add values in different objects in an array? How can I access only the first @NOTIFICATION_OPENED key?
How can I sum both values of @NOTIFICATION_OPENED?
This is my AJAX request:
$.getJSON("myapiurl", function(notificationData) {
  $.each(notificationData.data, function(index, value) {
    if (value["@NOTIFICATION_OPENED"]) {
      var notificationOpened = value["@NOTIFICATION_OPENED"]
    } else
      notificationOpened = 0;

    var val = {
      "notificationOpened": notificationOpened
    }
    _data.push(val)
  });
}

This is the data I retrieve from the API using the above request:
{
  "data": [{
    "date": 1577836800000,
    "@NOTIFICATION_SENT": 62629,
    "@NOTIFICATION_OPENED": 404
  }, {
    "date": 1577923200000,
    "@NOTIFICATION_OPENED": 734
  }]

A:
How can I access only the first @NOTIFICATION_OPENED key?

Simply take the first element of data, and then take the value of @NOTIFICATION_OPENED. for example:

var notification = {
    "data": [{
        "date": 1577836800000,
        "@NOTIFICATION_SENT": 62629,
        "@NOTIFICATION_OPENED": 404
    }, {
        "date": 1577923200000,
        "@NOTIFICATION_OPENED": 734
    }]
}

var firstNotificationData = notification.data[0]
var firstNotificationOpenedData = firstNotificationData["@NOTIFICATION_OPENED"]
console.log(firstNotificationOpenedData)

How can I sum both values of @NOTIFICATION_OPENED?

You can use reduce to summarize the total of notification opened. for example:

var notification = {
    "data": [{
        "date": 1577836800000,
        "@NOTIFICATION_SENT": 62629,
        "@NOTIFICATION_OPENED": 404
    }, {
        "date": 1577923200000,
        "@NOTIFICATION_OPENED": 734
    }]
}

var totalNotificationOpened = notification.data.reduce(function (acc, d) {
    return acc + d["@NOTIFICATION_OPENED"]
}, 0)

console.log(totalNotificationOpened)

A: I have added a square bracket to make it valid JSON:
const data =
[
  {
    "date": 1577836800000,
    "@NOTIFICATION_SENT": 62629,
    "@NOTIFICATION_OPENED": 404
  },
  {
   "date": 1577923200000,
   "@NOTIFICATION_OPENED": 734
  }
 ]

let nSent   = data[0]["@NOTIFICATION_SENT"]
let nOpened = data[0]["@NOTIFICATION_OPENED"]
let mySum   = nSent+nOpened

alert(mySum)

This will produce an alert with the sum 63033


text:
Q: Convert .py/.pyw to .exe I want to create an .exe file from a .py or .pyw file.
How can I do this? (with cx-freeze)

A: Code the file which will convert

*

*Download cx_Freeze (if you didn't do that) here.

*Create a new Python file and paste the following code:

import os
import time
from tkinter import *
from tkinter.filedialog import askopenfile
from tkinter.scrolledtext import ScrolledText
from tkinter.messagebox import *

tk = Tk()
tk.title(".py -> .exe")
tk.resizable(0, 0)

f = None # file chosen

def browse():
    global f, btn
    try:
        f = askopenfile().name # get the path of the chosen file
        btn["text"] = os.path.basename(f)
    except:
        f = None

def convert():
    global f, btn, ver, des
    OK = False
    try:
        dots = 0
        for x in ver.get():
            if x == ".":
                dots += 1
            else:
                x = int(x)
        if dots < 4:
            OK = True # check the number of dots in the version
    except:
        showwarning("","The version must be int.int.int... with max 3 dots.")
    if OK:
        try:
            if f is None:
                showwarning("","You must choose a file to convert.")
                btn.focus()
            elif ver.get() == "":
                showwarning("","You must enter a version.")
                ver.focus()
            else:
                # create and fill the launch files
                with open("setup.py", "w") as f_:
                    f_.write("NAME = '" + f +
                        "'\nVERSION = '" + ver.get() +
                        "'\nDESCRIPTION = \"\"\"" + des.get(1.0, "end") +
                        "\"\"\"\n\nfrom cx_Freeze import setup, Executable\nsetup(name = NAME, version = VERSION, description = DESCRIPTION, executables = [Executable(NAME)])")
                with open("start.bat", "w") as f_:
                    f_.write("py setup.py build")
                os.system("start.bat") # run the launch file

                os.remove("setup.py")  # remove the created files
                os.remove("start.bat") #
                showinfo("Information","End. Your exe file is in folder 'build'.")
        except:
            showerror("Error","Unknown error detected.") # any unknown error

# GUI
Label(text="File to convert").grid(column=0, row=0, sticky="w")
btn = Button(text="Browse...", command=browse)
btn.grid(column=1, row=0)
Label(text="Version").grid(column=0, row=2, sticky="w")
ver = Entry(width=23)
ver.grid(column=1, row=2, padx=5)
ver.insert(0, "1.0")
Label(text="Description").grid(column=0, row=3, sticky="w")
des = ScrolledText(width=15, height=5, wrap=WORD)
des.grid(column=1, row=3)
Label(text="Convert to .exe").grid(column=0, row=4, sticky="w")
Button(text="Convert", command=convert).grid(column=1, row=4, pady=5)

tk.mainloop()

*Run the code. Choose a file. Click the convert button.

*A command prompt window allows you to see the progress.

Errors

*

*The command prompt stayed open a very short time

*

*Change
  with open("start.bat", "w") as f_:
      f_.write("py setup.py build")

by
  with open("start.bat", "w") as f_:
      f_.write("py setup.py build")
      f_.write("pause")

Then, search the error on the Internet.

*Check if you have selected a .py or .pyw file.

*The folder "build" isn't created

*

*check the path of the file to convert: does it contains accentuated characters , some spaces ? >> put the file for example on your desktop, or in a flash drive to avoid it.

*check the description: does it contains accentuated characters? Remove them.

*Have you installed cx_Freeze?

*You can't open your .exe file

*

*If your code needs others files, like images, musics, then copy them in the current folder.

*Have you  checked your file? Does it contains some errors?

*If you use tkinter: have you looped the window?


text:
Q: MS Analysis Services - Calculated measure in measure group In my cube I have defined a calculated measure as the sum of two other measures. How can I make this measure show up in one of my measure groups?

A: Within your cube script where the calculated measure is defined, like so:
CREATE MEMBER CURRENTCUBE.[Measures].[Calculated Measure]
 AS ([Measures].[Measure 1] / [Measures].[Measure 2]),
FORMAT_STRING = "Percent",
NON_EMPTY_BEHAVIOR = { [Measure 1], [Measure 2] },
VISIBLE = 1 ,  DISPLAY_FOLDER = '\Custom Folder' , ASSOCIATED_MEASURE_GROUP = 'Custom Measure Group';
The properties relevant to your question are in bold.


text:
Q: Recursive function that operates on its own preceding output I have the price for a particular baseline year (in this case for 1993), and the multiplication factor for all the years. Using these known multiplication factor, I want to compute (project) price for all years succeeding and preceding the baseline year.
Here is the input data:
Year    City    MultiplicationFactor    Price_BaselineYear
1990    New York          NA            NA
1991    New York          0.9           NA
1992    New York          2.0           NA
1993    New York          0.8           100
1994    New York          0.6           NA
1995    New York          0.8           NA
1996    New York          2.0           NA
1990    Boston             NA           NA
1991    Boston             1.6          NA
1992    Boston             1.25         NA
1993    Boston             0.5          200
1994    Boston             1.75         NA
1995    Boston             2.5          NA
1996    Boston             0.5          NA

The code to construct the input Data:
myData<-structure(list(Year = c(1990L, 1991L, 1992L, 1993L, 1994L, 1995L,1996L, 1990L, 1991L, 1992L, 1993L, 1994L, 1995L, 1996L), City = structure(c(2L,2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Boston","New York"), class = "factor"), MultiplicationFactor = c(NA,0.9, 2, 0.8, 0.6, 0.8, 2, NA, 1.6, 1.25, 0.5, 1.75, 2.5, 0.5),`Price(BaselineYear)` = c(NA, NA, NA, 100L, NA, NA, NA, NA,NA, NA, 200L, NA, NA, NA)), .Names = c("Year", "City", "MultiplicationFactor","Price_BaselineYear"), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -14L))

The output I desire (the last column, Price_AllYears):
Year    City    MultiplicationFactor    Price_BaselineYear  Price_AllYears
1990    New York    NA                  NA                  69.4
1991    New York    0.9                 NA                  62.5
1992    New York    2.0                 NA                  125.0
1993    New York    0.8                 100                 100.0
1994    New York    0.6                 NA                  60.0
1995    New York    0.8                 NA                  48.0
1996    New York    2.0                 NA                  96.0
1990    Boston      NA                  NA                  200.0
1991    Boston      1.6                 NA                  320.0
1992    Boston      1.25                NA                  400.0
1993    Boston      0.5                 200                 200.0
1994    Boston      1.75                NA                  350.0
1995    Boston      2.5                 NA                  875.0
1996    Boston      0.5                 NA                  437.5

Here is what I have so far thanks to @alistaire:
myData %>%
  group_by(City) %>%
  arrange(Year) %>%
  mutate(Price_AllYears = ifelse(Year < Year[which(!is.na(Price_BaselineYear))],
                        lead(Price_AllYears) / lead(MultiplicationFactor),
                        ifelse(Year > Year[which(!is.na(Price_BaselineYear))],
                               lag(Price_AllYears) * MultiplicationFactor,
                               Price_BaselineYear)))%>%
  ungroup() %>%
  arrange(City)

This is the error I get:

Error: object 'Price_AllYears' not found

Here is the method I would use if I had to use Excel:
    A       B       C                       D                   E
1   Year    City    MultiplicationFactor    Price_BaselineYear  Price_AllYears
2   1990    New York    NA                  NA                  E3/C3
3   1991    New York    0.9                 NA                  E4/C4
4   1992    New York    2.0                 NA                  E5/C5
5   1993    New York    0.8                 100                 D5
6   1994    New York    0.6                 NA                  E5*C6
7   1995    New York    0.8                 NA                  E6*C7
8   1996    New York    2.0                 NA                  E7*C8
9   1990    Boston      NA                  NA                  E10/C10
10  1991    Boston      1.6                 NA                  E11/C11
11  1992    Boston      1.25                NA                  E12/C12
12  1993    Boston      0.5                 200                 D12
13  1994    Boston      1.75                NA                  E12*C13
14  1995    Boston      2.5                 NA                  E13*C14
15  1996    Boston      0.5                 NA                  E14*C15

A: fun inputs a set of row numbers, subsets MyData to those rows and determines the index of the base value, ix.base.  First check that there is exactly one baseline price and if not return NA; otherwise, calculate the multipliers prior to the base, hd, and after the base, tl.  For each of these we can use cumprod to avoid the type of iterative calculation shown in the spreadsheet formulas in the question.  Finally multiply the calculated multipliers by the base price.  Use ave to apply this to each city.  No packages are used:
fun <- function(ix) with(MyData[ix, ], {
  ix.base <- which(!is.na(Price_BaselineYear))
  if (length(ix.base) != 1) return(NA)
  hd <- rev(cumprod(rev(1/head(MultiplicationFactor, ix.base)[-1])))
  tl <- cumprod(tail(MultiplicationFactor, - ix.base))
  Price_BaselineYear[ix.base] * c(hd, 1, tl)
})
transform(MyData, Price_AllYears = ave(seq_along(Year), City, FUN = fun))

giving:
   Year     City MultiplicationFactor Price_BaselineYear Price_AllYears
1  1990 New York                   NA                 NA         69.444
2  1991 New York                 0.90                 NA         62.500
3  1992 New York                 2.00                 NA        125.000
4  1993 New York                 0.80                100        100.000
5  1994 New York                 0.60                 NA         60.000
6  1995 New York                 0.80                 NA         48.000
7  1996 New York                 2.00                 NA         96.000
8  1990   Boston                   NA                 NA        200.000
9  1991   Boston                 1.60                 NA        320.000
10 1992   Boston                 1.25                 NA        400.000
11 1993   Boston                 0.50                200        200.000
12 1994   Boston                 1.75                 NA        350.000
13 1995   Boston                 2.50                 NA        875.000
14 1996   Boston                 0.50                 NA        437.500


text:
Q: angular $q and google.maps.api I'm struggleling since hours trying to understand how is working $q.
I'm trying to make it works with a function from the google.maps api but I'm definitely not able to answer it by myself or maybe I totally don't understand $q.
I hope you'll be able to help me or at least give me some explanation.
Here is a very simple example of what I would like to do :
var geocoder = new google.maps.Geocoder();
let promise1 = geocoder.geocode({address: "someAddress"});
let promise2 = geocoder.geocode({address: "someOtherAddress"});
$q.all([promise1, promise2]).then(data => {
    console.log(data)
});

//The ouput I get is : [undefined, undefined] but it's definitely not what I expect :P

Where am I wrong ? Here is the original async method from google api which works fine.
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: "someAddress"}, function(response, status){
    if(status === 'ok')
        //Do what I need with the response
    else
        //Do something else
});

The thing is I want to do do something with multiple requests, not only one.
So I need to store all the responses (and wait for them to be stored as it's an async function) before doing something.
That's why I try to use $q to reach my goal.
PS: Maybe it's a double thread because I saw a lot of discussion about $q but even after hours of researches I can't find an issue... So please don't tell me to google it.
Thanks by advance for your help !

A: .geocode doesn't return a Promise, it uses a callback (as you know) and returns undefined as you've found out
You can make a "promisified" geocode function, along the lines of
const geocodePromise = (geocoder, params) => new Promise((resolve, reject)  => {
    geocoder.geocode(params, function(response, status) {
        if (status == 'ok') resolve(response);
        else reject(status);
    });
});

var geocoder = new google.maps.Geocoder();
let promise1 = geocodePromise(geocoder, {address: "someAddress"});
let promise2 = geocodePromise(geocoder, {address: "someOtherAddress"});
$q.all([promise1, promise2]).then(data => {
    console.log(data)
});

or
google.maps.Geocoder.geocodeP = function geocodeP(params) {
    return new Promise((resolve, reject)  => {
        this.geocode(params, function(response, status) {
            if (status == 'ok') resolve(response);
            else reject(status);
        });
    });
};
var geocoder = new google.maps.Geocoder();
let promise1 = geocoder.geocodeP({address: "someAddress"});
let promise2 = geocoder.geocodeP({address: "someOtherAddress"});
$q.all([promise1, promise2]).then(data => {
    console.log(data)
});

A: what node module you're using? google-maps-api?
geocoder.geocode({address: "someAddress"});

returns a promise or
try do this
geocoder.geocode({address: "someAddress"}).then(data => console.log(data));

if it returns undefined then the one causing the problem is the API it self.
if data is not undefined then the geocoder.geocode() part is is not causing the problem
you can try this library Get states of tasks ran by bluebird.all().spread()
for the "double thread" you mention, JavaScript don't support multi thread. you can refer to this link Why doesn't JavaScript support multithreading?


text:
Q: Folium library error in choropleth Am using folium library with an open data set from kaggle,
map.choropleth(geo_path=country_geo, data=plot_data,
         columns=['CountryCode', 'Value'],
         key_on='feature.id',
         fill_color='YlGnBu', fill_opacity=0.7, line_opacity=0.2,
         legend_name=hist_indicator
          )

The above part of the code is giving me the following error:
TypeError: choropleth() got an unexpected keyword argument 'geo_path'

When I replace geo_path with geo_data I get this error:
 JSONDecodeError: Expecting value: line 7 column 1 (char 6)

A: Is the issue related to "UCSanDiegoX: DSE200x Python for Data Science"? I took the advice of Cody and rename geo_path to geo_data at the specifications of map.choropleth.
At the git hub repository, take care of using the RAW data, which is in fact a file structured with the format GeoJSON. The first two lines should start like the code provided below
{"type":"FeatureCollection","features":[
{"type":"Feature","properties":{"name":"Afghanistan"},"geometry":
{"type":"Polygon","coordinates":[[[61.210817,35.650072],.....

A: geo_path doesn't work because it is not a parameter for choropleth. You are correct in replacing it with geo_data.
Your second error is likely due to non-existent or incorrectly formatted geojson file.
From http://python-visualization.github.io/folium/docs-master/modules.html?highlight=chor# your argument for geo_data needs to be a "URL, file path, or data (json, dict, geopandas, etc) to your GeoJSON geometries".
GeoJSON formatted files follow this structure from geojson.org:
 {
  "type": "Feature",
  "geometry": {
    "type": "Point",
    "coordinates": [125.6, 10.1]
  },
  "properties": {
    "name": "Dinagat Islands"
  }
}


text:
Q: Invoking Spring MVC controller method from another thread (javax.jms.MessageListener) I'm looking for a way of sending messages to my Spring MVC Controller from another thread. In particular my thread is an implementation of javax.jms.MessageListener which listens for messages on a ActiveMQ queue. As soon as I get a new message in the Queue, the jms MessageListener's onMessage() method is invoked. However, now I want to invoke another method in my spring controller whenever MessageListener's onMessage() is invoked.

A: The controllers in Spring MVC are not intended to be directly invoked the way you are looking for, but are designed to handle and respond to to web requests. A cleaner way to handle what you are doing will be to move the controller logic that you plan to invoke to a services layer and invoke this common services layer from controller and JMS listener.
If you absolutely want to, you can always autowire in a controller and invoke methods on it as if it is a normal POJO though.


text:
Q: PyGTK Horizontal List I have a presentation program, and I have a vertical list with slides. I was wanting to put a horizontal list for re-ordering, and easy movement between slides.
It would look something like this, and might even have a horizontal scrollbar:
+------+------+------+------+-+
|  S1  |  S2  |  S3  |  S4  | |
 <===========================>   Scrollbar
+-----------------------------+

Does PyGTK have support for a horizontal list that I am overlooking, or do I need to implement it using a table? Or maybe a better interface would be just to have another vertical column, but I kind of like the idea of a horizontal list.

A: It looks like the CellView may be what I'm looking for. I'll have to play with it to make sure, but it sounds good to me.

A: Why don't you use an HBox? Put it on a Viewport and a ScrolledWindow and you will have scrolling support.


text:
Q: cbind specific columns from multiple csv files I have multiple of these CSV files with the same headers

I am trying to cbind the log2FoldChange and padj columns from all of my CSV into one data frame. I want the end result to look like this

With the specific columns appended together.
My code so far
files <- list.files(pattern = "*.csv")
res1 <- do.call(cbind, lapply(files,read.csv, header = T))
pos <- grep("log2FoldChange|padj", names(res1))
dataset <- res1[, pos]

But the columns (log2FoldChange, padj) in my dataset at the end don't match the values of the CSV progenitors.
Any help would be greatly appreciated, thanks in advance.

A: You can use merge:
f1 <- read.csv("file1.csv")
f2 <- read.csv("file2.csv")
dataset <- merge(f1, f2, by.x = "row.names", by.y = "row.names")


text:
Q: how to retrieve all events which are stored in EKEventStore without any predicate how to retrieve all events which are stored in EKEventStore without any predicate
I am getting the ways only based on predicate having startdate and enddate only. can you please help?
thanks in advance.

A: The DistantPast and DistantFuture doesn't work, apparently Apple doesn't like it the timespan is too large. However, since you can only get events maximally 2 months in the past anyway, I found out this does work:
NSDate *startDate = [[NSDate date] dateByAddingTimeInterval:-604800*10];   //This is 10 weeks in seconds
NSPredicate *pred = [self.eventStore predicateForEventsWithStartDate:startDate endDate:[NSDate distantFuture] calendars:nil];

A: Edit (1/30/17): This answer is outdated; see Bob's answer above.
--
Sorry, this answer might be a bit late, but for those who get here searching for this:
You still need to use a predicate, but you can just put the start date as [NSDate distantPast] and the end date as [NSDate distantFuture]
For example, this would fetch all the calendar events for the calendars included in "calendarArray" provided that you have an EKEventStore called "eventStore":
NSPredicate *fetchCalendarEvents = [self.eventStore predicateForEventsWithStartDate:[NSDate distantPast] endDate:[NSDate distantFuture] calendars:calendarArray];

NSArray *allEvents = [self.eventStore eventsMatchingPredicate:fetchCalendarEvents];