问:
Why isn't my Weather Underground data not printing in Swift 3?
I'm having an issue printing data from Weather Underground. My code works with other data sources, just not Weather Underground. I have even tried replacing the URL with actual data (i.e. https://api.wunderground.com/api/APIKEY/forecast/geolookup/forecast/q/94129.json"), but it doesn't print.

Any suggestions on what it could be?

```<code>import Foundation
import UIKit

class APIManager {
    func weatherJSON(zip: String, completion: @escaping ([Weather]) -> Void) {
        let baseUrlString = "https://api.wunderground.com/api/APIKEY/forecast/geolookup/forecast/q/\(zip).json"

        guard let url = URL(string: baseUrlString) else { return }

        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard error == nil, let data = data else { return }

            do {
                guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] else { return }

                // MARK: Print JSON
                print(json)

                var weatherList = [Weather]()
                for item in json {
                    if let weather = Weather.create(from: item) {
                        weatherList.append(weather)
                    }
                }
                completion(weatherList)
            } catch {
                print("Uh oh. You have an error with \(zip)!")
            }
        }
        task.resume()
    }
}
</code>```

EDIT: SOLVED

I have used the code posted below and am now seeing errors.

答:
I'd suggest changing this to report errors:

```<code>enum WeatherError Error {
    case badURL
    case invalidJSON
}

func weatherJSON(zip: String, completion: @escaping ([Weather]?, Error?) -> Void) {
    let baseUrlString = "https://api.wunderground.com/api/APIKEY/forecast/geolookup/forecast/q/\(zip).json"

    guard let url = URL(string: baseUrlString) else {
        completion(nil, WeatherError.badURL)
        return
    }

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard error == nil, let data = data else {
            completion(nil, error)
            return
        }

        do {
            guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] else {
                completion(nil, WeatherError.invalidJSON)
                return
            }

            // MARK: Print JSON
            print(json)

            var weatherList = [Weather]()
            for item in json {
                if let weather = Weather.create(from: item) {
                    weatherList.append(weather)
                }
            }
            completion(weatherList, nil)
        } catch let parseError {
            print("Uh oh. You have an error with \(zip)!")
            if let responseString = String(data: data, encoding: .utf8) {
                print("responseString = \(responseString)")
            }
            completion(nil, parseError)
        }
    }
    task.resume()
}
</code>```

Then, when you call it, you can see what the error was

```<code>weatherJSON(zip: something) { weatherReports, error in
    guard let weatherReports = weatherReports, error == nil else {
        print(error)
        return
    }

    // use weatherReports here
}
</code>```

This won't solve your problem, but it will help you diagnose what the issue is.

Body:
I'm having an issue printing data from Weather Underground. My code works with other data sources, just not Weather Underground. I have even tried replacing the URL with actual data (i.e. https://api.wunderground.com/api/APIKEY/forecast/geolookup/forecast/q/94129.json"), but it doesn't print.

Any suggestions on what it could be?

import Foundation
import UIKit

class APIManager {
    func weatherJSON(zip: String, completion: @escaping ([Weather]) -> Void) {
        let baseUrlString = "https://api.wunderground.com/api/APIKEY/forecast/geolookup/forecast/q/\(zip).json"

        guard let url = URL(string: baseUrlString) else { return }

        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            guard error == nil, let data = data else { return }

            do {
                guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] else { return }

                // MARK: Print JSON
                print(json)

                var weatherList = [Weather]()
                for item in json {
                    if let weather = Weather.create(from: item) {
                        weatherList.append(weather)
                    }
                }
                completion(weatherList)
            } catch {
                print("Uh oh. You have an error with \(zip)!")
            }
        }
        task.resume()
    }
}

EDIT: SOLVED

I have used the code posted below and am now seeing errors.

Body:
I'd suggest changing this to report errors:

enum WeatherError Error {
    case badURL
    case invalidJSON
}

func weatherJSON(zip: String, completion: @escaping ([Weather]?, Error?) -> Void) {
    let baseUrlString = "https://api.wunderground.com/api/APIKEY/forecast/geolookup/forecast/q/\(zip).json"

    guard let url = URL(string: baseUrlString) else {
        completion(nil, WeatherError.badURL)
        return
    }

    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        guard error == nil, let data = data else {
            completion(nil, error)
            return
        }

        do {
            guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] else {
                completion(nil, WeatherError.invalidJSON)
                return
            }

            // MARK: Print JSON
            print(json)

            var weatherList = [Weather]()
            for item in json {
                if let weather = Weather.create(from: item) {
                    weatherList.append(weather)
                }
            }
            completion(weatherList, nil)
        } catch let parseError {
            print("Uh oh. You have an error with \(zip)!")
            if let responseString = String(data: data, encoding: .utf8) {
                print("responseString = \(responseString)")
            }
            completion(nil, parseError)
        }
    }
    task.resume()
}

Then, when you call it, you can see what the error was

weatherJSON(zip: something) { weatherReports, error in
    guard let weatherReports = weatherReports, error == nil else {
        print(error)
        return
    }

    // use weatherReports here
}

This won't solve your problem, but it will help you diagnose what the issue is.


来源: stackexchange

问:
Linq with MongDB Error with Where Clause
I have this code:

```<code>Imports MongoDB.Bson
Imports MongoDB.Driver
Imports MongoDB.Driver.Linq

Public Class Principal

Private Sub Find

    Dim mongo As New MongoClient("mongodb://localhost")
    Dim db = mongo.GetDatabase("test")

    Dim Tipos = db.GetCollection(Of TipoDeIdentificacion).("TiposDeIdentificacion")
</code>```

These work fine:

```<code>Dim query = Tipos.AsQueryable.OrderByDescending(Function(X) X.id).ToList
Dim query1 = Tipos.AsQueryable.Where(Function(X)  x.Nombre.Contains("DNI")).ToList
</code>```

These doesn't work:

```<code>Dim query2 = Tipos.AsQueryable.Where(Function(X) X.Nombre = "DNI").ToList
</code>```

Exception thrown:

CompareString({document}{Nombre}, "DNI", False) is not supported.

¿Any idea?

答:
i had the same probem.
For me, this code works </p>

```<code>Dim query2 = Tipos.AsQueryable.Where(Function(X) X.Nombre.Equals("DNI")).ToList
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have this code:

Imports MongoDB.Bson
Imports MongoDB.Driver
Imports MongoDB.Driver.Linq

Public Class Principal

Private Sub Find

    Dim mongo As New MongoClient("mongodb://localhost")
    Dim db = mongo.GetDatabase("test")

    Dim Tipos = db.GetCollection(Of TipoDeIdentificacion).("TiposDeIdentificacion")

These work fine:

Dim query = Tipos.AsQueryable.OrderByDescending(Function(X) X.id).ToList
Dim query1 = Tipos.AsQueryable.Where(Function(X)  x.Nombre.Contains("DNI")).ToList

These doesn't work:

Dim query2 = Tipos.AsQueryable.Where(Function(X) X.Nombre = "DNI").ToList

Exception thrown:

CompareString({document}{Nombre}, "DNI", False) is not supported.

¿Any idea?

Body:
i had the same probem.
For me, this code works

Dim query2 = Tipos.AsQueryable.Where(Function(X) X.Nombre.Equals("DNI")).ToList


问:
Closing Menu on Outside Click on page with iFrames
I'm trying to use the trick outlined on this answer to close a navigation menu on a page I've designed. However, the majority of the space on the page is taken up by an iframe that loads articles stored on the same server as the page containing the iframe.

If I click on any of the elements on the parent page, the menu closes as it should. However, clicking on any of the space within the iframe does not close the menu.

I'm assuming this is because the parent page does not capture events happening inside of the iframe. Like I've said, both pages are stored on the same server, so how can I capture the click to close my menu when the user clicks within the iframe?

HTML:

```<code><div id="menucontainer">
<nav id="mobilemenu">
    <ul>
        <li><span class="menutrigger">☰ Menu</span></li>
    </ul>
</nav>
<nav id="fullmenu">
    <ul>
        <li><a href="page1.html" target="content">Menu Item 1</a></li>
        <li><a href="page2.html" target="content">Menu Item 2</a></li>
        <li><a href="page3.html" target="content">Menu Item 3</a></li>
        <li><a href="page4.html" target="content">Menu Item 4</a></li>
    </ul>
</nav>
</div>
<div id="frame">
        <iframe name="content" id="content" src="intro.html"></iframe>
</div>
</code>```

JQuery:

```<code>$(document).ready(function() {
    $("a[target='content']").click(function() {
        if ($("#mobilemenu").css("display") == "block" ){
            $('#fullmenu').hide();
        }
    });
    $('html').click(function() {
        $('#fullmenu').hide();
    });
    $('#menucontainer').click(function(event){
        event.stopPropagation();
    });
    $('.menutrigger').click(function() {
        $('#fullmenu').toggle();
    });
});
</code>```

CSS: (Added because it occurred to me it might be affecting things)

```<code>html, body { height: 100%; width: 100%; }

nav, #frame { position: absolute; right: 0; left: 0; padding: 0; margin: 0; width: 100%; }

#content { height: 100%; width: 100%; }

#frame { top: 38px; bottom: 14px; }

nav { width: 100%; z-index: 100; }

#fullmenu { display: none; position: absolute; top: 38px; width: 100%; }

#mobilemenu { display: block; height: 38px; top: 0; background: #333; }

.menutrigger { font-size: 20px; font-weight: bold; padding: 1px 8px; color: #FFF; cursor: pointer; }

#frame { top: 38px; bottom: 14px; }

nav ul { position: relative; width: 100%; background: #333; list-style: none; display: inline-block; padding: 0; }

nav ul:after { clear: both; }

nav ul li { height: 29px; float: none; min-width: 110px; font-size: 14px; padding: 4px 4px; font-family: 'Roboto Condensed', sans-serif; }

nav ul li a { display: block; padding: 5px; color: #FFF; text-decoration: none; }

nav ul li:hover { background: #666; display: inline-block; height: 29px; }

nav ul li:hover a { color: #FFF; }
</code>```

答: The contents().click() does not work when the iframe is on a different domain. You'll get a cross-domain access error attempting to make the contents() call.</p>

Body:
I'm trying to use the trick outlined on this answer to close a navigation menu on a page I've designed. However, the majority of the space on the page is taken up by an iframe that loads articles stored on the same server as the page containing the iframe.

If I click on any of the elements on the parent page, the menu closes as it should. However, clicking on any of the space within the iframe does not close the menu.

I'm assuming this is because the parent page does not capture events happening inside of the iframe. Like I've said, both pages are stored on the same server, so how can I capture the click to close my menu when the user clicks within the iframe?

HTML:

☰ Menu

Menu Item 1

Menu Item 2

Menu Item 3

Menu Item 4

JQuery:

$(document).ready(function() {
    $("a[target='content']").click(function() {
        if ($("#mobilemenu").css("display") == "block" ){
            $('#fullmenu').hide();
        }
    });
    $('html').click(function() {
        $('#fullmenu').hide();
    });
    $('#menucontainer').click(function(event){
        event.stopPropagation();
    });
    $('.menutrigger').click(function() {
        $('#fullmenu').toggle();
    });
});

CSS: (Added because it occurred to me it might be affecting things)

html, body { height: 100%; width: 100%; }

nav, #frame { position: absolute; right: 0; left: 0; padding: 0; margin: 0; width: 100%; }

#content { height: 100%; width: 100%; }

#frame { top: 38px; bottom: 14px; }

nav { width: 100%; z-index: 100; }

#fullmenu { display: none; position: absolute; top: 38px; width: 100%; }

#mobilemenu { display: block; height: 38px; top: 0; background: #333; }

.menutrigger { font-size: 20px; font-weight: bold; padding: 1px 8px; color: #FFF; cursor: pointer; }

#frame { top: 38px; bottom: 14px; }

nav ul { position: relative; width: 100%; background: #333; list-style: none; display: inline-block; padding: 0; }

nav ul:after { clear: both; }

nav ul li { height: 29px; float: none; min-width: 110px; font-size: 14px; padding: 4px 4px; font-family: 'Roboto Condensed', sans-serif; }

nav ul li a { display: block; padding: 5px; color: #FFF; text-decoration: none; }

nav ul li:hover { background: #666; display: inline-block; height: 29px; }

nav ul li:hover a { color: #FFF; }


问:
Why Maven asks me for distribution config in every module in multi-module site deployment?
My multi-module Maven project looks like:

```<code>/foo
  pom.xml
  /foo-parent
  /foo-core
  /foo-something
  /src
    /site
</code>```

Pay attention that foo is not a parent project, but foo-parent is (for foo-core and foo-something). foo is not inheriting from foo-parent. Site configuration is stored in foo. All other sub-modules don't know anything about project site and don't have <distributionManagement>. mvn site works perfect,  and now I'm running mvn site-deploy:

```<code>[ERROR] Failed to execute goal org.apache.maven.plugins:maven-site-plugin:2.0.1:deploy
(default-deploy) on project foo-parent: Missing site information in the
distribution management element in the project.. -> [Help 1]
</code>```

Maven is trying to site-deploy every sub-module individually?? Is it a correct behavior?

答:
In regards to your distribution config question:

Maven won't let a child module be the parent pom of the top level pom.xml. That's Maven's way of telling you that you not structuring you project to convention.

You'll have to make foo's pom.xml a parent pom for all modules in the whole project.

The workaround for what you are trying to structure, have the modules that depend on foo-parent, list foo-parent's pom.xml in the parent section of their pom.  Then have foo-parent list foo's pom.xml in its parent section.  You can get away with having foo-parent be the parent pom.xml for all the other modules because all modules are peers to each other in structure layout.

The top level pom.xml should only contain the necessary information to be shared between all modules.

In regards to your site-deploy question:

Maven tries to deploy every site individually for each module because of the top level /src/site/site.xml you have setup.  But this is also partly due to the fact that your probably running site-deploy from the top level (foo).  If you only want the documentation for foo-parent, run site-deploy only on foo-parent.  However, you may not get any of the documentation for the other modules linked into foo-parent's site documentation.

P.S.  Better read up on Maven 3.  There are some very significant changes to the site documentation generation coming!

EDIT: Links for reference:

Maven 3 Compatibility Notes

Maven 3 Site Plugin Notes

ContentLicense: CC BY-SA 2.5

Body:
My multi-module Maven project looks like:

/foo
  pom.xml
  /foo-parent
  /foo-core
  /foo-something
  /src
    /site

Pay attention that foo is not a parent project, but foo-parent is (for foo-core and foo-something). foo is not inheriting from foo-parent. Site configuration is stored in foo. All other sub-modules don't know anything about project site and don't have <distributionManagement>. mvn site works perfect,  and now I'm running mvn site-deploy:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-site-plugin:2.0.1:deploy
(default-deploy) on project foo-parent: Missing site information in the
distribution management element in the project.. -> [Help 1]

Maven is trying to site-deploy every sub-module individually?? Is it a correct behavior?


问:
Is there a way to use React Components within Elm?
I know that using Elm components ("modules"? still learning parlance) within React is an established pattern with libraries like react-elm-components, but is there a way to do the inverse?

e.g., something like this is possible:

```<code>Top-level React App
 -> React layout/component
    -> Elm components
</code>```

But what about this:

```<code>Top-level Elm App
  -> Elm layout/components
     -> React components
</code>```

If it is possible, is the 'elm-at-the-bottom' pattern superior? Trying to reason why there doesn't seem to be literature on it & that's a possible explanation.

答:
I've been trying to do the same. I took a popular React date picker and started by interoperating via ports. It's still work in progress but does work

```<code>import React from 'react';
import ReactDOM from 'react-dom';

import * as Datetime from 'react-datetime'

function datepicker(d, cb) {
    return requestAnimationFrame( () => {
        ReactDOM.render(Welcome(d, (res) => {
            cb(res);
        }), document.getElementById('reactDate'));
    });
}

function Welcome(initialdate, cb) {
  return (
      <div>
         <h1>{initialdate}</h1>
         <Datetime onChange={cb} value={initialdate} />
     </div>
  );
}

export default datepicker;
</code>```

Then my ports code looks like

```<code>import datepicker from './reactDPPort.jsx';
elm.ports.trigger.subscribe( (s) => {
    datepicker(s, res => app.ports.toElm.send(res.toString()));
});
</code>```

Body:
I know that using Elm components ("modules"? still learning parlance) within React is an established pattern with libraries like react-elm-components, but is there a way to do the inverse?

e.g., something like this is possible:

Top-level React App
 -> React layout/component
    -> Elm components

But what about this:

Top-level Elm App
  -> Elm layout/components
     -> React components

If it is possible, is the 'elm-at-the-bottom' pattern superior? Trying to reason why there doesn't seem to be literature on it & that's a possible explanation.

Body:
I've been trying to do the same. I took a popular React date picker and started by interoperating via ports. It's still work in progress but does work

import React from 'react';
import ReactDOM from 'react-dom';

import * as Datetime from 'react-datetime'

function datepicker(d, cb) {
    return requestAnimationFrame( () => {
        ReactDOM.render(Welcome(d, (res) => {
            cb(res);
        }), document.getElementById('reactDate'));
    });
}

function Welcome(initialdate, cb) {
  return (
      <div>
         <h1>{initialdate}</h1>
         <Datetime onChange={cb} value={initialdate} />
     </div>
  );
}

export default datepicker;

Then my ports code looks like

import datepicker from './reactDPPort.jsx';
elm.ports.trigger.subscribe( (s) => {
    datepicker(s, res => app.ports.toElm.send(res.toString()));
});


问:
Why is datekey in fact tables always INT?
I'm looking at the datekey column from the fact tables in AdventureWorksDW and they're all of type int.

Is there a reason for this and not of type date?

I understand that creating a clustered index composed of an INT would optimize query speed. But let's say I want to get data from this past week. I can subtract 6 from date 20170704 and I'll get 20170698 which is not a valid date. So I have to cast everything to date, subtract, and then cast as int.

Right now I have a foreign key constraint to make sure that something besides 'YYYYMMDD' isn't inserted. It wouldn't be necessary with a Date type. Just now, I wanted to get some data between 6/28 and 7/4. I can't just subtract six from `20170703'; I have to cast from int to date.

It seems like a lot of hassle and not many benefits.

Thanks.

答:
Actually that fact table has a relationship to a table DimDate, and if you join that table you would get many more options for point in time search, then if you would`ve got by adding and removing days/months.

Say you need list of all orders on second Saturday of May? Or all orders on last week of december?
Also some business regulate their fiscal year different. Some start in June, some start in January..

In summary, DimDate is there to provide you with flexibility when you need to do complicated date searches without doing any calculations, and using a simple index seek on DimDate


问:
Custom selector (with extra params) in UIBarButtonItem
How to define action with extra param in UIBarButtonItem?

I need to pass CNContactViewController object to buttonActionMethod:

```<code>class ContactHelper {

    public static func showContact(controller: UIViewController, contactViewControllerDelegate: CNContactViewControllerDelegate,

                                   contact: CNContact) {

        let contactController = CNContactViewController.init(for: contact)

        contactController.navigationItem.leftBarButtonItem =

            UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self,

                          action: #selector(ContactHelper.buttonAction))

        contactController.delegate = contactViewControllerDelegate

        let navigationController = UINavigationController(rootViewController: contactController)

        controller.present(navigationController, animated: false)

    }

    private static func buttonAction(sender: ContactButton) {
        // need to pass contactController from showContact function
        contactController.dismiss(animated: true, completion: nil)

    }

}
</code>```

答:
You can't modify the signature of action methods. The given API enforces a specific set of allowed parameters. In this case, the only allowed parameter is the button.

The proper solution is to refactor your ContactHelper class to use instance methods and instance properties to store state instead of making everything static.

Another (possibly better) solution to is extend CNContactViewController to add the additional functionality instead of creating this helper class.

Body:
How to define action with extra param in UIBarButtonItem?

I need to pass CNContactViewController object to buttonActionMethod:

class ContactHelper {

    public static func showContact(controller: UIViewController, contactViewControllerDelegate: CNContactViewControllerDelegate,

                                   contact: CNContact) {

        let contactController = CNContactViewController.init(for: contact)

        contactController.navigationItem.leftBarButtonItem =

            UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.cancel, target: self,

                          action: #selector(ContactHelper.buttonAction))

        contactController.delegate = contactViewControllerDelegate

        let navigationController = UINavigationController(rootViewController: contactController)

        controller.present(navigationController, animated: false)

    }

    private static func buttonAction(sender: ContactButton) {
        // need to pass contactController from showContact function
        contactController.dismiss(animated: true, completion: nil)

    }

}


问:
Why can't I set x and y labels as arguments to pd.plot(), whereas I can easily set similar stuff, such as title?
I'm printing various things with pandas, using the inbuilt plot command, such as my_dataframe.plot() followed by plt.show() in ipython.

Now this is a very easy and convenient way to visualize stuff, and given that I do postprocessing on the SVG file anyways, I don't care too much about details of the plot.

However, I need a title, a legend and labels for the x and y axis on the plot, both as a reminder to myself about what is what, and for quickly sending some stuff to other folks, without having to add a "Oh, and BTW, the x axis is hours this time, y is meters as always, but blue now is sample B…" line to the email.

I figured out how to do this in an easy way (see below) and I'm also aware about the various powerful things I could do with ax, but it took me a while to get to my "easy" solution, and I'm staying away from ax because there is way too much stuff going on that I neither need nor understand.

I do understand why one would want all the powerful options of ax, but I do not understand why such a simply option is not included in pandas plotting function. And it seems like I'm not the only one. User Chrispy for example posted this highly rated comment:

is there a particular reason why x and y labels can't be added as arguments to pd.plot()? Given the additional concision of pd.plot() over plt.plot() it seems it would make sense to make it even more succinct instead of having to call ax.set_ylabel()

on the answer to this question, but got no further comments. Hence I'm blatantly stealing this question.

Why does plt.plot() include legends by default and also easily lets me add a title (my_df.plot(title = 'check out my cool plot')), but the logical next step (my_df.plot(ylabel = 'size in meters')) results in TypeError: There is no Line2D property "ylabel"?

Am I missing something or is there a reason for this oversight?

Example code:

This works when I implement it in my real file and run it with run workflow.py in ipython, but I cant reproduce it when copy-pasting the code. Either my labels get ignored, or it downright fails:

EDIT:

Originally I had plt.xlabel = 'time in seconds' in my example here, which did not work, but I had the correct plt.xlabel('time in seconds') in my real code, which of course did work.

```<code>times = np.arange(0,43200,60)
my_df = pd.DataFrame(np.random.randn(len(times)), index = times)
my_df.plot(title = 'just some random data')    #this works
#my_df.plot(title = 'just some random data', ylabel = 'size in meters', xlabel = 'time in seconds')    #this seems like the logical next step, but it errors
plt.ylabel('size in meters')
plt.xlabel('time in seconds')
</code>```

This seems like the most easy/minimal solution with axes, using @Johannes solution, but I think this (see comments to the answer) is also a good illustration why I would like to not having to bother myself with axes:

```<code>axes = my_df.plot(title = 'just some random data')
axes.set_ylabel('size in meters')
axes.set_xlabel('time in seconds')
</code>```

Also, I can set the title another way, but there is only one option for the labels, which is what's confusing me:

```<code>axes = my_df.plot()
axes.set_title('just some random data')
axes.set_ylabel('size in meters')
axes.set_xlabel('time in seconds')
</code>```

答:
First of all, there is no particular reason for the pandas plotting command not to also include keyword arguments for the labels, just as for the title.

This option could well be implemented, but it isn't. To speculate about the reasons will not lead anywhere but there is an issue about it at the pandas issue tracker.

Concerning the actual problem, there are several ways to set labels to the axes. Three possible methods are listed below. Note that in the question as well as in the other answer there appear some non working methods.

Especially ax.xlabel() does not exist. Neither does plt.ylabel = 'size in meters' make any sense, since it overwrites  the ylabel method instead of using  it.

Working options:

ax.set_xlabel()

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

times = np.arange(0,43200,60)
my_df = pd.DataFrame(np.random.randn(len(times)), index = times)
ax = my_df.plot(title = 'just some random data')

ax.set_ylabel('size in meters')
ax.set_xlabel('time in seconds')

plt.show()
</code>```

ax.set()

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

times = np.arange(0,43200,60)
my_df = pd.DataFrame(np.random.randn(len(times)), index = times)
ax = my_df.plot(title = 'just some random data')
ax.set(xlabel='time in seconds', ylabel='size in meters')

plt.show()
</code>```

plt.xlabel()

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

times = np.arange(0,43200,60)
my_df = pd.DataFrame(np.random.randn(len(times)), index = times)
my_df.plot(title = 'just some random data')

plt.ylabel('size in meters')
plt.xlabel('time in seconds')

plt.show()
</code>```

plt.setp()

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

times = np.arange(0,43200,60)
my_df = pd.DataFrame(np.random.randn(len(times)), index = times)
ax = my_df.plot(title = 'just some random data')

plt.setp(ax,xlabel='time in seconds', ylabel='size in meters')

plt.show()
</code>```

Body:
I'm printing various things with pandas, using the inbuilt plot command, such as my_dataframe.plot() followed by plt.show() in ipython.

Now this is a very easy and convenient way to visualize stuff, and given that I do postprocessing on the SVG file anyways, I don't care too much about details of the plot.

However, I need a title, a legend and labels for the x and y axis on the plot, both as a reminder to myself about what is what, and for quickly sending some stuff to other folks, without having to add a "Oh, and BTW, the x axis is hours this time, y is meters as always, but blue now is sample B…" line to the email.

I figured out how to do this in an easy way (see below) and I'm also aware about the various powerful things I could do with ax, but it took me a while to get to my "easy" solution, and I'm staying away from ax because there is way too much stuff going on that I neither need nor understand.

I do understand why one would want all the powerful options of ax, but I do not understand why such a simply option is not included in pandas plotting function. And it seems like I'm not the only one. User Chrispy for example posted this highly rated comment:

is there a particular reason why x and y labels can't be added as arguments to pd.plot()? Given the additional concision of pd.plot() over plt.plot() it seems it would make sense to make it even more succinct instead of having to call ax.set_ylabel()

on the answer to this question, but got no further comments. Hence I'm blatantly stealing this question.

Why does plt.plot() include legends by default and also easily lets me add a title (my_df.plot(title = 'check out my cool plot')), but the logical next step (my_df.plot(ylabel = 'size in meters')) results in TypeError: There is no Line2D property "ylabel"?

Am I missing something or is there a reason for this oversight?

Example code:

This works when I implement it in my real file and run it with run workflow.py in ipython, but I cant reproduce it when copy-pasting the code. Either my labels get ignored, or it downright fails:

EDIT:

Originally I had plt.xlabel = 'time in seconds' in my example here, which did not work, but I had the correct plt.xlabel('time in seconds') in my real code, which of course did work.

times = np.arange(0,43200,60)
my_df = pd.DataFrame(np.random.randn(len(times)), index = times)
my_df.plot(title = 'just some random data')    #this works
#my_df.plot(title = 'just some random data', ylabel = 'size in meters', xlabel = 'time in seconds')    #this seems like the logical next step, but it errors
plt.ylabel('size in meters')
plt.xlabel('time in seconds')

This seems like the most easy/minimal solution with axes, using @Johannes solution, but I think this (see comments to the answer) is also a good illustration why I would like to not having to bother myself with axes:

axes = my_df.plot(title = 'just some random data')
axes.set_ylabel('size in meters')
axes.set_xlabel('time in seconds')

Also, I can set the title another way, but there is only one option for the labels, which is what's confusing me:

axes = my_df.plot()
axes.set_title('just some random data')
axes.set_ylabel('size in meters')
axes.set_xlabel('time in seconds')

Body:
First of all, there is no particular reason for the pandas plotting command not to also include keyword arguments for the labels, just as for the title.

This option could well be implemented, but it isn't. To speculate about the reasons will not lead anywhere but there is an issue about it at the pandas issue tracker.

Concerning the actual problem, there are several ways to set labels to the axes. Three possible methods are listed below. Note that in the question as well as in the other answer there appear some non working methods.

Especially ax.xlabel() does not exist. Neither does plt.ylabel = 'size in meters' make any sense, since it overwrites  the ylabel method instead of using  it.

Working options:

ax.set_xlabel()

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

times = np.arange(0,43200,60)
my_df = pd.DataFrame(np.random.randn(len(times)), index = times)
ax = my_df.plot(title = 'just some random data')

ax.set_ylabel('size in meters')
ax.set_xlabel('time in seconds')

plt.show()

ax.set()

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

times = np.arange(0,43200,60)
my_df = pd.DataFrame(np.random.randn(len(times)), index = times)
ax = my_df.plot(title = 'just some random data')
ax.set(xlabel='time in seconds', ylabel='size in meters')

plt.show()

plt.xlabel()

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

times = np.arange(0,43200,60)
my_df = pd.DataFrame(np.random.randn(len(times)), index = times)
my_df.plot(title = 'just some random data')

plt.ylabel('size in meters')
plt.xlabel('time in seconds')

plt.show()

plt.setp()

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

times = np.arange(0,43200,60)
my_df = pd.DataFrame(np.random.randn(len(times)), index = times)
ax = my_df.plot(title = 'just some random data')

plt.setp(ax,xlabel='time in seconds', ylabel='size in meters')

plt.show()


问:
Firebase FCM Usage Limits
I was wondering if there is a comprehensive list that privides details of the various Firebase FCM usage limits.

I knew of the Data message payload limit of 4KB maximum.
and then recently I got some issue with my app and then figured it was due to another limit - "maximum of 4 different collapse keys per device".

I also remember in one of the recent talks Google mentioned they have removed certain limits that they had previously like number of topics etc..

I am trying to get details of what are all the various limits that Google enforces on the FCM usage.

答:
Here the answer given by Firebase support:

Firebase Cloud Messaging is free of charge, no matter the number of users and message pushes, just like Google Cloud Messaging was.
  However, here are some of its product "limitation":
  There's a limit of 1000 registration tokens used when using registration_ids parameter per send. So if you want to send 5000 messages to different users, you'll need to send the message in 5 batches. There's a limit of 100 messages that can be stored without collapsing. You can read more details here.
  You may also encounter limitations such as sending too much messages per second. Aside from that, everything in FCM is free and unlimited.

We currently don't have an SLA for FCM since it's a free service. We could never guarantee the delivery of messages since we do not control the networks between our servers and the device. We also offer the same level of support for both our paid and free plans for this service. Kindly see our Pricing FAQ here, under "What kind of support will I receive?" for more information.

Title: Firebase FCM Usage Limits


问:
Why the switch statement and not if-else?
I've been wondering this for some time now.  I'm by far not a hardcore programmer, mainly small Python scripts and I've written a couple molecular dynamics simulations.  For the real question:  What is the point of the switch statement?  Why can't you just use the if-else statement?

Thanks for your answer and if this has been asked before please point me to the link.

EDIT

S.Lott has pointed out that this may be a duplicate of questions If/Else vs. Switch.  If you want to close then do so.  I'll leave it open for further discussion.

答:
I'm ignoring this type of low level optimization as usually unimportant, and probably different from compiler to compiler.

I'd say the main difference is readability.  if/else is very flexible, but when you see a switch you know right away that all of the tests are against the same expression.

OwnerDisplayName: Casey

LastEditorDisplayName: Casey

OwnerDisplayName: Darron


问:
Shiny App - passing the string to variable
I am trying to build Shiny App that does sentiment analysis. I have the code that works fine when i execute the script normally where Rstudio is importing the data from email.csv file. This file contains only 2 columns ( SentTo and RawText) and the text i am analyzing is located in B2 cell.
Once i run the code below i get nice chart that measure the sentiment.

```<code>library(readr)
library("ggplot2")
library('syuzhet')
Emails <- read_csv("C:/email.csv")
d<-get_nrc_sentiment(Emails$RawText)
td<-data.frame(t(d))
td_new <- data.frame(rowSums(td[1:14]))
names(td_new)[1] <- "count"
td_new <- cbind("sentiment" = rownames(td_new), td_new)
rownames(td_new) <- NULL
td_new2<-td_new[1:8,]
qplot(sentiment, data=td_new2, weight=count,
geom="bar",fill=sentiment)+ggtitle("Email sentiments")
</code>```

Now what i am trying to do is to modify this code a bit and build the Shiny application by doing next:

ui.R

```<code># Adding the Imput text field to the app
shinyUI(fluidPage(

textAreaInput("UserInput", "Caption", "Please Enter Your Text", width =
"500px", height = "300px"),

mainPanel(
plotOutput("distPlot"))
))
</code>```

Server.R

```<code>library(shiny)
library(syuzhet)
library(ggplot2)

# Define server logic required to draw a histogram
shinyServer(function(input, output) {

output$distPlot <- renderPlot({

Emails <- input$UserInput

d<-get_nrc_sentiment(Emails)
td<-data.frame(t(d))
td_new <- data.frame(rowSums(td[1:14]))
names(td_new)[1] <- "count"
td_new <- cbind("sentiment" = rownames(td_new), td_new)
rownames(td_new) <- NULL
td_new2<-td_new[1:8,]
qplot(sentiment, data=td_new2, weight=count,
geom="bar",fill=sentiment)+ggtitle("Email sentiments")

  })
})
</code>```

After i run the app i get this error:

So ti builds the app but even when i paste some text in to the field it seems that the code i am using in server.R part is not doing what it needs to do.
If i replace the line in server.R part (Emails <- input$UserInput) with (Emails <- read_csv("C:/email.csv"))
than it works fine. This tells me that the issue is within the way i am passing the text to the Emails. Through the input form its text through the csv file it is a second row and second column that contains the data. The code that follows i think its looking that specific format.
Anybody has suggestion on how to modify this to make it work?
Thank you in advance.

答:
I believe the issue is in line:

```<code>td_new <- data.frame(rowSums(td[1:14]))
</code>```

If I change it to the following, it works for me:

```<code>td_new <- data.frame(rowSums(td))
</code>```

I'm not sure why you had the 1:14 index in there, but I don't see what it does.

Body:
I am trying to build Shiny App that does sentiment analysis. I have the code that works fine when i execute the script normally where Rstudio is importing the data from email.csv file. This file contains only 2 columns ( SentTo and RawText) and the text i am analyzing is located in B2 cell.
Once i run the code below i get nice chart that measure the sentiment.

library(readr)
library("ggplot2")
library('syuzhet')
Emails <- read_csv("C:/email.csv")
d<-get_nrc_sentiment(Emails$RawText)
td<-data.frame(t(d))
td_new <- data.frame(rowSums(td[1:14]))
names(td_new)[1] <- "count"
td_new <- cbind("sentiment" = rownames(td_new), td_new)
rownames(td_new) <- NULL
td_new2<-td_new[1:8,]
qplot(sentiment, data=td_new2, weight=count,
geom="bar",fill=sentiment)+ggtitle("Email sentiments")

Now what i am trying to do is to modify this code a bit and build the Shiny application by doing next:

ui.R

# Adding the Imput text field to the app
shinyUI(fluidPage(

textAreaInput("UserInput", "Caption", "Please Enter Your Text", width =
"500px", height = "300px"),

mainPanel(
plotOutput("distPlot"))
))

Server.R

library(shiny)
library(syuzhet)
library(ggplot2)

# Define server logic required to draw a histogram
shinyServer(function(input, output) {

output$distPlot <- renderPlot({

Emails <- input$UserInput

d<-get_nrc_sentiment(Emails)
td<-data.frame(t(d))
td_new <- data.frame(rowSums(td[1:14]))
names(td_new)[1] <- "count"
td_new <- cbind("sentiment" = rownames(td_new), td_new)
rownames(td_new) <- NULL
td_new2<-td_new[1:8,]
qplot(sentiment, data=td_new2, weight=count,
geom="bar",fill=sentiment)+ggtitle("Email sentiments")

  })
})

After i run the app i get this error:

So ti builds the app but even when i paste some text in to the field it seems that the code i am using in server.R part is not doing what it needs to do.
If i replace the line in server.R part (Emails <- input$UserInput) with (Emails <- read_csv("C:/email.csv"))
than it works fine. This tells me that the issue is within the way i am passing the text to the Emails. Through the input form its text through the csv file it is a second row and second column that contains the data. The code that follows i think its looking that specific format.
Anybody has suggestion on how to modify this to make it work?
Thank you in advance.

Body:
I believe the issue is in line:

td_new <- data.frame(rowSums(td[1:14]))

If I change it to the following, it works for me:

td_new <- data.frame(rowSums(td))

I'm not sure why you had the 1:14 index in there, but I don't see what it does.


问:
Google webmaster URL crawl error - 301 moved permanently
There are many question on SO similar to mine but none has solved my issue.

I have installed SSL on a wordpress website recently prior to which everything was working fine including SEARCH RESULTS. After installing SSL my site rank dropped drastically and page views dropped to 300 from 1500 approx. This is a big shock to me.

I reset everything in my google webmaster account including sitemap.xml after which I found fetch as google says the following 301 Moved Permanently

I have this in my .htaccess

```<code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
</code>```

I want the following to work

```<code>http:// domain.com (works)
https:// domain.com (works)
http:// subomain.domain.com (is automatically redirected to https. I don't have wildcard ssl installed and this causes error)
</code>```

I want the domain.com to be forced to https and all subdomains to http. How do I get this done

答:
You can do this thing also from your cPanel..

Steps:

login to your cPanel

go on DOMAIN Section

Click on redirect button in this section.

Then ADD REDIRECTION through that page..

whatever domain or sub domain you want to redirect..

Body:
There are many question on SO similar to mine but none has solved my issue.

I have installed SSL on a wordpress website recently prior to which everything was working fine including SEARCH RESULTS. After installing SSL my site rank dropped drastically and page views dropped to 300 from 1500 approx. This is a big shock to me.

I reset everything in my google webmaster account including sitemap.xml after which I found fetch as google says the following 301 Moved Permanently

I have this in my .htaccess

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

I want the following to work

http:// domain.com (works)
https:// domain.com (works)
http:// subomain.domain.com (is automatically redirected to https. I don't have wildcard ssl installed and this causes error)

I want the domain.com to be forced to https and all subdomains to http. How do I get this done


问:
Pymongo bulk inserts
I am trying to insert documents in bulk. But it doesn't insert more than 84 documents during bulk insert.
Gives me this error:

```<code>in insert pymongo.errors.InvalidOperation: cannot do an empty bulk insert
</code>```

Is it possible to do batch inserts, like inserting 50 documents per insert?

答:
Late to the game here but have had good success with the bulk operations described here (http://api.mongodb.com/python/current/examples/bulk.html). The insert_many() method already does the necessary chunking under the hood. My workflow involved one large 'bulk insert' and then many subsequent full collection updates. Using the bulk update process was many times faster then the looped single update. However the % increase in speed varied based on the size of the input (10, 100, 1000, 1

```<code>def unordered_bulk_write():
    bulk_op = collection.initialize_unordered_bulk_op()

    for primary_key in primary_key_list:
        bulk_op.find({'fubar_key': primary_key}).update({'$set': {'dopeness_factor': 'unlimited'}})

    try:
        bulk_op.execute()
    except Exception as e:
        print e, e.details

def single_update_write():
    for primary_key in primary_key_list:
        collection.update_one({'fubar_key': primary_key}, {'$set':
        {'dopeness_factor': 'unlimited'}})
</code>```

These methods were run in an ipy notebook with the %%timing magic and i got the following stats. Methods were called in a map over a given chunk of randomly selected primary keys with increasing chunk sizes.

```<code>WITH CHUNK_SIZE = 10
UNORDERED BULK WRITE = 1000 loops, best of 3: 871 µs per loop
SINGLE UPDATE ONE = 100 loops, best of 3: 2.47 ms per loop

WITH CHUNK_SIZE = 100
UNORDERED BULK WRITE = 100 loops, best of 3: 4.57 ms per loop
SINGLE UPDATE ONE = 10 loops, best of 3: 26.2 ms per loop

WITH CHUNK_SIZE = 1000
UNORDERED BULK WRITE = 10 loops, best of 3: 39 ms per loop
SINGLE UPDATE ONE = 1 loops, best of 3: 246 ms per loop

WITH CHUNK_SIZE = 10000
UNORDERED BULK WRITE = 1 loops, best of 3: 399 ms per loop
SINGLE UPDATE ONE = 1 loops, best of 3: 2.58 s per loop

WITH CHUNK_SIZE = 100000
UNORDERED BULK WRITE = 1 loops, best of 3: 4.34 s per loop
SINGLE UPDATE ONE = 1 loops, best of 3: 24.8 s per loop
</code>```

Title: Pymongo bulk inserts

Body:
I am trying to insert documents in bulk. But it doesn't insert more than 84 documents during bulk insert.
Gives me this error:

in insert pymongo.errors.InvalidOperation: cannot do an empty bulk insert

Is it possible to do batch inserts, like inserting 50 documents per insert?

Body:
Late to the game here but have had good success with the bulk operations described here (http://api.mongodb.com/python/current/examples/bulk.html). The insert_many() method already does the necessary chunking under the hood. My workflow involved one large 'bulk insert' and then many subsequent full collection updates. Using the bulk update process was many times faster then the looped single update. However the % increase in speed varied based on the size of the input (10, 100, 1000, 1

def unordered_bulk_write():
    bulk_op = collection.initialize_unordered_bulk_op()

    for primary_key in primary_key_list:
        bulk_op.find({'fubar_key': primary_key}).update({'$set': {'dopeness_factor': 'unlimited'}})

    try:
        bulk_op.execute()
    except Exception as e:
        print e, e.details

def single_update_write():
    for primary_key in primary_key_list:
        collection.update_one({'fubar_key': primary_key}, {'$set':
        {'dopeness_factor': 'unlimited'}})

These methods were run in an ipy notebook with the %%timing magic and i got the following stats. Methods were called in a map over a given chunk of randomly selected primary keys with increasing chunk sizes.

WITH CHUNK_SIZE = 10
UNORDERED BULK WRITE = 1000 loops, best of 3: 871 µs per loop
SINGLE UPDATE ONE = 100 loops, best of 3: 2.47 ms per loop

WITH CHUNK_SIZE = 100
UNORDERED BULK WRITE = 100 loops, best of 3: 4.57 ms per loop
SINGLE UPDATE ONE = 10 loops, best of 3: 26.2 ms per loop

WITH CHUNK_SIZE = 1000
UNORDERED BULK WRITE = 10 loops, best of 3: 39 ms per loop
SINGLE UPDATE ONE = 1 loops, best of 3: 246 ms per loop

WITH CHUNK_SIZE = 10000
UNORDERED BULK WRITE = 1 loops, best of 3: 399 ms per loop
SINGLE UPDATE ONE = 1 loops, best of 3: 2.58 s per loop

WITH CHUNK_SIZE = 100000
UNORDERED BULK WRITE = 1 loops, best of 3: 4.34 s per loop
SINGLE UPDATE ONE = 1 loops, best of 3: 24.8 s per loop


问:
Developing gems and testing
I am new to developing Ruby gems, but I thought I'd give it a try.

Recently checking out the latest episode on Railscasts (http://railscasts.com/episodes/245-new-gem-with-bundler) I'm using Bundler to create my gem.

However I'm kind of clueless on how to test my gem.

Sure I could run rake install and then require it from irb, but this seems like a kind of slow workflow for me.

What I'd like to do is create a dummy Rails app and require the gem by referencing to it's source code. Is this possible? I'm sure I've read about it somewhere…

Thanks!

答:
I can't recommend this guide from Ryan Bigg enough: http://bundler.io/v1.16/guides/creating_gem.html. It walks you through generating a gem using Bundler and setting up automated testing. You can develop your features without ever actually having to run your code manually. It's a workflow I'm using for my own gem development and has worked very well so far.

UPDATE: Rereading your question, it sounds like your gem is a Rails engine. I'd recommending looking at José Valim's EngineX. It's a generator that creates a gem with a dummy Rails app for testing (https://github.com/josevalim/enginex). If you already have a lot of code, http://keithschacht.com/creating-a-rails-3-engine-plugin-gem/ might help you setup a dummy app for testing.

Title: Developing gems and testing

ContentLicense: CC BY-SA 4.0


问:
Laravel: Polymorphic types table vs many types tables
I am trying to determine what the best way to many a relationship describing a type would be using Laravel.  For example, I might have a user model that can be of many types.  Everything I have ever been taught would suggest I need to make a users_types.  However, if I wanted to use Eloquent to reference this relationship, I would also need to make a UserType model and an IdentificationType model.  For example:

```<code>// User Class
public function type() {
  return $this->belongsTo('App\UserType');
}

// User Type Class
public function users(){
  return $this->hasMany('App\User');
}

$user->type->description;  // Could return 'casual'
</code>```

This seems like it could quickly become ridiculous if I have a bunch of models and each one could potentially have a "type" or maybe a "status".

Would it be better to make a single types table or a single status table and manage everything with a polymorphic relationship, or is that bad database design? Is there a better way to accomplish this using Query Builder instead of Eloquent?

答:
If it makes semantic sense then using a polymorphic relationship is reasonable. The example Laravel sets is with commentable entities. A commentable entity can either be a video or a post (both allow comments).

In your case you'd need to do something like these tables:

```<code>typable_type
type_id | typable_id | typable_type

type
id | name
</code>```

and use:

```<code>public function type() {
      return $this->morphToMany(Type::class,"type");
}
</code>```

There's no practical reason why you can't do this anyway, in your case. There is however a semantic reason. Example:

A User can be of type primary , a Product can be of type primary however does that mean the same thing? For example does it make sense to say : "Everything primary can be accessed through this page" in short when you say primary user and primary product, does the word primary carry the same meaning?  If the answer is yes then polymorphism is something you should use.

Body:
I am trying to determine what the best way to many a relationship describing a type would be using Laravel.  For example, I might have a user model that can be of many types.  Everything I have ever been taught would suggest I need to make a users_types.  However, if I wanted to use Eloquent to reference this relationship, I would also need to make a UserType model and an IdentificationType model.  For example:

// User Class
public function type() {
  return $this->belongsTo('App\UserType');
}

// User Type Class
public function users(){
  return $this->hasMany('App\User');
}

$user->type->description;  // Could return 'casual'

This seems like it could quickly become ridiculous if I have a bunch of models and each one could potentially have a "type" or maybe a "status".

Would it be better to make a single types table or a single status table and manage everything with a polymorphic relationship, or is that bad database design? Is there a better way to accomplish this using Query Builder instead of Eloquent?

Body:
If it makes semantic sense then using a polymorphic relationship is reasonable. The example Laravel sets is with commentable entities. A commentable entity can either be a video or a post (both allow comments).

In your case you'd need to do something like these tables:

typable_type
type_id | typable_id | typable_type

type
id | name

and use:

public function type() {
      return $this->morphToMany(Type::class,"type");
}

There's no practical reason why you can't do this anyway, in your case. There is however a semantic reason. Example:

A User can be of type primary , a Product can be of type primary however does that mean the same thing? For example does it make sense to say : "Everything primary can be accessed through this page" in short when you say primary user and primary product, does the word primary carry the same meaning?  If the answer is yes then polymorphism is something you should use.


问:
count the number of items in a shell variable
I have a shell variable sampleDir:

```<code>sampleDir=/home/sample*
echo $sampleDir
</code>```

will give:

```<code>/home/sample_001 /home/sample_002 /home/sample_003
</code>```

(note there are sub-directories under the sample_*** ones)

If I would like to count how much of these items are in this $sampleDir variable, what would be a best way please? (Expect to return 3)

答:
Store the variables in an array:

```<code>sampleDir=(/home/sample*)
</code>```

Use Parameter Expansion to get count of items in array:

```<code>echo "${#sampleDir[@]}"
</code>```

Body:
I have a shell variable sampleDir:

sampleDir=/home/sample*
echo $sampleDir

will give:

/home/sample_001 /home/sample_002 /home/sample_003

(note there are sub-directories under the sample_*** ones)

If I would like to count how much of these items are in this $sampleDir variable, what would be a best way please? (Expect to return 3)

Body:
Store the variables in an array:

sampleDir=(/home/sample*)

Use Parameter Expansion to get count of items in array:

echo "${#sampleDir[@]}"


问:
Uncaught Error: Class not found - Laravel
I am trying to run a script within my laravel project when I am having difficulty with the model class not found error.

My model class is located at :

App\UserLoginAudit;

I am calling my class like this :

```<code><?php

namespace App\Scripts;

use App\UserLoginAudit as user_login_audit;
use Illuminate\Support\Facades\DB;

class UserSignOut {
private $currentDate;
private $report;
public function __construct() {
    $this->currentDate = date('Y-m-d H:i:s');
    $this->doQuery();
}

private function doQuery () {
    $this->report = new user_login_audit();

    //die(print_r($this->report,true));

    $this->report->select(
        DB::raw('TIMEDIFF(NOW(),user_login_audit.last_accessed) as time_difference'),
        'user.user_id',
        'user_login_audit.ip_address'
    )
    ->join(
        'tutor_times.user',
        'user.user_id',
        '=',
        'user_login_audit.user_id'
    )
    ->whereNull('user_login_audit.time_out_type')
    ->where('last_accessed','<=',$this->currentDate)
    ->get()
    ->toArray();

    die(print_r($this->report,true));

    $this->processQuery();
}

private function processQuery () {
    foreach ($this->report as $record) {
        if ($record['time_difference'] > 5) {
            $lookup = user_login_audit
                ::where('user_id','=',$record['user_id'])
                ->where('ip_address','=',$record['ip_address'])
                ->whereNull('time_out_type')
                ->first();

            if (!empty($lookup)) {
                $lookup->time_out_type = "system";
                $lookup->save();
            }
        }
    }
}
}
$obj = new UserSignOut();
</code>```

Have I missed something out ? please can someone help me with this issue

When I run the script this is the error I get:

Uncaught Error: Class 'App\UserLoginAudit' not found in /home/public/TutorTimes/app/Scripts/user_sign_out.php:17

答:
Yeah, that won't work. To use Laravel classes, you need Laravel's autoloader.

The correct way of doing this is a custom Artisan command.

Body:
I am trying to run a script within my laravel project when I am having difficulty with the model class not found error.

My model class is located at :

App\UserLoginAudit;

I am calling my class like this :

<?php

namespace App\Scripts;

use App\UserLoginAudit as user_login_audit;
use Illuminate\Support\Facades\DB;

class UserSignOut {
private $currentDate;
private $report;
public function __construct() {
    $this->currentDate = date('Y-m-d H:i:s');
    $this->doQuery();
}

private function doQuery () {
    $this->report = new user_login_audit();

    //die(print_r($this->report,true));

    $this->report->select(
        DB::raw('TIMEDIFF(NOW(),user_login_audit.last_accessed) as time_difference'),
        'user.user_id',
        'user_login_audit.ip_address'
    )
    ->join(
        'tutor_times.user',
        'user.user_id',
        '=',
        'user_login_audit.user_id'
    )
    ->whereNull('user_login_audit.time_out_type')
    ->where('last_accessed','<=',$this->currentDate)
    ->get()
    ->toArray();

    die(print_r($this->report,true));

    $this->processQuery();
}

private function processQuery () {
    foreach ($this->report as $record) {
        if ($record['time_difference'] > 5) {
            $lookup = user_login_audit
                ::where('user_id','=',$record['user_id'])
                ->where('ip_address','=',$record['ip_address'])
                ->whereNull('time_out_type')
                ->first();

            if (!empty($lookup)) {
                $lookup->time_out_type = "system";
                $lookup->save();
            }
        }
    }
}
}
$obj = new UserSignOut();

Have I missed something out ? please can someone help me with this issue

When I run the script this is the error I get:

Uncaught Error: Class 'App\UserLoginAudit' not found in /home/public/TutorTimes/app/Scripts/user_sign_out.php:17


问:
Derived Attribute both in Where Clause and Order By
I am returning a complex derived attribute in my SQL statement called "FULLNAME"  e.g.

```<code>select p.id,
       nvl2(p.ID, upper(p.ATTR1) || ... decode(..) + ) as fullname, // details omitted
       // ...
from
    person_t p, ...
where
    lower(fullname) like '%abc%'
order by
    fullname asc;
</code>```

Previously we were using Hibernate which allows you to attach a @Formula annotation for derived attributes; then you can use the custom field in HQL.

But now we have to transition to JPA, and I have to remove all Hibernate-specific stuff. This requires a rewrite into regular SQL.

The custom field doesn't work in the (1) Where Clause and in the (2) Order By in plain SQL. Is there an easy solution?

答:
The use of aliases in where in not allowed in most of the db. instead in order by is normally allowed.

So you should repeat the code (related to the alias)  in where

eg :

```<code>select p.id,
     nvl2(p.ID, upper(p.ATTR1) || ... decode(..) + ) as fullname, // details omitted
               // ...
from  person_t p, ...
where  lower( nvl2(p.ID, upper(p.ATTR1) || ... decode(..) + ) ) like '%abc%'
order by  fullname asc;
</code>```

Body:
I am returning a complex derived attribute in my SQL statement called "FULLNAME"  e.g.

select p.id,
       nvl2(p.ID, upper(p.ATTR1) || ... decode(..) + ) as fullname, // details omitted
       // ...
from
    person_t p, ...
where
    lower(fullname) like '%abc%'
order by
    fullname asc;

Previously we were using Hibernate which allows you to attach a @Formula annotation for derived attributes; then you can use the custom field in HQL.

But now we have to transition to JPA, and I have to remove all Hibernate-specific stuff. This requires a rewrite into regular SQL.

The custom field doesn't work in the (1) Where Clause and in the (2) Order By in plain SQL. Is there an easy solution?

Body:
The use of aliases in where in not allowed in most of the db. instead in order by is normally allowed.

So you should repeat the code (related to the alias)  in where

eg :

select p.id,
     nvl2(p.ID, upper(p.ATTR1) || ... decode(..) + ) as fullname, // details omitted
               // ...
from  person_t p, ...
where  lower( nvl2(p.ID, upper(p.ATTR1) || ... decode(..) + ) ) like '%abc%'
order by  fullname asc;


问:
Nested Flexbox with horizontal overflow
I am using a nested flexbox layout.

I would like a left nav to always be 1/3rd of the page, and the right side always be 2/3rds.

The left nav should always stay in view.

The right side (an image carousel in my case) should always take up 2/3rds and have a horizontal scrollbar on the boxes.

In the code below, it simply stretches and ignores the overflow.

  Top Header (should stay in view)

    LeftNav

```

答:
Instead of flex-grow, which simply distributes free space in the container, use flex-basis, which explicitly sizes your items 1/3 and 2/3.

Then, because the default minimum width of flex items is min-width: auto, meaning they cannot be smaller than the size of their content, use min-width: 0 to override that default on the carousel.

  Top Header (should stay in view)

LeftNav

```

Title: Nested Flexbox with horizontal overflow

Body:
Instead of flex-grow, which simply distributes free space in the container, use flex-basis, which explicitly sizes your items 1/3 and 2/3.

Then, because the default minimum width of flex items is min-width: auto, meaning they cannot be smaller than the size of their content, use min-width: 0 to override that default on the carousel.

<div>
  Top Header (should stay in view)
</div>
<div style="display: flex">
  <div style="flex: 0 0 33%">LeftNav</div>
  <div style="flex: 0 0 67%; min-width: 0;">
    <div style="display: flex; flex-direction: row; overflow-x: scroll">
      <div style="background-color: blue; min-width: 400px; height: 500px">
      </div>
      <div style="background-color: red; min-width: 400px; height: 500px">
      </div>
      <div style="background-color: green; min-width: 400px; height: 500px">
      </div>
    </div>
  </div>


答:
This maybe useful to others so I will post it here. I have modified @Y0da's code so that his function can output the result for multiple detectors in one go. That is to say you have a tecplot file of the form

```<code> Title="test"
 Variables = "var1", "var2", "var3" ,
 "var4","var5"
 Zone T ="Detector =           1 "
  0.000000000000000E+000  0.000000000000000E+000  0.000000000000000E+000
  0.000000000000000E+000  0.000000000000000E+000
   50.0000000000000       0.000000000000000E+000  0.000000000000000E+000
  0.000000000000000E+000  0.000000000000000E+000

 Zone T ="Detector =           2 "
  0.000000000000000E+000  0.000000000000000E+000  0.000000000000000E+000
  0.000000000000000E+000  0.000000000000000E+000
   50.0000000000000       0.000000000000000E+000  0.000000000000000E+000
  0.000000000000000E+000  0.000000000000000E+000
</code>```

Note that the format is intentionally ugly. That is because if your output is from a FORTRAN code, and you write to a file without explicit formatting, there is a finite number of columns used.

```<code>import re
import numpy as np
import matplotlib.pyplot as plt

path = 'path_to_file/file.plt'

def tecplot_reader(file, nb_var):
    """Tecplot reader for multiple detectors"""
    detectors = []
    with open(file, 'r') as a:
        lines = a.readlines()
        for idx, line in enumerate(lines):
            if (idx <= 3) : continue                        # If this is header line skip
            detec = re.match(r' ZONE (.*$)', line, re.M | re.I) # Determine if this is a new detector line
            if (type(detec)!=type(None)):                       # If this is a new detector line
                detector = int(line[20:-3])-1               # The detector index is between column 30 and -3 characters (counting starts at 1 for the output file)
                detectors.append([])                        # Add a new list for this detector
                continue
            else:
                detectors[detector].append([float(s) for s in line.split()])

    for i,detec in enumerate(detectors):    # For each detector
        detectors[i] = np.concatenate(np.array(detec))                            # Concatinate into one array
        detectors[i] = np.split(np.array(detectors[i]),len(detectors[i])/nb_var)  # Break into correct rows (each row has nb_vars)
        detectors[i] = np.hsplit(np.array(detectors[i]),nb_var)                   # Break up vertically
    return detectors
</code>```

What this returns is a list of the variables for each detector.

Title: Convert Tecplot ascii to Python numpy

Body:
I want to convert a Tecplot file into an array but I don't know how to do it.
Here is an extract of the file:

TITLE = "Test"
VARIABLES = "x" "y"
ZONE I=18,  F=BLOCK
0.1294538E-01  0.1299554E-01  0.1303974E-01  0.1311453E-01  0.1313446E-01  0.1319080E-01
0.1322709E-01  0.1323904E-01  0.1331753E-01  0.1335821E-01  0.1340850E-01  0.1347061E-01
0.1350522E-01  0.1358302E-01  0.1359585E-01  0.1363086E-01  0.1368307E-01  0.1370017E-01
0.1377368E-01  0.1381353E-01  0.1386420E-01  0.1391916E-01  0.1395847E-01  0.1400548E-01
0.1405659E-01  0.1410006E-01  0.1417611E-01  0.1419149E-01  0.1420015E-01  0.1428019E-01
0.1434745E-01  0.1436735E-01  0.1439856E-01  0.1445430E-01  0.1448778E-01  0.1454278E-01

I want to retrieve x and y as array. So x should contain:

0.1294538E-01  0.1299554E-01  0.1303974E-01  0.1311453E-01  0.1313446E-01  0.1319080E-01
0.1322709E-01  0.1323904E-01  0.1331753E-01  0.1335821E-01  0.1340850E-01  0.1347061E-01
0.1350522E-01  0.1358302E-01  0.1359585E-01  0.1363086E-01  0.1368307E-01  0.1370017E-01

And y should contain:

0.1377368E-01  0.1381353E-01  0.1386420E-01  0.1391916E-01  0.1395847E-01  0.1400548E-01
0.1405659E-01  0.1410006E-01  0.1417611E-01  0.1419149E-01  0.1420015E-01  0.1428019E-01
0.1434745E-01  0.1436735E-01  0.1439856E-01  0.1445430E-01  0.1448778E-01  0.1454278E-01

I have seen np.loadtxt('./file.dat', skiprows=3) but I can't find the right options to say read all numbers and separate every 18 figures.

Also, I started something like this with no luck:

with open(file, 'r') as a:
    for line in a.readlines():
        A = re.match(r'TITLE = (.*$)', line, re.M | re.I)
        B = re.match(r'VARIABLES = (.*$)', line, re.M | re.I)
        C = re.match(r'ZONE (.*$)', line, re.M | re.I)
        if A or B or C:
                continue
        else:
            D = re.match(r'(.*$)', line, re.M | re.I)
            value = "{:.16}".format(D.group(1))
            y.append(float(value))
            j = j+1
            if j == 18:
                j = 0

Thank you for your help!

Body:
This maybe useful to others so I will post it here. I have modified @Y0da's code so that his function can output the result for multiple detectors in one go. That is to say you have a tecplot file of the form

 Title="test"
 Variables = "var1", "var2", "var3" ,
 "var4","var5"
 Zone T ="Detector =           1 "
  0.000000000000000E+000  0.000000000000000E+000  0.000000000000000E+000
  0.000000000000000E+000  0.000000000000000E+000
   50.0000000000000       0.000000000000000E+000  0.000000000000000E+000
  0.000000000000000E+000  0.000000000000000E+000

 Zone T ="Detector =           2 "
  0.000000000000000E+000  0.000000000000000E+000  0.000000000000000E+000
  0.000000000000000E+000  0.000000000000000E+000
   50.0000000000000       0.000000000000000E+000  0.000000000000000E+000
  0.000000000000000E+000  0.000000000000000E+000

Note that the format is intentionally ugly. That is because if your output is from a FORTRAN code, and you write to a file without explicit formatting, there is a finite number of columns used.

import re
import numpy as np
import matplotlib.pyplot as plt

path = 'path_to_file/file.plt'

def tecplot_reader(file, nb_var):
    """Tecplot reader for multiple detectors"""
    detectors = []
    with open(file, 'r') as a:
        lines = a.readlines()
        for idx, line in enumerate(lines):
            if (idx <= 3) : continue                        # If this is header line skip
            detec = re.match(r' ZONE (.*$)', line, re.M | re.I) # Determine if this is a new detector line
            if (type(detec)!=type(None)):                       # If this is a new detector line
                detector = int(line[20:-3])-1               # The detector index is between column 30 and -3 characters (counting starts at 1 for the output file)
                detectors.append([])                        # Add a new list for this detector
                continue
            else:
                detectors[detector].append([float(s) for s in line.split()])

    for i,detec in enumerate(detectors):    # For each detector
        detectors[i] = np.concatenate(np.array(detec))                            # Concatinate into one array
        detectors[i] = np.split(np.array(detectors[i]),len(detectors[i])/nb_var)  # Break into correct rows (each row has nb_vars)
        detectors[i] = np.hsplit(np.array(detectors[i]),nb_var)                   # Break up vertically
    return detectors

What this returns is a list of the variables for each detector.


问:
Multiple Errors In Code
Theese are the errors

I asked on the website where I am doing the course at my the answer I was given I either do not understand, it is not clear enough or it it complete shit, I have been looking for 2 days for solutions for this  and with all the edits I have done it has not worked]

anyway here is  the answer I was given
"In the header you are trying to define functions multiple times. as you can see here on lines 6&15, and  7&18" I have changed the int's around and it still does not work so could somebody possibly explain in more detail or just give me the correct code please:

My Code is

Main.cpp

```<code>#include <iostream>
#include <string>
#include "FBullCowGame.h"
void PrintIntro();
std::string GetGuess();
void PlayGame();
bool AskToPlayAgain();
FBullCowGame BCGame; // instantiate a new game

// the entry point for our application
int main() {
 bool bPlayAgain = false;
 do {
 PrintIntro();
 PlayGame();
 // TODO add game summary
 bPlayAgain = AskToPlayAgain();
 } while (bPlayAgain);
 return 0;
}
// introduce the game
void PrintIntro() {
 constexpr int WORD_LENGTH = 5;
 std::cout << "Welme To Bulls and Cows, a fun word game.\n";
 std::cout << "Can you guess the " << WORD_LENGTH << " letter isogram I'm thinking of? \n ";
}
//Play the game
void PlayGame() {
 BCGame.Reset;
 int MaxTries = BCGame.GetMaxTries(); // checks how many tries the game has got
 std::cout << "MaxTries = " << MaxTries << "\n";
 // loop for the number of turns asking for our guesses
 // TODO make while looop
 for (int count = 1; count <= MaxTries; count++) {
 std::string Guess = GetGuess(); // TODO check valid guesses
 std::cout << "Your guess was " << Guess << "\n";
 }
 return;
}
// get a guess from the player
std::string GetGuess() {
 int CurrentTry = BCGame.GetCurrentTry();
 std::cout << "Try " << CurrentTry << ". Enter your guess: ";
 std::string Guess = "";
 std::getline(std::cin, Guess);
 return Guess;
}
bool AskToPlayAgain() {
 std::cout << "Would you like to play again? (y/n) \n ";
 std::string Response = "";
 std::getline(std::cin, Response);
 return (Response[0] == 'y') || (Response[0] == 'Y');
}
</code>```

Header

```<code>#pragma once
#include<string>
// senpai notice me
class FBullCowGame {
public:
 FBullCowGame(); // contructor
 bool Reset(); // make a more rich return valuve
 int GetMaxTries()const;
 int GetCurrentTry()const;
 bool IsGameWon()const;
 bool CheckGuessCorrect(std::string); // make a rich return value
 // TODO make a method  to get bulls and cowws
//Focus above ,not here
private:
 int MyCurrentTry ; // find the contructor or somthing
 int MyMaxTries;
};
</code>```

Fbullcowgame,.cpp

```<code>#include "FBullCowGame.h"
FBullCowGame::FBullCowGame() {
 Reset();
}
int FBullCowGame::GetMaxTries() const { return MyMaxTries;}
int FBullCowGame::GetCurrentTry() const { return MyCurrentTry;}
bool FBullCowGame::Reset() {

 constexpr int MyMaxTries = 8;
 MyCurrentTry = 1;
 return MyMaxTries;
}

int FBullCowGame::GetMaxTries() const {
 return;
}
int FBullCowGame::GetCurrentTry() const {
 return MyCurrentTry;
}
bool FBullCowGame::IsGameWon() const {
 return false;
}
bool FBullCowGame::CheckGuessCorrect(std::string) {
 return false;
}
</code>```

Severity Code Description Project File Line Suppression State

```<code>Error C2084 function 'int FBullCowGame::GetCurrentTry(void) const' already has a body BullCowGame
c:\users\nem\documents\unrealcorse\section_2\section_02\bullcowgame\fbullcowgame.cpp 22
Error C2084 function 'int FBullCowGame::GetMaxTries(void) const' already has a body BullCowGame
c:\users\nem\documents\unrealcorse\section_2\section_02\bullcowgame\fbullcowgame.cpp 18
Error C3867 'FBullCowGame::Reset': non-standard syntax; use '&' to create a pointer to member BullCowGame c:\users\nem\documents\unrealcorse\section_2\section_02\bullcowgame\main.cpp 33
</code>```

答:
function 'int FBullCowGame::GetCurrentTry(void) const' already has a body BullCowGame

The function int FBullCowGame::GetCurrentTry(void) is defined twice (meaning the second time it is seen, it already has a body).

```<code>1. int FBullCowGame::GetCurrentTry() const { return MyCurrentTry;}

2. int FBullCowGame::GetCurrentTry() const {
        return MyCurrentTry;
   }
</code>```

C2084 function 'int FBullCowGame::GetMaxTries(void) const' already has a body BullCowGame

Same goes for the second error.

C3867 'FBullCowGame::Reset': non-standard syntax; use '&' to create a pointer to member

You missed the () when trying to call this method. This assumes that you're trying to reference the function itself, hence the error relating to pointer to member.

```<code>BCGame.Reset;
</code>```

Title: Multiple Errors In Code

Body:
Theese are the errors

I asked on the website where I am doing the course at my the answer I was given I either do not understand, it is not clear enough or it it complete shit, I have been looking for 2 days for solutions for this  and with all the edits I have done it has not worked]

anyway here is  the answer I was given
"In the header you are trying to define functions multiple times. as you can see here on lines 6&15, and  7&18" I have changed the int's around and it still does not work so could somebody possibly explain in more detail or just give me the correct code please:

My Code is

Main.cpp

#include <iostream>
#include <string>
#include "FBullCowGame.h"
void PrintIntro();
std::string GetGuess();
void PlayGame();
bool AskToPlayAgain();
FBullCowGame BCGame; // instantiate a new game

// the entry point for our application
int main() {
 bool bPlayAgain = false;
 do {
 PrintIntro();
 PlayGame();
 // TODO add game summary
 bPlayAgain = AskToPlayAgain();
 } while (bPlayAgain);
 return 0;
}
// introduce the game
void PrintIntro() {
 constexpr int WORD_LENGTH = 5;
 std::cout << "Welme To Bulls and Cows, a fun word game.\n";
 std::cout << "Can you guess the " << WORD_LENGTH << " letter isogram I'm thinking of? \n ";
}
//Play the game
void PlayGame() {
 BCGame.Reset;
 int MaxTries = BCGame.GetMaxTries(); // checks how many tries the game has got
 std::cout << "MaxTries = " << MaxTries << "\n";
 // loop for the number of turns asking for our guesses
 // TODO make while looop
 for (int count = 1; count <= MaxTries; count++) {
 std::string Guess = GetGuess(); // TODO check valid guesses
 std::cout << "Your guess was " << Guess << "\n";
 }
 return;
}
// get a guess from the player
std::string GetGuess() {
 int CurrentTry = BCGame.GetCurrentTry();
 std::cout << "Try " << CurrentTry << ". Enter your guess: ";
 std::string Guess = "";
 std::getline(std::cin, Guess);
 return Guess;
}
bool AskToPlayAgain() {
 std::cout << "Would you like to play again? (y/n) \n ";
 std::string Response = "";
 std::getline(std::cin, Response);
 return (Response[0] == 'y') || (Response[0] == 'Y');
}

Header

#pragma once
#include<string>
// senpai notice me
class FBullCowGame {
public:
 FBullCowGame(); // contructor
 bool Reset(); // make a more rich return valuve
 int GetMaxTries()const;
 int GetCurrentTry()const;
 bool IsGameWon()const;
 bool CheckGuessCorrect(std::string); // make a rich return value
 // TODO make a method  to get bulls and cowws
//Focus above ,not here
private:
 int MyCurrentTry ; // find the contructor or somthing
 int MyMaxTries;
};

Fbullcowgame,.cpp

#include "FBullCowGame.h"
FBullCowGame::FBullCowGame() {
 Reset();
}
int FBullCowGame::GetMaxTries() const { return MyMaxTries;}
int FBullCowGame::GetCurrentTry() const { return MyCurrentTry;}
bool FBullCowGame::Reset() {

 constexpr int MyMaxTries = 8;
 MyCurrentTry = 1;
 return MyMaxTries;
}

int FBullCowGame::GetMaxTries() const {
 return;
}
int FBullCowGame::GetCurrentTry() const {
 return MyCurrentTry;
}
bool FBullCowGame::IsGameWon() const {
 return false;
}
bool FBullCowGame::CheckGuessCorrect(std::string) {
 return false;
}

Severity Code Description Project File Line Suppression State

Error C2084 function 'int FBullCowGame::GetCurrentTry(void) const' already has a body BullCowGame
c:\users\nem\documents\unrealcorse\section_2\section_02\bullcowgame\fbullcowgame.cpp 22
Error C2084 function 'int FBullCowGame::GetMaxTries(void) const' already has a body BullCowGame
c:\users\nem\documents\unrealcorse\section_2\section_02\bullcowgame\fbullcowgame.cpp 18
Error C3867 'FBullCowGame::Reset': non-standard syntax; use '&' to create a pointer to member BullCowGame c:\users\nem\documents\unrealcorse\section_2\section_02\bullcowgame\main.cpp 33

Body:
function 'int FBullCowGame::GetCurrentTry(void) const' already has a body BullCowGame

The function int FBullCowGame::GetCurrentTry(void) is defined twice (meaning the second time it is seen, it already has a body).

1. int FBullCowGame::GetCurrentTry() const { return MyCurrentTry;}

2. int FBullCowGame::GetCurrentTry() const {
        return MyCurrentTry;
   }

C2084 function 'int FBullCowGame::GetMaxTries(void) const' already has a body BullCowGame

Same goes for the second error.

C3867 'FBullCowGame::Reset': non-standard syntax; use '&' to create a pointer to member

You missed the () when trying to call this method. This assumes that you're trying to reference the function itself, hence the error relating to pointer to member.

BCGame.Reset;


问:
convert a string to json in java
I want to convert the stdout of the following python into a json object in Java code.

```<code>Process p = Runtime.getRuntime().exec(python one.py);

BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));

while ((s = stdInput.readLine()) != null) {
    System.out.println(s); }
</code>```

python output sample:  cat-red-fish dog-brown-meat

desired JSON : "animal":{"type":"cat", "color":"red", "food":"fish"}...

How can I split while passing the output in JSON?

答:
If you're okay with using libraries, you can use something like Google's Gson to map the string to an object.

https://github.com/google/gson

With this you can create three String/Enum fields inside an Animal class like:

```<code>public class Animal {
  private String type;
  private String color;
  private String food;
}
</code>```

You can then use Gson#fromJson("jsonString", Animal.class);

Title: convert a string to json in java

Body:
I want to convert the stdout of the following python into a json object in Java code.

Process p = Runtime.getRuntime().exec(python one.py);

BufferedReader stdInput = new BufferedReader(new
InputStreamReader(p.getInputStream()));

while ((s = stdInput.readLine()) != null) {
    System.out.println(s); }

python output sample:  cat-red-fish dog-brown-meat

desired JSON : "animal":{"type":"cat", "color":"red", "food":"fish"}...

How can I split while passing the output in JSON?

Body:
If you're okay with using libraries, you can use something like Google's Gson to map the string to an object.

https://github.com/google/gson

With this you can create three String/Enum fields inside an Animal class like:

public class Animal {
  private String type;
  private String color;
  private String food;
}

You can then use Gson#fromJson("jsonString", Animal.class);


问:
Instanciating an object via DOM element inside setup() on p5
I'm facing a problem where I'm trying to instantiate an object inside the setup function of p5, using a callback to do so:

This is the part of sketch.js relevant to the problem:

```<code>var g; //for graph instance
var dropzone; //for the file dropping area

function setup() {
    createCanvas(640, 480);

    dropzone = select('#dropzone'); //selects the <p> element I'm using as dropzone
    dropzone.drop(process_file, unhighlight); //unhighlight is just a function to make the drop area not-highlighted
}

function draw() {
    background(200);
    if (g) {
        g.show();
    }else{
        msg = "Please, load a file by dropping it in the box above";
        text(msg, width/2, height/2);
    }
}

// callback being used to process the text file content
function process_file(file){
    data = file.data; //gets file data(content)
    lines = data.split('\n'); // split the lines
    digraph = lines[0] == 1 ? true : false; // is it a digraph?
    v = int(lines[1]);
    g = Graph(digraph, v); //the class I"m using to instantiate the graph
    console.log(g); // <-- says undefined
    g.init_graph(); // initialize all vertices
    for (var i = 2; i < lines.length; i++) {
        edge = lines[i].split(' ');
        g.add_edge(edge[0], edge[1], edge[2]);
    }
}
</code>```

I already checked using console.log() and the content of the file is being correctly loaded, and the values are correct in what I was expecting. the Graph() class is in another file, but it is being imported as well as the sketch.js. I also tried to put the script importing at the end of the page, but got the same result, the g is still saying undefined.

What I didn't try is to put the whole code of my Graph class into the sketch.js file, but I will need to put more 15 algorithms on the class later, so the sketch file will grow in a unneeded size. I thought the by declaring g as a global variable I would have no problems with it.

I'm fairly inexperienced with JavaScript, so this is probably a rookie mistake about some kind of loading order, so please, if you answer this question, show me the why it is not working as it is. If there's need of any other piece of code, please let me know.

Thanks in advance.

答:
Looking at this line:

```<code>g = Graph(digraph, v);
</code>```

I think you meant to do this:

```<code>g = new Graph(digraph, v);
</code>```

This creates a new instance and stores a reference to that instance in the g variable.

Body:
I'm facing a problem where I'm trying to instantiate an object inside the setup function of p5, using a callback to do so:

This is the part of sketch.js relevant to the problem:

var g; //for graph instance
var dropzone; //for the file dropping area

function setup() {
    createCanvas(640, 480);

    dropzone = select('#dropzone'); //selects the
 element I'm using as dropzone
    dropzone.drop(process_file, unhighlight); //unhighlight is just a function to make the drop area not-highlighted
}

function draw() {
    background(200);
    if (g) {
        g.show();
    }else{
        msg = "Please, load a file by dropping it in the box above";
        text(msg, width/2, height/2);
    }
}

// callback being used to process the text file content
function process_file(file){
    data = file.data; //gets file data(content)
    lines = data.split('\n'); // split the lines
    digraph = lines[0] == 1 ? true : false; // is it a digraph?
    v = int(lines[1]);
    g = Graph(digraph, v); //the class I"m using to instantiate the graph
    console.log(g); // <-- says undefined
    g.init_graph(); // initialize all vertices
    for (var i = 2; i < lines.length; i++) {
        edge = lines[i].split(' ');
        g.add_edge(edge[0], edge[1], edge[2]);
    }
}

I already checked using console.log() and the content of the file is being correctly loaded, and the values are correct in what I was expecting. the Graph() class is in another file, but it is being imported as well as the sketch.js. I also tried to put the script importing at the end of the page, but got the same result, the g is still saying undefined.

What I didn't try is to put the whole code of my Graph class into the sketch.js file, but I will need to put more 15 algorithms on the class later, so the sketch file will grow in a unneeded size. I thought the by declaring g as a global variable I would have no problems with it.

I'm fairly inexperienced with JavaScript, so this is probably a rookie mistake about some kind of loading order, so please, if you answer this question, show me the why it is not working as it is. If there's need of any other piece of code, please let me know.

Thanks in advance.

Body:
Looking at this line:

g = Graph(digraph, v);

I think you meant to do this:

g = new Graph(digraph, v);

This creates a new instance and stores a reference to that instance in the g variable.


问:
unable to get react app started when starting node.js
I'm following a tutorial on react, and the final step is to start node, but when I do "npm start" as indicated by this tutorial. I get this error.

here's the error cmd line is giving me on starting node "npm start"

```<code>C:\Users\George\Desktop\reactapp>npm start
npm ERR! Windows_NT 10.0.15063
npm ERR! argv "C:\\nodejs\\node.exe" "C:\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v6.11.0
npm ERR! npm  v3.10.10
npm ERR! file C:\Users\George\Desktop\reactapp\package.json
npm ERR! code EJSONPARSE

npm ERR! Failed to parse json
npm ERR! Unexpected token '"' at 11:3
npm ERR!   "keywords": [
npm ERR!   ^
npm ERR! File: C:\Users\George\Desktop\reactapp\package.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR!
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\George\Desktop\reactapp\npm-debug.log
</code>```

and finally here's my package.json file

```<code>{
  "name": "reactapp",
  "version": "1.0.0",
  "description": "test react application",
  "main": "index.js",
  "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "start": "node server.js"
    }
}
  "keywords": [
    "test",
    "react",
    "application"
  ],
  "author": "George Louis",
  "license": "ISC",
  "dependencies": {
    "webpack": "^3.0.0"
  }
}
</code>```

答:
You are missing comma between } and "keywoards", Also you have sufficient }.

Your JSON should look like

```<code>  {
    "name": "reactapp",
    "version": "1.0.0",
    "description": "test react application",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "node server.js"
    },
    "keywords": [
        "test",
        "react",
        "application"
    ],
    "author": "George Louis",
    "license": "ISC",
    "dependencies": {
        "webpack": "^3.0.0"
    }
}
</code>```

Body:
I'm following a tutorial on react, and the final step is to start node, but when I do "npm start" as indicated by this tutorial. I get this error.

here's the error cmd line is giving me on starting node "npm start"

C:\Users\George\Desktop\reactapp>npm start
npm ERR! Windows_NT 10.0.15063
npm ERR! argv "C:\\nodejs\\node.exe" "C:\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v6.11.0
npm ERR! npm  v3.10.10
npm ERR! file C:\Users\George\Desktop\reactapp\package.json
npm ERR! code EJSONPARSE

npm ERR! Failed to parse json
npm ERR! Unexpected token '"' at 11:3
npm ERR!   "keywords": [
npm ERR!   ^
npm ERR! File: C:\Users\George\Desktop\reactapp\package.json
npm ERR! Failed to parse package.json data.
npm ERR! package.json must be actual JSON, not just JavaScript.
npm ERR!
npm ERR! This is not a bug in npm.
npm ERR! Tell the package author to fix their package.json file. JSON.parse

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\George\Desktop\reactapp\npm-debug.log

and finally here's my package.json file

{
  "name": "reactapp",
  "version": "1.0.0",
  "description": "test react application",
  "main": "index.js",
  "scripts": {
      "test": "echo \"Error: no test specified\" && exit 1",
      "start": "node server.js"
    }
}
  "keywords": [
    "test",
    "react",
    "application"
  ],
  "author": "George Louis",
  "license": "ISC",
  "dependencies": {
    "webpack": "^3.0.0"
  }
}

Body:
You are missing comma between } and "keywoards", Also you have sufficient }.

Your JSON should look like

  {
    "name": "reactapp",
    "version": "1.0.0",
    "description": "test react application",
    "main": "index.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "node server.js"
    },
    "keywords": [
        "test",
        "react",
        "application"
    ],
    "author": "George Louis",
    "license": "ISC",
    "dependencies": {
        "webpack": "^3.0.0"
    }
}


答:
By the name of your file and class, I can understand that you run/load your script manually.
In this case, you won't load the composer's autoloader which should load the classes for you.

Try to create a custom artisan command and run it with php artisan {commandName}.

See Laravel docs for the creation of the custom artisan command.

**** Update ****

For your need, use this command (and don't forget to register it):

```<code><?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\UserLoginAudit as user_login_audit;
use Illuminate\Support\Facades\DB;

class UserSignOut extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'user-sign-our';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '...';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->report = new user_login_audit();

        $this->report->select(
            DB::raw('TIMEDIFF(NOW(),user_login_audit.last_accessed) as time_difference'),
            'user.user_id',
            'user_login_audit.ip_address'
        )
            ->join(
                'tutor_times.user',
                'user.user_id',
                '=',
                'user_login_audit.user_id'
            )
            ->whereNull('user_login_audit.time_out_type')
            ->where('last_accessed', '<=', $this->currentDate)
            ->get()
            ->toArray();

        die(print_r($this->report, true));

        $this->processQuery();
    }

    /**
     *
     */
    private function processQuery()
    {
        foreach ($this->report as $record) {
            if ($record['time_difference'] > 5) {
                $lookup = user_login_audit
                    ::where('user_id', '=', $record['user_id'])
                    ->where('ip_address', '=', $record['ip_address'])
                    ->whereNull('time_out_type')
                    ->first();

                if ( ! empty($lookup)) {
                    $lookup->time_out_type = "system";
                    $lookup->save();
                }
            }
        }
    }
}
</code>```

To run it, use:

```<code>php artisan user-sign-our
</code>```

Title: Uncaught Error: Class not found - Laravel

Body:
By the name of your file and class, I can understand that you run/load your script manually.
In this case, you won't load the composer's autoloader which should load the classes for you.

Try to create a custom artisan command and run it with php artisan {commandName}.

See Laravel docs for the creation of the custom artisan command.

**** Update ****

For your need, use this command (and don't forget to register it):

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\UserLoginAudit as user_login_audit;
use Illuminate\Support\Facades\DB;

class UserSignOut extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'user-sign-our';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '...';

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->report = new user_login_audit();

        $this->report->select(
            DB::raw('TIMEDIFF(NOW(),user_login_audit.last_accessed) as time_difference'),
            'user.user_id',
            'user_login_audit.ip_address'
        )
            ->join(
                'tutor_times.user',
                'user.user_id',
                '=',
                'user_login_audit.user_id'
            )
            ->whereNull('user_login_audit.time_out_type')
            ->where('last_accessed', '<=', $this->currentDate)
            ->get()
            ->toArray();

        die(print_r($this->report, true));

        $this->processQuery();
    }

    /**
     *
     */
    private function processQuery()
    {
        foreach ($this->report as $record) {
            if ($record['time_difference'] > 5) {
                $lookup = user_login_audit
                    ::where('user_id', '=', $record['user_id'])
                    ->where('ip_address', '=', $record['ip_address'])
                    ->whereNull('time_out_type')
                    ->first();

                if ( ! empty($lookup)) {
                    $lookup->time_out_type = "system";
                    $lookup->save();
                }
            }
        }
    }
}

To run it, use:

php artisan user-sign-our


问:
Hash tables Ω(n^2) runtime?
I am really confused about this. Having read the textbook and done exercises I still don't get how it works, and unfortunately I can't go in person to see the professor and it's somewhat difficult to get in touch (summer online course, different time zones). I feel like it would 'click' if I just understood how to do this problem. The textbook details hash functions and runtime individually but I feel like this question is outside the scope of what we've learned. If someone could point me at anything that might help, that would be great.

1) Consider the process of inserting m keys into a hash table T[0..m − 1], where m is a prime, and we use open addressing. The hash function we use is h(k, i) = (k + i) mod m. Give an example of m keys k1, k2 ... km, such that the following sequence of operations takes Ω(n^2) time:

insert(k1), insert(k2), ..., insert(km)

I understand that insert operations are supposed to take O(1) time or, in some cases, O(n). How exactly am I supposed to come up with keys that will turn that into Ω(n^2) time? I'm hoping to understand this and I feel like I'm missing some huge hint, because the textbook chapter seems simple, makes sense to me, and doesn't help with this at all. In the question it's stated that m is a prime, is this important? I'm just so lost, and Google for once fails me.

答:
The keyword here is hash collision:

In order for a hash function to work well, you need the values for a certain input to be well-distributed over all m possible values the entries are stored in. If the hash table has about as many entries as elements were inserted, you can expect every element to be stored at (or near) its hash value (meaning only small amounts of probing are necessary), making access, insertion and deletion a constant-time operation.

If you however find different input values for which the hash function maps to the same value every time (collisions), during insertion the probing step will have to skip over all previously added elements, taking Ω(n) time per element on average. Thus we get a runtime of Ω(n²)

Title: Hash tables Ω(n^2) runtime?