问:
AttributeError: 'ModuleSpec' object has no attribute 'load_data_wrapper'
This is a bit long so bear with me.

I am trying to learn both Python and Linux and am very new to both. I am currently doing some reading on deep learning from the following:

http://neuralnetworksanddeeplearning.com/chap1.html

I am attempting to import the mnist_loader package to use the associated data for testing the script that was previously written. However, upon typing import mnist_loader into the Linux command line, I was given the following:

"the program 'import' can be found in the following packages:"

at which point it listed some packages. Because I'm new to Linux and I don't have admin privileges, I decided to go a route that I understood better; that is to create a new python script and simply use the import command within (which has worked in all previous attempts).

I created a python script and tried import mnist_loader and received the following error:

"ModuleNotFoundError: No module named 'mnist_loader'"

I then checked my C drive and found that the file was indeed there. Here is a link to the Git repository where the files may be found:

https://github.com/MichalDanielDobrzanski/DeepLearningPython35

Next I moved on to trying to directly input the path to the file as follows:

```<code>import importlib.util

mnist_loader = importlib.util.spec_from_file_location("mnist_loader",r"C:\Users\XXXXXX\Documents\neural-networks-and-deep-learning-master\neural-networks-and-deep-learning-master\src\mnist_loader.py")

training_data, validation_data, test_data = mnist_loader.load_data_wrapper()
</code>```

However, this produced the following error:

"AttributeError: 'ModuleSpec' object has no attribute 'load_data_wrapper'"

Note: the last line is used to collect the necessary data from the nist files.

I am running out of thoughts at this point and would love some feedback on all my "wrongdoings" up till now.

Thanks in advance!

P.S. It is worth noting that the book uses a package designed for Python 2.X whereas I am using 3.6. The readme provided by the book file location mentioned a different location where a Python 3.6 version could be found which is what I am going with.

答: Been a while since I have worked with Python, but I have some ideas as to what would cause the specific errors you are seeing. First I would suggest setting a PYTHON_PATH environment variable with the path you have that contains the module you want to import, this does not require administrator privileges fortunately. As for the load_data_wrapper attribute, you might have to do a from from mnist_loader import * to import all the functions inside the mnist_loader module.

Body:
This is a bit long so bear with me.

I am trying to learn both Python and Linux and am very new to both. I am currently doing some reading on deep learning from the following:

http://neuralnetworksanddeeplearning.com/chap1.html

I am attempting to import the mnist_loader package to use the associated data for testing the script that was previously written. However, upon typing import mnist_loader into the Linux command line, I was given the following:

"the program 'import' can be found in the following packages:"

at which point it listed some packages. Because I'm new to Linux and I don't have admin privileges, I decided to go a route that I understood better; that is to create a new python script and simply use the import command within (which has worked in all previous attempts).

I created a python script and tried import mnist_loader and received the following error:

"ModuleNotFoundError: No module named 'mnist_loader'"

I then checked my C drive and found that the file was indeed there. Here is a link to the Git repository where the files may be found:

https://github.com/MichalDanielDobrzanski/DeepLearningPython35

Next I moved on to trying to directly input the path to the file as follows:

import importlib.util

mnist_loader = importlib.util.spec_from_file_location("mnist_loader",r"C:\Users\XXXXXX\Documents\neural-networks-and-deep-learning-master\neural-networks-and-deep-learning-master\src\mnist_loader.py")

training_data, validation_data, test_data = mnist_loader.load_data_wrapper()

However, this produced the following error:

"AttributeError: 'ModuleSpec' object has no attribute 'load_data_wrapper'"

Note: the last line is used to collect the necessary data from the nist files.

I am running out of thoughts at this point and would love some feedback on all my "wrongdoings" up till now.

Thanks in advance!

P.S. It is worth noting that the book uses a package designed for Python 2.X whereas I am using 3.6. The readme provided by the book file location mentioned a different location where a Python 3.6 version could be found which is what I am going with.


来源: stackexchange

问:
Android - Trying to get reference to a locally stored image with intent results in unexpected behavior
What should be happening:

A user clicks on a button which brings up their phone's image gallery. They select an image via startActivityForResult, which I then get the path for and handle it from there.

What is happening:

When I click the button, the gallery opens up perfectly. But when I select an image, onActivityResult is never called and instead of closing the gallery and going back to the initial activity, the app goes back to the activity before it. Like it's calling onBackPressed or something.

My code for opening the gallery:

```<code>profilePicView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, 1);
        }
}
</code>```

Trying to get the result (this never gets called):

```<code>public void onActivityResult(int requestCode, int resultCode, Intent data){
    // none of this is every called, including the entire onActivityResult method
    if(requestCode == 1){
        Uri selectedImageUri = data.getData();
        selectedProfilePicPath = getPath(selectedImageUri);
    }
}
</code>```

So all I'm trying to do is get the path to the selected image with onActivityResult. But that is never being called and for some reason this action causes the activity to go back to the previous activity. If it matters, this is an Activity and not a Fragment.

Thanks

答: The issue was that I had "noHistory=true" defined in the Android Manifest for this Activity. Removing that fixed everything. </p>

ContentLicense: CC BY-SA 3.0

Body:
What should be happening:

A user clicks on a button which brings up their phone's image gallery. They select an image via startActivityForResult, which I then get the path for and handle it from there.

What is happening:

When I click the button, the gallery opens up perfectly. But when I select an image, onActivityResult is never called and instead of closing the gallery and going back to the initial activity, the app goes back to the activity before it. Like it's calling onBackPressed or something.

My code for opening the gallery:

profilePicView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(intent, 1);
        }
}

Trying to get the result (this never gets called):

public void onActivityResult(int requestCode, int resultCode, Intent data){
    // none of this is every called, including the entire onActivityResult method
    if(requestCode == 1){
        Uri selectedImageUri = data.getData();
        selectedProfilePicPath = getPath(selectedImageUri);
    }
}

So all I'm trying to do is get the path to the selected image with onActivityResult. But that is never being called and for some reason this action causes the activity to go back to the previous activity. If it matters, this is an Activity and not a Fragment.

Thanks


问:
How I reference hash inside of subroutine?
I am trying to use the tie function of the module Config::IniFiles but I cannot figure out how to reference the hash inside of sub routine. If I remove the tie function and related code from the sub routine it works perfectly.

This is the line I thought would work, but tells me that "$cfg" is not initialized.

```<code>use Config::IniFiles
sub config_file {
    my $cfg_file = 'settings.ini';
    my %cfg;
    tie %cfg, 'Config::IniFiles', ( -file => "$cfg_file" );

    #my $cfg = Config::IniFiles->new( -file => $cfg_file );

}

sub esx_host_check {
    my $esx_host = config_file()->$cfg{ESX}{host};
}
</code>```

I am sure it is something simple, but I am stumped.

答:
You are declaring %cfg with my (good!), so it's only visible inside the config_file sub; You then tie it, which returns the underlying Config::IniFiles object, and, as it is the last entry of the function, it returns that object... So I'm not sure why you are tie'ing in the first place, rather than just using the commented line.

In any case, config_file() returns a Config::IniFiles object. You then try to call a method, named by the contents of the variable $cfg{ESX}{host}.. A variable that doesn't exist!

If you want to use the tie interface, add a return \%cfg; to the end of config_file. If you want to use the object interface.. Well, I can only point you to the docs.

ContentLicense: CC BY-SA 2.5

Body:
I am trying to use the tie function of the module Config::IniFiles but I cannot figure out how to reference the hash inside of sub routine. If I remove the tie function and related code from the sub routine it works perfectly.

This is the line I thought would work, but tells me that "$cfg" is not initialized.

use Config::IniFiles
sub config_file {
    my $cfg_file = 'settings.ini';
    my %cfg;
    tie %cfg, 'Config::IniFiles', ( -file => "$cfg_file" );

    #my $cfg = Config::IniFiles->new( -file => $cfg_file );

}

sub esx_host_check {
    my $esx_host = config_file()->$cfg{ESX}{host};
}

I am sure it is something simple, but I am stumped.


问:
To PyQt5 'connect' conversion
I try to make a conversion of some code from PyQt4 to PyQt5, however I have not ever worked with PyQt, that is why I have some problems with this. I failed to convert some code with .connect, because as I understand in PyQt5 work with signals and slots changed. Here is the code.

```<code>class Gui(QWidget.QMainWindow, Ui_MainWindow):

    def __init__(self, cfgpath):
        QWidget.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)

        self.configpath = cfgpath
        self.paint = Viewer(self)
        self.setupUi(self)

        self.loadButton.clicked.connect(self.loadImage)
        self.maskClearButton.clicked.connect(self.paint.clearMask)
        self.brushSizeSB.valueChanged.connect(self.brushSizeChange)
        btnlist = [self.horDownBtn, self.horDownLargeBtn, self.horUpBtn, self.horUpLargeBtn,
                   self.vertDownBtn, self.vertDownLargeBtn, self.vertUpBtn, self.vertUpLargeBtn]
        sigmap = QtCore.QSignalMapper(self)
        for i in range(len(btnlist)):
            # Here it falls
            self.connect(btnlist[i], QtCore.SIGNAL("clicked()"), sigmap, QtCore.SLOT("map()"))
            btnlist[i].clicked
            sigmap.setMapping(btnlist[i], i)
        # And here
        self.connect(sigmap, QtCore.SIGNAL("mapped(int)"), self.paint.handleScaleBtn)
</code>```

So how can I change this code to make it work?

答:
The new connection style is as follows:

```<code>sender.signal.connect(slot)
</code>```

In your case change:

```<code>self.connect(btnlist[i], QtCore.SIGNAL("clicked()"), sigmap, QtCore.SLOT("map()"))

self.connect(sigmap, QtCore.SIGNAL("mapped(int)"), self.paint.handleScaleBtn)
</code>```

to

```<code>btnlist[i].clicked.connect(sigmap.map)

sigmap.mapped.connect(self.paint.handleScaleBtn)
</code>```

Title: To PyQt5 'connect' conversion

Body:
I try to make a conversion of some code from PyQt4 to PyQt5, however I have not ever worked with PyQt, that is why I have some problems with this. I failed to convert some code with .connect, because as I understand in PyQt5 work with signals and slots changed. Here is the code.

class Gui(QWidget.QMainWindow, Ui_MainWindow):

    def __init__(self, cfgpath):
        QWidget.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)

        self.configpath = cfgpath
        self.paint = Viewer(self)
        self.setupUi(self)

        self.loadButton.clicked.connect(self.loadImage)
        self.maskClearButton.clicked.connect(self.paint.clearMask)
        self.brushSizeSB.valueChanged.connect(self.brushSizeChange)
        btnlist = [self.horDownBtn, self.horDownLargeBtn, self.horUpBtn, self.horUpLargeBtn,
                   self.vertDownBtn, self.vertDownLargeBtn, self.vertUpBtn, self.vertUpLargeBtn]
        sigmap = QtCore.QSignalMapper(self)
        for i in range(len(btnlist)):
            # Here it falls
            self.connect(btnlist[i], QtCore.SIGNAL("clicked()"), sigmap, QtCore.SLOT("map()"))
            btnlist[i].clicked
            sigmap.setMapping(btnlist[i], i)
        # And here
        self.connect(sigmap, QtCore.SIGNAL("mapped(int)"), self.paint.handleScaleBtn)

So how can I change this code to make it work?

Body:
The new connection style is as follows:

sender.signal.connect(slot)

In your case change:

self.connect(btnlist[i], QtCore.SIGNAL("clicked()"), sigmap, QtCore.SLOT("map()"))

self.connect(sigmap, QtCore.SIGNAL("mapped(int)"), self.paint.handleScaleBtn)

to

btnlist[i].clicked.connect(sigmap.map)

sigmap.mapped.connect(self.paint.handleScaleBtn)

ContentLicense: CC BY-SA 4.0


问:
How to get output of awk into a tab-delimited file merging two lines to a line every time?
I have multiple files in gz format and used this script which counts lines in each file and prints 1/4 of lines for each file:

```<code>for file in *.gz;
do echo $file;
gunzip -c $file | wc -l | awk '{print, $1/4}';
done
</code>```

STDOUT:

```<code>AB.gz
12
CD.gz
4
</code>```

How I can pipe outputs of awk into a tab-delimited file like this merging two lines each time:

```<code>AB.gz 12
CD.gz 4
</code>```

I tried paste by piping | paste -sd '\t' > output.txt in the script but it didn't work.

答:
Do not echo a newline after the file:</p>

```<code>for file in *.gz;
do
   printf "%s " "${file}"
   gunzip -c $file | wc -l | awk '{print, $1/4}';
done
</code>```

Body:
I have multiple files in gz format and used this script which counts lines in each file and prints 1/4 of lines for each file:

for file in *.gz;
do echo $file;
gunzip -c $file | wc -l | awk '{print, $1/4}';
done

STDOUT:

AB.gz
12
CD.gz
4

How I can pipe outputs of awk into a tab-delimited file like this merging two lines each time:

AB.gz 12
CD.gz 4

I tried paste by piping | paste -sd '\t' > output.txt in the script but it didn't work.

Body:
Do not echo a newline after the file:

for file in *.gz;
do
   printf "%s " "${file}"
   gunzip -c $file | wc -l | awk '{print, $1/4}';
done


问:
NodeJS Identify once
I want variable identify once so;

├── project_folder

|   ├── app.js //main file

|   └── router/index.js

app.js

```<code>const express = require('express');
const app = express();
const path = require('path');
const router = require('./router/index');
const mysql = require('mysql');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use('/',router);

app.listen( 8000, function(){
    console.log( 'Server listening on * 8000' );
});
</code>```

index.js

```<code>//other codes
const connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'wordpress'
});

connection.connect(function(err){
    if(err)
        console.log(err);
});
//other codes
</code>```

error : mysql is not defined

I don't want identify mysql and other variables again.

How can I solve?

Thank you for your helping.

SOLVED

Create a settings.js
Define settings in file

EXAMPLE

```<code>const testSettings = "test Settings...";

module.exports = {
    test:testSettings
}
</code>```

In a file you want
require('./settings');

Using: settings.test

答:
As others answers pointed, you should import module using 'require()' when you want to access it in the file.

If you are asking how to initialize db connection without initializing it in every file, you can create module for db connection.

Check Dave's answer on this topic how does createConnection work with nodeJS in mysql?

Title: NodeJS Identify once

Body:
I want variable identify once so;

├── project_folder

|   ├── app.js //main file

|   └── router/index.js

app.js

const express = require('express');
const app = express();
const path = require('path');
const router = require('./router/index');
const mysql = require('mysql');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use('/',router);

app.listen( 8000, function(){
    console.log( 'Server listening on * 8000' );
});

index.js

//other codes
const connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : 'root',
    database : 'wordpress'
});

connection.connect(function(err){
    if(err)
        console.log(err);
});
//other codes

error : mysql is not defined

I don't want identify mysql and other variables again.

How can I solve?

Thank you for your helping.

SOLVED

Create a settings.js
Define settings in file

EXAMPLE

const testSettings = "test Settings...";

module.exports = {
    test:testSettings
}

In a file you want
require('./settings');

Using: settings.test


问:
Angularjs custom directive cannot work for ui-sref
First, this works: {{ student.Name }}
Which supports that my router works fine.

I create a custom directive: link: "=link"

```<code><div ng-if="$ctrl.link && $ctrl.link.Name && $ctrl.link.State">
            <a ui-sref="{{$ctrl.link.State}}">{{$ctrl.link.Name}}</a>
</div>
</code>```

Why this cannot work:

```<code><div link="{ Name: 'View Students', State: 'students({courseId: $ctrl.Course.Id})' }">
</code>```

Here is the error:

Transition Rejection($id: 0 type: 6, message: The transition errored, detail: Error: Param values not valid for state ‘students’)

Update:
My custom directive

```<code>angular.module('Foo').component('Bar', {
        controller: LinkController,
        templateUrl: "link.tpl.html",
        transclude: true,
        bindings: {
            link: "=link",
    });
</code>```

答:
I solved this problem as below:

How I debug: I try to replace ‘$ctrl.Course.Id’ with 123 (Number), it works. So I know my custom link directive is working.

```<code><div link="{ Name: 'View Students', State: 'students({courseId: $ctrl.Course.Id})' }">
</code>```

Then I realized that it is because I put this ‘$ctrl.Course.Id’ inside the single quote, it will parse it as a string, instead of a number.

So, this is what I did:

Go to component, make an object:

this.studentsLink = { Name: 'View Students', State: 'students({courseId:'.concat(this.$stateParams.courseId, '})')};

My this.$stateParams.courseId is a string. If it is a number, we should do this.$stateParams.courseId.toString()

Then go to Template:

```<code><div link="$ctrl.studentsLink">
</code>```

Hope this help future developers who have the same problem.

Body:
First, this works: {{ student.Name }}
Which supports that my router works fine.

I create a custom directive: link: "=link"

            {{$ctrl.link.Name}}

Why this cannot work:

Here is the error:

Transition Rejection($id: 0 type: 6, message: The transition errored, detail: Error: Param values not valid for state ‘students’)

Update:
My custom directive

angular.module('Foo').component('Bar', {
        controller: LinkController,
        templateUrl: "link.tpl.html",
        transclude: true,
        bindings: {
            link: "=link",
    });

Body:
I solved this problem as below:

How I debug: I try to replace ‘$ctrl.Course.Id’ with 123 (Number), it works. So I know my custom link directive is working.

<div link="{ Name: 'View Students', State: 'students({courseId: $ctrl.Course.Id})' }">

Then I realized that it is because I put this ‘$ctrl.Course.Id’ inside the single quote, it will parse it as a string, instead of a number.

So, this is what I did:

Go to component, make an object:

this.studentsLink = { Name: 'View Students', State: 'students({courseId:'.concat(this.$stateParams.courseId, '})')};

My this.$stateParams.courseId is a string. If it is a number, we should do this.$stateParams.courseId.toString()

Then go to Template:

<div link="$ctrl.studentsLink">

Hope this help future developers who have the same problem.


问:
tkinter class composition not working
My intention is to create gui from several classes and as exercise I created small example. As can be seen in app self.greet should be button created from class Button, but what I get is generic button (without text and callback function).
Any suggestions?</p>

```<code>import tkinter as tk
import tkinter.ttk as ttk

class Button(ttk.Button):

    def __init__(self, parent):
        super().__init__(parent)

        self.item = ttk.Button(parent, text="Greet", command=self.greet)

    def greet(self):
        print("Greetings!")

class App():

    def __init__(self, parent):
        parent.title("A simple GUI")

        self.label = ttk.Label(parent, text="A label")
        self.greet = Button(parent)
        self.button = ttk.Button(parent, text="Close", command=parent.quit)

        self.label.grid(row=0, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))
        self.greet.grid(row=1, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))
        self.button.grid(row=2, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))

        parent.grid_columnconfigure(0, weight=1)

    def greet(self):
        print("Greetings!")

if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()
</code>```

答:
Your new class is a Button, it does not need to contain a Button.

```<code>class FlebasButton(ttk.Button):
    def __init__(self, master):
        super().__init__(master, text="Greet", command=self.greet)

    def greet(self):
        print("Greetings!")
</code>```

Also, pick a name other than "Button" for your new class so that you (and others) don't confuse it with the class from tk. And tkinter uses "master" internally for the parent class, so it's generally better to use "master" as well for tkinter objects.

Title: tkinter class composition not working

Body:
My intention is to create gui from several classes and as exercise I created small example. As can be seen in app self.greet should be button created from class Button, but what I get is generic button (without text and callback function).
Any suggestions?

import tkinter as tk
import tkinter.ttk as ttk

class Button(ttk.Button):

    def __init__(self, parent):
        super().__init__(parent)

        self.item = ttk.Button(parent, text="Greet", command=self.greet)

    def greet(self):
        print("Greetings!")

class App():

    def __init__(self, parent):
        parent.title("A simple GUI")

        self.label = ttk.Label(parent, text="A label")
        self.greet = Button(parent)
        self.button = ttk.Button(parent, text="Close", command=parent.quit)

        self.label.grid(row=0, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))
        self.greet.grid(row=1, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))
        self.button.grid(row=2, column=0, sticky=(tk.N, tk.S, tk.W, tk.E))

        parent.grid_columnconfigure(0, weight=1)

    def greet(self):
        print("Greetings!")

if __name__ == "__main__":
    root = tk.Tk()
    app = App(root)
    root.mainloop()

Body:
Your new class is a Button, it does not need to contain a Button.

class FlebasButton(ttk.Button):
    def __init__(self, master):
        super().__init__(master, text="Greet", command=self.greet)

    def greet(self):
        print("Greetings!")

Also, pick a name other than "Button" for your new class so that you (and others) don't confuse it with the class from tk. And tkinter uses "master" internally for the parent class, so it's generally better to use "master" as well for tkinter objects.


问:
How to stop Laravel (5.4) thinking a 3rd party API call is a Laravel controller?
I'm trying to integrate a 3rd party library (this video site API: https://github.com/SproutVideo/sproutvideo-php ) with my Laravel site. But I think this is a generic question.

The video API instructs me to call it like so:

```<code>SproutVideo::$api_key = 'abcd1234';
</code>```

or

```<code>$token = SproutVideo\UploadToken::create_upload_token();
</code>```

I put these calls inside a function in one of my Laravel controllers. Unfortunately when this function is called, I get the following kind of error:

(for the first example call above)

```<code>FatalThrowableError
Class 'App\Http\Controllers\SproutVideo' not found
</code>```

(or for the second:)

```<code>FatalThrowableError
Class 'App\Http\Controllers\SproutVideo\UploadToken' not found
</code>```

(I think) I've included the Sproutvideo library at the top of the Controller file:

```<code>require '../vendor/autoload.php'; // Load SproutVideo API library
</code>```

So how do I get Laravel to stop thinking the Sproutvideo API calls are Laravel controller calls, and just let them pass through to the Sproutvideo library?

Thanks

答:
You have to import it at the top with

```<code>use (Path To Lib in vendor directory)
</code>```

Then it's namespaced and you can use it. Otherwise use the fully qualified namspace directly in the code.

Although you import it via autoload (which really should happen not in the controller class itself when using Laravel btw *), you have to tell the controller class the namespace.

Have a look here

The autoloader sits in /bootstrap/autoload.php and references /vendor/autoload.php again. It is called in /public/index.php. It gets called with every request anyway :)

Body:
I'm trying to integrate a 3rd party library (this video site API: https://github.com/SproutVideo/sproutvideo-php ) with my Laravel site. But I think this is a generic question.

The video API instructs me to call it like so:

SproutVideo::$api_key = 'abcd1234';

or

$token = SproutVideo\UploadToken::create_upload_token();

I put these calls inside a function in one of my Laravel controllers. Unfortunately when this function is called, I get the following kind of error:

(for the first example call above)

FatalThrowableError
Class 'App\Http\Controllers\SproutVideo' not found

(or for the second:)

FatalThrowableError
Class 'App\Http\Controllers\SproutVideo\UploadToken' not found

(I think) I've included the Sproutvideo library at the top of the Controller file:

require '../vendor/autoload.php'; // Load SproutVideo API library

So how do I get Laravel to stop thinking the Sproutvideo API calls are Laravel controller calls, and just let them pass through to the Sproutvideo library?

Thanks

Body:
You have to import it at the top with

use (Path To Lib in vendor directory)

Then it's namespaced and you can use it. Otherwise use the fully qualified namspace directly in the code.

Although you import it via autoload (which really should happen not in the controller class itself when using Laravel btw *), you have to tell the controller class the namespace.

Have a look here

The autoloader sits in /bootstrap/autoload.php and references /vendor/autoload.php again. It is called in /public/index.php. It gets called with every request anyway :)


问:
Make div container auto-expand width to the left instead of the right when text is added
I have a little dropdown, which works just fine:

However, when more text is added to the dropdown, the div expands to the right, like so:

Whereas I'd rather it expand to the left.

Markup/Blade (I'm using Laravel):

```<code><div class="status-dropdown-arrow pointer" id="status-dropdown-arrow-{{ $status->id }}" data-value="{{ $status->id }}"><i class="fa fa-angle-down" aria-hidden="true"></i>
 <ul class="fallback">
    @if (Auth::user()->isFollowing($status->user))
     <a href="{{ route('get.following.add', ['username' => $status->user->username]) }}"><li>Unfollow</li></a>
    @else
     <a href="{{ route('get.following.add', ['username' => $status->user->username]) }}"><li>Follow</li></a>
    @endif
    <a href="{{ route('status.report', ['statusId' => $status->id]) }}"><li>Report</li></a>
 </ul>
</div>
</code>```

CSS:

```<code>.status-dropdown-arrow {
float:right;
margin-top: -58px;
color:#b9adad;
}

.status-dropdown-arrow ul.fallback {
position: absolute;
border: 1px solid #d8d8d8;
border-radius: 3px;
padding: 5px;
display: none;
z-index: 1000;
background-color: #f6f4f4;
list-style: none;
margin-top: 0px;
margin-left: -72px;
}
</code>```

How could I make the container expand to the left rather than the right?

答: Set rigth: 0 on .status-dropdown-arrow ul.fallback and position: relative on .status-dropdown-arrow should do the job.

Body:
I have a little dropdown, which works just fine:

However, when more text is added to the dropdown, the div expands to the right, like so:

Whereas I'd rather it expand to the left.

Markup/Blade (I'm using Laravel):

id }}" data-value="{{ $status->id }}">

    @if (Auth::user()->isFollowing($status->user))
      $status->user->username]) }}">
Unfollow

    @else
      $status->user->username]) }}">
Follow

    @endif
     $status->id]) }}">
Report

CSS:

.status-dropdown-arrow {
float:right;
margin-top: -58px;
color:#b9adad;
}

.status-dropdown-arrow ul.fallback {
position: absolute;
border: 1px solid #d8d8d8;
border-radius: 3px;
padding: 5px;
display: none;
z-index: 1000;
background-color: #f6f4f4;
list-style: none;
margin-top: 0px;
margin-left: -72px;
}

How could I make the container expand to the left rather than the right?


问:
Azure Media Analytics vs Cognitive Services Video API
Azure is coming is with new Video Analytics API under the Azure Media Analytics(AMA) bracket, and looks promising. In the meantime, Azure Cognitive Services has also come up with Video API which can do some of the analytics jobs which already exist in AMA.
                                                      Why is Microsoft following these two different tracks to come up with analytics solution, rather than having one team look at it completely ?</p>

答:
In addition to what Adarsh has stated above, the other area to watch out for is compliance requirements.  There are different terms of use for Cognitive Services like Video Indexer vs. Azure Media Services.  At this time, if you need a fully compliant service with the Azure Terms of services, then you should look at Azure Media Services/Analytics.  If you are ok with the Cognitive Services terms of service and lack of full compliance that Azure has, then you can look at videoindexer.ai.  </p>

<p>Over time, we will be bringing more compliance to the Video Indexer platform as well, but since that is a newer set of features it will take some time. </p>

Body:
In addition to what Adarsh has stated above, the other area to watch out for is compliance requirements.  There are different terms of use for Cognitive Services like Video Indexer vs. Azure Media Services.  At this time, if you need a fully compliant service with the Azure Terms of services, then you should look at Azure Media Services/Analytics.  If you are ok with the Cognitive Services terms of service and lack of full compliance that Azure has, then you can look at videoindexer.ai.

Over time, we will be bringing more compliance to the Video Indexer platform as well, but since that is a newer set of features it will take some time.


问:
Inequalities on pandas column
I have a pandas dataframe, and I would like to create a new column based on an existing column and certain inequalities. For example, let

```<code>df=pd.DataFrame({'a':[1,2,3,4,5,6,7],'b':[3,6,4,2,7,7,1]})
</code>```

so df looks like

```<code>    a   b
0   1   3
1   2   6
2   3   4
3   4   2
4   5   7
5   6   7
6   7   1
</code>```

I would like to add a new column, res, that equals 0 if the corresponding value in a is smaller than 2, 1 if the corresponding value in a is at least 2 and smaller than 4, and 2 otherwise. So I would like to get

```<code>    a   b   res
0   1   3   0
1   2   6   1
2   3   4   1
3   4   2   2
4   5   7   2
5   6   7   2
6   7   1   2
</code>```

So far I have been doing this by using apply as follows:

```<code>def f(x):
    if x['a']<2:
        return 0
    elif x['a']>=2 and x['a']<4:
        return 1
    else:
        return 2
df['res']=df.apply(f,axis=1)
</code>```

but I was wondering if there is a more direct way, or some specific pandas method that can enable me to do that.

答:
searchsorted

Should give you more performant results.  Similar to pd.cut, you need specify the break points.

pandas

pd.Series.searchsorted

```<code>df.assign(res=pd.Series([2, 4]).searchsorted(df.a, side='right'))

   a  b  res
0  1  3    0
1  2  6    1
2  3  4    1
3  4  2    2
4  5  7    2
5  6  7    2
6  7  1    2
</code>```

numpy

ndarray.searchsorted

```<code>df.assign(res=np.array([2, 4]).searchsorted(df.a.values, side='right'))

   a  b  res
0  1  3    0
1  2  6    1
2  3  4    1
3  4  2    2
4  5  7    2
5  6  7    2
6  7  1    2
</code>```

Timing

```<code>%timeit df.assign(res=pd.Series([2, 4]).searchsorted(df.a, side='right'))
%timeit df.assign(res=np.array([2, 4]).searchsorted(df.a.values, side='right'))
%timeit df.assign(res=pd.np.where(df.a < 2, 0, pd.np.where((df.a >= 2) & (df.a < 4), 1, 2)))
%timeit df.assign(res=pd.cut(df.a, [-np.inf,2,4,np.inf], labels=[0,1,2], right=False))

1000 loops, best of 3: 443 µs per loop
1000 loops, best of 3: 337 µs per loop
1000 loops, best of 3: 1.06 ms per loop
1000 loops, best of 3: 530 µs per loop
</code>```

Title: Inequalities on pandas column

Body:
I have a pandas dataframe, and I would like to create a new column based on an existing column and certain inequalities. For example, let

df=pd.DataFrame({'a':[1,2,3,4,5,6,7],'b':[3,6,4,2,7,7,1]})

so df looks like

    a   b
0   1   3
1   2   6
2   3   4
3   4   2
4   5   7
5   6   7
6   7   1

I would like to add a new column, res, that equals 0 if the corresponding value in a is smaller than 2, 1 if the corresponding value in a is at least 2 and smaller than 4, and 2 otherwise. So I would like to get

    a   b   res
0   1   3   0
1   2   6   1
2   3   4   1
3   4   2   2
4   5   7   2
5   6   7   2
6   7   1   2

So far I have been doing this by using apply as follows:

def f(x):
    if x['a']<2:
        return 0
    elif x['a']>=2 and x['a']<4:
        return 1
    else:
        return 2
df['res']=df.apply(f,axis=1)

but I was wondering if there is a more direct way, or some specific pandas method that can enable me to do that.

Body:
searchsorted

Should give you more performant results.  Similar to pd.cut, you need specify the break points.

pandas

pd.Series.searchsorted

df.assign(res=pd.Series([2, 4]).searchsorted(df.a, side='right'))

   a  b  res
0  1  3    0
1  2  6    1
2  3  4    1
3  4  2    2
4  5  7    2
5  6  7    2
6  7  1    2

numpy

ndarray.searchsorted

df.assign(res=np.array([2, 4]).searchsorted(df.a.values, side='right'))

   a  b  res
0  1  3    0
1  2  6    1
2  3  4    1
3  4  2    2
4  5  7    2
5  6  7    2
6  7  1    2

Timing

%timeit df.assign(res=pd.Series([2, 4]).searchsorted(df.a, side='right'))
%timeit df.assign(res=np.array([2, 4]).searchsorted(df.a.values, side='right'))
%timeit df.assign(res=pd.np.where(df.a < 2, 0, pd.np.where((df.a >= 2) & (df.a < 4), 1, 2)))
%timeit df.assign(res=pd.cut(df.a, [-np.inf,2,4,np.inf], labels=[0,1,2], right=False))

1000 loops, best of 3: 443 µs per loop
1000 loops, best of 3: 337 µs per loop
1000 loops, best of 3: 1.06 ms per loop
1000 loops, best of 3: 530 µs per loop


问:
Define MySQL field name as a variable
Is there a way to set a field name as a variable in MySQL?
For example:

```<code>set @gender = (table_name.gender_column);

select * from table_name
where find_in_set(table_name.gender_column, @gender);
</code>```

This is exactly how i have tried it but i it returns "Unknown table in field list".

Thanks in advance,

Mike

EDIT:  The aim is to use the variables in dynamic crystal report parameters.  But what i dont want to do is have to add a new type of gender every time a new one comes along.

E.G.  I have 'Male' and 'Female' and am adding 'Trans-gender'.  I want the dynamic parameter in Crystal to present the 'Trans-gender' variable in the parameter when it is added to the gender_column.  I dont want to have to revisit the multiple queries that use the variable to add 'Trans-gender' to it.

答:
Is there a way to set a field name as a variable in MySQL?

No.  SQL doesn't allow variables for schema, table, or column names.

There's a workaround in which you can use text-string processing to create a query, then run it.  Something like this may help.

```<code>PREPARE query
  FROM CONCAT ('select * from table_name',
               'where find_in_set(table_name.gender_column, '
               @variable,
               ');'
              );

EXEC query;

DEALLOCATE PREPARE query;
</code>```

This may be a roundabout way of doing what you want.  The technical term is "big fat hairball."

Title: Define MySQL field name as a variable

Body:
Is there a way to set a field name as a variable in MySQL?
For example:

set @gender = (table_name.gender_column);

select * from table_name
where find_in_set(table_name.gender_column, @gender);

This is exactly how i have tried it but i it returns "Unknown table in field list".

Thanks in advance,

Mike

EDIT:  The aim is to use the variables in dynamic crystal report parameters.  But what i dont want to do is have to add a new type of gender every time a new one comes along.

E.G.  I have 'Male' and 'Female' and am adding 'Trans-gender'.  I want the dynamic parameter in Crystal to present the 'Trans-gender' variable in the parameter when it is added to the gender_column.  I dont want to have to revisit the multiple queries that use the variable to add 'Trans-gender' to it.

Body:
Is there a way to set a field name as a variable in MySQL?

No.  SQL doesn't allow variables for schema, table, or column names.

There's a workaround in which you can use text-string processing to create a query, then run it.  Something like this may help.

PREPARE query
  FROM CONCAT ('select * from table_name',
               'where find_in_set(table_name.gender_column, '
               @variable,
               ');'
              );

EXEC query;

DEALLOCATE PREPARE query;

This may be a roundabout way of doing what you want.  The technical term is "big fat hairball."


问:
batch file for curl
I would like to create a windows batch file for a curl command that will run every five minutes and save it to a local file. Here's my curl command

```<code>curl -k https://root:password@rbc-v1-ml/webacs/api/v1data/ClientDetails?.full=true > C:\Users\Desktop\Sample1\curl
</code>```

May I ask how can I do a batch file?

答:
Something like this: ?

```<code>@echo off
echo Begining at %time%
set file=https://root:password@rbc-v1-ml/webacs/api/v1data/ClientDetails?.full=true
if not exist "C:\Users\Desktop\Sample1\curl" echo. > "C:\Users\Desktop\Sample1\curl"
:top
echo Ran at %time%
curl -k %file% >> C:\Users\Desktop\Sample1\curl
echo waiting 5 minutes... Press Q to download now.
choice /c q /d q /t 300 /n
goto top
</code>```

Note: You may need to change the URL from

```<code>https://root:password@rbc-v1-ml/webacs/api/v1data/ClientDetails?.full=true
</code>```

to

```<code>https://root:password@rbc-v1-ml/webacs/api/v1data/ClientDetails?.full^=true
</code>```

I'm not quite sure how it will handle it.

Title: batch file for curl

Body:
I would like to create a windows batch file for a curl command that will run every five minutes and save it to a local file. Here's my curl command

curl -k https://root:password@rbc-v1-ml/webacs/api/v1data/ClientDetails?.full=true > C:\Users\Desktop\Sample1\curl

May I ask how can I do a batch file?

Body:
Something like this: ?

@echo off
echo Begining at %time%
set file=https://root:password@rbc-v1-ml/webacs/api/v1data/ClientDetails?.full=true
if not exist "C:\Users\Desktop\Sample1\curl" echo. > "C:\Users\Desktop\Sample1\curl"
:top
echo Ran at %time%
curl -k %file% >> C:\Users\Desktop\Sample1\curl
echo waiting 5 minutes... Press Q to download now.
choice /c q /d q /t 300 /n
goto top

Note: You may need to change the URL from

https://root:password@rbc-v1-ml/webacs/api/v1data/ClientDetails?.full=true

to

https://root:password@rbc-v1-ml/webacs/api/v1data/ClientDetails?.full^=true

I'm not quite sure how it will handle it.


问:
Very Slow network graph animation in Python's matplotlib with networkx
I am tyring to animate a networkx graph growing over time. I have
it working with curved edges and all. Quite pleased, BUT as the graph
grows it slows down Considerably !? Can anyone explain or alter the code given to run faster. I don't think it's my computer that is the problem.
NOTE: EVEN without the fancy curved edges it was very slow. A simple nx.draw would cause the same problem

```<code>import time
from matplotlib import pyplot as plt
from matplotlib import animation
import networkx as nx
from matplotlib.patches import FancyArrowPatch, Circle
import numpy as np

mainGraph = nx.DiGraph()
nodeToCoordinate_dict = {}
label_coordinatePositions = {}
edgeLabel_coordinatePositions = {}
edgeLabel_values_dict = {}
fig = plt.figure()

#=============================================================

def draw_network(G,pos,ax,sg=None):
    e = None
    for n in G:
        c=Circle(pos[n],radius=0.02,alpha=0.5)
        ax.add_patch(c)
        G.node[n]['patch']=c
        x,y=pos[n]
    seen={}
    for (u,v,d) in G.edges(data=True):
        n1=G.node[u]['patch']
        n2=G.node[v]['patch']
        rad=0.1
        if (u,v) in seen:
            rad=seen.get((u,v))
            rad=(rad+np.sign(rad)*0.1)*-1
        alpha=0.5
        color='k'

        e = FancyArrowPatch(n1.center,n2.center,patchA=n1,patchB=n2,
                            arrowstyle='-|>',
                            connectionstyle='arc3,rad=%s'%rad,
                            mutation_scale=10.0,
                            lw=2,
                            alpha=alpha,
                            color=color)
        seen[(u,v)]=rad
        ax.add_patch(e)

    return e

#========================================================

def animate(i):
    startTime = time.time()
    """perform animation step"""
    global mainGraph, nodeToCoordinate_dict, label_coordinatePositions

    mainGraph.add_node(str(i%20)+","+str(i/20), pos = (i%20,i/20))
    if not (i%20 == 0):
        mainGraph.add_edge(str(i%20-1)+","+str(i/20), str(i%20)+","+str(i/20))
        prevNode_coordinate = nodeToCoordinate_dict[str(i%20-1)+","+str(i/20)]

        mainGraph[str(i%20-1)+","+str(i/20)][str(i%20)+","+str(i/20)]['p'] = 1.0
    #END IF
    nodeToCoordinate_dict[str(i%20)+","+str(i/20)] = (i%20,i/20)
    ax=plt.gca()
    draw_network(mainGraph,nodeToCoordinate_dict,ax)
    ax.autoscale()
    plt.axis('equal')
    plt.axis('off')
    print("time Elapsed = ", time.time()-startTime)
    return None #mainGraph

#====================================================

ani = animation.FuncAnimation(fig, animate, frames= 60,interval=1000)
plt.show()
</code>```

答:
I Think I figured it out. The function that uses "matplotlib.patches import FancyArrowPatch, Circle" is slowing it down. This is the "draw_network" function.

I tried replacing the drawing code with the simpler (nx.draw(mainGraph, nodeToCoordinate_dict)) and reduced the time interval to 100 (0.1 seconds). Worked like a charm

Now, I just need to figure a way of speeding up the graph with curved edges.

Body:
I am tyring to animate a networkx graph growing over time. I have
it working with curved edges and all. Quite pleased, BUT as the graph
grows it slows down Considerably !? Can anyone explain or alter the code given to run faster. I don't think it's my computer that is the problem.
NOTE: EVEN without the fancy curved edges it was very slow. A simple nx.draw would cause the same problem

import time
from matplotlib import pyplot as plt
from matplotlib import animation
import networkx as nx
from matplotlib.patches import FancyArrowPatch, Circle
import numpy as np

mainGraph = nx.DiGraph()
nodeToCoordinate_dict = {}
label_coordinatePositions = {}
edgeLabel_coordinatePositions = {}
edgeLabel_values_dict = {}
fig = plt.figure()

#=============================================================

def draw_network(G,pos,ax,sg=None):
    e = None
    for n in G:
        c=Circle(pos[n],radius=0.02,alpha=0.5)
        ax.add_patch(c)
        G.node[n]['patch']=c
        x,y=pos[n]
    seen={}
    for (u,v,d) in G.edges(data=True):
        n1=G.node[u]['patch']
        n2=G.node[v]['patch']
        rad=0.1
        if (u,v) in seen:
            rad=seen.get((u,v))
            rad=(rad+np.sign(rad)*0.1)*-1
        alpha=0.5
        color='k'

        e = FancyArrowPatch(n1.center,n2.center,patchA=n1,patchB=n2,
                            arrowstyle='-|>',
                            connectionstyle='arc3,rad=%s'%rad,
                            mutation_scale=10.0,
                            lw=2,
                            alpha=alpha,
                            color=color)
        seen[(u,v)]=rad
        ax.add_patch(e)

    return e

#========================================================

def animate(i):
    startTime = time.time()
    """perform animation step"""
    global mainGraph, nodeToCoordinate_dict, label_coordinatePositions

    mainGraph.add_node(str(i%20)+","+str(i/20), pos = (i%20,i/20))
    if not (i%20 == 0):
        mainGraph.add_edge(str(i%20-1)+","+str(i/20), str(i%20)+","+str(i/20))
        prevNode_coordinate = nodeToCoordinate_dict[str(i%20-1)+","+str(i/20)]

        mainGraph[str(i%20-1)+","+str(i/20)][str(i%20)+","+str(i/20)]['p'] = 1.0
    #END IF
    nodeToCoordinate_dict[str(i%20)+","+str(i/20)] = (i%20,i/20)
    ax=plt.gca()
    draw_network(mainGraph,nodeToCoordinate_dict,ax)
    ax.autoscale()
    plt.axis('equal')
    plt.axis('off')
    print("time Elapsed = ", time.time()-startTime)
    return None #mainGraph

#====================================================

ani = animation.FuncAnimation(fig, animate, frames= 60,interval=1000)
plt.show()


问:
Conditional won't execute properly
I wonder if you could help me with the code below:

```<code>min = None
max = None
while True:
    input = raw_input("Please enter number: ")
    if input == "done":
        break
    else:
        try:
            input = float(input)
        except:
            continue

    if max < input:
        max = input
    elif min > input:
        min = input

    print min
    print max
</code>```

It looks right to me, but the elif statement which gives a value to min always prints None. Could you please explain why?

答:
None > number is never true, because Python 2 sorts None before any other type. Don't compare numbers with None.

Either test for None explicitly, or replace None with an infinity value.

Testing for None:

```<code>if max is None or max < input:
    max = input
elif min is None or min > input:
    min = input
</code>```

Setting the values to positive or negative infinity:

```<code>min = float('inf')
max = float('-inf')
</code>```

By setting min to positive infinity, any other number is guaranteed to be smaller; the same applies to max negative infinity.

Title: Conditional won't execute properly

Body:
I wonder if you could help me with the code below:

min = None
max = None
while True:
    input = raw_input("Please enter number: ")
    if input == "done":
        break
    else:
        try:
            input = float(input)
        except:
            continue

    if max < input:
        max = input
    elif min > input:
        min = input

    print min
    print max

It looks right to me, but the elif statement which gives a value to min always prints None. Could you please explain why?

Body:
None > number is never true, because Python 2 sorts None before any other type. Don't compare numbers with None.

Either test for None explicitly, or replace None with an infinity value.

Testing for None:

if max is None or max < input:
    max = input
elif min is None or min > input:
    min = input

Setting the values to positive or negative infinity:

min = float('inf')
max = float('-inf')

By setting min to positive infinity, any other number is guaranteed to be smaller; the same applies to max negative infinity.


问:
MySQL - How Can I Automate a View Query That Subtracts Metrics From the Most Recent Date To The Previous Day & Date Stamps The Most Recent Data
I have a daily API call that gives me LIFETIME data for a unique ID and date stamps the data batch every day at midnight. This data is appended to a database in MySQL, but I need to transform it in a way where I can get daily data for that unique id for every metric.

My Table in MySQL:

Desired Output:

For id 3 I took the previous day (7/3/2017) and most recent date (7/4/2017) difference for it's respective metrics (Impressions, Clicks) and time stamped that line item as 7/4/2017. I need to process this type of transformation by id for multiple ids and metrics. Thank you!

UPDATE of My Query Based on Jacob's Feedback:

```<code>CREATE VIEW `facebook_insights` AS
SELECT
  t1.id
, t1.timestamp
, t1.message
, t1.posted
, t1.permalink_url
, t1.caption
, t1.link
, t1.type
, t1.post_impressions - t2.post_impressions as Impressions
, t1.post_impressions_organic - t2.post_impressions_organic as Post_Impressions_Organic
, t1.post_impressions_paid - t2.post_impressions_paid as Post_Impressions_Paid
, t1.post_engaged_users - t2.post_engaged_users as Post_Engaged_Users
, t1.post_consumptions - t2.post_consumptions as Post_Consumptions
, t1.post_negative_feedback - t2.post_negative_feedback as
Post_Negative_Feedback
, t1.post_negative_feedback_unique - t2.Post_Negative_Feedback_Unique as
Post_Negative_Feedback_Unique
, t1.post_impressions_fan - t2.post_impressions_fan as Post_Impressions_Fan
, t1.post_impressions_fan_paid - t2.post_impressions_fan_paid as
Post_Impressions_Fan_Paid
, t1.post_engaged_fan - t2.Post_Engaged_Fan as Post_Engaged_Fan
, t1.post_video_complete_views_organic -
t2.post_video_complete_views_organic as Post_Video_Complete_Views_Organic
, t1.post_video_complete_views_paid - t2.post_video_complete_views_paid as
Post_Video_Complete_Views_Paid
, t1.post_video_views_10s - t2.post_video_views_10s as Post_Video_Views_10s
, t1.post_video_views_10s_unique - t2.post_video_views_10s_unique as
Post_Video_Views_10s_Unique
, t1.post_video_views_organic - t2.post_video_views_organic as
Post_Video_Views_Organic
, t1.post_video_views_paid - t2.post_video_views_paid as
Post_Video_Views_Paid
, t1.post_video_views_clicked_to_play - t2.post_video_views_clicked_to_play
as Post_Video_Views_Clicked_to_Play

FROM
unpaid_media.facebook_insight t1
JOIN unpaid_media.facebook_insight t2
ON t1.id = t2.id
and t1.timestamp  = t2.timestamp + INTERVAL 1 DAY
</code>```

答:
It looks like a grouping function can be useful as it looks like you want to aggregate the impressions and clicks by date and ID. Also, you didnt mention this data required any joins (yet), so this is assuming it's in a single table. Below in T-SQL: </p>

```<code>USE DatabaseName
GO

SELECT T.ID,
       (CAST(T.TimeStamp) as Date) as Date,
       SUM(T.Impressions) as TotalImpressionsPerDay,
       SUM(T.Clicks) as TotalClicksPerDay
FROM TableName as T
GROUP BY ID, (CAST(T.TimeStamp) as Date)
ORDER BY ID ASC
</code>```

Body:
I have a daily API call that gives me LIFETIME data for a unique ID and date stamps the data batch every day at midnight. This data is appended to a database in MySQL, but I need to transform it in a way where I can get daily data for that unique id for every metric.

My Table in MySQL:

Desired Output:

For id 3 I took the previous day (7/3/2017) and most recent date (7/4/2017) difference for it's respective metrics (Impressions, Clicks) and time stamped that line item as 7/4/2017. I need to process this type of transformation by id for multiple ids and metrics. Thank you!

UPDATE of My Query Based on Jacob's Feedback:

CREATE VIEW `facebook_insights` AS
SELECT
  t1.id
, t1.timestamp
, t1.message
, t1.posted
, t1.permalink_url
, t1.caption
, t1.link
, t1.type
, t1.post_impressions - t2.post_impressions as Impressions
, t1.post_impressions_organic - t2.post_impressions_organic as Post_Impressions_Organic
, t1.post_impressions_paid - t2.post_impressions_paid as Post_Impressions_Paid
, t1.post_engaged_users - t2.post_engaged_users as Post_Engaged_Users
, t1.post_consumptions - t2.post_consumptions as Post_Consumptions
, t1.post_negative_feedback - t2.post_negative_feedback as
Post_Negative_Feedback
, t1.post_negative_feedback_unique - t2.Post_Negative_Feedback_Unique as
Post_Negative_Feedback_Unique
, t1.post_impressions_fan - t2.post_impressions_fan as Post_Impressions_Fan
, t1.post_impressions_fan_paid - t2.post_impressions_fan_paid as
Post_Impressions_Fan_Paid
, t1.post_engaged_fan - t2.Post_Engaged_Fan as Post_Engaged_Fan
, t1.post_video_complete_views_organic -
t2.post_video_complete_views_organic as Post_Video_Complete_Views_Organic
, t1.post_video_complete_views_paid - t2.post_video_complete_views_paid as
Post_Video_Complete_Views_Paid
, t1.post_video_views_10s - t2.post_video_views_10s as Post_Video_Views_10s
, t1.post_video_views_10s_unique - t2.post_video_views_10s_unique as
Post_Video_Views_10s_Unique
, t1.post_video_views_organic - t2.post_video_views_organic as
Post_Video_Views_Organic
, t1.post_video_views_paid - t2.post_video_views_paid as
Post_Video_Views_Paid
, t1.post_video_views_clicked_to_play - t2.post_video_views_clicked_to_play
as Post_Video_Views_Clicked_to_Play

FROM
unpaid_media.facebook_insight t1
JOIN unpaid_media.facebook_insight t2
ON t1.id = t2.id
and t1.timestamp  = t2.timestamp + INTERVAL 1 DAY

Body:
It looks like a grouping function can be useful as it looks like you want to aggregate the impressions and clicks by date and ID. Also, you didnt mention this data required any joins (yet), so this is assuming it's in a single table. Below in T-SQL:

USE DatabaseName
GO

SELECT T.ID,
       (CAST(T.TimeStamp) as Date) as Date,
       SUM(T.Impressions) as TotalImpressionsPerDay,
       SUM(T.Clicks) as TotalClicksPerDay
FROM TableName as T
GROUP BY ID, (CAST(T.TimeStamp) as Date)
ORDER BY ID ASC


问:
Copy all styles from one element to another
How can i get every styles (even inherited) from an element A to an element B ? in javascript or using jquery.

let's tell i have an element
...
 and i append new element
 which would look like the same, except content.

答:
Try to copy every CSS-properties like this:

$("#target").css("border", $("#source").css("border"));
$("#target").css("background", $("#source").css("background"));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#source {
  background-color: #dfeacb !important;
  color: #bbae4e !important;
  border: 1px solid green !important;
}</code>```

<textArea id="source">Hello world!</textArea>
<textArea id="target">Hello world!</textArea>```

Why not? you can create the dictionary that may consists of all properties.

Body:
Try to copy every CSS-properties like this:

$("#target").css("border", $("#source").css("border"));
$("#target").css("background", $("#source").css("background"));

#source {
  background-color: #dfeacb !important;
  color: #bbae4e !important;
  border: 1px solid green !important;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textArea id="source">Hello world!</textArea>
<textArea id="target">Hello world!</textArea>

Why not? you can create the dictionary that may consists of all properties.


问:
Return last line of multiple matching records - Git Bash
I have two files.....

One file contains records:

```<code>123
456
789
abc
def
ghi
</code>```

Second file contains records:

```<code>123,a
123,b
456,a
456,b
789,a
789,b
abc,1
abc,2
def,1
def,2
ghi,1
ghi,2
</code>```

Trying to do a grep and tail command that would return the last line of a matching string in file 2 so that the output file would return the following:

```<code>123,b
456,b
789,b
abc,2
def,2
ghi,2
</code>```

Tried to use the following but it just returns the last line of the last matching record:

```<code>grep -f file1.txt file2.txt | tail -1 > output.txt
</code>```

答:
Use awk solution:

```<code>awk 'NR==FNR{ a[$0]; next }$1 in a{ b[$1]=$2 }END{ for(i in b) print i FS b[i] }' file1 FS=',' file2
</code>```

The output:

```<code>def,2
abc,2
ghi,2
123,b
456,b
789,b
</code>```

FS=',' - field separator

b[$1]=$2 - eventually contains the last 2nd field value for same 1st field values

Body:
I have two files.....

One file contains records:

123
456
789
abc
def
ghi

Second file contains records:

123,a
123,b
456,a
456,b
789,a
789,b
abc,1
abc,2
def,1
def,2
ghi,1
ghi,2

Trying to do a grep and tail command that would return the last line of a matching string in file 2 so that the output file would return the following:

123,b
456,b
789,b
abc,2
def,2
ghi,2

Tried to use the following but it just returns the last line of the last matching record:

grep -f file1.txt file2.txt | tail -1 > output.txt

Body:
Use awk solution:

awk 'NR==FNR{ a[$0]; next }$1 in a{ b[$1]=$2 }END{ for(i in b) print i FS b[i] }' file1 FS=',' file2

The output:

def,2
abc,2
ghi,2
123,b
456,b
789,b

FS=',' - field separator

b[$1]=$2 - eventually contains the last 2nd field value for same 1st field values


问:
How to get DB connection in grails 3
What is proper way to get DB connection in Grails 3?

For grails 2 following code has works:

```<code>((SessionImpl) sessionFactory.getCurrentSession()).connection() // sessionFactory initialized in bootstrap
</code>```

But after migration to Grails 3 sometimes I see exceptions in the log:

java.sql.SQLException: Operation not allowed after ResultSet closed at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957) at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896) at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885) at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860) at
  com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:743) at
  com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1037) at
  com.mysql.jdbc.ResultSetImpl.getLong(ResultSetImpl.java:2757) at
  com.mchange.v2.c3p0.impl.NewProxyResultSet.getLong(NewProxyResultSet.java:424)
  at java_sql_ResultSet$getLong$3.call(Unknown Source)

It happens for 0,01% of requests

Grails 3.2.11

Gorm 6.0.12

答:
I guess it depends on where you need it, but you can inject a DataSource into a service.

```<code>javax.sql.DataSource dataSource
</code>```

Then you can just use

```<code>dataSource.getConnection()
</code>```

Also be aware of the changes to flush mode in GORM 6 (http://gorm.grails.org/6.0.x/hibernate/manual/ section 1.2.1).  If an upstream save/commit is failing, your result set could be incidentally closed and trigger an error that looks like this while not really have anything to do with this particular line of code at all.  I'd (very temporarily) set back to the old flush mode and see if the problem goes away, before tracking much more down!

Title: How to get DB connection in grails 3

Body:
What is proper way to get DB connection in Grails 3?

For grails 2 following code has works:

((SessionImpl) sessionFactory.getCurrentSession()).connection() // sessionFactory initialized in bootstrap

But after migration to Grails 3 sometimes I see exceptions in the log:

java.sql.SQLException: Operation not allowed after ResultSet closed at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957) at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896) at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885) at
  com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860) at
  com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:743) at
  com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1037) at
  com.mysql.jdbc.ResultSetImpl.getLong(ResultSetImpl.java:2757) at
  com.mchange.v2.c3p0.impl.NewProxyResultSet.getLong(NewProxyResultSet.java:424)
  at java_sql_ResultSet$getLong$3.call(Unknown Source)

It happens for 0,01% of requests

Grails 3.2.11

Gorm 6.0.12

Body:
I guess it depends on where you need it, but you can inject a DataSource into a service.

javax.sql.DataSource dataSource

Then you can just use

dataSource.getConnection()

Also be aware of the changes to flush mode in GORM 6 (http://gorm.grails.org/6.0.x/hibernate/manual/ section 1.2.1).  If an upstream save/commit is failing, your result set could be incidentally closed and trigger an error that looks like this while not really have anything to do with this particular line of code at all.  I'd (very temporarily) set back to the old flush mode and see if the problem goes away, before tracking much more down!


问:
Repeating image count for both directories
I'm using the glob function in PHP to browse directories and trying to also match up only the image files. This is working but when I try to count the images in each directory, it repeats the count of the first directory for the others. For example, directory 1 has 6 images and directory 2 has 4 images but when I try to display the count for each directory, it shows 6 images for directory 2 and so forth.

Here is the code I have in place:

```<code>public function viewphotoalbumsAction()
{
    $identity = $this->identity();
    $dirname = array();
    $files = array();

    foreach (glob(getcwd() . '/public/images/profile/' . $identity . '/albums/*', GLOB_ONLYDIR) as $dir) {
        $dirname[] = basename($dir);

        foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images) {
            $files[] = $images;
        }
    }
    //var_dump($files); exit;

    $data = array(
        'albums' => array_values($dirname),
        'files'  => $files,
    );

    return new ViewModel(array('album' => $data['albums'], 'files' => $data['files']));
}
</code>```

The results of var_dump()

```<code> array(9) { [0]=> string(96) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/massive snow.jpg"
[1]=> string(91) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/mom-jon.jpg"
[2]=> string(90) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/sunset.jpg"
[3]=> string(85) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/cref.jpg"
[4]=> string(88) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/diploma.jpg"
[5]=> string(86) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/eeyor.jpg"
[6]=> string(93) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/frother-jaws.jpg"
[7]=> string(88) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/frother.jpg"
[8]=> string(93) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/goat_singing.jpg" }
</code>```

It is getting all the images from each directory as expected but what I really need to do is separate the images so I can have a accurate count for each directory and not just have it show the whole count (9)

The view code:

```<code><div class="w3-col m7">
    <div class="w3-row-padding">
        <div class="w3-col m12">
            <div class="w3-card-2 w3-round w3-white">
                <div class="w3-container w3-padding" id="view-photo-albums">
                    <p class="w3-center">Current Albums</p>
                    <br>
                    <?php
foreach ($this->album as $albums):
    ?>
                    <p>
                        <?php echo $albums; ?> - Number of images: <?php echo $this->files; ?>
                    </p>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

Any help would be appreciated.

Update:

I cannot use array_values for $data['files'] as I did for $data['albums'] as it is giving a warning of array to string conversion.

答:
I think you need to use foreach for files array also :

```<code>//its a demo
foreach(array_combine($a,$b) as $key=>$value) {
    echo $key."<br/>".$value;
}//its a demo
</code>```

Try this:

```<code><div class="w3-col m7">
<div class="w3-row-padding">
    <div class="w3-col m12">
        <div class="w3-card-2 w3-round w3-white">
            <div class="w3-container w3-padding" id="view-photo-albums">
                <p class="w3-center">Current Albums</p>
                <br>
                    <?php

 foreach(array_combine($this->album,$this->files) as $albums=>$files) :
    ?>
                    <p>
                        <?php echo $albums; ?> - Number of images: <?php echo files; ?>
                    </p>
                    <?php endforeach; ?>
                </div>
        </div>
    </div>
</div>
</code>```

Body:
I'm using the glob function in PHP to browse directories and trying to also match up only the image files. This is working but when I try to count the images in each directory, it repeats the count of the first directory for the others. For example, directory 1 has 6 images and directory 2 has 4 images but when I try to display the count for each directory, it shows 6 images for directory 2 and so forth.

Here is the code I have in place:

public function viewphotoalbumsAction()
{
    $identity = $this->identity();
    $dirname = array();
    $files = array();

    foreach (glob(getcwd() . '/public/images/profile/' . $identity . '/albums/*', GLOB_ONLYDIR) as $dir) {
        $dirname[] = basename($dir);

        foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images) {
            $files[] = $images;
        }
    }
    //var_dump($files); exit;

    $data = array(
        'albums' => array_values($dirname),
        'files'  => $files,
    );

    return new ViewModel(array('album' => $data['albums'], 'files' => $data['files']));
}

The results of var_dump()

 array(9) { [0]=> string(96) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/massive snow.jpg"
[1]=> string(91) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/mom-jon.jpg"
[2]=> string(90) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/sunset.jpg"
[3]=> string(85) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/cref.jpg"
[4]=> string(88) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/diploma.jpg"
[5]=> string(86) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/eeyor.jpg"
[6]=> string(93) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/frother-jaws.jpg"
[7]=> string(88) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/frother.jpg"
[8]=> string(93) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/goat_singing.jpg" }

It is getting all the images from each directory as expected but what I really need to do is separate the images so I can have a accurate count for each directory and not just have it show the whole count (9)

The view code:

Current Albums

                    <?php
foreach ($this->album as $albums):
    ?>

                        <?php echo $albums; ?> - Number of images: <?php echo $this->files; ?>

                    <?php endforeach; ?>

Any help would be appreciated.

Update:

I cannot use array_values for $data['files'] as I did for $data['albums'] as it is giving a warning of array to string conversion.

Body:
I think you need to use foreach for files array also :

//its a demo
foreach(array_combine($a,$b) as $key=>$value) {
    echo $key."<br/>".$value;
}//its a demo

Try this:

<div class="w3-col m7">
<div class="w3-row-padding">
    <div class="w3-col m12">
        <div class="w3-card-2 w3-round w3-white">
            <div class="w3-container w3-padding" id="view-photo-albums">
                <p class="w3-center">Current Albums</p>
                <br>
                    <?php

 foreach(array_combine($this->album,$this->files) as $albums=>$files) :
    ?>
                    <p>
                        <?php echo $albums; ?> - Number of images: <?php echo files; ?>
                    </p>
                    <?php endforeach; ?>
                </div>
        </div>
    </div>
</div>


问:
Getting parameters from query string
I am creating a web page using ASP.Net WebAPi, MVC and Knockout.

I have a normal MVC controller that loads the pages when I need them:

```<code> [Authorize]
    public class AdminController : Controller
    {
        public ActionResult Clients()
        {
            return View();
        }

        public ActionResult ClientEdit(int? Id)
        {
            return View();
        }
    }
</code>```

And once the page is loaded, my Knockout model takes care of the loading of the data. So, the 'Clients' controller simply loads a list of all clients. When on that screen, a user can click 'Edit' next to a client, and the page is navigated to the 'ClientEdit' controller, which takes an id.

So, my knockout click event looks like this in my knockout view model:

```<code>self.EditClick = function () {
        if (this.ClientId && typeof this.ClientId !== 'undefined') {
            window.location.href = "/Admin/ClientEdit/" + this.ClientId;
        }
        else
            window.location.href = "/Admin/ClientEdit/";
    }
</code>```

(It handles the 'Create New' button and the edit button, hence the 'if')

Once I redirect, the MVC controller loads the page, and the URL is:

http://localhost:49389/Admin/ClientEdit/1

I then load the knockout model, and would like to make an API call to get the data...

After my page loads, I want to bind the view model to the page. Here's my view model at the moment:

```<code>function AdminClientEditor() {
    var self = this;

    self.Name = ko.observable("");
    self.ContactName = ko.observable("");

ko.applyBindings(new AdminClientEditor(), $("#clienteditor")[0]);
</code>```

So, I will create a $.get method that calls a webAPI method that will return me data based on the id. I just need to get the ID somehow.

But, how do I get the Id (In this case, '1', from the URL?
And, is this the right way to achieve what I am trying to do?

答:
I'm not sure if this is the best way, but you can get the ID from the URL by using JS:</p>

```<code>var id = GetID();

function GetID() {
  var href = location.href;
  var results = href.split("/");
  return results[results.length - 1];
}
</code>```

Title: Getting parameters from query string

Body:
I am creating a web page using ASP.Net WebAPi, MVC and Knockout.

I have a normal MVC controller that loads the pages when I need them:

 [Authorize]
    public class AdminController : Controller
    {
        public ActionResult Clients()
        {
            return View();
        }

        public ActionResult ClientEdit(int? Id)
        {
            return View();
        }
    }

And once the page is loaded, my Knockout model takes care of the loading of the data. So, the 'Clients' controller simply loads a list of all clients. When on that screen, a user can click 'Edit' next to a client, and the page is navigated to the 'ClientEdit' controller, which takes an id.

So, my knockout click event looks like this in my knockout view model:

self.EditClick = function () {
        if (this.ClientId && typeof this.ClientId !== 'undefined') {
            window.location.href = "/Admin/ClientEdit/" + this.ClientId;
        }
        else
            window.location.href = "/Admin/ClientEdit/";
    }

(It handles the 'Create New' button and the edit button, hence the 'if')

Once I redirect, the MVC controller loads the page, and the URL is:

http://localhost:49389/Admin/ClientEdit/1

I then load the knockout model, and would like to make an API call to get the data...

After my page loads, I want to bind the view model to the page. Here's my view model at the moment:

function AdminClientEditor() {
    var self = this;

    self.Name = ko.observable("");
    self.ContactName = ko.observable("");

ko.applyBindings(new AdminClientEditor(), $("#clienteditor")[0]);

So, I will create a $.get method that calls a webAPI method that will return me data based on the id. I just need to get the ID somehow.

But, how do I get the Id (In this case, '1', from the URL?
And, is this the right way to achieve what I am trying to do?

Body:
I'm not sure if this is the best way, but you can get the ID from the URL by using JS:

var id = GetID();

function GetID() {
  var href = location.href;
  var results = href.split("/");
  return results[results.length - 1];
}


答:
I think you need to explicitly declare variable type array i.e.

```<code>public function viewphotoalbumsAction()
{
    $identity = $this->identity();
    $dirname = array();
    $files = array();
   // continue ...
}
</code>```

let me know if works. thanks.

Title: Repeating image count for both directories

Body:
I think you need to explicitly declare variable type array i.e.

public function viewphotoalbumsAction()
{
    $identity = $this->identity();
    $dirname = array();
    $files = array();
   // continue ...
}

let me know if works. thanks.


问:
Read files in Phoenix in production mode
I've Phoenix app (I created it with --api flag) that has some additional data required to process requests that I store in priv/data/filters.csv.

So it works fine in dev mode, I can read this file like: File.stream!("priv/data/filters.csv"), but once app is delivered using mix edeliver update this file is not accessible anymore.

I can see this folder in build directory, but after app is delivered there is no such folder priv. I'm not sure why it's not copied to deliver folder.

What I'm doing wrong? Do I need to copy these files after deliver process?
Where can I store my files that I have to use in prod mode?

答: I had a similar issue and managed to resolve it using Application.app_dir(my_app, "priv")


问:
HTML tags to highlight data in MYSQL and Crystal Reports
This may be a duplicate but from what i have found i think it is slightly different.  Also didnt want to comment or add answers to articles already marked as "Answered"

I have a query that i have used in a Crystal Report.  I have concatenated a few columns together and have made some of them bold in CR easily enough.

However for ease of redevelopment of the Crystal Report (the code wont change much but the design probably will), i have now concatenated several columns and the ones already concatenated above, in to one column.

This creates a blob that i have handle with....

```<code>CONVERT(USING UTF8)
</code>```

All well and good (sorry, convoluted intro!).

However i am now exploring using HTML tags within the MYSQL query to make things bold and insert spaces, breaks and non-breaked spaces.

The code i tried is below.

```<code>CONVERT(
CONCAT_WS(' ',
        <b>c.codetext</b>,
        m.pcdose,
        SP_GETCODECODE(m.pcunit),
        SP_GETCODECODE(m.pcrout),
        SP_GETCODECODE(m.pcfreqcode),
        m.pcinstruct)USING UTF8) AS 'Drug Info'

From P_DRUGS
</code>```

I know this doesn't work because i have tried it >:)....and i think it can be done successfully if the concatenated value is text, such as...

```<code>CONVERT(
CONCAT_WS(' ',
        '<b>Paracetamol</b>',
        '500mg',
        'Orally',
        SP_GETCODECODE(m.pcrout),
        SP_GETCODECODE(m.pcfreqcode),
        m.pcinstruct)USING UTF8) AS 'Drug Info'

From Drugs
</code>```

Can anyone tell me how (or if) you can use HTML tags to do the above and make certain columns bold etc?

Cheers!

答:
Figured this out and it is embarrassing that i missed it before i posted.

Simply type up the code as you would like it to appear using HTML tags in the MySQL query.  As below.

```<code>Select
<b>column_name_1</b>, column_name_2
from table_name
</code>```

Paste that in to the Crystal Report command and create your report.
Then right click on the field that has the HTML on it, click 'Format Field' and under 'Text Interpretation' drop the box down and select 'HTML'

Painfully easy!

Hope it helps someone one day anyway!

Body:
This may be a duplicate but from what i have found i think it is slightly different.  Also didnt want to comment or add answers to articles already marked as "Answered"

I have a query that i have used in a Crystal Report.  I have concatenated a few columns together and have made some of them bold in CR easily enough.

However for ease of redevelopment of the Crystal Report (the code wont change much but the design probably will), i have now concatenated several columns and the ones already concatenated above, in to one column.

This creates a blob that i have handle with....

CONVERT(USING UTF8)

All well and good (sorry, convoluted intro!).

However i am now exploring using HTML tags within the MYSQL query to make things bold and insert spaces, breaks and non-breaked spaces.

The code i tried is below.

CONVERT(
CONCAT_WS(' ',
        c.codetext,
        m.pcdose,
        SP_GETCODECODE(m.pcunit),
        SP_GETCODECODE(m.pcrout),
        SP_GETCODECODE(m.pcfreqcode),
        m.pcinstruct)USING UTF8) AS 'Drug Info'

From P_DRUGS

I know this doesn't work because i have tried it >:)....and i think it can be done successfully if the concatenated value is text, such as...

CONVERT(
CONCAT_WS(' ',
        'Paracetamol',
        '500mg',
        'Orally',
        SP_GETCODECODE(m.pcrout),
        SP_GETCODECODE(m.pcfreqcode),
        m.pcinstruct)USING UTF8) AS 'Drug Info'

From Drugs

Can anyone tell me how (or if) you can use HTML tags to do the above and make certain columns bold etc?

Cheers!

Body:
Figured this out and it is embarrassing that i missed it before i posted.

Simply type up the code as you would like it to appear using HTML tags in the MySQL query.  As below.

Select
<b>column_name_1</b>, column_name_2
from table_name

Paste that in to the Crystal Report command and create your report.
Then right click on the field that has the HTML on it, click 'Format Field' and under 'Text Interpretation' drop the box down and select 'HTML'

Painfully easy!

Hope it helps someone one day anyway!


问:
Android M Adoptable Storage
I have read about Android M adoptable storage from here

My Question is if I move a App(Android app) from internal storage of phone to adoptable storage ( using OTG cable + pen drive), what "all files" will be moved from internal storage to adoptable storage.
for example

1) Will it move the app private area to this adoptable storage ?

2) Will .lib and .so files will also move to adoptable storage ?

3) What happen to resource file that has been bundle with apk ?

4) will jars that had been bundle with apk also moved to adoptable storage once app is moved from internal storage to this?

Let add one more point here : as soon as you put sdcard in Android-M devices, it ask for whether to use it as internal storage or as external storage. now tell what happen if move the app to sdcard in both scenario

Please help me out in figuring what actually happens when app moved to adoptable storage. Any edits are most welcome.Thanks

答: Having had bad experiences with adoptable-storage on both M and N, I feel qualified to answer: the only things that get moved to SD are the files marked as such in the app, by the programmer/packager. Almost no apps use adoptable storage, and Android gives you no choice. You will need a "hack" to get any value out of adoptable storage, IMHO at the moment it makes no sense to "format as internal". HTH</p>

Title: Android M Adoptable Storage


问:
Enable users of a WebRtc app to download webrtc logs via javascript
I've seen the following:

```<code>chrome://webrtc-internals
</code>```

However I'm looking for a way to let users click a button from within the web app to either download or - preferably - POST WebRtc logs to an endpoint baked into the app.  The idea is that I can enable non-technical users to share technical logs with me through the click of a UI button.

How can this be achieved?

Note: This should not be dependent on Chrome; Chromium will also be used as the app will be wrapped up in Electron.

答:
Reading through js source of chrome://webrtc-internals, I noticed that the web page is using a method called chrome.send() to send messages like chrome.send('enableEventLogRecordings');, to execute logging commands.
According to here:

chrome.send() is a private function only available to internal chrome
  pages.

so the function is sandboxed which makes accessing to it not possible

Body:
I've seen the following:

chrome://webrtc-internals

However I'm looking for a way to let users click a button from within the web app to either download or - preferably - POST WebRtc logs to an endpoint baked into the app.  The idea is that I can enable non-technical users to share technical logs with me through the click of a UI button.

How can this be achieved?

Note: This should not be dependent on Chrome; Chromium will also be used as the app will be wrapped up in Electron.


问:
Failing to parse 1 MB XML File with BS4
I have two SVG maps of the world, downloaded here. My goal is to do some editing of these maps in python, working with them via BeautifulSoup4. This works perfectly with the low-res file (132.5 Kb). However, the BS4 parser (using lxml) fails entirely when I attempt to use it with the high-res file (1.2 Mb).

The code is as such:

```<code>    import lxml
    from bs4 import BeautifulSoup as Soup
    with open('worldHigh.svg','r') as f:
        handler = f.read()
        soup = Soup(handler,'xml')
        print(soup.prettify())
</code>```

When I run that with the worldHigh.svg fifle, the only thing that is printed is

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

When I run the equivalent, but changing worldHigh.svg for worldLow.svg, it prints the XML correctly (as desired).

Both SVG files work fine when opened by themselves (i.e., they show the map). However, one fails when I try to parse it, the other succeeds. I am at a loss for what is going wrong. I would understand if the parser fails at large sizes, but 1.2 MB does not seem large.

答:
The XML parser needs the raw sequence of unencoded bytes. Use open(...,'rb') when parsing XML.

The reason why one worked and the other didn't is worldHigh.svg has a BOM at the beginning of the file.

Title: Failing to parse 1 MB XML File with BS4

Body:
I have two SVG maps of the world, downloaded here. My goal is to do some editing of these maps in python, working with them via BeautifulSoup4. This works perfectly with the low-res file (132.5 Kb). However, the BS4 parser (using lxml) fails entirely when I attempt to use it with the high-res file (1.2 Mb).

The code is as such:

    import lxml
    from bs4 import BeautifulSoup as Soup
    with open('worldHigh.svg','r') as f:
        handler = f.read()
        soup = Soup(handler,'xml')
        print(soup.prettify())

When I run that with the worldHigh.svg fifle, the only thing that is printed is

<?xml version="1.0" encoding="utf-8"?>

When I run the equivalent, but changing worldHigh.svg for worldLow.svg, it prints the XML correctly (as desired).

Both SVG files work fine when opened by themselves (i.e., they show the map). However, one fails when I try to parse it, the other succeeds. I am at a loss for what is going wrong. I would understand if the parser fails at large sizes, but 1.2 MB does not seem large.


问:
InputArrayOfArrays in OpenCV
I'm trying to generate an InputArrayOfArrays to pass into OpenCV calibrate. I believe it should be a vector of vectors. However, when I call the calibrate function it bombs out with an exception that my input and output arrays aren't the same size. I've tried to perform the conversion outside of the calibrate call and the resulting InputArrayOfArrays (op and ip) appear to not be initialised (the reported total() size is random). If I interrogate the vectors directly, they are as expected.
Any help is much appreciated!

```<code>{
....
//pixel position is imagePoints
std::vector<std::vector<cv::Point> > imagePoints(1); //={ Point(144,103),  Point(206,75),  Point(109,151), Point(253,159) };
imagePoints[0].push_back(Point(144,103));
imagePoints[0].push_back(Point(206,75));
imagePoints[0].push_back(Point(109,151));
imagePoints[0].push_back(Point(253,159));
//real world position is object Points
std::vector<std::vector<cv::Point3d> > objectPoints(1); //={ Point3d(4,3,0),  Point3d(7,2,0),  Point3d(2,5,0), Point3d(8,6,0)};
objectPoints[0].push_back(Point3d(4,3,0));
objectPoints[0].push_back(Point3d(7,2,0));
objectPoints[0].push_back(Point3d(2,5,0));
objectPoints[0].push_back(Point3d(8,6,0));

InputArrayOfArrays ip = InputArrayOfArrays(imagePoints);
InputArrayOfArrays op = InputArrayOfArrays(objectPoints);

printf("ip (%d, %I64u) op (%d, %I64u)\n", ip.empty(), ip.total(), op.empty(), op.total());

fisheye::calibrate(objectPoints, imagePoints, distorted.size(), Ka, Da, rvec, tvec, flag, cv::TermCriteria(3, 20, 1e-6));

}
</code>```

Ouptut is:

ip (0, 18446744073709499195) op (0, 18446744073709499176)

OpenCV Error: Assertion failed (!objectPoints.empty() && !imagePoints.empty() && objectPoints.total() == imagePoints.total()) in cv::fisheye::calibrate, file C:\Temp\OpenCV_3.2_extra\source\opencv\modules\calib3d\src\fisheye.cpp, line 701

答:
Im not sure if you are defining the vectors and adding points in a right way

try doing it as follows

```<code>std::vector<cv::Point2d> imagePoints; //={ Point(144,103),  Point(206,75),  Point(109,151), Point(253,159) };
imagePoints.push_back(Point2d(144,103));
imagePoints.push_back(Point2d(206,75));
imagePoints.push_back(Point2d(109,151));
imagePoints.push_back(Point2d(253,159));
//real world position is object Points
std::vector<cv::Point3d> objectPoints; //={ Point3d(4,3,0),  Point3d(7,2,0),  Point3d(2,5,0), Point3d(8,6,0)};
objectPoints.push_back(Point3d(4,3,0));
objectPoints.push_back(Point3d(7,2,0));
objectPoints.push_back(Point3d(2,5,0));
objectPoints.push_back(Point3d(8,6,0));
</code>```

Title: InputArrayOfArrays in OpenCV

Body:
I'm trying to generate an InputArrayOfArrays to pass into OpenCV calibrate. I believe it should be a vector of vectors. However, when I call the calibrate function it bombs out with an exception that my input and output arrays aren't the same size. I've tried to perform the conversion outside of the calibrate call and the resulting InputArrayOfArrays (op and ip) appear to not be initialised (the reported total() size is random). If I interrogate the vectors directly, they are as expected.
Any help is much appreciated!

{
....
//pixel position is imagePoints
std::vector<std::vector<cv::Point> > imagePoints(1); //={ Point(144,103),  Point(206,75),  Point(109,151), Point(253,159) };
imagePoints[0].push_back(Point(144,103));
imagePoints[0].push_back(Point(206,75));
imagePoints[0].push_back(Point(109,151));
imagePoints[0].push_back(Point(253,159));
//real world position is object Points
std::vector<std::vector<cv::Point3d> > objectPoints(1); //={ Point3d(4,3,0),  Point3d(7,2,0),  Point3d(2,5,0), Point3d(8,6,0)};
objectPoints[0].push_back(Point3d(4,3,0));
objectPoints[0].push_back(Point3d(7,2,0));
objectPoints[0].push_back(Point3d(2,5,0));
objectPoints[0].push_back(Point3d(8,6,0));

InputArrayOfArrays ip = InputArrayOfArrays(imagePoints);
InputArrayOfArrays op = InputArrayOfArrays(objectPoints);

printf("ip (%d, %I64u) op (%d, %I64u)\n", ip.empty(), ip.total(), op.empty(), op.total());

fisheye::calibrate(objectPoints, imagePoints, distorted.size(), Ka, Da, rvec, tvec, flag, cv::TermCriteria(3, 20, 1e-6));

}

Ouptut is:

ip (0, 18446744073709499195) op (0, 18446744073709499176)

OpenCV Error: Assertion failed (!objectPoints.empty() && !imagePoints.empty() && objectPoints.total() == imagePoints.total()) in cv::fisheye::calibrate, file C:\Temp\OpenCV_3.2_extra\source\opencv\modules\calib3d\src\fisheye.cpp, line 701

Body:
Im not sure if you are defining the vectors and adding points in a right way

try doing it as follows

std::vector<cv::Point2d> imagePoints; //={ Point(144,103),  Point(206,75),  Point(109,151), Point(253,159) };
imagePoints.push_back(Point2d(144,103));
imagePoints.push_back(Point2d(206,75));
imagePoints.push_back(Point2d(109,151));
imagePoints.push_back(Point2d(253,159));
//real world position is object Points
std::vector<cv::Point3d> objectPoints; //={ Point3d(4,3,0),  Point3d(7,2,0),  Point3d(2,5,0), Point3d(8,6,0)};
objectPoints.push_back(Point3d(4,3,0));
objectPoints.push_back(Point3d(7,2,0));
objectPoints.push_back(Point3d(2,5,0));
objectPoints.push_back(Point3d(8,6,0));


问:
JAXB 2 annotation and XSD
In the JAXB 1.0 era, the recommended way of working with java object, XSD and XML is to start with XSD definition, use JAXB to generate java classes from the XSD and maintain the XSDs.

But now with JAXB 2.0 annotations, it's very convenient to generate XSDs from java classes. Is it recommended to take the approach of starting with java classes and annotations and generate XSD's?

Thanks,

答:
I wouldn't say so, no. XML Schema is much richer in terms of types and certain structures, and so any schema you generate from Java are going to quite basic and unexpressive.

By all means generate a starting schema from your code, but then you should really embellish the result and maintain it as a first-class citizen, not a generated product. Once it's been fleshed out, you can plug it back in to the JAXB marshaller/unmarshaller as a validation layer.

Title: JAXB 2 annotation and XSD


问:
VBA to delete rows based on cell value
I am trying to do the following :

VBA to lookup a value from a particular cell

Match these values in a particular column in specified sheets

Delete all rows from the sheet if the value do not match

I have tried the following - the code doesn't seem to function

```<code>Sub Delete()
    Dim List As Variant
    Dim LR As Long
    Dim r As Long
    List = Worksheets("Sheet1").Cells(28, "C").Value
    LR = Range("E" & Rows.Count).End(xlUp).Row
    For r = LR To 1 Step -1
        If IsError(Application.Match(Range("E" & r).Value, List, False)) Then
            Worksheets("Sheet2").Range("A1:AA36429").Rows(r).Delete
        End If
    Next r
End Sub
</code>```

答:
Try this:</p>

```<code>Sub Delete()

Dim i As Integer
Dim LR As Long
Dim List As Variant

LR = Range("E" & Rows.Count).End(xlUp).Row
List = Worksheets("Sheet1").Cells(28, "C").Value

For i = 1 To LR
    If Cells(i, "E").Value = List Then
        Worksheets("Sheet1").Rows(i).Delete
    End If
Next i

End Sub
</code>```

Title: VBA to delete rows based on cell value

Body:
I am trying to do the following :

VBA to lookup a value from a particular cell

Match these values in a particular column in specified sheets

Delete all rows from the sheet if the value do not match

I have tried the following - the code doesn't seem to function

Sub Delete()
    Dim List As Variant
    Dim LR As Long
    Dim r As Long
    List = Worksheets("Sheet1").Cells(28, "C").Value
    LR = Range("E" & Rows.Count).End(xlUp).Row
    For r = LR To 1 Step -1
        If IsError(Application.Match(Range("E" & r).Value, List, False)) Then
            Worksheets("Sheet2").Range("A1:AA36429").Rows(r).Delete
        End If
    Next r
End Sub

Body:
Try this:

Sub Delete()

Dim i As Integer
Dim LR As Long
Dim List As Variant

LR = Range("E" & Rows.Count).End(xlUp).Row
List = Worksheets("Sheet1").Cells(28, "C").Value

For i = 1 To LR
    If Cells(i, "E").Value = List Then
        Worksheets("Sheet1").Rows(i).Delete
    End If
Next i

End Sub


问:
Cant connect dynamo Db from my vpc configured lambda function
i need to connect elastic cache and dynamo db from a single lambda function. My code is

```<code>exports.handler = (event, context, callback) => {

    var redis = require("redis");
    var client;
    function connectRedisClient() {
        client = redis.createClient(6379, "dgdfgdfgdfgdfgdfgfd.use1.cache.amazonaws.com", { no_ready_check: true });
    }

    connectRedisClient();
    client.set('sampleKey', 'Hello World', redis.print);
    console.log("set worked");
    client.quit();

    var AWS = require("aws-sdk");
    var docClient = new AWS.DynamoDB.DocumentClient();
    var table = "dummy";
    var year = 2015;
    var title = "The Big New Movie";
    var params = {
        TableName: table,
        Item: {
            "userid": "manafcj",
            "year": year,
            "title": title,
            "test1": [645645, 7988],
            "info": {
                "plot": "Nothing happens at all.",
                "rating": 0
            }
        }
    };

    console.log("Adding a new item...");
    docClient.put(params, function (err, data) {
        if (err) {
            console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
        } else {
            console.log("Added item:", JSON.stringify(data, null, 2));
        }
    });
    callback(null, 'Hello from Lambda');
 };
</code>```

I executed this lambda code without configuring vpc, elastic cache section is not working , but dynamo insertion is done perfectly.

after that i made setup for VPC in my account by following steps.

create vpc
name : test-vpc-name
CIDR block:172.31.0.0/16
Tenancy:Default

Create a new subnet.
name tag : test-subnet-1a
CIDR block :172.31.0.0/20

name tag : test-subnet-1b
CIDR block :172.31.16.0/20

Create a route table
name tag : test-route-table

Create a internet gateway
name:test-internet-gateway

Attach VPC

Route all outbound 0.0.0.0/0 traffic in routes

Create a route table subnet association

Create a NAT Gateway
subnet : test-subnet-1a

also i have configured my elastic cache setup by following steps

Create subnet cache group
name : test-cache-group

Create elastic cache

type: redis
Cluster Name : test-cache

subnet cache group :  test-cache-group

Finally, i have configured newly created vpc on my lambda function. Then redis-elastic cache connection is working fine, but dynamo db connection is lost. I need both working fine from a single lambda function.

I think, some fault in VPC configuration with NAT Gateway.

What is the actual issue in this setup?

答:
Lambda and DynamoDB are executed in the AWS Public Cloud. Both are services executed in a internet facing environment. The Elastic Cache Cluster, otherwise, is user managed service that runs on your own VPC.

The first option to give access to your elastic cache cluster to your lambda function is using a NAT instance to foward external network connections to Elastic Cache cluster inside your VPC. You can get use the instructions from this document to help you with this task.

The second option, is the one that you already tried. Amazon says that when you configure this option it does not means that the Lambda will be executed inside your VPC. What is does it define the Elastic Network Interface of the Lambda container to access your VPC. At the end of day I don't think that this makes difference. You can see the details here.

But the point is, the container where your lambda is executed has only one Elastic Network Interface. If you configure your lambda to use your VPC, the Network Interface will be configured to access your subnet using a private IP and lost the internet connection. So, it will not be able to access DynamoDB unless you have a configure NAT instance/Gateway in your VPC.

As per you told us. You configured your VPC with a NAT Gateway. If all were correctly configured, this should be working. Maybe you can try the fist option, leaving your lambda outside your VPC and configuring the NAT Gateway to route the inboud connections to your Elastic Cache Cluster.

Why don't try and tell us the result?

Body:
i need to connect elastic cache and dynamo db from a single lambda function. My code is

exports.handler = (event, context, callback) => {

    var redis = require("redis");
    var client;
    function connectRedisClient() {
        client = redis.createClient(6379, "dgdfgdfgdfgdfgdfgfd.use1.cache.amazonaws.com", { no_ready_check: true });
    }

    connectRedisClient();
    client.set('sampleKey', 'Hello World', redis.print);
    console.log("set worked");
    client.quit();

    var AWS = require("aws-sdk");
    var docClient = new AWS.DynamoDB.DocumentClient();
    var table = "dummy";
    var year = 2015;
    var title = "The Big New Movie";
    var params = {
        TableName: table,
        Item: {
            "userid": "manafcj",
            "year": year,
            "title": title,
            "test1": [645645, 7988],
            "info": {
                "plot": "Nothing happens at all.",
                "rating": 0
            }
        }
    };

    console.log("Adding a new item...");
    docClient.put(params, function (err, data) {
        if (err) {
            console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
        } else {
            console.log("Added item:", JSON.stringify(data, null, 2));
        }
    });
    callback(null, 'Hello from Lambda');
 };

I executed this lambda code without configuring vpc, elastic cache section is not working , but dynamo insertion is done perfectly.

after that i made setup for VPC in my account by following steps.

create vpc
name : test-vpc-name
CIDR block:172.31.0.0/16
Tenancy:Default

Create a new subnet.
name tag : test-subnet-1a
CIDR block :172.31.0.0/20

name tag : test-subnet-1b
CIDR block :172.31.16.0/20

Create a route table
name tag : test-route-table

Create a internet gateway
name:test-internet-gateway

Attach VPC

Route all outbound 0.0.0.0/0 traffic in routes

Create a route table subnet association

Create a NAT Gateway
subnet : test-subnet-1a

also i have configured my elastic cache setup by following steps

Create subnet cache group
name : test-cache-group

Create elastic cache

type: redis
Cluster Name : test-cache

subnet cache group :  test-cache-group

Finally, i have configured newly created vpc on my lambda function. Then redis-elastic cache connection is working fine, but dynamo db connection is lost. I need both working fine from a single lambda function.

I think, some fault in VPC configuration with NAT Gateway.

What is the actual issue in this setup?