问:
Setting the camera button for different actions swift 3
I am creating an app where I open the camera as the first thing. I am able to do that. Once the user takes the photo, he is shown with two options, 'Use photo' or 'cancel'. My question is how can I write code in swift 3 to set the 'Use photo' button to my convenience like storing the photo to the gallery, or some other actions. Please suggest some code to do that. Thanks!

Below is the code I am using for opening the camera:

```<code>class ViewController: UIViewController, UINavigationControllerDelegate,         UIImagePickerControllerDelegate {
        override func viewDidAppear(_ animated: Bool) {
            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
                let image = UIImagePickerController()
                image.delegate = self
                image.sourceType = UIImagePickerControllerSourceType.camera
                image.allowsEditing = false
                self.present(image, animated: true)
            } else {
                print("This device does not support camera")
            }
        }
   }

  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        myImageView.image = image
    }
    else {
        //Error message
    }
    self.dismiss(animated: true, completion: nil)
    print("camera is dismissed or not")
}
</code>```

答:
My question is how can I write code in swift 3 to set the 'Use photo' button to my convenience like storing the photo to the gallery, or some other actions.

You're already setting ViewController as the image picker controller's delegate, so you just need to implement the imagePickerController(_:didFinishPickingMediaWithInfo:) method in ViewController.

Body:
I am creating an app where I open the camera as the first thing. I am able to do that. Once the user takes the photo, he is shown with two options, 'Use photo' or 'cancel'. My question is how can I write code in swift 3 to set the 'Use photo' button to my convenience like storing the photo to the gallery, or some other actions. Please suggest some code to do that. Thanks!

Below is the code I am using for opening the camera:

class ViewController: UIViewController, UINavigationControllerDelegate,         UIImagePickerControllerDelegate {
        override func viewDidAppear(_ animated: Bool) {
            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
                let image = UIImagePickerController()
                image.delegate = self
                image.sourceType = UIImagePickerControllerSourceType.camera
                image.allowsEditing = false
                self.present(image, animated: true)
            } else {
                print("This device does not support camera")
            }
        }
   }

  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        myImageView.image = image
    }
    else {
        //Error message
    }
    self.dismiss(animated: true, completion: nil)
    print("camera is dismissed or not")
}


来源: stackexchange

问:
"Nested" RecyclerViews
Hi everyone.

I've come up with an idea for an Android App, and I was thinking how to turn my thoughts into something working. I know how to program for Android even though I'm not that advanced as you might see, so I wanted some tips from you guys who I'm sure will be able to help.

Idea

I was thinking about an App to organize stuff, see your objects on a list and be able to add, move or remove them from the list.

Thoughts

I first thought I needed a RecyclerViewto display each item. Then I thought every item itself might be a box, and so be containing other items inside: this brought me to think of a sort of "nested" system of RecyclerViews. Before going too deep into this system I had to clarify each item should have been a Class, each of which should have had a RecyclerView assigned.

Question

I was wondering how I could make this "nested" system of RecyclerViews. I thought about making a RecyclerView an object, because I need each RecyclerView to display, function and be always the same in any screen of any item. But I don't know what the best way is.

Should I make it an object? How do I create a new RecyclerView through a button so the user can first tap an item and then, eventually, tap a button (inside the item details view for instance) to make it a box item and so create and open a RecyclerView when tapped?

P.S.

It may seem like multiple questions but it actually is only one: how to add and display a RecycerView when I tap a button inside a details screen of an item, of course automatically (have a reference to that RecyclerView).

答: You have to create the RecyclerView that holds your items list, let's call it rv_list, this RecyclerView has an adapter that takes each item and adapts it to an xml layout row_item.xml that you should define. Now to make an item itself display its own recyclerview you should put a recyclerview inside row_item.xml and populate it when adapting that item to rv_list inside the method onBindViewHolder.

ContentLicense: CC BY-SA 3.0

Title: "Nested" RecyclerViews


问:
Stop parsing out zeros after decimals in ggplot2's annotate
I need to annotate a location on a ggplot2 plot with a line that contains both a (real) greek letter and a number rounded to 2 decimal places. My problem arises because I want to display the decimal places even if they are both zero. Unfortunately, the parse = T setting in annotate converts the string "1.00" into "1". Here's a specific example:

```<code>alpha_num <- "1.00"
p <- ggplot(data.frame(x=1,y=1,label=paste0("alpha == ", alpha_num)))
p <- p + geom_text(aes(x,y,label=label), parse = TRUE, size = 30)
</code>```

The code above produces the following plot:

How do I get alpha_num displayed in its entirety?

答:
You can do it with the use of deparse.

So your code looks like this

```<code>alpha_num <- "1.00"
p <- ggplot(data.frame(x=1,y=1,label=paste0("alpha == ", alpha_num)))
# Use deparse in label
p <- p + geom_text(aes(x,y,label=paste0("alpha == ", deparse(alpha_num))), parse = TRUE, size = 30)
p
</code>```

And the output is:

Body:
I need to annotate a location on a ggplot2 plot with a line that contains both a (real) greek letter and a number rounded to 2 decimal places. My problem arises because I want to display the decimal places even if they are both zero. Unfortunately, the parse = T setting in annotate converts the string "1.00" into "1". Here's a specific example:

alpha_num <- "1.00"
p <- ggplot(data.frame(x=1,y=1,label=paste0("alpha == ", alpha_num)))
p <- p + geom_text(aes(x,y,label=label), parse = TRUE, size = 30)

The code above produces the following plot:

How do I get alpha_num displayed in its entirety?

Body:
You can do it with the use of deparse.

So your code looks like this

alpha_num <- "1.00"
p <- ggplot(data.frame(x=1,y=1,label=paste0("alpha == ", alpha_num)))
# Use deparse in label
p <- p + geom_text(aes(x,y,label=paste0("alpha == ", deparse(alpha_num))), parse = TRUE, size = 30)
p

And the output is:


问:
Angular UI Bootstrap responsive Navbar dropdown not working properly in new version
I just created an AngularJS project with grunt bower and Yeoman. Included Updated version to Angular 1.3.13. I want to use Angular UI bootstrap. I added Nav Bar which is responsive. But while on small screens, the drop down doesn't seem to work. When I click on dropdown the entire menu hides.

here is my index.html

```<code><!doctype html>
<html class="no-js">
<head>
<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<!-- build:css(.) styles/vendor.css -->
<!-- bower:css -->
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />
<!-- endbower -->
<!-- endbuild -->
<!-- build:css(.tmp) styles/main.css -->
<link rel="stylesheet" href="styles/main.css">
<!-- endbuild -->
</head>
<body ng-app="webClientApp">
    <!--[if lt IE 7]>
      <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> to improve your experience.</p>
    <![endif]-->

    <!-- Add your site or application content here -->
    <header>
        <nav class="navbar navbar-default" role="navigation">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">

                <button type="button" class="navbar-toggle"
                    ng-init="navCollapsed = true"
                    ng-click="navCollapsed = !navCollapsed">
                    <span class="sr-only">Toggle navigation</span> <span
                        class="icon-bar"></span> <span class="icon-bar"></span> <span
                        class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#/">Web Client</a>
            </div>

            <!-- Collect the nav links, forms, and other content for toggling -->
            <div class="collapse navbar-collapse"
                ng-class="!navCollapsed && 'in'" ng-click="navCollapsed=true">

                <ul class="nav navbar-nav">
                    <li class="active"><a href="">Link</a></li>
                    <li><a href="">Link</a></li>

                    <li class="dropdown"><a href="" class="dropdown-toggle" data-toggle="dropdown">Dropdown
                            <b class="caret"></b>
                    </a>
                        <ul class="dropdown-menu">
                            <li><a href="">Action</a></li>
                            <li><a href="">Another action</a></li>
                            <li><a href="">Something else here</a></li>
                            <li><a href="">Separated link</a></li>
                            <li><a href="">One more separated link</a></li>
                        </ul></li>

                </ul>
                <form class="navbar-form navbar-left" role="search">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="Search">
                    </div>
                    <button type="submit" class="btn btn-default">Submit</button>
                </form>
                <ul class="nav navbar-nav navbar-right">
                    <li><a href="">Link</a></li>
                    <li class="dropdown"><a href="" class="dropdown-toggle"
                        data-toggle="dropdown">Dropdown <b class="caret"></b></a>
                        <ul class="dropdown-menu">
                            <li><a href="">Action</a></li>
                            <li><a href="">Another action</a></li>
                            <li><a href="">Something else here</a></li>
                            <li><a href="">Separated link</a></li>
                        </ul></li>
                </ul>
            </div>
            <!-- /.navbar-collapse -->
        </nav>
    </header>
    <div class="container">
        <div ng-view=""></div>
    </div>

    <div class="footer">
        <div class="container">
            <p>
                <span class="glyphicon glyphicon-heart"></span> from the Yeoman team
            </p>
        </div>
    </div>

    <!-- Google Analytics: change UA-XXXXX-X to be your site's ID -->
    <script>
        !function(A, n, g, u, l, a, r) {
            A.GoogleAnalyticsObject = l, A[l] = A[l] || function() {
                (A[l].q = A[l].q || []).push(arguments)
            }, A[l].l = +new Date, a = n.createElement(g), r = n
                    .getElementsByTagName(g)[0], a.src = u, r.parentNode
                    .insertBefore(a, r)
        }(window, document, 'script',
                '//www.google-analytics.com/analytics.js', 'ga');

        ga('create', 'UA-XXXXX-X');
        ga('send', 'pageview');
    </script>

    <!-- build:js(.) scripts/vendor.js -->
    <!-- bower:js -->
    <script src="bower_components/jquery/dist/jquery.js"></script>
    <script src="bower_components/angular/angular.js"></script>
    <script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
    <script src="bower_components/angular-animate/angular-animate.js"></script>
    <script src="bower_components/angular-cookies/angular-cookies.js"></script>
    <script src="bower_components/angular-resource/angular-resource.js"></script>
    <script src="bower_components/angular-route/angular-route.js"></script>
    <script src="bower_components/angular-sanitize/angular-sanitize.js"></script>
    <script src="bower_components/angular-touch/angular-touch.js"></script>
    <script src="bower_components/angular-bootstrap/ui-bootstrap-tpls.js"></script>
    <!-- endbower -->
    <!-- endbuild -->

    <!-- build:js({.tmp,app}) scripts/scripts.js -->
    <script src="scripts/app.js"></script>
    <script src="scripts/controllers/main.js"></script>
    <script src="scripts/controllers/about.js"></script>
    <!-- endbuild -->
</body>
</html>
</code>```

I'm using all latest versions of JS. Here is my bower.json

```<code>{
  "name": "web-client",
  "version": "0.0.0",
  "dependencies": {
    "angular": "^1.3.13",
    "bootstrap": "^3.3.2",
    "angular-animate": "^1.3.13",
    "angular-cookies": "^1.3.13",
    "angular-resource": "^1.3.13",
    "angular-route": "^1.3.13",
    "angular-sanitize": "^1.3.13",
    "angular-touch": "^1.3.13",
    "angular-bootstrap": "0.12.1"
  },
  "devDependencies": {
    "angular-mocks": "^1.3.13"
  },
  "appPath": "app",
  "moduleName": "webClientApp"
}
</code>```

The nav bar on full screen is working fine. But when I resize the browser size, The responsive bar is working. Menu will show up only on clicking the toggle buton. But when I click on drop down menu, the entire menu hides.

I have followed this StackOverflow Question and I got one Plunker Demo for it. It is working fine there.

But I'm using Latest versions of all files. So mine is not working. Here is my code what I tried in Plnker.

How to Solve this Issue? Thanks.

答:
UPDATED for AngularJS 1.5+ and angular-ui-ootstrap 2.5+

I tried several options for a working dropdown menu in AngularJS 1.5+ and UIBootstrap in the menu bar - nothing worked and was outdated, so I thought I'd share my solution here, also available in this repo commit.

What I did

Used the normal navbar example from https://angular-ui.github.io/bootstrap/#!#collapse

Combined it with button dropdown functionality as showcased in there from the example on https://angular-ui.github.io/bootstrap/#!#dropdown

The code (please ref to points 1 & 2 above for further guidance)

```<code><nav class="navbar navbar-default" role="navigation">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle" ng-click="isNavCollapsed = !isNavCollapsed">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        <a class="navbar-brand" href="#">ToDoSth</a>
    </div>
    <div class="collapse navbar-collapse" uib-collapse="isNavCollapsed">
        <ul class="nav navbar-nav">
            <li><a href="#">Link 1</a></li>
            <li><a href="#">Link 2</a></li>
            <li uib-dropdown on-toggle="toggled(open)">
                <a href id="simple-dropdown" uib-dropdown-toggle>Link 3 <span class="caret"></span></a>
                <ul class="dropdown-menu" uib-dropdown-menu aria-labelledby="simple-dropdown">
                    <li><a href="#">SubItem 1</a></li>
                    <li><a href="#">SubItem 2</a></li>
                    <li><a href="#">SubItem 3</a></li>
                    <li role="separator" class="divider"></li>
                    <li><a href="#">SubItem 4</a></li>
                </ul>
            </li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
            <li uib-dropdown on-toggle="toggled(open)">
                <a href id="simple-dropdown" class="nav-text" uib-dropdown-toggle>Signed in as John Doe <span class="caret"></span></a>
                <ul class="dropdown-menu" uib-dropdown-menu aria-labelledby="simple-dropdown">
                    <li><a href="#">Profile</a></li>
                    <li role="separator" class="divider"></li>
                    <li><a href="#">Sign Out</a></li>
                </ul>
            </li>
        </ul>
    </div>
</nav>
</code>```

Body:
I just created an AngularJS project with grunt bower and Yeoman. Included Updated version to Angular 1.3.13. I want to use Angular UI bootstrap. I added Nav Bar which is responsive. But while on small screens, the drop down doesn't seem to work. When I click on dropdown the entire menu hides.

here is my index.html

<!doctype html>

<meta charset="utf-8">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width">

<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css" />

<link rel="stylesheet" href="styles/main.css">

                <button type="button" class="navbar-toggle"
                    ng-init="navCollapsed = true"
                    ng-click="navCollapsed = !navCollapsed">
                    Toggle navigation
                </button>
                Web Client

Link

Link

Dropdown

Action

Another action

Something else here

Separated link

One more separated link

                <form class="navbar-form navbar-left" role="search">

                        <input type="text" class="form-control" placeholder="Search">

                    <button type="submit" class="btn btn-default">Submit</button>
                </form>

Link

Dropdown

Action

Another action

Something else here

Separated link

                 from the Yeoman team

I'm using all latest versions of JS. Here is my bower.json

{
  "name": "web-client",
  "version": "0.0.0",
  "dependencies": {
    "angular": "^1.3.13",
    "bootstrap": "^3.3.2",
    "angular-animate": "^1.3.13",
    "angular-cookies": "^1.3.13",
    "angular-resource": "^1.3.13",
    "angular-route": "^1.3.13",
    "angular-sanitize": "^1.3.13",
    "angular-touch": "^1.3.13",
    "angular-bootstrap": "0.12.1"
  },
  "devDependencies": {
    "angular-mocks": "^1.3.13"
  },
  "appPath": "app",
  "moduleName": "webClientApp"
}

The nav bar on full screen is working fine. But when I resize the browser size, The responsive bar is working. Menu will show up only on clicking the toggle buton. But when I click on drop down menu, the entire menu hides.

I have followed this StackOverflow Question and I got one Plunker Demo for it. It is working fine there.

But I'm using Latest versions of all files. So mine is not working. Here is my code what I tried in Plnker.

How to Solve this Issue? Thanks.

Body:
UPDATED for AngularJS 1.5+ and angular-ui-ootstrap 2.5+

I tried several options for a working dropdown menu in AngularJS 1.5+ and UIBootstrap in the menu bar - nothing worked and was outdated, so I thought I'd share my solution here, also available in this repo commit.

What I did

Used the normal navbar example from https://angular-ui.github.io/bootstrap/#!#collapse

Combined it with button dropdown functionality as showcased in there from the example on https://angular-ui.github.io/bootstrap/#!#dropdown

The code (please ref to points 1 & 2 above for further guidance)

<nav class="navbar navbar-default" role="navigation">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle" ng-click="isNavCollapsed = !isNavCollapsed">
                <span class="sr-only">Toggle navigation</span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
                <span class="icon-bar"></span>
            </button>
        <a class="navbar-brand" href="#">ToDoSth</a>
    </div>
    <div class="collapse navbar-collapse" uib-collapse="isNavCollapsed">
        <ul class="nav navbar-nav">
            <li><a href="#">Link 1</a></li>
            <li><a href="#">Link 2</a></li>
            <li uib-dropdown on-toggle="toggled(open)">
                <a href id="simple-dropdown" uib-dropdown-toggle>Link 3 <span class="caret"></span></a>
                <ul class="dropdown-menu" uib-dropdown-menu aria-labelledby="simple-dropdown">
                    <li><a href="#">SubItem 1</a></li>
                    <li><a href="#">SubItem 2</a></li>
                    <li><a href="#">SubItem 3</a></li>
                    <li role="separator" class="divider"></li>
                    <li><a href="#">SubItem 4</a></li>
                </ul>
            </li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
            <li uib-dropdown on-toggle="toggled(open)">
                <a href id="simple-dropdown" class="nav-text" uib-dropdown-toggle>Signed in as John Doe <span class="caret"></span></a>
                <ul class="dropdown-menu" uib-dropdown-menu aria-labelledby="simple-dropdown">
                    <li><a href="#">Profile</a></li>
                    <li role="separator" class="divider"></li>
                    <li><a href="#">Sign Out</a></li>
                </ul>
            </li>
        </ul>
    </div>
</nav>


问:
C# DateTimePicker DataBinding Parse event not working
I have a datetimepicker that I am binding with nullable Date/Time column in dataset. I applied Format event successfully for null and not null object value. But, when I uncheck dtp control it does not get set to null in the dataset.
This is my code:

```<code>dtpBirthdate.DataBindings.Add(new Binding("Value", bsStaff, "birthDate", true));
dtpBirthdate.DataBindings["Value"].Format += new ConvertEventHandler(dtpFormat);
dtpBirthdate.DataBindings["Value"].Parse += new ConvertEventHandler(dtpParse);
</code>```

Format and Parse events:

```<code>private void dtpFormat(object sender, ConvertEventArgs e)
{
      Binding b = sender as Binding;
      if(b != null)
      {
           DateTimePicker dtp = (b.Control as DateTimePicker);
           if(dtp != null)
           {
                if (e.Value == null || e.Value == DBNull.Value)
                {
                    dtp.Checked = false;
                    dtp.CustomFormat = " ";
                    e.Value = false;
                }
                else
                {
                    dtp.Checked = true;
                    dtp.CustomFormat = "dd-MMM-yyyy";
                    dtp.Value = (DateTime) e.Value;
                }
            }
        }
    }

    private void dtpParse(object sender, ConvertEventArgs e)
    {
        Binding b = sender as Binding;

        if (b != null)
        {
            DateTimePicker dtp = (b.Control as DateTimePicker);
            if (dtp != null)
            {
                if (dtp.Checked == false)
                {
                    e.Value = DBNull.Value;
                }
                else
                {
                    e.Value = dtp.Value;
                }
            }
        }
   }
</code>```

After debugging, I found that it goes to infinite loop between parse and format events. What is wrong with my code?

Edit: There is also a datagridview binded to bsStaff bindingsource.

答: dtpParse is setting e.Value = dbNull.Value which will fire the dtpFormat as the value has changed which in turn sets e.Value = false which is different to dbNull.Value which will again fire dtpParse. Try removing the e.Value = false from dtpFormat</p>

Body:
I have a datetimepicker that I am binding with nullable Date/Time column in dataset. I applied Format event successfully for null and not null object value. But, when I uncheck dtp control it does not get set to null in the dataset.
This is my code:

dtpBirthdate.DataBindings.Add(new Binding("Value", bsStaff, "birthDate", true));
dtpBirthdate.DataBindings["Value"].Format += new ConvertEventHandler(dtpFormat);
dtpBirthdate.DataBindings["Value"].Parse += new ConvertEventHandler(dtpParse);

Format and Parse events:

private void dtpFormat(object sender, ConvertEventArgs e)
{
      Binding b = sender as Binding;
      if(b != null)
      {
           DateTimePicker dtp = (b.Control as DateTimePicker);
           if(dtp != null)
           {
                if (e.Value == null || e.Value == DBNull.Value)
                {
                    dtp.Checked = false;
                    dtp.CustomFormat = " ";
                    e.Value = false;
                }
                else
                {
                    dtp.Checked = true;
                    dtp.CustomFormat = "dd-MMM-yyyy";
                    dtp.Value = (DateTime) e.Value;
                }
            }
        }
    }

    private void dtpParse(object sender, ConvertEventArgs e)
    {
        Binding b = sender as Binding;

        if (b != null)
        {
            DateTimePicker dtp = (b.Control as DateTimePicker);
            if (dtp != null)
            {
                if (dtp.Checked == false)
                {
                    e.Value = DBNull.Value;
                }
                else
                {
                    e.Value = dtp.Value;
                }
            }
        }
   }

After debugging, I found that it goes to infinite loop between parse and format events. What is wrong with my code?

Edit: There is also a datagridview binded to bsStaff bindingsource.


问:
Is there some way to reduce the pain of range tracking?
There's currently a pull request by Jonathan S. to replace the implementation of Data.IntMap with one explained in this README based on ideas from a blog post by Edward Kmett.

The basic concept Jonathan S. developed from is that an IntMap is a binary tree that looks like this (I've made some slight changes to his development for the sake of consistency):

```<code>data IntMap0 a = Empty | NonEmpty (IntMapNE0 a)
data IntMapNE0 a =
    Tip !Int a
  | Bin { lo :: !Int
        , hi :: !Int
        , left :: !(IntMapNE0 a)
        , right :: !(IntMapNE0 a) }
</code>```

In this representation, each node has a field indicating the least and greatest key contained in the IntMapNE0. Using just a little bit fiddling allows this to be used as a PATRICIA trie. Jonathan noted that this structure has almost twice as much range information as it needs. Following a left or right spine will produce all the same lo or hi bounds. So he cut those out by only including the bound not determined by the ancestors:

```<code>data IntMap1 a = Empty | NonEmpty { topLo :: !Int, child :: !(IntMapNE1 a) }
data IntMapNE1 a =
    Tip a
  | IntMapNE1 { bound :: !Int
              , left :: !(IntMapNE1 a)
              , right :: !(IntMapNE1 a)
</code>```

Now each node has either a left bound or a right bound, but not both. A right child will have only a left bound, while a left child will have only a right bound.

Jonathan makes one further change, moving the values out of the leaves and into the internal nodes, which places them exactly where they are determined. He also uses phantom types to help track left and right. The final type (for now, anyway) is

```<code>data L
data R
newtype IntMap a = IntMap (IntMap_ L a) deriving (Eq)
data IntMap_ t a = NonEmpty !Int a !(Node t a) | Empty deriving (Eq)
data Node t a = Bin !Int a !(Node L a) !(Node R a) | Tip deriving (Eq, Show)
</code>```

Certain aspects of this new implementation are quite attractive. Most importantly, many of the most-used operations are substantially faster. Less importantly, but very nicely, the bit fiddling involved is much easier to understand.

However, there is one serious pain point: passing the missing range information down through the tree. This isn't so bad for lookups, insertions, etc., but gets pretty seriously hairy in the union and intersection code. Is there some abstraction that would allow this to be done automatically?

A couple extremely vague thoughts:

Could the phantom types be used with a custom class to tie treatment directly to handedness?

The "missing piece" nature is somewhat reminiscent of some zippery situations. Might there be a way to use ideas from that realm?

I've started thinking about using an intermediate type of some sort to provide a symmetrical "view" of the structure, but I'm a bit stuck. I can fairly easily convert back and forth between the basic structure and the fancy one, but that conversion is recursive. I need a way to convert only partially, but I don't know nearly enough about fancily built types to get it done.

答:
Is there some abstraction that would allow this to be done automatically?

You should be able to define a set of pattern synonyms that give you that. I’ll start from the second-to-last variant of your code, i.e.:

```<code>data IntMap1 a = Empty | NonEmpty { topLo :: !Int, child :: !(IntMapNE1 a) }
data IntMapNE1 a =
    Tip a
  | IntMapNE1 { bound :: !Int
              , left :: !(IntMapNE1 a)
              , right :: !(IntMapNE1 a)
</code>```

We tuple such a value with the bound from the parent in an Either (indicating whether it is a low or a high bound).

```<code>viewLoHi (Left lo, IntMapNE1 hi left right)
    = Just (lo, hi, (Left lo, left), (Right hi, right)
viewLoHi (Right hi, IntMapNE1 lo left right)
    = Just (lo, hi, (Left lo, left), (Right hi, right)
viewLoHi _
    = Nothing

pattern Bin' lo hi left right <- (viewLoHi -> Just (lo, hi, left, right))
</code>```

The top-level data type is different, so it needs its own pattern synonym

```<code>viewLoHi' (NonEmpty lo child) = viewLoHi (Left lo, child)
viewLoHi' Empty = Nothing

pattern NonEmpty' lo hi left right <- (viewLoHi' -> Just (lo, hi, left, right)
</code>```

Using only NonEmpty' and Bin' as you traverse the tree, the bookkeeping should now be completely hidden. (Code not tested, so there will be typos here)

Body:
There's currently a pull request by Jonathan S. to replace the implementation of Data.IntMap with one explained in this README based on ideas from a blog post by Edward Kmett.

The basic concept Jonathan S. developed from is that an IntMap is a binary tree that looks like this (I've made some slight changes to his development for the sake of consistency):

data IntMap0 a = Empty | NonEmpty (IntMapNE0 a)
data IntMapNE0 a =
    Tip !Int a
  | Bin { lo :: !Int
        , hi :: !Int
        , left :: !(IntMapNE0 a)
        , right :: !(IntMapNE0 a) }

In this representation, each node has a field indicating the least and greatest key contained in the IntMapNE0. Using just a little bit fiddling allows this to be used as a PATRICIA trie. Jonathan noted that this structure has almost twice as much range information as it needs. Following a left or right spine will produce all the same lo or hi bounds. So he cut those out by only including the bound not determined by the ancestors:

data IntMap1 a = Empty | NonEmpty { topLo :: !Int, child :: !(IntMapNE1 a) }
data IntMapNE1 a =
    Tip a
  | IntMapNE1 { bound :: !Int
              , left :: !(IntMapNE1 a)
              , right :: !(IntMapNE1 a)

Now each node has either a left bound or a right bound, but not both. A right child will have only a left bound, while a left child will have only a right bound.

Jonathan makes one further change, moving the values out of the leaves and into the internal nodes, which places them exactly where they are determined. He also uses phantom types to help track left and right. The final type (for now, anyway) is

data L
data R
newtype IntMap a = IntMap (IntMap_ L a) deriving (Eq)
data IntMap_ t a = NonEmpty !Int a !(Node t a) | Empty deriving (Eq)
data Node t a = Bin !Int a !(Node L a) !(Node R a) | Tip deriving (Eq, Show)

Certain aspects of this new implementation are quite attractive. Most importantly, many of the most-used operations are substantially faster. Less importantly, but very nicely, the bit fiddling involved is much easier to understand.

However, there is one serious pain point: passing the missing range information down through the tree. This isn't so bad for lookups, insertions, etc., but gets pretty seriously hairy in the union and intersection code. Is there some abstraction that would allow this to be done automatically?

A couple extremely vague thoughts:

Could the phantom types be used with a custom class to tie treatment directly to handedness?

The "missing piece" nature is somewhat reminiscent of some zippery situations. Might there be a way to use ideas from that realm?

I've started thinking about using an intermediate type of some sort to provide a symmetrical "view" of the structure, but I'm a bit stuck. I can fairly easily convert back and forth between the basic structure and the fancy one, but that conversion is recursive. I need a way to convert only partially, but I don't know nearly enough about fancily built types to get it done.

Body:
Is there some abstraction that would allow this to be done automatically?

You should be able to define a set of pattern synonyms that give you that. I’ll start from the second-to-last variant of your code, i.e.:

data IntMap1 a = Empty | NonEmpty { topLo :: !Int, child :: !(IntMapNE1 a) }
data IntMapNE1 a =
    Tip a
  | IntMapNE1 { bound :: !Int
              , left :: !(IntMapNE1 a)
              , right :: !(IntMapNE1 a)

We tuple such a value with the bound from the parent in an Either (indicating whether it is a low or a high bound).

viewLoHi (Left lo, IntMapNE1 hi left right)
    = Just (lo, hi, (Left lo, left), (Right hi, right)
viewLoHi (Right hi, IntMapNE1 lo left right)
    = Just (lo, hi, (Left lo, left), (Right hi, right)
viewLoHi _
    = Nothing

pattern Bin' lo hi left right <- (viewLoHi -> Just (lo, hi, left, right))

The top-level data type is different, so it needs its own pattern synonym

viewLoHi' (NonEmpty lo child) = viewLoHi (Left lo, child)
viewLoHi' Empty = Nothing

pattern NonEmpty' lo hi left right <- (viewLoHi' -> Just (lo, hi, left, right)

Using only NonEmpty' and Bin' as you traverse the tree, the bookkeeping should now be completely hidden. (Code not tested, so there will be typos here)


问:
jQuery UI Autocomplete widget: Edit search term before perform search
I use an autocomplete widget on a text input (#MapSearchName). The source is a simple array of strings (MapListNames). I need to modify the search term, before show autocomplete results.

In my case the MapListNames array contents strings in cyrillic and it works when user searches in cyrillic. I want autocomplete to suggest search results when a user searches in latin too. I wrote a Met2Kir() function which converts a latin string to a cyrillic one.

I found that this should be done by using the request/response function, but in the Autocomplete documentation that is not described particularly clear and I can not guess what should be the right way to do it.

Here is my code:

```<code>    $( "#MapSearchName" ).autocomplete({
    // source: MapListNames,
    delay: 0,
    autoFocus: true,

    source: function( request, response ) {
      var term = Met2Kir(request.term);
      response(  MapListNames, function( item ){
          return term;
      } );
    }

});
</code>```

I need some help with the source: part, so that any user input to be processed by the Met2Kir() function before it is sent for search.

The whole situation can be found here: Lyaskovets Citymap (it's in bulgarian, but the #MapSearchName is right below the map)

The JS code is at the end of citymap.js file

答:
This can be done by filtering the results into a new Array and sending them back to response(). For example:

```<code>$("#MapSearchName").autocomplete({
  delay: 0,
  autoFocus: true,
  source: function( request, response ) {
    var term = Met2Kir(request.term);
    var results = $.ui.autocomplete.filter(MapListNames, term);
    response(results);
  }
});
</code>```

Body:
I use an autocomplete widget on a text input (#MapSearchName). The source is a simple array of strings (MapListNames). I need to modify the search term, before show autocomplete results.

In my case the MapListNames array contents strings in cyrillic and it works when user searches in cyrillic. I want autocomplete to suggest search results when a user searches in latin too. I wrote a Met2Kir() function which converts a latin string to a cyrillic one.

I found that this should be done by using the request/response function, but in the Autocomplete documentation that is not described particularly clear and I can not guess what should be the right way to do it.

Here is my code:

    $( "#MapSearchName" ).autocomplete({
    // source: MapListNames,
    delay: 0,
    autoFocus: true,

    source: function( request, response ) {
      var term = Met2Kir(request.term);
      response(  MapListNames, function( item ){
          return term;
      } );
    }

});

I need some help with the source: part, so that any user input to be processed by the Met2Kir() function before it is sent for search.

The whole situation can be found here: Lyaskovets Citymap (it's in bulgarian, but the #MapSearchName is right below the map)

The JS code is at the end of citymap.js file

Body:
This can be done by filtering the results into a new Array and sending them back to response(). For example:

$("#MapSearchName").autocomplete({
  delay: 0,
  autoFocus: true,
  source: function( request, response ) {
    var term = Met2Kir(request.term);
    var results = $.ui.autocomplete.filter(MapListNames, term);
    response(results);
  }
});


问:
dynamic content on pages
I'm trying to migrate all "content" pages on a website to DNN5 Pro.

So I just created all the pages in DNN, added HTML module to the ContentPane and copied and pasted the HTML content from old pages.

The problem is that most of the pages have bits of classic asp code which do some minor server-side tasks - for example, populate tables with prices fetched from DB, pre-select user's country based on his IP address, do some basic dates calculations, etc.

Obviously, this code won't work in DNN.

If I had to migrate to PHP, I'd just rewrite these bits of code from classic ASP to PHP, then assign values from PHP to smarty and then would use them in templates.

But as DNN has a completely different architecture, I can't see how similar approach can be used.

Token replacement feature in HTML module looks like what I need, but it allows to "map" only tokens provided by DNN.

So, maybe anyone had similar issue with DNN and/or knows how this should be done.

答:
You could write code directly in your skin file.  Do some logic like:

```<code><%If PortalSettings.ActiveTab.TabID = 33 Then

//code here of what you want

End If%>
</code>```

Where 33 is the page id for the page you want to run custom code on.  There are other ways to do this like creating skin objects, or creating custom modules, but this is probably the easiest thing to do. Just write code directly in you skin.  Or make a copy of your skin for each page you need to do custom code for... again, more elegant ways but this will get'er done.

ContentLicense: CC BY-SA 2.5

Title: dynamic content on pages

Body:
You could write code directly in your skin file.  Do some logic like:

<%If PortalSettings.ActiveTab.TabID = 33 Then

//code here of what you want

End If%>

Where 33 is the page id for the page you want to run custom code on.  There are other ways to do this like creating skin objects, or creating custom modules, but this is probably the easiest thing to do. Just write code directly in you skin.  Or make a copy of your skin for each page you need to do custom code for... again, more elegant ways but this will get'er done.


问:
Creating a table of counts by some factor level in R
I have some data of foods eaten on different days.

```<code>day <- c(1,1,1,1,2,2,2,3,3,3,3,3)
food <- c('pizza','pizza','taco','snake','snake','taco','taco','pizza','taco','pizza','taco','snake')
all <- data.frame(day, food)
</code>```

I'd like to create a table with food on the x axis, day on the y axis, and the number of foods per day in the matrices such that

```<code>food.list <- unique(all$food)
 day.list <- unique(all$day )
output <- data.frame(c(2,1,1),c(0,2,1),c(2,2,1))
output
      1 2 3
pizza 2 0 2
taco  1 2 2
snake 1 1 1
</code>```

What is a straightforward way to solve this problem?

答:
```<code>library(reshape2)
dcast(data = all, formula = food~day, fun.aggregate = length, value.var = "food")
   food 1 2 3
1 pizza 2 0 2
2 snake 1 1 1
3  taco 1 2 2
</code>```

OR

```<code>table(all$food, all$day)

        1 2 3
  pizza 2 0 2
  snake 1 1 1
  taco  1 2 2
</code>```

Body:
I have some data of foods eaten on different days.

day <- c(1,1,1,1,2,2,2,3,3,3,3,3)
food <- c('pizza','pizza','taco','snake','snake','taco','taco','pizza','taco','pizza','taco','snake')
all <- data.frame(day, food)

I'd like to create a table with food on the x axis, day on the y axis, and the number of foods per day in the matrices such that

food.list <- unique(all$food)
 day.list <- unique(all$day )
output <- data.frame(c(2,1,1),c(0,2,1),c(2,2,1))
output
      1 2 3
pizza 2 0 2
taco  1 2 2
snake 1 1 1

What is a straightforward way to solve this problem?

Body:
library(reshape2)
dcast(data = all, formula = food~day, fun.aggregate = length, value.var = "food")
   food 1 2 3
1 pizza 2 0 2
2 snake 1 1 1
3  taco 1 2 2

OR

table(all$food, all$day)

        1 2 3
  pizza 2 0 2
  snake 1 1 1
  taco  1 2 2


问:
Set the Version of a Secret When Setting the Secret in Azure KeyVault
It doesn't seem like it's possible currently to set the version of an Azure Key Vault secret when uploading the secret. I'm using SetSecretAsync. Am I missing something? Even when attempting the operation from the Azure Portal, you aren't given the opportunity to set the version, nor is there a way to back up or restore a secret.

It seems like this is intentional (given the seeming lack of methods to do it), but consider the background of why I'm doing this. We're concerned with a secret being deleted by mistake or even the vault itself being deleted by mistake. As we're using the secrets for encryption/decryption purposes, if the secrets or vault were to be deleted, we would have an issue... So we are planning to back up the secrets to blob storage in the event we do need to restore them. With keys in the vault, a simple way to do this type of operation is available, but it doesn't seem secrets were given this same treatment unfortunately.

答:
No this is not possible, just look at the rest call to do that, there's no option for that.

Reference: https://learn.microsoft.com/en-us/rest/api/keyvault/setsecret


问:
Print all the nodes in a binary tree which do not have sibling?
A sibling is a node that has same parent. In a Binary Tree, there can be at most one sibling. Root should not be printed as root cannot have a sibling.

I have written code for this which works fine in all the Testcases which I have used so far but when I tried to submit it in online judge it got wrong for most of the cases. I am not able to figure out what could be the bug although I have tried my best to figure out what it is. Also I can not dry run for that particular Testcases as I do not have access to them.

```<code>public static void printNodesWithoutSibling(BinaryTreeNode<Integer> root) {

        if(root==null)
        return;

        printNodesWithoutSibling(root.left);
        printNodesWithoutSibling(root.right);

        if(root.right==null && root.left!=null)
        {
            System.out.print(root.left.data+" ");
            return;
        }

        else if(root.left==null && root.right!=null)
        {

            System.out.print(root.right.data+" ");
            return;
        }
}
</code>```

答:
Your code does not take into account the case for a left child without a right sibling.

The required knowledge for determining if a node has a sibling is in its parent.

The following code snippet prints, in preorder, the nodes that do not have a sibling. You could easily modify it is you require it in inorder or postorder. The code is written in c++, but I think that you will not have any problem for refactoring in java

```<code>void print_nodes_without_sibling(Node * root, bool no_sibling = false)
{
  if (root == nullptr)
    return;

  if (no_sibling)
    cout << root->key << endl;

  print_nodes_without_sibling(root->left,
                              root->left != nullptr and root->right != nullptr);
  print_nodes_without_sibling(root->right,
                              root->left != nullptr and root->right != nullptr);
}
</code>```

Body:
A sibling is a node that has same parent. In a Binary Tree, there can be at most one sibling. Root should not be printed as root cannot have a sibling.

I have written code for this which works fine in all the Testcases which I have used so far but when I tried to submit it in online judge it got wrong for most of the cases. I am not able to figure out what could be the bug although I have tried my best to figure out what it is. Also I can not dry run for that particular Testcases as I do not have access to them.

public static void printNodesWithoutSibling(BinaryTreeNode<Integer> root) {

        if(root==null)
        return;

        printNodesWithoutSibling(root.left);
        printNodesWithoutSibling(root.right);

        if(root.right==null && root.left!=null)
        {
            System.out.print(root.left.data+" ");
            return;
        }

        else if(root.left==null && root.right!=null)
        {

            System.out.print(root.right.data+" ");
            return;
        }
}

Body:
Your code does not take into account the case for a left child without a right sibling.

The required knowledge for determining if a node has a sibling is in its parent.

The following code snippet prints, in preorder, the nodes that do not have a sibling. You could easily modify it is you require it in inorder or postorder. The code is written in c++, but I think that you will not have any problem for refactoring in java

void print_nodes_without_sibling(Node * root, bool no_sibling = false)
{
  if (root == nullptr)
    return;

  if (no_sibling)
    cout << root->key << endl;

  print_nodes_without_sibling(root->left,
                              root->left != nullptr and root->right != nullptr);
  print_nodes_without_sibling(root->right,
                              root->left != nullptr and root->right != nullptr);
}


问:
What is a Pythonic way to remove doubled duplicates in a list but allow triplets/greater?
I have a list in Python

```<code>list1 = [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1]
</code>```

There are "groupings" of consecutive 1's and 0's. For my purposes, I am only interested in the consecutive 1's. Let's say if there is a solitary 1, e.g.

```<code> ... 0, 0, 1, 0, 0 ...
</code>```

I would like it to be changed into a 0. Similarly, if there are only pairs of 1's, these should become 0s as well. e.g.

```<code>.... 0, 0, 1, 1, 0, 0...
</code>```

should become

```<code>.... 0, 0, 0, 0, 0, 0...
</code>```

But "triplets" of consecutive ones or higher are ok.

I considered keeping track of the counts of 1s via a dictionary, but this feels too complex. The idea would be to iterate through the list, keeping track of the count of consecutive 1s in a list. But, how do you "go back" and switch the 1s to 0s?

```<code>counter_list = []
for i in list1:
    if i == 1:
        counter_list = counter_list + 1
            if len(counter_list)==1 or len(counter_list)==2:
                # now I don't know how to "go back" to change these elements into 0s
</code>```

答: You can use methods from image processing for this. The morphological operation "opening" with the structure element [1 1 1]should do the job. Should be a 1-liner.</p>

Body:
I have a list in Python

list1 = [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1]

There are "groupings" of consecutive 1's and 0's. For my purposes, I am only interested in the consecutive 1's. Let's say if there is a solitary 1, e.g.

 ... 0, 0, 1, 0, 0 ...

I would like it to be changed into a 0. Similarly, if there are only pairs of 1's, these should become 0s as well. e.g.

.... 0, 0, 1, 1, 0, 0...

should become

.... 0, 0, 0, 0, 0, 0...

But "triplets" of consecutive ones or higher are ok.

I considered keeping track of the counts of 1s via a dictionary, but this feels too complex. The idea would be to iterate through the list, keeping track of the count of consecutive 1s in a list. But, how do you "go back" and switch the 1s to 0s?

counter_list = []
for i in list1:
    if i == 1:
        counter_list = counter_list + 1
            if len(counter_list)==1 or len(counter_list)==2:
                # now I don't know how to "go back" to change these elements into 0s


问:
How to setup application icon that shows up in Alt-Tab dialog when switching tasks on Windows?
How do I setup icon, for wxpython application on Windows, that shows up in the Alt-Tab dialog when I'm switching between applications?

The application icon in the menu bar and the corner of the running app shows my icon but when I switch between applications using Alt-Tab I can see the default square with blue outline icon.

Do I need to do something extra for my icon to show up in Alt-Tab dialog or does my icon have to include a special resolution?

In my class initializer I setup icon :

```<code>class A(wx.Frame):
    def __init__(self,parent,id,title):
        wx.Frame.__init__(self,parent,-1,title,size=(265,434))
        favicon = wx.Icon('C:\source\python\gui\gf.ico',
                           wx.BITMAP_TYPE_ICO, 16,16)
        wx.Frame.SetIcon(self,favicon)
</code>```

答:
This works for me:

```<code>self.icon = wx.Icon(fn, wx.BITMAP_TYPE_ICO)
self.SetIcon(self.icon)
</code>```

where the icon in fn has several resolutions (16, 32, and 48, I think).

Looks like you at least want to change

```<code>    wx.Frame.SetIcon(self,favicon)
</code>```

to

```<code>    self.SetIcon(favicon)
</code>```

Also, try removing the 16's from the wx.Icon call and making sure your icon has other resolutions.

Body:
How do I setup icon, for wxpython application on Windows, that shows up in the Alt-Tab dialog when I'm switching between applications?

The application icon in the menu bar and the corner of the running app shows my icon but when I switch between applications using Alt-Tab I can see the default square with blue outline icon.

Do I need to do something extra for my icon to show up in Alt-Tab dialog or does my icon have to include a special resolution?

In my class initializer I setup icon :

class A(wx.Frame):
    def __init__(self,parent,id,title):
        wx.Frame.__init__(self,parent,-1,title,size=(265,434))
        favicon = wx.Icon('C:\source\python\gui\gf.ico',
                           wx.BITMAP_TYPE_ICO, 16,16)
        wx.Frame.SetIcon(self,favicon)

Body:
This works for me:

self.icon = wx.Icon(fn, wx.BITMAP_TYPE_ICO)
self.SetIcon(self.icon)

where the icon in fn has several resolutions (16, 32, and 48, I think).

Looks like you at least want to change

    wx.Frame.SetIcon(self,favicon)

to

    self.SetIcon(favicon)

Also, try removing the 16's from the wx.Icon call and making sure your icon has other resolutions.


问:
Accessing a siblings children, not the first instance of a class
I have the following code:

```<code>$(document).on( 'click', '.chevronright', function( event ) {
for (var i=0; i<2; i++){
            var $next =  $(this).siblings('.postlink').find('.post-title').eq(i+1).html();
            $('.row').find('.post-title').eq(i).html($next);
}
</code>```

I have three instances of row, and 3 instances of postlink inside each row, and there is also a chevron in each row. I want it so that when the chevron is clicked, the title from the middle one changes to the left one and the rightmost one changes to the middle one.

What happens is that when i click a chevron in row 2 or row 3, the first row is the one that the actions happen to. It gets the title of the chevron that is the next in line, in the row that I click on but it always happens to the first post-title in the page.  How would I need to refer to the children of the chevrons parent row?

答:
This is a bit "brute force" and sequence dependent but does that: (verbose for clarity)

//chevron is clicked,
$(document).on('click', '.chevronright', function(event) {
  // get the elements with the class
  var myPostlinks = $(this).parent('.row').find('.postlink');
  //the title from the middle one changes to the left one and the rightmost one changes to the middle one.
  // get reference to middle one
  var middleoneNow = myPostlinks.eq(1).find('.post-title');
  // get reference to left one
  var leftoneNow = myPostlinks.eq(0).find('.post-title');
  // Set right to middle (before we change middle)
  myPostlinks.eq(2).find('.post-title').html(middleoneNow.html());
  // Set middle to left now that right is set
  middleoneNow.html(leftoneNow.html());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><style>.row{border:solid cyan 2px;}</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <span class="chevronright">chevron right</span>
  <div class="postlink">
    <span class="post-title">left title</span>
  </div>
  <div class="postlink">
    <span class="post-title">middle title</span>
  </div>
  <div class="postlink">
    <span class="post-title">right title</span>
  </div>
</div>
<div class="row">
  <span class="chevronright">chevron right</span>
  <div class="postlink">
    <span class="post-title">left title</span>
  </div>
  <div class="postlink">
    <span class="post-title">middle title</span>
  </div>
  <div class="postlink">
    <span class="post-title">right title</span>
  </div>
</div>
<div class="row">
  <span class="chevronright">chevron right</span>
  <div class="postlink">
    <span class="post-title">left title</span>
  </div>
  <div class="postlink">
    <span class="post-title">middle title</span>
  </div>
  <div class="postlink">
    <span class="post-title">right title</span>
  </div>
</div>

<!-- begin snippet: js hide: false console: true babel: false --></code>```

For clarity here is an assumption on the markup: (yes it is horrid but demonstrates as here:  https://jsfiddle.net/MarkSchultheiss/vfu10c5k/

Body:
I have the following code:

$(document).on( 'click', '.chevronright', function( event ) {
for (var i=0; i<2; i++){
            var $next =  $(this).siblings('.postlink').find('.post-title').eq(i+1).html();
            $('.row').find('.post-title').eq(i).html($next);
}

I have three instances of row, and 3 instances of postlink inside each row, and there is also a chevron in each row. I want it so that when the chevron is clicked, the title from the middle one changes to the left one and the rightmost one changes to the middle one.

What happens is that when i click a chevron in row 2 or row 3, the first row is the one that the actions happen to. It gets the title of the chevron that is the next in line, in the row that I click on but it always happens to the first post-title in the page.  How would I need to refer to the children of the chevrons parent row?

Body:
This is a bit "brute force" and sequence dependent but does that: (verbose for clarity)

//chevron is clicked,
$(document).on('click', '.chevronright', function(event) {
  // get the elements with the class
  var myPostlinks = $(this).parent('.row').find('.postlink');
  //the title from the middle one changes to the left one and the rightmost one changes to the middle one.
  // get reference to middle one
  var middleoneNow = myPostlinks.eq(1).find('.post-title');
  // get reference to left one
  var leftoneNow = myPostlinks.eq(0).find('.post-title');
  // Set right to middle (before we change middle)
  myPostlinks.eq(2).find('.post-title').html(middleoneNow.html());
  // Set middle to left now that right is set
  middleoneNow.html(leftoneNow.html());
});

<style>.row{border:solid cyan 2px;}</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <span class="chevronright">chevron right</span>
  <div class="postlink">
    <span class="post-title">left title</span>
  </div>
  <div class="postlink">
    <span class="post-title">middle title</span>
  </div>
  <div class="postlink">
    <span class="post-title">right title</span>
  </div>
</div>
<div class="row">
  <span class="chevronright">chevron right</span>
  <div class="postlink">
    <span class="post-title">left title</span>
  </div>
  <div class="postlink">
    <span class="post-title">middle title</span>
  </div>
  <div class="postlink">
    <span class="post-title">right title</span>
  </div>
</div>
<div class="row">
  <span class="chevronright">chevron right</span>
  <div class="postlink">
    <span class="post-title">left title</span>
  </div>
  <div class="postlink">
    <span class="post-title">middle title</span>
  </div>
  <div class="postlink">
    <span class="post-title">right title</span>
  </div>
</div>

<!-- begin snippet: js hide: false console: true babel: false -->

For clarity here is an assumption on the markup: (yes it is horrid but demonstrates as here:  https://jsfiddle.net/MarkSchultheiss/vfu10c5k/


问:
In php strom, I want to add command php aritsan serve system cannot find the file specified

php artisan serve Cannot run program "php" (in directory "E:\xampp\htdocs\eagleeye"): CreateProcess error=2, The system cannot find the file specified

答: settings->command line tool support : remove or disable command))</p>


问:
SQLite, Linq, Foreach: how to optimize performances?
I've developed an UWP app where I use a SQLite database to store datas that are synced.

Among these data, there a lot of tables that contain translated data. For example, for various cases, we have:

a "businness" table, which contains the id that is really used in the database

a "translation" table, which contains transaltion for the business table

The models of the "business" tables are defined like this:

```<code>public class Failure_Type : BasePoco
{
    [PrimaryKey, NotNull]
    public int failure_id { get; set; }

    public int? function_type_id { get; set; }

    public int? component_category_id { get; set; }

    [MaxLength(200), NotNull]
    public string description { get; set; }
    public DateTime? disable_date { get; set; }

    [Ignore]
    public string _descriptionTr { get; set; }
}
</code>```

The field "description" stores the english/default description, and the "_descriptionTr" field will store the translated description.

The models of the "translation" tables are defined like this:

```<code>public class Failure_Type_Translation : BasePoco
{
    [PrimaryKey, NotNull]
    public int failure_type_translation_id { get; set; }

    public int? failure_type_id { get; set; }
    [MaxLength(2)]
    public string language { get; set; }
    [MaxLength(200), NotNull]
    public string description { get; set; }
}
</code>```

The field "failure_type_id" is related to the business table, the other fields store the language code and the related translation.

So, after syncing datas in the SQLite database, I refresh the "translated" datas in the app and this can take a long moment. The load of the the 2 tables from the SQLite is very quickly, but the update of the "_descriptionTr" field can be very slow:

```<code>var failureType = ServiceLocator.Current.GetInstance<IRepository>().GetAll<Failure_Type>();
var failureTypeTranslations = ServiceLocator.Current.GetInstance<IRepository>().GetAll<Failure_Type_Translation>();
FailureType = new ObservableCollection<Failure_Type>();
foreach (var ft in failureType)
{
    var ftt = failureTypeTranslations.FirstOrDefault(i => i.failure_type_id == ft.failure_id && i.language.ToLower().Equals(lang));
    if (ftt != null)
        ft._descriptionTr = ftt.description;
    else
        ft._descriptionTr = ft.description;
    FailureType.Add(ft);
}
</code>```

Is there a better way for doing this?
How could I optimize it?

Edit :

the "business" table contains 550 rows

the "translation" table contains 3500 rows

the duration of the loop is nearly 1 minute

答:
A couple of suggestions:

Create the observable collection at once ...

```<code>FailureType = new ObservableCollection<Failure_Type>(failureType);
</code>```

... so the individual additions don't fire notifications. Now use FailureType in the loop.

Instead of fetching all translations, filter them by lang:

```<code>var failureTypeTranslations = ServiceLocator.Current.GetInstance<IRepository>()
    .GetAll<Failure_Type_Translation>()
    .Where(l => i.language == lang);
</code>```

Create a dictionary for lookup of known translations:

```<code>var dict = failureTypeTranslations.ToDictionary(ftt => ftt.failure_id);
foreach (var ft in FailureType)
{
     Failure_Type_Translation ftt;
     if (dict.TryGetValue(ft.failure_id, out ftt)
         ft._descriptionTr = ftt.description;
     else
         ft._descriptionTr = ft.description;
}
</code>```

I think that esp. the part failureTypeTranslations.FirstOrDefault kills performance. The query is executed for each iteration of the loop.

Body:
I've developed an UWP app where I use a SQLite database to store datas that are synced.

Among these data, there a lot of tables that contain translated data. For example, for various cases, we have:

a "businness" table, which contains the id that is really used in the database

a "translation" table, which contains transaltion for the business table

The models of the "business" tables are defined like this:

public class Failure_Type : BasePoco
{
    [PrimaryKey, NotNull]
    public int failure_id { get; set; }

    public int? function_type_id { get; set; }

    public int? component_category_id { get; set; }

    [MaxLength(200), NotNull]
    public string description { get; set; }
    public DateTime? disable_date { get; set; }

    [Ignore]
    public string _descriptionTr { get; set; }
}

The field "description" stores the english/default description, and the "_descriptionTr" field will store the translated description.

The models of the "translation" tables are defined like this:

public class Failure_Type_Translation : BasePoco
{
    [PrimaryKey, NotNull]
    public int failure_type_translation_id { get; set; }

    public int? failure_type_id { get; set; }
    [MaxLength(2)]
    public string language { get; set; }
    [MaxLength(200), NotNull]
    public string description { get; set; }
}

The field "failure_type_id" is related to the business table, the other fields store the language code and the related translation.

So, after syncing datas in the SQLite database, I refresh the "translated" datas in the app and this can take a long moment. The load of the the 2 tables from the SQLite is very quickly, but the update of the "_descriptionTr" field can be very slow:

var failureType = ServiceLocator.Current.GetInstance<IRepository>().GetAll<Failure_Type>();
var failureTypeTranslations = ServiceLocator.Current.GetInstance<IRepository>().GetAll<Failure_Type_Translation>();
FailureType = new ObservableCollection<Failure_Type>();
foreach (var ft in failureType)
{
    var ftt = failureTypeTranslations.FirstOrDefault(i => i.failure_type_id == ft.failure_id && i.language.ToLower().Equals(lang));
    if (ftt != null)
        ft._descriptionTr = ftt.description;
    else
        ft._descriptionTr = ft.description;
    FailureType.Add(ft);
}

Is there a better way for doing this?
How could I optimize it?

Edit :

the "business" table contains 550 rows

the "translation" table contains 3500 rows

the duration of the loop is nearly 1 minute

Body:
A couple of suggestions:

Create the observable collection at once ...

FailureType = new ObservableCollection<Failure_Type>(failureType);

... so the individual additions don't fire notifications. Now use FailureType in the loop.

Instead of fetching all translations, filter them by lang:

var failureTypeTranslations = ServiceLocator.Current.GetInstance<IRepository>()
    .GetAll<Failure_Type_Translation>()
    .Where(l => i.language == lang);

Create a dictionary for lookup of known translations:

var dict = failureTypeTranslations.ToDictionary(ftt => ftt.failure_id);
foreach (var ft in FailureType)
{
     Failure_Type_Translation ftt;
     if (dict.TryGetValue(ft.failure_id, out ftt)
         ft._descriptionTr = ftt.description;
     else
         ft._descriptionTr = ft.description;
}

I think that esp. the part failureTypeTranslations.FirstOrDefault kills performance. The query is executed for each iteration of the loop.


问:
D3 Javascript - Probable issue with nested function -- generates console error
Hello again Stackoverflow.   As is usually the case, once you fix the initial problem you gain another.   Yesterday I posted a question regarding
implementing a D3 Visualization.  My question was answered lickety-split by Sparta93 (maybe you can help on this one too).

As I pointed out I am actually embedding the D3 Viz inside a packaged application, Oracle Big Data Discovery (BDD).  BDD uses a Visualization
renderer to display the chart.   This requires the JS block to be inside a Chart function (the entire body of code is in a linked JS Fiddle below for ease of reading and review):

```<code>renderChart: function(queryResults) {
</code>```

When I run the code it generates an error that
Stratify is not a function.

```<code>Uncaught TypeError: d3.stratify is not a function
at S.renderChart (script:44)
at S.executeQueryCallback (eval at globalEval (barebone.jsp:4), <anonymous>:1:3460)
at S.handleResize (eval at globalEval (barebone.jsp:4), <anonymous>:1:3751)
at constructor.resizeListener (eval at globalEval (barebone.jsp:4), <anonymous>:1:17193)
at Object.run (eval at globalEval (barebone.jsp:4), <anonymous>:1:16634)
at i (barebone.jsp:32)
</code>```

If I reorder the code and place Cluster first I get a similar error.

I suspect the issue is related to the fact that these two functions being inside "renderChart: function(queryResults)".    I am DBA, Big Data and BI guy so my
JS skills are quite modest.  I likely barely hacked the code together enough to get it to work.    I have much simplier viz working in BDD that does
not error out.  It does not however have any sub-functions

Here is a Fiddle where the code works as expected (thanks to Sparta93). Chart working in "normal" context:  https://jsfiddle.net/hb4oLy2x/

Here is a Fiddle just for simplicity of posting all the code.  It will not run because it depends on the server-side BDD Visualization Renderer.   I placed some comments around the elements that I believe are the issue.  Chart not working in BDD context (this is the code with the issue):  https://jsfiddle.net/sx7oaput/

Here is a Fiddle where I removed the URI for d3 v4.  Interestingly it creates a similar error in the Console.  Chart code that simulates error (maybe just a coincidence):  https://jsfiddle.net/u48o39k2/

Here is a another Fiddle for simplicity of sharing the code.  This does render the Bar Chart and HTML table successfully in BDD.  Chart that does work in BDD context:  https://jsfiddle.net/j7r9f743/

Guidance, advice, and/or help are greatly appreciated.

答:
I tried looking at other courses of action because I knew that some visualizations did in fact work.  I found this code on line and when I extracted the individual pieces and tested replacements in the working code, I got it to work.

```<code>var tree = d3.layout.tree()
.size([360, diameter / 2 - 80])
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 10) / a.depth; });

var diagonal = d3.svg.diagonal.radial()
    .projection(function(d) { return [d.y, d.x / 180 * Math.PI]; });
</code>```

http://codepen.io/anon/pen/xItvw

Many thanks to "CAPTAIN ANONYMOUS" the author of the Code Pen (lol).

Body:
Hello again Stackoverflow.   As is usually the case, once you fix the initial problem you gain another.   Yesterday I posted a question regarding
implementing a D3 Visualization.  My question was answered lickety-split by Sparta93 (maybe you can help on this one too).

As I pointed out I am actually embedding the D3 Viz inside a packaged application, Oracle Big Data Discovery (BDD).  BDD uses a Visualization
renderer to display the chart.   This requires the JS block to be inside a Chart function (the entire body of code is in a linked JS Fiddle below for ease of reading and review):

renderChart: function(queryResults) {

When I run the code it generates an error that
Stratify is not a function.

Uncaught TypeError: d3.stratify is not a function
at S.renderChart (script:44)
at S.executeQueryCallback (eval at globalEval (barebone.jsp:4), <anonymous>:1:3460)
at S.handleResize (eval at globalEval (barebone.jsp:4), <anonymous>:1:3751)
at constructor.resizeListener (eval at globalEval (barebone.jsp:4), <anonymous>:1:17193)
at Object.run (eval at globalEval (barebone.jsp:4), <anonymous>:1:16634)
at i (barebone.jsp:32)

If I reorder the code and place Cluster first I get a similar error.

I suspect the issue is related to the fact that these two functions being inside "renderChart: function(queryResults)".    I am DBA, Big Data and BI guy so my
JS skills are quite modest.  I likely barely hacked the code together enough to get it to work.    I have much simplier viz working in BDD that does
not error out.  It does not however have any sub-functions

Here is a Fiddle where the code works as expected (thanks to Sparta93). Chart working in "normal" context:  https://jsfiddle.net/hb4oLy2x/

Here is a Fiddle just for simplicity of posting all the code.  It will not run because it depends on the server-side BDD Visualization Renderer.   I placed some comments around the elements that I believe are the issue.  Chart not working in BDD context (this is the code with the issue):  https://jsfiddle.net/sx7oaput/

Here is a Fiddle where I removed the URI for d3 v4.  Interestingly it creates a similar error in the Console.  Chart code that simulates error (maybe just a coincidence):  https://jsfiddle.net/u48o39k2/

Here is a another Fiddle for simplicity of sharing the code.  This does render the Bar Chart and HTML table successfully in BDD.  Chart that does work in BDD context:  https://jsfiddle.net/j7r9f743/

Guidance, advice, and/or help are greatly appreciated.

Body:
I tried looking at other courses of action because I knew that some visualizations did in fact work.  I found this code on line and when I extracted the individual pieces and tested replacements in the working code, I got it to work.

var tree = d3.layout.tree()
.size([360, diameter / 2 - 80])
.separation(function(a, b) { return (a.parent == b.parent ? 1 : 10) / a.depth; });

var diagonal = d3.svg.diagonal.radial()
    .projection(function(d) { return [d.y, d.x / 180 * Math.PI]; });

http://codepen.io/anon/pen/xItvw

Many thanks to "CAPTAIN ANONYMOUS" the author of the Code Pen (lol).


问:
Gson can't deserialize multiple type List
I have a class which holds other objects in an ArrayList:

```<code>class Program {
    @Expose
    private List<BaseData> dataList;
}
</code>```

And I have other classes:

```<code>class BaseData {
    @Expose
    String name;
}

class Data extends BaseData {
    @Expose
    String description;
}

class DataA extends Data{
    @Expose
    String a;
}

class DataB extends Data{
    @Expose
    String b;
}
</code>```

When I would like to serialize it:

```<code>Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Log.d(TAG, gson.toJson(myProgram));
</code>```

I can see only the keys which I have in BaseData. My list in my Program object contains DataA, DataB and Data objects too.

How can I fix this?

Update:

So my program work like this: it does stuff and fills the Program's list with data. Than I save it: I use Gson to turn the Program to a json string. I use Shared Preferences.
Than when I open up the app again, it loads the previously saved json string. I Log.d it, and everything is cool.

Than

I would like to create a Program object from that json.

```<code>Gson gson = new Gson();
instance = gson.fromJson(savedJson, Program.class);
</code>```

And after I serialize it again with Gson happens what I wrote above. So it seems that it only creates BaseData objects from the json.

答:
I found the Solution.

Btw. It feels like a bit "brute force" method.

```<code>Gson gson = new Gson();
JSONObject progJsonObj = new JSONObject(json);
progJsonObj.clearDataList();
JSONArray dataList= reader.getJSONArray("dataList");
Program program = gson.fromJson(progJsonObj.toString());
for (int i = 0; i < dataList.length(); i++) {
    JSONObject blockData = blocksInProgram.getJSONObject(i);
    // Added new class variable of the base class
    String type = blockData.getString("dataType");
    if (type.equals("data_a")) {
        DataA d = gson.fromJson(blockData.toString(), DataA.class);
        program.addData(d);
    } else if (type.equals("data_b")){
        DataB d = gson.fromJson(blockData.toString(), DataB.class);
        program.addData(d);
    }
}
</code>```

Body:
I have a class which holds other objects in an ArrayList:

class Program {
    @Expose
    private List<BaseData> dataList;
}

And I have other classes:

class BaseData {
    @Expose
    String name;
}

class Data extends BaseData {
    @Expose
    String description;
}

class DataA extends Data{
    @Expose
    String a;
}

class DataB extends Data{
    @Expose
    String b;
}

When I would like to serialize it:

Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
Log.d(TAG, gson.toJson(myProgram));

I can see only the keys which I have in BaseData. My list in my Program object contains DataA, DataB and Data objects too.

How can I fix this?

Update:

So my program work like this: it does stuff and fills the Program's list with data. Than I save it: I use Gson to turn the Program to a json string. I use Shared Preferences.
Than when I open up the app again, it loads the previously saved json string. I Log.d it, and everything is cool.

Than

I would like to create a Program object from that json.

Gson gson = new Gson();
instance = gson.fromJson(savedJson, Program.class);

And after I serialize it again with Gson happens what I wrote above. So it seems that it only creates BaseData objects from the json.

Body:
I found the Solution.

Btw. It feels like a bit "brute force" method.

Gson gson = new Gson();
JSONObject progJsonObj = new JSONObject(json);
progJsonObj.clearDataList();
JSONArray dataList= reader.getJSONArray("dataList");
Program program = gson.fromJson(progJsonObj.toString());
for (int i = 0; i < dataList.length(); i++) {
    JSONObject blockData = blocksInProgram.getJSONObject(i);
    // Added new class variable of the base class
    String type = blockData.getString("dataType");
    if (type.equals("data_a")) {
        DataA d = gson.fromJson(blockData.toString(), DataA.class);
        program.addData(d);
    } else if (type.equals("data_b")){
        DataB d = gson.fromJson(blockData.toString(), DataB.class);
        program.addData(d);
    }
}


问:
efficient merge when static data
I have some static data stored in the data frame static_data. The goal is to merge the data with the static_data in order to obtain the output

```<code>data <- data.frame(A = c("a","b","c","d","e"),B=c("a","b","b","e","e"))

static_data <- data.frame(I=c("a","b","c","d","e"),Info=c(1,2,3,4,5))

output <- data.frame(A = c("a","b","c","d","e"),B=c("a","b","b","e","e"),
                     AI=c(1,2,3,4,5),BI=c(1,2,2,5,5))
</code>```

my code is the following

```<code>colnames(data) <- c("I","B")
temp <- merge(data, static_data,by="I)
</code>```

and so one. what's the best way to have an efficient code?

答:
You can try this:</p>

```<code>mg <- merge(data, static_data, by.x = "A", by.y = "I")
cbind(mg, BI=merge(data, static_data, by.x = "B", by.y = "I")[,3])

#  A B Info BI
#1 a a    1  1
#2 b b    2  2
#3 c b    3  2
#4 d e    4  5
#5 e e    5  5
</code>```

Title: efficient merge when static data

Body:
I have some static data stored in the data frame static_data. The goal is to merge the data with the static_data in order to obtain the output

data <- data.frame(A = c("a","b","c","d","e"),B=c("a","b","b","e","e"))

static_data <- data.frame(I=c("a","b","c","d","e"),Info=c(1,2,3,4,5))

output <- data.frame(A = c("a","b","c","d","e"),B=c("a","b","b","e","e"),
                     AI=c(1,2,3,4,5),BI=c(1,2,2,5,5))

my code is the following

colnames(data) <- c("I","B")
temp <- merge(data, static_data,by="I)

and so one. what's the best way to have an efficient code?

Body:
You can try this:

mg <- merge(data, static_data, by.x = "A", by.y = "I")
cbind(mg, BI=merge(data, static_data, by.x = "B", by.y = "I")[,3])

#  A B Info BI
#1 a a    1  1
#2 b b    2  2
#3 c b    3  2
#4 d e    4  5
#5 e e    5  5


问:
Android Studio Intent Not working
i am trying to start a new activity when a user click a imageView...
the imageView is on CardView.
I have added the Intent to the .java but still the app crashes..
here is my code

```<code>    package com.example.rishav.thisiscarsearch20;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MarutiSuzukiScrollingActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_maruti_suzuki_scrolling);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        }
    public void onBaleno (View view){
        Intent baleno = new Intent(this, LoginActivity.class);
        startActivity(baleno);
    }

}
</code>```

XML

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/onmarutiselectcars"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.rishav.thisiscarsearch20.MarutiSuzukiScrollingActivity">
<android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:paddingBottom="8dp"
            app:cardCornerRadius="10dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/textView12"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="8dp"
                    android:layout_marginBottom="8dp"
                    android:text="Maruti Baleno"
                    android:textAlignment="center"
                    android:textSize="20sp"
                    android:textStyle="normal|bold" />

                <ImageView
                    android:id="@+id/baleno01"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@drawable/balenointro"
                    android:onClick="onBaleno" />

                <TextView
                    android:id="@+id/textview01"
                    android:layout_width="273dp"
                    android:layout_height="wrap_content"
                    android:layout_margin="8dp"
                    android:text="Price :  5.3 - 8.7 Lakh"
                    android:textSize="18sp" />

            </LinearLayout>

        </android.support.v7.widget.CardView>

    </LinearLayout>
</android.support.v4.widget.NestedScrollView>
</code>```

when i run this on emulator i get the following error

E/AndroidRuntime: FATAL EXCEPTION: main
                    Process: com.example.rishav.thisiscarsearch20, PID: 2407
                    java.lang.IllegalStateException: Could not find method please(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageView with id 'baleno01'
                        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
                        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
                        at android.view.View.performClick(View.java:5198)
                        at android.view.View$PerformClick.run(View.java:21147)
                        at android.os.Handler.handleCallback(Handler.java:739)
                        at android.os.Handler.dispatchMessage(Handler.java:95)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:5417)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

答:
```<code>public void onBaleno (View view){
    Intent baleno = new Intent(getApplicationContext(), LoginActivity.class);
    startActivity(baleno);
}
</code>```

Hope it helps!

Title: Android Studio Intent Not working

Body:
i am trying to start a new activity when a user click a imageView...
the imageView is on CardView.
I have added the Intent to the .java but still the app crashes..
here is my code

    package com.example.rishav.thisiscarsearch20;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MarutiSuzukiScrollingActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_maruti_suzuki_scrolling);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        }
    public void onBaleno (View view){
        Intent baleno = new Intent(this, LoginActivity.class);
        startActivity(baleno);
    }

}

XML

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/onmarutiselectcars"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.rishav.thisiscarsearch20.MarutiSuzukiScrollingActivity">
<android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:paddingBottom="8dp"
            app:cardCornerRadius="10dp">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/textView12"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="8dp"
                    android:layout_marginBottom="8dp"
                    android:text="Maruti Baleno"
                    android:textAlignment="center"
                    android:textSize="20sp"
                    android:textStyle="normal|bold" />

                <ImageView
                    android:id="@+id/baleno01"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:background="@drawable/balenointro"
                    android:onClick="onBaleno" />

                <TextView
                    android:id="@+id/textview01"
                    android:layout_width="273dp"
                    android:layout_height="wrap_content"
                    android:layout_margin="8dp"
                    android:text="Price :  5.3 - 8.7 Lakh"
                    android:textSize="18sp" />

            </LinearLayout>

        </android.support.v7.widget.CardView>

    </LinearLayout>
</android.support.v4.widget.NestedScrollView>

when i run this on emulator i get the following error

E/AndroidRuntime: FATAL EXCEPTION: main
                    Process: com.example.rishav.thisiscarsearch20, PID: 2407
                    java.lang.IllegalStateException: Could not find method please(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatImageView with id 'baleno01'
                        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
                        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
                        at android.view.View.performClick(View.java:5198)
                        at android.view.View$PerformClick.run(View.java:21147)
                        at android.os.Handler.handleCallback(Handler.java:739)
                        at android.os.Handler.dispatchMessage(Handler.java:95)
                        at android.os.Looper.loop(Looper.java:148)
                        at android.app.ActivityThread.main(ActivityThread.java:5417)
                        at java.lang.reflect.Method.invoke(Native Method)
                        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Body:
public void onBaleno (View view){
    Intent baleno = new Intent(getApplicationContext(), LoginActivity.class);
    startActivity(baleno);
}

Hope it helps!


问:
Spark - avro data not visible when queried from hive
I am creating dataframe using spark avro like

```<code>dataframe.write.format("com.databricks.spark.avro").save(outputPath)
</code>```

The output path in my case will be like hdfs path + table_name + partition

The table table_name is already created in hive using AvroSerDe where the LOCATION is set to outputPath.

However the created dataframe is not visible when I do a select * for table_name from hive. What could be issue

答:
What is happening here is that .save doesn't update the Hive Metastore, and so the new data isn't visible from your query.

You could try with dataframe.write().mode(SaveMode.Append).partitionBy("partition").saveAsTable("table_name") to append data into your table.

Body:
I am creating dataframe using spark avro like

dataframe.write.format("com.databricks.spark.avro").save(outputPath)

The output path in my case will be like hdfs path + table_name + partition

The table table_name is already created in hive using AvroSerDe where the LOCATION is set to outputPath.

However the created dataframe is not visible when I do a select * for table_name from hive. What could be issue


问:
Traversing a binary tree using linked list
I am trying to do a preorder traversal of binary tree using a linked list.

```<code>class BTNode:
"""A node in a binary tree."""

    def __init__(self: 'BTNode', item: object,
             left: 'BTNode' =None, right: 'BTNode' =None) -> None:

        self.item, self.left, self.right = item, left, right

class LLNode:
    """A node in a linked list."""

    def __init__(self: 'LLNode', item: object, link: 'LLNode' =None) -> None:

        self.item, self.link = item, link

    def __str__(self: 'LLNode') -> str:
        """Return an informative string showing self

        >>> b = LLNode(1, LLNode(2, LLNode(3)))
        >>> str(b)
        '1 -> 2 -> 3'
        """
        return str(self.item) + (' -> ' + str(self.link) if self.link else '')

def preorder(root: BTNode) -> LLNode:
    """Return the first node in a linked list that contains every value from the
    binary tree rooted at root, listed according to an preorder traversal.

    >>> b = BTNode(1, BTNode(2), BTNode(3))
    >>> repr(preorder(b))
   'LLNode(1, LLNode(2, LLNode(3)))'
   >>> b2 = BTNode(4, BTNode(5))
   >>> b3 = BTNode(7, b, b2)
   >>> str(preorder(b3))
   '7 -> 1 -> 2 -> 3 -> 4 -> 5'
    """

    return _preorder(root)[0]

def _preorder(root: BTNode) -> (LLNode, LLNode):
    """Return the first and last nodes in a linked list that contains every
    value from the binary tree rooted at root, listed according to an preorder
    traversal.
    """

    if not root:
        return None, None

    left_head, left_tail = _preorder(root.left)

    right_head, right_tail = _preorder(root.right)

    # change from right_tail = left_tail to right_tail = left_head
    if not right_tail:
        right_tail = left_head

    if not left_head:
        left_head = right_head

    if left_tail:
        left_tail.link = right_head

    root_node = LLNode(root.item, left_head)

    return root_node, right_tail
</code>```

I am always getting '7 -> 1 -> 2' instead of '7 -> 1 -> 2 -> 3 -> 4 -> 5' as my output in preorder function. I am not quite sure why. Could someone please tell me how I can edit my current code to fix this problem?

答:
You appear to have an error in your preorder code dealing with returns like LLNode(value, None).

Specifically, when you are traversing BTNode(a, BTNode(b), BTNode(c)) where neither b nor c has children, you don't merge correctly. You'll want to have another look at your logic for this case.

Body:
I am trying to do a preorder traversal of binary tree using a linked list.

class BTNode:
"""A node in a binary tree."""

    def __init__(self: 'BTNode', item: object,
             left: 'BTNode' =None, right: 'BTNode' =None) -> None:

        self.item, self.left, self.right = item, left, right

class LLNode:
    """A node in a linked list."""

    def __init__(self: 'LLNode', item: object, link: 'LLNode' =None) -> None:

        self.item, self.link = item, link

    def __str__(self: 'LLNode') -> str:
        """Return an informative string showing self

        >>> b = LLNode(1, LLNode(2, LLNode(3)))
        >>> str(b)
        '1 -> 2 -> 3'
        """
        return str(self.item) + (' -> ' + str(self.link) if self.link else '')

def preorder(root: BTNode) -> LLNode:
    """Return the first node in a linked list that contains every value from the
    binary tree rooted at root, listed according to an preorder traversal.

    >>> b = BTNode(1, BTNode(2), BTNode(3))
    >>> repr(preorder(b))
   'LLNode(1, LLNode(2, LLNode(3)))'
   >>> b2 = BTNode(4, BTNode(5))
   >>> b3 = BTNode(7, b, b2)
   >>> str(preorder(b3))
   '7 -> 1 -> 2 -> 3 -> 4 -> 5'
    """

    return _preorder(root)[0]

def _preorder(root: BTNode) -> (LLNode, LLNode):
    """Return the first and last nodes in a linked list that contains every
    value from the binary tree rooted at root, listed according to an preorder
    traversal.
    """

    if not root:
        return None, None

    left_head, left_tail = _preorder(root.left)

    right_head, right_tail = _preorder(root.right)

    # change from right_tail = left_tail to right_tail = left_head
    if not right_tail:
        right_tail = left_head

    if not left_head:
        left_head = right_head

    if left_tail:
        left_tail.link = right_head

    root_node = LLNode(root.item, left_head)

    return root_node, right_tail

I am always getting '7 -> 1 -> 2' instead of '7 -> 1 -> 2 -> 3 -> 4 -> 5' as my output in preorder function. I am not quite sure why. Could someone please tell me how I can edit my current code to fix this problem?


问:
Undefined Index PHP, MySQL, PhpMyAdmin
Error:

( ! ) Notice: Undefined index: VIN in C:\wamp\www\php\myJoyofPHP\viewcar.php on line 10

```<code>09 <?php include 'db.php';
10 $vin = $_GET['VIN'];
11 $query = "SELECT * FROM INVENTORY";
12 /* Try to query the database */
13 if($result = $mysqli->query($query)){
14 //Don't do anything if successful.
15 }
16 else
17 {
18 echo "Sorry, a vehicle with VIN of $vin cannot be found ".mysql_error()."<br>";
19 }
20
21 //Loop through all the rows returned by the query, creating a table row for each
22 while ($result_ar = mysqli_fetch_assoc($result)){
23  $year = $result_ar['YEAR'];
24  $make = $result_ar['Make'];
25  $model = $result_ar['Model'];
26  $trim = $result_ar['TRIM'];
27  $color = $result_ar['EXT_COLOR'];
28  $interior = $result_ar['INT_COLOR'];
29  $mileage = $result_ar['MILEAGE'];
30  $transmission = $result_ar['TRANSMISSION'];
31  $price = $result_ar['ASKING_PRICE'];
32 }
33 echo "$year $make $model </p>";
34 echo "<p>Asking Price: $price </p>";
35 echo "<p>Exterior Color: $color </p>";
36 echo "<p>Interior Color: $interior </p>";
37
38 $mysqli->close();
39 ?>
</code>```

I'm not concerned about security at the moment because I am just learning the basics as of now. So please don't respond saying that it's vulnerable code, I know.

I have a Column named 'VIN' in the 'cars' database within PhpMyAdmin with multiple values in it but For some reason this error comes up. Also, underneath the error, a single data set appears.

Why would I be getting this error?
Why would I be getting the error especially if a database exists with the same column name 'VIN'?
When I enter the following code above it, there is a variable error too.

```<code>$value = isset($array['VIN']) ? $array['VIN'] : '';
$value = array_key_exists('VIN', $array) ? $array['VIN'] : '';
</code>```

Also, this is the db.php file that is included:

```<code><?php
//localhost, root, password, database
$mysqli = new mysqli('localhost','root','','cars');
/*check connection */
if (mysqli_connect_errno()){
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//select a database to work with
$mysqli->select_db("cars");

?>
</code>```

As I mentioned, I understand this is a vulnerable database. There is no password. Please don't post anything regarding that, as I need to fully understand the basics. Thank you.

答:
Short and simple:

```<code>$vin = @$_GET['VIN'];
</code>```

If VIN was not fed in

There will be no error message;

$vin will be NULL.

Later, you can use if (isset($vin)) ..., which reads easily.

Title: Undefined Index PHP, MySQL, PhpMyAdmin

Body:
Error:

( ! ) Notice: Undefined index: VIN in C:\wamp\www\php\myJoyofPHP\viewcar.php on line 10

09 <?php include 'db.php';
10 $vin = $_GET['VIN'];
11 $query = "SELECT * FROM INVENTORY";
12 /* Try to query the database */
13 if($result = $mysqli->query($query)){
14 //Don't do anything if successful.
15 }
16 else
17 {
18 echo "Sorry, a vehicle with VIN of $vin cannot be found ".mysql_error()."
";
19 }
20
21 //Loop through all the rows returned by the query, creating a table row for each
22 while ($result_ar = mysqli_fetch_assoc($result)){
23  $year = $result_ar['YEAR'];
24  $make = $result_ar['Make'];
25  $model = $result_ar['Model'];
26  $trim = $result_ar['TRIM'];
27  $color = $result_ar['EXT_COLOR'];
28  $interior = $result_ar['INT_COLOR'];
29  $mileage = $result_ar['MILEAGE'];
30  $transmission = $result_ar['TRANSMISSION'];
31  $price = $result_ar['ASKING_PRICE'];
32 }
33 echo "$year $make $model
";
34 echo "
Asking Price: $price
";
35 echo "
Exterior Color: $color
";
36 echo "
Interior Color: $interior
";
37
38 $mysqli->close();
39 ?>

I'm not concerned about security at the moment because I am just learning the basics as of now. So please don't respond saying that it's vulnerable code, I know.

I have a Column named 'VIN' in the 'cars' database within PhpMyAdmin with multiple values in it but For some reason this error comes up. Also, underneath the error, a single data set appears.

Why would I be getting this error?
Why would I be getting the error especially if a database exists with the same column name 'VIN'?
When I enter the following code above it, there is a variable error too.

$value = isset($array['VIN']) ? $array['VIN'] : '';
$value = array_key_exists('VIN', $array) ? $array['VIN'] : '';

Also, this is the db.php file that is included:

<?php
//localhost, root, password, database
$mysqli = new mysqli('localhost','root','','cars');
/*check connection */
if (mysqli_connect_errno()){
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//select a database to work with
$mysqli->select_db("cars");

?>

As I mentioned, I understand this is a vulnerable database. There is no password. Please don't post anything regarding that, as I need to fully understand the basics. Thank you.

Body:
Short and simple:

$vin = @$_GET['VIN'];

If VIN was not fed in

There will be no error message;

$vin will be NULL.

Later, you can use if (isset($vin)) ..., which reads easily.