text:
Q: Parsing a non regular text file in pandas I am trying to parse a text file that looks like this using pandas:
Some random text
more random text that may be of different length
JUNK 0 9 8
GOOD 0 1 1
GOOD 5 5 5
more random text interdispersed
GOOD 123 321 2
JUNK 55 1 9
GOOD 1 2 3

The file is space delimited.
I only care about lines that start with 'GOOD', which will all have the same formatting.
I believe that read_table() is the right command but I don't know how to filter it.
My current method of parsing files is to open the file, use regex to match the lines I care about and then split the line on spaces.  This can be slow and I am looking for a faster cleaner way.

A: You don't need regex to match lines that start with "GOOD".  Just iterate over the file and throw away all other lines, creating a "clean" copy of the data you want:
with open('irregular.txt') as inFile, open('regular.txt', 'w') as outFile:
    for line in inFile:
        if line.startswith('GOOD'):
            outFile.write(line)

Then you can read "regular.txt" using read_table or read_csv with the delim_whitespace=True argument.

A: Lets make a generator that filters good lines
def generate_good_lines(filename):
    with open(filename) as f:
        if line.startswith('GOOD'):
            yield line

Now all you need is parse these lines in way you want, eg:
def generate_parsed(filename_list):
    for filename in filename_list:
        for line in generate_good_lines(filename)
            data = your_parser_function(line)
            yield data

Then you consume all lines into list (for example):
your_list = list(generate_parsed(your_filename_list))

in your question it looks like your_parser_function looks like this:
def your_parser_function(line):
    return map(int, line[5:].split()) # split values and convert them to integers

generators take care about your memory and processor time consumption
/ sorry for my english /


text:
Q: How to swipe within a view controller within in an an array of strings? My app has so many strings in an NSArray and the user usually can click on a button which is linked with an ib action to go either next or previous. When they click next or previous the text within a TextView changes to the next or previous string within the array. I want the user to be able to swipe within the TextView to go either next or previous. I've learned a little bit about how to recognize swipes but that requires a whole new class which inherits UITextView while my other class that contains the array and ib actions inherit a UIViewcontroller. I'm going to post what my code looks like and I just want to know how to connect either the swipe class or have within the action to recognize the swipe. Thanks for your time!
//DateIdeasViewController.m

    #import "DateIdeasViewController.h"

@interface DateIdeasViewController ()

@end

@implementation DateIdeasViewController
@synthesize labelsText;
@synthesize textView;
@synthesize adView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void) bannerViewDidLoadAd:(ADBannerView *)banner {
    [adView setHidden:NO];
    NSLog(@"Showing");
}
- (void) bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error {
    [adView setHidden:YES];
    NSLog(@"Hidden");
}

-(void)viewDidLoad {
    adView.delegate = self;
    [adView setHidden:YES];

    titles = [NSArray arrayWithObjects:
              //Date ideas

       @"Some date ideas may be seasonal!",
               nil];
    step= 0;
    textView.text = [titles objectAtIndex:step];

    labelsText.text = [NSString stringWithFormat:@"%d/%d", step+1, titles.count];

}

-(IBAction) nextclicked:(id)sender{

    if (step<titles.count-1) {
        step++;
    }
    else
    {
        step= 0;
    }
    textView.text = [titles objectAtIndex:step];
    labelsText.text = [NSString stringWithFormat:@"%d/%d", step+1, titles.count];
}

-(IBAction) prevClicked:(id)sender{

    if (step>0) {
        step--;
    }
    else
    {
        step =titles.count-1;
    }
    textView.text = [titles objectAtIndex:step];
    labelsText.text = [NSString stringWithFormat:@"%d/%d", step+1, titles.count];
}

-(IBAction) randomClicked:(id)sender{

    step = 1+arc4random() %(titles.count-1);

    textView.text = [titles objectAtIndex:step];
    labelsText.text = [NSString stringWithFormat:@"%d/%d", step+1, titles.count];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(IBAction) favorite:(id)sender{
    NSMutableArray *array = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"favorites"]];
    [array addObject:textView.text];
    [[NSUserDefaults standardUserDefaults] setObject:array forKey:@"favorites"];

}

@end

SwipeableTextView.h
#import <UIKit/UIKit.h>

#define kMinimumGestureLength   25
#define kMaximumVariance        5

typedef enum swipeDirection {
    kSwipeNone,
    kSwipeLeft,
    kSwipeRight
} tSwipeDirection;

@interface SwipeableTextView : UITextView {
    CGPoint gestureStartPoint;
    tSwipeDirection swipeDirection;
}
@end

SwipeableTextView.m
#import "SwipeableTextView.h"

@implementation SwipeableTextView

- (id)initWithFrame:(CGRect)frame;
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;

}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];

    swipeDirection = kSwipeNone;
    UITouch *touch =[touches anyObject];
    gestureStartPoint = [touch locationInView:self];

}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesMoved:touches withEvent:event];

    UITouch *touch = [touches anyObject];
    CGPoint currentPosition = [touch locationInView:self];

    CGFloat deltaX = fabsf(gestureStartPoint.x - currentPosition.x);
    CGFloat deltaY = fabsf(gestureStartPoint.y - currentPosition.y);

    // Check if we already started a swipe in a particular direction
    // Don't let the user reverse once they get going
    if (deltaX >= kMinimumGestureLength && deltaY <= kMaximumVariance &&
        swipeDirection == kSwipeNone) {
        if (gestureStartPoint.x < currentPosition.x) {
            swipeDirection = kSwipeRight;
        }
        else {
            swipeDirection = kSwipeLeft;
        }
    }
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    if (swipeDirection == kSwipeRight) {

    }
    else if (swipeDirection == kSwipeLeft) {
        NSLog(@"Swipe left");
    }
    [super touchesEnded:touches withEvent:event];
}

@end

A: You shouldn't have to subclass a UITextView at all, just use UISwipeGestureRecognizer. In your view controller, you'll add something like this:
//Updated for both left and right swipes

//Create one gesture recognizer for the swipe left
UISwipeGestureRecognizer *swipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(actionToBePerformedOnSwipe:)];
swipe.direction = UISwipeGestureRecognizerDirectionLeft;
[self.textView addGestureRecognizer:swipe];

//Then do the same for UISwipeGestureRecognizerDirectionRight

Your view controller will now be notified that the user swiped on the text view. Also, this tutorial might help clarify gesture recognizers. EDIT: You can query the gesture recognizer (in the sender argument of the action method) for its direction by checking ((UISwipeGestureRecognizer *)sender).direction.
However, if you want to go the UITextView route, you'll have to add a make the view controller the text view's delegate and add a method to represent the swipe. In your text view sub class's header, you'd add something like this:
@protocol SwipeableTextViewDelegate <UITextView>
-(void)textViewReceivedLeftSwipe;
-(void)textViewReceivedRightSwipe;

@end

The custom text view would call these methods on the delegate when the swipes were received, and the delegate (your view controller) would perform whatever action you want.
Hope this helps!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change IPython/Jupyter notebook working directory When I open a Jupyter notebook (formerly IPython) it defaults to C:\Users\USERNAME.
How can I change this so to another location?

A: OS Windows 10
Python Anaconda 2018 ver
CHANGE WORKING DIRECTORY OF JUPYTER NOTEBOOK BY CONFIGURATION FILE:

*

*Open cmd prompt (or Anaconda Prompt), then type 'jupyter notebook --generate-config' and press enter

*This auto create a file 'jupyter_notebook_config' in the 'C:\Users\username.jupyter\' folder

*Look for the created file 'jupyter_notebook_config'and edit it.

*Find for  #c.NotebookApp.notebook_dir = ''

*Put you're desired path inside double quote, it becomes --->  c.NotebookApp.notebook_dir = 'D:/my_folder/jupiter'

*

*Note the forward slash (/) is used, and the comment (#) was remove.

Hence,
#c.NotebookApp.notebook_dir = ''

Edit to becomes
c.NotebookApp.notebook_dir = 'D:/your/desired/path'

*Let's modify the path of the Jupyter Notebook shortcut icon
6.0 On start menu, right-click on the shortcut, open folder location.
6.1 Once inside the folder, recommended to create a copy of Jupyter shortcut,
6.2 right click on the new shortcut icon  to open properties,

Finally,
6.3 on Target text box, remove %USERPROFILE% at the end of path, The very long path should end with jupyter-notebook-script.py
searcch my vid
Jupyter Notebook - Change working folder path from default to desired path

A: just change to the preferred directory in CMD, so if you are in
C:\Users\USERNAME>

just change the path like this
C:\Users\USERNAME>cd D:\MyProjectFolder

the CMD cursor then will move to this folder
D:\MyProjectFolder>

next you can call jupyter
D:\MyProjectFolder>jupyter notebook

A: For Windows 10

*

*Look for the jupyter_notebook_config.py in
C:\Users\your_user_name\.jupyter or look it up with cortana.

*If you don't have it, then go to the cmd line and type:
jupyter notebook --generate-config

*Open the jupyter_notebook_config.py and do a ctrl-f search for:
c.NotebookApp.notebook_dir

*Uncomment it by removing the #.

*Change it to:
c.NotebookApp.notebook_dir = 'C:/your/new/path'
Note: You can put a u in front of the first ', change \\\\ to /,  or change the '  to ". I don't think it matters.

*Go to your Jupyter Notebook link and right click  it. Select properties. Go to the Shortcut menu and click Target. Look for %USERPROFILE%. Delete it. Save. Restart Jupyter.

A: As MrFancypants mentioned in the comments, if you are using Jupyter (which you should, since it currently supersedes the older IPython Notebook project), things are a little different. For one, there are no profiles any more.
After installing Jupyter, first check your ~/.jupyter folder to see its content. If no config files were migrated from the default IPython profile (as they weren't in my case), create a new one for Jupyter Notebook:
jupyter notebook --generate-config

This generates ~/.jupyter/jupyter_notebook_config.py file with some helpfully commented possible options. To set the default directory add:
c.NotebookApp.notebook_dir = u'/absolute/path/to/notebook/directory'

As I switch between Linux and OS X, I wanted to use a path relative to my home folder (as they differ – /Users/username and /home/username), so I set something like:
import os
c.NotebookApp.notebook_dir = os.path.expanduser('~/Dropbox/dev/notebook')

Now, whenever I run jupyter notebook, it opens my desired notebook folder. I also version the whole ~/.jupyter folder in my dotfiles repository that I deploy to every new work machine.

As an aside, you can still use the --notebook-dir command line option, so maybe a simple alias would suit your needs better.
jupyter notebook --notebook-dir=/absolute/path/to/notebook/directory

A: To do the same trick described below for Windows in OS X, create this shell script
#!/bin/bash
cd $(dirname "$0") && pwd
ipython notebook

Call it ipython-notebook.command and make it executable.
Put it in the directory you want to work in, then double-click it.

A: When launched from the command line, the IPython Notebook will use your current working directory. I took advantage of this and created context menu entries to open it directly from Windows Explorer. No need for shortcuts or batch scripts!
I was inspired by the registry-based 'Git GUI Here/Git Bash Here' entries created by Git for Windows. This page (archived version linked) was helpful in locating the correct keys.
This first pair is for the context menu presented with nothing selected (e.g. the directory background). The notebook will open with the current directory as it's working directory.
Key: HKCR\Directory\Background\shell\ipythonnb
Value: &IPython Notebook Here

Key: HKCR\Directory\Background\shell\ipythonnb\command
Value: "<full path to IPython notebook>" "%v"

This pair is for the context menu presented when clicking on a folder. The notebook will open with the selected folder as it's working directory.
Key: HKCR\Directory\shell\ipythonnb
Value: &IPython Notebook Here

Key: HKCR\Directory\shell\ipythonnb\command
Value: "<full path to IPython notebook>" "%1"

Pay attention to %v vs %1 arguments or it won't work. Don't forget the quotes either. On my platform the full path to IPython Notebook is C:\WinPython-32bit-2.7.6.4\IPython Notebook.exe but this value will obviously dependent on your installation.
Edit: AFAICT  the full path is required even if the executable is on the system path.

A: A neat trick for those using IPython in windows is that you can make an ipython icon in each of your project directories designed to open with the notebook pointing at that chosen project. This helps keep things separate.
For example if you have a new project in C:\fake\example\directory
Copy an ipython notebook icon to the directory or create a new link to the windows "cmd" shell. Then right click on the icon and "Edit Properties"
Set the shortcut properties to:
Target:
C:\Windows\System32\cmd.exe /k "cd C:\fake\example\directory & C: & ipython notebook --pylab inline"

Start in:
C:\fake\example\directory\

(Note the added slash at the end of "start in")
This runs windows command line, changes to your working directory, and runs the ipython notebook pointed at that directory.
Drop one of these in each project folder and you'll have ipython notebook groups kept nice and separate while still just a doubleclick away.
UPDATE: IPython has removed support for the command line inlining of pylab so the fix for that with this trick is to just eliminate "--pylab inline" if you have a newer IPython version (or just don't want pylab obviously).
UPDATE FOR JUPYTER NOTEBOOK ~ version 4.1.1
On my test machines and as reported in comments below, the newest jupyter build appears to check the start directory and launch with that as the working directory. This means that the working directory override is not needed.
Thus your shortcut can be as simple as:
Target (if jupyter notebook in path):
    jupyter notebook

Target (if jupyter notebook NOT in path):
    C:\Users\<Your Username Here>\Anaconda\Scripts\jupyter.exe notebook

If jupyter notebook is not in your PATH you just need to add the full directory reference in front of the command. If that doesn't work please try working from the earlier version. Very conveniently, now "Start in:" can be empty in my tests with 4.1.1 and later. Perhaps they read this entry on SO and liked it, so long upvotes, nobody needs this anymore :)

A: In iPython Notebook on Windows, this worked for me:
cd d:\folder\

A: Besides @Matt's approach, one way to change the default directory to use for notebooks permanently is to change the config files. Firstly in the cmdline, type:
$> ipython profile create

to initialize a profile with the default configuration file. Secondly, in file ipython_notebook_config.py, uncomment and edit this line:
# c.NotebookManager.notebook_dir = 'D:\\Documents\\Desktop'

changing D:\\Documents\\Desktop to whatever path you like.
This works for me ;)
UPDATE: There is no c.NotebookManager.notebook_dir anymore.
Now, the line to uncomment and config is this one:
c.NotebookApp.notebook_dir = 'Z:\\username_example\folder_that_you_whant'

A: Locate your ipython binary. If you have used anaconda to install ipython-notebook on a mac, chances are it will be in the /Users/[name]/anaconda/bin/ directory
in that directory, instead of launching your notebook as
./ipython notebook

add a --notebook-dir=<unicode> option.
./ipython notebook --notebook-dir=u'../rel/path/to/your/python-notebooks'

I use a bashscript in my ipython bin directory to launch my notebooks:
DIR=$(dirname $0)
$DIR/ipython notebook --notebook-dir=u'../rel/path/to/your/python-notebooks'

Note - the path to the notebook dir is relative to the ipython bin directory.

A: Simply follow the guide on the official site, also copied below. For the first step, instead of copying the launcher, you can just go to start menu and right click to open the location.

*

*Copy the Jupyter Notebook launcher from the menu to the desktop.

*Right click on the new launcher and change the "Start in" field by pasting the full path of the folder which will contain all the notebooks.

*Double-click on the Jupyter Notebook desktop launcher (icon shows [IPy]) to start the Jupyter Notebook App, which will open in a new browser window (or tab). Note also that a secondary terminal window (used only for error logging and for shut down) will be also opened. If only the terminal starts, try opening this address with your browser: http://localhost:8888/.

A: Usually $ ipython notebook will launch the notebooks and kernels at he current working directory of the terminal.
But if you want to specify the launch directory, you can use --notebook-dir option as follows:
$ ipython notebook --notebook-dir=/path/to/specific/directory

A: jupyter notebook --help-all could be of help:
--notebook-dir=<Unicode> (NotebookManager.notebook_dir)
    Default: u'/Users/me/ipynbs'
    The directory to use for notebooks.

For example:
jupyter notebook --notebook-dir=/Users/yourname/folder1/folder2/

You can of course set it in your profiles if needed, you might need to escape backslash in Windows.
Note that this will override whatever path you might have set in a jupyter_notebook_config.py file.  (Where you can set a variable c.NotebookApp.notebook_dir that will be your default startup location.)

A: On MiniConda2/Anaconda2 under Windows to change Jupyter or iPython working directory, you can modify this file:
C:\Program Files\Miniconda2\cwp.py

and add your project folder location: development_folder= 'C:\Users\USERNAME\Development'
Which is My Username \ Development in my case.
also change: os.chdir(documents_folder) to os.chdir(development_folder)
try:
    documents_folder = get_folder_path(FOLDERID.Documents)
    development_folder= 'C:\Users\USERNAME\Development'
except PathNotFoundException:
    documents_folder = get_folder_path(FOLDERID.PublicDocuments)
os.chdir(development_folder)
subprocess.call(args, env=env)

Execute by using your regular Jupiter Notebook shortcuts.

A: This might help someone who doesn't want to change config file. If you are on Windows/ using Anaconda3, go to Win Start ->Search for  Jupyter Notebook(env).
Click on it and the Jupyter opens up. On Jupyter webpage, on right hand side go to New -> Terminal and the terminal window opens up. In this terminal windows change the directory to the working directory, using cd command. Example: cd "c:\User\<user-name>\workingdir".  Now in the same terminal window type Jupyter-notebook, this will open Jupyter with the working directory we used in cd command above.

A: Before runing ipython:

*

*Change directory to your preferred directory

*Run ipython

After runing ipython:

*

*Use  %cd /Enter/your/prefered/path/here/

*Use %pwd to check your current directory

A: %pwd  #look at the current work dir
%cd   #change to the dir you want

A: A simpler modification to the Windows Trick above -  without the need to hard-code the directory.
A) Create a batch file with the following contents:
  (Note: A batch file is a simple text file containing commands that can
    be run in the cmd window.  It must have a '.bat' extension, therefore ...
    you'll need to disable the folder setting which hides extensions of known types)
rem -- start_ipython_notebook_here.bat ---
dir
ipython notebook
pause

B) Copy and paste the batch file to any folder you want to start a notebook server in.
(Make sure it's a folder that you have permission to edit. "C:\" is not a good choice.)
C) Double-click on the batch file in Windows Explorer.
The notebook server should start as it normally does.

A: For linux and Windows:
Just modify 1 line, and you can change it.
1. Open file

cwp.py

in

C:\Users\ [your computer name]\Anaconda2

.
2. find the line

os.chdir(documents_folder)

at the end of the file.
Change it to

os.chdir("your expected working folder")

for example: os.chdir("D:/Jupyter_folder")
3. save and close.

It worked.

Update:
When it comes to MacOS, I couldn't find the cwp.py.
Here is what I found:
Open terminal on your Macbook, run 'jupyter notebook --generate-config'.
It will create a config file at /Users/[your_username]/.jupyter/jupyter_notebook_config.py
Open the config file, then change this line #c.NotebookApp.notebook_dir = ''
to
c.NotebookApp.notebook_dir = 'your path'
and remember un-comment this line too.
For example, I change my path to '/Users/catbuilts/JupyterProjects/'

A: According to official Jupyter Notebook Documentation Change

%USERPROFILE%

to your folder path
Documentation Link
3.1.1. Change Jupyter Notebook startup folder (Windows)

*

*Copy the Jupyter Notebook launcher from the menu to the desktop.

*Right click on the new launcher and change the Target field, change %USERPROFILE% to the full path of the folder which will contain all the notebooks.

*Double-click on the Jupyter Notebook desktop launcher (icon shows [IPy]) to start the Jupyter Notebook App. The notebook interface will appear in a new browser window or tab. A secondary terminal window (used only for error logging and for shut down) will be also opened.

A: I have both 32 and 64 bit python and ipython using WinPython, I wanted both 32 and 64 bit versions to point to the same working directory for ipython notebook.
I followed the above suggestions here I was still unable to get my setup working.
Here's what I did - in case anyone needs it:

It looks like Ipython notebook was using the configuration from C:\pythonPath\winpythonPath\settings\.ipython\profile_default
Even though ipython locate returns C:\users\Username\.ipython
As a result, modifying the ipython_notebook_config.py file did nothing to change my working directory.
Additionally ipython profile_create was not creating the needed python files in C:\pythonPath\winpythonPath\settings\.ipython\profile_default
I'm sure there's a better way, but to resolve this quickly, I copied the edited python files from C:\users\Username\.ipython\profile_default to C:\pythonPath\winpythonPath\settings\.ipython\profile_default
Now (finally) ipython notebook 64 bit runs and provides me the correct working directory
Note on Windows I'm having no issue with the following syntax:
c.NotebookApp.notebook_dir = u'C:/Users/Path_to_working_directory'

A: If you are using ipython in linux, then follow the steps:

!cd /directory_name/
You can try all the commands which work in you linux terminal.
!vi file_name.py
Just specify the exclamation(!) symbol before your linux commands.

A: import sys
sys.path.append('C:/')

A: For Mac OS X with blanks in target directory (follow up to @pheon). Add extra pair of double quotes around $(...) in line 2 thus. See: https://stackoverflow.com/a/1308838 (Sean Bright)
#!/bin/bash
cd "$(dirname "$0")" && pwd
ipython notebook

A: I have a very effective method to save the notebooks in a desired location in windows.

*

*One-off activity: Make sure the path of jupyter-notebook.exe is
saved under environment variable.

*Open your desired directory either from windows explorer or by cd
from command prompt

*From the windows explorer on your desired folder, select the address
bar(in a way that the path label is fully selected) and type jupyter-notebook.exe

*voila!! the notebook opens from the
desired folder and any new notebook will be saved in this location.

A: In command line before typing "jupyter notebook" navigate to the desired folder.
In my case my all python files are in "D:\Python".
Then type the command "jupyter notebook" and there you have it. You have changed your working directory.

A: This question keeps coming up when I search for ipython change pwd even though I am not interested in a notebook, but a terminal or qtconsole.  Not finding a relevant config entry I tried:
# lines of code to run at IPython startup.
c.InteractiveShellApp.exec_lines = ['%cd /home/paul/mypy']

This is the base level shell class; there are Terminal and Console (and probably notebook) entries that could further customize the action.
From the docs it looks like import statements are most common in the entry, but it appears that many magic commands work as well.

A: If you are using ipython in windows, then follow the steps:

*

*navigate to ipython notebook in programs and right click on it and
go to properties.

*In shortcut Tab , change the 'Start in' directory to your desired
directory.

*Restart the kernal.

A: You can also use AutoHotKey with a simple script to open a Jupyter Notebook server in a default directory (CTRL+I) or a path highlighted in explorer (or elsewhere with CTRL+SHIFT+I).
#SingleInstance Force
#NoTrayIcon

SetTitleMatchMode RegEx

; Press CTRL+ALT+I in a Windows Explorer window to launch a IPython notebook server in the current folder.
^+!i::
; Get the current path.
Send ^l
; Backup the current clipboard.
ClipSaved := ClipboardAll
; Copy and save the current path.
Send ^c
ClipWait
x = %Clipboard%
; Restore the clipboard.
Clipboard := ClipSaved
ClipSaved = ; Free the memory in case the clipboard was very large.
; Now, run the IPython notebook server.
RunWait, ipython notebook --notebook-dir "%x%", , min
return

^i::
; Now, run the IPython notebook server.
RunWait, jupyter notebook --notebook-dir "C:\Path\To\Workspace", , min
return

; Press CTRL+ALT+P to kill all Python processes.
^!p::
Run, taskkill /f /im python.exe, , min
return

A: Upper Solution may not work for you if you have installed latest version of Python in Windows. I have installed Python 3.6.0 :: Anaconda 4.3.0 (64-bit) and I wanted to change the working directory of iPython Notebook called Jupyter and this is how it worked for me.
Step-1 :  Open your CMD and type following command.
Step1 : CMD
Step-2 : It has now generated a file in your .jupyter folder. For me, it's C:\Users\Admin.jupyter . There you will find a file called jupyter_notebook_config.py .Right click and edit it. Add the following line and set path of your working directory.
Set your own working directory in place of "I:\STUDY\Y2-Trimester-1\Modern Data Science"
We are done. Now you can try restarting your Jupyter Notebook. Hope this is useful to you. Thanks

A: I'll add to the long list of answers here. If you are on Windows/ using Anaconda3, I accomplished this by going to the file /Scripts/ipython-script.py, and just added the lines
import os
os.chdir(<path to desired dir>)

before the line
sys.exit(IPython.start_ipython())

A: Try the nbopen module. When you install and integrate it with the windows explorer, you will be able to open any notebook by double clicking on it.


text:
Q: I am gettig all my catagorries and subcatagories in json string,but I want only active catagories in my json string class Ab_CategoryObserver_Model_Observer
{
    public function updateTopMenuJson(Varien_Event_Observer $observer)
    {
      $_helper = Mage::helper('catalog/category');
      $_categories = $_helper->getStoreCategories();
      $recursionLevel = 3; // Add recursion level
      $storeId = 1; // Add your Store ID for which you want to get category tree
      $node = '';
      $categoryTreeData = $this->getCategoryTree($recursionLevel, $storeId);
      $arr = json_encode($this->getCategoryTree(3));
      file_put_contents("cat_node.json", $arr);
    }

    protected function getCategoryTree($recursionLevel, $storeId = 1)
    {
        $parent = Mage::app()->getStore($storeId)->getRootCategoryId();
        $tree = Mage::getResourceModel('catalog/category_tree');
        /* @var $tree Mage_Catalog_Model_Resource_Category_Tree */

        $nodes = $tree->loadNode($parent)
            ->loadChildren($recursionLevel)
            ->getChildren();
        $tree->addCollectionData(null, false, $parent);

        $categoryTreeData = array();
        foreach ($nodes as $node) {
            $categoryTreeData[$node->getData('entity_id')] = $this->getNodeChildrenData($node);
        }

        return $categoryTreeData;
    }

    protected function getNodeChildrenData(Varien_Data_Tree_Node $node)
    {
        $categoryData = array(
          'title' => $node->getData('name'),
          'url'   => $node->getData('url_key'),
          'id'    => $node->getId(),
          // 'mega_menu1'=> $node->getData('mega_menu')
          'mega_menu'=> 'false'
        );

        foreach ($node->getChildren() as $childNode) {
          if (!array_key_exists('children', $categoryData)) {
              $categoryData['mega_menu'] = 'true';
              $categoryData['children'] = array();
          }

            $categoryData['children'][$childNode->getData('entity_id')] = $this->getNodeChildrenData($childNode);
        }
        return $categoryData;
    }
}

A: In getCategoryTree() you can change:
foreach ($nodes as $node) {
    $categoryTreeData[$node->getData('entity_id')] = $this->getNodeChildrenData($node);
}

To:
foreach ($nodes as $node) {
    if ($node->getIsActive()) {
        $categoryTreeData[$node->getData('entity_id')] = $this->getNodeChildrenData($node);
    }
}


text:
Q: Most efficient const char* comparison being case insensitive Would anyone please be able to tell me the most efficient way to compare two constant char stars?
#include <iostream>
#include <string>

int main()
{
    const char* value1 = "hello";
    const char* value2 = "HELLO";
    const char* possibility = NULL;

    if(stricmp(value1, value2)==0)
    {
        std::cout <<"\nThey Match!!!!!" << std::endl;
    }
    else{std::cout << "\nThey dont match :("<< std::endl;}

    return 0;
}

I used the following standard function but I know its not the most efficient way to do this?
Besides stricmp cannot handle NULL which in my case has a possibility of occurring.
So is there any other alternatives good for performance?
Thanks in advance

A: There is no efficient way to compare two character strings.
There are a couple of ways to improve on the basic stricmp(), if it shows up very high on a profile (which I have seen in real apps). You may find that the bulk of the cost is in tolower(), which is a function called on each character to convert it from upper to lowercase before comparison. The overhead of this function call, plus the cost of its body, can add up to significant time, because it must be locale-sensitive and deal with letters like Ö. If you know that your comparisons will only ever be performed in one locale (ie, only in English), then you can speed up tolower() by building a 256-character ASCII lookup table and implementing stricmp() manually.
With GCC, if you know you are targeting a CPU that supports SSE3, you can also specify the -msse3 command line switch that generates slightly more efficient machine instructions for the string comparison. It mostly helps case sensitive comparison, however.
In my line of work, any algorithm that requires comparing lots of constant character strings, as opposed to using interns or symbols to represent such identifiers, is considered a code smell. On one project, profiling indicated that about 7% of the CPU time was spent inside tolower() inside stricmp. That is effectively 7 out of 100 machines per data center doing nothing but turning uppercase letters into lowercase ones.

A: stricmp is probably faster than anything you can write yourself, and you shouldn't bother unless you know that this will be the bottleneck in your program's performance.


text:
Q: I want to return a the length of the string using 2 methods. Newbie in Java I have errors when I run program(1). But when I used program(2), writing 0 after a, it run and produced the correct output. Writing 0, is just my guess and somehow it worked. Why is that?
Program (1):
    public static void main(String[] args) {

        System.out.println(a);

    }

    private static int a(int len) {
        String s = "What";
        len = s.length();
        return (len);
    }
}

Program (2):
 public static void main(String[] args) {

        System.out.println(a(0));

    }

    private static int a(int len) {
        String s = "What";
        len = s.length();
        return (len);
    }
}

A: public static void main(String[] args) {
    System.out.println(a);
}

private static int a(int len) {
    String s = "What";
    len = s.length();
    return (len);
}

The problem here is that a is a function which receives a single integer parameter. This code is therefore a compilation error:
System.out.println(a);

You cannot print a function. What you can do is call a function and print that function's return value. Which is precisely what your second chunk of code does.
However, since your function a ignores its input parameter, you could re-write the code like this:
public static void main(String[] args) {
   System.out.println(a());
}

private static int a() {
    String s = "What";
    int len = s.length();
    return len;
}

Note that you still need to call the function using parentheses, a(). But because there is no longer a parameter required, you can leave the parameter list empty.

A: (Note: this really has nothing to do with the string length part. It's just simple method calling.)
Well look at this code:
public static void main(String[] args) {
   System.out.println(a);
}

That's trying to use a as if it's a variable - it's not, it's a method. So you want to invoke that method, and use the return value, which is what you do in your second version.
Admittedly it's pretty odd to pass in an argument and then not use it, and likewise you've got unnecessary parentheses around your return value - return isn't a method call.
So your code can be simplified to:
public static void main(String[] args) {
    System.out.println(a());
}

private static int a() {
    return "What".length();
}

Or if you really want the local variable:
public static void main(String[] args) {
    System.out.println(a());
}

private static int a() {
    String s = "What";
    return s.length();
}

A: You seem to be confusing method parameters with normal variable declarations.  You've written a as a method that takes a single int parameter, so you need to pass it a value; but you don't actually use that value in the body of the function.
You probably really want to use a local variable, and not pass a parameter at all, e.g.:
public static void main(String[] args) {

    System.out.println(a());

}

private static int a() {
    String s = "What";
    int len = s.length();
    return (len);

Note that you still need to write a() in the call, not just a, to make clear that it is a method call.

A: You wrote the function in such a way that it requires a parameter. To call a function that requires a parameter, you have to supply one. That's why the second program worked--you gave the function a a parameter of 0.
To make the first program work, then, you have two options. The first is what you did--supply the required parameter for the function. The second is to modify the function declaration so it does not require a parameter, changing
private static int a(int len) {

to
private static int a() {

A: The first code can't compile as you are trying to output a variable a that has not been declared (this syntax is not a method call). In the second one you are actually calling the static method a that exists, so it runs.

A: a is a function not a variable. You cannot call a function without the paranthesis...
you would have to type in a() to call the function.
Now, what happens in the first case is, since there are missing paranthesis it tries to resolve it as a variable and errors out.
The second case is where you call the function in the correct fashion

A: You need to read up on how to make method calls.  This is one of the most basic things you will be doing in java.
When you want to call method a, you need to pass the correct number of arguments(in this case a single int) or the method call will not be recognized and be an error.  What IDE are you using to develop your java code? If you are using something like Eclipse you shouldnt even be able to run the code with this error present.

A: Your function a is defined as a function that takes a single argument, which is named len. When you call it as a(0), you provide that argument and everything works just fine. When you call it as a, you do not provide that argument and compilation fails. The code never runs.
The question is: why have you defined a to take an argument? It isn't used: its value is immediately overwritten with the result of s.length().
It seems like you are attempting to declare a local variable for use by mentioning it in the function signature. That does is not necessary, and does not work, in Java.


text:
Q: How to ignore dependsOn failure because some subprojects don't have the defined task I have a multi-project gradle build where not all of the subprojects have the same plugin, but I would like to define tasks in the root build.gradle file like this:
subprojects {
    task continuousBuild(dependsOn: ["clean", "check", "jacocoTestReport", "integrationTests"]
}

Not all subprojects have "jacocoTestReport" or "integrationTests" defined, but this task will fail because of that fact. How do I configure this to work, and frankly, why is the default behavior so strict?

A: This is what ended up working for me:
   task continuousBuild(dependsOn: ['clean', 'check']) {
        def uncommonTasks = ['jacocoTestReport', 'integrationTests']
        dependsOn += tasks
                .findAll { uncommonTasks.contains(name) }
   }

And I forgot that I actually needed to run integrationTests in a doLast, which looks like this:
    task continuousBuild(dependsOn: ['clean', 'check']) {
        dependsOn += tasks
                .findAll { 'jacocoTestReport' == name) }

        if (tasks.findByName('integrationTests')) {
            doLast {
                integrationTests
            }
        }
    }


text:
Q: why my R code is not parallel CPU when using foreach I have a long code, so I wrapped them with "foreach" to parallel multi-CPU. But looks like there is only 1 CPU core busy running.

Here is my code:
library(doParallel)
library(foreach)
no_cores <- detectCores() - 2             # leave 2 core2 for the system
registerDoParallel(cores = no_cores)

ReadList <- read_excel("E:xxxx")
foreach(Index = 1:nrow(ReadList)) %do% {
 # code body part is huge
 write.table(D.results, quote = FALSE, sep = " ", paste(outputpath, "Daily_", List$Gid[Index], ".txt", sep=""))   # I output result for each Index within the loop
}

A: Like @coletl said, you need to change %do% to %dopar% if you want foreach to run parallel.
library(doParallel)
library(foreach)
no_cores <- detectCores() - 2             # leave 2 core2 for the system
registerDoParallel(cores = no_cores)

ReadList <- read_excel("E:xxxx")
foreach(Index = 1:nrow(ReadList)) %dopar% {
 # code body part is huge
 write.table(D.results, quote = FALSE, sep = " ", paste(outputpath, "Daily_", List$Gid[Index], ".txt", sep=""))   # I output result for each Index within the loop
}


text:
Q: Problem with Foreign Key in @OneToOne annotation I have spent a couple of days with a weird problem. There is a plethora of similar posts here in StackOverflow and I have check a lot of them but I was unable to find something similar with this. I have a Human Parent class
import javax.persistence.*;
import java.util.Date;

@Entity(name = "Human")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Human
{
    @Id
    @Column(name = "human_id", nullable = false)
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @JsonProperty("name")
    private String name;

    @JsonProperty("date_of_birth")
    private Date dateOfBirth;

    @Embedded
    @JsonProperty("authentication_credential")
    private AuthenticationCredentials authCred;

    // constructors + setter/getters
}

A User child class :
import javax.persistence.*;
import java.util.Date;

@Entity(name = "User")
@Table(name = "end_user")
public class User extends Human
{
    @OneToOne(mappedBy = "user",
              cascade = CascadeType.ALL,
              fetch = FetchType.LAZY,
              optional = false)
    @JsonProperty("contact_numbers")
    private CollectionOfContactMethods contactNumbers;

    @JsonProperty("telephone")
    private String telephone;

    // constructors + setter/getters
 }

and also a CollectionOfContactMethods with composition relationship with the User.
import javax.persistence.*;
import java.util.List;

@Entity(name = "CollectionOfContactMethods")
@Table(name = "collection_of_contact_methods")
public class CollectionOfContactMethods
{
    @Id
    @Column(name = "collection_id", nullable = false)
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private Long id;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ext_human_id", referencedColumnName = "human_id")
    private User user;

    @JsonProperty("email")
    private String email;

    // constructors + setter/getters
}

The plan, according to the ER diagram is this :

However, what I get at a database level is this :

I appreciate the time you spent. Thanks.
PS : Here is the UserController
@RestController
@RequestMapping("api/v1/user/")
public class UserController
{
    @Autowired
    UserService userService;

    @GetMapping(value = "users")
    Iterable<User> list()
    {
        Iterable<User> retVal = userService.findAll();
        return retVal;
    }

    @RequestMapping(value = "user", method = RequestMethod.POST)
    User create(@RequestBody User user)
    {
        return userService.save(user);
    }

    @RequestMapping(value = "user/{id}",  method = RequestMethod.GET )
    Optional<User> get(@PathVariable Long id)
    {
        return userService.findById(id);
    }
}

and also UserService :
import com.tsakirogf.schedu.model.human.User;
import org.springframework.data.repository.CrudRepository;

public interface UserService extends CrudRepository<User, Long>
{
}

A: Since you have a bi-directional relationship between User and CollectionOfContactMethods, the issue might be that CollectionOfContactMethods user is null when you try to create it, hence the null data in the database or the not-null property references a null or transient value : com.tsakirogf.schedu.model.CollectionOfContactMethods.user error. Try the following:
@RequestMapping(value = "user", method = RequestMethod.POST)
User create(@RequestBody User user) {
    CollectionOfContactMethods contactNumbers = user.getContactNumbers();
    contactNumbers.setUser(user);
    user.setContactNumbers(contactNumbers);
    return userService.save(user);
}


text:
Q: Hidden Overflow in Tablecells with 100% width I am trying to achieve a hidden overflow in a table column with "width: 100%".
In a normal div or a cell with a absolute width I would do it like this:
white-space: nowrap;
overflow: hidden;

but this just stretches the cell to fit the content, even if I give the table a max-width.
Here's an example to illustrate my problem: https://codesandbox.io/s/infallible-gates-7fxrg
feel free to ask some questions if something isn't clear.
Thank you for your solutions in advance.

A: Overflow only works on elements that are not stretchable. Otherwise there is no real "overflow" because the element can adapt itself to the width of its contents. In your case, you have to first assign the cell a fixed width, then use:
overflow: hidden;
white-space: nowrap;


text:
Q: Cloud Firestore security rules development mode We are developing an Android app based on Cloud Firestore.
Now, we have released the app to production and we continue to add more features, the changes force us to add/change the Firestore security rules.
The question is how to test the app with new security rules but before publishing the rules to all users?
I see in docs that Firestore has some emulator, but I don't understand if he can help or it used only for unit testing, there are also an simulator to test single request in draft mode, but in the end of the day we need to test the functionality of the app manually.
In other words, is there a way to change the security rules and test the app before apply it to all users?
Also i have some question to those who using Firebase in production:

*

*I guess your database splitted for development and production, do you split it in same project or create 2 projects with 2 google-services.json files, if you using in same project how do you handle changes in security rules for both versions?

*There may be changes between the app releases and data structures, but there are only one version of rules, some rules will be not compatible with another app releases, how do you handle this situation? is there way to match specific app release to specific security rules?

Maybe i missing something important about Firestore.
Thanks in advance.

A: You may want to look into Firebase Emulators (Beta) for testing security rules:

Firebase Emulators
The Firebase Emulators make it easier to fully
validate your app's behavior and verify your Firebase Security Rules
configurations. Use the Firebase Emulators to run and automate unit
tests in a local environment.

Sample Test:
firebase.assertFails(app.firestore().collection("private").doc("super-secret-document").get());

assertFails(pr: Promise) => Promise
This method returns a promise that is rejected if the input succeeds
or that succeeds if the input is rejected. Use this to assert if a
database read or write fails.

More here: https://firebase.google.com/docs/rules/unit-tests

A: I have used the Bolt, a superset that transpiles to JSON security rules. It looks like a much better option than using the standard rules and simulator through the Firebase UI especially if the rules are getting large and complex when the application grows, since Bolt allows you to create functions to re-use common code for read/write/validate logic.
Bolt Documentation:
https://github.com/FirebaseExtended/bolt/blob/master/docs/guide.md

Testing Instructions
https://github.com/FirebaseExtended/bolt/issues/80

Also Answering to our question, A Detail explanation is given here to support separate Firebase projects for your development and production environments.

A: Unfortunately I didn't find official solution, I split the security rules to development and production and the database to development and production using prefix dev-, so debug mode work with development database and matching development security rules.
Off course need to add prefix to each root collection during runtime.
This way I can publish new changes to development mode without effecting production, all work fine I am copy rules from development to production and remove `dev' prefix.
    service cloud.firestore { match /databases/{database}/documents {

            //production rules ********************************************************************
        match /data/{user}/{doc=**} {
          allow read, write: if request.auth.uid == user || hasPerrmision(request.auth.token.email);

        //development rules ********************************************************************
        match /dev-data/{user}/{doc=**} {
          allow read, write: if request.auth.uid == user || hasPerrmision(request.auth.token.email);

        }
    }
}

A: I did some research and I saw that Firestore Emulator Suite has the option to connect your local app to a local database which also uses your local security rules. You need to create a firestore.rules file and install the firestore emulator. Start the emulator and run your app to connect it to the local firestore database.This works really well.
More info:
firebase.google.com/docs/emulator-suite/connect_firestore
youtu.be/xyvxvnIlgBo?t=360


text:
Q: Peticion http con AngularJS a un Servidor PHP que responde con status -1 Estoy enviando una petición http desde AngularJS (Angular 1) a un servidor PHP y me responde esto:
{
  "data": null,
  "status": -1,
  "config": {
    "method": "POST",
    "transformRequest": [
      null
    ],
    "transformResponse": [
      null
    ],
    "data": {},
    "url": "http://api.elpozon.com/rest/login",
    "headers": {
      "Accept": "application/json",
      "Content-Type": "application/json;charset=utf-8"
    }
  },
  "statusText": ""
}

Cuando lo hago desde POSTMAN, me devuelve la información de logueo.
Esta es la función en AngularJS (Angular 1) que ejecuta la petición.
$scope.intentoDeLoginPozon = function(){

        var datapost = {
                method: 'POST',
                data: {
                    user : $scope.username,
                    pass: $scope.password
                },
                url: 'http://api.elpozon.com/rest/login',
                headers:{
                    'Accept': 'application/json'
                }
            };

            $http(datapost).then(function successCallback(response){
                $scope.mensaje = response;

            }, function errorCallback(response){
                $scope.error = response;

            });
    }

No tengo nada de informacion de como esta programado el Servidor en PHP.
Que explicacion existe para esto?

A: Si, son los mismos parametros. Hablé con el administrador del servidor php y me dice que olvido colocarle los headers, especialmente este:
'Content-Type: application/json; charset="UTF-8"
ahora cuando le hago la peticion, el server me devuelve la info del usuario.


text:
Q: How to "undo" a Projection in Fluent NHibernate? I have to display some objects which are stored in a relational database and I use fluent NHibernate to get them.
Since I need paging, I have to get both - the count of all objects, and the objects for the current page themselves.
The ICriteria for both purposes is very similar up to a point - for count i finally add
.SetProjection(Projections.RowCount())
and for current object list I add
SetFirstResult, AddOrder and SetMaxResults
Is there any way I could undo the projection on the criteria and reuse criteria for the results themselves, or do I have to reconstruct the criteria  for that purpose?
hibernate forums suggests a way that does not work.

A: I would write a method encapsulating the query logic including restrictions, grouping, ...:
public DetachedCriteria GetCriteria()
{
    return DetachedCriteria.For<Entity>()
        .Add(Restrictions.Eq(...))
        .Add(...);
}

And then send requests to the database:
var count = GetCriteria()
    .GetExecutableCriteria(session)
    .SetProjection(Projections.Count(Projections.Id()))
    .UniqueResult<int>();

var result = GetCriteria()
    .GetExecutableCriteria(session)
    .SetFirstResult(0)
    .SetMaxResults(10)
    .List<Entity>();

To further optimize this you could take a look at this excellent blog post in which Ayende Rahien talks about NHibernate Futures.

A: public static DetachedCriteria Clone(this DetachedCriteria criteria)
{
   var dummy = criteria.ToByteArray();
   return dummy.FromByteArray<DetachedCriteria>();
}

var criteria = GetCriteria()
var count = criteria
    .Clone()
    .GetExecutableCriteria(session)
    .SetProjection(Projections.Count(Projections.Id()))
    .UniqueResult<int>();

var result = criteria
    .GetExecutableCriteria(session)
    .SetFirstResult(0)
    .SetMaxResults(10)
    .List<Entity>();


text:
Q: Python Multithreading Execute Threads In Order with Pandas Dataframe Is there a way to execute threads in a specific order? I am familiar with the commands ".wait()" and ".notifyAll()", however it does not seem to work when all threads are targeting to a single function. The code below should write the csv file in this order: df1, df2, df3, df4.

import threading
import pandas as pd

df1 = pd.DataFrame(columns=["col1","col2","col3"])
df2 = pd.DataFrame(columns=["col1","col2","col3"])
df3 = pd.DataFrame(columns=["col1","col2","col3"])
df4 = pd.DataFrame(columns=["col1","col2","col3"])

def function(df):
    ###webscraping, compile web data to dataframe
    df.to_csv('output.csv', mode='a')

if __name__ == '__main__':
    t1 = threading.Thread(target=function, args=(df1,))
    t2 = threading.Thread(target=function, args=(df2,))
    t3 = threading.Thread(target=function, args=(df3,))
    t4 = threading.Thread(target=function, args=(df4,))
    t1.start()
    t2.start()
    t3.start()
    t4.start()

I want all dataframes to wait inside "function()" until they can execute in order. With multithreading, threads like to "race each other" and can fall out of order executed. Although multithreading is a good performance enhancing tool, its' downfall comes into play when order matters.
Example of Simplicity: If thread 4 finishes compiling its' dataframe, it needs to wait for the first 3 threads to compile its' corresponding dataframe and upload to the csv file until thread 4 can upload.
As always, thanks in advance!!

A: To solve your problem in a clean way, you probably want to be using concurrent.futures instead of threading, hopefully you're on python3.2+.
To do so, you want to create a list of your arguments to the function in the order you need them to write arglist = [df1, df2, ...], and then do something like
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=len(arglist)) as ex:
    results = ex.map(function, arglist)
for res in results:
    res.to_csv(..., mode='a')

To be honest, you should really try to use concurrent.futures for everything related to threading or multiprocessing.
It appears I read the question wrong the first time. I'll leave my previous answer here for people who google

You can use a lock (see
https://docs.python.org/3/library/threading.html#lock-objects), and
then call lock.acquire() before writing to csv and then
lock.release() afterwards. This will do exactly what you want.
Although in my opinion this is not ideal, instead I would suggest
returning the dataframes from each thread and just writing them all at
the end.
Your code would simply look like ``` lock = threading.Lock()
def function(args):
# web stuff
with lock:
df.to_csv(...) ```


text:
Q: List instead of multiple objects in one class GSON To simplify I have json string with the structure:
{
  "route": {
    "bus-1": {
      "stations": [
      ],
      "geo": [
      ]
    },
    "bus-2": {
      "stations": [
      ],
      "geo": [
      ]
    }
  },
  "routesReverse": {
    "bus-1": {
      "stations": [
      ],
      "geo": [
      ]
    },
    "bus-2": {
      "stations": [
      ],
      "geo": [
      ]
    }
  }
}

I'm trying to parse it using GSON:
public class MainJson {

    @SerializedName("route")
    @Expose
    public Routes route;
    @SerializedName("routesReverse")
    @Expose
    public Routes routesReverse;

    public Routes getRoute() {
        return route;
    }

    public Routes getRoutesReverse() {
        return routesReverse;
    }
}

I had created all models but and I have a question about this model:
public class Routes {

    @SerializedName("bus-1")
    @Expose
    BusStop busStop1;

    @SerializedName("bus-2")
    @Expose
    BusStop busStop2;

    public BusStop getBusStop1() {
        return busStop1;
    }

    public BusStop getBusStop2() {
        return busStop2;
    }
}

I don't like this approach to create BusStop object with annotation for each bus-route, I would like to create something like  List<BusStop> because my json has not only 2 routes.
How to achieve that ?

A: Can you modify the structure of a json you receive? Because the simplest way would be to have an array named "bus" instead of multiple "bus-i" objects inside "route" json object. If you can't modify json, then I don't think any convenient solution inside GSON is available, since it maps object 1-to-1, even if you apply 'alternate' tag. Check out docs for @SerializedName annotation here.

A: //Each object is just a list of bus stops
public class MainJson {
    @Expose
    public List<BusStop> route;

    @Expose
    public List<BusStop> routesReverse;

    public List<BusStop> getRoute() {
        return route;
    }

    public List<BusStop> getRoutesReverse() {
        return routesReverse;
    }
}

public class BusStop {
    @Expose
    List<Object> stations;

    @Expose
    List<Object> geo;

    public List<Object> getStations() {
        return stations;
    }

    public List<Object> getGeo() {
        return geo;
    }
}

It's not clear what stations/geo contain, but since you used array notation, I assume they each contain a list of objects.


text:
Q: Creating Alert Policy in Cloud Monitoring with OpenCensus Metric I'd like to use an OpenCensus metric in a Cloud Monitoring (Stackdriver) Alert Policy.
When I try to click the Add button, I get This query must contain a resource type. error. The odd thing, is that I can view this metric in MQL and can chart it.
According to the MQL charts that us this metric, the Resource: field is blank, and the charts work fine. The MQL charts show a resource type (on metric hover) of knative_broker, dataflow_job, aws_rds_database, k8s_control_plane_component, aws_lambda_function, and 36 more.
What Resource type should be used to alert on Open Census metrics in Cloud Monitoring alerts?

A: In Cloud Monitoring, application-specific metrics are typically called "custom metrics". You can create custom metrics with opencensus. For more detailed information please follow Custom Metrics with OpenCensus. We define a Stackdriver exporter as the goal to create an alert policy on the aggregation of two metrics. Refer Alert policy metric thresholds with stackdriver and opencensus for more information.


text:
Q: Reading TCURR table with RFC_READ_TABLE truncates the rate value I'm trying to read data from SAP ECC using Microsoft .NET. For this, I am using the SAP Connector for Microsoft .NET 3.0 Following is the code to retrieve the data, I'm getting the results too. However, I found that the exchange rate value is having a * if it exceeds 7 characters.
        ECCDestinationConfig cfg = new ECCDestinationConfig();

        RfcDestinationManager.RegisterDestinationConfiguration(cfg);

        RfcDestination dest = RfcDestinationManager.GetDestination("mySAPdestination");

        RfcRepository repo = dest.Repository;

        IRfcFunction testfn = repo.CreateFunction("RFC_READ_TABLE");
        testfn.SetValue("QUERY_TABLE", "TCURR");

        // fields will be separated by semicolon
        testfn.SetValue("DELIMITER", ";");

        // Parameter table FIELDS contains the columns you want to receive
        // here we query 3 fields, FCURR, TCURR and UKURS
        IRfcTable fieldsTable = testfn.GetTable("FIELDS");
        fieldsTable.Append();
        fieldsTable.SetValue("FIELDNAME", "FCURR");
        fieldsTable.Append();
        fieldsTable.SetValue("FIELDNAME", "TCURR");
        fieldsTable.Append();
        fieldsTable.SetValue("FIELDNAME", "UKURS");
        fieldsTable.Append();
        fieldsTable.SetValue("FIELDNAME", "GDATU");

        // the table OPTIONS contains the WHERE condition(s) of your query
        // several conditions have to be concatenated in ABAP syntax, for instance with AND or OR
        IRfcTable optsTable = testfn.GetTable("OPTIONS");

        var dateVal = 99999999 - 20190701;
        optsTable.Append();
        optsTable.SetValue("TEXT", "gdatu = '" + dateVal + "' and KURST = 'EURX'");

        testfn.Invoke(dest);

Values are as follows:

How to get the full value without any truncation?

A: You just ran into the worst limitation of RFC_READ_TABLE.
Its error is to return field values based on internal length and truncating the rest, rather than using the output length. TCURR-UKURS is a BCD decimal packed field of length 9,5 (9 bytes = 17 digits, including 5 digits after the decimal point) and an output length of 12. Unfortunately, RFC_READ_TABLE outputs the result on 9 characters, so a value of 105.48000- takes 10 characters is too long, so ABAP default logic is to set the * overflow character on the leftmost character (*5.48000-).
Either you create another RFC-enabled function module at SAP/ABAP side, or you access directly the SAP database (classic RDBMS connected to SAP server).

A: Just an addition to Sandra perfect explanation about this issue. Yes, the only solution here would be writing a custom module for fetching remote records.
If you don't want to rewrite it from scratch the simplest solution would be to copy RFC_READ_TABLE into Z module and change line 137
FIELDS_INT-LENGTH_DST = TABLE_STRUCTURE-LENG.

to
FIELDS_INT-LENGTH_DST = TABLE_STRUCTURE-OUTPUTLEN.

This solves the problem.
UPDATE: try BAPI_EXCHANGERATE_GETDETAIL BAPI, it is RFC-enabled and reads rates correctly. The interface is quite self-explanatory, the only difference is that date should be in native format, not in inverted:
CALL FUNCTION 'BAPI_EXCHANGERATE_GETDETAIL'
  EXPORTING
    rate_type  = 'EURO'
    from_curr  = 'USD'
    to_currncy = 'EUR'
    date       = '20190101'
  IMPORTING
    exch_rate  = rates
    return     = return.

A: Use BBP_RFC_READ_TABLE. It is still not the best but it does one thing right which RFC_READ_TABLE did not: one additional byte for the decimal sign.
No need to go through all the ordeal if you only look for patching the decimal issue.

A: This is the sample code used with SAP connector for .NET, let it be helpful for someone who looks for the same. Thanks for all those who helped.
        var RateForDate = 20190701;

        ECCDestinationConfig cfg = new ECCDestinationConfig();
        RfcDestinationManager.RegisterDestinationConfiguration(cfg);
        RfcDestination dest = RfcDestinationManager.GetDestination("mySAPdestination");
        RfcRepository repo = dest.Repository;

        IRfcFunction sapFunction = repo.CreateFunction("RFC_READ_TABLE");
        sapFunction.SetValue("QUERY_TABLE", "TCURR");
        // fields will be separated by semicolon
        sapFunction.SetValue("DELIMITER", ";");

        // Parameter table FIELDS contains the columns you want to receive
        // here we query 3 fields, FCURR, TCURR and UKURS
        IRfcTable fieldsTable = sapFunction.GetTable("FIELDS");
        fieldsTable.Append();
        fieldsTable.SetValue("FIELDNAME", "FCURR");
        //fieldsTable.Append();
        //fieldsTable.SetValue("FIELDNAME", "TCURR");
        //fieldsTable.Append();
        //fieldsTable.SetValue("FIELDNAME", "UKURS");

        // the table OPTIONS contains the WHERE condition(s) of your query
        // here a single condition, KUNNR is to be 0012345600
        // several conditions have to be concatenated in ABAP syntax, for instance with AND or OR
        IRfcTable optsTable = sapFunction.GetTable("OPTIONS");

        var dateVal = 99999999 - RateForDate;
        optsTable.Append();
        optsTable.SetValue("TEXT", "gdatu = '" + dateVal + "' and KURST = 'EURX'");

        sapFunction.Invoke(dest);

        var companyCodeList = sapFunction.GetTable("DATA");
        DataTable Currencies = companyCodeList.ToDataTable("DATA");

        //Add additional column for rates
        Currencies.Columns.Add("Rate", typeof(double));

        //------------------
        sapFunction = repo.CreateFunction("BAPI_EXCHANGERATE_GETDETAIL");
        //rate type of your system
        sapFunction.SetValue("rate_type", "EURX");
        sapFunction.SetValue("date", RateForDate.ToString());
        //Main currency of your system
        sapFunction.SetValue("to_currncy", "EUR");

        foreach (DataRow item in Currencies.Rows)
        {
            sapFunction.SetValue("from_curr", item[0].ToString());
            sapFunction.Invoke(dest);
            IRfcStructure impStruct = sapFunction.GetStructure("EXCH_RATE");
            item["Rate"] = impStruct.GetDouble("EXCH_RATE_V");
        }

        dtCompanies.DataContext = Currencies;
        RfcDestinationManager.UnregisterDestinationConfiguration(cfg);


text:
Q: What is the probability of choosing 15 correct bags out of 40 with 8 fake ones? In a certain television program there are 40 bags, 15 to be chosen if the participant answers correctly (but suppose he gets them all right) out of those 40 there are 8 bags that will remove the high prizes.
So what is the chance that I will choose 15 correct bags?
I thought that way:
P = probability of the correct bag
P(first bag) = 32/40, P(second bag) = 31/39 and so on...
In this logic the answer would be:
(32!/(32-15)!)/(40!/(40-15)!) = 0.01406383759 or 1.4%
But I have a feeling that this is wrong because I learned at school that when the order doesn't matter we use the combination formula, I hope someone will answer me if I'm correct :)

A: You are correct in a sense. We have to formulas to consider and compare:
$$
nPr=\frac{n!}{(n-r)!}\text{ and }nCr=\frac{n!}{r!(n-r)!}
$$
but when you divide two of those using different values of $n$ but the same value of $r$, the two results will be equal whether using combinations (nCr) or permutations (nPr).

I will give you two reasons for this:

*

*Suppose we give the good bags an ID 1 through 32 and the bad ones 33 through 40. Then you could consider a successful outcome either as an ordered sequence from the 32 good bags, or just some subset of the 32 bags without considering their order. For the ordered case, to compute the probability of success, you would then have to divide by ALL ordered sequences from the 40 bags. Hence $32P15/40P15$. But if you only considered groups of $15$ without considering order, it should be $32C15/40C15$.

*The factor $r!$ cancels out when dividing the combinations formulas with the same $r$.

A: They are two different ways to calculate the same probability.
$$\frac{\binom{32}{15}}{\binom{40}{15}} = \frac{\frac{32\times\dots\times18}{15!}}{\frac{40\times\dots\times26}{15!}} = \frac{32\times\dots\times18}{40\times\dots\times26} = \frac{32}{40} \times \frac{31}{39} \times \dots \times \frac{18}{26}$$

*

*LHS : number of correct combinations divided by number of possible combinations

*RHS : your thinking

Note that the $15!$ on both the denominator and the numerator cancel each other.


text:
Q: Reset Buttons shows 0 score but doesn't really clean the answers I have a simple quiz app where users can see their score from the scoreButton and reset their score from the resetButton. Questions are in RadioBoxes.The problem is that when the user clicks on resetButton, button shows 0 BUT doesn't clean the radioBoxes user had choose to start from the beginning. Something I miss in my code but can't figure it out.
    Any help appreciated a lot!
MainActivity.java
public class MainActivity extends AppCompatActivity {

    String Name;
    int score = 0;
    Button submitButton;
    Button resetButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //user input name
         final EditText nameField = (EditText)findViewById(R.id.nameField);
          Name = nameField.getText().toString();

        //submitButton shows user score
        submitButton = (Button) findViewById(R.id.submitButton);
        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitButton.setText("Your score is:" + score);
            }
        });
        //resetButton reset score to 0
        resetButton = (Button) findViewById(R.id.resetButton);
        resetButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submitButton.setText((String.valueOf(0)));
            }
        });
    }
    //This method is called when Radio Buttons are clicked
    public void onRadioButtonClicked(View view) {

        boolean checked = ((RadioButton)view).isChecked();
        switch (view.getId()) {
            //display a toast message all right answers
            case R.id.firstLeftRadioButton:
                if (checked)
                    Toast.makeText(this, "Hooray!Your answer is right", Toast.LENGTH_SHORT).show();
                score ++;
                break;
            case R.id.secondRightRadioButton:
                if (checked)
                    Toast.makeText(this, "Hooray!Your answer is right", Toast.LENGTH_SHORT).show();
                score++;
                break;
            case R.id.thirdLeftRadioButton:
                if (checked)
                    Toast.makeText(this, "Hooray!Your answer is right", Toast.LENGTH_SHORT).show();
                score++;
                break;
            case R.id.fourthLeftRadioButton:
                if (checked)
                    Toast.makeText(this, "Hooray!Your answer is right", Toast.LENGTH_SHORT).show();
                score++;
                break;
            case R.id.fifthRightRadioButton:
                if (checked)
                    Toast.makeText(this, "Hooray!Your answer is right", Toast.LENGTH_SHORT).show();
                score++;
                break;
            case R.id.sixthLeftRadioButton:
                if (checked)
                    Toast.makeText(this, "Hooray!Your answer is right", Toast.LENGTH_SHORT).show();
                score++;
                break;

            //display a toast message for all wrong answers
            case R.id.firstRightRadioButton:
                if (checked)
                    Toast.makeText(this, "Sorry, try again!", Toast.LENGTH_SHORT).show();
                score--;
                break;
            case R.id.secondLeftRadioButton:
                if (checked)
                    Toast.makeText(this, "Sorry, try again!", Toast.LENGTH_SHORT).show();
                score--;
                break;
            case R.id.thirdRightRadioButton:
                if (checked)
                    Toast.makeText(this, "Sorry, try again!", Toast.LENGTH_SHORT).show();
                score--;
                break;
            case R.id.fourthRightCheckBox:
                if (checked)
                    Toast.makeText(this, "Sorry, try again!", Toast.LENGTH_SHORT).show();
                score--;
                break;
            case R.id.fifthLeftRadioButton:
                if (checked)
                    Toast.makeText(this, "Sorry, try again!", Toast.LENGTH_SHORT).show();
                score--;
                break;
            case R.id.sixthRightRadioButton:
                if (checked)
                    Toast.makeText(this, "Sorry, try again!", Toast.LENGTH_SHORT).show();
                score--;
                break;
        }
    }

activity_main.xml

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <EditText
        android:id="@+id/nameField"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-light"
        android:inputType="text"
        android:hint="Name"
        android:textColor="#EF6C00"
        android:textSize="15sp"/>

    <TextView
        android:id="@+id/welcomeMessage"
        style="@style/WelcomeScreenText"
        android:fontFamily="sans-serif-light"
        android:text="Welcome to Hungry For History!\n         Let's get started!"/>

    <TextView
        android:id="@+id/firstQuestion"
        style="@style/QuestionsStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/welcomeMessage"
        android:paddingLeft="5dp"
        android:text="Who was born in Ancient City Stagira, Greece?"/>

    <TextView
        android:id="@+id/secondQuestion"
        style="@style/QuestionsStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/firstLeftRadioButton"
        android:paddingLeft="5dp"
        android:text="Who said in his last speech:With malice toward none;...let us strive on to finish the work we are in;to bind up the nation's wounds;into care for him who shall have borne the battle and for his widow and his orphans?"/>

    <TextView
        android:id="@+id/thirdQuestion"
        style="@style/QuestionsStyle"
        android:layout_below="@+id/secondLeftRadioButton"
        android:paddingLeft="5dp"
        android:text="Where the An Lushan Rebellion took place?"/>

    <TextView
        android:id="@+id/fourthQuestion"
        style="@style/QuestionsStyle"
        android:layout_below="@+id/thirdLeftRadioButton"
        android:text="Who was the most famous exemplar of absolute monarchy in France?"/>

    <TextView
        android:id="@+id/fifthQuestion"
        style="@style/QuestionsStyle"
        android:layout_below="@+id/fourthLeftRadioButton"
        android:text="When Alexander The Great lived?"/>

    <TextView
        android:id="@+id/sixthQuestion"
        style="@style/QuestionsStyle"
        android:layout_below="@+id/fifthLeftRadioButton"
        android:text="Where Albert Einstein studied?"/>

    <TextView
        android:id="@+id/seventhQuestion"
        style="@style/QuestionsStyle"
        android:layout_below="@+id/sixthLeftRadioButton"
        android:text="What was the main interest of Democritus?"/>

    <RadioGroup
        android:id="@+id/firstGroupRadioButtons"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/firstQuestion"
        android:orientation="horizontal"/>

    <RadioButton
        android:id="@+id/firstLeftRadioButton"
        style="@style/RadioButtonStyle"
        android:layout_below="@+id/firstQuestion"
        android:text="Aristotle"
        android:onClick="onRadioButtonClicked"/>

    <RadioButton
        android:id="@+id/firstRightRadioButton"
        style="@style/RadioButtonStyle"
        android:layout_below="@+id/firstQuestion"
        android:layout_toRightOf="@+id/firstLeftRadioButton"
        android:text="Pythagoras"
        android:onClick="onRadioButtonClicked"/>

    <RadioGroup
        android:id="@+id/secondGroupRadioButtons"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/secondQuestion"
        android:orientation="horizontal"/>
    <RadioButton
        android:id="@+id/secondLeftRadioButton"
        style="@style/RadioButtonStyle"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/secondQuestion"
        android:text="William McKinley"
        android:onClick="onRadioButtonClicked"/>

    <RadioButton
        android:id="@+id/secondRightRadioButton"
        style="@style/RadioButtonStyle"
        android:layout_below="@+id/secondQuestion"
        android:layout_toRightOf="@+id/secondLeftRadioButton"
        android:text="Abraham Lincoln"
        android:onClick="onRadioButtonClicked"/>

    <RadioGroup
        android:id="@+id/thirdGroupRadioButtons"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/thirdQuestion"
        android:orientation="horizontal"/>

    <RadioButton
        android:id="@+id/thirdLeftRadioButton"
        style="@style/RadioButtonStyle"
        android:layout_below="@+id/thirdQuestion"
        android:text="China"
        android:onClick="onRadioButtonClicked"/>

    <RadioButton
        android:id="@+id/thirdRightRadioButton"
        style="@style/RadioButtonStyle"
        android:layout_below="@+id/thirdQuestion"
        android:layout_toRightOf="@+id/thirdLeftRadioButton"
        android:text="Thailand"
        android:onClick="onRadioButtonClicked"/>

    <RadioGroup
        android:id="@+id/fourthGroupRadioButtons"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/fourthQuestion"
        android:orientation="horizontal"/>

    <RadioButton
        android:id="@+id/fourthLeftRadioButton"
        style="@style/RadioButtonStyle"
        android:layout_below="@+id/fourthQuestion"
        android:text="Louis XIV"
        android:onClick="onRadioButtonClicked"/>

    <RadioButton
        android:id="@+id/fourthRightCheckBox"
        style="@style/RadioButtonStyle"
        android:layout_below="@+id/fourthQuestion"
        android:layout_toRightOf="@+id/fourthLeftRadioButton"
        android:text="Michael I"
        android:onClick="onRadioButtonClicked"/>

    <RadioGroup
        android:id="@+id/fifthGroupRadioButtons"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/fifthQuestion"
        android:orientation="horizontal"/>

    <RadioButton
        android:id="@+id/fifthLeftRadioButton"
        style="@style/RadioButtonStyle"
        android:layout_below="@+id/fifthQuestion"
        android:text="330-323 BC"
        android:onClick="onRadioButtonClicked"/>

    <RadioButton
        android:id="@+id/fifthRightRadioButton"
        style="@style/RadioButtonStyle"
        android:layout_below="@+id/fifthQuestion"
        android:layout_toRightOf="@+id/fifthLeftRadioButton"
        android:text="336-323 BC"
        android:onClick="onRadioButtonClicked"/>

    <RadioGroup
        android:id="@+id/sixthGroupRadioButtons"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/sixthQuestion"
        android:orientation="horizontal"/>

    <RadioButton
        android:id="@+id/sixthLeftRadioButton"
        style="@style/RadioButtonStyle"
        android:layout_below="@+id/sixthQuestion"
        android:text="University of Zurich"
        android:onClick="onRadioButtonClicked"/>

    <RadioButton
        android:id="@+id/sixthRightRadioButton"
        style="@style/RadioButtonStyle"
        android:layout_below="@+id/sixthQuestion"
        android:layout_toRightOf="@+id/sixthLeftRadioButton"
        android:text="University of Germany"
        android:onClick="onRadioButtonClicked"/>

    <RadioGroup
        android:id="@+id/seventhGroupRadioButtons"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/seventhQuestion"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/seventhLeftRadioButton"
            style="@style/RadioButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Mathematics-Astronomy"
            android:onClick="onRadioButtonClicked"/>

        <RadioButton
            android:id="@+id/seventhRightRadioButton"
            style="@style/RadioButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Philosophy-Psychology"
            android:onClick="onRadioButtonClicked"/>
    </RadioGroup>

    <TextView
        android:id="@+id/score"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"/>

    <Button
        android:id="@+id/submitButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/seventhGroupRadioButtons"
        android:layout_marginBottom="3dp"
        android:background="@color/backgroundColor"
        android:text="Submit"
        android:textColor="@color/textColor"
        android:onClick="OnClick"/>

    <Button
        android:id="@+id/resetButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/submitButton"
        android:layout_marginBottom="3dp"
        android:onClick="OnClick"
        android:background="@color/backgroundResetColor"
        android:textColor="@color/textColor"
        android:text="Reset"
        android:textAllCaps="true"/>

</RelativeLayout>

A: put
RadioGroup.clearCheck();

to your resetButton onClick.
This might help you.

A: Do something like this
   RadioGroup radioGroup;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     radioGroup= (RadioGroup)findViewById(R.id.firstGroupRadioButtons);
    //resetButton reset score to 0
    resetButton = (Button) findViewById(R.id.resetButton);
    resetButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            submitButton.setText((String.valueOf(0)));
            radioGroup.clearCheck();

        }
    });
  }

You need to declare your radio group then define it! So you can clear all checks on radio button.
Hope this helps!


text:
Q: How to import USGS SDTS ddf file into Qgis I have downloaded SDTS dem files from the USGS.  These extract from tar.gz files as ddf files.
I have tried importing these files into Qgis using "add raster layer and choosing .ddf or .DDF from the file type list.  But the program returns "Unsupported Data Source: C:\tmp\RockyHills_dem\1694744.DEM.SDTS\9948CEL0.DDF is not a supported raster data source".
Can anyone help?


text:
Q: JQuery .not(next) - is it possible? Example HTML:

.......

.......

.......

Using slideToggle, if I click the first div moreCats I want next subCats to slideDown, which it does. At the same time I want to slideUp any other open subCats, but, NOT the one I'm toggling or else it would close then reopen, which is what its doing.
Question: is this valid? If not is there something similar?
$('div.subCats').not($(this).next('.subCats')).slideUp();

Here's the full JQuery I'm trying
// show children cat items
$('#sideNav').on("click", ".moreCats", function() {
    $('div.subCats').not($(this).next('.subCats')).slideUp(); // close all except next
    $(this).next('.subCats').slideToggle(); // slideToggle next
});

A: You can combine them by placing the slideToggle for the current target (which will return that element) inside .not and you want to select the parent's next as well
$('#sideNav').on("click", ".moreCats", function() {
    $('div.subCats').not($(this).parent().next('.subCats').slideToggle()).slideUp();
    //or do $(this).closest('.blah').next('.subCats');
});

Demo
If you want to split them, then better cache the next instead of selecting it again.
 $('#sideNav').on("click", ".moreCats", function() {
     var $target = $(this).parent().next('.subCats');
     $('div.subCats').not($target.slideToggle()).slideUp();
     //or just do as below
    //$('div.subCats').not($target).slideUp();
    //$target.slideToggle()
});

A: What you have is valid but it doesn't do what you expect, .next() selects the next immediate sibling element, you should first select the parent element:
$('div.subCats').not($(this.parentNode).next('.subCats')).slideUp();

You can also use .index() method:
$('#sideNav').on({
    click: function() {
       var $sub = $('div.subCats'),
           i    = $('#sideNav .moreCats').index(this);

       $sub.not( $sub.eq(i).slideToggle() ).slideUp();
    }
}, ".moreCats");

A: .moreCats doesn't have any siblings so you can't use .next().  What you really need is to get the next sibling of this's parent.  So you go from $(this) > .parent() > .next('.subCats')
$('body').on("click", ".moreCats", function() {
    console.log($(this).parent().next('.subCats'));
    $('div.subCats').not($(this).parent().next('.subCats')).slideUp(); // close all except next
    $(this).parent().next('.subCats').slideToggle(); // slideToggle next
});

See this JSFiddle for an example.


text:
Q: busybox: watchdog - logging I'm trying to debug a reboot of an embedded device and suspect watchdog might be involved but cannot find any logs.
I also cannot find the watchdog.conf anywhere.
The device is available at /dev/watchdog
Does watchdog log events to anywhere? Can I make it?
I've also read that it I should be able to find out if the last boot was the result of a watchdog restart via ioctl using the flag WDIOC_GETBOOTSTATUS but I can't figure out how to run that from shell.
any help appreciated.

A: Actually I have the exact same problem.
I think this can help much.
This is the missing tool to call arbitrary ioctl on devices.
Since most of data associated with ioctl are not human readable, this tools is intended for driver developpers who want to do quick tests on their drivers.
Usage:

ioctl [OPTIONS] FILEDEV IOCTL_NUM


text:
Q: Unable to use Excel as Database in Automation Anywhere 10 I am trying to use Excel as Database in Automation Anywhere 10. Following is my code
Connect to "Provider=Microsoft.ACE.OLEDB.16.0",Data Source = C:\Users\myuser\Documents\demo.xlsx;Extended Properties="Excel 10.0 Xml;HDR=YES";"Session:"session1"
Execute SQL statement:'Select * from [Sheet1]$'

But it is showing the following error,
Provider cannot be found. It may not properly installed.

Can anyone help on this?

A: Try
dim cn as object, cnstr as string, rs as object

set cn = createobject("adodb.connection")
cnstr = "Provider=Microsoft.ACE.OLEDB.16.0,Data Source=C:\Users\myuser\Documents\demo.xlsx;Extended Properties=""Excel 10.0 Xml;HDR=YES"";Session:""session1"""
set rs = cn.Execute("Select * from [Sheet1]$")

some version EXCEL use Provider=Microsoft.ACE.OLEDB.12.0 instead of Provider=Microsoft.ACE.OLEDB.16.0.

A: Couple of things you can check

*

*You may not have the database engine actually installed for the Office suite. I would check this first especially if you've not been able to connect before. Here is a link. This requires Access be installed, I think.

*You may also try Provider=Microsoft.ACE.OLEDB.12.0 or Extended Properties="Excel 12.0;HDR=YES"; as I do not think you need to the XML in Excel 10.0 XML.

*I have two additional notes for when you get it working:

*

*You need to reference your table name like so [$vSheetName$$] with the $ inside the brackets. Two dollar signs like so if you're inputting a variable

*It is a best practice to wrap your headers in ticks [ ` ] seen between the brackets. With AA, if any header has spaces, this is the only way to parse it

A: Your query syntax is incorrect.
Try using the following syntax instead:
Select * from [Sheet1$]


text:
Q: How to implement itemChecked and itemUnchecked signals for QTreeWidget in PyQt4? Where are the signals itemChecked and itemUncheсked on the QTreeWidget?
Qt Signals: (quote from PyQt4 QTreeWidget documentation page)

void currentItemChanged (QTreeWidgetItem *,QTreeWidgetItem *)
void itemActivated (QTreeWidgetItem *,int)
void itemChanged (QTreeWidgetItem *,int)
void itemClicked (QTreeWidgetItem *,int)
void itemCollapsed (QTreeWidgetItem *)
void itemDoubleClicked (QTreeWidgetItem *,int)
void itemEntered (QTreeWidgetItem *,int)
void itemExpanded (QTreeWidgetItem *)
void itemPressed (QTreeWidgetItem *,int)
void itemSelectionChanged ()

At current moment I solved it like this:
self.treeWidget.itemClicked.connect (self.handle)

def handle (item, column):
    print 'emitted!', item.text(column)
    if item.checkState(column) == QtCore.Qt.Checked:
        # there are a lot of my functions inside which work with item data
        self.handleChecked(item, column)
    elif item.checkState(column) == QtCore.Qt.Unchecked:
        self.handleUnchecked(item, column)

But it's a bad solution for me, because itemClicked emitted in a really lot of cases. It emitted in the case of Left/Right Mouse Clicks on the item text, which is absolutely unnecessary (I have heavy functions within self.handleChecked, and unnecessary calls of them on the context menu opening are pretty lousy).
Well, I also tried to use itemChanged:
self.treeWidget.itemChanged.connect (self.handle)

but this way situation is even worse! self.handle function calls himself recursively to infinity and beyond, because my functions within self.handleChecked change item data and this signal emits again and again. Also, I need signal which emits only on item checkbox toggling.
Can someone tell me, what I'm doing wrong?

A: To avoid problems with recursion when using the itemChanged signal, try temporarily blocking signals until the handler has completed:
def handle(self, item, column):
    self.treeWidget.blockSignals(True)
    if item.checkState(column) == QtCore.Qt.Checked:
        self.handleChecked(item, column)
    elif item.checkState(column) == QtCore.Qt.Unchecked:
        self.handleUnchecked(item, column)
    self.treeWidget.blockSignals(False)

UPDATE
The other part of your question asked about emitting a signal only when an item is checked.
One way to do this would be to subclass QTreeWidgetItem and reimplement it's setData function:
class TreeWidgetItem(QtGui.QTreeWidgetItem):
    def setData(self, column, role, value):
        state = self.checkState(column)
        QtGui.QTreeWidgetItem.setData(self, column, role, value)
        if (role == QtCore.Qt.CheckStateRole and
            state != self.checkState(column)):
            treewidget = self.treeWidget()
            if treewidget is not None:
                treewidget.itemChecked.emit(self, column)

class Window(QtGui.QTreeWidget):
    itemChecked = QtCore.pyqtSignal(object, int)

    def __init__(self, rows, columns):
        QtGui.QTreeWidget.__init__(self)
        self.itemChecked.connect(self.handleItemChecked)

    def handleItemChecked(self, item, column):
        print 'ItemChecked', int(item.checkState(column))

A: To complete the answer of @ekhumoro,
and to give a shorter answer (without subclassing QTreeWidgetItem):
block the signal :
self.treeWidget.blockSignals(True)
self.treeWidget.blockSignals(False)

and use
self.treeWidget.itemChanged

to connect to what you want.
the signal is used when the data is changed (text inside, checked state, ...)
and in your function linked to this signal verify if the treeWidget has changed is checked state.


text:
Q: Repeat Forms Rendering in Rails I have a rails nested form like this one below. What I'd like to do is to automatically render a certain quantity of phases forms depending on the value selected by the user on my main challenge form.
<%= form_for(@challenge, :html => {:id => "new_challenge_form"}) do |f| %>
    .
    .
    .
    <h3 class="color-gray small-padding-bottom">
        <%= t "challenges.form_labels.how_many_phases" %>
    </h3>
    <%= number_field_tag 'quantity', 1, :in => 1...10, :class => "text-input-wizard" %>
    <button> Generate Phases! </button>
<% end %>

I was trying to achieve this with some jquery but it isn't working. Something like
$('.block').html('<%= escape_javascript(render("phases/new")).html_safe %>')

What's the right way of doing this?
Thank you

A: Create partial with form. For mexample _challenge_form.html.erb in new.html.erb create div with class .block.
Then create new.js.erb and move there js code
$('.block').html('<%= escape_javascript(render("phases/_challenge_form", :challenge => @challenge)).html_safe %>')


text:
Q: Pairing columns and making dataframe from wide to long in r I have this kind of dataframe:
id institution  name_a      info_a bfullname      idb
1  A            Chet Baker  666    Clifford Brown 123

I need to reshape it, keeping the id, institution and pair the columns keeping the values like this:
id institution role       name           id_name
1  A           student    Chet Baker     666
1  A           teacher    Clifford Brown 123

The role column is defined by the column name, which I have an id vector identifying like this:
value     id
name_a    student
bfullname teacher

The problem is that I have a lot of columns with different names, I needed an way to specify which ones go along with another, or maybe a solution that I could rename the columns and do so.
I've seen a lot of reshape , dcast,melt and so on topics but still couldn't figure it out
Any ideas how to do it?

A: Forget reshape, use tidyr:
require(dplyr)
require(tidyr)

df <- tribble(
~id, ~institution,  ~name_a,      ~info_a, ~bfullname,      ~idb,
1,  "A",            "Chet Baker",  666,    "Clifford Brown", 123,
2,  "B",            "George Baker",  123,    "Charlie Brown", 234,
3,  "C",            "Banket Baker",  456,    "James Brown", 647,
4,  "D",            "Koeken Baker",  789,    "Golden Brown", 967
)

def <- tribble(~value, ~roleid, ~info,
"name_a",    "student", "info_a",
"bfullname", "teacher", "idb")

def

dflong <- df %>%
  gather(key, value, -id, -institution)

dflong %>%
  filter(key %in% def$value) %>%
  rename(role = key, name = value) %>%
  inner_join(def, by = c('role' = 'value')) %>%
  left_join(dflong %>% select(- institution), by = c('id' = 'id','info' = 'key'))

Which will result in:
# A tibble: 8 x 7
id institution role      name           roleid  info   value
      <dbl> <chr>       <chr>     <chr>          <chr>   <chr>  <chr>
1     1 A           name_a    Chet Baker     student info_a 666
2     2 B           name_a    George Baker   student info_a 123
3     3 C           name_a    Banket Baker   student info_a 456
4     4 D           name_a    Koeken Baker   student info_a 789
5     1 A           bfullname Clifford Brown teacher idb    123
6     2 B           bfullname Charlie Brown  teacher idb    234
7     3 C           bfullname James Brown    teacher idb    647
8     4 D           bfullname Golden Brown   teacher idb    967

A: library(data.table)

setDT(df)

melt(
  df,
  id.vars = 1:2,
  measure.vars = list(name = c(3, 5), id_name = c(4, 6)),
  variable.name = "role"
)
#>    id institution role           name id_name
#> 1:  1           A    1     Chet Baker     666
#> 2:  1           A    2 Clifford Brown     123

Where df is:
df <- read.table(text = '
id institution  name_a      info_a bfullname      idb
1  A            "Chet Baker"  666    "Clifford Brown" 123
', header = TRUE)

Created on 2019-02-14 by the reprex package (v0.2.1)


text:
Q: How can I prepend, append and join each item in an array? myArr = [1,2,3,4,5]
I would like to join but also prepend and append to each item
Result: '$'1'^'|'$'2'^'|'$'3'^'|'$'4'^'|'$'5'^'|'$'6'^'
I have tried this:
console.log("$" + valArr.join("'|'") + "^");
which results in:
'$'1'|'2'^'
I have tried: valArr.map(i => "'$'" + i).join("|"); but this only appends.

A: First map the array and then join it,

const myArr = [1, 2, 3, 4, 5].map((i) => `'$'${i}'^'`).join("|");
console.log(myArr);


text:
Q: Interception on constructor causes ClassNotFoundException I'm trying to intercept constructors annotated with @Inject. That worked fine in the context of a small unit test. However in the context of a DI container like Spring it fails with a ClassNotFoundException.
I managed to narrow down on the root cause. Calling getDeclaredConstructors on the instrumented class will trigger this exception. Interestingly enough, if we first create an instance of that class, the problem disappears.
For example:
public class InterceptConstructorTest {

    @Test
    public void testConstructorInterception() throws ClassNotFoundException {

        ByteBuddyAgent.install();

        new AgentBuilder.Default().type(nameStartsWith("test")).transform(new AgentBuilder.Transformer() {

            @Override
            public Builder<?> transform(Builder<?> builder, TypeDescription td) {

                return builder.constructor(isAnnotatedWith(Inject.class))
                        .intercept(SuperMethodCall.INSTANCE.andThen(MethodDelegation.to(ConstructorInterceptor.class)));
            }
        }).installOnByteBuddyAgent();

        // If this line is uncommented, ClassNotFoundException won't be thrown
//      MyClass myClass = new MyClass("a param");

        // Manually load MyClass
        Class<?> myClassDefinition = getClass().getClassLoader().loadClass("test.MyClass");

        // Throws NoClassDefFoundError
        for(Constructor<?> constructor : myClassDefinition.getDeclaredConstructors()) {
            System.out.println(constructor);
        }
    }
}

The stack stack trace can be found: http://pastebin.com/1zhx3fVX
class MyClass {

    @Inject
    public MyClass(String aParam) {
        System.out.println("constructor called");
    }
}

class ConstructorInterceptor {

    public static void intercept() {
        System.out.println("Intercepted");
    }
}

A: The problem in this case is the constructor injection. In order to rebase a constructor, Byte Buddy needs to create an additional type and creates a class like the following:
class MyClass {

    private synthetic MyClass(String aParam, $SomeType ignored) {
        System.out.println("constructor called");
    }

    @Inject
    public MyClass(String aParam) {
      this(aParam, null);
      // Instrumentation logic.
    }
}

The additional type is unfortunately necessary to create a unique signature for the rebased constructors. With methods, Byte Buddy can rather change the name but for constructors that is not possible as they must be named <init> in the class file to be recognized as constructors.
Byte Buddy tries to only load auxiliary classes after a type was instrumented. Depending on the virtual machine, loading a class that references another class causes the loading of the referenced type. If this type is the instrumented class, the instrumentation aborts the ongoing instrumentation for the circularity.
Therefore, Byte Buddy makes sure that any auxiliary type is only loaded at the first possible point after it can be sure that the instrumented type is loaded. And it does this by adding a self-initialization into the instrumented class's class initializer. In a way, Byte Buddy adds a block:
static {
  ByteBuddy.loadAuxiliaryTypes(MyClass.class);
}

If this block is not executed before reflecting on the class, the auxiliary type is not loaded and the exception you encounter is thrown. If you called:
Class.forName("test.MyClass", true, getClass().getClassLoader());

instead of loadClass, the problem would not occur where the second parameter indicates to execute the class initializer eagerly. Also, the initializer is executed if you create an instance.
Of course, this is not satisfactory, I am now adding some logic to decide for an auxiliary type if it can be loaded during the instrumentation to avoid such errors.