text:
Q: removeFromSuperview with animation and views management I did some digging around about this, but nothing really seems to answer my particular question (not even this: Is it possbile to removeFromSuperview with Animation?).
Basically, my app starts with a welcome screen, where a user clicks on "sign in", then goes to the sign in view, then getting to a tab bar view, which is the actual app.
The way I did it, is that I wrote a custom class - TabBarController, which sets up all the tabs and their respective view controllers. Now, when the user clicks on "sign in" i am calling removeFromSuperview and present the tabbar.
I am trying to find a way to animate the transition from the sign in page to the tab bar. I tried some proposed solutions around here, but none seems to do the job. Here is my code in the signin.m view controller. I am looking to animate out the current view (ideally, not just by fading out, but more cool stuff like flips, etc.).
//when done signing in --> go to the tab bar view
-(IBAction)done:(id)sender {

TabBarController  *tabController = [[TabBarController alloc] init];
[UIView beginAnimations:@"removeWithEffect" context:nil];
[UIView setAnimationDuration:4.0];
self.parentViewController.view.frame = CGRectMake(0,0,320,480);
self.parentViewController.view.alpha = 1.0f;
[UIView commitAnimations];
[self.parentViewController.view performSelector:@selector(removeFromSuperview) withObject:nil afterDelay:2.5f];
[self presentModalViewController:tabController animated:YES];

}

Appreciate any help!

A: That can't work that way. presentModalViewController dislpays the view of a viewController over the own view. It won't replace the source viewController (self).
Since you remove self.parentViewController.view from the view hierarchy, it can't present your tabController modally because you have removed self.
Anyway, i would recommend you another way to achieve your view layout:
Create a tabBarViewController and add its view to a rootView (self.window in the app delegate or whatever you are using now). Then add your login-view to the same view. Due the view hierarchy, the login-view will be displayed above the tabBar.view. And the done button should be implemented this way: (i'm using block syntax for animation as it should be)
-(IBAction)done:(id)sender {
    [UIView animateWithDuration:1.0
                     animations:^{
                         self.view.frame = CGRectMake(0, 480, 320, 480);
                         self.view.alpha = 0.0
                     }
                     completion:^(BOOL finished){
                         [self.view removeFromSuperView];
                     }
     ];
}

You can animate more things than just the alpha, size or position. Just take a look about animations in the documentation. I guess, you'll be interested in view.transform to commit flip animations. ;)

A: This is how you have to remove the view after animating it.
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
[UIView setAnimationDelay:2.0];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDelegate:myView];
[UIView setAnimationDidStopSelector:@selector(removeFromSuperview)];

[UIView commitAnimations];

Hope this helps.
Happy coding.


text:
Q: How to override some specific variables values in Ansible playbook I have some multiple war files which I am downloading from nexus and creating the respective app folder on my remote host and copying the files.
Now there are 2 files which have a different name as war file but need to create a directory with different name. What I am doing right now is this -
- name: Ensuring the web deployment folder is created on tomcat nodes for each web application
   file:
     path: "{{tomcat_server_release_location}}/Release{{my_release_version}}/{{item}}"
     state: directory
     mode: 0777
   with_items:
    - "{{ apps }}"

- name: Copying the release from Admin server to tomcat nodes
   copy: src={{admin_server_release_location}}/{{my_release_version}}/{{item}}-{{my_release_version}}.war dest={{tomcat_server_release_location}}/Release{{my_release_version}}/{{item}}
   with_items:
    - "{{ apps }}"

apps variable is defined like this -
webapps: ['test1','test2','test3','test4'].
 Now test2 has a different name on the nexus it says test2-web.war but on the remote node I have to create a folder called just test2 and copy the war file in there.
Is there a way to override some variables at run time of playbook by using some condition or anything

A: If you want to override at runtime use extra vars.
From the docs --extra-vars "version=1.23.45"
Don't use conditions if you know a specific host should always be overwritten. I think placing it as a host var is best.
hosts:
  myhost:
    apps:
      - test1
      - trst2
See https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable for all of the various locations you can put variables and how to determine which will be used

A: It is possible to override variables by doing something like this:
- name: copy war
  copy:
    src: "{{ src_war | default('/path/to/my/war') }}"
    dest: "{{ dest_war | default(src_war) }}"

Then at runtime you can set the variables src_war and dest_war either with extra vars, host/group_vars or any other way documented here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html
In your case I think it would be helpful to set a src & dest mapping:
- set_fact:
    apps:
      - {src: "test1"}
      - {src: "test2", dest: "test2-web"}
      - {src: "test3"}
      - {src: "test4"}

Then you can use this mapping to achieve your goal:
- name: Ensuring the web deployment...
  file:
    path: {{ tomcat_server_release_location }}/Release{{ my_release_version }}/{{ item.src }}
    state: directory
    mode: 0777
  with_items: "{{ apps }}"

- name: Copying the release...
  copy:
    src: "{{ admin_server_release_location }}/{{ my_release_version }}/{{ item.src }}-{{ my_release_version }}.war"
    dest: "{{ tomcat_server_release_location }}/Release{{ my_release_version }}/{{ item.dest | default(item.src) }}"
  with_items: "{{ apps }}"

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I push new values to a JavaScript object array I have an object with a property that contains an array, I was wondering what the best way of inserting into that array, this is the object:
const object1 =
  {"users": [{"username":"john","email":"john@gmail.com","id":"john_2011221"},
  {"username":"steve","email":"steve@gmail.com","id":"steve_201193841"}]};

I want  to make the object like this:
const object1 =
      {"users": [{"username":"john","email":"john@gmail.com","id":"john_2011221"},
      {"username":"steve","email":"steve@gmail.com","id":"steve_201193841"}
      {"username":"Emily","email":"emily@gmail.com","id":"emily_20119567"}]};

A: Access the array inside the Object using object1["users"]. Then you can simply push your  new object into this array like this
const object1 =
  {"users": [{"username":"john","email":"john@gmail.com","id":"john_2011221"},
  {"username":"steve","email":"steve@gmail.com","id":"steve_201193841"}]};

object1["users"].push({"username":"Emily","email":"emily@gmail.com","id":"emily_20119567"})

A: Use Array#push.
object1.users.push({"username":"Emily","email":"emily@gmail.com","id":"emily_20119567"});


text:
Q: Cannot access data from hbase with amazon ec2 I have a single node hadoop machine in which hbase is running in the amazon ec2 instance.
Due to some reason the server got restarted. So i need to start hadoop and hbase again. Then its working fine, but the old data in the hbase cannot be accessed through the web-servies.
While i use the shell command its working fine, i am getting the data.
So i created the scenario on my local server machine, but its working fine.
The version details are as follows.
hadoop-0.20.2
hbase-0.90.5
apache-tomcat-7.0.30
in Amazon ec2 medium instance
And I use restful web-services with Orm-hbase to access data.


text:
Q: amp multi page form button disabled until selected fields are completed I have a multi-page form where by I want to only allow the 'next' button to work once all fields are completed. I have followed the following link;
Amp Multipage Flow

  <button class="step-title step-active"
    [class]="currentStep > 0 ? 'step-title' : 'step-title step-active'"
    on="tap:AMP.pushState({ currentStep: 0 })">

    Animal
  </button>

 0">

What's your favorite animal?

      <amp-selector on="select:AMP.setState({animalSelected: true})"
        class="poll"
        name="animal-poll">

Cat

Dog

Horse

      </amp-selector>
      <button disabled
        [disabled]="!animalSelected"
        on="tap:AMP.pushState({ currentStep: currentStep + 1 })">
        continue
      </button>

  <button class="step-title"
    [class]="currentStep != 1 ? 'step-title' : 'step-title step-active'"
    disabled
    [disabled]="!animalSelected"
    on="tap:AMP.pushState({ currentStep: 1 })">

    Color
  </button>

What's your favorite color?

      <amp-selector on="select:AMP.setState({colorSelected: true})"
        class="poll"
        name="color-poll">

Blue

Green

Yellow

      </amp-selector>
      <button disabled
        [disabled]="!colorSelected"
        on="tap:AMP.pushState({ currentStep: currentStep + 1 })">
        continue
      </button>

  <button class="step-title"
    [class]="currentStep != 2 ? 'step-title' : 'step-title step-active'"
    disabled
    [disabled]="!colorSelected"
    on="tap:AMP.pushState({ currentStep: 2 })">

    Fruit
  </button>

What's your favorite fruit?

      <amp-selector on="select:AMP.setState({fruitSelected: true})"
        class="poll"
        name="fruit-poll">

Apple

Banana

Cheery

      </amp-selector>
      <button disabled
        [disabled]="!fruitSelected"
        on="tap:AMP.pushState({ currentStep: currentStep + 1 })">
        continue
      </button>

Which shows how I can achieve this for a single radio button, however, how can I extend this to work for multiple inputs in the same section?
Also is it possible instead of simply disabling the button, that when the button is clicked give some kind of feedback (i.e. trigger the error popups for the required inputs)?

A: You can use expressions in your binding:
See: https://www.ampproject.org/docs/reference/components/amp-bind#expressions
Something along the line of
[disabled] = "!select1 || !select2"

where "select1" and "select2" are from respective inputs.


text:
Q: Laravel different environment git .env Xampp & Mamp i'm using github in combination with laraval for the first time.
I have 2 local environments :

*

*a) i use MAMP Pro for local development (Mac)

*b) i use XAMPP for local development (Windows)

I made a new repository and pushed to github on environment a) , I cloned this repository on setup b) and added a .env file to setup my database. However i'm a bit confused what to do with the app_key value, do i need to just copy it form my initial environment? or need a new one?.
The second part of my question is that i seem to have problems with xampp vs mamp pro because they rewrite a couple of urls, wich means my project won't run on environment b). Are there other settings i need to adjust? and will it brake again if i commit on environment b) ?
Error message when running the project on environment b)
Warning: require(D:\dev.local\ADifferentDesign\bootstrap/../vendor/autoload.php): failed to open stream: No such file or directory in D:\dev.local\ADifferentDesign\bootstrap\autoload.php on line 17

Fatal error: require(): Failed opening required 'D:\dev.local\ADifferentDesign\bootstrap/../vendor/autoload.php' (include_path='.;C:\xampp\php\PEAR') in D:\dev.local\ADifferentDesign\bootstrap\autoload.p

I'm really confused , i saw other questions like this but none are quite what i was looking for.
A good aproach for future projects would also be very much appreciated
Progress update 1: I updated my .env file with the same key. But the error shown above still persists. I dont want to change te path in autoload every time i switch environments either.

A: It depends. If you are sharing any resources that hold encrypted data between the two environments, like a database, then you must copy the app_key. This is because Laravel uses the app_key whenever it encrypts something like a user's password or a session ID.
If you don't need to share a database, sessions, etc then you can and should generate a new key for every environment.
You generate a new key by running this command in your site root:
php artisan key:generate

Ideally, you would run this command as the first step in setting up a new environment, before running database seeds or other stuff. This is because if you generate a new key after seeding your database then any password you created in the seeds will be invalid and you'll have to reseed the database.


text:
Q: How do I get the path of the container folder of a file? I want to pass the path of the containing folder of a file to a command make new file at path. I know how to get the path of the currently open file (with tell application "TexShop" to set thePath to get path of document 1), but I don't know how to get the path of the containing folder.
I tried using container of, like this:
tell application "TeXShop"
    set thePath to get container of path of document 1
end tell.
But I get this error:
TeXShop got an error: Can't make container of path of document 1 into type reference.
Is that because while the container command is allowed in the application Finder it is not for the application TeXShop?

A: This following AppleScript code will get the path to the front most document in the front most application and the path to its containing folder. This will also create the new file in the containing folder.
(* The Delay Command  Gives You Time To Bring The Desired App To The Front
    Mainly For Use While Testing This Code In Script Editor.app *)

delay 5 -- Can Be Removed If Not Needed

tell application (path to frontmost application as text) to ¬
    set documentPath to (get path of document 1) as POSIX file as alias

tell application "Finder" to set containingFolder to container ¬
    of documentPath as alias

tell application "Finder" to make new file at containingFolder


text:
Q: SharePoint Versioning issue Good day,
I have hit a speed bump with SharePoint. I have developed a web part and application page, and packaged them in a wsp.
In my dev environment it seems to work with no problems, but when it is deployed in the testing environment it seems to not work. The web part calls the application page on my dev environment, but in the testing environment i get a "file not found screen".
I did some checking on it and found that my dev build version is 14.0.6029.1000 and the testing version is 14.0.7015.1000.
Does this mean my wsp will not work period or will i have to change my code?


text:
Q: Change the text direction in WPF FlowDocument TableCell I'm trying to create a simple table in a WPF FlowDocument that has rotated text in some of the cells. In Microsoft Word you can easily change the text direction of a table cell but I haven't been able to find a way in a WPF FlowDocument.
Any idea on how to rotate the text 90 degrees or change the text direction. I've tried a few things but the text doesn't wrap and size as desired.
Any help would be great. Thanks

A: Look into using the BlockUIContainer and RotateTransform
Example:
<TableCell>
  <BlockUIContainer>
    <TextBlock Text="Hello World">
      <TextBlock.LayoutTransform>
        <RotateTransform Angle="90"></RotateTransform>
      </TextBlock.LayoutTransform>
    </TextBlock>
 </BlockUIContainer>
</TableCell>


text:
Q: Why is the move constructor only called when there is already an element in the vector? I am trying to learn the new features in C++11. And I am testing the following code in XCode.
#include <iostream>
#include <string>
#include <vector>

class CClass
{
    std::string s;
public:
    CClass()
    {
        std::cout<<"Default Constructor"<<std::endl;
    }
    CClass(const std::string v) :s(v) {
        std::cout<<"Constructor"<<std::endl;
    }

    CClass(const CClass& other): s(other.s) {
        std::cout<<"Copy Constructor"<<std::endl;
    }
    CClass(CClass&& a) noexcept
    {
        std::cout<<"Move Constructor"<<std::endl;
        s = std::move(a.s);
    }
    CClass& operator = (const CClass& other)noexcept
    {
        std::cout<<"Copy Assignment"<<std::endl;
        if(this != &other)
        {
            s = other.s;
        }
        return *this;
    }
    CClass& operator = (CClass&& other) noexcept
    {
        std::cout<<"Move Assignment"<<std::endl;
        if(this != &other)
        {
            s = std::move(other.s);
        }
        return *this;
    }
};

int main()
{
    std::vector<CClass> v;
    CClass x("hello");
    //v.push_back(x);
    std::cout<<"--------------------"<<std::endl;
    v.emplace_back("uiuiu");
    std::cout<<"--------------------"<<std::endl;
}

When I uncomment the push back I get the following result:
Constructor
Copy Constructor
--------------------
Constructor
Move Constructor
--------------------

Otherwise, if I comment it, I get:
Constructor
--------------------
Constructor
--------------------

My question is why is the move constructor not being called in second case? It is only being called in the first case when vector is initially not empty.

A: It's because the one element in the vector needs to be moved to a new memory location. The reason why that happens is that the new size would exceed the vector capacity, so new memory with the new capacity had to be allocated for the vector.
From std::vector::emplace_back:

If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.

The iterators and references are invalidated for the same reason: Because the elements are now stored in a new location in memory.
If you call reserve in the first case, you'll see that no move constructor is called:
CClass x{"hello"}; // constructor
v.reserve(2); // make space for 2 elements (you could have also used resize)
v.push_back(x); // copy constructor
v.emplace_back("uiuiu"); // constructor


text:
Q: Grub doesn't install(no way till now) I have windows 10 and I installed fedora 24(Dual boot). I use easyBCD to choose OS when the PC is booted. but when I go to federa, the MINIMAL BASH like editing is appeared. I googled many hours and I tried many solutions, but still my problem is not solved and I can't install grub. also in live session or rescue mode, I can't use this command(the result is error):
chroot /mnt/sysimage

Here is some solutions that I tried: many helpful command, grub-customizer, boot-repair and etc in both live session and rescue mode.
I am very tired now, Pls help me and tell an absolute solution to solve this annoying problem, I really need fedora these days and I don't want to boot it from VMware(and such this) in windows, Thank you very much in advance.
***EDIT: Finally I solved my problem with reinstall fedora with DVD disk(not USB), because always my USB is booted in UEFI mode and I couldn't to change it to legacy mode(for my BIOS).

A: What always worked for me is Rescatux which you can find here: http://www.supergrubdisk.org/rescatux/
Boot into Rescatux and select Automatic Repair (or worded similar).
If Automatic Repair does not do the trick, select "Restore Grub" and select the Boot Device accordingly.


text:
Q: Activating a Window on X11, why do I lose the title bar? Using the bellow code, I am activating a window on X11.
I'm using FindWindow to get the window handle, which works just fine.
Then I want to bring the specified window in the foreground.
To do this, I use XRaiseWindow.
XRaiseWindow(display, wdThisWindow);

However, XRaiseWindow doesn't work on some windows (quite many, but not all).
I figured this is because their override_redirect WindowAttribute is not set to true.
So I used XChangeWindowAttributes to set this property to true.
Now, XRaiseWindow brings all windows to the top.
The problem is, EyeOfGnome (picture viewer) and all other applications looses the top title bar... (you know, the one with the close control on the right...).
And what's even worse, the window doesn't go to the background anymore...
I figured if I set back the override_redirect property after I raised the window, the problem would be gone.
But...
The problem is now gone from all applications (such as gnome-terminal) - all except EyeOfGnome (Picture Viewer)...
Am I missing something, or is this an EyeOfGnome issue, or is it a general GTK issue ?
Here's the problem-causing part of the code:
XSetWindowAttributes xswa;
xswa.override_redirect = True;
XChangeWindowAttributes(display, wdThisWindow, CWOverrideRedirect, &xswa);
XRaiseWindow(display, wdThisWindow);
xswa.override_redirect = False;
XChangeWindowAttributes(display, wdThisWindow, CWOverrideRedirect, &xswa);
XSetInputFocus(display, wdThisWindow, RevertToNone, CurrentTime);

And this is the complete code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <X11/X.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xatom.h>

// Info: xwininfo
// I am compiling using
// gcc -o activate activate.c -L/usr/X11R6/lib -lX11

// ERROR HANDLER, GENERIC
static int ErrorHandler (Display *display, XErrorEvent *error)
{
   //printf ("\r\n error! \r\n");// gcc -o xwinspy lol.c -L/usr/X11R6/lib -lX11
   return 0;
}
// END ERROR HANDLER

// Recursively search through all windows on display
Window SearchWindow(char* szWindowToFind, int level, Display *display, Window rootWindow, int iMatchMode, int showErrors)
{
    Window parent;
    Window *children;
    unsigned int noOfChildren;
    int status;
    int i;
    Window wSearchedWindow = 0;

    char* win_name;
    if (XFetchName(display, rootWindow, &win_name))
    {
            //printf("WinName (Level %d): %s\n", level, win_name);
            if(iMatchMode == 0)
            {
                if( strstr(win_name, szWindowToFind) )
                {
                    return rootWindow;
                }
            }
            else if(iMatchMode == 1)
            {
                if( !strcmp(win_name, szWindowToFind) )
                {
                    return rootWindow;
                }
            }
            else if(iMatchMode == 2)
            {
                if( strcasestr(win_name, szWindowToFind) )
                {
                    return rootWindow;
                }
            }
            else if(iMatchMode == 3)
            {
                if( !strcasecmp(win_name, szWindowToFind) )
                {
                    return rootWindow;
                }
            }
            else
            {
                if( strstr(win_name, szWindowToFind) )
                {
                    return rootWindow;
                }
            }

    } // End if XFetchName

    status = XQueryTree (display, rootWindow, &rootWindow, &parent, &children, &noOfChildren);

    if (status == 0)
    {
        if (showErrors)
            printf ("ERROR - Could not query the window tree. Aborting.\r\n");
        return;
    }

    if (noOfChildren > 0)
    {
        for (i=0; i < noOfChildren; i++)
        {
            wSearchedWindow = SearchWindow(szWindowToFind, level+1, display, children[i], iMatchMode, showErrors);
            if(wSearchedWindow)
            {
                break;
            }
        }
    }

    XFree ((char*) children);

    return wSearchedWindow;
} // End Sub EnumerateWindows

Window FindWindow(char* szWindowToFind)
{
    Display *display = XOpenDisplay (NULL);
    int screen = DefaultScreen (display);

    XSetErrorHandler(ErrorHandler);

    Window rootWindow = RootWindow (display, screen);

    Window wSearchedWindow = SearchWindow(szWindowToFind, 0, display, rootWindow, 0, 0);

    char* win_name;
    if (XFetchName(display, wSearchedWindow, &win_name))
    {
        printf("Found: %s\n", win_name);
    }

    XCloseDisplay (display);
    return wSearchedWindow;
}

void ActivateWindow(char* szWindow)
{
    Window wdThisWindow = FindWindow(szWindow);

    Display *display = XOpenDisplay (NULL);

    char* win_name;
    if (XFetchName(display, wdThisWindow, &win_name))
    {
        printf("Activating: %s\n", win_name);
    }

    XSetErrorHandler(ErrorHandler);

    XSetWindowAttributes xswa;
    xswa.override_redirect = True;
    XChangeWindowAttributes(display, wdThisWindow, CWOverrideRedirect, &xswa);
    XRaiseWindow(display, wdThisWindow);
    xswa.override_redirect = False;
    XChangeWindowAttributes(display, wdThisWindow, CWOverrideRedirect, &xswa);
    XSetInputFocus(display, wdThisWindow, RevertToNone, CurrentTime);

    XCloseDisplay (display);
}

// ENUMARATE THROUGH WINDOWS AND DISPLAY THEIR TITLES
void EnumerateWindows(int level, Display *display, Window rootWindow, int showErrors)
{
    Window parent;
    Window *children;
    unsigned int noOfChildren;
    int status;
    int i;

    char* win_name;
    if (XFetchName(display, rootWindow, &win_name))
    {
            printf("Window-Name (Level %d): %s\n", level, win_name);
    }

    status = XQueryTree (display, rootWindow, &rootWindow, &parent, &children, &noOfChildren);

    if (status == 0)
    {
        if (showErrors)
            printf ("ERROR - Could not query the window tree. Aborting.\r\n");
        return;
    }

    if (noOfChildren > 0)
    {
        for (i=0; i < noOfChildren; i++)
        {
            EnumerateWindows(level+1, display, children[i], showErrors);
        }
    }

    XFree ((char*) children);
} // End Sub EnumerateWindows

void ListAllWindowsOnScreen()
{
    Display *display = XOpenDisplay (NULL);
    int screen = DefaultScreen (display);

    XSetErrorHandler(ErrorHandler);

    Window rootWindow = RootWindow (display, screen);

    EnumerateWindows(0, display, rootWindow, 0);
    XCloseDisplay (display);
}

int main(int argc, char *argv[])
{
    ListAllWindowsOnScreen();
    //ActivateWindow("000727");
    return EXIT_SUCCESS;
}

A: What you have to do, as ninjalj mentions, is use the protocols in the EWMH specification rather than making these raw X protocol requests. What you're doing here will confuse the heck out of both GTK+ and the window manager.
Specifically, what you want to do here is send a _NET_ACTIVE_WINDOW client message, with the
source indication (http://standards.freedesktop.org/wm-spec/wm-spec-1.4.html#sourceindication) probably set to say you're a pager.
Incidentally there's a library called libwnck (which I wrote originally but other people now maintain) which will do all this for you. Even if you don't use it, you can look at its source code to learn how to do stuff.

A: OverrideRedirect is for windows that bypass the window manager. The protocol for requesting stacking order changes is described in the ICCCM, section 4.1.5. The EWMH spec includes some extensions to this protocol, like layered stacking order and window activation (giving focus and possibly raising the window).


text:
Q: A total of $60$ (indistinguishable) iPads are to be distributed to $7$ elementary school classrooms. How many ways are there to do this if
A total of $60$ (indistinguishable) iPads are to be distributed to $7$ elementary school classrooms. How many ways are there to do this if

(a) There are no restrictions?

(b) Four of the classrooms receive iPads but three do not.

If the iPads were distinguishable then I could say that for (a) the answer would be $ = 60 \cdot 59 \cdot ... \cdot 54$ but I'm really losing it when it comes to indistinguishable objects.
I am  completely lost solving this. Can anyone help me understand the problem in a easier way so that I can solve it?
P.S. : I don't need full solution, just some help understanding it, hints at max so that I can solve it on my own.

A: $\mathbf{\text{Note 2}}=$ I am sorry, i did not see that you do not want the answers , so i have erased them now , if you find the solution , you can write them to comment section , and i can check them for you.
a-) It is said that the ipads are identical and the classrooms are distinct , so by using stars and bars there are ... ways , because there is not anymore restriction.
Lets come to the logic behind this method assume that the ipads are represented by "*" and $|$ represents the classrooms.If there were $5$ identical ipads and $3$ different classrooms then ,one of the distribution will be "$**|*|**$" ,by using combinantion with repetition ,we find the all arrangements of stars and bars formula ,$C(m+n-1 ,n)$ where m is the number of distinct boxes (in this question it represents classrooms , to satisfy the number bars ,we subtract $1$ from $m$)  and $n$ is the number of stars, you can also think their arrangements as permutation with repetition , so it give use all arrangements.In that example , we applied it for $60$ stars and $6$ bars , we used $6$ bars because it gives us $7$ places to represent $7$ classrooms.
b-) Select $4$ classroom that take ipads by $C(7,4)$ and again stars and bars ... , then $$C(7,4) \times ..$$
For more information as to star and bars , look at : https://en.wikipedia.org/wiki/Stars_and_bars_(combinatorics)
$\mathbf{\text{Note}}=$ If the ipads were distinct then , it would $\mathbf{\color{red}{\text{not}}}$ be equal to $60 \times 59 \times 58 ... 54$ as you said (if there is not restriction) , in that cases , you had better use exponential generating functions.


text:
Q: How are XCode Storyboards compiled? I'm learning iOS development and I was wondering how Storyboards actually work when the app is running.
While the editable .storyboard is just an xml file, the compiled .storyboardc file in the application bundle seems to be a package containing many .nib files.
How do these nib files work at runtime? What are they exactly? How is data encoded and extracted?


text:
Q: Centos 7 server performance problems. High load I have a Centos 7 VPS at HostGator that has been very slow lately. HostGator have not been overly helpful in diagnosing the problem, insisting that everything is ok.
The server is a 4 core VPS with 8GB of RAM.
I figured out my cPanel backups are at least partially to blame, but I'm certain something else is amiss. I found they were basically running all day, because they were constantly pausing while server load was high (which is a good thing I guess). But this was compounding the issue further due to the backups consequently running all day long, further loading the server.
The sites on the server are loading slower than normal, and it seems intermittent, sometimes they load quickly, others there is a noticable (~3 second) delay before the pages load.
I host a few sites on the server (3) and although they get a bit of traffic we're not talking anything over 1200 visits a day between all three sites.
Currently my load averages are sitting at 4.33 3.59 3.38 (no backups running):
results of top command sorted by CPU
I'm kind of at a loss from here. I've spent hours looking at logs etc, trying to figure out what exactly is going on with no luck. I'm not getting DDOSed or anything like that (from what I can tell from my HTTP logs.
Can anyone suggest any steps I might take next to determine what is going on?
Thanks for any help you can provide.

A: For a server with 4 CPUs a load avg at around 4 is considered harmless, as this means at any time there are about 4 tasks being processed, which with 4 CPUs means each task is being actually processed.
I would suggest you run a benchmark against your sites, and figure out where the loading time is actually spent, in many cases this could be things like database connects that take time to establish, or external resources that prevent the site from being rendered.
Looking at your screenshot I see a four practically bored CPUs, loads of RAM to spare, which is mostly used for the disk cache. You didn't include the processes in the list (so the sorting is irrelevant), which also doesn't provide any pointers to what is at fault.
Lastly it could still be, that your provider runs older hardware or is overbooking their hypervisor machines to stay competitive.


text:
Q: ES6 groupBy, partition, sort list of objects I am trying to figure out an elegant way in ES6 to sort an array of objects based on specified values. Here's the scenario:
const list = [
{
"name": "john",
"lastName": "smith"
}, {
"name": "tony",
"lastName": "smith"
}, {
"name": "tony",
"lastName": "grey"
}, {
"name": "mary",
"lastName": "smith"
}, {
"name": "john",
"lastName": "x"
}, {
"name": "tom",
"lastName": "y"
}
, {
"name": "mary",
"lastName": "x"
}
]

let orderList = [{"name":["john","mary"]}, {"lastName":["x"]}];

So, basically sort the result by the names(John, Mary) and then sort that result by lastName(x), but the name sorting still takes precedence.
The result should look like this:
[
  {
   "name": "john",
   "lastName": "x"
  }, {
   "name": "john",
   "lastName": "smith"
  }, {
    "name": "mary",
   "lastName": "x"
  }, {
   "name": "mary",
   "lastName": "smith"
  }, {
   "name": "tony",
   "lastName": "smith"
   }, {
    "name": "tony",
    "lastName": "grey"
   }, {
    "name": "tom",
    "lastName": "y"
   }
 ]

I have already tried doing something with group by, but it's a manual process for each name and last name.
_.groupBy(list , {"name": "john"});
I also tried experimenting with array reduce, but can't seem to find a good dynamic solution.
const sortArr = ['john', 'mary'];
const sortedList= list.reduce((result, element) => {
   let index = sortArr.findIndex(x => x === element.name);
   result[index !== -1
      ? index
      : result.length - 1].push(element);
     return result;
       },[  [], [], [] ]);

Any help is appreciated. Thanks

A: You could use Array#sort and take an iterative approach for sorting first by name and then by lastName.
This proposal works with a check if a property is in an array and sorts these value to top by taking the delta of the indices. This is repeated until the delta is not zero or the array of order has ended.
For getting the delta, an Array#indexOf search is made and if -1, the value for not found item, is replaced with Infinity, because this item has to be sorted to the end of the array. The items with a found index are sorted according to the index.
For a bit faster sorting, objects with a single key/value pair are converted to an array with key and value.

var list = [{ name: "john", lastName: "smith" }, { name: "tony", lastName: "smith" }, { name: "tony", lastName: "grey" }, { name: "mary", lastName: "smith" }, { name: "john", lastName: "x" }, { name: "tom", lastName: "y" }, { name: "mary", lastName: "x" }],
    orderList = [{ name: ["john", "mary"] }, { lastName: ["x"] }],
    order = orderList.map(o => (k => [k, o[k]])(Object.keys(o)[0]));

list.sort((a, b) => {
    var d;
    order.some(([k, v]) =>
        d = (v.indexOf(a[k]) + 1 || Infinity) - (v.indexOf(b[k]) + 1 || Infinity)
    );
    return d;
});

console.log(list);
.as-console-wrapper { max-height: 100% !important; top: 0; }


text:
Q: Azure - Shared Access Signature with Social Media sharing I am in a situation where I have few terabytes of data on azure blobs. I have recently added SAS (shared access signature) functionality while returning the direct blob urls back to client and added an expiry date of 2 minutes for all the images coming out. So, now the resource is guaranteed the read access for 2 minutes and expires after it.
All good up to now. I also have social media buttons to share my content to facebook, google+ or twitter etc. When a user shares the content to facebook lets say, the thumbnail remains with the link for specified time but expires after that time giving a bad user experience.
The example of URL generated is
 https://storageaccount.blob.core.windows.net/images/2016-May-23-03-28-56_14.jpg?sv=2015-07-08&sr=c&sig=LENHRuvX1Q1d8r2DCJTdMp6fB8mv82DJsMAN8ZAM3C4%3D&se=2016-06-14T22%3A55%3A37Z&sp=r

I want to ask if there is any way out to avoid this situation? I don't have a clue right now.


text:
Q: Do I need to "keep the electrons moving occasionally" in my laptop battery? I read this:
http://www.apple.com/shop/question/answers/product/MC556LL/B/will-it-hurt-my-macbook-pro-if-i-leave-the-power-supply-plugged-in-to-the-wall-socket-and-in-to-my-2011-macbook-pro-at-all-times-mostly/Q4X77ADTHJX977UJD
Apparently, to maintain my laptop battery, I need to keep the electrons moving occasionally. Are they suggesting that electrons decay? It sounds like nonsense to me.

A:
Are they suggesting

In this case they means some random contributor (Gary S from Jacksonville Beach), not official Apple advice.

that electrons decay?

No, the person who provided the answer was being euphemistic. Some battery chemistries require that the battery not be left in a fully discharged state, some that it not be left in a partially discharged state. Rechargeable batteries have a limited life and most require some care in how they are charged, discharged and stored.

keep the electrons moving occasionally

In reality,

*

*electrons are always moving

*usually, the charge carriers in batteries are ions, not electrons.

The problem is chemical effects, not charge carrier motion as such.


text:
Q: Stored Data in Keychain? I am saving my data in keychain.
if someone have root access of iPhone then is it possible to decrypt stored encrypted data in keychain?

A: The worse case is jailbroken (rooted), even then there are only two options: a brute force attack against the Keychain key or against the user's passcode (PIN).
The first attack is essentially not possible.
To attack the user's pin requests must be made to the Keychain and that is rate limited by the Keychain, there is no other way to brute force against the user's passcode. Apple has promised that as CPU speeds increase the minimum time between passcode attempts will not decrease. The user needs to choose an extended passcode.
Note: people who jailbreak do so with the tradeoff of security but content owners probably still do desire security.


text:
Q: Autohotkey: Hotkeys on Firefox not doing what they're supposed to I just want W to correspond to the Up Arrow key and S to correspond to the Down Arrow key, and work just like they do, and for A/D to move the focus to the last/next tab.
When i hold S, the page skips down erratically and then Firefox opens the "Save as" window multiple times.
When i hold W, the page skips up erratically and then multiple tabs are closed.
D does what it's supposed to, and A straight up doesn't work.
    #IfWinActive ahk_exe firefox.exe

    w::
    Send {Up}  ; Move page up.

    s::
    send {down} ; Move page down.

    a::
    send, ^{pgup} ; Go to tab on the left.

    d::
    send, ^{pgdn} ; Go to tab on the right.

    #IfWinActive

    Return

What exactly is happening? It should work normally but it isn't.

A: #IfWinActive ahk_exe firefox.exe

    w:: Send {Up}       ; Move page up.
    s:: send {down}     ; Move page down.

#IfWinActive    ; turn off context sensitivity

The above examples are known as single-line hotkeys because each consists of only one command.
To have more than one command executed by a hotkey, put the first line beneath the hotkey definition and make the last line a return. For example:
#n::
Run http://www.google.com
Run Notepad.exe
return

https://autohotkey.com/docs/Hotkeys.htm#Intro


text:
Q: add together the numbers I have a txt file with numbers between space in a few lines and I want to add together the numbers in each line and write the amount to the line's end. I split the file by newlines, it's okay, but I don't know how can I add together the numbers.
ArrayList<String> numbers = new ArrayList<>();
try {
    RandomAccessFile raf= new RandomAccessFile("numbers.txt","rw");
    while (raf.getFilePointer() < raf.length()) {
        String sor = raf.readLine();

        String newline[] = sor.split("\r\n");
        for (String item:newline) {
            numbers.add(item);
        }

    }
    // just test
    for(String item:numbers)
        System.out.println(item);

    raf.close();
}catch (IOException e) {
    System.err.println("An error was occured: "+ e);
}

A: You can split each line using space as delimeter. Then convert to number and sum them. Assuming single space between each numbers and only integer you can do like following. When the criteria changes you can change your code accordingly
for(String item:numbers){
        String n[] = item.split(" ");
        for(String number: n)
            sum+= Integer.parseInt(number);
        System.out.println(sum);
        sum = 0;
}

A: If I understand correctly everything here works, that means your for each loop prints lines with numbers separated by space? If yes then you need to:
numbers.stream().forEach(s ->
  System.out.println(Arrays.stream(s.split("\\s+")).mapToInt(Integer::parseInt).sum()));

Getting the stream on numbers list, then for every line we split it by whitespaces, parse each number to Integer and then sum those numbers.
Ofcourse instead of printing you can just add it to sum list, or append to your line immediately, your choice.


text:
Q: How to parse date-time with two or three milliseconds digits in java? Here is my method to parse String into LocalDateTime.
    public static String formatDate(final String date) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS");
        LocalDateTime formatDateTime = LocalDateTime.parse(date, formatter);
        return formatDateTime.atZone(ZoneId.of("UTC")).toOffsetDateTime().toString();
    }

but this only works for input String like
2017-11-21 18:11:14.05
but fails for 2017-11-21 18:11:14.057
with DateTimeParseException.
How can I define a formatter that works for both .SS and .SSS?

A: You would need to build a formatter with a specified fraction
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
  .appendPattern("yyyy-MM-dd HH:mm:ss")
  .appendFraction(ChronoField.MILLI_OF_SECOND, 2, 3, true) // min 2 max 3
  .toFormatter();

LocalDateTime formatDateTime = LocalDateTime.parse(date, formatter);

A: The answers by Basil Bourque and Sleiman Jneidi are excellent. I just wanted to point out that the answer by EMH333 has a point in it too: the following very simple modification of the code in the question solves your problem.
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.[SSS][SS]");

The square bracket in the format pattern string enclose optional parts, so this accepts 3 or 2 decimals in the fraction of seconds.

*

*Potential advantage over Basil Bourque's answer: gives better input validation, will object if there is only 1 or there are four decimals on the seconds (whether this is an advantage depends entirely on your situation).

*Advantage over Sleiman Jneidi's answer: You don't need the builder.

Possible downside: it accepts no decimals at all (as long as the decimal point is there).
As I said, the other solutions are very good too. Which one you prefer is mostly a matter of taste.

A: Using Java 8 you can use the DateTimeFormatterBuilder and a Pattern. See this answer for a little more information
public static String formatDate(final String date) {

  DateTimeFormatterBuilder dateTimeFormatterBuilder = new DateTimeFormatterBuilder()
        .append(DateTimeFormatter.ofPattern("" + "[yyyy-MM-dd HH:mm:ss.SSS]"
         + "[yyyy-MM-dd HH:mm:ss.SS]"));

  DateTimeFormatter formatter = dateTimeFormatterBuilder.toFormatter();

  try {
    LocalDateTime formatDateTime = LocalDateTime.parse(date, formatter);
    return formatDateTime.atZone(ZoneId.of("UTC")).toOffsetDateTime().toString();
  } catch (DateTimeParseException e) {
    return "";
  }
}

A: Ideally, you would account for a time that has 0 nanoseconds as well. If the time so happens to land perfectly on 2021-02-28T12:00:15.000Z, it may actually be serialised to 2021-02-28T12:00:15Z (at least, for something like java.time.OffsetDateTime it would be). It would therefore be more appropriate to use the following:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS][.SS][.S]");

... and if you require time zone, like I did, then it would look this:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS][.SS][.S]z");

A: tl;dr
No need to define a formatter at all.
LocalDateTime.parse(
    "2017-11-21 18:11:14.05".replace( " " , "T" )
)

ISO 8601
The Answer by Sleiman Jneidi is especially clever and high-tech, but there is a simpler way.
Adjust your input string to comply with ISO 8601 format, the format used by default in the java.time classes. So no need to specify a formatting pattern at all. The default formatter can handle any number of decimal digits between zero (whole seconds) and nine (nanoseconds) for the fractional second.
Your input is nearly compliant. Just replace the SPACE in the middle with aT.
String input = "2017-11-21 18:11:14.05".replace( " " , "T" );
LocalDateTime ldt = LocalDateTime.parse( input );

ldt.toString(): 2017-11-21T18:11:14.050

A: DateTimeFormatter allows specifying optional units using square brackets.
Demo:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
                "yyyy-MM-dd HH:mm:ss[.[SSSSSSSSS][SSSSSSSS][SSSSSSS][SSSSSS][SSSSS][SSSS][SSS][SS][S]]",
                Locale.ENGLISH);

        // Test
        Stream.of(
                "2015-05-04 12:34:56.123456789",
                "2015-05-04 12:34:56.123456",
                "2015-05-04 12:34:56.123",
                "2015-05-04 12:34:56"
        ).forEach(s -> System.out.println(LocalDateTime.parse(s, formatter)));
    }
}

Output:
2015-05-04T12:34:56.123456789
2015-05-04T12:34:56.123456
2015-05-04T12:34:56.123
2015-05-04T12:34:56

Learn more about the modern date-time API from Trail: Date Time.


text:
Q: Best way to return joined table in Sqlite.swift The following code works perfectly and I get exactly what I need, but I'm curious if there is a better way to return a joined table. If you look below, how much code I need to write for the joined "Address" table. I was hoping someone can confirm this is the best way to do this. Thanks!
static func findByEntityId(entityId: Int) throws -> [EntityAddress] {
    let query = table.filter(EntityId == entityId).join(AddressDB.table, on: AddressDB.table[Id] == table[AddressId])
    var array = [T]()
    let items = try db.prepare(query)
    for item in items {

        let address = Address(id: item[AddressDB.table[AddressDB.Id]], addressType: item[AddressDB.table[AddressDB.AddressType]], addressStatus: item[AddressDB.table[AddressDB.AddressStatus]], address1: item[AddressDB.table[AddressDB.Address1]], address2: item[AddressDB.table[AddressDB.Address2]], city: item[AddressDB.table[AddressDB.City]], state: item[AddressDB.table[AddressDB.State]], zip: item[AddressDB.table[AddressDB.Zip]], country: item[AddressDB.table[AddressDB.Country]], latitude: item[AddressDB.table[AddressDB.Latitude]], longitude: item[AddressDB.table[AddressDB.Longitude]], isDeleted: item[AddressDB.table[AddressDB.IsDeleted]], created: item[AddressDB.table[AddressDB.Created]], createdBy: item[AddressDB.table[AddressDB.CreatedBy]]!, modified: item[AddressDB.table[AddressDB.Modified]], modifiedBy: item[AddressDB.table[AddressDB.ModifiedBy]]!)

        array.append(EntityAddress(id: item[table[Id]], addressId: item[AddressId], entityId: item[EntityId], entityType: item[EntityType], address: address, isDeleted: item[table[IsDeleted]], created: item[table[Created]], createdBy: item[table[CreatedBy]] ?? 0, modified: item[table[Modified]], modifiedBy: item[table[ModifiedBy]] ?? 0))
    }
    return array
}


text:
Q: How to display a users name using PHP SESSIONS? I was wondering how would I display a logged in members users name on every page using PHP SESSIONS?

A: Put the members username into a session variable. I haven't personally touched any PHP in a while but you usually use the $_SESSION[] super global array.
echo $_SESSION['username'];

A: The user data has to be stored somewhere in the $_SESSION global. Whether or not the name is included, depends on your scripts.
I would do a var_dump($_SESSION) to see exactly what is stored in the session, then use that information to check if the name exists in the session, and if not, query the database for it and store it in the session.
if (!isset($_SESSION['User']['name']) {
   $q = mysql_query("SELECT name FROM users WHERE id = $_SESSION['User']['id']");
   $r = mysql_fetch_row($q);
   $_SESSION['User']['name'] = $r[0];
}

echo 'Hello, '.$_SESSION['User']['name']


text:
Q: Getting an attribute via another attribute in XSL I stink at XSLT, so I'm not sure how to approach this... I'm getting a feed from the EQ2 database. The XML looks like this:
<guilds limit="1" returned="1">
  <guild accounts="3" alignment="0" dateformed="1127855265" guildid="111" guildstatus="0" id="1111111111" last_update="1326986410" level="11" name="MyGuild" version="1" world="Permafrost" worldid="202">
    <ranks>
      <rank id="0" name="Leader"/>
      <rank id="1" name="Senior Officer"/>
      <rank id="2" name="Officer"/>
      <rank id="3" name="Senior Member"/>
      <rank id="4" name="Member"/>
      <rank id="5" name="Junior Member"/>
      <rank id="6" name="Initiate"/>
      <rank id="7" name="Recruit"/>
    </ranks>
    <members>
      <member dbid="123456" rank="0" name="Dude1"/>
      <member dbid="123457" rank="1" name="Dude2"/>
      <member dbid="123458" rank="2" name="Dude3"/>
      <member dbid="123459" rank="4" name="Dude4"/>
      <member dbid="123460" rank="4" name="Dude5"/>
      <member dbid="123461" rank="4" name="Dude6"/>
    </members>
    <events/>
  </guild>
</guilds>

I'm trying to add the ranks into a table. The XSL (version 1) snippet for it is as follows, but adding the name from the rank isn't working properly - I know this part is wrong:
<xsl:value-of select="rank/rank[@id=1]/@name"/>

So, can I get some help making it work and maybe an idea of how to shorten it?
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html" version="4.0" indent="yes"/>
<xsl:template match="/">

   Character
   Tradeskills

   Name
   Rank
   Class
   Level
   Artisan
   Level
   Secondary

  <xsl:for-each select="guilds/guild/members/member">
   <xsl:if test="@id > 1">

     <xsl:element name="a">
      <xsl:attribute name="href">
       <xsl:text>http://eq2players.station.sony.com/</xsl:text>
       <xsl:value-of select="concat(normalize-space(/guilds/guild/@world), '/')"/>
       <xsl:value-of select="concat(normalize-space(@name), '/')"/>
      </xsl:attribute>
      <xsl:attribute name="target">
       <xsl:text>_blank</xsl:text>
      </xsl:attribute>
      <xsl:value-of select="normalize-space(@name)"/>
     </xsl:element>

    <xsl:element name="td">
     <xsl:attribute name="class">
      <xsl:text>eq2Rank eq2rank-</xsl:text>
      <xsl:value-of select="translate(normalize-space(guild/@rank),' ','')"/>
     </xsl:attribute>

       <xsl:choose>
         <xsl:when test="member/@rank = 1"><xsl:value-of select="ranks/rank[@id=1]/@name"/></xsl:when>
         <xsl:when test="member/@rank = 2"><xsl:value-of select="ranks/rank[@id=2]/@name"/></xsl:when>
         <xsl:when test="member/@rank = 3"><xsl:value-of select="ranks/rank[@id=3]/@name"/></xsl:when>
         <xsl:when test="member/@rank = 4"><xsl:value-of select="ranks/rank[@id=4]/@name"/></xsl:when>
         <xsl:when test="member/@rank = 5"><xsl:value-of select="ranks/rank[@id=5]/@name"/></xsl:when>
         <xsl:when test="member/@rank = 6"><xsl:value-of select="ranks/rank[@id=6]/@name"/></xsl:when>
         <xsl:when test="member/@rank = 7"><xsl:value-of select="ranks/rank[@id=7]/@name"/></xsl:when>
        </xsl:choose>

    </xsl:element>

    <xsl:element name="td">
     <xsl:attribute name="class">
      <xsl:text>eq2Class eq2</xsl:text>
      <xsl:value-of select="translate(normalize-space(type/@class),' ','')"/>
     </xsl:attribute>
    <xsl:value-of select="type/@class"/>
    </xsl:element>

    <xsl:value-of select="type/@level"/>

    <xsl:element name="td">
     <xsl:attribute name="class">
      <xsl:text>eq2ArtisanClass eq2</xsl:text>
      <xsl:value-of select="translate(normalize-space(tradeskills/tradeskill/@class),' ','')"/>
     </xsl:attribute>
    <xsl:value-of select="tradeskills/tradeskill/@class"/>
    </xsl:element>

    <xsl:value-of select="tradeskills/tradeskill/@level"/>

    <xsl:element name="td">
     <xsl:attribute name="class">
      <xsl:text>eq2Secondary eq2</xsl:text>
      <xsl:value-of select="translate(normalize-space(secondarytradeskills/secondarytradeskill/@name),' ','')"/>
     </xsl:attribute>
    <xsl:value-of select="secondarytradeskills/secondarytradeskill/@name"/>
    </xsl:element>

   </xsl:if>
  </xsl:for-each>

</xsl:template>
</xsl:stylesheet>

A: Not sure if you can do something like this but it might be worth a shot. In the context of a single member
<xsl:value = "//ranks/rank[@id = ./@rank]/@name"/>

It uses X-Path to jump to the top and look for the ranks node, find the rank element whose ID attribute equals the rank attribute of the member, and grabs the name attribute
It's been a few years since I had to XSL like that, but should allow you to get rid of the XSL:choose block

A: I'm not really sure if I get the question.
Asume that you have the right rankid you probably want to use variable
<xsl:variable name="rank" select="translate(normalize-space(guild/@rank),' ','')"/>

<xsl:value-of select="ranks/rank[@id = $rank]/@name"/>

A: The following expression associates a member with its corresponding rank using current() (assuming that the context node is the member in question):
../../ranks/rank[@id=current()/@rank]/@name

Full example:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output omit-xml-declaration="yes" indent="yes"/>
    <xsl:strip-space elements="*"/>
    <xsl:template match="member">

                <xsl:value-of
                    select="../../ranks/rank[@id=current()/@rank]/@name"/>

    </xsl:template>
</xsl:stylesheet>

Output (based on the originally posted sample XML):

   Leader

   Senior Officer

   Officer

   Member

   Member

   Member


text:
Q: ASP.NET MVC two calls by button to same view action So I have two features on this 'tester' app I have where I am fiddling with ASP.NET for learning purposes.
I have come across an issue with the app. The app has 4 user input boxes, all of which are for mathematical purposes. The first pair take 2 values to multiply, while the second pair take two values to add together.
The issue here is that if I was to multiply values, then add, the multiplied output would disappear (also happens if you were to add then multiply, add would disappear) and I would like for this to not happen. Here's the code if anyone is able to address the issue:
public class HomeController : Controller
{
    public IActionResult Index(ExampleModel example, string Submit)
    {
        if (Submit == "Multiply")
        {
            double firstm = Convert.ToDouble(example.multFirst);
            double secondm = Convert.ToDouble(example.multSecond);
            example.multResult = firstm * secondm;
        }
        else if (Submit == "Add")
        {
            double firsta = Convert.ToDouble(example.addFirst);
            double seconda = Convert.ToDouble(example.addSecond);
            example.addResult = firsta + seconda;

        }

        return View(example);
    }

and the view:
@using (Html.BeginForm("Index", "Home"))
{

    @Html.EditorFor(m => m.multFirst)

    @Html.EditorFor(m => m.multSecond)

    @Html.DisplayFor(m => m.multResult)

    <input type="submit" name="Submit" value="Multiply" id="divide" />

    @Html.EditorFor(m => m.addFirst)

    @Html.EditorFor(m => m.addSecond)

    @Html.DisplayFor(m => m.addResult)

    <input type="submit" name="Submit" value="Add" id="divide" />
}

is there anyway to address this issue? any advice is much appreciated!

A: One solution would be to change DisplayFor to be EditorFor like this
@using (Html.BeginForm("Index", "Home"))
{

    @Html.EditorFor(m => m.multFirst)

    @Html.EditorFor(m => m.multSecond)

    @Html.EditorFor(m => m.multResult)

    <input type="submit" name="Submit" value="Multiply" id="divide" />

    @Html.EditorFor(m => m.addFirst)

    @Html.EditorFor(m => m.addSecond)

    @Html.EditorFor(m => m.addResult)

    <input type="submit" name="Submit" value="Add" id="divide" />
}

The actual problem is that when you render the page the second time, you use a model that does not have it's multResult initialized because the result of the previous computation wasn't stored anywhere except the form itself, and the form won't submit this value back since the respective field is a display field, not an editor one.

A: You could store your add result and multiple result on a session and retrieve them each time to example.addResult and example.multResult before return view(example)


text:
Q: Sql query match and against order by relevance using regex? Hello I'm trying to make a query in sql using match and against to sort by relevance. I don't want to use the like query or the REGEXP because my index is a FULLTEXT and it'll run faster...
This is my query:
SELECT test.*, MATCH(books) AGAINST ('+\'book') as Relevance
FROM Books.test
WHERE MATCH(books) AGAINST('+\'book' IN BOOLEAN MODE)
ORDER BY Relevance

And the result that I'm getting is:
id  books              relavance

2   book, folder, paper    '0.15835624933242798'

5  'book                  '0.15835624933242798'

The dataypes are:
id is an INT(11)
books LONGTEXT
And the indexes that I have:
key             type      unique   columns

idx_test_books  FULLTEXT  NO       books

I want to only retrieve the book with id 5: 'book

A: You can't use FULLTEXT for a search for 'book, the apostrophe will be ignored. The FULLTEXT index is builds with words.
MariaDB [test]> SELECT *, MATCH(books) AGAINST('"book,.,.,.,$%$:;§$%:;§$%§$:$%"') AS relevance FROM Books ORDER BY relevance;
+----+---------------------+----------------------------+
| id | books               | relevance                  |
+----+---------------------+----------------------------+
|  1 | book, folder, paper | 0.000000001885928302414186 |
|  2 | 'book               | 0.000000001885928302414186 |
+----+---------------------+----------------------------+
2 rows in set (0.00 sec)

MariaDB [test]> SELECT *, MATCH(books) AGAINST('"book,.,.,.,$%$:;§$%folder:;§$%§$:$%"') AS relevance FROM Books ORDER BY relevance;
+----+---------------------+--------------------+
| id | books               | relevance          |
+----+---------------------+--------------------+
|  2 | 'book               |                  0 |
|  1 | book, folder, paper | 0.0906190574169159 |
+----+---------------------+--------------------+
2 rows in set (0.00 sec)

MariaDB [test]> SELECT *, MATCH(books) AGAINST('"book folder"') AS relevance FROM Books ORDER BY relevance;
+----+---------------------+--------------------+
| id | books               | relevance          |
+----+---------------------+--------------------+
|  2 | 'book               |                  0 |
|  1 | book, folder, paper | 0.0906190574169159 |
+----+---------------------+--------------------+
2 rows in set (0.00 sec)


text:
Q: What is the typdef size_t actual code definition I am starting to learn c now ,after looking all over I cannot find the actual code definition for size_t in the header files.
I am trying to understand how this is defined because I believe it is system dependent.
Can someone direct/show the actual definition code.


text:
Q: embedded-kafka scalatest ClassNotFoundException: scala.collection.GenTraversableOnce New to Scala, I'm on step one of implementing a ScalaTest with https://github.com/embeddedkafka/embedded-kafka according to the second example at the top of that README:
import net.manub.embeddedkafka.EmbeddedKafka
import org.scalatest.matchers.should.Matchers
import org.scalatest.wordspec.AnyWordSpecLike

class MinimalTest extends AnyWordSpecLike with Matchers {

  "runs with embedded kafka" should {

    "work" in {
      EmbeddedKafka.start()

      1 + 1 shouldBe 2
      // ... code goes here

      EmbeddedKafka.stop()
    }
  }
}

Running this test, the failure is at a lower level than I am familiar with:
MinimalTest:
runs with embedded kafka
*** RUN ABORTED ***
  java.lang.NoClassDefFoundError: scala/collection/GenTraversableOnce
  at com.myorganization.api.MinimalTest.$anonfun$new$2(MinimalTest.scala:13)
  at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.scala:18)
  at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)
  at org.scalatest.OutcomeOf.outcomeOf$(OutcomeOf.scala:83)
  at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
  at org.scalatest.Transformer.apply(Transformer.scala:22)
  at org.scalatest.Transformer.apply(Transformer.scala:20)
  at org.scalatest.wordspec.AnyWordSpecLike$$anon$3.apply(AnyWordSpecLike.scala:1076)
  at org.scalatest.TestSuite.withFixture(TestSuite.scala:196)
  at org.scalatest.TestSuite.withFixture$(TestSuite.scala:195)
  ...
  Cause: java.lang.ClassNotFoundException: scala.collection.GenTraversableOnce
  at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
  at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
  at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
  at com.myorganization.api.MinimalTest.$anonfun$new$2(MinimalTest.scala:13)
  at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.scala:18)
  at org.scalatest.OutcomeOf.outcomeOf(OutcomeOf.scala:85)
  at org.scalatest.OutcomeOf.outcomeOf$(OutcomeOf.scala:83)
  at org.scalatest.OutcomeOf$.outcomeOf(OutcomeOf.scala:104)
  at org.scalatest.Transformer.apply(Transformer.scala:22)
  at org.scalatest.Transformer.apply(Transformer.scala:20)
  ...

I suspect a mismatch of dependency versions, but can't spot it. Here's my relevant build.gradle contents:
plugins {
    id 'java'
    id 'scala'
}

task spec(dependsOn: ['testClasses'], type: JavaExec) {
    main = 'org.scalatest.tools.Runner'
    args = ['-R', 'build/classes/scala/test', '-o']
    classpath = sourceSets.test.runtimeClasspath
}

dependencies {
    compile 'io.confluent:kafka-streams-avro-serde:5.4.0'
    compile 'io.github.embeddedkafka:embedded-kafka-streams_2.12:2.4.0'
    compile 'io.github.embeddedkafka:embedded-kafka_2.12:2.4.0'
    compile 'org.apache.avro:avro:1.9.1'
    compile 'org.apache.kafka:kafka-clients:2.4.0'
    compile 'org.apache.kafka:kafka-streams:2.4.0'
    compile 'org.apache.kafka:kafka_2.13:2.4.0'
    compile 'org.scala-lang:scala-reflect:2.12.6'
    testCompile 'io.github.embeddedkafka:embedded-kafka-schema-registry_2.12:5.4.0' // match schema registry version
    testCompile 'io.github.embeddedkafka:embedded-kafka-streams_2.13:2.4.0' // match kafka streams version
    testCompile 'io.github.embeddedkafka:embedded-kafka_2.13:2.4.0' // match kafka version
    testCompile 'org.scala-lang:scala-library:2.13.2'
    testCompile 'org.scalatest:scalatest_2.13:3.1.2'
    testImplementation 'junit:junit:4.11'
    testRuntime 'org.pegdown:pegdown:1.4.2'
}

A: Gradle can indeed be a bit funny with transitive dependencies for Scala - in the sense that it will not automatically calculate a coherent set of versions.
The "missing" class scala/collection/GenTraversableOnce is part of the scala-library and is available in 2.12.x
So you should be able to fix this by:

*

*a. Explicitly declaring the scala library version on your runtime classpath:
implementation group: 'org.scala-lang', name: 'scala-library', version: '2.12.6'

*b. Checking all your other dependencies for 2.13 versions of the libraries (as @ShankarShastri suggested).    Seems like embedded-kafka does have a 2.12 compatible build here: https://mvnrepository.com/artifact/io.github.embeddedkafka/embedded-kafka_2.12/2.5.0
Once you have done this, assuming your IDE is set up to sync with your build.gradle file, you should be able to look at the dependencies (declared and transitive) that gradle has calculated.    If you still have problems, go through these manually and see if the org.scala-lang:scala-library library is missing or declared twice.    If you have multiple declarations you can look at each library's dependencies in mvncentral.com .
N.B. the reason for step (a) is that you have scala artefacts in your 'compile' dependencies, so I assume that all your code (not just your test code) is using scala.

A: I can confirm the fix is validation dependencies. Or more technically check the test dependencies.
For me I upgraded my SpringBoot version which changed my spring-kafka-test version which intern included kafka 2.13.x which finally included scala libs.
I used mvn dependency:tree on my project's build file and searched for '2.12' to find where the old dependency was coming from. Example dependency tree (unrelated dependencies removed). Notice org.apache.kafka:kafka_2.11:jar:0.10.0.0 included as part of my.company.riptide.api:ness-logger:jar:1.0.0 but org.springframework.kafka:spring-kafka-test:jar:2.7.9 includes a newer version org.apache.kafka:kafka_2.13:jar:2.7.2
My solution was to exclude kafaka_2.11 from my ness-logger dependency like this:
<dependency>
  <groupId>my.company.riptide.api</groupId>
  <artifactId>ness-logger</artifactId>
  <version>1.0.0</version>
  <exclusions>
    <exclusion>
      <groupId>org.apache.kafka</groupId>
      <artifactId>kafka_2.11</artifactId>
    </exclusion>
  </exclusions>
</dependency>

Truncated output of mvn dependency:tree:
[INFO] +- my.company.riptide.api:ness-logger:jar:1.0.0:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-validation:jar:2.5.7:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-el:jar:9.0.55:compile
[INFO] |  |  \- org.hibernate.validator:hibernate-validator:jar:6.2.0.Final:compile
[INFO] |  |     \- jakarta.validation:jakarta.validation-api:jar:2.0.2:compile
[INFO] |  +- commons-io:commons-io:jar:2.7:compile
[INFO] |  +- my.company.eis:ness-logging-package:jar:4.0.1:compile
[INFO] |  |  +- org.apache.avro:avro:jar:1.8.2:compile
[INFO] |  |  |  +- org.codehaus.jackson:jackson-core-asl:jar:1.9.13:compile
[INFO] |  |  |  +- org.codehaus.jackson:jackson-mapper-asl:jar:1.9.13:compile
[INFO] |  |  |  +- com.thoughtworks.paranamer:paranamer:jar:2.7:compile
[INFO] |  |  |  \- org.tukaani:xz:jar:1.5:compile
[INFO] |  |  +- org.apache.avro:avro-compiler:jar:1.8.2:compile
[INFO] |  |  |  +- org.apache.velocity:velocity:jar:1.7:compile
[INFO] |  |  |  \- joda-time:joda-time:jar:2.7:compile
[INFO] |  |  +- org.apache.kafka:kafka_2.11:jar:0.10.0.0:compile
[INFO] |  |  |  +- com.101tec:zkclient:jar:0.8:compile
[INFO] |  |  |  \- org.scala-lang.modules:scala-parser-combinators_2.11:jar:1.0.4:compile
[INFO] |  |  \- com.netflix.hystrix:hystrix-core:jar:1.5.18:compile
[INFO] |  |     +- com.netflix.archaius:archaius-core:jar:0.4.1:compile
[INFO] |  |     \- io.reactivex:rxjava:jar:1.3.8:compile
[INFO] |  +- org.springframework.boot:spring-boot-loader-tools:jar:2.5.7:compile
[INFO] |  |  \- org.apache.commons:commons-compress:jar:1.21:compile
[INFO] |  \- my.company.riptide.springboot:graceful-shutdown:jar:1.0.2:compile

[INFO] +- org.springframework.kafka:spring-kafka:jar:2.7.9:compile
[INFO] |  +- org.springframework:spring-messaging:jar:5.3.13:compile
[INFO] |  +- org.springframework:spring-tx:jar:5.3.13:compile
[INFO] |  +- org.springframework.retry:spring-retry:jar:1.3.1:compile
[INFO] |  |  \- javax.annotation:javax.annotation-api:jar:1.3.2:compile
[INFO] |  +- org.apache.kafka:kafka-clients:jar:2.7.2:compile
[INFO] |  |  +- com.github.luben:zstd-jni:jar:1.4.5-6:compile
[INFO] |  |  +- org.lz4:lz4-java:jar:1.7.1:compile
[INFO] |  |  \- org.xerial.snappy:snappy-java:jar:1.1.7.7:compile
[INFO] |  \- com.google.code.findbugs:jsr305:jar:3.0.2:compile
[INFO] +- junit:junit:jar:4.13.2:test
[INFO] |  \- org.hamcrest:hamcrest-core:jar:2.2:compile
[INFO] +- io.cucumber:cucumber-spring:jar:7.0.0:test
[INFO] |  \- org.apiguardian:apiguardian-api:jar:1.1.2:test
[INFO] +- io.cucumber:cucumber-core:jar:7.0.0:test
[INFO] |  +- io.cucumber:cucumber-gherkin:jar:7.0.0:test
[INFO] |  +- io.cucumber:cucumber-gherkin-messages:jar:7.0.0:test
[INFO] |  +- io.cucumber:messages:jar:17.1.1:test
[INFO] |  +- io.cucumber:tag-expressions:jar:4.0.2:test
[INFO] |  +- io.cucumber:cucumber-expressions:jar:13.0.1:test
[INFO] |  +- io.cucumber:datatable:jar:7.0.0:test
[INFO] |  +- io.cucumber:cucumber-plugin:jar:7.0.0:test
[INFO] |  +- io.cucumber:docstring:jar:7.0.0:test
[INFO] |  +- io.cucumber:html-formatter:jar:17.0.0:test
[INFO] |  \- io.cucumber:create-meta:jar:6.0.1:test

[INFO] +- org.springframework.kafka:spring-kafka-test:jar:2.7.9:test
[INFO] |  +- org.apache.kafka:kafka-clients:jar:test:2.7.2:test
[INFO] |  +- org.apache.kafka:kafka-streams:jar:2.7.2:test
[INFO] |  |  +- org.apache.kafka:connect-json:jar:2.7.2:test
[INFO] |  |  |  \- org.apache.kafka:connect-api:jar:2.7.2:test
[INFO] |  |  \- org.rocksdb:rocksdbjni:jar:5.18.4:test
[INFO] |  +- org.apache.kafka:kafka-streams-test-utils:jar:2.7.2:test
[INFO] |  +- org.apache.kafka:kafka_2.13:jar:2.7.2:test
[INFO] |  |  +- org.apache.kafka:kafka-raft:jar:2.7.2:test
[INFO] |  |  +- com.fasterxml.jackson.module:jackson-module-scala_2.13:jar:2.12.5:test
[INFO] |  |  +- com.fasterxml.jackson.dataformat:jackson-dataformat-csv:jar:2.12.5:test
[INFO] |  |  +- net.sf.jopt-simple:jopt-simple:jar:5.0.4:compile
[INFO] |  |  +- com.yammer.metrics:metrics-core:jar:2.2.0:compile
[INFO] |  |  +- org.scala-lang.modules:scala-collection-compat_2.13:jar:2.2.0:test
[INFO] |  |  +- org.scala-lang.modules:scala-java8-compat_2.13:jar:0.9.1:test
[INFO] |  |  +- org.scala-lang:scala-library:jar:2.13.3:compile
[INFO] |  |  +- org.scala-lang:scala-reflect:jar:2.13.3:test
[INFO] |  |  +- com.typesafe.scala-logging:scala-logging_2.13:jar:3.9.2:test
[INFO] |  |  +- org.apache.zookeeper:zookeeper:jar:3.5.9:compile
[INFO] |  |  |  +- org.apache.zookeeper:zookeeper-jute:jar:3.5.9:compile
[INFO] |  |  |  +- org.apache.yetus:audience-annotations:jar:0.5.0:compile
[INFO] |  |  |  \- io.netty:netty-transport-native-epoll:jar:4.1.70.Final:compile
[INFO] |  |  \- commons-cli:commons-cli:jar:1.4:test
[INFO] |  +- org.apache.kafka:kafka_2.13:jar:test:2.7.2:test
[INFO] |  \- org.junit.jupiter:junit-jupiter-api:jar:5.7.2:test
[INFO] |     +- org.opentest4j:opentest4j:jar:1.2.0:test
[INFO] |     \- org.junit.platform:junit-platform-commons:jar:1.7.2:test


text:
Q: How do I search for a folder in a folder in c#? I want to check if a specific folder exists in a folder in c#.
Currently I'm using the following code.
        string currentPath = Directory.GetCurrentDirectory();

        foreach (string subDir in Directory.GetDirectories(currentPath))
        {
            if (subDir == currentPath + @"\Database") // if "Database" folder exists
            {
                dbinRoot = true;
            }
        }
        if (dbinRoot == true)
        {
            currentPath = currentPath + @"\Database\SMAStaff.accdb";
        }
        else
        {
            for (int i = 0; i < 2; i++)
            {
                currentPath = currentPath.Remove(currentPath.LastIndexOf("\\"));
            }
            currentPath = currentPath + "\\Database\\SMAStaff.accdb";
        }

I wish to know if there is a better way of doing this ???

A: you can use:
Directory.Exists(currentPath + @"\Database")

A: It also more reliably to use Path.Combine method to concatenate parts of path

if (Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), @"Database"))){}

A: You are probably directly looking for
currentPath = Directory.GetCurrentDirectory();
bool fileExists = File.Exists(Path.Combine(currentPath, "Database\\SMAStaff.accdb")))

And the for cycle may contain for better readability
currentPath = Directory.GetParent(currentPath).FullName;


text:
Q: not showing custom type meta box Here is my custom type post code. I want to add the meta box in there...
function events_cust(){
      $label = array(
            'name' => _x('Events'),
            'singular_name' => _x('events'),
            'menu_name'  => __('Events'),
            'add_new' => __('Add Event'),
            'add_new_item' => __ ('Add New Event'),
            'all_item' => __('All Event'),
            'edit_item' => __('Edit Event'),
            'new_item' => __('New Event'),
            'view_item' => __('View Event'),
            'update_item' => __('update Event'),
            'search_item' => __('Search Event')
            );
            $attr = array(
            'label' => __('Events'),
            'description' => __('Event'),
            'labels' => $label,
            'supports'  => array('title','editor','thumbnail'),
            'taxonomies' => array('genres'),
            'hiecrarhical' => false,
            'public' => true,
            'show_ui' => true,
            'show_in_menu' => true,
            'show_in_adim_bar' => true,
            'menu_position'       => 5,
   'can_export'          => true,
   'has_archive'         => true,
   'exclude_from_search' => false,
   'publicly_queryable'  => true,
   'capability_type'     => 'post',
            );
            register_post_type('events-lists',$attr);
      }
      add_action( 'init', 'events_cust', 0 );

   add_action('add_meta_boxes','create_events_metaboxes');
   function create_events_metaboxes(){
      add_meta_box('events-meta-box','Events Details','show_events_metaboxes','events-lists','normal','hight');
   }

   function show_events_metaboxes(){
    echo 'Hello Meta box';
   }

What's wrong with us.

A: Try below code.
add_action('add_meta_boxes','create_events_metaboxes');
function create_events_metaboxes() {
  add_meta_box('events-meta-box','Events Details','show_events_metaboxes','events-lists');
}

function show_events_metaboxes($post){ echo 'Hello Meta box'; }

Hope this will helps you.
Refer from add_meta_box

A: ACF may help in your farther run. Try it if you need meta boxes more organised.

A: Try this:
    function event_custom_meta_boxes( $post_type, $post ) {
        add_meta_box(
            'my-meta-box',
            __( 'My Meta Box' ),
            'render_my_meta_box',
            'post', //post type, event, product etc.
            'normal',
            'default'
        );
    }
    add_action( 'add_meta_boxes', 'event_custom_meta_boxes', 10, 2 );

  function render_my_meta_box(){
    echo "Hello World!";
  }

for more reference: https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes


text:
Q: Button for adding a dropdown menu to form_for I am stuck on a problem which I just can't get a good solution to, and hope someone with more experience than me can help.
I'm creating a rails app where you can register matches in a game, and you pick which players were participants in that match by selecting from drop down lists. I am doing this by using form_for with nested fields_for.
<%= form_for [@group, @match] do |f| %>

      Placement
      Player

    <%= create_player_in_match_row(f, 1, @group.active_players) %>
    <%= create_player_in_match_row(f, 2, @group.active_players) %>

  Add Player
  <%= f.submit("Create") %>
<% end %>

The create_player_in_match_row method is for creating a row with a dropdown. The code is in a helper class and it looks like this:
def create_player_in_match_row(form, nr, players)
  form.fields_for :player_in_matches, @match.player_in_matches.build do |pim|
    "

      #{ pim.hidden_field "placement", value: nr }
      #{ nr }.
      #{ player_select_tag(pim, players) }
      #{ tie_check_box(pim) }

".html_safe
  end
end

def player_select_tag(pim, players)
  players = players.order "name ASC"
  pim.select :player_id,
             players.map { |p| [p.name, p.id] },
             { include_blank: false },
             { class: 'chosen-select' }
end

The problem:
As you can see in the form_for I've got a link "Add Player". I want this button to add a new row with a dropdown for choosing players.
As of now I am creating a new row in coffeescript with something like this:
$("#add_player_row").click ->
  select_row_original = document.getElementById('row_p1')
  new_select_row = select_row_original.cloneNode(true)
  new_select_row_placement = document.getElementsByClassName('player_row').length + 1

  # Change A LOT of ids and stuff

  $("#match_players").append(new_select_row)

But this feels hacky and has really unintuitive code. Can someone point me in the direction of a smarter solution? Is there some way I can reuse the helper class method for adding row?

A: As a reference, this RailsCast, #196 - Nested Model Form (revised) provides the most updated answer to your problem.
But you can see:

*

*196 - Nested Model Form Part 1 and

*197- Nested Model Form Part 2
Which can give you a (somewhat outdated) idea of better ways to handle your problem.
Now, to your code:

*

*As a first suggestion, it's probably better in this case to use ul's instead of table (and for layout purposes in general).

*Avoid using SQL queries in views or helpers, queries always belong in the models.
For instance, you can use a scope for players ordered by name in your Player model:
    class Player < ActiveRecord::Base
      scope :name_ordered, -> { order(:name) }
    end

*Then you can load an instance variable @players from your Controller, and use it in the view.

*Use HTML in Ruby code is difficult to read, and you may end up with escaping \", it's better to use content_tag. See this example. If you need to concatenate several tags inside, use concat.
An example (it may not be a 100% correct, but you'll get the idea):
player_select = pim.select @players, :id, {include_blank: false}, {class: 'chosen-select'})
   content_tag :tr, id: "row_p#{nr}" do
     concat(pim.hidden_field "placement", value: nr)
     concat(content_tag :td, "#{nr}")
     concat(content_tag :td, player_select)
     # ...
   end
You can see Rails Guides - Form Helpers for more information.
Hope this helps!


text:
Q: How to access Data from XML File in C# how can I access data coming from an XML File into variables?
<RESULTS>
    <ROW>
        <COLUMN NAME="OM_USER"><![CDATA[TEXT]]></COLUMN>
        <COLUMN NAME="LASTNAME"><![CDATA[TEXT]]></COLUMN>
        <COLUMN NAME="FIRSTNAME"><![CDATA[TEXT]]></COLUMN>
        <COLUMN NAME="PHONE"><![CDATA[TEXT]]></COLUMN>
    </ROW>
</RESULTS>

this is what i tried but the output is weired
XDocument xmlDocument = XDocument.Load(@"PATH");

var xElement = xmlDocument.Element();

if (xElement != null)
{
    foreach (var child in xElement.Elements())
    {
       Console.WriteLine(child.Name + ": " + child.Value);
    }
 }

My Output come like this:
ROW: TEXTEXTTEXTTEXT
ROW: TEXTEXTTEXTTEXT
ROW: TEXTEXTTEXTTEXT
ROW: TEXTEXTTEXTTEXT
Thanks for any help =)

A: The problem that you are facing is that you are a level too high in the xml tree. By stating
var xElement = xmlDocument.Elements();

You get all the elements from the top of the xdocument, which is the root named "RESULTS"
Your foreach is looping over all the child's of the "RESULTS" element which is only "ROW". If you the specify that you want to print the name of the child (ROW) and its value you get all the text that element "ROW" and all it's children have. If you use the debugger you will see this content.
By changing your code to something simular below you will get the correct outcome
const string msg = "<RESULTS><ROW><COLUMN NAME=\"OM_USER\"><![CDATA[TEXT]]></COLUMN><COLUMN NAME=\"LASTNAME\"><![CDATA[TEXT]]></COLUMN><COLUMN NAME=\"FIRSTNAME\"><![CDATA[TEXT]]></COLUMN><COLUMN NAME=\"PHONE\"><![CDATA[TEXT]]></COLUMN></ROW></RESULTS>";

XDocument xmlDocument = XDocument.Parse(msg);

//get the first element named ROW from the xdocument.
var xElement = xmlDocument.Descendants().First(x => x.Name == "ROW");

if (xElement != null)
{
   //Loop through the childs of ROW
   foreach (var child in xElement.Elements())
   {
      //Find the first attribute in the child element which is named NAME.
      var childAttrName = child.Attributes().First(x => x.Name == "NAME");
      //Print the value of the attribute called name and the value of the element.
      System.Console.WriteLine(childAttrName.Value + " : " + child.Value);
   }
}


text:
Q: How firebase charges for storage BANDWITH? Recently my firebase spark plan was disabled & I wanted to know how firebase charges for bandwith.
I see the limit is 1 GB per day but I don't know exactly how much they will be charging me after the limit. I tried searching on Firebase Blaze Plan Calculator but I couldn't found any specific section for just bandwidth charges.

A: There's a GB transferred slider in that pricing calculator, which is the charge for bandwidth used for downloads.

Firebase does not have its own pricing though, and this is really just a simplified view of Google Cloud Storage network pricing, so I recommend reading up on the Network cost in the pricing page of that.


text:
Q: How do I Login as a Contact's Portal User to Force.com Site that uses Customer Portal for authentication? On the Contact detail page there is a Work With Portal -> Login As Portal User button when the Customer Portal is enabled.  I have a Force.com Site that uses Customer Portal for authentication.  When an internal SF user clicks on that button link it takes them to the unbranded standard SF portal. I would like it to log them in to the skinned site.  How can that be done?  I didn't find any documentation on this, but maybe I just missed it.
I tried just copying and pasting in the url of the secure site after clicking the Login As Portal button link, but I guess a different cookie is used or something because it didn't recognize that I was logged in.
To be clear, it is this button on the Contact page. The desired functionality is that the internal user that has access to the Contact can log in to the Force.com Site that uses Customer Portal for the authentication.  I'm not asking how to use set up Force.com Sites + Customer Portal for a skinned log in.  It's the logging in as the Contact user to the skinned site that that I'm interested in.

Thanks.

A: I did this on our site.  I made a homepage component and assigned it to the customer portal home page.  It's just a link to /apex/thepageyouwanttostarton.
So the process is login-as, click the link, then you're on the page you wanted.
The catch here is that the internal logging-in-as user is the only one whoever sees this because the customers log in from the site, never hitting the actual portal home page.

A: There isn't a method to use the 'Login As' and view the portal through a Site. In order to view the portal through the Site, you will need to sign in just as the user does on the Site themselves with that user's username and password.
An alternative is to additionally skin the Customer Portal itself using HTML fragments for the Customer Portal Header and Footer elements.
Setup > Customize > Customer Portal > Settings > (Header, Footer)
Each of these fragments should be stored as Document records with the 'Externally Available Image' checkbox checked.
Your Header document would contain something like:
<html>
    <head>
        <link rel="stylesheet" type="text/css" href="/resource/yourstaticresource/yourstylesheet.css" />
    </head>
    <body>
        <div id="bodyContent">

Your Footer document would contain something like:
        </div>
    </body>
</html>

At that point the #bodyContent div will be wrapped around the native Customer Portal body and you'll have a customer portal with your defined look and feel when using the 'Login As' feature as well as the separately defined Site configuration.

A: I don't believe a standard user can login as one of your portal users. I'm thinking this would be a security problem since it's not as if some System Admin of a company logs in as another employee of that company. That is to be expected. But logging in as an outside portal user, presumably without them knowing it, would break the contract of trust, no?
But in order for internal users to experience a site with the skin intact, all you need to do is make sure the access rights of the users in question permit viewing the site. Then just create a tab that points to the home page of your site and users can click through to the skinned version. I use this technique to quickly view my code/UI changes during development. If needed, you can create a dummy contact/user (work with portal) that internal users can login as from the home page of your site.
On a related note, here's a method to use custom usernames and passwords to allow high volume portal users to login to your sites (assuming the custom login name is forced to be unique and the custom password matches the actual password):
private static String endPoint = 'https://cs4.salesforce.com/secur/login_portal.jsporgId=XXXXXORGIDXXXXXX&portalId=XXXXXXPORTALIDXXXXXX';
private static String orgId = userInfo.getOrganizationId();
private static String portalId = 'XXXXXXPORTALIDXXXXXXX';

public PageReference login()
{
   PageReference p = null;
   if(login != null && password != null )
   {
      List<User> users = [SELECT Id, Username, FederationIdentifier, IsPortalEnabled, IsActive, Contact.YourCustomLoginName__c, Contact.YourCustomPassword__c, ContactId
         FROM User
         WHERE Contact.YourCustomLoginName__c = :login
         AND Contact.YourCustomPassword__c = :password
         AND IsPortalEnabled = TRUE
         AND IsActive = TRUE
         LIMIT 1];
      if(users.size() == 1)
      {
         p = new PageReference(endPoint+'&un='+users[0].Username+'&pw='+password);
      }

   }

   return p;
}

Then you can use the following to make sure that when they change their custom password that their actual password changes along with it:
System.setPassword(user.Id, Contact.YourCustomPassword__c);


text:
Q: mysql error 1406 I have created a database & am trying to load data from a spreadsheet csv file. There is no data in it yet. When I run
LOAD DATA INFILE 'docs.csv' INTO list FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n' (vendor, title, project, description, shelf);

I get a message "ERROR 1406 (22001): Data too long for column 'vendor' at row 1". The vendor entry at row 1 is 6 characters long though. I created my table as follows:
CREATE TABLE list (
    autonumber  SERIAL,
    vendor      varchar(50),
    title       varchar(100),
    project     varchar(100),
    description     text,
    shelf       smallint UNSIGNED,
PRIMARY KEY(autonumber));

There are commas & carriage returns (Alt + Enter in the spreadsheet)in many entries in the description column; am I right in using \t for the FIELDS TERMINATED command & will the carriage returns cause trouble?

A: the value is too long for this column
try change from 50 to 100 as this
     CREATE TABLE list (
     autonumber  SERIAL,
     vendor      varchar(100),
     title       varchar(100),
     project     varchar(100),
     description     text,
     shelf       smallint UNSIGNED,
    PRIMARY KEY(autonumber));

A: I think having carriage return characters in you fields will cause trouble because your line separator is \n.  A carriage return in a field will be taken as the end of the record I believe.  If you can add quoted identifiers to your fields, that might help.
You would need to add this clause to your infile statement:
OPTIONALLY ENCLOSED BY '"'

A: Give the complete path of the infile and do your code as following.
LOAD DATA INFILE 'docs.csv' INTO TABLE list

 FIELDS TERMINATED BY ','

 ENCLOSED BY '"'

 LINES TERMINATED BY '\r\n' (vendor, title, project, description, shelf);

Give the path of the infile just like the following example..
load data local infile 'c:/xampp/htdocs/example.csv'

     into table mytbl fields terminated by ','

     enclosed by '"'

     lines terminated by '\r\n'

     ignore 1 lines (f_name,age,id);

Hope this will help you out.

A: maybe your csv file encoding is not same as mysql character set, this will also lead to "ERROR 1406 (22001): Data too long for column 'vendor' at row 1".
for example, if you mysql character set is GBK, while you csv file is encoded in UTF-8, then it will lead to the same error when load.
just change you file encoding to the same as mysql character set.


text:
Q: Can a Codable protocol be used for decoding without exposing the underlying type? I want to do something like this where the underlying concrete types are not used, and instead only a Codable protocol is used.
protocol MyProtocol: Codable {}

struct MyProtocolImpl: MyProtocol {}

struct Something: Codable {
    let x: MyProtocol
}

This does not compile with:

Type 'Something' does not conform to protocol 'Decodable'

I assume this is intentional by Swift, but I want to check whether I am missing something.


text:
Q: Django pass object to model of another form I have implemented a Python form/view/template that lets you configure different notifications for a product:
models.py
class PNotification(models.Model):
    add = models.BooleanField(default=False, help_text='Receive messages when an engagement is
    added')
    delete = models.BooleanField(default=False, help_text='Receive

class Product(models.Model):

forms.py
class PNotificationForm(forms.ModelForm):
    class Meta:
        model = PNotification
        exclude = ['']

class ProductForm(forms.ModelForm):

The PNotification has an own view and template:

 Edit Notifications for {{ product.name }}

    <form class="form-horizontal" method="post">{% csrf_token %}
        {% include "dojo/form_fields.html" with form=form %}

                <input class="btn btn-primary" type="submit" value="Submit"/>

    </form>

When I call the page (edit/product_id/notifications) to edit an products notifications, the h3 is set correct, so the product is passed to the form/template.
My problem is: I need to link PNotification with a product.
How can I pass product.id to my PNotificationForm so I can save it there? This field should be the primary key of PNotification.
Edit
Here is my view.py:
def edit_product_notifications(request, pid):
    prod = Product.objects.get(pk=pid)
    logger.info('Editing product')
    if request.method == 'POST':
        pnotification = PNotificationForm(request.POST, instance=prod)
        if pnotification.is_valid():
            pnotification.save()
            logger.info('saved')

    else:
        pnotification = PNotificationForm()
        if pnotification.is_valid():
            pnotification.save()
            logger.info('saved')

logger.info(PNotification.objects.get(id=1).msteams)
logger.info('returning')
return render(request,
              'dojo/edit_product_notifications.html',
              {'form': pnotification,
               'product': prod
               }).

I am passing the product id and then getting it from objects.get().

A: In urls.py the path to that view needs to have <int:pk>. The path would look like this edit/<int:pn_pk>/notifications
In your view you need to get the kwargs which is the argument passed by the url.
In a function based view:
def your_view_name(request, pk):
    # use pk how you want.
    PN = PNotification.objects.get(pk=pn_pk)
    return render(...)


text:
Q: Fixed height of the_content() I have page with news. I'm displaying them as a shortened text (300 chars limit), I'm removing any images using preg_replace() and everything looks fine, until someone uses line breaks in his post. Things gets messy then and my height is way to high sometimes. Ofc I'm using overflow: hidden; but its not as good as I would like it to be. Is there a way to trim out those spaces, remove <strong> if someone uses it etc.? So my news page looks always as awesome as it should?
Cheers

A: If you run a wp_kses() on the_excerpt() (through a filter) you can whitelist specific HTML tags and such. In your case, the code would probably look something like this:
if( is_page( 'your_page' ) ) {
    add_filter( 'the_excerpt', 'wpse44363_filter_the_excerpt' );
}
function wpse44363_filter_the_excerpt( $excerpt ) {
    // this allows no html, you can allow only links or something of that nature
    $allowed_html = array();
    return wp_kses( $excerpt, $allowed_html );
}