问:
makeObjectsPerformSelector:
I want to make all objects in an array perform a selector. I've discovered the appropriately named makeObjectsPerformSelector: method, but I have a question with it. If I use it on an array, will it change the existing array or return a new one? If it modifies the existing object, what be the easiest way to return a new array with the selector applied?

答:
makeObjectsPerformSelector: is going to run that selector against every object in the array. If those objects are modified by the selector they will be modified. It does not return anything. Now, there is a catch, which that by default most copies in Cocoa are shallow copies, which means you get a new array, but the underlying objects it points to are the same objects. You will need to use initWithArray:copyItems to make it copy the root level items as well. If you want a new array containing the altered objects as well as the old array do something like this:</p>

```<code>NSArray *newArray = [[NSArray alloc] initWithArray:oldArray copyItems:YES];
[newArray makeObjectsPerformSelector:@selector(doSomethingToObject)];
</code>```

OwnerDisplayName: Allyn

Title: makeObjectsPerformSelector:

Body:
makeObjectsPerformSelector: is going to run that selector against every object in the array. If those objects are modified by the selector they will be modified. It does not return anything. Now, there is a catch, which that by default most copies in Cocoa are shallow copies, which means you get a new array, but the underlying objects it points to are the same objects. You will need to use initWithArray:copyItems to make it copy the root level items as well. If you want a new array containing the altered objects as well as the old array do something like this:

NSArray *newArray = [[NSArray alloc] initWithArray:oldArray copyItems:YES];
[newArray makeObjectsPerformSelector:@selector(doSomethingToObject)];

OwnerDisplayName: Louis Gerbarg


来源: stackexchange

问:
How to get the caller method information from Around advise
ThisJoinPoint can only get the current method information, anyway to get the caller method information?</p>

答:
You can try the special variable thisEnclosingJoinPointStaticPart which holds the static part of the enclosing JoinPoint.

Mentioned here (example) and here (docs)

Or if using annotation-based AspectJ, pass following to the advice method's parameters, e.g.:

```<code>@Before("call( /* your pointcut definition */ )")
public void myCall(JoinPoint.EnclosingStaticPart thisEnclosingJoinPointStaticPart)
{
     // ...
}
</code>```

Mentioned here

ContentLicense: CC BY-SA 3.0

Body:
You can try the special variable thisEnclosingJoinPointStaticPart which holds the static part of the enclosing JoinPoint.

Mentioned here (example) and here (docs)

Or if using annotation-based AspectJ, pass following to the advice method's parameters, e.g.:

@Before("call( /* your pointcut definition */ )")
public void myCall(JoinPoint.EnclosingStaticPart thisEnclosingJoinPointStaticPart)
{
     // ...
}

Mentioned here


问:
Javascript fullscreen toggle resets user viewport position
I've got a fullscreen toggle button for a web application I'm working on, but when I toggle fullscreen on and then back off again, it resets the user's position on the page.

It's pretty jarring, as resetting the viewport position to the top of the web-page cuts off the user's access to the application about halfway, requiring them to scroll back down.

How can I modify my fullscreen toggle button to maintain a user's position on the page through fullscreen toggles?

const application = document.querySelector(".application");

function toggleFullscreen(elem) {
  elem = elem || document.documentElement;
  if (!document.fullscreenElement && !document.mozFullScreenElement &&
    !document.webkitFullscreenElement && !document.msFullscreenElement) {
    if (elem.requestFullscreen) {
      elem.requestFullscreen();
    } else if (elem.msRequestFullscreen) {
      elem.msRequestFullscreen();
    } else if (elem.mozRequestFullScreen) {
      elem.mozRequestFullScreen();
    } else if (elem.webkitRequestFullscreen) {
      elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    }
  }
};

document.getElementById("fullscreenbtn").addEventListener("click", function() {
  toggleFullscreen(application);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>html,
body {
  padding: 0 !important;
  margin: 0 !important;
  background: #2d2a2a;
}

#header {
  width: 100vw;
  height: 10vh;
  background: #000;
}

#spacer {
  width: 1px;
  height: 40vh;
}

#application {
  width: 100vw;
  height: 95vh;
}</code>```

<button id="fullscreenbtn">fullscreen</button>

```

As you (hopefully) can see, the fullscreen toggle resets the viewport to the top of the page when not in fullscreen mode. I'd rather it didn't do that.

答:
Remember the window.pageYOffset position when user toggles between full-screen view and regular view. Add fullscreenchange event listener to the global document. Most importantly - test it in different browsers since they all use different event names (like mozfullscreenchange). Add those listeners as per your supported browser list.

Here is modified code for Chrome to track and return to previous position between full screen toggle.

```<code>    const application = document.querySelector(".application");

    let screenOffset;
    document.addEventListener("fullscreenchange", (event) => {
        window.scrollTo(0, screenOffset);
    });

    document.onfullscreenchange = function ( event ) {
        window.scrollTo(0, screenOffset);
    };

    function toggleFullscreen(elem) {
      elem = elem || document.documentElement;
      screenOffset = window.pageYOffset;
      if (!document.fullscreenElement && !document.mozFullScreenElement &&
        !document.webkitFullscreenElement && !document.msFullscreenElement) {
        if (elem.requestFullscreen) {
          elem.requestFullscreen();
        } else if (elem.msRequestFullscreen) {
          elem.msRequestFullscreen();
        } else if (elem.mozRequestFullScreen) {
          elem.mozRequestFullScreen();
        } else if (elem.webkitRequestFullscreen) {
          elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen();
        }
      }
    };

    document.getElementById("fullscreenbtn").addEventListener("click", function() {
      toggleFullscreen(application);
    });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've got a fullscreen toggle button for a web application I'm working on, but when I toggle fullscreen on and then back off again, it resets the user's position on the page.

It's pretty jarring, as resetting the viewport position to the top of the web-page cuts off the user's access to the application about halfway, requiring them to scroll back down.

How can I modify my fullscreen toggle button to maintain a user's position on the page through fullscreen toggles?

const application = document.querySelector(".application");

function toggleFullscreen(elem) {
  elem = elem || document.documentElement;
  if (!document.fullscreenElement && !document.mozFullScreenElement &&
    !document.webkitFullscreenElement && !document.msFullscreenElement) {
    if (elem.requestFullscreen) {
      elem.requestFullscreen();
    } else if (elem.msRequestFullscreen) {
      elem.msRequestFullscreen();
    } else if (elem.mozRequestFullScreen) {
      elem.mozRequestFullScreen();
    } else if (elem.webkitRequestFullscreen) {
      elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    }
  }
};

document.getElementById("fullscreenbtn").addEventListener("click", function() {
  toggleFullscreen(application);
});

html,
body {
  padding: 0 !important;
  margin: 0 !important;
  background: #2d2a2a;
}

#header {
  width: 100vw;
  height: 10vh;
  background: #000;
}

#spacer {
  width: 1px;
  height: 40vh;
}

#application {
  width: 100vw;
  height: 95vh;
}

<button id="fullscreenbtn">fullscreen</button>

As you (hopefully) can see, the fullscreen toggle resets the viewport to the top of the page when not in fullscreen mode. I'd rather it didn't do that.

Body:
Remember the window.pageYOffset position when user toggles between full-screen view and regular view. Add fullscreenchange event listener to the global document. Most importantly - test it in different browsers since they all use different event names (like mozfullscreenchange). Add those listeners as per your supported browser list.

Here is modified code for Chrome to track and return to previous position between full screen toggle.

    const application = document.querySelector(".application");

    let screenOffset;
    document.addEventListener("fullscreenchange", (event) => {
        window.scrollTo(0, screenOffset);
    });

    document.onfullscreenchange = function ( event ) {
        window.scrollTo(0, screenOffset);
    };

    function toggleFullscreen(elem) {
      elem = elem || document.documentElement;
      screenOffset = window.pageYOffset;
      if (!document.fullscreenElement && !document.mozFullScreenElement &&
        !document.webkitFullscreenElement && !document.msFullscreenElement) {
        if (elem.requestFullscreen) {
          elem.requestFullscreen();
        } else if (elem.msRequestFullscreen) {
          elem.msRequestFullscreen();
        } else if (elem.mozRequestFullScreen) {
          elem.mozRequestFullScreen();
        } else if (elem.webkitRequestFullscreen) {
          elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
        }
      } else {
        if (document.exitFullscreen) {
          document.exitFullscreen();
        } else if (document.msExitFullscreen) {
          document.msExitFullscreen();
        } else if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen();
        } else if (document.webkitExitFullscreen) {
          document.webkitExitFullscreen();
        }
      }
    };

    document.getElementById("fullscreenbtn").addEventListener("click", function() {
      toggleFullscreen(application);
    });


问:
docker can't connect to mariadb from localhost with different user
Hi I have followed this docker tutorial for mariabdb and also checked this stackoverflow question as well. I can start to mariadb container without any issues and can connect with root and mypass password with command mysql -h0.0.0.0 -uroot -pmypass. However, after I create a new user and grant all on it, I am not able to connect with that specific username and password. I am getting access denied error.

Here is the docker ps command output;

```<code>CONTAINER ID        IMAGE                 COMMAND                  CREATED             STATUS              PORTS                    NAMES
268c36eac13a        mariadb/server:10.3   "docker-entrypoint.s…"   31 minutes ago      Up 31 minutes       0.0.0.0:3306->3306/tcp   mariadbtest
</code>```

I connect to mariadb container with docker exec -it 268c36eac13a /bin/sh and run these commands;

```<code>mysql -uroot -pmypass
create database emails;
grant all on emails.* to 'testUser'@'localhost' identified by '123456';
</code>```

Then, from localhost when I am run mysql -h0.0.0.0 -utestUser -123456 I am getting Access denied for user 'testUser'@'172.17.0.1' (using password: YES) error.

Thanks for help!

答:
I think this is a problem with networking : you allow user testUser to connect to your database from localhost but this means he will be able to connect only from client running inside the container. As you can see when you are logging to your MariaDB container from host machine you get your host docker address 172.17.0.1.

One solution is to allow your user to connect from any ip :

```<code>grant all on emails.* to 'testUser'@'%' identified by '123456';
</code>```

or IP from given subnet. You can check how to do it in CREATE USER docs.

Another solution would be to add user for IP of host machine. You can get the host IP from within the container and add user for this IP. On how to get host IP from the container check this question.

Body:
Hi I have followed this docker tutorial for mariabdb and also checked this stackoverflow question as well. I can start to mariadb container without any issues and can connect with root and mypass password with command mysql -h0.0.0.0 -uroot -pmypass. However, after I create a new user and grant all on it, I am not able to connect with that specific username and password. I am getting access denied error.

Here is the docker ps command output;

CONTAINER ID        IMAGE                 COMMAND                  CREATED             STATUS              PORTS                    NAMES
268c36eac13a        mariadb/server:10.3   "docker-entrypoint.s…"   31 minutes ago      Up 31 minutes       0.0.0.0:3306->3306/tcp   mariadbtest

I connect to mariadb container with docker exec -it 268c36eac13a /bin/sh and run these commands;

mysql -uroot -pmypass
create database emails;
grant all on emails.* to 'testUser'@'localhost' identified by '123456';

Then, from localhost when I am run mysql -h0.0.0.0 -utestUser -123456 I am getting Access denied for user 'testUser'@'172.17.0.1' (using password: YES) error.

Thanks for help!

Body:
I think this is a problem with networking : you allow user testUser to connect to your database from localhost but this means he will be able to connect only from client running inside the container. As you can see when you are logging to your MariaDB container from host machine you get your host docker address 172.17.0.1.

One solution is to allow your user to connect from any ip :

grant all on emails.* to 'testUser'@'%' identified by '123456';

or IP from given subnet. You can check how to do it in CREATE USER docs.

Another solution would be to add user for IP of host machine. You can get the host IP from within the container and add user for this IP. On how to get host IP from the container check this question.


问:
Selecting cases based on values in previous cases
I've got the following list in SPSS:

```<code>Subjekt    Reactiontime       correct/incorrect
1          x                  1
1          x                  0
1          x                  1
1          x                  0
</code>```

I now want to select all rows/cases that follow AFTER "0" (in the column correct/incorrect) because I want to compute the mean of all reactiontimes that come after "0".

How can I do that in SPSS?

答:
Here's a shorter approach (though less generic than @user45392's full process):

```<code>if lag(correct)=0 ReactiontimeAfter0=Reactiontime.
</code>```

now you can just run means ReactiontimeAfter0.

Body:
I've got the following list in SPSS:

Subjekt    Reactiontime       correct/incorrect
1          x                  1
1          x                  0
1          x                  1
1          x                  0

I now want to select all rows/cases that follow AFTER "0" (in the column correct/incorrect) because I want to compute the mean of all reactiontimes that come after "0".

How can I do that in SPSS?

Body:
Here's a shorter approach (though less generic than @user45392's full process):

if lag(correct)=0 ReactiontimeAfter0=Reactiontime.

now you can just run means ReactiontimeAfter0.


问:
Transfer a Response object to another process
I am trying to pass an Express' Response object from child process A to child process B.

In a.js, I am doing the following process.send(process.pid, res.socket);

In b.js, I can get the response socket by using the following

```<code>process.on('message', (msg, handle) => {
    var output = { msg: msg, socket: handle };
    console.log(output);
    handle.on('end', () => console.log('disconnected'));
    handle.write('hello there client!');
}
</code>```

When I print the contents of output, I do get the msg: 4355 and socket is connected and contains the IP address and port of the connected client. But when I use the socket to write hello there client!, the client did not receive the response, and the server prints out disconnected. Please help?

My client is Postman.

答: Turns out socket is a TCP connection, so I just have to write HTTP response for my client to receive the message. It works now! :D

Body:
I am trying to pass an Express' Response object from child process A to child process B.

In a.js, I am doing the following process.send(process.pid, res.socket);

In b.js, I can get the response socket by using the following

process.on('message', (msg, handle) => {
    var output = { msg: msg, socket: handle };
    console.log(output);
    handle.on('end', () => console.log('disconnected'));
    handle.write('hello there client!');
}

When I print the contents of output, I do get the msg: 4355 and socket is connected and contains the IP address and port of the connected client. But when I use the socket to write hello there client!, the client did not receive the response, and the server prints out disconnected. Please help?

My client is Postman.


问:
How to avoid a thread being completed in C#?
I have a RabbitMQ client program written in C#. While the application works in console based application (because execution is blocked by Console.ReadLine) it does not work in Windows Form based application. In Windows Form application, execution doesn't wait on Console.ReadLine and terminates on completion. I am looking for solution where my listener keeps monitoring for new messages from server without being terminated.
Here is the the client code :</p>

```<code>    try {
            var factory = new ConnectionFactory() { HostName = "xxx" , UserName ="xxx", Password="xxx"};
            using(var connection = factory.CreateConnection())
            using(var channel = connection.CreateModel())
            {
                channel.ExchangeDeclare(exchange: "call_notify", type: "fanout");

                var queueName = channel.QueueDeclare().QueueName;
                channel.QueueBind(queue: queueName,
                                  exchange: "call_notify",
                                  routingKey: "");

                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (model, ea) =>
                {
                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);
                    Console.WriteLine(message);
                };
                channel.BasicConsume(queue: queueName,
                                     autoAck: true,
                                     consumer: consumer);

                Console.WriteLine(" Press [enter] to exit.");
                Console.ReadLine();  // Program does'nt wait here in windows form based application
            }
        }
</code>```

答:
Don't use using since that will dispose of everything immediately

Store the needed objects (connection? channel? consumer?) in class fields rather than local variables

No need for threads since the objects handle things asynchronously. Just create the objects and that's it

Close/dispose of the objects when the application terminates or you need to stop listening

This way they'll live until the application terminates.

Body:
I have a RabbitMQ client program written in C#. While the application works in console based application (because execution is blocked by Console.ReadLine) it does not work in Windows Form based application. In Windows Form application, execution doesn't wait on Console.ReadLine and terminates on completion. I am looking for solution where my listener keeps monitoring for new messages from server without being terminated.
Here is the the client code :

    try {
            var factory = new ConnectionFactory() { HostName = "xxx" , UserName ="xxx", Password="xxx"};
            using(var connection = factory.CreateConnection())
            using(var channel = connection.CreateModel())
            {
                channel.ExchangeDeclare(exchange: "call_notify", type: "fanout");

                var queueName = channel.QueueDeclare().QueueName;
                channel.QueueBind(queue: queueName,
                                  exchange: "call_notify",
                                  routingKey: "");

                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (model, ea) =>
                {
                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);
                    Console.WriteLine(message);
                };
                channel.BasicConsume(queue: queueName,
                                     autoAck: true,
                                     consumer: consumer);

                Console.WriteLine(" Press [enter] to exit.");
                Console.ReadLine();  // Program does'nt wait here in windows form based application
            }
        }


问:
How to remove previous stack of UIView after adding a new one?
I want to add a new subview every time I swipe right, but then it will stack many times if I do not destroy the previous subview. I know how to remove it, but I am struggling with the logic of how to remove it only after I add a new one.

I have tried this:

```<code>    var view1: UIView?
    var view2: UIView?
    var ctrl = false

    override func viewDidLoad() {
        super.viewDidLoad()

        view1?.addSubview(CustomView(frame: self.view.bounds))
    }

    func addView(){
        if let test1 = view1, let test2 = view2 {
            if ctrl == true {
                test1.addSubview(CustomView(frame: self.view.bounds))
                test2.removeFromSuperview()
                ctrl = false
            }else{
                test2.addSubview(CustomView(frame: self.view.bounds))
                test1.removeFromSuperview()
                ctrl = true
            }
        }
    }

    @IBAction func swipeRight(_ sender: Any) {
        print("Right")
        UIView.animate(withDuration: 1, animations: {
            self.view.layer.backgroundColor = .black
        }){(isFinished) in
            self.addView()
            //I am hoping that after this the view stack before will be removed
        }
    }
</code>```

the Class CustomView is this:

```<code>var primaryColors: [UIColor] = [
    .red,
    .yellow,
    .blue]

class CustomView: UIView {

    override func draw(_ rect: CGRect) {
        super.draw(rect)
        primaryColors.shuffle()

        let leftRect = CGRect(x: 0, y: 0, width: rect.size.width/2, height: rect.size.height)
        primaryColors[0].set()
        guard let leftContext = UIGraphicsGetCurrentContext() else { return }
        leftContext.fill(leftRect)

        let rightRect = CGRect(x: rect.size.width/2, y: 0, width: rect.size.width/2, height: rect.size.height)
        primaryColors[1].set()
        guard let rightContext = UIGraphicsGetCurrentContext() else { return }
        rightContext.fill(rightRect)
    }
}
</code>```

答:
It might not working. In your if condition of addSubview method you are using:
if let test1 = view1, let test2 = view2 which check that both view1 and view2 are not nil.
This must be failing because you only initialized view1 in viewDidLoad():
view1?.addSubview(CustomView(frame: self.view.bounds)). So in above if condition view2 must be nil and hence it will evaluate to false.

Try placing your if condition like this:
if let test1 = view1 || let test2 = view2 (check for syntax if it gives error, ll will give error in if condition with let). And let me know if it doesn't work. Try below code:

```<code>if((self.view1 != nil) || (self.view2 != nil){
    if ctrl == true {
        self.view1?.addSubview(CustomView(frame: self.view.bounds))
        self.view2?.removeFromSuperview()
        ctrl = false
    }else{
        self.view2?.addSubview(CustomView(frame: self.view.bounds))
        self.view1?.removeFromSuperview()
        ctrl = true
    }
 }
</code>```

Body:
I want to add a new subview every time I swipe right, but then it will stack many times if I do not destroy the previous subview. I know how to remove it, but I am struggling with the logic of how to remove it only after I add a new one.

I have tried this:

    var view1: UIView?
    var view2: UIView?
    var ctrl = false

    override func viewDidLoad() {
        super.viewDidLoad()

        view1?.addSubview(CustomView(frame: self.view.bounds))
    }

    func addView(){
        if let test1 = view1, let test2 = view2 {
            if ctrl == true {
                test1.addSubview(CustomView(frame: self.view.bounds))
                test2.removeFromSuperview()
                ctrl = false
            }else{
                test2.addSubview(CustomView(frame: self.view.bounds))
                test1.removeFromSuperview()
                ctrl = true
            }
        }
    }

    @IBAction func swipeRight(_ sender: Any) {
        print("Right")
        UIView.animate(withDuration: 1, animations: {
            self.view.layer.backgroundColor = .black
        }){(isFinished) in
            self.addView()
            //I am hoping that after this the view stack before will be removed
        }
    }

the Class CustomView is this:

var primaryColors: [UIColor] = [
    .red,
    .yellow,
    .blue]

class CustomView: UIView {

    override func draw(_ rect: CGRect) {
        super.draw(rect)
        primaryColors.shuffle()

        let leftRect = CGRect(x: 0, y: 0, width: rect.size.width/2, height: rect.size.height)
        primaryColors[0].set()
        guard let leftContext = UIGraphicsGetCurrentContext() else { return }
        leftContext.fill(leftRect)

        let rightRect = CGRect(x: rect.size.width/2, y: 0, width: rect.size.width/2, height: rect.size.height)
        primaryColors[1].set()
        guard let rightContext = UIGraphicsGetCurrentContext() else { return }
        rightContext.fill(rightRect)
    }
}

Body:
It might not working. In your if condition of addSubview method you are using:
if let test1 = view1, let test2 = view2 which check that both view1 and view2 are not nil.
This must be failing because you only initialized view1 in viewDidLoad():
view1?.addSubview(CustomView(frame: self.view.bounds)). So in above if condition view2 must be nil and hence it will evaluate to false.

Try placing your if condition like this:
if let test1 = view1 || let test2 = view2 (check for syntax if it gives error, ll will give error in if condition with let). And let me know if it doesn't work. Try below code:

if((self.view1 != nil) || (self.view2 != nil){
    if ctrl == true {
        self.view1?.addSubview(CustomView(frame: self.view.bounds))
        self.view2?.removeFromSuperview()
        ctrl = false
    }else{
        self.view2?.addSubview(CustomView(frame: self.view.bounds))
        self.view1?.removeFromSuperview()
        ctrl = true
    }
 }


问:
How do I remove values that are under a specified length of characters from a dictionary?
In this code, I am trying to remove values (synonyms) within a list that are 7 or fewer characters from the dictionary. For some reason, my code is only partially removing the values that are 7 or fewer characters. Also, please do not remove any of the functions or use imports and sets to solve and keep the current code as intact as possible.

My current output:

```<code>{'show': ['exhibit', 'note', 'point to', 'indicate', 'reveal', 'demonstrate'], 'slow': ['unhurried', 'leisurely', 'behind', 'slack'],
'dangerous': ['perilous', 'hazardous', 'uncertain']}

</code>```

Desired output:

```<code>{'show' : ['demonstrate', 'indicate', 'point to'],
'slow' : ['leisurely', 'unhurried'],
'dangerous' : ['hazardous', 'perilous', 'uncertain']}
</code>```

```<code>word_dict = {'show': ['display', 'exhibit', 'convey', 'communicate', 'manifest', 'disclose'],
             'slow': ['unhurried', 'gradual', 'leisurely', 'late', 'behind', 'tedious', 'slack'],
             'dangerous': ['perilous', 'hazardous', 'uncertain']}

def main():
    edited_synonyms = remove_word(word_dict)
    print(edited_synonyms)

def remove_word(word_dict):
    for key, value in word_dict.items():
        for item in value:
            if len(item) <= 7:
                value.remove(item)
    return word_dict

main()
</code>```

答:
You are modifying the same list you are iterating on when you do for item in value:.

Instead you need to iterate on  value[:] which returns a copy of the array

```<code>word_dict = {'show': ['exhibit', 'note', 'point to', 'indicate', 'reveal', 'demonstrate'], 'slow': ['unhurried', 'leisurely', 'behind', 'slack'],
'dangerous': ['perilous', 'hazardous', 'uncertain']}

def main():
    edited_synonyms = remove_word(word_dict)
    print(edited_synonyms)

def remove_word(word_dict):
    for key, value in word_dict.items():
        #Iterate on copy of value
        for item in value[:]:
            if len(item) <= 7:
                value.remove(item)
    return word_dict

main()

</code>```

The output will be

```<code>{
'show': ['point to', 'indicate', 'demonstrate'],
'slow': ['unhurried', 'leisurely'],
 'dangerous': ['perilous', 'hazardous', 'uncertain']
}
</code>```

Another option is to create a new list, add words with len>7 to the list and assign the list to the key of the dictionary

```<code> word_dict = {'show': ['exhibit', 'note', 'point to', 'indicate', 'reveal', 'demonstrate'], 'slow': ['unhurried', 'leisurely', 'behind', 'slack'],
'dangerous': ['perilous', 'hazardous', 'uncertain']}

def main():
    edited_synonyms = remove_word(word_dict)
    print(edited_synonyms)

def remove_word(word_dict):
    for key, value in word_dict.items():

        #List of holding words with len more that 7
        li = []
        for item in value:
            #Add words with len more than 7 to the list
            if len(item) > 7:
                li.append(item)
        #Assign the list to the key
        word_dict[key] = li
    return word_dict

main()
</code>```

Body:
In this code, I am trying to remove values (synonyms) within a list that are 7 or fewer characters from the dictionary. For some reason, my code is only partially removing the values that are 7 or fewer characters. Also, please do not remove any of the functions or use imports and sets to solve and keep the current code as intact as possible.

My current output:

{'show': ['exhibit', 'note', 'point to', 'indicate', 'reveal', 'demonstrate'], 'slow': ['unhurried', 'leisurely', 'behind', 'slack'],
'dangerous': ['perilous', 'hazardous', 'uncertain']}

Desired output:

{'show' : ['demonstrate', 'indicate', 'point to'],
'slow' : ['leisurely', 'unhurried'],
'dangerous' : ['hazardous', 'perilous', 'uncertain']}

word_dict = {'show': ['display', 'exhibit', 'convey', 'communicate', 'manifest', 'disclose'],
             'slow': ['unhurried', 'gradual', 'leisurely', 'late', 'behind', 'tedious', 'slack'],
             'dangerous': ['perilous', 'hazardous', 'uncertain']}

def main():
    edited_synonyms = remove_word(word_dict)
    print(edited_synonyms)

def remove_word(word_dict):
    for key, value in word_dict.items():
        for item in value:
            if len(item) <= 7:
                value.remove(item)
    return word_dict

main()

Body:
You are modifying the same list you are iterating on when you do for item in value:.

Instead you need to iterate on  value[:] which returns a copy of the array

word_dict = {'show': ['exhibit', 'note', 'point to', 'indicate', 'reveal', 'demonstrate'], 'slow': ['unhurried', 'leisurely', 'behind', 'slack'],
'dangerous': ['perilous', 'hazardous', 'uncertain']}

def main():
    edited_synonyms = remove_word(word_dict)
    print(edited_synonyms)

def remove_word(word_dict):
    for key, value in word_dict.items():
        #Iterate on copy of value
        for item in value[:]:
            if len(item) <= 7:
                value.remove(item)
    return word_dict

main()

The output will be

{
'show': ['point to', 'indicate', 'demonstrate'],
'slow': ['unhurried', 'leisurely'],
 'dangerous': ['perilous', 'hazardous', 'uncertain']
}

Another option is to create a new list, add words with len>7 to the list and assign the list to the key of the dictionary

 word_dict = {'show': ['exhibit', 'note', 'point to', 'indicate', 'reveal', 'demonstrate'], 'slow': ['unhurried', 'leisurely', 'behind', 'slack'],
'dangerous': ['perilous', 'hazardous', 'uncertain']}

def main():
    edited_synonyms = remove_word(word_dict)
    print(edited_synonyms)

def remove_word(word_dict):
    for key, value in word_dict.items():

        #List of holding words with len more that 7
        li = []
        for item in value:
            #Add words with len more than 7 to the list
            if len(item) > 7:
                li.append(item)
        #Assign the list to the key
        word_dict[key] = li
    return word_dict

main()


问:
How to restrict merge from specific branches
I would like only specific branches merge to specific branches.

Some example: I want to do master branch accept pull requests only from test branch, and test branch accept only from development branch.

How can I do this restriction on TFS/Git?

We have some policies about reviewers and build validation.

答:
If you have branch policies you can do a workaround to achieve the goal:

In the build definition (that you specified in the build validation) add a PowerShell task that check the source branch of the pull request. When the source branch is not what you want the build will fail.

For example, in the following script, if the source branch is not test the build will fail, so add it in the master branch build validation:

```<code>$sourceBranch = "$(System.PullRequest.SourceBranch)"

if($sourceBranch -ne "test")
{
    exit 1
}
</code>```

Body:
If you have branch policies you can do a workaround to achieve the goal:

In the build definition (that you specified in the build validation) add a PowerShell task that check the source branch of the pull request. When the source branch is not what you want the build will fail.

For example, in the following script, if the source branch is not test the build will fail, so add it in the master branch build validation:

$sourceBranch = "$(System.PullRequest.SourceBranch)"

if($sourceBranch -ne "test")
{
    exit 1
}


问:
firebase get only required data javascript
I'm using get() to read data into my react native app, using the following..

```<code>    firebase
  .firestore()
  .collection("users")
  .doc("test")
  .get()
  .then(response => {
    console.log(response);
  });
</code>```

I only want the test document, but what I'm getting is a 17000 line json doc, it does contain the data I need but the doc I'm after only has one field!

答:
Try this code:

```<code>var leadsRef = database.ref('users');
leadsRef.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
      var childData = childSnapshot.val();
    });
});
</code>```

Now childSnapshot will contain the required data, the same thing can also be accessed using child_added:

```<code>leadsRef.on('child_added', function(snapshot) {
      //Do something with the data
});
</code>```

Just use the forEach

Body:
I'm using get() to read data into my react native app, using the following..

    firebase
  .firestore()
  .collection("users")
  .doc("test")
  .get()
  .then(response => {
    console.log(response);
  });

I only want the test document, but what I'm getting is a 17000 line json doc, it does contain the data I need but the doc I'm after only has one field!

Body:
Try this code:

var leadsRef = database.ref('users');
leadsRef.on('value', function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
      var childData = childSnapshot.val();
    });
});

Now childSnapshot will contain the required data, the same thing can also be accessed using child_added:

leadsRef.on('child_added', function(snapshot) {
      //Do something with the data
});

Just use the forEach


问:
Is it possible to extend a default method implementation of a trait in a struct?
In traditional object-oriented languages (e.g. Java), it is possible to "extend" the functionality of a method in an inherited class by calling the original method from the super class in the overridden version, for example:

class A {
    public void method() {
        System.out.println("I am doing some serious stuff!");
    }
}

class B extends A {
    @Override
    public void method() {
        super.method(); // here we call the original version
        System.out.println("And I'm doing something more!");
    }
}
```

<p>As you can see, in Java, I am able to call the original version from the super class using the <code>super</code> keyword. I was able to get the equivalent behavior for inherited traits, but not when implementing traits for structs.</p>

```trait Foo {
    fn method(&self) {
        println!("default implementation");
    }
}

trait Boo: Foo {
    fn method(&self) {
        // this is overriding the default implementation
        Foo::method(self);  // here, we successfully call the original
                            // this is tested to work properly
        println!("I am doing something more.");
    }
}

struct Bar;

impl Foo for Bar {
    fn method(&self) {
        // this is overriding the default implementation as well
        Foo::method(self);  // this apparently calls this overridden
                            // version, because it overflows the stack
        println!("Hey, I'm doing something entirely different!");
        println!("Actually, I never get to this point, 'cause I crash.");
    }
}

fn main() {
    let b = Bar;
    b.method();     // results in "thread '' has overflowed its stack"
}
```

So, in case of inherited traits, calling the original default implementation is no problem, however, using the same syntax when implementing structs exhibits different behavior. Is this a problem within Rust? Is there a way around it? Or am I just missing something?

答:
Another way of accomplishing this would be to place the overriding method in impl block of struct

```<code>trait A {
    fn a(&self) {
        println!("trait default method");
    }
}

struct B;

impl B {
    fn a(&self) {
        println!("overridden method");
        // call default method here
        A::a(self);
    }
}

impl A for B {}

fn main() {
    let a = B;
    a.a();
}
</code>```

playground

Body:
In traditional object-oriented languages (e.g. Java), it is possible to "extend" the functionality of a method in an inherited class by calling the original method from the super class in the overridden version, for example:

class A {
    public void method() {
        System.out.println("I am doing some serious stuff!");
    }
}

class B extends A {
    @Override
    public void method() {
        super.method(); // here we call the original version
        System.out.println("And I'm doing something more!");
    }
}

As you can see, in Java, I am able to call the original version from the super class using the super keyword. I was able to get the equivalent behavior for inherited traits, but not when implementing traits for structs.

trait Foo {
    fn method(&self) {
        println!("default implementation");
    }
}

trait Boo: Foo {
    fn method(&self) {
        // this is overriding the default implementation
        Foo::method(self);  // here, we successfully call the original
                            // this is tested to work properly
        println!("I am doing something more.");
    }
}

struct Bar;

impl Foo for Bar {
    fn method(&self) {
        // this is overriding the default implementation as well
        Foo::method(self);  // this apparently calls this overridden
                            // version, because it overflows the stack
        println!("Hey, I'm doing something entirely different!");
        println!("Actually, I never get to this point, 'cause I crash.");
    }
}

fn main() {
    let b = Bar;
    b.method();     // results in "thread '' has overflowed its stack"
}

So, in case of inherited traits, calling the original default implementation is no problem, however, using the same syntax when implementing structs exhibits different behavior. Is this a problem within Rust? Is there a way around it? Or am I just missing something?

Body:
Another way of accomplishing this would be to place the overriding method in impl block of struct

trait A {
    fn a(&self) {
        println!("trait default method");
    }
}

struct B;

impl B {
    fn a(&self) {
        println!("overridden method");
        // call default method here
        A::a(self);
    }
}

impl A for B {}

fn main() {
    let a = B;
    a.a();
}

playground


问:
give me some help this error in android studio
i want make android ble scanner

no problem start this app but i want startscan and push start scan button then turn off this app

this is error code

```<code>E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /vendor/lib64]]
V/BoostFramework: BoostFramework() : mPerf = null
D/ViewRootImpl@d967e4a[MainActivity]: ViewPostImeInputStage processPointer 1
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 15923
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.le.BluetoothLeScanner.startScan(java.util.List, android.bluetooth.le.ScanSettings, android.bluetooth.le.ScanCallback)' on a null object reference
        at com.example.myapplication.MainActivity.startScan(MainActivity.java:182)
        at com.example.myapplication.MainActivity.lambda$onCreate$0$MainActivity(MainActivity.java:141)
        at com.example.myapplication.-$$Lambda$MainActivity$mssl4La-mhhX0ttBjD5v7QdktdI.onClick(lambda)
        at android.view.View.performClick(View.java:6205)
        at android.widget.TextView.performClick(TextView.java:11103)
        at android.view.View$PerformClick.run(View.java:23653)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
</code>```

this is my code in MainActivity

```<code>    //// GUI variables
    // text view for status
    private TextView tv_status_;
    // text view for read
    private TextView tv_read_;
    // button for start scan
    private Button btn_scan_;
    // button for stop connection
    private Button btn_stop_;
    // button for send dataenter code here
    private Button btn_send_;
    // button for show paired devices
    private Button btn_show_;

    // Tag name for Log message
    private final static String TAG="Central";
    // used to identify adding bluetooth names
    private final static int REQUEST_ENABLE_BT= 1;
    // used to request fine location permission
    private final static int REQUEST_FINE_LOCATION= 2;
    // scan period in milliseconds
    private final static int SCAN_PERIOD= 5000;
    // ble adapter
    private BluetoothAdapter ble_adapter_;
    // flag for scanning
    private boolean is_scanning_= false;
    // flag for connection
    private boolean connected_= false;
    // scan results
    private Map<String, BluetoothDevice> scan_results_;
    // scan callback
    private ScanCallback scan_cb_;
    // ble scanner
    private BluetoothLeScanner ble_scanner_;
    // scan handler
    private Handler scan_handler_;

    public final static String MAC_ADDR="18:62:E4:3C:2A:1B";

    //BLE Scan Callback class

    private class BLEScanCallback extends ScanCallback {
        private Map<String, BluetoothDevice> cb_scan_results_;

        //Constructor

        BLEScanCallback(Map<String, BluetoothDevice> _scan_results ){

        }

        public void onScanResult(int _callback_type, ScanResult _result) {
            Log.d(TAG, "onScanResult");
            addScanResult(_result);

        }

        public void onScanFailed(int _error) {
            Log.e(TAG,"BLE scan failed with code "+_error);
        }

        //add scan result

        private void addScanResult(ScanResult _result) {
            //get scanned device
            BluetoothDevice device = _result.getDevice();
            //get scanned device Mac address
            String device_address = device.getAddress();
            //add the device to the result list
            cb_scan_results_.put(device_address, device);
            //log
            Log.d(TAG, "scan results device: " + device);
            tv_status_.setText("add scanned device: "+ device_address);

        }

    }

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

        //// get instances of gui objects
        // status textview
        tv_status_= findViewById( R.id.tv_status );
        // read textview
        tv_read_= findViewById( R.id.tv_read );
        // scan button
        btn_scan_= findViewById( R.id.btn_scan );
        // stop button
        btn_stop_= findViewById( R.id.btn_stop );
        // send button
        btn_send_= findViewById( R.id.btn_send );
        // show button
        btn_show_= findViewById( R.id.btn_show );

        // ble manager
        BluetoothManager ble_manager;
        ble_manager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
        // set ble adapter
        ble_adapter_ = ble_manager.getAdapter();

        btn_scan_.setOnClickListener((v) -> {startScan(v); });

    }

    //start scan
    private void startScan(View v) {

        tv_status_.setText("Scanning...");

        // check ble adapter and ble enabled
        if(ble_adapter_ == null || !ble_adapter_.isEnabled()){
            requestEnableBLE();
            tv_status_.setText("Scanning Failed: ble not enabled");
            return;

        }

        //Set scanfilter
        //creat filter list
        List<ScanFilter> filters = new ArrayList<>();

        // create a scan filter with device mac address
        ScanFilter scan_filter = new ScanFilter.Builder().setDeviceAddress(MAC_ADDR).build();

        // add filter to list

        filters.add(scan_filter);

        //// scan settings
        // set low power scan mode
        ScanSettings settings= new ScanSettings.Builder().setScanMode( ScanSettings.SCAN_MODE_LOW_POWER ).build();

        // Scan callback
        scan_results_ = new HashMap<>();
        scan_cb_= new BLEScanCallback(scan_results_);

        //now ready to scan
        //start scan
        ble_scanner_.startScan(filters, settings, scan_cb_);
        //set scanning flag
        is_scanning_ = true;

    }

    // Request BLE enable
    private void requestEnableBLE() {
        Intent ble_enable_intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(ble_enable_intent, REQUEST_ENABLE_BT);
    }

    // Request Fine Location permission
    private void requestLocationPermission() {

        requestPermissions( new String[]{ Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION );

    }

    protected void onResume() {
        super.onResume();

        //finish app if the BLE is not supported
        if( !getPackageManager().hasSystemFeature( PackageManager.FEATURE_BLUETOOTH_LE ) ) {
            finish();
        }
    }

}
</code>```

give me some help

答:
You use ble_scanner_ as  BluetoothLeScanner and you init that on global

```<code> private BluetoothLeScanner ble_scanner_;
</code>```

But you never call

```<code> ble_scanner_ = ble_adapter_.getBluetoothLeScanner();
</code>```

So your ble_scanner_ is null and give you NullPointerException

Add above line into onCreate like this

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

    //other codes...

    ble_adapter_ = ble_manager.getAdapter();
    ble_scanner_ =  ble_scanner_ = ble_adapter_.getBluetoothLeScanner();

    btn_scan_.setOnClickListener((v) -> {startScan(v); });

}
</code>```

Body:
i want make android ble scanner

no problem start this app but i want startscan and push start scan button then turn off this app

this is error code

E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /vendor/lib64]]
V/BoostFramework: BoostFramework() : mPerf = null
D/ViewRootImpl@d967e4a[MainActivity]: ViewPostImeInputStage processPointer 1
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 15923
    java.lang.NullPointerException: Attempt to invoke virtual method 'void android.bluetooth.le.BluetoothLeScanner.startScan(java.util.List, android.bluetooth.le.ScanSettings, android.bluetooth.le.ScanCallback)' on a null object reference
        at com.example.myapplication.MainActivity.startScan(MainActivity.java:182)
        at com.example.myapplication.MainActivity.lambda$onCreate$0$MainActivity(MainActivity.java:141)
        at com.example.myapplication.-$$Lambda$MainActivity$mssl4La-mhhX0ttBjD5v7QdktdI.onClick(lambda)
        at android.view.View.performClick(View.java:6205)
        at android.widget.TextView.performClick(TextView.java:11103)
        at android.view.View$PerformClick.run(View.java:23653)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6682)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

this is my code in MainActivity

    //// GUI variables
    // text view for status
    private TextView tv_status_;
    // text view for read
    private TextView tv_read_;
    // button for start scan
    private Button btn_scan_;
    // button for stop connection
    private Button btn_stop_;
    // button for send dataenter code here
    private Button btn_send_;
    // button for show paired devices
    private Button btn_show_;

    // Tag name for Log message
    private final static String TAG="Central";
    // used to identify adding bluetooth names
    private final static int REQUEST_ENABLE_BT= 1;
    // used to request fine location permission
    private final static int REQUEST_FINE_LOCATION= 2;
    // scan period in milliseconds
    private final static int SCAN_PERIOD= 5000;
    // ble adapter
    private BluetoothAdapter ble_adapter_;
    // flag for scanning
    private boolean is_scanning_= false;
    // flag for connection
    private boolean connected_= false;
    // scan results
    private Map<String, BluetoothDevice> scan_results_;
    // scan callback
    private ScanCallback scan_cb_;
    // ble scanner
    private BluetoothLeScanner ble_scanner_;
    // scan handler
    private Handler scan_handler_;

    public final static String MAC_ADDR="18:62:E4:3C:2A:1B";

    //BLE Scan Callback class

    private class BLEScanCallback extends ScanCallback {
        private Map<String, BluetoothDevice> cb_scan_results_;

        //Constructor

        BLEScanCallback(Map<String, BluetoothDevice> _scan_results ){

        }

        public void onScanResult(int _callback_type, ScanResult _result) {
            Log.d(TAG, "onScanResult");
            addScanResult(_result);

        }

        public void onScanFailed(int _error) {
            Log.e(TAG,"BLE scan failed with code "+_error);
        }

        //add scan result

        private void addScanResult(ScanResult _result) {
            //get scanned device
            BluetoothDevice device = _result.getDevice();
            //get scanned device Mac address
            String device_address = device.getAddress();
            //add the device to the result list
            cb_scan_results_.put(device_address, device);
            //log
            Log.d(TAG, "scan results device: " + device);
            tv_status_.setText("add scanned device: "+ device_address);

        }

    }

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

        //// get instances of gui objects
        // status textview
        tv_status_= findViewById( R.id.tv_status );
        // read textview
        tv_read_= findViewById( R.id.tv_read );
        // scan button
        btn_scan_= findViewById( R.id.btn_scan );
        // stop button
        btn_stop_= findViewById( R.id.btn_stop );
        // send button
        btn_send_= findViewById( R.id.btn_send );
        // show button
        btn_show_= findViewById( R.id.btn_show );

        // ble manager
        BluetoothManager ble_manager;
        ble_manager = (BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
        // set ble adapter
        ble_adapter_ = ble_manager.getAdapter();

        btn_scan_.setOnClickListener((v) -> {startScan(v); });

    }

    //start scan
    private void startScan(View v) {

        tv_status_.setText("Scanning...");

        // check ble adapter and ble enabled
        if(ble_adapter_ == null || !ble_adapter_.isEnabled()){
            requestEnableBLE();
            tv_status_.setText("Scanning Failed: ble not enabled");
            return;

        }

        //Set scanfilter
        //creat filter list
        List<ScanFilter> filters = new ArrayList<>();

        // create a scan filter with device mac address
        ScanFilter scan_filter = new ScanFilter.Builder().setDeviceAddress(MAC_ADDR).build();

        // add filter to list

        filters.add(scan_filter);

        //// scan settings
        // set low power scan mode
        ScanSettings settings= new ScanSettings.Builder().setScanMode( ScanSettings.SCAN_MODE_LOW_POWER ).build();

        // Scan callback
        scan_results_ = new HashMap<>();
        scan_cb_= new BLEScanCallback(scan_results_);

        //now ready to scan
        //start scan
        ble_scanner_.startScan(filters, settings, scan_cb_);
        //set scanning flag
        is_scanning_ = true;

    }

    // Request BLE enable
    private void requestEnableBLE() {
        Intent ble_enable_intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(ble_enable_intent, REQUEST_ENABLE_BT);
    }

    // Request Fine Location permission
    private void requestLocationPermission() {

        requestPermissions( new String[]{ Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION );

    }

    protected void onResume() {
        super.onResume();

        //finish app if the BLE is not supported
        if( !getPackageManager().hasSystemFeature( PackageManager.FEATURE_BLUETOOTH_LE ) ) {
            finish();
        }
    }

}

give me some help

Body:
You use ble_scanner_ as  BluetoothLeScanner and you init that on global

 private BluetoothLeScanner ble_scanner_;

But you never call

 ble_scanner_ = ble_adapter_.getBluetoothLeScanner();

So your ble_scanner_ is null and give you NullPointerException

Add above line into onCreate like this

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

    //other codes...

    ble_adapter_ = ble_manager.getAdapter();
    ble_scanner_ =  ble_scanner_ = ble_adapter_.getBluetoothLeScanner();

    btn_scan_.setOnClickListener((v) -> {startScan(v); });

}


答:
Well I am not that good at swift, but till what I understand your problem, this should solve it.
And if it doesn’t, I am pretty sure someone better in swift will answer it in a more better way.

Every ViewController has a base view which you can access like view.method().

You add a subview to an existing view.

Supposing you want to add a new UIView named view1.

First you initialise it like,

view1 = UIView(frame: view.bounds)

Now to make it appear on screen, do like,

view.addSubview(view1)

This line would add view1 as subview of view.

Also now view1 is on top of view. So now when you touch your screen it is the view1 you are accessing.
So the next time you swipe right, the gesture recogniser should be on view1.

```<code>let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swipeRightAction))
        swipeRight.direction = UISwipeGestureRecognizer.Direction.right

view1.addGestureRecognizer(swipeRight)
</code>```

This is how you will add gesture of right swipe to view1.

Now when you right swipe on screen, swipeRightAction() will get called.

You can remove this view1 from super view like,

view1.removeFromSuperView()

Now view1 is gone and now you can add view2 by similar process as we added view1.

See the following code, it may be relatable.

```<code>//The old view that has to be replaced
    var viewToBeRemoved : UIView!

    //The new view that will replace the previous one
    var viewToBeAdded   : UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        replaceWithNewSwipableSubview()

    }

    func replaceWithNewSwipableSubview()
    {
        viewToBeAdded = UIView(frame: view.bounds)

        //New view being added should have a gesture so that next time
        //it need to be replaced we can swipe on it
        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swipeRightAction))
        swipeRight.direction = UISwipeGestureRecognizer.Direction.right

        viewToBeAdded.addGestureRecognizer(swipeRight)

        UIView.animate(withDuration: 1, animations: {

            //This will be animated

            if self.viewToBeRemoved != nil{

                //As there is no subview the very first time this func is called

                self.viewToBeRemoved.removeFromSuperview()

            }

            //Because next time it will be the view to be removed
            self.viewToBeRemoved = self.viewToBeAdded

        }) { (isFinished) in

            //This block gets executed only after
            //the block above has completed
            self.view.addSubview(self.viewToBeAdded)

            //view is the default base view of a ViewController

        }
    }

    @objc func swipeRightAction() {

        replaceWithNewSwipableSubview()

    }
</code>```

In your code view1?.addSubview(CustomView(frame: self.view.bounds)) this line adds a view to view1 and you have no reference to the view you are adding. You should first store the view you add like view3 = CustomView(frame: self.view.bounds) so that later you can remove view3. Also your view1 actually never gets added If I am right because to add view1 you need to add like view.addSubview(view1) first.

Although possibly a better solution can be suggested if you tell us what you actually want to achieve?

Title: How to remove previous stack of UIView after adding a new one?

Body:
Well I am not that good at swift, but till what I understand your problem, this should solve it.
And if it doesn’t, I am pretty sure someone better in swift will answer it in a more better way.

Every ViewController has a base view which you can access like view.method().

You add a subview to an existing view.

Supposing you want to add a new UIView named view1.

First you initialise it like,

view1 = UIView(frame: view.bounds)

Now to make it appear on screen, do like,

view.addSubview(view1)

This line would add view1 as subview of view.

Also now view1 is on top of view. So now when you touch your screen it is the view1 you are accessing.
So the next time you swipe right, the gesture recogniser should be on view1.

let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swipeRightAction))
        swipeRight.direction = UISwipeGestureRecognizer.Direction.right

view1.addGestureRecognizer(swipeRight)

This is how you will add gesture of right swipe to view1.

Now when you right swipe on screen, swipeRightAction() will get called.

You can remove this view1 from super view like,

view1.removeFromSuperView()

Now view1 is gone and now you can add view2 by similar process as we added view1.

See the following code, it may be relatable.

//The old view that has to be replaced
    var viewToBeRemoved : UIView!

    //The new view that will replace the previous one
    var viewToBeAdded   : UIView!

    override func viewDidLoad() {
        super.viewDidLoad()

        replaceWithNewSwipableSubview()

    }

    func replaceWithNewSwipableSubview()
    {
        viewToBeAdded = UIView(frame: view.bounds)

        //New view being added should have a gesture so that next time
        //it need to be replaced we can swipe on it
        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swipeRightAction))
        swipeRight.direction = UISwipeGestureRecognizer.Direction.right

        viewToBeAdded.addGestureRecognizer(swipeRight)

        UIView.animate(withDuration: 1, animations: {

            //This will be animated

            if self.viewToBeRemoved != nil{

                //As there is no subview the very first time this func is called

                self.viewToBeRemoved.removeFromSuperview()

            }

            //Because next time it will be the view to be removed
            self.viewToBeRemoved = self.viewToBeAdded

        }) { (isFinished) in

            //This block gets executed only after
            //the block above has completed
            self.view.addSubview(self.viewToBeAdded)

            //view is the default base view of a ViewController

        }
    }

    @objc func swipeRightAction() {

        replaceWithNewSwipableSubview()

    }

In your code view1?.addSubview(CustomView(frame: self.view.bounds)) this line adds a view to view1 and you have no reference to the view you are adding. You should first store the view you add like view3 = CustomView(frame: self.view.bounds) so that later you can remove view3. Also your view1 actually never gets added If I am right because to add view1 you need to add like view.addSubview(view1) first.

Although possibly a better solution can be suggested if you tell us what you actually want to achieve?


问:
App Crashing- Core Data Problem Or Memory Management?
Console Message:

Had to use picture because wasn't formatting correctly in post as text.

the received memory warning level 2 showed up before the app crashed.

errror comes at this line - cell.textLabel.text = tempRoutine.name;

link to full-size picture (http://www.box.net/shared/static/7igj3r4trh.png)

ViewController:

```<code>@implementation RoutineTableViewController

@synthesize tableView;
@synthesize eventsArray;
@synthesize entered;
@synthesize managedObjectContext;

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    if (managedObjectContext == nil)
    {
        managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    }

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Routine" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];

    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        // Handle the error.
    }
    [self setEventsArray:mutableFetchResults];
    [mutableFetchResults release];
    [request release];

    UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showPrompt)];
    [self.navigationItem setLeftBarButtonItem:addButton];
    [addButton release];

    UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleEdit)];
    self.navigationItem.rightBarButtonItem = editButton;
    [editButton release];

    [super viewDidLoad];
}

- (void)viewDidUnload
{
    self.eventsArray = nil;
    [super viewDidUnload];
}

-(void)toggleEdit
{
    [self.tableView setEditing: !self.tableView.editing animated:YES];

    if (self.tableView.editing)
        [self.navigationItem.rightBarButtonItem setTitle:@"Done"];
    else
        [self.navigationItem.rightBarButtonItem setTitle:@"Edit"];
}

- (void)dealloc
{
    [managedObjectContext release];
    [eventsArray release];
    [entered release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark -
#pragma mark Add an event

-(void)addEvent
{
    Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];

    routine.name=entered;

    NSError *error = nil;
    if (![managedObjectContext save:&error]) {
        // Handle the error.
    }
    NSLog(@"%@", error);

    [eventsArray insertObject:routine atIndex:0];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

-(void)showPrompt
{
    AlertPrompt *prompt = [AlertPrompt alloc];
    prompt = [prompt initWithTitle:@"Add Workout Day" message:@"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:@"Cancel" okButtonTitle:@"Add"];
    [prompt show];
    [prompt release];
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{

    if (buttonIndex != [alertView cancelButtonIndex])
    {
        entered = [(AlertPrompt *)alertView enteredText];

        if(eventsArray && entered)
        {
            Routine *tempRoutine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];
            tempRoutine.name = entered;
           // Routine *tempRoutine = [[Routine alloc]init];
            //tempRoutine.name = entered;
            [eventsArray addObject:tempRoutine];
            [tempRoutine release];
            [tableView reloadData];
            [self addEvent];
        }
        /*
        if(eventsArray && entered)
        {
            [eventsArray addObject:entered];
            [tableView reloadData];
            [self addEvent];
        }
        */
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [eventsArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    // Dequeue or create a new cell.

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    Routine *tempRoutine = (Routine *)[eventsArray objectAtIndex:indexPath.row];
    cell.textLabel.text = tempRoutine.name;

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;

}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {

     if (editingStyle == UITableViewCellEditingStyleDelete) {

         // Delete the managed object at the given index path.
         NSManagedObject *eventToDelete = [eventsArray objectAtIndex:indexPath.row];
         [managedObjectContext deleteObject:eventToDelete];

         // Update the array and table view.
         [eventsArray removeObjectAtIndex:indexPath.row];
         [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];

         // Commit the change.
         NSError *error = nil;
         if (![managedObjectContext save:&error]) {
             // Handle the error.
         }
     }
 }
</code>```

答:
HI,

IS your table view is showing a lot many data at a time ?

I think this is the only problem with your code. If there are more then 50 to 60 rows you are calling at a time and you are viewing the same by scrolling up and down then it may cause the memory warning.

The best way to use Lazy loading , call the number of raws like you can load only 20 raws at a time and then load another rows as user scroll down.

Here is nice discussion on the same. You are not using images still a number of images may cause the crash of application.

Hope this shall solve your issue.

Body:
Console Message:

Had to use picture because wasn't formatting correctly in post as text.

the received memory warning level 2 showed up before the app crashed.

errror comes at this line - cell.textLabel.text = tempRoutine.name;

link to full-size picture (http://www.box.net/shared/static/7igj3r4trh.png)

ViewController:

@implementation RoutineTableViewController

@synthesize tableView;
@synthesize eventsArray;
@synthesize entered;
@synthesize managedObjectContext;

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    if (managedObjectContext == nil)
    {
        managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
    }

    NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Routine" inManagedObjectContext:managedObjectContext];
    [request setEntity:entity];

    NSError *error = nil;
    NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResults == nil) {
        // Handle the error.
    }
    [self setEventsArray:mutableFetchResults];
    [mutableFetchResults release];
    [request release];

    UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showPrompt)];
    [self.navigationItem setLeftBarButtonItem:addButton];
    [addButton release];

    UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(toggleEdit)];
    self.navigationItem.rightBarButtonItem = editButton;
    [editButton release];

    [super viewDidLoad];
}

- (void)viewDidUnload
{
    self.eventsArray = nil;
    [super viewDidUnload];
}

-(void)toggleEdit
{
    [self.tableView setEditing: !self.tableView.editing animated:YES];

    if (self.tableView.editing)
        [self.navigationItem.rightBarButtonItem setTitle:@"Done"];
    else
        [self.navigationItem.rightBarButtonItem setTitle:@"Edit"];
}

- (void)dealloc
{
    [managedObjectContext release];
    [eventsArray release];
    [entered release];
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark -
#pragma mark Add an event

-(void)addEvent
{
    Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];

    routine.name=entered;

    NSError *error = nil;
    if (![managedObjectContext save:&error]) {
        // Handle the error.
    }
    NSLog(@"%@", error);

    [eventsArray insertObject:routine atIndex:0];

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

-(void)showPrompt
{
    AlertPrompt *prompt = [AlertPrompt alloc];
    prompt = [prompt initWithTitle:@"Add Workout Day" message:@"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:@"Cancel" okButtonTitle:@"Add"];
    [prompt show];
    [prompt release];
}

- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{

    if (buttonIndex != [alertView cancelButtonIndex])
    {
        entered = [(AlertPrompt *)alertView enteredText];

        if(eventsArray && entered)
        {
            Routine *tempRoutine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:@"Routine" inManagedObjectContext:managedObjectContext];
            tempRoutine.name = entered;
           // Routine *tempRoutine = [[Routine alloc]init];
            //tempRoutine.name = entered;
            [eventsArray addObject:tempRoutine];
            [tempRoutine release];
            [tableView reloadData];
            [self addEvent];
        }
        /*
        if(eventsArray && entered)
        {
            [eventsArray addObject:entered];
            [tableView reloadData];
            [self addEvent];
        }
        */
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [eventsArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";

    // Dequeue or create a new cell.

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    Routine *tempRoutine = (Routine *)[eventsArray objectAtIndex:indexPath.row];
    cell.textLabel.text = tempRoutine.name;

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;

    return cell;

}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {

     if (editingStyle == UITableViewCellEditingStyleDelete) {

         // Delete the managed object at the given index path.
         NSManagedObject *eventToDelete = [eventsArray objectAtIndex:indexPath.row];
         [managedObjectContext deleteObject:eventToDelete];

         // Update the array and table view.
         [eventsArray removeObjectAtIndex:indexPath.row];
         [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];

         // Commit the change.
         NSError *error = nil;
         if (![managedObjectContext save:&error]) {
             // Handle the error.
         }
     }
 }


问:
C# - There is no argument given that corresponds to the required formal parameter 'Role' of 'MainMenuForm.MainMenuForm(string)'
Good evening,

I am trying to create a role based login for my C# WinForms App. I am still a very basic C# user, and this is part of an academic project. The error above is showing, and I'm not sure how to tackle it.

The logins are taken from a local DB I have created, connected to the .NET (for this application).

I have two users, one is Admin user, one is default user.

PLEASE NOTE, I know about the SQL Injection issue, I will sort that out as soon as I fix this error.

Can you kindly advise on how to fix this error, please?

Thank you in advance.

I was following a YT tutorial, and got as far as this part, where the error is generated - please see code below.

```<code>namespace Library_System_Project
{
    public partial class MainMenuForm : Form
    {
        public MainMenuForm(string Role) // Error occurs here
        {
            InitializeComponent();
            lblRole.Text = Role; // Error occurs here
        }
</code>```

Also, the below is on a different form, but related to the above:

```<code>private void btnOk_Click(object sender, EventArgs e)
{
    //Database Connection Setup
    SqlConnection Connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename = C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\DATA\Library System Project.mdf;Integrated Security=True;Connect Timeout=30;");
    string query = "Select * from Users where User_Username = '" + txtUsername.Text.Trim() + "' and User_Password = '" + txtPassword.Text.Trim() + "'";
    SqlDataAdapter SDA = new SqlDataAdapter(query, Connection);
    DataTable DT = new DataTable();
    SDA.Fill(DT);

    // Access to Main Menu for Authorized Users
    if (DT.Rows.Count == 1)
    {
        MainMenuForm MainMenu = new MainMenuForm(DT.Rows[0][0].ToString());
        MainMenu.Show();
        this.Hide();
    }
</code>```

答:
As mentioned in my comment, Winforms requires controls to have a parameterless constructor. You can work around that by creating a method to further initialize the Form:

```<code>public partial class MainMenuForm : Form
{
   public MainMenuForm()
   {
      InitializeComponent();
   }

   public void SetRole(string role)
   {
       lblRole.Text = role;
   }
}
</code>```

and then

```<code>private void btnOk_Click(object sender, EventArgs e)
{
    //...

    // Access to Main Menu for Authorized Users
    if (DT.Rows.Count == 1)
    {
        MainMenuForm MainMenu = new MainMenuForm();
        MainMenu.SetRole(DT.Rows[0][0].ToString());
        MainMenu.Show();
        this.Hide();
    }
}
</code>```

Body:
Good evening,

I am trying to create a role based login for my C# WinForms App. I am still a very basic C# user, and this is part of an academic project. The error above is showing, and I'm not sure how to tackle it.

The logins are taken from a local DB I have created, connected to the .NET (for this application).

I have two users, one is Admin user, one is default user.

PLEASE NOTE, I know about the SQL Injection issue, I will sort that out as soon as I fix this error.

Can you kindly advise on how to fix this error, please?

Thank you in advance.

I was following a YT tutorial, and got as far as this part, where the error is generated - please see code below.

namespace Library_System_Project
{
    public partial class MainMenuForm : Form
    {
        public MainMenuForm(string Role) // Error occurs here
        {
            InitializeComponent();
            lblRole.Text = Role; // Error occurs here
        }

Also, the below is on a different form, but related to the above:

private void btnOk_Click(object sender, EventArgs e)
{
    //Database Connection Setup
    SqlConnection Connection = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename = C:\Program Files\Microsoft SQL Server\MSSQL14.SQLEXPRESS\MSSQL\DATA\Library System Project.mdf;Integrated Security=True;Connect Timeout=30;");
    string query = "Select * from Users where User_Username = '" + txtUsername.Text.Trim() + "' and User_Password = '" + txtPassword.Text.Trim() + "'";
    SqlDataAdapter SDA = new SqlDataAdapter(query, Connection);
    DataTable DT = new DataTable();
    SDA.Fill(DT);

    // Access to Main Menu for Authorized Users
    if (DT.Rows.Count == 1)
    {
        MainMenuForm MainMenu = new MainMenuForm(DT.Rows[0][0].ToString());
        MainMenu.Show();
        this.Hide();
    }

Body:
As mentioned in my comment, Winforms requires controls to have a parameterless constructor. You can work around that by creating a method to further initialize the Form:

public partial class MainMenuForm : Form
{
   public MainMenuForm()
   {
      InitializeComponent();
   }

   public void SetRole(string role)
   {
       lblRole.Text = role;
   }
}

and then

private void btnOk_Click(object sender, EventArgs e)
{
    //...

    // Access to Main Menu for Authorized Users
    if (DT.Rows.Count == 1)
    {
        MainMenuForm MainMenu = new MainMenuForm();
        MainMenu.SetRole(DT.Rows[0][0].ToString());
        MainMenu.Show();
        this.Hide();
    }
}


问:
Positioning Element Relative to its Friend Element
I Would like to create a effect the same as Position Relative in css by using some jquery.

I have created a type of tooltip which I am trying to attach to different objects such as textboxes, checkboxes, some text etc.

so my code is along the lines of

```<code><input id="adsfjlk" type="textbox" />
<div class="TooltipBalloon"> SOME TEXT</div>
</code>```

Now of course CSS relative positioning is based on a elements parent. I cannot do that in this case as I cannot place a div inside of a input element.

Currently I use some Jquery to position the tooltip just to the right of the textbox.

The problem comes when something on the page changes. For example if you have a elastic textarea above your textbox. When this expands it pushes down your textbox and then the tooltip is no longer aligned correctly.

Because of the amount of different things that could happen I cannot really apply a OnChange type event to the elastic and instead need a better way to keep to elements positioned relative to each other.

答:
I'm not sure how you are displaying tooltips (on focus, on hover), however I have created this example of how I may create tooltips for inputs.

http://jsfiddle.net/c4KyD/2/

I followed each input with a span tag containing the tooltip. I positioned the span to 'absolute'. The tooltip is displayed on focus and removed on blur.

If there is some dynamic content on the page the tooltips will still be positioned correctly (if you comment out the blur function and use the "Change Page" link to insert content you'll see this in action).

I also created code for hover events (commented out in my example).

Here are snippets of the code.

HTML...

```<code><ul class="tooltip-stuff">
  <li>
    <label>First Name</label>
    <input class="tooltip" type="text" />
    <span>Enter your first name here.</span>
  </li>
</ul>
</code>```

CSS...

```<code>
.tooltip-stuff SPAN
{
    border: 1px solid #D3D3D3;
    margin-left: 5px;
    padding: 0 6px;
    background-color: #C4ECF8;
    position: absolute;
    display: none;
}
</code>```

jQuery...

```<code>
    $('.tooltip').focus(function () {
        $(this).next('span').fadeIn(100);
    });

    $('.tooltip').blur(function () {
        $(this).next('span').fadeOut(100);
    });
</code>```

Body:
I Would like to create a effect the same as Position Relative in css by using some jquery.

I have created a type of tooltip which I am trying to attach to different objects such as textboxes, checkboxes, some text etc.

so my code is along the lines of

<input id="adsfjlk" type="textbox" />

 SOME TEXT

Now of course CSS relative positioning is based on a elements parent. I cannot do that in this case as I cannot place a div inside of a input element.

Currently I use some Jquery to position the tooltip just to the right of the textbox.

The problem comes when something on the page changes. For example if you have a elastic textarea above your textbox. When this expands it pushes down your textbox and then the tooltip is no longer aligned correctly.

Because of the amount of different things that could happen I cannot really apply a OnChange type event to the elastic and instead need a better way to keep to elements positioned relative to each other.

Body:
I'm not sure how you are displaying tooltips (on focus, on hover), however I have created this example of how I may create tooltips for inputs.

http://jsfiddle.net/c4KyD/2/

I followed each input with a span tag containing the tooltip. I positioned the span to 'absolute'. The tooltip is displayed on focus and removed on blur.

If there is some dynamic content on the page the tooltips will still be positioned correctly (if you comment out the blur function and use the "Change Page" link to insert content you'll see this in action).

I also created code for hover events (commented out in my example).

Here are snippets of the code.

HTML...

<ul class="tooltip-stuff">
  <li>
    <label>First Name</label>
    <input class="tooltip" type="text" />
    <span>Enter your first name here.</span>
  </li>
</ul>

CSS...

.tooltip-stuff SPAN
{
    border: 1px solid #D3D3D3;
    margin-left: 5px;
    padding: 0 6px;
    background-color: #C4ECF8;
    position: absolute;
    display: none;
}

jQuery...

    $('.tooltip').focus(function () {
        $(this).next('span').fadeIn(100);
    });

    $('.tooltip').blur(function () {
        $(this).next('span').fadeOut(100);
    });


问:
How to access scene functions from other scenes with react-native-router-flux
I have a feeling that I might be going in the wrong direction,

Because it cant possibly be this unintuitive

But then again, I can be really dumb.

So my question is:

How can I access scene functions when I'm not in the scene currently.

My example:

App.js

import React from 'react';
import {Text, View} from 'react-native';
import Home from './components/Home';
import Add from './components/Add';
import {Router, Scene, Actions} from 'react-native-router-flux';

class App extends React.Component {
  constructor() {
    super();
  }

  render() {
    return(
      <Router>
        <Scene key='root'>
        <Scene key='home' component={Home} title='Home' rightButtonImage={require('./assets/plus.png')} onRight={() => {Actions.add()}}/>
        <Scene key='add' component={Add} title='Add'/>
        </Scene>
      </Router>
    );
  }
}

export default App;
```

<p><strong>Home.js</strong></p>

<pre class="lang-js prettyprint-override"><code>import React from 'react';
import {View, Text, ScrollView, SafeAreaView, Image, Dimensions} from 'react-native';
import ScrollCompanyIndex from './ScollCompanyIndex';

var {screenHeight, screenWidth} = Dimensions.get('window');

var companies = require('./companies.json');
var companiesString = JSON.stringify(companies);
var comapniesJson = JSON.parse(companiesString.toString());
var companyList = [];

class Home extends React.Component {
    constructor() {
        super();
        companyList = [];
        comapniesJson.companies.forEach(element => {
            companyList.push(element);
        });
    }

    rerenderComponent() {
        console.log('Rerendering the component');

    }

    render() {
        return(
            <SafeAreaView style={{flex: 1}}>
                <ScrollView>
                    {
                        companyList.map((item, key) => (
                            <ScrollCompanyIndex key={key} imageUri={'https://picsum.photos/' + (129 + Math.floor(Math.random() * 3)) + '/' + (129 + Math.floor(Math.random() * 3))} companyName={item.name} companyAddress={item.address + ', ' + item.city}/>
                        ))
                    }
                </ScrollView>
            </SafeAreaView>
        );
    }
}

export default Home;
</code>```

Add.js

import React from 'react';
import {View, Text, Button} from 'react-native';
import { Actions } from 'react-native-router-flux';

class Add extends React.Component {
    render() {
        return(
            <View>
                <Button onPress={gallaryButtonPressed} title='Camera / Gallery Button' color='#841584'/>
                <Button onPress={addButton} title='Add button' color='#841584'/>
            </View>
        );
    }
}

function gallaryButtonPressed() {

}

function addButton() {

}

export default Add;
```

So. How can i access for example, The function rerenderComponent() that is found in Home.js,

when I click the "Add button" button that is found in Add.js that is currently linked to the function addButton() but nvm that,

Thank you very much :3

答:
You asked a good question, i was also wondering about this but then i found the solution.

App.js

<Scene key='home' component={Home} title='Home' rightButtonImage=require('./assets/plus.png')} onRight={() => {}} />

Home.js

```<code>constructor(props) {
        super(props);
        companyList = [];
        comapniesJson.companies.forEach(element => {
            companyList.push(element);
        });
    }

    componentDidMount() {
     this.props.navigation.setParams({
     onRight: this.addButton
     });
    }

    addButton = () => {
      return <Button onPress={() => Actions.Something()} title='Add button' color='#841584'/>;
    }
</code>```

Similarly you can access rerenderComponent function.

Body:
I have a feeling that I might be going in the wrong direction,

Because it cant possibly be this unintuitive

But then again, I can be really dumb.

So my question is:

How can I access scene functions when I'm not in the scene currently.

My example:

App.js

import React from 'react';
import {Text, View} from 'react-native';
import Home from './components/Home';
import Add from './components/Add';
import {Router, Scene, Actions} from 'react-native-router-flux';

class App extends React.Component {
  constructor() {
    super();
  }

  render() {
    return(
      <Router>
        <Scene key='root'>
        <Scene key='home' component={Home} title='Home' rightButtonImage={require('./assets/plus.png')} onRight={() => {Actions.add()}}/>
        <Scene key='add' component={Add} title='Add'/>
        </Scene>
      </Router>
    );
  }
}

export default App;

Home.js

import React from 'react';
import {View, Text, ScrollView, SafeAreaView, Image, Dimensions} from 'react-native';
import ScrollCompanyIndex from './ScollCompanyIndex';

var {screenHeight, screenWidth} = Dimensions.get('window');

var companies = require('./companies.json');
var companiesString = JSON.stringify(companies);
var comapniesJson = JSON.parse(companiesString.toString());
var companyList = [];

class Home extends React.Component {
    constructor() {
        super();
        companyList = [];
        comapniesJson.companies.forEach(element => {
            companyList.push(element);
        });
    }

    rerenderComponent() {
        console.log('Rerendering the component');

    }

    render() {
        return(
            <SafeAreaView style={{flex: 1}}>
                <ScrollView>
                    {
                        companyList.map((item, key) => (
                            <ScrollCompanyIndex key={key} imageUri={'https://picsum.photos/' + (129 + Math.floor(Math.random() * 3)) + '/' + (129 + Math.floor(Math.random() * 3))} companyName={item.name} companyAddress={item.address + ', ' + item.city}/>
                        ))
                    }
                </ScrollView>
            </SafeAreaView>
        );
    }
}

export default Home;

Add.js

import React from 'react';
import {View, Text, Button} from 'react-native';
import { Actions } from 'react-native-router-flux';

class Add extends React.Component {
    render() {
        return(
            <View>
                <Button onPress={gallaryButtonPressed} title='Camera / Gallery Button' color='#841584'/>
                <Button onPress={addButton} title='Add button' color='#841584'/>
            </View>
        );
    }
}

function gallaryButtonPressed() {

}

function addButton() {

}

export default Add;

So. How can i access for example, The function rerenderComponent() that is found in Home.js,

when I click the "Add button" button that is found in Add.js that is currently linked to the function addButton() but nvm that,

Thank you very much :3

Body:
You asked a good question, i was also wondering about this but then i found the solution.

App.js

<Scene key='home' component={Home} title='Home' rightButtonImage=require('./assets/plus.png')} onRight={() => {}} />

Home.js

constructor(props) {
        super(props);
        companyList = [];
        comapniesJson.companies.forEach(element => {
            companyList.push(element);
        });
    }

    componentDidMount() {
     this.props.navigation.setParams({
     onRight: this.addButton
     });
    }

    addButton = () => {
      return <Button onPress={() => Actions.Something()} title='Add button' color='#841584'/>;
    }

Similarly you can access rerenderComponent function.


问:
How to convert int to datetime in pandas DataFrame
I have a pandas DataFrame having the following structure:

where time attribute/column represents some point in time from which measurements were taken for a particular animal, denoted by animal_id attribute. The measurements were x and y co-ordinates represented by attributes x and y respectively.

I want to convert time from int to datetime format. But when I do the following:

```<code>data['time'] = pd.to_datetime(data['time'])
</code>```

The output of:

```<code>data['time'][:10]
</code>```

is:

```<code>0   1970-01-01 00:00:00.000000001
1   1970-01-01 00:00:00.000000001
2   1970-01-01 00:00:00.000000001
3   1970-01-01 00:00:00.000000001
4   1970-01-01 00:00:00.000000001
5   1970-01-01 00:00:00.000000002
6   1970-01-01 00:00:00.000000002
7   1970-01-01 00:00:00.000000002
8   1970-01-01 00:00:00.000000002
9   1970-01-01 00:00:00.000000002
Name: time, dtype: datetime64[ns]
</code>```

How do I specify two things in this:

Starting date instead of 1970-01-01 to say 2019-05-10

Specify differences between two consecutive times from the output in above to say differences between minutes

Thanks!

Body:
I have a pandas DataFrame having the following structure:

where time attribute/column represents some point in time from which measurements were taken for a particular animal, denoted by animal_id attribute. The measurements were x and y co-ordinates represented by attributes x and y respectively.

I want to convert time from int to datetime format. But when I do the following:

data['time'] = pd.to_datetime(data['time'])

The output of:

data['time'][:10]

is:

0   1970-01-01 00:00:00.000000001
1   1970-01-01 00:00:00.000000001
2   1970-01-01 00:00:00.000000001
3   1970-01-01 00:00:00.000000001
4   1970-01-01 00:00:00.000000001
5   1970-01-01 00:00:00.000000002
6   1970-01-01 00:00:00.000000002
7   1970-01-01 00:00:00.000000002
8   1970-01-01 00:00:00.000000002
9   1970-01-01 00:00:00.000000002
Name: time, dtype: datetime64[ns]

How do I specify two things in this:

Starting date instead of 1970-01-01 to say 2019-05-10

Specify differences between two consecutive times from the output in above to say differences between minutes

Thanks!

Body:
Use to_timedelta for minutes timedeltas and add Timestamp, because for minutes to_datetime with parameter origin and unit is not implemented:

data = pd.DataFrame({'time':[1,1,2,2,3,4]})

data['time0'] = pd.to_timedelta(data['time'], unit='Min') + pd.Timestamp('2019-05-10')

data['time1'] = pd.to_datetime(data['time'], origin='2019-05-10', unit='s')
data['time2'] = pd.to_datetime(data['time'], origin='2019-05-10', unit='d')
print (data)

   time               time0               time1      time2
0     1 2019-05-10 00:01:00 2019-05-10 00:00:01 2019-05-11
1     1 2019-05-10 00:01:00 2019-05-10 00:00:01 2019-05-11
2     2 2019-05-10 00:02:00 2019-05-10 00:00:02 2019-05-12
3     2 2019-05-10 00:02:00 2019-05-10 00:00:02 2019-05-12
4     3 2019-05-10 00:03:00 2019-05-10 00:00:03 2019-05-13
5     4 2019-05-10 00:04:00 2019-05-10 00:00:04 2019-05-14

because:

data['time0'] = pd.to_datetime(data['time'], origin='2019-05-10', unit='Min')

ValueError: cannot cast unit Min