问:
Removing empty
 tags from the start of the string and last of the string containing html in PHP
I have a html string in the format like

```<code><p><br /></p><p><br /></p><p>some random stuf</p><p><br /></p><p><br /></p>
</code>```

Now i need to remove the

```
</div>
</div>
</p>

<p>tags that contains only</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><br /></code>```

element in the start of the string as well as on the tail side of the string in PHP.
How can i remove?

答:
It can be done by few steps:

Explode by each
 tag

Traverse all element via foreach

Do strip_tags each element and check length

If length is 0, then do not print.

Title: Removing empty <p> tags from the start of the string and last of the string containing html in PHP

Body:
I have a html string in the format like

some random stuf

Now i need to remove the

tags that contains only

element in the start of the string as well as on the tail side of the string in PHP.
How can i remove?

Body:
It can be done by few steps:

Explode by each <p> tag

Traverse all element via foreach

Do strip_tags each element and check length

If length is 0, then do not print.


来源: stackexchange

问:
Make request from apple watch requests via ios app
Now I'm developing apple watch extension and I use WatchConnectivity.
Can I send message to ios app ios application make a request ?

Who can make a request to the server ios app or watch extension ?

P.S. Use AFNetworking to work with server.

Thanks

答:
You can use this method to send notification to ios App to make request

```<code>[[WCSession defaultSession] sendMessage:dictSendMessage replyHandler:^(NSDictionary<NSString *,id> * _Nonnull replyMessage) {
} errorHandler:^(NSError * _Nonnull error) {

    }];
</code>```

And you can receive that notification with this delegate method in ios app

```<code>-(void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *,id> *)message replyHandler:(void (^)(NSDictionary<NSString *,id> * _Nonnull))replyHandler
{
}
</code>```

Note : You can also request to server from watch app it self with the help of

```<code>NSURLSessionDataTask *taskDownload = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
    {
}];
// Start the task.
    [taskDownload resume];
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can use this method to send notification to ios App to make request

[[WCSession defaultSession] sendMessage:dictSendMessage replyHandler:^(NSDictionary<NSString *,id> * _Nonnull replyMessage) {
} errorHandler:^(NSError * _Nonnull error) {

    }];

And you can receive that notification with this delegate method in ios app

-(void)session:(WCSession *)session didReceiveMessage:(NSDictionary<NSString *,id> *)message replyHandler:(void (^)(NSDictionary<NSString *,id> * _Nonnull))replyHandler
{
}

Note : You can also request to server from watch app it self with the help of

NSURLSessionDataTask *taskDownload = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
    {
}];
// Start the task.
    [taskDownload resume];


问:
Codeigniter calling a view
I'm new to CodeIgniter and i wonder what is best way to load a page without need to call  header and footer views always this way

```<code>$this->load->view('header');
$this->load->view('something');
$this->load->view('footer');
</code>```

for example i successfully logged in and was redirected to dashboard page .

答:
For that I'm using easy way like PHP:

Controller :

```<code>class My_Controller extends CI_Controller{

    public function __construct() {
       parent::__construct();
    }

    public function load_view(){
         $data=array();
         $this->load->view('dashboard_view',$data);

    }
    public function get_data(){

         $data['welcome_text']="Wooh ! I've a Something...";
         $this->load->view('dashboard_view',$data);
    }
}
</code>```

View dashboard_view.php:

```<code><html lang="en">
    <body>
        <?php include('header.php');?>
         <h1>welcome to the dashboard </h1>
        <?php include('footer.php');?>
    </body>
</html>
</code>```

Note:
In this you don't need to call each and everytime header and footer just change the controller methods.

Same dashboard_view.php for the edit function :

```<code><html lang="en">
    <body>
        <?php include('header.php');?>

        <?php
        // you can use here any checking method whether it is
        // I'll use isset() method to check  data is set or not
        //if you don't use isset then it will give you an error when you call the load_view() method
        echo (isset($welcome_text) ? $welcome_text : '');

        ?>

        <?php include('footer.php');?>
    </body>
</html>
</code>```

Title: Codeigniter calling a view

Body:
I'm new to CodeIgniter and i wonder what is best way to load a page without need to call  header and footer views always this way

$this->load->view('header');
$this->load->view('something');
$this->load->view('footer');

for example i successfully logged in and was redirected to dashboard page .

Body:
For that I'm using easy way like PHP:

Controller :

class My_Controller extends CI_Controller{

    public function __construct() {
       parent::__construct();
    }

    public function load_view(){
         $data=array();
         $this->load->view('dashboard_view',$data);

    }
    public function get_data(){

         $data['welcome_text']="Wooh ! I've a Something...";
         $this->load->view('dashboard_view',$data);
    }
}

View dashboard_view.php:

<html lang="en">
    <body>
        <?php include('header.php');?>
         <h1>welcome to the dashboard </h1>
        <?php include('footer.php');?>
    </body>
</html>

Note:
In this you don't need to call each and everytime header and footer just change the controller methods.

Same dashboard_view.php for the edit function :

<html lang="en">
    <body>
        <?php include('header.php');?>

        <?php
        // you can use here any checking method whether it is
        // I'll use isset() method to check  data is set or not
        //if you don't use isset then it will give you an error when you call the load_view() method
        echo (isset($welcome_text) ? $welcome_text : '');

        ?>

        <?php include('footer.php');?>
    </body>
</html>


问:
onClick on li element are not passing target id properly?
I am working on a ReactJS project using MaterialUI. I have following code

```<code>{ this.state.categories.map((category, key) => (
      <List>
        <ListItem button id={key} onClick={this.handleClick}>
              <ListItemText primary={category.name} />
              {(category.id === Number(this.state.nestedOpenNum)) ?
<ExpandLess /> : <ExpandMore />}
        </ListItem>
      </List>
            )

      )}
</code>```

and state looks something like

```<code>this.state = {
  open: false,
  nestedOpen: false,
  nestedOpenNum: 0,
  result: [],
  categories: [{
      id: 0,
      name: "COMPUER SCIENCE",
    }, {
      id: 1,
      name: "BUSINESS",
    }, {
      id: 2,
      name: "ART & HUMANITIES",
    }, {
      id: 3,
      name: "MATH & LOGIC",
    },{
      id: 4,
      name: "SCIENCE",
    }]
};
</code>```

this is the handleClick function-

```<code>handleClick = (e) => {
this.setState({ nestedOpenNum: e.target.id });
this.setState({ nestedOpen: !this.state.nestedOpen });
console.log(e.target.id );
</code>```

};

PROBLEM

When I click in padding area of li element(green area), everything working perfectly. But e.target.id is not passing when I click on li element(blue area).

how can I solve this?

答: Try passing the onClick handler as a prop to the ListItemText component, it looks to me like this component is blocking the other element from detecting its onClick handler. </p>

Body:
I am working on a ReactJS project using MaterialUI. I have following code

{ this.state.categories.map((category, key) => (
      <List>
        <ListItem button id={key} onClick={this.handleClick}>
              <ListItemText primary={category.name} />
              {(category.id === Number(this.state.nestedOpenNum)) ?
<ExpandLess /> : <ExpandMore />}
        </ListItem>
      </List>
            )

      )}

and state looks something like

this.state = {
  open: false,
  nestedOpen: false,
  nestedOpenNum: 0,
  result: [],
  categories: [{
      id: 0,
      name: "COMPUER SCIENCE",
    }, {
      id: 1,
      name: "BUSINESS",
    }, {
      id: 2,
      name: "ART & HUMANITIES",
    }, {
      id: 3,
      name: "MATH & LOGIC",
    },{
      id: 4,
      name: "SCIENCE",
    }]
};

this is the handleClick function-

handleClick = (e) => {
this.setState({ nestedOpenNum: e.target.id });
this.setState({ nestedOpen: !this.state.nestedOpen });
console.log(e.target.id );

};

PROBLEM

When I click in padding area of li element(green area), everything working perfectly. But e.target.id is not passing when I click on li element(blue area).

how can I solve this?


问:
What are the pitfalls of multiplication by juxtaposition when designing a numeric programming language?
In lieu of a standard definition (happy to replace if exists), I'll define syntax for multiplication by juxtaposition using a space between symbols or expressions so that:

```<code>c = a b  --> c = a * b
</code>```

(Note: I'm specifically not allowing c=ab --> c = a * b as ab would be the 2-character name of a variable ab).

This ought to work nicely with parenthesis and order of operations so that

```<code>c = a (b + q)       --> c = a * (b + q)
c = (a + p) (b + q) --> c = (a + p) * (b + q)
c = a/p b           --> c = a/p*b
</code>```

It seems that very few languages (e.g., Wolfram Alpha), allow such implied multiplication. I'm wondering why?

Is this just a pain to parse?

Are there ambiguities?

A keyword-search skim of "A practical approach to type-sensitive parsing" [Sailor & McCorsky 1994] seems to imply that this is possible.

Regarding vote to close due to "primarily opinion-based": I am not looking for opinions. I'm looking for theoretical reasons why parsing this would be more complex or impossible due to ambiguities.

答:
It's not impossible to parse but there are a number of issues which need to be resolved.

First, x(a+b) could be a product or a function call, depending on whether x is a scalar or a function. To resolve the ambiguity, you need to know what x is, which pretty well requires mandatory declare before use. Even if your language is strongly typed and you don't mind the requirement to declare first, you still ned a somewhat clunky back-channel from the parser to the lexical scanner, or some other parsing hack. (For example, Awk -- which uses juxtaposition for string concatenation -- treats it as a function call if there is no space between the function name and the (.). You can defer the parse but you might find that you need to reparse the entire expression in order to get precedences right.

A similar ambiguity with unary operators. It's easy enough to insist that a -b is a subtraction, so that the product would be written with parentheses -- a(-b) -- but it complicates the grammar.

Precedence can be confusing for people reading the code, too. Consider n!/k!(n-k)!; if that is the correct way to write the expression, juxtaposition must have a higher precedence than division, but there are those who think that juxtaposition and product should have the same precedence. (This group includes some of the authors of the SI measurements standard, which recommends not using juxtaposition to write measurements where the expression type has a multiplied denominator.)

In short, a syntax supposedly designed for improved readability can produce confusion and even subtle bugs. That, plus the increase in parsing complexity, raises the question of how much real benefit there is in leaving out a few *s.

Body:
In lieu of a standard definition (happy to replace if exists), I'll define syntax for multiplication by juxtaposition using a space between symbols or expressions so that:

c = a b  --> c = a * b

(Note: I'm specifically not allowing c=ab --> c = a * b as ab would be the 2-character name of a variable ab).

This ought to work nicely with parenthesis and order of operations so that

c = a (b + q)       --> c = a * (b + q)
c = (a + p) (b + q) --> c = (a + p) * (b + q)
c = a/p b           --> c = a/p*b

It seems that very few languages (e.g., Wolfram Alpha), allow such implied multiplication. I'm wondering why?

Is this just a pain to parse?

Are there ambiguities?

A keyword-search skim of "A practical approach to type-sensitive parsing" [Sailor & McCorsky 1994] seems to imply that this is possible.

Regarding vote to close due to "primarily opinion-based": I am not looking for opinions. I'm looking for theoretical reasons why parsing this would be more complex or impossible due to ambiguities.

ContentLicense: CC BY-SA 4.0


问:
Implement Markov's algorithm using random letters till letters makeup one word in the string?
I am trying to use the Markov chain to display random letters till the letters make up one of the words found in the string. I think I’m on the right track, but instead of stopping when it reaches one word it just prints the whole string of random.

I believe there will be a check to see if characters match with the print out, but not sure…

What am I doing wrong here?

```<code>public class Main {

    public static void main(String[] args) {

        final int NUMBER_OF_CHARS = 100000;
        String[] words = { "at", "is", "he", "we", "up", "on" };

        for (int i = 0; i < NUMBER_OF_CHARS; i++) {
            char ch = main.getRandomLowerCaseLetter();
            if ((i + 1) % 40 == 0)
                System.out.println(ch);
            else
                System.out.print(ch);
        }
    }

    public static char getRandomCharacter(char ch1, char ch2) {
        return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
    }

    public static char getRandomLowerCaseLetter() {
        return getRandomCharacter('a', 'z');
    }
}
</code>```

答:
I don't see any if statements checking whether the characters have formed a word yet. In other words, the loop will never exit, because you haven't written logic for it to do so.

You probably want to store each character you generate in a String as you go, like this:

```<code>String chars = "";
...
for(...){
    ...
    chars.append(ch);
    ...
}
</code>```

You should also write something like this to break out of the loop:

```<code>for(String word : words){
    if(chars.contains(word){
        break outerLoop;
    }
}
</code>```

Label the outer for loop like this so the break statement breaks out of both loops, not just the inner for loop:

```<code>outerLoop: while(...){}
</code>```

Body:
I am trying to use the Markov chain to display random letters till the letters make up one of the words found in the string. I think I’m on the right track, but instead of stopping when it reaches one word it just prints the whole string of random.

I believe there will be a check to see if characters match with the print out, but not sure…

What am I doing wrong here?

public class Main {

    public static void main(String[] args) {

        final int NUMBER_OF_CHARS = 100000;
        String[] words = { "at", "is", "he", "we", "up", "on" };

        for (int i = 0; i < NUMBER_OF_CHARS; i++) {
            char ch = main.getRandomLowerCaseLetter();
            if ((i + 1) % 40 == 0)
                System.out.println(ch);
            else
                System.out.print(ch);
        }
    }

    public static char getRandomCharacter(char ch1, char ch2) {
        return (char)(ch1 + Math.random() * (ch2 - ch1 + 1));
    }

    public static char getRandomLowerCaseLetter() {
        return getRandomCharacter('a', 'z');
    }
}

Body:
I don't see any if statements checking whether the characters have formed a word yet. In other words, the loop will never exit, because you haven't written logic for it to do so.

You probably want to store each character you generate in a String as you go, like this:

String chars = "";
...
for(...){
    ...
    chars.append(ch);
    ...
}

You should also write something like this to break out of the loop:

for(String word : words){
    if(chars.contains(word){
        break outerLoop;
    }
}

Label the outer for loop like this so the break statement breaks out of both loops, not just the inner for loop:

outerLoop: while(...){}


问:
Check if chrome WebkitSpeechRecognition is initialised?
I'm currently developing a web application using the WebkitSpeechRecognition API.
The problem is, that when I first initialise the API with .start() and begin yelling into my microphone, it usually takes more than 20 seconds until the first .onresult is triggered. In this meantime, I want to give feedback to the user that the tool is booting up and tell him once he can start talking. Unfortunately, onresult is only triggered if there is a speech input, not if the user patiently waits in silence for the initialisation to finish. Is there a way to check if the recognition is ready to go?

Thanks a lot.

答:
set continuous to false on the initialization

see the below example

```<code>if ('webkitSpeechRecognition' in window) {
                var recognition = new webkitSpeechRecognition();
                recognition.continuous = false;
                recognition.interimResults = false;
                recognition.onstart = function () { $('#modalLoadText').hide(); $('#modalListenText').show(); $('#myModal').modal('show'); console.log("Start"); }
                recognition.onresult = function (event) { console.log("Finish"); }
                recognition.onerror = function (event) { console.log("Error"); }
                recognition.onend = function () { $('#modalLoadText').show(); $('#modalListenText').hide(); $('#myModal').modal('hide'); console.log("End"); }
            }
</code>```

Body:
set continuous to false on the initialization

see the below example

if ('webkitSpeechRecognition' in window) {
                var recognition = new webkitSpeechRecognition();
                recognition.continuous = false;
                recognition.interimResults = false;
                recognition.onstart = function () { $('#modalLoadText').hide(); $('#modalListenText').show(); $('#myModal').modal('show'); console.log("Start"); }
                recognition.onresult = function (event) { console.log("Finish"); }
                recognition.onerror = function (event) { console.log("Error"); }
                recognition.onend = function () { $('#modalLoadText').show(); $('#modalListenText').hide(); $('#myModal').modal('hide'); console.log("End"); }
            }


问:
How to replace a ' from a String in python
I am trying to remove a " ' " character from a python string .
Below code gives a syntax error, How to achieve this task  </p>

```<code>final = string.replace(old_str, '\'', '')
</code>```

答:
str = "this is string example....wow!!! this is really string"
print(str.replace("is", "was"))

Here's an example of how to correctly use the replace function. This replaces all the is's with was's. It's hard to see what you're trying to do but use this as a guide.

Body:
I am trying to remove a " ' " character from a python string .
Below code gives a syntax error, How to achieve this task

final = string.replace(old_str, '\'', '')


问:
'Use of Unresolved Identifier' in Swift
So I have been making an app, and everything has been working great. But today I made a new class like usual and for some reason in this class I can't access Public/Global variable from other classes. All the other classes can, but now when ever I try to make a new class I can't. How would this be fixed?

I am using Swift and Xcode 6.

Working Class:

```<code>import UIKit
import Foundation
import Parse
import CoreData

var signedIn = true

class ViewController: UIViewController {
</code>```

New Class:

```<code>import UIKit

class NewClass: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        signedIn = false

}
</code>```

But on signedIn = false

I get the error:

use of unresolved identifier "signedIn"

答:
I got this error for Mantle Framework in my Objective-Swift Project.
What i tried is ,

Check if import  is there in Bridging-Header.h file

Change the Target Membership for Framework in Mantle.h file as shown in below screenshot.

Toggle between Private Membership first build the project , end up with errors.
Then build the project with Public Membership  for all the frameworks appeared for Mantle.h file, you must get success.

It is just a bug of building with multiple framework in Objective-C Swift project.

Title: 'Use of Unresolved Identifier' in Swift

Body:
So I have been making an app, and everything has been working great. But today I made a new class like usual and for some reason in this class I can't access Public/Global variable from other classes. All the other classes can, but now when ever I try to make a new class I can't. How would this be fixed?

I am using Swift and Xcode 6.

Working Class:

import UIKit
import Foundation
import Parse
import CoreData

var signedIn = true

class ViewController: UIViewController {

New Class:

import UIKit

class NewClass: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        signedIn = false

}

But on signedIn = false

I get the error:

use of unresolved identifier "signedIn"


问:
How to use result of pattern matching in R
I have a dataframe with string values

```<code>id str
a  1
b  10
c  0
d  102
e  010
</code>```

I need to create a flag such that if there is a 0 in the str, the flag is 1 else, the flag is 0

I'm using the following code :

```<code>df$flag <-ifelse(grep('0', df$str) == "1", 1, 0)
</code>```

But this returns less rows than the number of total rows in df.

On inspection i found that

```<code>grep('0', df$str[1]) returns int(0)
</code>```

whereas
    grep('0', df$str[2]) returns 1

Any idea how I could use this

答:
you can use grepl like this

```<code>df <- read.table(text = "id str
a  1
b  10
c  0
d  102
e  010", header = T)

df$Flag <- ifelse(grepl(0,df$str), 1, 0)

> df
  id str Flag
1  a   1    0
2  b  10    1
3  c   0    1
4  d 102    1
5  e  10    1
</code>```

Body:
I have a dataframe with string values

id str
a  1
b  10
c  0
d  102
e  010

I need to create a flag such that if there is a 0 in the str, the flag is 1 else, the flag is 0

I'm using the following code :

df$flag <-ifelse(grep('0', df$str) == "1", 1, 0)

But this returns less rows than the number of total rows in df.

On inspection i found that

grep('0', df$str[1]) returns int(0)

whereas
    grep('0', df$str[2]) returns 1

Any idea how I could use this

Body:
you can use grepl like this

df <- read.table(text = "id str
a  1
b  10
c  0
d  102
e  010", header = T)

df$Flag <- ifelse(grepl(0,df$str), 1, 0)

> df
  id str Flag
1  a   1    0
2  b  10    1
3  c   0    1
4  d 102    1
5  e  10    1


问:
Pyramid AuthTktAuthenticationPolicy callback never invoked

Im trying to implement simple authentication in Pyramid by using AuthTktAuthenticationPolicy. I follow this - authentication and this - authorization.

init.py

```<code>from pyramid.config import Configurator

from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from .security import groupfinder, Root

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    #config = Configurator(settings=settings)

    # ACL
    config = Configurator(settings=settings, root_factory=Root)
    authn_policy = AuthTktAuthenticationPolicy('sosecret', callback=groupfinder, hashalg='sha512')
    authz_policy = ACLAuthorizationPolicy()
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)

    config.include('pyramid_jinja2')
    config.include('.models')
    config.include('.routes')
    config.scan()
    return config.make_wsgi_app()
</code>```

security.py

```<code>GROUPS = {'admin': ['group:admin']}
USERS = {'receptionist' : 'receptionist'}

def groupfinder(userid, request):
    print("It's here")
    return ['group:admin']

from pyramid.security import Allow, Everyone

class Root(object):
    def __acl__(self):
        return [(Allow, Everyone, 'view'), (Allow, 'group:admin', 'edit')]

def __init__(self, request):
    pass
</code>```

my view default.py

```<code>...

@view_config(route_name='login', renderer='../templates/login.jinja2')
def login(request):
    try:
        if not ('user_name' in request.params and 'password' in request.params):
            return {}

        if request.params['user_name'] == '' or request.params['password'] == '':
            raise Exception('Ada inputan yang kosong dari form')

        match_ = request.dbsession.query(TblUser).filter_by(user_name=request.params['user_name'], user_password=request.params['password']).one()
        username = request.params['user_name']

        if match_ is not None:
            headers = remember(request, username)
            request.response.headerlist.extend(headers)
            next_url = request.route_url('search-room')

            return HTTPFound(location=next_url)

    except Exception as e:
        log.exception(str(e))
        return {'code' : 'error', 'message' : str(e) }

...

@view_config(route_name='search-room', renderer='../templates/search-room.jinja2', permission='edit')
def search_room(request):
    try:
        if not ('floor' in request.params):
            return {}

        if request.params['floor'] == '':
            raise Exception('Ada inputan yang kosong dari form')

        query = request.dbsession.query(TblReservation)
        result = query.join(TblRoom, aliased=True).filter_by(room_floor=request.params['floor']).all()

        if result is None or len(result) < 1:
            raise Exception("No row found")

        return {'code' : 'ok', 'message' : '', 'content' : result }

    except Exception as e:
        log.exception(str(e))
        return {'code' : 'error', 'message' : str(e), 'content' : ''}
</code>```

Full code in repo https://github.com/muhakbaryasin/pyramid-simple-acl

I set at least the user need to be authenticated and authorized as 'admin' so it can get 'edit' role and access 'search-room' page.

What I got right now is the login process is done but it wont give the authorization to access 'search-room' and the groupfinder is never invoked.

What do I miss? :(

答: Run a diff against the source in the Pyramid Quick Tutorial to find what you missed.</p>

Body:
Im trying to implement simple authentication in Pyramid by using AuthTktAuthenticationPolicy. I follow this - authentication and this - authorization.

init.py

from pyramid.config import Configurator

from pyramid.authentication import AuthTktAuthenticationPolicy
from pyramid.authorization import ACLAuthorizationPolicy
from .security import groupfinder, Root

def main(global_config, **settings):
    """ This function returns a Pyramid WSGI application.
    """
    #config = Configurator(settings=settings)

    # ACL
    config = Configurator(settings=settings, root_factory=Root)
    authn_policy = AuthTktAuthenticationPolicy('sosecret', callback=groupfinder, hashalg='sha512')
    authz_policy = ACLAuthorizationPolicy()
    config.set_authentication_policy(authn_policy)
    config.set_authorization_policy(authz_policy)

    config.include('pyramid_jinja2')
    config.include('.models')
    config.include('.routes')
    config.scan()
    return config.make_wsgi_app()

security.py

GROUPS = {'admin': ['group:admin']}
USERS = {'receptionist' : 'receptionist'}

def groupfinder(userid, request):
    print("It's here")
    return ['group:admin']

from pyramid.security import Allow, Everyone

class Root(object):
    def __acl__(self):
        return [(Allow, Everyone, 'view'), (Allow, 'group:admin', 'edit')]

def __init__(self, request):
    pass

my view default.py

...

@view_config(route_name='login', renderer='../templates/login.jinja2')
def login(request):
    try:
        if not ('user_name' in request.params and 'password' in request.params):
            return {}

        if request.params['user_name'] == '' or request.params['password'] == '':
            raise Exception('Ada inputan yang kosong dari form')

        match_ = request.dbsession.query(TblUser).filter_by(user_name=request.params['user_name'], user_password=request.params['password']).one()
        username = request.params['user_name']

        if match_ is not None:
            headers = remember(request, username)
            request.response.headerlist.extend(headers)
            next_url = request.route_url('search-room')

            return HTTPFound(location=next_url)

    except Exception as e:
        log.exception(str(e))
        return {'code' : 'error', 'message' : str(e) }

...

@view_config(route_name='search-room', renderer='../templates/search-room.jinja2', permission='edit')
def search_room(request):
    try:
        if not ('floor' in request.params):
            return {}

        if request.params['floor'] == '':
            raise Exception('Ada inputan yang kosong dari form')

        query = request.dbsession.query(TblReservation)
        result = query.join(TblRoom, aliased=True).filter_by(room_floor=request.params['floor']).all()

        if result is None or len(result) < 1:
            raise Exception("No row found")

        return {'code' : 'ok', 'message' : '', 'content' : result }

    except Exception as e:
        log.exception(str(e))
        return {'code' : 'error', 'message' : str(e), 'content' : ''}

Full code in repo https://github.com/muhakbaryasin/pyramid-simple-acl

I set at least the user need to be authenticated and authorized as 'admin' so it can get 'edit' role and access 'search-room' page.

What I got right now is the login process is done but it wont give the authorization to access 'search-room' and the groupfinder is never invoked.

What do I miss? :(


问:
Execution of xpath failed in Mulesoft
My Mulesoft process is making a call to SuccessFactors API. The /LOGIN call results in a response like this.

```<code>    <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
       <S:Body>
          <loginResponse xmlns="urn:sfobject.sfapi.successfactors.com" xmlns:ns2="urn:fault.sfapi.successfactors.com">
             <result>
                <sessionId>9A95*******A2631B8E820894CA.ps8bsfapi52t</sessionId>
                <msUntilPwdExpiration>9223372036854775807</msUntilPwdExpiration>
             </result>
          </loginResponse>
       </S:Body>
    </S:Envelope>
</code>```

I've the following name spaces declared in my namespace manager

```<code>            <mulexml:namespace-manager>
                <mulexml:namespace prefix="S" uri="http://schemas.xmlsoap.org/soap/envelope/"/>
                <mulexml:namespace prefix="ns2" uri="urn:fault.sfapi.successfactors.com"/>
                <mulexml:namespace prefix="" uri="urn:sfobject.sfapi.successfactors.com"/>
            </mulexml:namespace-manager>
</code>```

I want to read the sessionId into a mule session variable.

```<code>    <set-session-variable variableName="SESSION" value="#[xpath('//S:Envelope/S:Body/loginResponse/result/sessionId').text]" doc:name="Get Session from Login"/>
</code>```

But, upon execution I end up in this

```<code>        <faultstring>Execution of the expression "xpath('//S:Envelope/S:Body/loginResponse/result/sessionId').text" failed. (org.mule.api.expression.ExpressionRuntimeException).</faultstring>
</code>```

The XPath checks out well on any other tool but for Mulesoft.

答:
Use XPATH with * as namespace, so you dont need to bother about namespace.

```<code>#[xpath('//*:Envelope/*:Body/*:loginResponse/*:result/*:sessionId').text]
</code>```

xpath is deprecated new version of mule.

Update:

```<code>#[xpath3('//*:Envelope/*:Body/*:loginResponse/*:result/*:sessionId')]
</code>```

Hope this helps.

Title: Execution of xpath failed in Mulesoft

Body:
My Mulesoft process is making a call to SuccessFactors API. The /LOGIN call results in a response like this.

    <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
       <S:Body>
          <loginResponse xmlns="urn:sfobject.sfapi.successfactors.com" xmlns:ns2="urn:fault.sfapi.successfactors.com">
             <result>
                <sessionId>9A95*******A2631B8E820894CA.ps8bsfapi52t</sessionId>
                <msUntilPwdExpiration>9223372036854775807</msUntilPwdExpiration>
             </result>
          </loginResponse>
       </S:Body>
    </S:Envelope>

I've the following name spaces declared in my namespace manager

            <mulexml:namespace-manager>
                <mulexml:namespace prefix="S" uri="http://schemas.xmlsoap.org/soap/envelope/"/>
                <mulexml:namespace prefix="ns2" uri="urn:fault.sfapi.successfactors.com"/>
                <mulexml:namespace prefix="" uri="urn:sfobject.sfapi.successfactors.com"/>
            </mulexml:namespace-manager>

I want to read the sessionId into a mule session variable.

    <set-session-variable variableName="SESSION" value="#[xpath('//S:Envelope/S:Body/loginResponse/result/sessionId').text]" doc:name="Get Session from Login"/>

But, upon execution I end up in this

        <faultstring>Execution of the expression "xpath('//S:Envelope/S:Body/loginResponse/result/sessionId').text" failed. (org.mule.api.expression.ExpressionRuntimeException).</faultstring>

The XPath checks out well on any other tool but for Mulesoft.

Body:
Use XPATH with * as namespace, so you dont need to bother about namespace.

#[xpath('//*:Envelope/*:Body/*:loginResponse/*:result/*:sessionId').text]

xpath is deprecated new version of mule.

Update:

#[xpath3('//*:Envelope/*:Body/*:loginResponse/*:result/*:sessionId')]

Hope this helps.


问:
How to deserialize JSON from MVC using JQuery?
Ok, its late Friday afternoon, and I've been fighting this for way too long... I have an MVC2 class that returns a JSON. JQuery throws an error when trying to deserialize it in the browser.

Here's the controller:

```<code><HttpPost()>
Function ChangeAddress(ByVal addressId As Integer) As ActionResult

    ' Build and return JSON containing address.
    Dim v As New TestViewModel With {.Address1 = "My House"}
    Return Json(v)

End Function
</code>```

Here's the view model:

```<code>Public Class TestViewModel

    Public Property Address1 As String

End Class
</code>```

And here's the script:

```<code>// If list is not empty and item was found...
if (found == true) {

         var sum = 14;

    // Get fields of newly selected address.
    $.ajax({
        url: '../../Checkout/ChangeAddress',
        type: 'POST',
        traditional: true,
             data: { addressId: sum },
        success: function (result) {

            var json = result.get_data();
            var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);

            alert("Success!");

        }
    });
};
</code>```

The deserialization code is from the MVC Music Store example. When executed, JQuery throws an exception on get_data, saying "Object doesn't support this property or method". Ok, so I try commenting out that line and trying deserialize(result). Then exception says "Sys.ArgumentException: Cannot deserialize. The data does not correspond to valid JSON. Parameter name: data".

Where am I going wrong?

答:
You should not need to explicitly parse ("deserialize") your JSON! jQuery will try to do this automagically, provided that it can correctly guess the dataType returned. You can, of course, specify that you're expecting JSON:

```<code>$.ajax({
    url: '../../Checkout/ChangeAddress',
    type: 'POST',
    dataType: 'JSON',               // <========== this line
    traditional: true,
    data: {addressId: sum},
    success: function (result) {

        var json = result.get_data();
        var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);

        alert("Success!");
    }
});
</code>```

That said - it is possible that the XHR is not coming back with valid JSON. Could you perhaps provide an example of the JSON returned to your jQuery success callback?

ContentLicense: CC BY-SA 2.5

Body:
Ok, its late Friday afternoon, and I've been fighting this for way too long... I have an MVC2 class that returns a JSON. JQuery throws an error when trying to deserialize it in the browser.

Here's the controller:

<HttpPost()>
Function ChangeAddress(ByVal addressId As Integer) As ActionResult

    ' Build and return JSON containing address.
    Dim v As New TestViewModel With {.Address1 = "My House"}
    Return Json(v)

End Function

Here's the view model:

Public Class TestViewModel

    Public Property Address1 As String

End Class

And here's the script:

// If list is not empty and item was found...
if (found == true) {

         var sum = 14;

    // Get fields of newly selected address.
    $.ajax({
        url: '../../Checkout/ChangeAddress',
        type: 'POST',
        traditional: true,
             data: { addressId: sum },
        success: function (result) {

            var json = result.get_data();
            var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);

            alert("Success!");

        }
    });
};

The deserialization code is from the MVC Music Store example. When executed, JQuery throws an exception on get_data, saying "Object doesn't support this property or method". Ok, so I try commenting out that line and trying deserialize(result). Then exception says "Sys.ArgumentException: Cannot deserialize. The data does not correspond to valid JSON. Parameter name: data".

Where am I going wrong?

Body:
You should not need to explicitly parse ("deserialize") your JSON! jQuery will try to do this automagically, provided that it can correctly guess the dataType returned. You can, of course, specify that you're expecting JSON:

$.ajax({
    url: '../../Checkout/ChangeAddress',
    type: 'POST',
    dataType: 'JSON',               // <========== this line
    traditional: true,
    data: {addressId: sum},
    success: function (result) {

        var json = result.get_data();
        var data = Sys.Serialization.JavaScriptSerializer.deserialize(json);

        alert("Success!");
    }
});

That said - it is possible that the XHR is not coming back with valid JSON. Could you perhaps provide an example of the JSON returned to your jQuery success callback?


问:
Android EditText How to disable automatic insertion of spaces when pasting text?
Sometimes, when pasting text in an EditText, blanks/spaces are automatically inserted. For example, this happens if text is pasted into the middle or at the end of text that is already contained in the text field. Is there a way to tell the EditText object or the ClipboardManager that leading and trailing blanks should not automatically be inserted?</p>

答:
I'm late but in my old tablet, my EditText also works like you said.

So, I fixed it like below.

1.Create a class to store the information about the start index and the length of inserted string.

```<code>public class PasteUnit {
    int start = 0;
    int length = 0;

    public PasteUnit(int start, int length) {
        this.start = start;
        this.length = length;
    }
}
</code>```

2.Create a class that extends EditText.

```<code>public class MyEditText extends EditText
{
    boolean pasteStarted = false;
    ArrayList<PasteUnit> pasteUnits = new ArrayList<>();

    public MyEditText(Context context)
    {
        super(context);
    }

    public MyEditText(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public MyEditText(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onTextContextMenuItem(int id) {
        if(id==android.R.id.paste) {//This is called when the paste is triggered
            pasteStarted = true;
        }

        boolean consumed = super.onTextContextMenuItem(id);
        //the super.onTextContextMenuItem(id) processes the pasted string.
        //This is where EditText acts weird.
        //And we can watch what is happening in our TextWatcher to be added below

        switch (id){
            case android.R.id.paste://This is called after we collected all the information

                if(pasteUnits.size()>1) {//When a space or spaces are inserted
                    int startIndex = pasteUnits.get(0).start;
                    int totalLength = 0;
                    for(int i=0;i<pasteUnits.size();i++) {
                        PasteUnit pasteUnit = pasteUnits.get(i);
                        totalLength = totalLength + pasteUnit.length;
                    }
                    int endIndex = startIndex + totalLength;

                    String string = this.getText().toString();
                    String before = string.substring(0, startIndex);
                    String after = string.substring(endIndex);

                    PasteUnit lastPasteUnit = pasteUnits.get(pasteUnits.size()-1);
                    String lastString = string.substring(lastPasteUnit.start, lastPasteUnit.start + lastPasteUnit.length);

                    String result = before + lastString + after;
                    this.setText(result);
                    this.setSelection(startIndex + lastString.length());
                }
                pasteUnits.clear();
                pasteStarted = false;
                break;
            case android.R.id.copy:
                break;
            case android.R.id.cut:
                break;
        }
        return consumed;
    }
}
</code>```

3.Add TextWatcher to your EditText.

The old EditText acts really weird seeing the TextWatcher. When you paste string A into string B, it first inserts a space into string B, and it inserts another space into string B, and last it inserts string A between the two spaces.

And in other situations like pasting string A after string B, it first appends a space after string B and after that appends string A.

So anyway it seems to insert the original string at the last step.

```<code>   MyEditText edit = (MyEditText) findViewById(R.id.mainEditText1);

   edit.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if(edit.pasteStarted) {//when it is processing what we pasted
                    edit.pasteUnits.add(new PasteUnit(start, count));
                   //store the information about the inserted spaces and the original pasted string
                }
            }
        });
</code>```

Body:
I'm late but in my old tablet, my EditText also works like you said.

So, I fixed it like below.

1.Create a class to store the information about the start index and the length of inserted string.

public class PasteUnit {
    int start = 0;
    int length = 0;

    public PasteUnit(int start, int length) {
        this.start = start;
        this.length = length;
    }
}

2.Create a class that extends EditText.

public class MyEditText extends EditText
{
    boolean pasteStarted = false;
    ArrayList<PasteUnit> pasteUnits = new ArrayList<>();

    public MyEditText(Context context)
    {
        super(context);
    }

    public MyEditText(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    public MyEditText(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean onTextContextMenuItem(int id) {
        if(id==android.R.id.paste) {//This is called when the paste is triggered
            pasteStarted = true;
        }

        boolean consumed = super.onTextContextMenuItem(id);
        //the super.onTextContextMenuItem(id) processes the pasted string.
        //This is where EditText acts weird.
        //And we can watch what is happening in our TextWatcher to be added below

        switch (id){
            case android.R.id.paste://This is called after we collected all the information

                if(pasteUnits.size()>1) {//When a space or spaces are inserted
                    int startIndex = pasteUnits.get(0).start;
                    int totalLength = 0;
                    for(int i=0;i<pasteUnits.size();i++) {
                        PasteUnit pasteUnit = pasteUnits.get(i);
                        totalLength = totalLength + pasteUnit.length;
                    }
                    int endIndex = startIndex + totalLength;

                    String string = this.getText().toString();
                    String before = string.substring(0, startIndex);
                    String after = string.substring(endIndex);

                    PasteUnit lastPasteUnit = pasteUnits.get(pasteUnits.size()-1);
                    String lastString = string.substring(lastPasteUnit.start, lastPasteUnit.start + lastPasteUnit.length);

                    String result = before + lastString + after;
                    this.setText(result);
                    this.setSelection(startIndex + lastString.length());
                }
                pasteUnits.clear();
                pasteStarted = false;
                break;
            case android.R.id.copy:
                break;
            case android.R.id.cut:
                break;
        }
        return consumed;
    }
}

3.Add TextWatcher to your EditText.

The old EditText acts really weird seeing the TextWatcher. When you paste string A into string B, it first inserts a space into string B, and it inserts another space into string B, and last it inserts string A between the two spaces.

And in other situations like pasting string A after string B, it first appends a space after string B and after that appends string A.

So anyway it seems to insert the original string at the last step.

   MyEditText edit = (MyEditText) findViewById(R.id.mainEditText1);

   edit.addTextChangedListener(new TextWatcher() {

            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if(edit.pasteStarted) {//when it is processing what we pasted
                    edit.pasteUnits.add(new PasteUnit(start, count));
                   //store the information about the inserted spaces and the original pasted string
                }
            }
        });


问:
Helly's theorem Test?
I'm working on this following problem:

Method common_point: returns True if there exists a point that intersects all rectangles in the calling canvas. To test this (for axis parallel rectangles like ours), it is enough to test if every pair of rectangles intersects (according to a Helly’s theorem for axis-aligned rectangles:
http://en.wikipedia.org/wiki/Helly's_theorem

How would test Helly's theorum  in this case? Helly's theorem states that for N convex objects in D-dimensional space the fact that any (D+1) of them intersect implies that all together they have a common point. SO this means I have to check if any 3 rectangles intersect right? How would I do this??

So far I have:

```<code>def common_point(self):
    '''(Canvas)-> bool'''
    count=0
    for i in range(len(self.listofrectangles)-1):
        if self.listofrectangles[i].intersects(self.listofrectangles[i+1]):
            count +=1
    if count>=3:
        return True
    else:
        return False
</code>```

And when I run this I get True instead of False

```<code>>>>
>>> c=Canvas()
>>> r1=Rectangle(Point(-2,-2), Point(-1,2), "blue")
>>> r2=Rectangle(Point(-2,-2), Point(2,-1), "blue")
>>> r3=Rectangle(Point(1,-2), Point(2,2), "blue")
>>> r4=Rectangle(Point(-2,1), Point(2,2), "blue")
>>> c.add_one_rectangle(r1)
>>> c.add_one_rectangle(r2)
>>> c.add_one_rectangle(r3)
>>> c.add_one_rectangle(r4)
>>> c.common_point()
False
</code>```

Updated code:

```<code> def common_point(self):
        '''(Canvas)-> bool'''
        TopRightx=[]
        TopRighty=[]
        BottomLeftx=[]
        BottomLefty=[]

        for i in self.listofrectangles:
            xval= i.bLx
            x2val= i.tRx
            TopRightx.append(x2val)
            BottomLeftx.append(xval)
            yval= i.bLy
            y2val= i.tRy
            BottomLefty.append(yval)
            TopRighty.append(y2val)

        if ((max(BottomLeftx))< (min(TopRightx))) and ((max(TopRighty))< (min(BottomLefty))):
            return True

        else:
            return False
</code>```

答:
You seem to be misunderstanding the theorem.  It is not sufficient that there be three independent intersections of two rectangles (that's absurd: imagine one additional rectangle, nowhere near the rest).  What the theorem says is that every individual subset of 3 rectangles must intersect, in order for the entire set to intersect.

The theorem doesn't seem to be a useful base for a computer algorithm, anyway, as enumerating all of the subsets of 3 out of n rectangles would take O(n3) time.  You can easily check for a common intersection with a single loop over all the rectangles: just keep track of the greatest left and top coordinates, and the least right and bottom coordinates.  If greatestLeft < leastRight, and greatestTop < leastBottom, there's an intersection (and those four coordinates give the exact bounds of the common area).

Title: Helly's theorem Test?

Body:
I'm working on this following problem:

Method common_point: returns True if there exists a point that intersects all rectangles in the calling canvas. To test this (for axis parallel rectangles like ours), it is enough to test if every pair of rectangles intersects (according to a Helly’s theorem for axis-aligned rectangles:
http://en.wikipedia.org/wiki/Helly's_theorem

How would test Helly's theorum  in this case? Helly's theorem states that for N convex objects in D-dimensional space the fact that any (D+1) of them intersect implies that all together they have a common point. SO this means I have to check if any 3 rectangles intersect right? How would I do this??

So far I have:

def common_point(self):
    '''(Canvas)-> bool'''
    count=0
    for i in range(len(self.listofrectangles)-1):
        if self.listofrectangles[i].intersects(self.listofrectangles[i+1]):
            count +=1
    if count>=3:
        return True
    else:
        return False

And when I run this I get True instead of False

>>>
>>> c=Canvas()
>>> r1=Rectangle(Point(-2,-2), Point(-1,2), "blue")
>>> r2=Rectangle(Point(-2,-2), Point(2,-1), "blue")
>>> r3=Rectangle(Point(1,-2), Point(2,2), "blue")
>>> r4=Rectangle(Point(-2,1), Point(2,2), "blue")
>>> c.add_one_rectangle(r1)
>>> c.add_one_rectangle(r2)
>>> c.add_one_rectangle(r3)
>>> c.add_one_rectangle(r4)
>>> c.common_point()
False

Updated code:

 def common_point(self):
        '''(Canvas)-> bool'''
        TopRightx=[]
        TopRighty=[]
        BottomLeftx=[]
        BottomLefty=[]

        for i in self.listofrectangles:
            xval= i.bLx
            x2val= i.tRx
            TopRightx.append(x2val)
            BottomLeftx.append(xval)
            yval= i.bLy
            y2val= i.tRy
            BottomLefty.append(yval)
            TopRighty.append(y2val)

        if ((max(BottomLeftx))< (min(TopRightx))) and ((max(TopRighty))< (min(BottomLefty))):
            return True

        else:
            return False


问:
get error while file upload in laravel
I am trying to upload image in laravel. But when i upload it gives error.

Call to a member function getClientOriginalExtension() on null

Here is my Blade file form

```<code>{{Form::open(array('url' => '/AddNewBlog','id'=>'blogadd' ,
   'method' => 'post','class'=>'form-row','files'=>true,
   "enctype"=>"multipart/form-data"))}}
</code>```

And here is controller

```<code> $imagename_bg = time() . '.' . $photo->getClientOriginalExtension();
 $destinationPath = public_path('/uploads/blog');
 $thumb_img = Image::make($photo->getRealPath())->resize(750, 450);
 $thumb_img->save($destinationPath . '/' . $imagename_bg, 80);
 $photo->move($destinationPath, $imagename_bg);
</code>```

Please help me how to resolve this problem.

答:
```<code>$photo = $request->file('file_name');
</code>```

Title: get error while file upload in laravel

Body:
I am trying to upload image in laravel. But when i upload it gives error.

Call to a member function getClientOriginalExtension() on null

Here is my Blade file form

{{Form::open(array('url' => '/AddNewBlog','id'=>'blogadd' ,
   'method' => 'post','class'=>'form-row','files'=>true,
   "enctype"=>"multipart/form-data"))}}

And here is controller

 $imagename_bg = time() . '.' . $photo->getClientOriginalExtension();
 $destinationPath = public_path('/uploads/blog');
 $thumb_img = Image::make($photo->getRealPath())->resize(750, 450);
 $thumb_img->save($destinationPath . '/' . $imagename_bg, 80);
 $photo->move($destinationPath, $imagename_bg);

Please help me how to resolve this problem.

Body: $photo = $request->file('file_name');


问:
Sendgrid : How to use mimepart with their PHP Api
Somthing makes me crazy, I use Sendgrid to send emails and I would like to send emails in PHP with both text/plain and text/html variants.

What I tried :

I have analyzed an email with 2 content-type. I see :

----==_mimepart_35656456787

Content-Type: text/plain; charset=UTF-8

[plain text version....]

----==_mimepart_67868876878

Content-Type: text/html; charset=UTF-8

[html version....]

Then I tried to add those 2 variants like this :

```<code>...
$from = new SendGrid\Email(null, $from);
$email = new SendGrid\Email(null, $to);
$content = new SendGrid\Content("text/plain",$body_plain);
$content1 = new SendGrid\Content("text/html",$body_html);

$mail = new SendGrid\Mail($from, $subject, $email, $content1, $content);
</code>```

Result :

Here is what I get :

----==_35656456787

Content-Type: text/plain; charset=UTF-8

[plain text version....]

----==_67868876878

Content-Type: text/html; charset=UTF-8

[html version....]

The mimepart is missing.

Sendgrid also advice (here : https://sendgrid.com/docs/Classroom/Build/Format_Content/html_formatting_issues.html) to send emails using both plain and html variants. So it's probably possible...

But I tried to find how to do that and I didn't find sthg..

Question : does someone has the same problem ? how to send emails using both plain and html??

Any idea?

答:
I checked the source code and found the Mail() function only takes 4 arguments,

```<code>public function __construct($from, $subject, $to, $content)
</code>```

so your code

```<code>$mail = new SendGrid\Mail($from, $subject, $email, $content1, $content);
</code>```

shouldn't work.

You can send both HTML and Plain text without using the helper class:

```<code>// If you are using Composer (recommended)
require 'vendor/autoload.php';

// If you are not using Composer
// require("path/to/sendgrid-php/sendgrid-php.php");
$to_email="recepient@somedomain.com";
$to_name="John Smith";
$subject="Testing sendgrid. See you in spam folder!";
$html="and easy to do anywhere, even with PHP<a href='https://someurl.com'>Really</a>";
$text="and easy to do anywhere, even with PHP";

$json=<<<JSON
{
  "personalizations": [
    {
      "to": [
        {
          "email": "$to_email",
          "name": "$to_name"
        }
      ],
      "subject": "$subject"
    }
  ],
  "from": {
    "email": "youremail@somedomain.com",
    "name": "Your Name"
  },
  "content": [
    {
      "type": "text/plain",
      "value": "$text"
    },
    {
      "type": "text/html",
      "value": "$html"
    }
  ]
}
JSON;

$request_body = json_decode($json);

$apiKey = "yourapikey";
$sg = new \SendGrid($apiKey);

$response = $sg->client->mail()->send()->post($request_body);
echo $response->statusCode();
echo $response->body();
print_r($response->headers());
</code>```

Body:
Somthing makes me crazy, I use Sendgrid to send emails and I would like to send emails in PHP with both text/plain and text/html variants.

What I tried :

I have analyzed an email with 2 content-type. I see :

----==_mimepart_35656456787

Content-Type: text/plain; charset=UTF-8

[plain text version....]

----==_mimepart_67868876878

Content-Type: text/html; charset=UTF-8

[html version....]

Then I tried to add those 2 variants like this :

...
$from = new SendGrid\Email(null, $from);
$email = new SendGrid\Email(null, $to);
$content = new SendGrid\Content("text/plain",$body_plain);
$content1 = new SendGrid\Content("text/html",$body_html);

$mail = new SendGrid\Mail($from, $subject, $email, $content1, $content);

Result :

Here is what I get :

----==_35656456787

Content-Type: text/plain; charset=UTF-8

[plain text version....]

----==_67868876878

Content-Type: text/html; charset=UTF-8

[html version....]

The mimepart is missing.

Sendgrid also advice (here : https://sendgrid.com/docs/Classroom/Build/Format_Content/html_formatting_issues.html) to send emails using both plain and html variants. So it's probably possible...

But I tried to find how to do that and I didn't find sthg..

Question : does someone has the same problem ? how to send emails using both plain and html??

Any idea?

Body:
I checked the source code and found the Mail() function only takes 4 arguments,

public function __construct($from, $subject, $to, $content)

so your code

$mail = new SendGrid\Mail($from, $subject, $email, $content1, $content);

shouldn't work.

You can send both HTML and Plain text without using the helper class:

// If you are using Composer (recommended)
require 'vendor/autoload.php';

// If you are not using Composer
// require("path/to/sendgrid-php/sendgrid-php.php");
$to_email="recepient@somedomain.com";
$to_name="John Smith";
$subject="Testing sendgrid. See you in spam folder!";
$html="and easy to do anywhere, even with PHP<a href='https://someurl.com'>Really</a>";
$text="and easy to do anywhere, even with PHP";

$json=<<<JSON
{
  "personalizations": [
    {
      "to": [
        {
          "email": "$to_email",
          "name": "$to_name"
        }
      ],
      "subject": "$subject"
    }
  ],
  "from": {
    "email": "youremail@somedomain.com",
    "name": "Your Name"
  },
  "content": [
    {
      "type": "text/plain",
      "value": "$text"
    },
    {
      "type": "text/html",
      "value": "$html"
    }
  ]
}
JSON;

$request_body = json_decode($json);

$apiKey = "yourapikey";
$sg = new \SendGrid($apiKey);

$response = $sg->client->mail()->send()->post($request_body);
echo $response->statusCode();
echo $response->body();
print_r($response->headers());


问:
Positioning of footer text
I am trying to add a footer similar to the Airbnb one. I have been able to do the first two columns. However the third one is always slightly below the rest. I've tried:
Position: Absolute (however this makes it disappear)
Position: relative (this works fine however it remove the links from the other two columns).
Float: right and left but doesn't let me move it up.

I'm running out of ideas of what to do so if someone could help me that would be great. here is my code and a image of what I have made.

footer {
  border-style: solid;
  border-color: grey;
  border-width: 0.25px;
  background-color: #EF6248;
  -webkit-box-shadow: 0 5px 10px -6px black;
  -moz-box-shadow: 0 5px 10px -6px black;
  box-shadow: 0 5px 10px -6px black;
  /* NOTE: shadow of footer */
  padding-bottom: 200px;
  margin-top: 10%;
  /* NOTE: where the footer sits on page */
}

.footer-links {
  color: white;
}

.footer-links:hover {
  color: black;
}

.col-1 {
  padding-left: 150px;
  padding-top: 15px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  float: left;
}

.col-1 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-2 {
  padding-top: 15px;
  padding-left: 130px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  position: relative;
}

.col-2 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-3 {
  padding-top: 15px;
  padding-left: 550px;
  padding-bottom: 100px;
  bottom: 100px;
  color: white;
  font-weight: bold;
  display: table;
  float: left;
  positi
}

.col-3 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>

  <div class="col-1">
    Revel
    <hr>
    <span> About us       </span>
    <span> Contact us     </span>
    <span> FAQ            </span>
    <span> Careers        </span>
  </div>

  <div class="col-2">
    Event Host
    <hr>
    <span>  Why use Revel  </span>
    <span>  test           </span>
    <span>  test           </span>
    <span>  Join Revel     </span>
  </div>

  <div class="col-3">
    Event Service
    <hr>
    <span> Why partner with Revel  </span>
    <span> Guidebooks              </span>
    <span> FAQ                     </span>
    <span> Partner with Revel      </span>
  </div>

</footer></code>```

enter image description here

答:
Please don't make it too complicated. It is simple with few lines of style. check the example below.

footer {
width: 100%;
  border-style: solid;
  border-color: grey;
  border-width: 0.25px;
  background-color: #EF6248;
  -webkit-box-shadow: 0 5px 10px -6px black;
   -moz-box-shadow: 0 5px 10px -6px black;
        box-shadow: 0 5px 10px -6px black; /* NOTE: shadow of footer */
  padding-bottom: 200px;
  margin-top: 10%; /* NOTE: where the footer sits on page */

  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
 }

 .footer-links {
   color: white;
 }
 .footer-links:hover {
   color: black;
 }

.col-1,
.col-2,
.col-3 {
 width: 30%;
 margin: 0 1.65%;
 float: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>

    <div class="col-1">
         Revel
             <hr>
      <span> About us       </span>
      <span> Contact us     </span>
      <span> FAQ            </span>
      <span> Careers        </span>
      </div>

    <div class="col-2">
         Event Host
         <hr>
      <span>  Why use Revel  </span>
      <span>  test           </span>
      <span>  test           </span>
      <span>  Join Revel     </span>
    </div>

    <div class="col-3">
        Event Service
       <hr>
       <span> Why partner with Revel  </span>
       <span> Guidebooks              </span>
       <span> FAQ                     </span>
       <span> Partner with Revel      </span>
    </div>

  </footer></code>```

Title: Positioning of footer text

Body:
I am trying to add a footer similar to the Airbnb one. I have been able to do the first two columns. However the third one is always slightly below the rest. I've tried:
Position: Absolute (however this makes it disappear)
Position: relative (this works fine however it remove the links from the other two columns).
Float: right and left but doesn't let me move it up.

I'm running out of ideas of what to do so if someone could help me that would be great. here is my code and a image of what I have made.

footer {
  border-style: solid;
  border-color: grey;
  border-width: 0.25px;
  background-color: #EF6248;
  -webkit-box-shadow: 0 5px 10px -6px black;
  -moz-box-shadow: 0 5px 10px -6px black;
  box-shadow: 0 5px 10px -6px black;
  /* NOTE: shadow of footer */
  padding-bottom: 200px;
  margin-top: 10%;
  /* NOTE: where the footer sits on page */
}

.footer-links {
  color: white;
}

.footer-links:hover {
  color: black;
}

.col-1 {
  padding-left: 150px;
  padding-top: 15px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  float: left;
}

.col-1 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-2 {
  padding-top: 15px;
  padding-left: 130px;
  line-height: 40px;
  color: white;
  font-family: raleway;
  font-weight: bold;
  display: table;
  position: relative;
}

.col-2 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

.col-3 {
  padding-top: 15px;
  padding-left: 550px;
  padding-bottom: 100px;
  bottom: 100px;
  color: white;
  font-weight: bold;
  display: table;
  float: left;
  positi
}

.col-3 span {
  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
}

    Revel

     About us
     Contact us
     FAQ
     Careers

    Event Host

      Why use Revel
      test
      test
      Join Revel

    Event Service

     Why partner with Revel
     Guidebooks
     FAQ
     Partner with Revel

enter image description here

Body:
Please don't make it too complicated. It is simple with few lines of style. check the example below.

footer {
width: 100%;
  border-style: solid;
  border-color: grey;
  border-width: 0.25px;
  background-color: #EF6248;
  -webkit-box-shadow: 0 5px 10px -6px black;
   -moz-box-shadow: 0 5px 10px -6px black;
        box-shadow: 0 5px 10px -6px black; /* NOTE: shadow of footer */
  padding-bottom: 200px;
  margin-top: 10%; /* NOTE: where the footer sits on page */

  color: white;
  line-height: 22px;
  font-weight: normal;
  display: table;
 }

 .footer-links {
   color: white;
 }
 .footer-links:hover {
   color: black;
 }

.col-1,
.col-2,
.col-3 {
 width: 30%;
 margin: 0 1.65%;
 float: left;
}

<footer>

    <div class="col-1">
         Revel
             <hr>
      <span><a href="#" class="footer-links"> About us       </a></span>
      <span><a href="#" class="footer-links"> Contact us     </a></span>
      <span><a href="#" class="footer-links"> FAQ            </a></span>
      <span><a href="#" class="footer-links"> Careers        </a></span>
      </div>

    <div class="col-2">
         Event Host
         <hr>
      <span> <a href="#" class="footer-links"> Why use Revel  </a></span>
      <span> <a href="#" class="footer-links"> test           </a></span>
      <span> <a href="#" class="footer-links"> test           </a></span>
      <span> <a href="#" class="footer-links"> Join Revel     </a></span>
    </div>

    <div class="col-3">
        Event Service
       <hr>
       <span><a href="#" class="footer-links"> Why partner with Revel  </a></span>
       <span><a href="#" class="footer-links"> Guidebooks              </a></span>
       <span><a href="#" class="footer-links"> FAQ                     </a></span>
       <span><a href="#" class="footer-links"> Partner with Revel      </a></span>
    </div>

  </footer>


问:
Finding the triggering statement
I want to write a trigger in MySQL, which will record down the statement that causes the trigger to fire. I know how to do this in Oracle:

```<code>n := ora_sql_txt(sql_text);
for i in 1..n loop
  stmt := stmt || sql_text(i);
end loop;
</code>```

But I can't find an equivalent in MySQL.

答:
The SQL text of the statement that caused the trigger to be fired might be available in the processlist table in information_schema database.

e.g. maybe something like this (not tested)

```<code>DECLARE ls_pl_info VARCHAR(65536);

SELECT pl.info
  INTO ls_pl_info
  FROM information_schema.processlist pl
 WHERE pl.id = CONNECTION_ID() ;
</code>```

-or maybe-

```<code>SELECT t.processlist_info
  INTO ls_pl_info
  FROM performance_schema.threads t
 WHERE t.processlist_id = CONNECTION_ID() ;
</code>```

(What I'm not sure about, and haven't tested, is whether the info column will contain the SQL text of the statement that fired the trigger, or if that's going to show the text of the current statement, which is accessing the processlist table.)

But that's the closest I can come; I don't believe the text of the statement that caused the trigger to fire is available within the trigger.

References:

https://dev.mysql.com/doc/refman/5.7/en/processlist-table.html

https://dev.mysql.com/doc/refman/5.7/en/thread-information.html

NOTE: If general_log is enabled (which isn't usually enabled on our systems; we usually only enable it temporarily to gather info for a small timeframe...) but I don;t think the triggering statement will be available in the general log until after it completes, which means after the fired triggers are completed.

Another option would be the binary log (if binary logging is enabled). But getting to that from inside a trigger seems like it would be messily over complicated.

Title: Finding the triggering statement

Body:
I want to write a trigger in MySQL, which will record down the statement that causes the trigger to fire. I know how to do this in Oracle:

n := ora_sql_txt(sql_text);
for i in 1..n loop
  stmt := stmt || sql_text(i);
end loop;

But I can't find an equivalent in MySQL.

Body:
The SQL text of the statement that caused the trigger to be fired might be available in the processlist table in information_schema database.

e.g. maybe something like this (not tested)

DECLARE ls_pl_info VARCHAR(65536);

SELECT pl.info
  INTO ls_pl_info
  FROM information_schema.processlist pl
 WHERE pl.id = CONNECTION_ID() ;

-or maybe-

SELECT t.processlist_info
  INTO ls_pl_info
  FROM performance_schema.threads t
 WHERE t.processlist_id = CONNECTION_ID() ;

(What I'm not sure about, and haven't tested, is whether the info column will contain the SQL text of the statement that fired the trigger, or if that's going to show the text of the current statement, which is accessing the processlist table.)

But that's the closest I can come; I don't believe the text of the statement that caused the trigger to fire is available within the trigger.

References:

https://dev.mysql.com/doc/refman/5.7/en/processlist-table.html

https://dev.mysql.com/doc/refman/5.7/en/thread-information.html

NOTE: If general_log is enabled (which isn't usually enabled on our systems; we usually only enable it temporarily to gather info for a small timeframe...) but I don;t think the triggering statement will be available in the general log until after it completes, which means after the fired triggers are completed.

Another option would be the binary log (if binary logging is enabled). But getting to that from inside a trigger seems like it would be messily over complicated.


问:
Signature error while connecting to s3 bucket via sparklyr
I am encountering an error when I  try to connect to a s3 bucket from R studio using sparklyr. The s3 bucket is in the eu-central-1(Frankfurt) region. Spark version - 2.1.0 , Hadoop 2.7. I am getting a 403 response code with signature mismatch error. However,  when I try to get an s3a bucket instead however I get a 400 response code. Any word on alternative methods to connect to s3 buckets via spark in R studio, is also appreciated. The connection to s3 works fine without Spark.

Here is the code,

```<code>   # install.packages("devtools")
# devtools::install_github("rstudio/sparklyr")
library(sparklyr)
library(dplyr)
sc <- spark_connect(master = "local")
spark_disconnect(sc)
config <- spark_config()
library(sparklyr)
library(dplyr)
# config$sparklyr.defaultPackages <- "org.apache.hadoop:hadoop-aws:2.7.3"
# config$spark.executor.memory <- "4g"
sc <- spark_connect(master = "local",config = config)

ctx <- sparklyr::spark_context(sc)
jsc <- invoke_static(
sc,
"org.apache.spark.api.java.JavaSparkContext",
"fromSparkContext",
ctx
)

hconf <- jsc %>% invoke("hadoopConfiguration")
hconf %>% invoke("set","fs.s3.access.key", "xx")
hconf %>% invoke("set","fs.s3.secret.key", "xx")
#hconf %>% invoke("set","com.amazonaws.services.s3.enableV4", "true")
test <- spark_read_csv(sc, "test", "s3://********.csv")
</code>```

Error: org.apache.hadoop.fs.s3.S3Exception: org.jets3t.service.S3ServiceException: Service Error Message. -- ResponseCode: 403, ResponseStatus: Forbidden, XML Error Message: <?xml version="1.0" encoding="UTF-8"?><Error>SignatureDoesNotMatch<Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message><AWSAccessKeyId>AKIAJ3ZD2ZEISKNQMSGQ</AWSAccessKeyId><StringToSign>AWS4-HMAC-SHA25620171129T123633Z20171129/eu-central-1/s3/aws4_request555016eca303c98732f51adcaaa83eac7368fb75f59eaa9f59116684b9030ee0</StringToSign><SignatureProvided>bf703f56827aa0f04aab3fa6a1e2aa277117344cdbfc3f4f3e51895ce62af826</SignatureProvided><StringToSignBytes>41 57 53 34 2d 48 4d 41 43 2d 53 48 41 32 35 36 0a 32 30 31 37 31 31 32 39 54 31 32 33 36 33 33 5a 0a 32 30 31 37 31 31 32 39 2f 65 75 2d 63 65 6e 74 72 61 6c 2d 31 2f 73 33 2f 61 77 73 34 5f 72 65 71 75 65 73 74 0a 35 35 35 30 31 36 65 63 61 33 30 33 63 39 38 37 33 32 66 35 31... <truncated>
    at org.apache.hadoop.fs.s3.Jets3tFileSystemStore.get(Jets3tFileSystemStore.java:175)
    at org.apache.hadoop.fs.s3.Jets3tFileSystemStore.retrieveINode(Jets3tFileSystemStore.java:221)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:191)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:102)
    at com.sun.proxy.$Proxy23.retrieveINode(Unknown Source)
    at org.apache.hadoop.fs.s3.S3FileSystem.getFileStatus(S3FileSystem.java:340)
    at org.apache.hadoop.fs.FileSystem.exists(FileSystem.java:1426)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$14.apply(DataSource.scala:381)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$14.apply(DataSource.scala:370)
    at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
    at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:241)
    at scala.collection.immutable.List.flatMap(List.scala:344)
    at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:370)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:152)
    at org.apache.spark.sql.DataFrameReader.csv(DataFrameReader.scala:415)
    at org.apache.spark.sql.DataFrameReader.csv(DataFrameReader.scala:352)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sparklyr.Invoke$.invoke(invoke.scala:102)
    at sparklyr.StreamHandler$.handleMethodCall(stream.scala:97)
    at sparklyr.StreamHandler$.read(stream.scala:62)
    at sparklyr.BackendHandler.channelRead0(handler.scala:52)
    at sparklyr.BackendHandler.channelRead0(handler.scala:14)
    at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:367)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:353)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:346)
    at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:102)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:367)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:353)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:346)
    at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:293)
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:267)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:367)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:353)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:346)
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1294)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:367)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:353)
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:911)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:652)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:575)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:489)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:451)
    at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:140)
    at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.jets3t.service.S3ServiceException: Service Error Message. -- ResponseCode: 403, ResponseStatus: Forbidden, XML Error Message: <?xml version="1.0" encoding="UTF-8"?><Error>SignatureDoesNotMatch<Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message><AWSAccessKeyId>AKIAJ3ZD2ZEISKNQMSGQ</AWSAccessKeyId><StringToSign>AWS4-HMAC-SHA25620171129T123633Z20171129/eu-central-1/s3/aws4_request555016eca303
```

答:
You need to set your AWS credentials via

```<code>Sys.setenv(AWS_ACCESS_KEY_ID="[Your access key]")
Sys.setenv(AWS_SECRET_ACCESS_KEY="[Your secret access key]")
</code>```

see ?spark_read_csv

Also config$sparklyr.defaultPackages <- "org.apache.hadoop:hadoop-aws:2.7.3"
 is essential.

Body:
I am encountering an error when I  try to connect to a s3 bucket from R studio using sparklyr. The s3 bucket is in the eu-central-1(Frankfurt) region. Spark version - 2.1.0 , Hadoop 2.7. I am getting a 403 response code with signature mismatch error. However,  when I try to get an s3a bucket instead however I get a 400 response code. Any word on alternative methods to connect to s3 buckets via spark in R studio, is also appreciated. The connection to s3 works fine without Spark.

Here is the code,

   # install.packages("devtools")
# devtools::install_github("rstudio/sparklyr")
library(sparklyr)
library(dplyr)
sc <- spark_connect(master = "local")
spark_disconnect(sc)
config <- spark_config()
library(sparklyr)
library(dplyr)
# config$sparklyr.defaultPackages <- "org.apache.hadoop:hadoop-aws:2.7.3"
# config$spark.executor.memory <- "4g"
sc <- spark_connect(master = "local",config = config)

ctx <- sparklyr::spark_context(sc)
jsc <- invoke_static(
sc,
"org.apache.spark.api.java.JavaSparkContext",
"fromSparkContext",
ctx
)

hconf <- jsc %>% invoke("hadoopConfiguration")
hconf %>% invoke("set","fs.s3.access.key", "xx")
hconf %>% invoke("set","fs.s3.secret.key", "xx")
#hconf %>% invoke("set","com.amazonaws.services.s3.enableV4", "true")
test <- spark_read_csv(sc, "test", "s3://********.csv")

Error: org.apache.hadoop.fs.s3.S3Exception: org.jets3t.service.S3ServiceException: Service Error Message. -- ResponseCode: 403, ResponseStatus: Forbidden, XML Error Message: <?xml version="1.0" encoding="UTF-8"?><Error>SignatureDoesNotMatch<Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message><AWSAccessKeyId>AKIAJ3ZD2ZEISKNQMSGQ</AWSAccessKeyId><StringToSign>AWS4-HMAC-SHA25620171129T123633Z20171129/eu-central-1/s3/aws4_request555016eca303c98732f51adcaaa83eac7368fb75f59eaa9f59116684b9030ee0</StringToSign><SignatureProvided>bf703f56827aa0f04aab3fa6a1e2aa277117344cdbfc3f4f3e51895ce62af826</SignatureProvided><StringToSignBytes>41 57 53 34 2d 48 4d 41 43 2d 53 48 41 32 35 36 0a 32 30 31 37 31 31 32 39 54 31 32 33 36 33 33 5a 0a 32 30 31 37 31 31 32 39 2f 65 75 2d 63 65 6e 74 72 61 6c 2d 31 2f 73 33 2f 61 77 73 34 5f 72 65 71 75 65 73 74 0a 35 35 35 30 31 36 65 63 61 33 30 33 63 39 38 37 33 32 66 35 31... <truncated>
    at org.apache.hadoop.fs.s3.Jets3tFileSystemStore.get(Jets3tFileSystemStore.java:175)
    at org.apache.hadoop.fs.s3.Jets3tFileSystemStore.retrieveINode(Jets3tFileSystemStore.java:221)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:191)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:102)
    at com.sun.proxy.$Proxy23.retrieveINode(Unknown Source)
    at org.apache.hadoop.fs.s3.S3FileSystem.getFileStatus(S3FileSystem.java:340)
    at org.apache.hadoop.fs.FileSystem.exists(FileSystem.java:1426)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$14.apply(DataSource.scala:381)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$14.apply(DataSource.scala:370)
    at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
    at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:241)
    at scala.collection.immutable.List.flatMap(List.scala:344)
    at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:370)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:152)
    at org.apache.spark.sql.DataFrameReader.csv(DataFrameReader.scala:415)
    at org.apache.spark.sql.DataFrameReader.csv(DataFrameReader.scala:352)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at sparklyr.Invoke$.invoke(invoke.scala:102)
    at sparklyr.StreamHandler$.handleMethodCall(stream.scala:97)
    at sparklyr.StreamHandler$.read(stream.scala:62)
    at sparklyr.BackendHandler.channelRead0(handler.scala:52)
    at sparklyr.BackendHandler.channelRead0(handler.scala:14)
    at io.netty.channel.SimpleChannelInboundHandler.channelRead(SimpleChannelInboundHandler.java:105)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:367)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:353)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:346)
    at io.netty.handler.codec.MessageToMessageDecoder.channelRead(MessageToMessageDecoder.java:102)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:367)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:353)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:346)
    at io.netty.handler.codec.ByteToMessageDecoder.fireChannelRead(ByteToMessageDecoder.java:293)
    at io.netty.handler.codec.ByteToMessageDecoder.channelRead(ByteToMessageDecoder.java:267)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:367)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:353)
    at io.netty.channel.AbstractChannelHandlerContext.fireChannelRead(AbstractChannelHandlerContext.java:346)
    at io.netty.channel.DefaultChannelPipeline$HeadContext.channelRead(DefaultChannelPipeline.java:1294)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:367)
    at io.netty.channel.AbstractChannelHandlerContext.invokeChannelRead(AbstractChannelHandlerContext.java:353)
    at io.netty.channel.DefaultChannelPipeline.fireChannelRead(DefaultChannelPipeline.java:911)
    at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:131)
    at io.netty.channel.nio.NioEventLoop.processSelectedKey(NioEventLoop.java:652)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeysOptimized(NioEventLoop.java:575)
    at io.netty.channel.nio.NioEventLoop.processSelectedKeys(NioEventLoop.java:489)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:451)
    at io.netty.util.concurrent.SingleThreadEventExecutor$2.run(SingleThreadEventExecutor.java:140)
    at io.netty.util.concurrent.DefaultThreadFactory$DefaultRunnableDecorator.run(DefaultThreadFactory.java:144)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.jets3t.service.S3ServiceException: Service Error Message. -- ResponseCode: 403, ResponseStatus: Forbidden, XML Error Message: <?xml version="1.0" encoding="UTF-8"?><Error>SignatureDoesNotMatch<Message>The request signature we calculated does not match the signature you provided. Check your key and signing method.</Message><AWSAccessKeyId>AKIAJ3ZD2ZEISKNQMSGQ</AWSAccessKeyId><StringToSign>AWS4-HMAC-SHA25620171129T123633Z20171129/eu-central-1/s3/aws4_request555016eca303

Body:
You need to set your AWS credentials via

Sys.setenv(AWS_ACCESS_KEY_ID="[Your access key]")
Sys.setenv(AWS_SECRET_ACCESS_KEY="[Your secret access key]")

see ?spark_read_csv

Also config$sparklyr.defaultPackages <- "org.apache.hadoop:hadoop-aws:2.7.3"
 is essential.


问:
You are not logged in: You are not logged in. Please log in and try again
I am using HybridAuth library in my codeigniter application. but when i click on login with facebook button it gives error "You are not logged in: You are not logged in. Please log in and try again.". Please help some to know why this error occured.</p>

答: This error is due to wrong 'Valid OAuth redirect Url' in Facebook login product settings. I also gone through this error. Facebook came up with Facebook Login product that links to a facebook app. Please check below correct settings pics i have that i got working -


问:
How to get the location of the DLL currently executing?
I have a config file that I need to load as part of the execution of a dll I am writing.

The problem I am having is that the place I put the dll and config file is not the "current location" when the app is running.

For example, I put the dll and xml file here:

D:\Program Files\Microsoft Team Foundation Server 2010\Application Tier\Web Services\bin\Plugins

But if I try to reference the xml file (in my dll) like this:

```<code>XDocument doc = XDocument.Load(@".\AggregatorItems.xml")
</code>```

then .\AggregatorItems.xml translates to:

C:\windows\system32\inetsrv\AggregatorItems.xml

So, I need to find a way (I hope) of knowing where the dll that is currently executing is located.  Basically I am looking for this:

```<code>XDocument doc = XDocument.Load(CoolDLLClass.CurrentDirectory+@"\AggregatorItems.xml")
</code>```

Body:
I have a config file that I need to load as part of the execution of a dll I am writing.

The problem I am having is that the place I put the dll and config file is not the "current location" when the app is running.

For example, I put the dll and xml file here:

D:\Program Files\Microsoft Team Foundation Server 2010\Application Tier\Web Services\bin\Plugins

But if I try to reference the xml file (in my dll) like this:

XDocument doc = XDocument.Load(@".\AggregatorItems.xml")

then .\AggregatorItems.xml translates to:

C:\windows\system32\inetsrv\AggregatorItems.xml

So, I need to find a way (I hope) of knowing where the dll that is currently executing is located.  Basically I am looking for this:

XDocument doc = XDocument.Load(CoolDLLClass.CurrentDirectory+@"\AggregatorItems.xml")

Body: System.Reflection.Assembly.GetExecutingAssembly().Location


问:
Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table
I am using AutoFilter to sort through a table in VBA, which results in a smaller table of data. I only want to copy/paste the visible cells of one column after the filter is applied. Also, I would like to average the filtered values of one column and put the result in a different cell.

I've found this snippet on Stack which allows me to copy/paste the entire visible results of the filter, but I don't know how to modify it or another way to get only one column's worth of data (without the header) from it.

```<code>Range("A1",Cells(65536,Cells(1,256).End(xlToLeft).Column).End(xlUp)).SpecialCells(xlCellTypeVisible).Copy
Sheets("Sheet2").Range("A1").PasteSpecial xlPasteValuesAndNumberFormats
Application.CutCopyMode = False
</code>```

Addition to answer (to calculate with the filtered values):

```<code>tgt.Range("B2").Value =WorksheetFunction.Average(copyRange.SpecialCells(xlCellTypeVisible))
</code>```

答:
I've found this to work very well. It uses the .range property of the .autofilter object, which seems to be a rather obscure, but very handy, feature:</p>

```<code>Sub copyfiltered()
    ' Copies the visible columns
    ' and the selected rows in an autofilter
    '
    ' Assumes that the filter was previously applied
    '
    Dim wsIn As Worksheet
    Dim wsOut As Worksheet

    Set wsIn = Worksheets("Sheet1")
    Set wsOut = Worksheets("Sheet2")

    ' Hide the columns you don't want to copy
    wsIn.Range("B:B,D:D").EntireColumn.Hidden = True

    'Copy the filtered rows from wsIn and and paste in wsOut
    wsIn.AutoFilter.Range.Copy Destination:=wsOut.Range("A1")
End Sub
</code>```

Body:
I am using AutoFilter to sort through a table in VBA, which results in a smaller table of data. I only want to copy/paste the visible cells of one column after the filter is applied. Also, I would like to average the filtered values of one column and put the result in a different cell.

I've found this snippet on Stack which allows me to copy/paste the entire visible results of the filter, but I don't know how to modify it or another way to get only one column's worth of data (without the header) from it.

Range("A1",Cells(65536,Cells(1,256).End(xlToLeft).Column).End(xlUp)).SpecialCells(xlCellTypeVisible).Copy
Sheets("Sheet2").Range("A1").PasteSpecial xlPasteValuesAndNumberFormats
Application.CutCopyMode = False

Addition to answer (to calculate with the filtered values):

tgt.Range("B2").Value =WorksheetFunction.Average(copyRange.SpecialCells(xlCellTypeVisible))

Body:
I've found this to work very well. It uses the .range property of the .autofilter object, which seems to be a rather obscure, but very handy, feature:

Sub copyfiltered()
    ' Copies the visible columns
    ' and the selected rows in an autofilter
    '
    ' Assumes that the filter was previously applied
    '
    Dim wsIn As Worksheet
    Dim wsOut As Worksheet

    Set wsIn = Worksheets("Sheet1")
    Set wsOut = Worksheets("Sheet2")

    ' Hide the columns you don't want to copy
    wsIn.Range("B:B,D:D").EntireColumn.Hidden = True

    'Copy the filtered rows from wsIn and and paste in wsOut
    wsIn.AutoFilter.Range.Copy Destination:=wsOut.Range("A1")
End Sub


答:
You can do this

```<code>string = "some ' string"
final = string.replace('\'','')
print(final)
</code>```

output

```<code>some  string
</code>```

Title: How to replace a ' from a String in python

Body:
I am trying to remove a " ' " character from a python string .
Below code gives a syntax error, How to achieve this task

final = string.replace(old_str, '\'', '')

Body:
You can do this

string = "some ' string"
final = string.replace('\'','')
print(final)

output

some  string


问:
Select wav files from a folder whose partial names are in a text file
I have 500 wave files in a folder ABC which are named  like

```<code>F1001
F1002
F1003
...
F1100
F2001
F2002
...
F2100
M3001
M3002
...
M3100
M4001
M4002
...
M4100
</code>```

all with extension .wav.

Also I have a text file which contains 3 digit numbers like

001

003

098

034 .... (200 in total).

I want to select wave files from the folder ABC whose names end with these 3 digits.

Expecting MATLAB or bash script solutions.

I read this:
Copy or move files to another directory based on partial names in a text file. But I don't know how to use it for me.

答:
for Matlab

1) Get all the file names in the folder using functions dir or rdir.

2) Using for loop go through every filename and add the last 3 digits of every filename to an array (array A). You will need str2num() here

3) Parse all 3 digit numbers to an array (array B)

4) Using function ismember(B, A) find which elements of B are contained in A

5) Load corresponding filenames

Body:
I have 500 wave files in a folder ABC which are named  like

F1001
F1002
F1003
...
F1100
F2001
F2002
...
F2100
M3001
M3002
...
M3100
M4001
M4002
...
M4100

all with extension .wav.

Also I have a text file which contains 3 digit numbers like

001

003

098

034 .... (200 in total).

I want to select wave files from the folder ABC whose names end with these 3 digits.

Expecting MATLAB or bash script solutions.

I read this:
Copy or move files to another directory based on partial names in a text file. But I don't know how to use it for me.


问:
Insert a page break if the height of a div does not fit in print media?
I am dynamically creating elements on a web page which I want to print. I want a page break if the element can't fit in the rest of the A4 size paper.
Example is this question: Force an element to take exactly half of available height in print media

In the picture, A broken element is appearing on first page, which should actually go on the second page.

How can I force a page break if the element does not fit in this page.
**What I tried: **

I tried to use css page-breakafter` property, with the following code:

```<code>$(document).ready(function(){

  $(".row").each(function(){

    if($(this).height()>$(document).height()/2){
      $(this).after('<div style="page-break-after:always"></div>');
    }
  });

});
</code>```

But it does not work.

Here is a JsFiddle

答:
Previous answer was good but there is a bug. You must need total_height. Please Check this I think this code help you. I use this code for a hospital management project for printing system. Thank you.</p>

```<code>jQuery(document).ready(function(){
        var prevRowHeight = 0;
        var total_height = 0;
        jQuery(".row").each(function(){

            // console.log($(this).height());
            var maxHeight = 1000;
            var eachRowHeight = jQuery(this).height();
            total_height += prevRowHeight + eachRowHeight;
            alert('now : '+total_height +' , Was: '+ prevRowHeight);
            if(total_height > maxHeight){
                jQuery(this).before('<div style="page-break-after:always"></div>');
                console.log("add page break before");
                now_height = 0;
            }
            prevRowHeight = jQuery(this).height();
        });

    });
</code>```

Body:
I am dynamically creating elements on a web page which I want to print. I want a page break if the element can't fit in the rest of the A4 size paper.
Example is this question: Force an element to take exactly half of available height in print media

In the picture, A broken element is appearing on first page, which should actually go on the second page.

How can I force a page break if the element does not fit in this page.
**What I tried: **

I tried to use css page-breakafter` property, with the following code:

$(document).ready(function(){

  $(".row").each(function(){

    if($(this).height()>$(document).height()/2){
      $(this).after('

');
    }
  });

});

But it does not work.

Here is a JsFiddle

Body:
Previous answer was good but there is a bug. You must need total_height. Please Check this I think this code help you. I use this code for a hospital management project for printing system. Thank you.

jQuery(document).ready(function(){
        var prevRowHeight = 0;
        var total_height = 0;
        jQuery(".row").each(function(){

            // console.log($(this).height());
            var maxHeight = 1000;
            var eachRowHeight = jQuery(this).height();
            total_height += prevRowHeight + eachRowHeight;
            alert('now : '+total_height +' , Was: '+ prevRowHeight);
            if(total_height > maxHeight){
                jQuery(this).before('<div style="page-break-after:always"></div>');
                console.log("add page break before");
                now_height = 0;
            }
            prevRowHeight = jQuery(this).height();
        });

    });