Q:

Form submit not triggering method from controller

I have a list of users that i will add the ability to remove users from but with what i currently have - the form is not doing what it is supposed to do: that is to trigger the delete method from the api controller. I am not getting any errors on the page nor in the console and not sure what i could be doing wrong:
<form  data-submit-button="#userRemoveSubmit"  id="userRemoveForm" action="/api/UserRemove/" class="ajax" method="delete" data-overview-id="@ViewBag.OverViewID" data-bind="attr: { 'data-user-id': ID(), 'data-type-id': TypeId() }">
    .......
</form>

REMOVE

Controller:
public HttpResponseMessage Delete(TypesList typeInfo)
{
 ........
}

TypeList Model:
public class TypesList
{
  public int UserId { get; set; }
  public int TypeId { get; set; }
  public int? OverViewId { get; set; }
}

How can i properly make them all connect together so that when i click on remove it triggers the delete method in the controller?

A:

You should use AJAX, and send a DELETE request:
$('#userRemoveSubmit').click(function(e){
    e.preventDefault(),
    $.ajax({
        url: '/api/UserRemove/',
        type: 'DELETE',
        data: { typeInfo : YOURVARIABLEHERE }
    }).done(function() {
         alert( "success" );
    })
    .fail(function() {
         alert( "error" );
    })
    .always(function() {
         alert( "complete" );
    });
});

ref: http://api.jquery.com/jquery.ajax/


Q:

submit to ninja form programmatically

I've been researching for days and all I want to be able to do is create entries in the ninja form admin listings. Either by submitting custom form (not ninja form generated) or just calling a hook and passing data (data will match actual form fields created in ninja form).
I want to be able to do this so that I can create any type of form layout and still be able to submit to ninja form entry. Or if anyone has any other information on a plugin that can allow me to do such a thing, please share.

A:

In NinjaForms version 3, you probably want to look at this file:
ninja-forms/includes/Actions/Save.php
The process function contains the important bits that may help you:
$sub = Ninja_Forms()->form( $form_id )->sub()->get();

foreach($fields as $field_id => $field_value){
    $sub->update_field_value( $field_id, $field_value );
}

$sub->save();

In NinjaForms version 2, it is a little different
$sub_id = Ninja_Forms()->subs()->create( $form_id );

foreach( $form_fields as $field_id => $value ) {

    Ninja_Forms()->sub( $sub_id )->add_field( $field_id, $value );
}

Where the $form_fields array would look like:
$form_fields = array(

    $fiel_id_1 => $value_1,
    $fiel_id_2 => $value_2,
    ...

);


Q:

ASP.NET MVC - Securing actions by default (without putting attributes on every action)

So far I've seen the main advice for applying authorization rules consists of adding various attributes to actions. Which is fine if the majority of your actions don't require authorisation.
However my application entirely exists behind a login form, so for me it makes sense to have all actions require authorisation by default.
Is there a way to do this without having to annotate every method?

A:

You can dictate the login via the web.config.
You can derive all your controllers from a common base controller which either has an attribute over it, or override the OnAuthorization method.
Implement the Application_AuthenticateRequest in the Global.asax.


Q:

"Failed to instantiate module" при подключение ng-app

Подключаю AngularJS 1.4.2 и директиву ng-app="test" в проект. Отключил всё кроме AngularJS. Получаю такую ошибку:

Uncaught Error: [$injector:modulerr] Failed to instantiate module test
   due to: Error: [$injector:nomod] Module 'test' is not available! You
   either misspelled the module name or forgot to load it. If registering
   a module ensure that you specify the dependencies as the second
   argument

подобная ошибка вылазит если запустить на codepen http://codepen.io/anon/pen/RPJNOG

A:

У меня используется require и поэтому это нужно было делать так
var angular =  require("angular");
var app = angular.module( "test", [] );
angular.bootstrap( document, ['test']);

Пример использования с require
require( [ 'angular', 'require' ], function ( ) {

 var angular =  require("angular");
 var app = angular.module( "XXX", [ 'ngResource' ] );

 require ( "../XXFactory" ) ( app );
 require ( "../XXFactory" ) ( app );
 require( "../XXController" ) ( app );
} )


Q:

How to add subview in ListView?

I am developing my first MAC application, i downloaded one Example of  PxListView
and i have to added one button and background image on cell xib and bind them with controller
and, when on button click i was set height of that cell is much bigger then other. that is done,
and work fine.
but now i want to develop like after is witch cell has open in that cell i want to add some extra contain (Controller) on it, so how it will possible using given example?
pls help me to give some suggest how it will be done.
for Ex like before click on button

after chick on button i want to develop like

A:

You write

i have to added one button and background image on cell xib and bind them with controller

It sounds like you've subclassed PXListViewCell--for convenience, let's call your subclass TemplateListViewCell--and added a xib from which instances of TemplateListViewCell will be loaded in
+[PXListViewCell cellLoadedFromNibNamed:bundle:reusableIdentifier:]

In addition, there is a[t least one] button in TemplateListViewCell.xib.
You write

when on button click i was set height of that cell is much bigger then other. that is done, and work fine

It sounds like this button has as its action a method on TemplateListViewCell such as
- (IBAction)toggleDetail:(id)sender
{
    //Code to grow or shrink the height of [self frame].
    //...
}

In my approach to implementing -toggleDetail, two modifications to the PXListView files were necessary:
1.  Adding a protocol method
- (void)listView:(PXListView *)aListView setHeight:(CGFloat)height ofRow:(NSUInteger)row;

to the PXListViewDelegate protocol.
2.  Adding a property
@property (nonatomic, assign) BOOL expanded;

to PXListViewCell.
My implementation of -toggleDetail looks something like this:
- (IBAction)toggleDetail:(id)sender
{
    BOOL wasExpanded = [self expanded];

    NSRect oldFrame = [self frame];
    CGFloat oldHeight = oldFrame.size.height;
    CGFloat newHeight = oldHeight;

    CGFloat heightIncrement = 0.0f;
    if (wasExpanded) {
        heightIncrement = -80.0f; //use whatever value is appropriate
    } else {
        heightIncrement = 80.0f;  //use whatever value is appropriate
    }
    newHeight += heightIncrement;

    [[[self listView] delegate] listView:[self listView] setHeight:newHeight ofRow:[self row]];
    [[self listView] reloadData];

    BOOL isExpanded = !wasExpanded;
    [self setExpanded:isExpanded];
}

It might seem better to use [[self listView] reloadRowAtIndex:[self row]]; in place of [[self listView] reloadData], but unfortunately, this doesn't work: if the user hides the detail--shrinks the cell vertically--new cells which should appear on the screen do not.
You write

that is done, and work fine.

It sounds like you were able to implement successfully a method analogous to -[TemplateListViewCell toggleDetail:].
You write

but now i want to develop like after is witch cell has open in that cell i want to add some extra contain (Controller) on it, so how it will possible using given example? pls help me to give some suggest how it will be done.

It sounds like you want instances of TemplateListViewCell to contain extra views if they are expanded.
It might seem tempting to put this code into -[TemplateListViewCell toggleDetail], but this will not work out as we might hope.  The trouble is, we need to handle cases where expanded cells have been scrolled out of view and scrolled back into view.
To get this right, we need to have a notion of expanded which persists beyond the usage of a PXListViewCell subclass instance: we either need to keep track of expansion in the PXListView itself or in its delegate.
The better--but less expedient--design seems to be to keep track of this information in the PXListView itself.   For the sake of this question, however, I'll demonstrate how to keep track of cell expansion in the delegate.  To do this, I'm expanding the PXListViewDelegate protocol and making other changes to the PXListView files:
1.  Adding the methods
- (void)listView:(PXListView *)aListView setExpanded:(BOOL)expanded atRow:(NSUInteger)row;
- (BOOL)listView:(PXListView *)aListView expandedAtRow:(NSUInteger)row;

to PXListViewDelegate.
2.  Adding the method
- (void)setCell:(PXListViewCell *)cell expandedAtRow:(NSUInteger)row
{
    if ([[self delegate] respondsToSelector:@selector(listView:expandedAtRow:)]) {
        [cell setExpanded:[[self delegate] listView:self expandedAtRow:row]];
    }
}

to PXListView.
3.  Calling -[PXListView setCell:expandedAtRow:] from -[PXListView layoutCells]
- (void)layoutCells
{
    //Set the frames of the cells
    for(id cell in _visibleCells)
    {
        NSInteger row = [cell row];
        [cell setFrame:[self rectOfRow:row]];

        [self setCell:cell expandedAtRow:row];

        [cell layoutSubviews];
    }

    NSRect bounds = [self bounds];
    CGFloat documentHeight = _totalHeight>NSHeight(bounds)?_totalHeight:(NSHeight(bounds) -2);

    //Set the new height of the document view
    [[self documentView] setFrame:NSMakeRect(0.0f, 0.0f, NSWidth([self contentViewRect]), documentHeight)];
}

and from -[PXListView layoutCell:atRow:]:
- (void)layoutCell:(PXListViewCell*)cell atRow:(NSUInteger)row
{
    [[self documentView] addSubview:cell];
    [cell setFrame:[self rectOfRow:row]];

    [cell setListView:self];
    [cell setRow:row];
    [cell setHidden:NO];

    [self setCell:cell expandedAtRow:row];
}

4.  Setting _expanded to NO in -[PXListViewCell prepareForReuse]:
- (void)prepareForReuse
{
    _dropHighlight = PXListViewDropNowhere;
    _expanded = NO;
}

Note: In the sample PXListViewCell subclass, MyListViewCell, distributed with PXListView, the implementation of -[MyListViewCell prepareForReuse] fails to call [super prepareForReuse].  Make sure that this call is made in [TemplateListViewCell prepareForReuse]:
- (void)prepareForReuse
{
    //...
    [super prepareForReuse];
}

One change needs to be made to -[TemplateListViewCell toggleDetail:].  The line
[self setExpanded:isExpanded];

needs to be replaced by
[[[self listView] delegate] listView:[self listView] setExpanded:isExpanded atRow:[self row]];

Once you've set up your PXListView's delegate to properly handle the new delegate methods, you're ready to override [PXListViewCell setExpanded:] in your subclass TemplateListViewCell:
- (void)setExpanded:(BOOL)expanded
{
    if (expanded) {
        //add detail subviews
    } else {
        //remove detail subviews
    }
    [super setExpanded:expanded];
}

Replace //add detail subviews with your own code which programmatically adds the detail subviews that you want and replace //remove detail subviews with code to remove the detail subviews that you want, checking to see that they are present first.
You write

i want to add some extra contain (Controller) on it

It sounds like you want to add view controllers rather than views to your TemplateListViewCell.  To do this, use an NSBox and set the box's contentView to your view controller's view.  (For details on this, see this answer.)
If you plan on just showing a single view controller's view in an NSBox on the expanded TemplateListViewCell, you can just (1) add a property to TemplateListViewCell referencing your view controller and (2) add an NSBox to TemplateListViewCell xib and set its contentView to the appropriate view controller's view on [cell setExpanded:YES] and set its contentView to nil on [cell setExpanded:NO].


Q:

If else code execution with Optional class

I was going through a tutorial of Optional class here - https://www.geeksforgeeks.org/java-8-optional-class/ which has the following
String[] words = new String[10];
Optional<String> checkNull = Optional.ofNullable(words[5]);
if (checkNull.isPresent()) {
    String word = words[5].toLowerCase();
    System.out.print(word);
} else{
    System.out.println("word is null");
}

I am trying to make it of less lines using ifPresent check of Optional as
Optional.ofNullable(words[5]).ifPresent(a -> System.out.println(a.toLowerCase()))

but not able to get the else part further
Optional.ofNullable(words[5]).ifPresent(a -> System.out.println(a.toLowerCase())).orElse();// doesn't work```

Is there a way to do it?

A:

Java-9
Java-9 introduced ifPresentOrElse for something similar in implementation. You could use it as :
Optional.ofNullable(words[5])
        .map(String::toLowerCase) // mapped here itself
        .ifPresentOrElse(System.out::println,
                () -> System.out.println("word is null"));

Java-8
With Java-8, you shall include an intermediate Optional/String and use as :
Optional<String> optional = Optional.ofNullable(words[5])
                                    .map(String::toLowerCase);
System.out.println(optional.isPresent() ? optional.get() : "word is null");

which can also be written as :
String value = Optional.ofNullable(words[5])
                       .map(String::toLowerCase)
                       .orElse("word is null");
System.out.println(value);

or if you don't want to store the value in a variable at all, use:
System.out.println(Optional.ofNullable(words[5])
                           .map(String::toLowerCase)
                           .orElse("word is null"));

A:

For a bit to be more clear ifPresent will take Consumer as argument and return type is void, so you cannot perform any nested actions on this
public void ifPresent(Consumer<? super T> consumer)

If a value is present, invoke the specified consumer with the value, otherwise do nothing.

Parameters:

consumer - block to be executed if a value is present

Throws:

NullPointerException - if value is present and consumer is null

So instead of ifPreset() use map()
String result =Optional.ofNullable(words[5]).map(String::toLowerCase).orElse(null);

print Just to print
System.out.println(Optional.ofNullable(words[5]).map(String::toLowerCase).orElse(null));


Q:

Protractor - compare numbers

In my program I'm calculating two numbers, and I want to make sure that subtraction of them equals 1.
this is the code:
var firstCount=element.all(by.repeater('app in userApps')).count();
var secondCount=element.all(by.repeater('app in userApps')).count();

so far it's good- I'm getting the numbers. the problem comes next:
var sub=secondCount-firstCount;
expect(sub).toEqual(1);

I'm getting this error:
Expected NaN to equal 1.

any idea?

A:

Both firstCount and secondCount are promises that are needed to be resolved:
element.all(by.repeater('app in userApps')).count().then(function (first) {
    element.all(by.repeater('app in userApps')).count().then(function(second) {
        expect(first - second).toEqual(1);
    })
});


Q:

Show and hide elements based on index in jquery

I am trying to show div based on index in jquery:
I have the elements like this:

$('#prod_thumb li').hover(function() {

  var idx = $('#prod_thumb li').index(this);
  console.log('clicked index', idx);

  $('.product-single__photos div:nth-child(1)').hide();
  $('.product-single__photos div').eq(idx).show();

}, function() {
  var idx = $('#prod_thumb li').index(this);
  $('.product-single__photos div').eq(idx).hide();
  $('.product-single__photos div:nth-child(1)').eq(idx).show();

});

I want to show div that I clicked and hide the other ones. How do I do it? Right now I am able to hide one image only in the callback function.

A:

You should use .siblings() to select all the other elements.

$('#prod_thumb li').hover(function(){
  var idx = $('#prod_thumb li').index(this);
  $('.product-single__photos div').eq(idx).show().siblings().hide();
}, function(){
  $('.product-single__photos div').show().slice(1).hide();
}).first().trigger('mouseover');
ul {padding: 0;margin: 0;}
ul li {display:inline-block;}


Q:

Turning JSON file into an array in Swift/Xcode

I have been struggling all week. I am new to programming. I cannot turn a simple JSON file into a dictionary in Xcode. There is little simplified documentation online using the new method of Codable. So I am using a walkthrough, which has the following code.
import UIKit
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        guard let path = Bundle.main.path(forResource: "menu", ofType: "json") else { return }
        let url = URL(fileURLWithPath: path)

        do {

            let data = try Data(contentsOf: url)
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
            //print(json)

            guard let array = json as? [Any] else { return }
            for user in array {
                guard let userDict = user as? [String: Any] else { return }
                guard let drinks = userDict["drinks"] as? String else { print("not a String"); return }
                guard let junkFood = userDict["junk-food"] as? String else { return }

                print(drinks)
                print(junkFood)
                print(" ")
            }
        }
        catch {
            print(error)
        }

    }

}

The below code is what my JSON looks like.

{"menu": {
  "drinks": [
    {"coke": "20"},
    {"pepsi": "20"},
    {"water": "20"}
  ],
  "junk-food": [
    {"hamburger": "40"},
    {"fries": "20"},
    {"pizza": "20"}
  ]
}}

Can anyone please walk me through, or show me some simplified documentation as to how I can turn the JSON into a dictionary that I can later map the data from? I am using Xcode and trying to work out Swift 4.
Thanks in advance for your patience.

A:

My guess is that your json is actually a Dictionary not an Array. So guard let array = json as? [Any] else { return } is falling through because the json is [String: Any]. You can get to the array with the "menu" key.
Here's an updated version of your code:
 do {
        let data = try Data(contentsOf: url)
        let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
        //print(json)

        guard let menuDict = json as? [String: Any] else { return }

        guard let drinks = menuDict["drinks"] as? [[String: Any]] else {
            print("not an array of dictionaries")
            return
        }

        guard let junkFood = menuDict["junk-food"] as? [[String: Any]] else {
            print("not an array of dictionaries")
            return
        }
        print(drinks)
        print(junkFood)
        print(" ")
    }

Try that, let me know if it works. This is just the do block by the way.


Q:

Partial - Differentiation problem

I am having a problem differentiating.
Thinking about the chain rule, but not sure how to get this to work.
Would like to calculate
$$\frac{\partial}{\partial\mu}\Bigg[\Bigg(\frac{p_0}{p_b(\mu)}\Bigg)^{\beta(\mu)}\Bigg]$$
Any help will be much appreciated.

A:

Hint:
I assume that $p_0$ and $b$ are constants. Set $y=\left(\frac{p_0}{p_b(\mu)}\right)^{\beta{(\mu)}}$ and by taking logarithym from both sides we have $$\ln(y)=\beta{(\mu)}\ln\left(\frac{p_0}{p_b(\mu)}\right)$$ Now differentiate form both sides respect to $\mu$: $$\frac{\partial}{\partial\mu}\ln(y)=\frac{\partial}{\partial\mu}\left(\beta{(\mu)}\ln\left(\frac{p_0}{p_b(\mu)}\right)\right)$$ so $$\frac{\partial y}{y\partial\mu}=\frac{\partial}{\partial\mu}(\beta{(\mu)})\ln\left(\frac{p_0}{p_b(\mu)}\right)+\frac{\partial}{\partial\mu}\left(\ln\left(\frac{p_0}{p_b(\mu)}\right)\right)(\beta{(\mu)})$$ so
$$\frac{\partial y}{\partial\mu}=y\left[\frac{\partial\beta}{\partial\mu}\ln\left(\frac{p_0}{p_b(\mu)}\right)-\frac{\partial{p_b}}{\partial\mu}\frac{\beta{(\mu)}}{p_b(\mu)}\right]$$


Q:

How return null by using Stream API?

So, I have an ArrayList of autogenerated strings. I want to find the first element that contains some character or else if there is no one element that matches this filter, to apply another filter. In another way, I want to return null object.
So I write this lambda expression:
str.stream()
   .filter(s -> s.contains("q"))
   .findFirst()
   .orElseGet(() -> str.stream()
                       .filter(s -> s.contains("w"))
                       .findFirst()
                       .orElseGet(null))

But if there is no one element that matches this two filters I will have NullPointerException. How, can I get something like: return null?

A:

Unless I'm missing something obvious, simply .orElse(null) instead of the last orElseGet. orElseGet accepts a Supplier and you pass a null, calling get() on a null reference, well...

A:

The problem is Optional::orElseGet(null) which accepts a Supplier<T> and throws the NullPointerException.
Use the Optional::orElse(null) which accepts T which is String in your case.
The following code works:
List<String> str = Arrays.asList("a", "b", "c");
String output = str.stream()
                   .filter(s -> s.contains("q"))
                   .findFirst()
                   .orElseGet(() -> str.stream()
                                       .filter(s -> s.contains("w"))
                                       .findFirst()
                                       .orElse(null));                 // <-- HERE

System.out.println(output);    // Prints null

Alternatively, use the Optional::orElseGet(Supplier<? extends T> other) to return null. The Supplier itself must be not null:
.orElseGet(() -> null));

A:

An additional, simpler approach: you can filter on strings containing q or w, then sort to move those containing q first, find first, return null if the optional is empty:
str.stream()
    .filter(s -> s.contains("q") || s.contains("w"))
    .sorted((s1, s2) -> s1.contains("q") ? -1 : 1 )
    .findFirst()
    .orElse(null);

.sorted((s1, s2) -> s1.contains("q") ? -1 : 1 ) will move the strings containing "q" first. Since the stream has been filtered only on values containing either q or w, then returning null will only happen no element is retained.


Q:

Where to place $PATH variable assertions in zsh?

I love zsh, but I am not sure where to place my $PATH and other variable assertions? I find that they are scattered between the files .zshrc .zprofile .bashrc .bash_profile, and sometimes doubled.
I realize that having anything inside the bash files doesn't make much sense seeing as I'm using zsh, but where exactly should I be placing my rvm, python, node etc additions to my $PATH?
Is there a specific file I should be using (i.e. .zshenv which does not currently exist in my installation), one of the ones I am currently using, or does it even matter?

A:

tl;dr version: use ~/.zshrc
And read the man page to understand the differences between:

~/.zshrc, ~/.zshenv and ~/.zprofile.

Regarding my comment
In my comment attached to the answer kev gave, I said:

This seems to be incorrect - /etc/profile isn't listed in any zsh documentation I can find.

This turns out to be partially incorrect: /etc/profile may be sourced by zsh. However, this only occurs if zsh is "invoked as sh or ksh"; in these compatibility modes:

The usual zsh startup/shutdown scripts are not executed. Login shells source /etc/profile followed by $HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a pathname. [man zshall, "Compatibility"].

The ArchWiki ZSH link says:

At login, Zsh sources the following files in this order:
  /etc/profile
  This file is sourced by all Bourne-compatible shells upon login

This implys that /etc/profile is always read by zsh at login - I haven't got any experience with the Arch Linux project; the wiki may be correct for that distribution, but it is not generally correct. The information is incorrect compared to the zsh manual pages, and doesn't seem to apply to zsh on OS X (paths in $PATH set in /etc/profile do not make it to my zsh sessions).

To address the question:

where exactly should I be placing my rvm, python, node etc additions to my $PATH?

Generally, I would export my $PATH from ~/.zshrc, but it's worth having a read of the zshall man page, specifically the "STARTUP/SHUTDOWN FILES" section - ~/.zshrc is read for interactive shells, which may or may not suit your needs - if you want the $PATH for every zsh shell invoked by you (both interactive and not, both login and not, etc), then ~/.zshenv is a better option.

Is there a specific file I should be using (i.e. .zshenv which does not currently exist in my installation), one of the ones I am currently using, or does it even matter?

There's a bunch of files read on startup (check the linked man pages), and there's a reason for that - each file has it's particular place (settings for every user, settings for user-specific, settings for login shells, settings for every shell, etc).
Don't worry about ~/.zshenv not existing - if you need it, make it, and it will be read.
.bashrc and .bash_profile are not read by zsh, unless you explicitly source them from ~/.zshrc or similar; the syntax between bash and zsh is not always compatible. Both .bashrc and .bash_profile are designed for bash settings, not zsh settings.

A:

Here is the docs from the zsh man pages under STARTUP/SHUTDOWN FILES section.
   Commands  are  first  read from /etc/zshenv this cannot be overridden.
   Subsequent behaviour is modified by the RCS and GLOBAL_RCS options; the
   former  affects all startup files, while the second only affects global
   startup files (those shown here with an path starting with  a  /).   If
   one  of  the  options  is  unset  at  any point, any subsequent startup
   file(s) of the corresponding type will not be read.  It is also  possi-
   ble  for  a  file  in  $ZDOTDIR  to  re-enable GLOBAL_RCS. Both RCS and
   GLOBAL_RCS are set by default.

   Commands are then read from $ZDOTDIR/.zshenv.  If the shell is a  login
   shell,  commands  are  read from /etc/zprofile and then $ZDOTDIR/.zpro-
   file.  Then, if the  shell  is  interactive,  commands  are  read  from
   /etc/zshrc  and then $ZDOTDIR/.zshrc.  Finally, if the shell is a login
   shell, /etc/zlogin and $ZDOTDIR/.zlogin are read.

From this we can see the order files are read is:
/etc/zshenv    # Read for every shell
~/.zshenv      # Read for every shell except ones started with -f
/etc/zprofile  # Global config for login shells, read before zshrc
~/.zprofile    # User config for login shells
/etc/zshrc     # Global config for interactive shells
~/.zshrc       # User config for interactive shells
/etc/zlogin    # Global config for login shells, read after zshrc
~/.zlogin      # User config for login shells
~/.zlogout     # User config for login shells, read upon logout
/etc/zlogout   # Global config for login shells, read after user logout file

You can get more information here.

A:

I had similar problem (in bash terminal command was working correctly but zsh showed command not found error)

Solution:

just paste whatever you were earlier pasting in ~/.bashrc to:
~/.zshrc


Q:

HTML + FLEX: display flash behind HTML

how can I display my flash video, behind the tags on top of the page ?
Website: http://www.sanstitre.ch/drupal/portfolio?tid[0]=58
thanks
I'm using SWFObject wrapper (cross-browser) http://code.google.com/p/swfobject/
<div style="background-color: rgb(255, 255, 255); width: 100%;">
<object height="445" width="660" type="application/x-shockwave-flash" data="/drupal/videoPlayer/bin-debug/videoPlayer.swf?file=http://www.sanstitre.ch/drupal/sites/default/files/files/projects/WM 1976/videos/P1030297.flv" id="movie_player_1" style="visibility: visible;" wmode="transparent">
<param name="bgColor" value="#ffffff">
<param name="allowfullscreen" value="true">
<param name="autoplay" value="true">
<param name="flashvars" value="0=movie_player_1">
<param value="transparent" name="WMODE">
</object>

A:

I've solved adding
display: block

property to object. (And of course doing all what you suggested).


Q:

 tag merely prints enclosed HTML

When this gets run on the first load with Javascript disabled it will just print to the screen without interpreting the HTML:

Refreshing the page always displays it correctly.
Looking at the requests and responses nothing looks all that different from the ones that get served properly.
Help appreciated!

A:

Tested this on other major websites like Amazon, this is a bug in the browser. I filed a bug report and hope they will fix it. Not much else to do.


Q:

Alternative to “façade”

In software development, I’m using the so-called “Façade Pattern” to hide the complexity of a workflow via abstraction and encapsulation. I’m naming my classes using a “_Façade” suffix, so like Customer_Façade, Filesystem_Façade, and such.
I’d like a better word to use in my naming convention. What is an alternative to façade?
I've seen the question Word for "ability to hide complexity", but it does not provide an acceptable answer.
After thought: I’m actually wondering whether I should even try to find a generalized word from the English language, or whether I should instead try to find a word from the specific domain (software development), considering that these will have different meanings depending on context — for example, Profile.

A:

This seems more like a programming question than an English-language one, but
here’s my answer anyway:
I question whether you need a suffix for these classes. Unless you have both Customer and CustomerFacade classes, you should just call your single class a Customer. If you do need the second class to hide certain features then perhaps a suffix like Worker or Interface would be appropriate, depending on what you are trying to accomplish.


Q:

Dashing dashboard and batman.js binding

I'm writing a dashing widget to stream a video. I have a widget that works, however getting it to change the URL remotely with batman.js is eluding me. As far as I can tell, all I'm needing to do is modify the end of a URL inside an object, but I'm not sure if I'm even going about this the correct way.
I would like to use a command like dashing uses in its example:
 curl -d '{ "auth_token": "YOUR_AUTH_TOKEN", "channel": "12345" }'\http://url:3030/widgets/twitch

the dashboard: twitch.erb

the widget: twitch.html
<object type="application/x-shockwave-flash" height="700" width="990" id="live_embed_player_flash" data="http://www.twitch.tv/widgets/live_embed_player.swf?channel=CHANNEL"></object>

twitch.coffee
class Dashing.Twitch extends Dashing.Widget

ANSWERED
And of course, after playing with it for another 10 minutes I figured it out. But for anyone else, here is what I changed:

twitch.html
<object type="application/x-shockwave-flash" height="700" width="990" id="live_embed_player_flash" data-bind-data="channel | prepend 'http://www.twitch.tv/widgets/live_embed_player.swf?channel='"></object>

A:

And of course, after playing with it for another 10 minutes I figured it out. But for anyone else, here is what I changed:

twitch.html
<object type="application/x-shockwave-flash" height="700" width="990" id="live_embed_player_flash" data-bind-data="channel | prepend 'http://www.twitch.tv/widgets/live_embed_player.swf?channel='"></object>


Q:

Edit Mozilla configuration file in Python

Settings for the Mozilla Firefox browser my be changed by entering about:config in the address bar, which will open a configuration file. I would like to be able to edit, delete and add parameters to this file in Python. How can I do this?

A:

The configuration files used in firefox are actually a couple of javascript files that you can find under the profile directory: prefs.js and user.js.
You can use python to append lines to those files (user.js recommended) like:
user_pref(<preference>, <value>)

However, I don't really think is a good idea to use python for this.


Q:

How to get onClickListener for Android array of buttons to work

I have created a dynamic array of buttons that come from sqllite database. For the life of me I cannot get a click listener set up to address each button individually. I have been searching for 3 hours with no success at all.
Any help would be appreciated. Don't worry about the database crap, it's just the listener.
imports...

public class CreatePlayList extends Activity {

    ScrollView scrollleft, scrollright;
    LinearLayout songsright, songsleft;
    TextView testtext;
    String[][] allsongs;
    int numofsongs, i;
    Button b1[];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.createplaylist);
        scrollleft = (ScrollView) findViewById(R.id.scrollleft);
        scrollright = (ScrollView) findViewById(R.id.scrollright);
        songsright = (LinearLayout) findViewById(R.id.layRight);
        songsleft = (LinearLayout) findViewById(R.id.layLeft);
        LyricDb connect = new LyricDb(CreatePlayList.this);
        connect.open();
        numofsongs = connect.getNumSongs();
        b1 = new Button[(numofsongs)];
        allsongs = new String[numofsongs][2];
        allsongs = connect.getSongArray();
        connect.close();
        testtext = new TextView(this);
        testtext.setText("Test");
        songsleft.addView(testtext);

        for (i = 0; i < allsongs.length; i++) {
            b1[i] = new Button(this);
            b1[i].setText(allsongs[i][1]);
            songsright.addView(b1[i]);
        }

        b1[19].setText("test 123");
        createClic();
    }

    public void createClic(){
        for (i = 0; i < (allsongs.length - 1); i++) {
            b1[i].setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    testtext.setText(b1[i].getText());
                }
            });
        }
    }
}

A:

Dump the 'i' declared at class level.  Replace method with this (the "Button theButton" needs to stay 'final').
public void createClic()
{
    for (int i = 0; i < (allsongs.length - 1); i++)
    {
        final Button theButton = b1[i];
        theButton.setOnClickListener(new View.OnClickListener()
        {

            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                testtext.setText(theButton.getText());
            }
        });
    }
}


Q:

DateTime in UTC not converting to Local

I'm receiving a DateTime response from API that's sets the timezone to UTC.
But when I try to convert the received data using toLocal() it doesn't convert.
my local time is HKT
here's my code.
    //TIME DIFFERENCE
  getNotificationDate(DateTime date) {
    date = date.toUtc();
    final convertedDate = date.toLocal();

    final dateNow = DateTime.now();
    print('TIMENOW: ' + dateNow.toString());
    print('TIMENOTIFC: ' + convertedDate.toString());
    final difference = dateNow.difference(convertedDate);
    print('DIFFERENCE: ' + difference.toString());
    return getDurationFormat(difference);
  }

EDIT:
date is the DateTime I'm receiving from the API. which is in UTC timezone.
I used print('TIMEZONENAME: ' + date.timeZoneName; and it automatically sets the timezone to HKT. that's why it does nothing when I try to use date.toLocal()

A:

Flutter gave us the easiest way to convert it.
You just need to pass utc: true while parsing your date.
var dateTime = DateFormat("yyyy-MM-dd HH:mm:ss").parse(dateUtc, true);
var dateLocal = dateTime.toLocal();

Input:
Assume my TimeZone : +05:30
UTC Date -> 2020-02-12 23:57:02.000
Output:
Local Date -> 2020-02-12 18:27:02.019660

A:

// you have time in utc
var dateUtc = DateTime.now().toUtc();
print("dateUtc: $dateUtc"); // 2019-10-10 12:05:01

// convert it to local
var dateLocal = dateUtc.toLocal();
print("local: $dateLocal"); // 2019-10-10 14:05:01

Can you see the difference in hours, in utc it is 12 and locally it is 14.


Q:

Correspondence between dbus-send and QDBusAbstractInterface

What is the correspondence between parameters of dbus-send utitily and parameters of constructor and call* methods of QDBusAbstractInterface?
There is a plenty of examples (e.g. [1]) in the Internet of how to rule NetworkManager via DBus using dbus-send utility, but I can't infer how to transform them into Qt C++ code.

A:

The question sounds a little too generic for any answer to be very useful for you but...
dbus-send --dest=com.example.service \
          /service/path \
          com.example.interfacename.Method \
          int32:123

should match
QDBusInterface iface("com.example.Service",
                     "/service/path",
                     "com.example.interfacename");
iface.call("Method", 123);


Q:

Do Non Vegetarians not have rights to mourn morally if their beloved ones are killed?

Pleasures for us is pain & suffering for the animals which are slaughtered. When we are causing suffering & pain to others, we lose moral rights to expect not the same ever happened to us. In case of animal slaughtering, do we also lose the moral rights to mourn if our beloved ones are killed the same way which we, being non Vegetarian, kill other creatures? In other words, Don't we have moral rights to take it as injustice to ourselves if our beloved ones are killed, being Non Vegetarian?
EDIT: Seems I am unable to express myself clearly, I would like to ask the same question in other words: Do non-vegetarians lose rights to ask GOD if their beloved ones are killed, presuming GOD doesn't want us to kill any creature intentionally for sensual pleasures. (Seems obvious if god is Benevolent & Equal to all the creatures.)?

A:

moral rights

"Rights" aren't a moral or ethical category. They are a juridical category.

to mourn

To "mourn", on the other hand, is psychological, not moral or juridical, phenomenon.
So, the "moral right to mourn" is a conflation of disparate concepts, which becomes meaningless at all three - juridical, moral, psychological - levels.
Juridically, there is nothing that can be done to prevent people from mourning. If they think that the defeat of their preferred soccer team is something to mourn, more than the death of thousands of people in a war on the other side of the planet, there is nothing to be done about. What would we do? Jail them? Tell them they are going to hell? Dose them some chemical that will make them unable to mourn?
Morally, you can condemn whatever you want. It doesn't affect the rights of others. You may think that those who see too much television lose their moral grounds to complain about the moral decadence of society, for television is hugely responsible for such decadence. They will still watch TV and complain about the decaying mores of the commonwealth. Both things are, and should be, legal rights; a society in which either or both were forbidden would be horrible to live in.
Psychologically, there is nothing that can be done about mourning or not mourning. One may think that I should mourn the extinction of the pox virus; but the fact is that if I am not, for any reason, psychologically attached to such virus, I won't mourn its extinction, and may be indifferent or happy about it. It's possible, I guess, to shame people into pretending that they are unhappy about a given event, but it is not possible to make them unhappy if they are not.
And this - shaming people - is what this idea is probably about. It is not that we should not mourn the passing of our grandmother just because we just ate a barbecue; it is that we should not have eaten the barbecue, for we should think of the poor cow as we think of our grandmother. But as some of the comments above pointed out, the vast majority of human beings do not think a cow is equivalent to a human being, and consequently won't be able to act as if it was.

Evidently, the idea of an all-encompassing equivalence among all living beings is pragmatically unsustainable. All human beings, vegetarians and animal-rights activists included, are "especiesist" - they do not think killing a vegetal is the same as killing an animal, they do not think killing an insect - or any invertebrate - is the same as killing a mammal, they rarely think that amphibians, fish, or lizards, are on the same standing as birds and mammals, and more often than not discriminate among mammals - who does empathise with a bat or a hyaena as much as with a panda, for instance?

Talking about empathy, it is often repeated that a psychopath is someone who is devoid of empathy. But empathy is a complicated thing; as someone else put it, if you break your leg, do you want a physician who painfully pulls it into the right position, or a physician who hugs you and cries together? "Empathy" can be paralising in this sence. If no empathy makes one a psychopath, unqualified empathy may turn one hysteric.
Most of us are by far more empathetic towards our own relatives, friends, neighbours, etc, than towards people we do not know and live far away. And the idea that you should not mourn your grandmother because you didn't properly mourn the victims of a hurricane in Texas or an earthquake in Mexico is somewhat disturbing - at some point, all-encompassing empathy veers dangerously in the direction of no empathy at all.


Q:

Defining conversion operator for specialized template class only

I want to define conversion to float for matrix<1, 1>. I have trouble figuring out how to actually define it. If I make it a global function
template<typename T>
inline operator T(const matrix<T, 1, 1> &m){ return m(0, 0); }

I get "operator.. must be a non static member function"
I can of course define it as member for the generic matrix template but then it will be defined for all matrices - which is not what I want. I want it to be defined only for the specific case of 1x1 matrix.

A:

You have to specialize a class for that, for example:
template <typename Base, typename T, std::size_t W, std::size_t H>
struct MatrixConversion
{ /*Empty*/ };

template <typename Base, typename T> struct MatrixConversion<T, 1u, 1u>
{
    operator const T&() const { return static_cast<const Base&>(*this).m[0][0]; }
};

template <typename T, std::size_t W, std::size_t H>
struct Matrix : MatrixConversion<Matrix<T, W, H>, T, W, H>
{
    // Your code
};


Q:

Where can I ask: Lotus Notes 8.5 Not Supporting Digital Badging

I have the following question that I want to ask. I think it is off-topic for main. Where can I ask this question:

I have recently taken (and passed) my SAS Global Certification exam. SAS offers some downloadable watermarks for business cards and resumes, but recently they have incorporated digital badges from Acclaim. The digital badges look great, and are interactive when used in a signature. I can use this digital badge flawlessly in my gmail account, but in the office I have Lotus Notes 8.5
The only way I am able to show my credential is using an image (which looks very poor) in this version of Lotus Notes, and is not clickable.
Does Lotus Notes 8.5 not support the full use of digital badging/hyperlink imaging?

Is Super User a site that will fit?

A:

You can post this question on Super User using at least the lotus-notes tag.
I'm not saying there is or isn't anything wrong with your question, but make sure to read How do I ask a good question? and What topics can I ask about here?.


Q:

Fulltext search not yielding results

I've started working with Fulltext indexing, and I've ran into a problem that I can't find a solution for.
Ive created a catalog with
create FULLTEXT CATALOG [ClaimDbCatalog] AS DEFAULT

Then my table looks like ...
create table Claim(
Id int identity(1,1) not null ,
DateTimeCreated dateTime not null default getDate(),

ScriptNumber varchar(20) not null,
IsResolved bit not null default 0,
ResolvedDateTime datetime,
PracticeId int not null references dbo.Practice(Id),
CreatedById int not null references dbo.SystemUser(Id)

CONSTRAINT [PK_Claim_Id] PRIMARY KEY CLUSTERED  ([Id] ASC));

Created my index with :
create fulltext index idxClaimonIdFulltext Claim(ScriptNumber) KEY INDEX [PK_Claim_Id] ON ClaimDbCatalog

Then, looking at my test data ..

Finally, I attempt the fulltext search with
SELECT * from     CONTAINSTABLE([dbo].[Claim], Scriptnumber, 'PR1234567890')

But this yields no results. I've tried using part of the text, but still no results.
What am I doing wrong?

A:

The issue was due to me doing my tests in a TRAN. The moment I committed the data, the fulltext kicked in and worked.


Q:

Fail to make repeated SOCK_STREAM connection to the server while the server did not start?

I was doing Network Programming with sockets. And there is a problem while my client program was trying to make repeated connections to the server when the server did not start ( particular requirement of the project ).
Here is the problem:
Server did not start: the client waits 3 seconds, then make another connect() request.
When I start the server: the client still attempts to connect every 3 second.
The error message when we run the client program:
$./client localhost
Cannot connect to the server. Retrying...: Connection refused
Cannot connect to the server. Retrying...: Invalid argument
Cannot connect to the server. Retrying...: Invalid argument
...

Here is the client code:
#include <stdio.h>
#include <sys/types.h>
#include <netdb.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#define SERVER_PORT "9734"
#define WAIT_SERVER_TIME 3
int main(int argc, char* argv[]){
    if(argc<2){
        printf("usage: %s MACHINE_NAME\n",argv[0]);
        exit(EXIT_SUCCESS);
    }else{
        int client_socket_fd = 0 ;
        struct addrinfo hints,*results;
        /* Get the address info of the server to be connected */
        memset(&hints,0,sizeof hints);
        hints.ai_family = AF_INET;
        hints.ai_socktype = SOCK_STREAM;
        if( getaddrinfo(argv[1],SERVER_PORT,&hints,&results) !=0){
            printf("Cannot recognize the given server name");
            exit(EXIT_FAILURE);
        }
        /* Create the client socket */
        if((client_socket_fd = socket( AF_INET, SOCK_STREAM, 0))<0){
            perror("Cannot create the client socket.");
            exit(EXIT_FAILURE);
        }
        if(results->ai_addr == NULL){
            perror("Cannot find the given server name.");
            exit(EXIT_FAILURE);
        }
        /* Set up the connection */
        while(connect(client_socket_fd,results->ai_addr,
                    results->ai_addrlen) < 0 ){
            perror("Cannot connect to the server. Retrying...");
            sleep(WAIT_SERVER_TIME);
        }
        printf("Successfully connected to the server.\n");
        // DO STUFFS HERE
        exit(EXIT_SUCCESS);
     }
}

Here is the server code for testing purpose:
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <ifaddrs.h>
int main(int argc, char* argv[]){

    /* SERVER SET UP */
    int enable_reuse_socket = 1;
    struct sockaddr_in server_address;
    socklen_t server_address_len=0;
    int server_socket_fd ;

    server_socket_fd = socket( AF_INET, SOCK_STREAM, 0);
    // Handle error creating a socket
    if( server_socket_fd < 0){
        perror("Cannot initialize the socket for connection.");
        exit( EXIT_FAILURE);
    }

    // Set up the INET address
    server_address.sin_family = AF_INET;
    server_address.sin_addr.s_addr= htonl(INADDR_ANY);
    server_address.sin_port = htons(SERVER_PORT);
    server_address_len = sizeof( server_address);
    // Bind the socket to the given address
    if(setsockopt(server_socket_fd,SOL_SOCKET,SO_REUSEADDR,&enable_reuse_socket
                ,sizeof(int))<0){
        perror("Fail to reuse socket.");
    }
    if(bind(server_socket_fd,(struct sockaddr*) &server_address,
                server_address_len) !=0){
        perror("Cannot bind the socket to the given address.");
        exit(EXIT_FAILURE);
    }
    // Allow the socket to listen to the clients
    if(listen(server_socket_fd, MAX_CLIENT)!=0){
        perror("Cannot allow the socket to listen to incoming client \
                messages");
        exit(EXIT_FAILURE);
    }
    struct sockaddr_in client_addr;
    socklen_t client_addr_len;
    while(1){
         int client_fd = accept(server_socket_fd,(struct sockaddr*)&client_addr,
            &client_addr_len);
         printf("Gotcha!");
    }
}

A:

Some socket implementations leave the socket in an inconsistent state after a failed connect(). Try something like this:
int client_socket_fd = 0 ;
struct addrinfo hints,*results;
/* Get the address info of the server to be connected */
memset(&hints,0,sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
if( getaddrinfo(argv[1],SERVER_PORT,&hints,&results) !=0){
    printf("Cannot recognize the given server name");
    exit(EXIT_FAILURE);
}
if(results->ai_addr == NULL){
    perror("Cannot find the given server name.");
    exit(EXIT_FAILURE);
}
/* Set up the connection */
while(1) {
    /* Create the client socket */
    if((client_socket_fd = socket( AF_INET, SOCK_STREAM, 0))<0){
        perror("Cannot create the client socket.");
        exit(EXIT_FAILURE);
    }

    if (connect(client_socket_fd,results->ai_addr,
            results->ai_addrlen) == 0 ) {
        break;
    }

    perror("Cannot connect to the server. Retrying...\n");
    close(client_socket_fd);
    sleep(WAIT_SERVER_TIME);
}
printf("Successfully connected to the server.\n");


Q:

Testing embedded spaces in c

I want to create a function in C programming, which will test for the embedded spaces in C.
if it found embedded spaces in a string it will return 1 else 0
examples:
'sjdfnsdj' >>>>> return 0
'sdsd sdsdf' >>>>> return 1
'    ssadsa' >>> return 0
'dfjksdnf sdfsdfdf' >>>> return 1
' sadf asdad' >>>> return 1

Embedded spaces means spaces between two strings or after the string but NOT before a string

A:

You could use strchr to scan the string for a space character after you you skipped leading spaces.
Assuming char buf[] holds the string to test
int i=0;
while ( buf[i] == ' ' && buf[i] != '\0' )
  i++;

return strchr( &buf[i], ' ' ) != NULL;

EDIT: The post has been retagged with homework.
Instead of using strchr you can also do another loop like the one to skip the leading spaces. To find out whether there are further spaces after the first non space char.


Q:

How to make custum layout in zing library?

I am working in qr code scanner project . Now i need to create custum layout for qr code scanner is it possible using zing ? any tutorial / code about this ?

A:

Here try this
 compile 'com.journeyapps:zxing-android-embedded:3.0.3@aar'
 compile 'com.google.zxing:core:3.2.0'

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<com.journeyapps.barcodescanner.CompoundBarcodeView
    android:id="@+id/barcode_scanner"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

</com.journeyapps.barcodescanner.CompoundBarcodeView>

</LinearLayout>

In Your Activity or Fragment
 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_page_three, container, false);
    barcodeView = (CompoundBarcodeView) view.findViewById(R.id.barcode_scanner);
    barcodeView.decodeContinuous(callback);

    return view;
}

Callback
 private BarcodeCallback callback = new BarcodeCallback() {
    @Override
    public void barcodeResult(BarcodeResult result) {
    String resultString = result;
    }


Q:

Using exported symbols

I have a Haskell file called maxflow.hs  that exports few symbols
module MaxFlow
(solveMaxFlow,MaxFlowNet,Vertex,Graph) where
import Data.List

data Vertex = Vertex {
                          vertexLabel :: String
                        , vertexNeighbors :: [(String,Int)]
                        , vertexDistance :: Int
                        , vertexPredecessor :: String
                      } deriving (Show)

....

In the same directory I have another file called elimination.hs  that tries to use one of those symbols
import MaxFlow

g =  [
                Vertex "0" [("1",16), ("2",13)         ] (maxBound::Int)  "",
                Vertex "1" [("2",10), ("3",12)  ] (maxBound::Int) "",
                Vertex "2" [("4",14) ,("1",4)        ] (maxBound::Int) ""    ,
                Vertex "3" [ ("5",20), ("2",9)] (maxBound::Int) ""      ,
                Vertex "4" [("5",4), ("3",7) ] (maxBound::Int) ""      ,
                Vertex "5" [ ] (maxBound::Int) ""
      ]

But for some reason I can't load this file. Running
:l  elimination.hs
I get
elimination.hs:4:17: error:
    Data constructor not in scope:
      Vertex :: [Char] -> [([Char], Integer)] -> Int -> [Char] -> a
  |
4 |                 Vertex "0" [("1",16), ("2",13)         ] (maxBound::Int)  "",
  |                 ^^^^^^

I'm probably missing something very basic. Any idea ?
 Thanks!

A:

module MaxFlow
   (...,Vertex,...) where

This says you want to export the type named Vertex and not the data constructor or the fields.  What you probably want is either to export both the data type and the data constructor:
module MaxFlow (Vertex(Vertex)) where

Or to export the type, all data constructors, and all fields:
module MaxFlow (Vertex(..)) where

Those dots are literal not a short hand, you can type Vertex(..) in the export list to mean the type, data constructors, and all fields.

A:

You only exported the type constructor, not its data constructor(s). If you want to export the data constructor(s), you can write the can write this between parenthesis in the export:
module MaxFlow (solveMaxFlow, MaxFlowNet, Vertex(Vertex), Graph) where

-- …
If you want to export the getters/setters, you should include these in the parenthesis as well:
module MaxFlow (solveMaxFlow, MaxFlowNet, Vertex(Vertex, vertexLabel, vertexNeighbors, vertexDistance, vertexPredecessor), Graph) where

-- …
You can write two consecutive dots (..) if you want to export all:
module MaxFlow (solveMaxFlow, MaxFlowNet, Vertex(..), Graph) where

-- …


Q:

How to get a list of uncommitted files from tortoise or svn

I am writing a c# app that needs to look at a folder and get a list of files that need to be committed.  Tortoise SVN is guaranteed to be installed on the machine.  How can I get that list programmatically?

A:

I don't think that TortoiseSVN can help you with this, but it should not be too much effort doing it yourself using a C# SVN library.
Take a look at this question: Does anyone know of a good C# API for Subversion?.


Q:

How to update different node child at same time firebase android

i want to update timeslot based on condition for example when user booked a bike start time 09:00AM and end time 12:00PM then i want to update time slot from 09:00AM to 12:00AM availability false.
so is it possible to update different child at same time. or please give me a path how can i do this.
                DatabaseReference ref= FirebaseDatabase.getInstance().getReference().child("TimeSlot").child(Common.BikeId);

            ref.orderByChild("TimeSlot").equalTo("10:00AM").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                   //update children

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });

in above code only one children i could update at a time
how to solve this kind of solution.

A:

First of all, you can't compare String to match with startAt and endAt time. Instead use long value like [0 - 24] to hold the time in 24 hour format.
And then, execute below operation to update the child isAvailable to false
DatabaseReference ref = FirebaseDatabase.getInstance().getReference()
        .child("TimeSlot")
        .child(Common.BikeId);

ref.orderByChild("time_slot")
        .startAt(9.0)
        .endAt(12.0)
        .addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for(DataSnapshot childSnapshot: dataSnapshot.getChildren()) {

                    //Check whether child with key 'isAvailable' exist or not
                    if(childSnapshot.hasChild("isAvailable")) {

                        //Now update the status with false
                        ref.child(childSnapshot.getKey())
                                .child("isAvailable")
                                .setValue(false);
                    }
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });


Q:

Anyone find the reset tag useful?

We have 88 questions tagged reset. It's used for almost any kind of reset action, from reset preferences to reset the system. I don't find that tag useful at all. Someone has been suggesting a tag wiki, but whenever I check the questions that are currently tagged (and as answerer) I see no pattern other than resetting stuff. I find more useful that the question is tagged with the thing you want to "reset" instead of a tag to "reset" anything.

A:

I think reset is just a hodge-podge of questions that in some way need something "reset".  I don't think it serves a purpose here because there are much better, more specific tags for most if not all of the questions in that tag.


Q:

Empty response body on retrofit call

I have a app whos call a service POST (postman test) and get some information from that call.
My retrofit initializer:
class RetrofitInitializer {

    private val retrofit = Retrofit.Builder()
        .baseUrl("https://bank-app-test.herokuapp.com/api/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()

    fun loginApiContract() : LoginApiContract{
        return retrofit.create(LoginApiContract::class.java)
    }
}

the interface:
interface LoginApiContract {

    @POST("login")
    fun login() : Call<UserAccount>

    @GET("statements")
    fun getStatements()
}

and finally the call:
val call = RetrofitInitializer().loginApiContract().login()

call.enqueue(object: Callback<UserAccount> {
    override fun onResponse(call: Call<UserAccount?>?,
    response: Response<UserAccount?>?) {
        response?.body()?.let {
            val myUserAccount: UserAccount = it
            loginView.doLogin(myUserAccount)
        }
    }

    override fun onFailure(call: Call<UserAccount?>?,
    t: Throwable?) {
        Log.e("onFailure error", t?.message)
    }
})

I got response code 200, but response body is empty.
This is my postman response:
{
"userAccount": {
    "userId": 1,
    "name": "Jose da Silva Teste",
    "bankAccount": "2050",
    "agency": "012314564",
    "balance": 3.3445
},
"error": {}
}

and this is my model:
class UserAccount constructor(var userId: Int, var name: String, var bankAccount: String, var agency: String, var balance: Double){

    init{

        this.userId = userId
        this.name = name
        this.bankAccount = bankAccount
        this.agency = agency
        this.balance = balance
    }
}

A:

I found!
Its a problem with my postman. For any reason my AVD cant access the mock server. now i solve my problem with a simple restful api node.js.
Thx for the help guys.


Q:

JQuery Tablesorter - leave the first row intact

I am using the jQuery Tablesorter 2.0 plugin to create a sortable table of ... say books.
The very first row of the table will be a summary of all books, and I want it to always be at the top.
I need to customize the behavior of the tablesorter, but I do not think I can/should do that with a custom parser. What I think I need is a custom comparator function - one that would allow me to compare any two rows myself, ideally also being able to invoke the default behavior if the condition that I am looking for has not been met.
Sample algorithm would be like so (hopefully I did not invert my result):
function customSort(lhs, rhs, table, column_index) {
    if (lhs === 'magic_str') {
        return -1; // Magic string wins
    }
    if (rhs === 'magic_str') {
        return 1; // Magic string wins
    }
    return defaultSort(lhs, rhs, table, column_index);
}

Now, I know some JS but not enough to pry a popular library open and rewrite parts of it, particularly as a patch that would go on top, after I load the original. (that would be ideal). Also, if I can accomplish this sort of behavior in any other way, I am all ears.

A:

An easier solution would be to try out my fork of tablesorter and just put that row you don't want to sort into a separate tbody - this won't work with the original tablesorter.
<table class="tablesorter">
    <thead>
        ...
    </thead>
    <tbody class="tablesorter-infoOnly">
        ... <!-- non-sorting tbody -->
    </tbody>
    <tbody>
        ...
    </tbody>
</table>

Since it is only one row, you don't really need to add the "tablesorter-infoOnly" class name; it does prevent column styling being applied to it. Try out this demo and remove the tbody class name to see the difference.
And FYI, you can add any number of tbodies to the table.


Q:

Error: [$injector:unpr] Unknown provider: ngCsvProvider <- ngCsv <- dynamicDemoController

Here is my scenario:

file A.js that define the main module.
file B.js lazy-loaded (after angular bootstrap) that contains a controller and some directives.

file A.js:
var APP = angular.module('app.hello', ['ui.router', 'ngAnimate', 'ngTable', 'ngSanitize', 'ngCsv']);

(function() {

  APP.config(function ($controllerProvider, $compileProvider) {
    APP.loadController = $controllerProvider.register;
    APP.loadDirective = $compileProvider.directive;
  });

})();

file B.js:
(function() {
  "use strict";

  APP.loadController("dynamicDemoController", dynamicDemoController);
  dynamicDemoController.$inject = ["NgTableParams", "ngCsv"]; // <-- err

  function dynamicDemoController(NgTableParams, CSV) {
   // ...
  }

})();

I'm injecting NgTableParams flawlessly but I'm not being able to "inject" the ngCsv module and I'm getting this error in console:

Error: [$injector:unpr] Unknown provider: ngCsvProvider <- ngCsv <-
  dynamicDemoController

Any idea what am I possibly missing?

A:

You are trying to inject a module in your controller, that's why its causing error.
  dynamicDemoController.$inject = ["NgTableParams", "ngCsv"]; // <-- err

ngCsv is a module and not a service.
Loading of module's should be limited to angular.module.
var myapp = angular.module('myapp', ['ngCsv'])


Q:

Admob Interstitial Ad not loading in Fragment in Android

I am trying to integrate Admob SmartBanner and Interstitial Ad in my app. SmartBanner is working fine but Interstitial Ads are not loading.
What is the proper code for integrating admob banner+Interstitial add in same app.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_home, container, false);
    //------------------------------------------------------------------------------------------
    AdView mAdView = (AdView) rootView.findViewById(R.id.adView);
    final AdRequest.Builder request = new AdRequest.Builder()
            .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)        // All emulators
            .addTestDevice("1E085E6103A6876F42FC5183C73D98CB");//genymotion galaxy s5 4.4.4
    mAdView.loadAd(request.build());

    mInterstitialAd = new InterstitialAd(getActivity());
    mInterstitialAd.setAdUnitId(String.valueOf(R.string.banner_ad_unit_id));//("ca-app-pub-5059726881726792/4446999064");

    //final AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
    //adRequestBuilder.addTestDevice("1E085E6103A6876F42FC5183C73D98CB")//genymotion galaxy s5 4.4.4
    //        .addTestDevice("0B80CC732BD7E24CF42938649A17A7DA");//s3
    mInterstitialAd.setAdListener(new AdListener() {
        @Override
        public void onAdLoaded() {
            super.onAdLoaded();
        }
        @Override
        public void onAdClosed() {
            super.onAdClosed();
            mInterstitialAd.loadAd(request.build());
        }
    });
    mInterstitialAd.loadAd(request.build());
    if (mInterstitialAd.isLoaded()) {
        mInterstitialAd.show();
    }

A:

From your code, you show the interstitial ad right after loading it.
There's always a latency(delay) issue with ads getting shown after requesting/loading them.
So you can't display your ad if it isn't loaded yet. Ideally, you should show interstitial ads at a natural break point in your app. Example: when transitioning from one activity to the other. However, you can modify your code to display the ad via the #onAdLoaded in your #onCreateView like this:
        @Override
        public void onAdLoaded() {
            super.onAdLoaded();
            mInterstitialAd.show();
        }


Q:

Is it possible to derive the CDF of $Z$?

Assume that $X_i$, $Y_k$, $i=0,\ldots,N$, $k=1,\ldots,K$ are non-negative independent non-identically distributed random variables.
Let us define the random variable $Z$ as
\begin{align}
  Z=\frac{aX_0}
    { \max\limits_{k=1,\ldots,K}Y_k\cdot \left( \sum \limits_{i=1}^{N} b_iX_i +1 \right)}
\end{align}
where $a$, $b_i$ are non-negative constants.
The PDF of $X_i$ and $Y_k$ are defined as $f_{X_i}(x_i)$ and $f_{Y_k}(y_k)$, respectively.
The CDF of $X_i$ and $Y_k$ are defined as $F_{X_i}(x_i)$ and $F_{Y_k}(y_k)$, respectively.
How could I find the CDF of $Z$?
More specifically, I am going to find the CDF of $Z$ as follows:
\begin{align}
   F_Z(z)=\Pr ( Z < z )=\int\limits_0^\infty \int \limits_0^\infty
\Pr
\left(
  \frac{aX_0}
    { y\left( x + 1 \right)} < z \right) f_Y(y) \; dy \; f_X(x) \; dx \; dy
\end{align}
where $Y=\max\limits_{k=1,\ldots,K}Y_k$ and $X=\sum \limits_{i=1}^N b_iX_i$, $f_Y(y)$ and $f_X(x)$ are  PDFs of $X$ and $Y$, respectively. Note that all random variables are distributed following independent non-identically distributed exponential distributions.
I am not sure whether this formula is correct or not? Could you please verify it for me please?

A:

In the end (see comments), it seems that the question is to write down the CDF $F_Z$ and/or the PDF $f_Z$ of $Z$ using the CDFs and/or the PDFs of $X_0$, $Y$ and $X$, where
$$
Z=\frac{aX_0}{Y(X+1)}.
$$
One assumes that $a\gt0$ and that $X_0$, $X$ and $Y$ are nonnegative and independent with respective CDFs $F_0$, $F_X$ and $F_Y$ and respective PDFs $f_0$, $f_X$ and $f_Y$.
For every $z\geqslant 0$,
$$
[Z\leqslant z]=[aX_0\leqslant zY(X+1)],
$$
hence
$F_Z(z)=\mathrm P(aX_0\leqslant zY(X+1))$ is, by definition,
$$
F_Z(z)=\int\!\!\!\iint_{au\leqslant zy(x+1)}f_0(u)f_Y(y)f_X(x)\mathrm dx\mathrm dy\mathrm du,
$$
or, equivalently,
$$
F_Z(z)=\iint F_0(a^{-1}zy(x+1))f_Y(y)f_X(x)\mathrm dx\mathrm dy.
$$
Differentiating this with respect to $z$, one gets
$$
f_Z(z)=a^{-1}\iint f_0(a^{-1}zy(x+1))\cdot yf_Y(y)\cdot (x+1)f_X(x)\cdot \mathrm dx\mathrm dy.
$$


Q:

How to redirect each type of user to a different page when access is denied?

In my app I have 3 roles of Users (user, admin, non logged user), and I want to redirect them to different pages when access is denied. How to do that?
In time, what $this->Auth->authorize = array('Controller'); means? I didn't understand this in cake docs.
Thanks all.

A:

I would have it in a IF statement, but perhaps someone else can suggest a more CakePHP specific method..
if($user === 'Admin') {
   //Admin Redirect
   $redirectController = 'admin';
   $redirectMethod = 'admin_index';
} elseif ($user === 'User') {
   //User Redirect
   $redirectController = 'user';
   $redirectMethod = 'index';
} else {
  //Not logged in
  $redirectController = 'SomeController';
  $redirectMethod = 'someMethod';
}

$this->Auth->unauthorizedRedirect = array(
        'controller' => $redirectController,
        'action' => $redirectMethod
    );

$this->Auth->authorize = array('Controller'); means that the Authorization is done at the Controller level. I believe you can change where authorization is carried out using this.


Q:

AJAX calls - dynamic JSON db array - to hide HTML elements - with CSS visibility property

I'm a super excited novice, stuck on this; can't find this anywhere, please help:
How to get the var dotContainer to be all of the ids from the JSON DB, as to make all the matching HTML id elements invisible using the CSS “dot-hide” property (appose to just this one “n788” id specified with getElementById).
So the JSON database which updates dynamically with new id values (like n790 or n786) will asynchronously hide the matching HTML id element dots with the CSS “dot-hide".
JavaScript
var dotContainer = document.getElementById("n788"); //THIS TO CONTAIN ALL ID VALUES FROM THE JSON DB
    var dataRequest = new XMLHttpRequest();
    dataRequest.open('get', 'https://raw.githubusercontent.com/sicronerver/sicronerve/master/dbn.json');
    dataRequest.onload = function() {
        var ourData = JSON.parse(dataRequest.responseText);
        //setInterval(function(){
            renderdata(ourData);
        //}, 1000);
    };
dataRequest.send(); {
    }
function renderdata(dataobjectarray) {
        var texString = ""
        for (i = 0; i < dataobjectarray.length; i++) {
            texString += dataobjectarray[i].id + ",";
        }
  dotContainer.insertAdjacentText('afterEnd', texString); //REFERENCE OF JSON ID VALUES TO HIDE HTML ID ELEMENTS
  dotContainer.classList.add("dot-hide");
}

JSON
[{"id":"n787"},{"id":"n788"},{"id":"n789"}]

HTML

CSS
.dot-hide {
  visibility: hidden;
  opacity: 0;
  transform: scale(.75);
}

.grid {
  display: grid;
  grid-template-columns: repeat(16, 1fr);
  grid-template-rows: repeat(9, 1fr);
}

.dot {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #777777;
}

.dot:hover {
  background-color: rgb(60, 255, 0);
  opacity: 50%;
}

.dot:active {
  background-color: #ff0000;
  opacity: 50%;
}

#n786 {
  position: relative;
  grid-column: 3 / span 2;
  grid-row: 6 / span 2;
}

#n787 {
  position: relative;
  grid-column: 6 / span 2;
  grid-row: 6 / span 2;
}

#n788 {
  position: relative;
  grid-column: 9 / span 2;
  grid-row: 6 / span 2;
}

#n789 {
  position: relative;
  grid-column: 12 / span 2;
  grid-row: 6 / span 2;
}

#n790 {
  position: relative;
  grid-column: 15 / span 2;
  grid-row: 6 / span 2;
}

I made a pen here: https://codepen.io/andijonson/pen/gOpEmEQ
Many thanks, Andi

A:

You have to add and remove css.
Sample:
var dotContainer = document.getElementById("n788"); //THIS TO CONTAIN ALL ID VALUES FROM THE JSON DB
var dataRequest = new XMLHttpRequest();
dataRequest.open(
  "get",
  "https://raw.githubusercontent.com/sicronerver/sicronerve/master/dbn.json"
);
dataRequest.onload = function() {
  var ourData = JSON.parse(dataRequest.responseText);
  //setInterval(function(){
  renderdata(ourData);
  //}, 1000);
};
dataRequest.send();

function renderdata(dataobjectarray) {
  document.querySelectorAll("div a").forEach(x => {
    x.className = "dot";
  });
  var texString = "";
  for (i = 0; i < dataobjectarray.length; i++) {
    texString += dataobjectarray[i].id + ",";
  }
  dotContainer.insertAdjacentText("afterEnd", texString);
}

Demo:

window.onload = () => {
  function fetchData() {
    fetch(
      "https://raw.githubusercontent.com/sicronerver/sicronerve/master/dbn.json"
    )
      .then(res => res.json())
      .then(renderdata);
  }
  function renderdata(data) {
    document.querySelectorAll("div a").forEach(x => {
      x.classList.remove("hide");
    });
    data.forEach(item => {
      const elm = document.getElementById(item.id);
      elm.classList.add("hide");
    });
  }
  function start() {
    setInterval(fetchData, 2000);
  }
  start();
};
.hide {
  visibility: hidden;
  opacity: 0;
}

.grid {
  display: grid;
  grid-template-columns: repeat(16, 1fr);
  grid-template-rows: repeat(9, 1fr);
}

.dot {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #777777;
}

.dot:hover {
  background-color: rgb(60, 255, 0);
  opacity: 50%;
}

.dot:active {
  background-color: #ff0000;
  opacity: 50%;
}

#n786 {
  position: relative;
  grid-column: 3 / span 2;
  grid-row: 6 / span 2;
}

#n787 {
  position: relative;
  grid-column: 6 / span 2;
  grid-row: 6 / span 2;
}

#n788 {
  position: relative;
  grid-column: 9 / span 2;
  grid-row: 6 / span 2;
}

#n789 {
  position: relative;
  grid-column: 12 / span 2;
  grid-row: 6 / span 2;
}

#n790 {
  position: relative;
  grid-column: 15 / span 2;
  grid-row: 6 / span 2;
}


Q:

Problem with RewriteCond replace

I'm havian a problem with RewriteCond in Apache. I have URL myurl.com/cache/100x100/filename.jpg and I need to check if the file exists. The problem is that for me is not important this exact path, but different one. I need to check if the file /images/100x100/filename.jpg exists. Is it possible? Right now I have:
RewriteCond %{REQUEST_URI} ^/cache/([0-9x]*)/(.*)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f

How can I change this to check different file? Is there anything like replace?

A:

In that case, you probably want something like
RewriteCond   %{DOCUMENT_ROOT}/images/%1/%2 !-f


Q:

Radius of convergence of power series $\sum_{n=0}^{\infty} n!x^{n^2}$

Radius of convergence of power series $\sum_{n=0}^{\infty} n!x^{n^2}$
$\sum_{n=0}^{\infty} n!x^{n^2} = 1 + x + 2x^4 + 6x^9\ldots$
Comparing this with $\sum_{n=0}^{\infty} a_nx^n=$
$a_n= n! $ or $0$
$|a_n|^{\frac1n} ={n!}^{\frac1n} $ or $0^{\frac1n}$
We need $L= \lim \sup |a_n|^{\frac1n}$ and the radius of convergence $R$ will be $R=\frac1L$
$0^{\frac1n} \to 0 $ as $n\to \infty$
$\lim {n!}^{\frac{1}{n}}= \lim \frac{(n+1)!}{n!} \to \infty$ as $n \to \infty$
So $\lim |a_n|^{\frac1n} = 0 $ or $ \infty$
But I am not sure what $\lim \sup |a_n|^{\frac1n}$ is ??
My doubt is that : We are looking for the greatest limit point of $|a_n|^{\frac1n}. $ Clearly $\infty$ seems the correct answer but $\infty$ does not belong in  R and can't be a limit point. So what is the correct answer?

A:

The radius of convergence is $1$, because, if $x>0$, then$$\frac{(n+1)!x^{(n+1)^2}}{n!x^{n^2}}=(n+1)x^{2n+1}$$and the sequence $\bigl((n+1)x^{2n+1}\bigr)_{n\in\mathbb N}$ converges to $0$ if $x\in(0,1)$ and diverges if $x\geqslant1$.


Q:

Closed form of $\sum_{n = 1}^{\infty} \frac{n^{n - k}}{e^{n} \cdot n!}$

When seeing this question I noticed that
$$
\sum_{n = 1}^{\infty} \frac{n^{n - 2}}{e^{n} \cdot n!}
= \frac{1}{2}.
$$
I don't know how to show this, I tried finding a power series that matches that but no avail.
Hints are very much appreciated.
But this can be generalised:
Define
$$
S_{k}(x)
:= \sum_{n = 1}^{\infty} \frac{n^{n - k}}{x^{n} \cdot n!}.
$$
WolframAlpha shows e.g. that $S_1(e) = 1$ and
$$
S_0(x) = - \frac{W(-x^{-1})}{1 + W(-x^{-1})},
$$
where $W$ denotes the Lambert W-function.
Is there any closed form for this sum or a special $k$ or $x$ beyond those results?
Somebody attempted to answer this using the Lagrange inversion theorem. I didn't work out completely but looked quite promising.

A:

Computing the Sums
Using the Taylor series for the Lambert W function derived in this answer, we see that
$$\newcommand{\W}{\operatorname{W}}
-\W(-x)=\sum_{n=1}^\infty\frac{n^{n-1}}{n!}x^n\tag1
$$
Define $u(x)=-\W(-x)$, then we have
$$
\begin{align}
1&=u(1/e)\tag{2a}\\[3pt]
x&=u(x)\,e^{-u(x)}\tag{2b}\\
\frac{\mathrm{d}x}x&=\frac{1-u(x)}{u(x)}\,\mathrm{d}u(x)\tag{2c}
\end{align}
$$
Define $u_1=u$ and
$$
u_{k+1}(x)=\int_0^xu_k(t)\,\frac{\mathrm{d}t}{t}\tag3
$$
Then
$$
u_k(x)=\sum_{n=1}^\infty\frac{n^{n-k}}{n!}x^n\tag4
$$
We will show that
$$
u_k(x)=P_k(u(x))\tag5
$$
where $P_k(x)$ is a degree $k$ polynomial with no constant term. It is true for $k=1$ with $P_1(x)=x$. Assume it is true for $k$, then $(3)$ and $\text{(2c)}$ imply
$$
\begin{align}
u_{k+1}(x)
&=\int_0^xP_k(u(t))\,\frac{\mathrm{d}t}t\\
&=\int_0^{u(x)}P_k(u)\,\frac{1-u}u\,\mathrm{d}u\\[9pt]
&=P_{k+1}(u(x))\tag6
\end{align}
$$
Thus, $(5)$ is true for $k+1$.
Equation $(6)$ enables us to compute
$$
P_{k+1}(x)=\int_0^xP_k(t)\frac{1-t}t\,\mathrm{d}t\tag7
$$
The initial part of the sequence of polynomials is
$$
\begin{align}
P_1(x)&=x\\
P_2(x)&=x-\tfrac12x^2\\
P_3(x)&=x-\tfrac34x^2+\tfrac16x^3\\
P_4(x)&=x-\tfrac78x^2+\tfrac{11}{36}x^3-\tfrac1{24}x^4\\
P_5(x)&=x-\tfrac{15}{16}x^2+\tfrac{85}{216}x^3-\tfrac{25}{288}x^4+\tfrac1{120}x^5\\
P_6(x)&=x-\tfrac{31}{32}x^2+\tfrac{575}{1296}x^3-\tfrac{415}{3456}x^4+\tfrac{137}{7200}x^5-\tfrac1{720}x^6\\
P_7(x)&=x-\tfrac{63}{64}x^2+\tfrac{3661}{7776}x^3-\tfrac{5845}{41472}x^4+\tfrac{12019}{432000}x^5-\tfrac{49}{14400}x^6+\tfrac1{5040}x^7\\
P_8(x)&=x{-}\tfrac{127}{128}x^2{+}\tfrac{22631}{46656}x^3{-}\tfrac{76111}{497664}x^4{+}\tfrac{874853}{25920000}x^5{-}\tfrac{13489}{2592000}x^6{+}\tfrac{121}{235200}x^7{-}\tfrac1{40320}x^8
\end{align}\tag8
$$
Applying $\text{(2a)}$, $(4)$, and $(5)$, we get
$$
\sum_{n=1}^\infty\frac{n^{n-k}}{e^nn!}=P_k(1)\tag9
$$

Table of Sums
$$
\begin{array}{c|c}
k&\sum\limits_{n=1}^\infty\frac{n^{n-k}}{e^nn!}\\\hline
1&1\\
2&\frac12\\
3&\frac5{12}\\
4&\frac7{18}\\
5&\frac{1631}{4320}\\
6&\frac{96547}{259200}\\
7&\frac{40291823}{108864000}\\
8&\frac{16870575007}{45722880000}
\end{array}\tag{10}
$$

Recursion for the Coefficients of $\boldsymbol{P_k}$
Let
$$
P_k(x)=\sum_{j=1}^\infty(-1)^{j-1}a_{k,j}x^j\tag{11}
$$
where $a_{k,1}=1$ and $a_{k,j}=0$ for $j\gt k$.  Applying $(7)$ to $(11)$ gives
$$
\begin{align}
a_{k,j}
&=\frac{a_{k-1,j}+a_{k-1,j-1}}j\tag{12}\\
&=\frac1{j^k}\sum_{i=j-1}^{k-1}j^ia_{i,j-1}\tag{13}
\end{align}
$$
$(13)$ follows from $(12)$ after unrolling the recursion.

Properties of the Coefficients
We will show that for some $b_{j,n}$,
$$
a_{k,j}=\sum_{n=1}^j(-1)^{n-1}b_{j,n}\left(\frac1n\right)^k\tag{14}
$$
Since $a_{k,1}=1$, $(14)$ is true for $j=1$ with $b_{1,1}=1$ and $b_{1,n}=0$ for $n\gt1$.
Suppose that $(14)$ is true for $j-1$. Applying $(13)$ to $(14)$ yields
$$
\begin{align}
a_{k,j}
&=\frac1{j^k}\sum_{i=j-1}^{k-1}j^ia_{i,j-1}\\
&=\frac1{j^k}\sum_{i=j-1}^{k-1}\sum_{n=1}^{j-1}(-1)^{n-1}b_{j-1,n}\left(\frac jn\right)^i\\
&=\frac1{j^k}\sum_{n=1}^{j-1}(-1)^{n-1}b_{j-1,n}\frac{\left(\frac jn\right)^k-\left(\frac jn\right)^{j-1}}{\frac jn-1}\\
&=\sum_{n=1}^{j-1}(-1)^{n-1}\underbrace{\,\frac{nb_{j-1,n}}{j-n}\vphantom{\sum_{n=1}^{j-1}}\,}_{b_{j,n}}\left(\frac1n\right)^k\underbrace{-\sum_{n=1}^{j-1}(-1)^{n-1}\frac{nb_{j-1,n}}{j-n}\left(\frac jn\right)^{j-1}}_{(-1)^{j-1}b_{j,j}}\left(\frac1j\right)^k\tag{15}
\end{align}
$$
which is of the form of $(14)$ with
$$
b_{j,n}=\frac{nb_{j-1,n}}{j-n}\tag{16}
$$
for $n\lt j$ and
$$
b_{j,j}=-\sum_{n=1}^{j-1}(-1)^{j-n}b_{j,n}\left(\frac jn\right)^{j-1}\tag{17}
$$
Thus, $(14)$ is true for $j$.

Computing $\boldsymbol{b_{j,n}}$
Equation $(14)$, $(16)$, and $(17)$ allow us to give formulas for $a_{k,j}$ for each $j$:
$$
\begin{align}
a_{k,1}&=1\vphantom{\left(\frac11\right)^k}\\
a_{k,2}&=1-2\left(\frac12\right)^k\\
a_{k,3}&=\frac12-4\left(\frac12\right)^k+\frac92\left(\frac13\right)^k\\
a_{k,4}&=\frac16-4\left(\frac12\right)^k+\frac{27}2\left(\frac13\right)^k-\frac{32}3\left(\frac14\right)^k\\
a_{k,5}&=\frac1{24}-\frac83\left(\frac12\right)^k+\frac{81}4\left(\frac13\right)^k-\frac{128}3\left(\frac14\right)^k+\frac{625}{24}\left(\frac15\right)^k\\
a_{k,6}&=\frac1{120}{-}\frac43\left(\frac12\right)^k{+}\frac{81}4\left(\frac13\right)^k{-}\frac{256}3\left(\frac14\right)^k{+}\frac{3125}{24}\left(\frac15\right)^k{-}\frac{324}5\left(\frac16\right)^k
\end{align}\tag{18}
$$
Looking at $b_{j,j}$ in $(18)$, a good guess appears to be
$$
b_{j,j}=\frac{j^j}{j!}\tag{19}
$$
Combining $(16)$ and $(19)$, we get
$$
b_{j,n}=\binom{j}{n}\frac{n^j}{j!}\tag{20}
$$
which satisfies $(16)$ and $(17)$, validating the guess made for $(19)$.

Computing $\boldsymbol{a_{k,j}}$
Putting together $(14)$ and $(20)$ gives
$$
a_{k,j}=\sum_{n=1}^j(-1)^{n-1}\binom{j}{n}\frac{n^j}{j!}\left(\frac1n\right)^k\tag{21}
$$
Note that for $j\gt k$, the sum in $(21)$ is an order $j$ difference of a degree $j-k$ polynomial, hence $a_{k,j}=0$, which shows that $(21)$ is valid even for $j\gt k$.

Simpler Formula for the Sums
Applying $(9)$ and $(11)$ to $(21)$ yields
$$
\begin{align}
\sum_{n=1}^\infty\frac{n^{n-k}}{e^nn!}
&=\sum_{j=1}^k(-1)^{j-1}a_{k,j}\\
&=\bbox[5px,border:2px solid #C0A000]{\sum_{j=1}^k\sum_{n=1}^j(-1)^{j-n}\binom{j}{n}\frac{n^j}{j!}\left(\frac1n\right)^k}\tag{22}
\end{align}
$$
For each $k$, the sum in $(22)$ has $\frac{k^2+k}2$ terms. This is as close to a closed formula for the sums as I have found.

Verification of the Formula
As noted after equation $(21)$, the inner sum in $(22)$ for $j\gt k$ is $0$. That is,
$$
\begin{align}
\sum_{j=1}^k\sum_{n=1}^j(-1)^{j-n}\binom{j}{n}\frac{n^j}{j!}\left(\frac1n\right)^k
&=\sum_{j=1}^\infty\sum_{n=1}^j(-1)^{j-n}\binom{j}{n}\frac{n^j}{j!}\left(\frac1n\right)^k\tag{23}\\
&=\sum_{n=1}^\infty\sum_{j=n}^\infty(-1)^{j-n}\frac1{n!}\frac{n^{j-k}}{(j-n)!}\tag{24}\\
&=\sum_{n=1}^\infty\sum_{j=0}^\infty(-1)^j\frac1{n!}\frac{n^{j+n-k}}{j!}\tag{25}\\
&=\sum_{n=1}^\infty\frac{n^{n-k}}{e^nn!}\tag{26}
\end{align}
$$
Explanation
$(23)$: extend the sum in $j$ since the inner sums vanish for $j\gt k$
$(24)$: switch order of summation and simplify the summand
$(25)$: substitute $j\mapsto j+n$
$(26)$: evaluate the sum in $j$

A:

For each $k \geq 1$ we define $T_k$ by
$$T_k(z) := \sum_{n\geq 1} \frac{n^{n-k}}{n!}z^n.$$
We make several observations.

$T_1(z) = -W(-z)$ from the Taylor series of the Lambert $W$-function, which is
$$
W(z)
= \sum_{n \geq 1} (-n)^{n-1} \frac{z^n}{n!}.
$$
In particular, we get
$$T_1(we^{-w}) = w $$
for all $w \leq 1$. As a special case, we get $T_1(e^{-1}) = 1$.
$T_k'(z) = T_{k-1}(z)/z$. In particular,
$$ \frac{\mathrm{d}}{\mathrm{d}w} T_k(w e^{-w}) = \frac{1-w}{w}T_{k-1}(w e^{-w}). $$

From this, we can compute $T_2$ as follows:
\begin{align*}
T_2(we^{-w})
= \int \frac{1-w}{w}T_{1}(w e^{-w}) \, \mathrm{d}w
= w - \frac{w^2}{2}.
\end{align*}
In particular,
$$ \sum_{n\geq 1} \frac{n^{n-2}}{n! e^n} = T_2(e^{-1}) = \frac{1}{2}. $$
A similar argument shows that each $T_k(we^{-w})$ is a degree $k$ polynomial over $\mathbb{Q}$ without constant term, which can be computed recursively in $k$. For instance, we have
$$
\begin{array}{|c|ccccccc|}
\hline
k & 1 & 2 & 3 & 4 & 5 & 6 & 7 \\
\hline
T_k(e^{-1}) & 1 & \dfrac{1}{2} & \dfrac{5}{12} & \dfrac{7}{18} & \dfrac{1631}{4320} & \dfrac{96547}{259200} & \dfrac{40291823}{108864000} \\
\hline
\end{array}
$$

Addendum - closed form of $P_n$.
As above, let $P_n$ be the polynomial such that $T_n(z) = P_n(T_1(z))$. Then we claim that the following generating function identity holds.

$$ \sum_{n=1}^{\infty} P_n(z)t^n = - \sum_{n=1}^{\infty} \prod_{i=1}^{n} \frac{tz}{t-i}. \tag{*} $$

Once we prove this, we can find the coefficient of $z^k$ in $P_n(z)$ as
$$ [z^k] P_n(z)
= - [t^n] \frac{t^k}{(t-1)(t-2)\cdots(t-k)}
= \frac{1}{k!} \sum_{j=1}^{k} (-1)^{k-j} \binom{k}{j} \frac{1}{j^{n-k}}. $$
Consequently, we get
$$ P_n(z) = \sum_{k=1}^{n} \Bigg( \sum_{j=1}^{k} (-1)^{k-j} \binom{k}{j} \frac{1}{j^{n-k}} \Bigg) \frac{z^k}{k!}. $$
We conclude with the proof of $\text{(*)}$.
Proof of $\text{(*)}$. Using partial fraction decomposition, we find that
\begin{align*}
- \frac{t^k}{(t-1)\cdots(t-k)}
&= -1 - \sum_{j=1}^{k} (-1)^{k-j} \frac{j^k}{(j-1)!(k-j)!} \frac{1}{t-j} \\
&= -1 + \sum_{j=1}^{k} \frac{(-1)^{k-j}}{j!(k-j)!} j^k \sum_{n=0}^{\infty} \frac{t^n}{j^n}.
\end{align*}
Multiplying $z^k$ and summing over $k = 1, 2, \cdots$, we get
\begin{align*}
- \sum_{k=1}^{\infty} \frac{t^k z^k}{(t-1)\cdots(t-k)}
&= -\frac{z}{1-z} + \sum_{k=1}^{\infty} z^k \sum_{j=1}^{k} \frac{(-1)^{k-j}}{j!(k-j)!} j^k \sum_{n=0}^{\infty} \frac{t^n}{j^n} \\
&= -\frac{z}{1-z} + \sum_{n=0}^{\infty} \sum_{j=1}^{\infty} \frac{t^n}{j! j^n} \sum_{k=j}^{\infty} z^k \frac{(-1)^{k-j}}{(k-j)!} j^k \\ \\
&= -\frac{z}{1-z} + \sum_{n=0}^{\infty} \sum_{j=1}^{\infty} \frac{t^n}{j!} j^{j-n} (ze^{-z})^j \\
&= -\frac{z}{1-z} + \sum_{n=0}^{\infty} T_n(ze^{-z}) t^n.
\end{align*}
Now the desired equality follows by noting that
$$ T_0(ze^{-z}) = \frac{z}{1-z} \qquad \text{and} \qquad T_n(ze^{-z}) = P_n(z) $$
for $n \geq 1$.


Q:

Parallel efficiency drops inconsistently

My question is probably of trivial nature. I parallelised a CFD code using MPI libraries and now I am trying to investigate my parallel efficiency. To start with, I created a case which would provide equal loads among the ranks and constant ratio of volume of calculations over transferred data. Thus, my expectation would be that as I increase the ranks, any runtime changes would be attributed to the communication delays only.  However, I realised that subroutines that do not invoke rank communication (so they only do domain calculations, hence they deal with the same load for all ranks) contribute significantly-actually the most- runtime increases. What am I missing here? Does this even make sense?

A:

Does this even make sense?

Yes!
The more processes you create (every process has a rank), the more you reach the limit of your system's capability to execute processes in a truly parallel manner.
Your system (e.g. your computer) can run in parallel a certain amount of processes, when this limit is surpassed, then some processes wait to be executed (thus not all processes run in parallel), which harms performance.
For example, assuming that a computer has 4 cores and you create 4 processes, then every core can execute a process, thus your performance is harmed by the communicated between the processes, if any.
Now, in the same computer, you create 8 processes. What will happen?
4 of the processes will start execute in parallel, but the other 4 will wait for a core to get available, so that they can run too. This is not a truly parallel execution (some processes will execute in linear fashion). Moreover, depending on the OS scheduling policy, some processes may be interleaved, causing overhead at every switch.


Q:

Maximum at any point of two lines in R

Suppose you have two lines, L1 and L2, which for each x value (x1 and x2 for example) they have known points at L1={(x1,L1_y1), (x2,L1_y2)}, and L2={(x1,L2_y1), (x2,L2_y2)}. By joining these points they may or may not have an intersection at some x3 where x1

Now suppose you want to know the maximum at any x value (not restricted to just x1, x2 etc, but anywhere along the axis) of both of these lines. Obviously it is often trivial to calculate for just a few lines, and a few different x value, but in my case I have several tens of thousand x values and a few lines to check it against, so it can't be done manually.
In R, is there some code which will calculate the maximum at any given point x3?
An example of this can be seen here with L1={(1,1), (2,4)}, and L2={(1,4),(2,1)}, illustrated by:

Here the intersection of these lines is at (1.5, 2.5). L2 is the maximum before this, and L1 after. This maximum line is shown in red below.

As you can see, it isn't enough just to take the max at every point and join these up, and so it will need to consider the lines as some form of function, and then take the maximum of this.
Also, as mention before as there are several thousand x values it will need to generalise to larger data.
To test the code further if you wish you can randomly generate y values for some x values, and it will be clear to see from a plot if it works correctly or not.
Thanks in advance!

A:

Defining points constituting your lines from the example
L1 <- list(x = c(1, 2), y = c(1, 4))
L2 <- list(x = c(1, 2), y = c(4, 1))

defining a function taking a pointwise maximum of two functions corresponding to the lines
myMax <- function(x)
  pmax(approxfun(L1$x, L1$y)(x), approxfun(L2$x, L2$y)(x))

This gives
plot(L1$x, L1$y, type = 'l')
lines(L2$x, L2$y, col = 'red')
curve(myMax(x), from = 1, to = 2, col = 'blue', add = TRUE)

Clearly this extends to more complex L1 and L2 as approxfun is just a piecewise-linear approximation. Also, you may add L3, L4, and so on.


Q:

SSH, entered command but it didn't execute, can't type anything

I used the command tar -x file.tar.gz and, for one reason or anything it failed. Then I get stuck being able to type anything in, but not being able to run any more commands. Pressing enter just gives me a new line. I don't know how to break out of it either (escape etc doesn't work). The only way I can get back working is to close putty and reconnect.
Is there a way to get it back to normal so I can keep going because it's irritating closing it all the time.

A:

Try hitting CTRL+C :) This will cancel/kill/stop the running command!
But the best way to untar is to use -v to verbose the output :
tar -zxvf yourfile.tar.gz

With that, you'll perhaps see that your file just take more time than you thought unarchiving ;)

A:

Ctrl-C can be used to send a break to the executable that's hanging, but it's up to the application to handle it. Ctrl-Z will break you out of the running executable, but you'll need to then manually kill the process.
What you're doing wrong is you're not gunzipping the archive.
Try this
tar -zxf file.tar.gz


Q:

RXJS - multiple consecutive http requests

source<http>
  .pipe(
    switchMap(d => this.http.get(d))
      .pipe(
        switchMap(j => this.http.get(j))
      )
  )
  .subscribe()

Hello, I need to make 3 http requests consecutively where each call contains data for the next call.. are nested switch maps the best practice for this case?

A:

You don't need to nest them. You can simply chain them:
source<http>
  .pipe(
    switchMap(d => this.http.get(d)),
    switchMap(j => this.http.get(j))
  )
  .subscribe()

Apart from that, using multiple switchMap is the way to go.


Q:

Setting text for new row placeholder

I have a simple datagrid with CanUserAddRows enabled:
<DataGrid Name="TestCasesDataGrid" Padding="0 0 5 0" AutoGenerateColumns="False" CanUserAddRows="True" CanUserDeleteRows="True" CanUserSortColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Width="100" Binding="{Binding Name}" />
    </DataGrid.Columns>
</DataGrid>

Now I want to to have a gray default text "new row..." in the new row placeholder, which disappears, when I click on it (to add a new row).
In another question I found the following way to set the foreground color:
<DataGrid Name="TestCasesDataGrid" Padding="0 0 5 0" AutoGenerateColumns="False" CanUserAddRows="True" CanUserDeleteRows="True" CanUserSortColumns="False">
    <DataGrid.Resources>
        <Style TargetType="{x:Type DataGridRow}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding}" Value="{x:Static CollectionView.NewItemPlaceholder}">
                    <Setter Property="Foreground" Value="Gray" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridTextColumn Width="100" Binding="{Binding Name}" />
    </DataGrid.Columns>
</DataGrid>

But I fail to find a way to add a text as well.

A:

Here is a code behind solution I found (using a helper method to find children in the visual tree):
public static DependencyObject FindChild(DependencyObject parent, Func<DependencyObject, bool> predicate)
{
    if (parent == null) return null;

    int childrenCount = VisualTreeHelper.GetChildrenCount(parent);
    for (int i = 0; i < childrenCount; i++)
    {
        var child = VisualTreeHelper.GetChild(parent, i);

        if (predicate(child))
        {
            return child;
        }
        else
        {
            var foundChild = FindChild(child, predicate);
            if (foundChild != null)
                return foundChild;
        }
    }

    return null;
}

Make the following call after the DataGrid became visible and is fully loaded:
var dataGridRow = Tools.FindChild(testCasesDataGrid, x =>
{
    var element = x as DataGridRow;
    if (element != null && element.Item == System.Windows.Data.CollectionView.NewItemPlaceholder)
        return true;
    else
        return false;
}) as DataGridRow;
var textBlock = Tools.FindChild(dataGridRow, x =>
{
    return x is TextBlock;
}) as TextBlock;
textBlock.Text = "new row...";
textBlock.Foreground = System.Windows.Media.Brushes.Gray;


Q:

AmCharts: Show all balloons in chart to x-axis

I´ve created an chart with several axis.
The x-axis is a date with the min period "seconds".
The problem is, that it only shows one balloon at the same time. It should display all balloons. (In that case --> two)
Date property in dataProvider: d.date(new Date(year, mm, dd, hh, mm, ss, 0);
...
valueAxes.push({
                        "id": "v" + i,
                        "axisColor": '#' + farbcode[i],
                        "axisThickness": 2,
                        "offset": offset,
                        "gridAlpha": 0,
                        "axisAlpha": 1,
                        "position": pos
                    });
...
graphs.push({
                        "valueAxis": "v" + i,
                        "lineColor": valueAxes[i].axisColor,
                        "bullet": "round",
                        "balloonText": "[[value]]
[[dateformated]]",
                        "bulletBorderThickness": 1,
                        "hideBulletsCount": 30,
                        "title": window.bezei[i],
                        "valueField": window.bezei[i],
                        "fillAlphas": 0
                    });
...

window.chart = AmCharts.makeChart(chartid[0].id, {
                    "type": "serial",
                    "theme": "light",
                    "legend": {
                        "useGraphSettings": true
                    },
                    "dataProvider": chartData,
                    "valueAxes": valueAxes,
                    "graphs": graphs,
                    "synchronizeGrid": true,
                    "chartScrollbar": {},
                    "chartCursor": {
                        "cursorPosition": "mouse"
                    },
                    "categoryField": "date",
                    "categoryAxis": {
                        "minPeriod": "ss",
                        "parseDates": true,
                        "axisColor": "#DADADA",
                        "minorGridEnabled": true
                    },
                    "export": {
                        "enabled": true,
                        "dateFormat": "YYYY-MM-DD HH:NN:SS",
                        "position": "bottom-right"
                    }
                });

A:

I´ve found my problem.
I added an element in my chartData[] for each variable.
I have to combine this two elements.


Q:

"Internal Server Error" with wp_update_post

I am coding a plugin for one of my sites which will toggle two pages statuses when a button is pressed. So when the ON button is pressed it will turn one page to draft while publishing the other, and vice versa with the OFF button.
The problem I am having is that when you press the button it bring you to a "Internal Server Error" page. You need to refresh that twice before it brings you to the page I want it to bring me to. How can I fix this.
My Code
<?php
/*
Plugin Name: Page Toggle
Description: Toggle page status
Version: 0.1
Author: Author
*/

add_action( 'admin_menu', 'my_admin_menu' );

function my_admin_menu() {
    add_menu_page( 'Registration Switch', 'Registration', 'manage_options', 'registration.php', 'registration_admin_page', 'dashicons-welcome-write-blog', 6  );
}

if( isset( $_REQUEST['on'] )) {
    $my_post1 = array('ID' => 8,'post_status' => 'publish',);
    wp_update_post( $my_post1 );
    $my_post2 = array('ID' => 66,'post_status' => 'draft',);
    wp_update_post( $my_post2 );
    echo "
Registration is turned ON.

Go Back
";
}

if( isset( $_REQUEST['off'] )) {
    $my_post3 = array('ID' => 8,'post_status' => 'draft',);
    wp_update_post( $my_post3 );
    $my_post4 = array('ID' => 66,'post_status' => 'publish',);
    wp_update_post( $my_post4 );
    echo "
Registration is turned OFF.

Go Back
";
}

function registration_admin_page() {
    ?>

Registration Information

Toggle Registration

        <form>
            <input type="submit" name="on" value="Turn Registration On" class="button-secondary" onclick="return confirm('Are you sure you want to enable registration?')" />

            <input type="submit" name="off" value="Turn Registration Off" class="button-secondary" onclick="return confirm('Are you sure you want to disable registration?')" />
        </form>

    <?php
}
?>

I suspect it is because I call wp_update_post twice, although I am fairly noob with coding so don't know how to fix it.

A:

Actually, there are 2 issues in your code:

You were using PHP custom file name instead of menu_slug.
You were not using action and method attributes of form tag. When you were submitting form WordPress redirecting into admin.php?on=Turn+Registration+On which is not a valid page.

add_submenu_page function 4th parameter must be unique menu slug of your plugin not the custom PHP file.
Please have a look at the add_submenu_page function.
I have updated the code and tested. it working fine.

add_action( 'admin_menu', 'my_admin_menu' );

function my_admin_menu() {
    add_menu_page( 'Registration Switch', 'Registration', 'manage_options', 'page-toggle', 'registration_admin_page', 'dashicons-welcome-write-blog', 6  );
}

function registration_admin_page() {
    ?>

Registration Information

Toggle Registration

        <form action="<?php echo admin_url('admin.php?page=page-toggle'); ?>" method="post">
            <input type="submit" name="on" value="Turn Registration On" class="button-secondary" onclick="return confirm('Are you sure you want to enable registration?')" />

            <input type="submit" name="off" value="Turn Registration Off" class="button-secondary" onclick="return confirm('Are you sure you want to disable registration?')" />
        </form>
        <?php

        if( isset( $_REQUEST['off'] )) {
          $my_post3 = array('ID' => 90,'post_status' => 'draft');
          wp_update_post( $my_post3 );
          $my_post4 = array('ID' => 83,'post_status' => 'publish');
          wp_update_post( $my_post4 );
          echo "
Registration is turned OFF.
";
        } elseif (isset( $_REQUEST['on'] )) {
          $my_post1 = array('ID' => 90,'post_status' => 'publish');
          wp_update_post( $my_post1 );
          $my_post2 = array('ID' => 83,'post_status' => 'draft');
          wp_update_post( $my_post2 );
          echo "
Registration is turned ON.
>";
        }
        ?>

    <?php
}
?>