问:
Why does the sum of the Rss fields in /proc/$$/smaps differ from the 24th field in /proc/$$/stat?
From my understanding, the value returned from

```<code>(1) awk '/Rss:/{ sum += $2 } END { print sum }' /proc/$$/smaps
</code>```

and

```<code>(2) cat /proc/$$/stat | cut -d " " -f24
</code>```

should be equal, why is this not the case?

They are in fact a factor of 4 out, so (1)/4 = (2) from everything I have tested

Details of the files can be found at man 5 proc

uname -a: Linux home-server 4.4.0-78-generic #99-Ubuntu SMP Thu Apr 27 15:29:09 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

答: The rss field in the stat file is in pages. A page on most hardware will be of size 4096 bytes. Since you are comparing this with a field in kilobytes, you can easily see how you got a factor-of-4 difference: 4096 / 1024 = 4.</p>

Body:
From my understanding, the value returned from

(1) awk '/Rss:/{ sum += $2 } END { print sum }' /proc/$$/smaps

and

(2) cat /proc/$$/stat | cut -d " " -f24

should be equal, why is this not the case?

They are in fact a factor of 4 out, so (1)/4 = (2) from everything I have tested

Details of the files can be found at man 5 proc

uname -a: Linux home-server 4.4.0-78-generic #99-Ubuntu SMP Thu Apr 27 15:29:09 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux


来源: stackexchange

问:
How to know the valueChanged origin in Aurelia?
I created a custom element in Aurelia and I also have the valueChanged, however I need to do a certain action only when the value is changed outside of the custom element. Since the signature is valueChanged(newValue, oldValue), how would I know when the value gets changed from the ViewModel and not from the custom element itself? Is that doable somehow with an observer or observable?

I actually got kind of a working sample, I saw that there's also an __array_observer__ property when the value is changed from the ViewModel, and it works but it's probably not ideal. So I got this piece of code which kinda works

```<code>valueChanged(newValue, oldValue) {
  if (newValue !== oldValue && newValue.__array_observer__) {
    // value got changed outside of this custom element
  }
}
</code>```

This is probably not ideal though, or is it? Any other suggestion in knowing where the value got changed outside of the custom element?

EDIT

As much as possible, I'm looking for a solution that will still have access to the custom element. Even if I want to get triggered by an external value change call, I still need to call an internal function of the same custom element.

EDIT #2

To give a little more description of my issue, I need to know when the value got changed from the outside because this will trigger an action that will re-affect the value. Without knowing if the change was from the outside of the custom element, I fall in a recursive call with no way to stop it. What I'm looking for is similar to what used to be the caller and the callee but this was removed with ES5 and Strict Mode, however this would have been very useful.

Still looking for an answer :(

答:
You could use a CustomBindingBehavior to intercept the updateTarget event. For instance:

```<code>export class InterceptBindingBehavior {
  bind(binding, scope, interceptor) {
    binding['originalUpdateTarget'] = binding['updateTarget'];
    binding.updateTarget = val => {
      alert('property was changed outside of the element');
      //do something here
      binding['originalUpdateTarget'](val);
    }
  }

  unbind(binding, scope) {
    binding.updateTarget = binding['originalUpdateTarget'];
    binding['originalUpdateTarget'] = null;
  }
}
</code>```

Usage:

```<code><template>
  <require from="./intercept-binding-behavior"></require>

  <some-element value.bind="message & intercept"></some-element>
</template>
</code>```

Runnable example: https://gist.run/?id=bcd7d39ed94856caf586f224f89fd1ff

I haven't tested this in many cases and I'm not sure if it's best way.

If you want to do the opposite (intercept when the property is changed from the element instead of the VM) just replace updateTarget for updateSource.

More info about CustomBindingBehaviors http://aurelia.io/hub.html#/doc/article/aurelia/binding/latest/binding-binding-behaviors/8

Hope this helps!

ContentLicense: CC BY-SA 3.0

Body:
I created a custom element in Aurelia and I also have the valueChanged, however I need to do a certain action only when the value is changed outside of the custom element. Since the signature is valueChanged(newValue, oldValue), how would I know when the value gets changed from the ViewModel and not from the custom element itself? Is that doable somehow with an observer or observable?

I actually got kind of a working sample, I saw that there's also an __array_observer__ property when the value is changed from the ViewModel, and it works but it's probably not ideal. So I got this piece of code which kinda works

valueChanged(newValue, oldValue) {
  if (newValue !== oldValue && newValue.__array_observer__) {
    // value got changed outside of this custom element
  }
}

This is probably not ideal though, or is it? Any other suggestion in knowing where the value got changed outside of the custom element?

EDIT

As much as possible, I'm looking for a solution that will still have access to the custom element. Even if I want to get triggered by an external value change call, I still need to call an internal function of the same custom element.

EDIT #2

To give a little more description of my issue, I need to know when the value got changed from the outside because this will trigger an action that will re-affect the value. Without knowing if the change was from the outside of the custom element, I fall in a recursive call with no way to stop it. What I'm looking for is similar to what used to be the caller and the callee but this was removed with ES5 and Strict Mode, however this would have been very useful.

Still looking for an answer :(

Body:
You could use a CustomBindingBehavior to intercept the updateTarget event. For instance:

export class InterceptBindingBehavior {
  bind(binding, scope, interceptor) {
    binding['originalUpdateTarget'] = binding['updateTarget'];
    binding.updateTarget = val => {
      alert('property was changed outside of the element');
      //do something here
      binding['originalUpdateTarget'](val);
    }
  }

  unbind(binding, scope) {
    binding.updateTarget = binding['originalUpdateTarget'];
    binding['originalUpdateTarget'] = null;
  }
}

Usage:

<template>
  <require from="./intercept-binding-behavior"></require>

  <some-element value.bind="message & intercept"></some-element>
</template>

Runnable example: https://gist.run/?id=bcd7d39ed94856caf586f224f89fd1ff

I haven't tested this in many cases and I'm not sure if it's best way.

If you want to do the opposite (intercept when the property is changed from the element instead of the VM) just replace updateTarget for updateSource.

More info about CustomBindingBehaviors http://aurelia.io/hub.html#/doc/article/aurelia/binding/latest/binding-binding-behaviors/8

Hope this helps!


问:
how to shutdown/stop scheduler after a specific time
I am creating a job which should run after every 10 seconds for next 2 hours, how can I do that? </p>

```<code>from apscheduler.schedulers.blocking import BlockingScheduler

sched = BlockingScheduler()
@sched.scheduled_job('interval', seconds=10)
  def timed_job():
     print('This job is run every 10 seconds.')
sched.start()
</code>```

<p>How can I stop this scheduled job to stop after 2 hours? </p>

答: You could use the time built-in module. You can do start_time = time.time() to get the start time. Then do a boolean test before running your code of if time.time()-start_time < 7200 and then your code. Otherwise it would cancel. Then your code will continue to run until 7200 seconds(2 hours) has passed.

Body:
I am creating a job which should run after every 10 seconds for next 2 hours, how can I do that?

from apscheduler.schedulers.blocking import BlockingScheduler

sched = BlockingScheduler()
@sched.scheduled_job('interval', seconds=10)
  def timed_job():
     print('This job is run every 10 seconds.')
sched.start()

How can I stop this scheduled job to stop after 2 hours?


问:
How can I run IE with different users and specify a url?
I'm trying to create a console application to replace a batch file. The batch file prompted for a user and ran the following code...

RUNAS /user:USA\%usr% "C:\Program Files\Internet Explorer\iexplore.exe %ServerPath%/%AppName%"

How can I translate this to C# code? I'm basically using the code below. I declare a User Name and a Path, but it always launches IE with my windows login. Am I using Verb incorrectly? Do I need to include a password, and if so, how?

```<code>string sPath = ServerPath
ProcessStartInfo startInfo = new ProcessStartInfo(@"C:\Program Files\Internet Explorer\iexplore.exe");
startInfo.Verb = @"runas /user:USA\" + sUser;
startInfo.Arguments = sPath;
startInfo.UseShellExecute = false;
Process.Start(startInfo);
</code>```

答:
```<code>function SecureString MakeSecureString(string text)
{
  SecureString secure = new SecureString();
  foreach (char c in text)
  {
    secure.AppendChar(c);
  }

  return secure;
}

function void RunAs(string path, string username, string password)
{
  ProcessStartInfo myProcess = new ProcessStartInfo(path);
  myProcess.UserName = username;
  myProcess.Password = MakeSecureString(password);
  myProcess.UseShellExecute = false;
  Process.Start(myProcess);
}

RunAs(APPLICATION, USERNAME, PASSWORD);
</code>```

Props to fraser chapman's blog

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to create a console application to replace a batch file. The batch file prompted for a user and ran the following code...

RUNAS /user:USA\%usr% "C:\Program Files\Internet Explorer\iexplore.exe %ServerPath%/%AppName%"

How can I translate this to C# code? I'm basically using the code below. I declare a User Name and a Path, but it always launches IE with my windows login. Am I using Verb incorrectly? Do I need to include a password, and if so, how?

string sPath = ServerPath
ProcessStartInfo startInfo = new ProcessStartInfo(@"C:\Program Files\Internet Explorer\iexplore.exe");
startInfo.Verb = @"runas /user:USA\" + sUser;
startInfo.Arguments = sPath;
startInfo.UseShellExecute = false;
Process.Start(startInfo);

Body:
function SecureString MakeSecureString(string text)
{
  SecureString secure = new SecureString();
  foreach (char c in text)
  {
    secure.AppendChar(c);
  }

  return secure;
}

function void RunAs(string path, string username, string password)
{
  ProcessStartInfo myProcess = new ProcessStartInfo(path);
  myProcess.UserName = username;
  myProcess.Password = MakeSecureString(password);
  myProcess.UseShellExecute = false;
  Process.Start(myProcess);
}

RunAs(APPLICATION, USERNAME, PASSWORD);

Props to fraser chapman's blog


问:
How do I update records in sql using other records as values?
MS SQL Server 2008 -
I have a db table where I have a small subset of rows that have a near match, save for 2 columns, elsewhere in the table.  How would you structure a SQL update loop to go through the subset (record1) and search for its matching counterpart (record2) and then copy a value from a column (record2.columnX) to update the other(record1.columnX)?

Before:

```<code>TxID|RecordID|ColumnA|ColumnX|ColumnY
1   |111.222 |ggg    |1234   |subset1
2   |111.222 |ggg    |3456   |subset2
3   |111.333 |hhh    |6789   |subset1
4   |111.333 |hhh    |7890   |subset2
5   |111.444 |jjj    |2345   |subset1
5   |111.444 |jjj    |5678   |subset2
</code>```

After:

```<code>TxID|RecordID|ColumnA|ColumnX|ColumnY
1   |111.222 |ggg    |1234   |subset1
2   |111.222 |ggg    |1234   |subset2
3   |111.333 |hhh    |6789   |subset1
4   |111.333 |hhh    |6789   |subset2
5   |111.444 |jjj    |2345   |subset1
5   |111.444 |jjj    |2345   |subset2
</code>```

Self-taught, relatively new to SQL.  Patience is appreciated.

答:
I would do something like:    </p>

```<code>UPDATE table t1 SET columnX=sq.columnXmin
FROM  (
   SELECT t2.RecordID, MIN(t2.columnX) as columnXmin
   FROM   table t2
   GROUP  BY t2.RecordID
   ) AS sq
WHERE  t1.RecordID = sq.RecordID;
</code>```

Body:
MS SQL Server 2008 -
I have a db table where I have a small subset of rows that have a near match, save for 2 columns, elsewhere in the table.  How would you structure a SQL update loop to go through the subset (record1) and search for its matching counterpart (record2) and then copy a value from a column (record2.columnX) to update the other(record1.columnX)?

Before:

TxID|RecordID|ColumnA|ColumnX|ColumnY
1   |111.222 |ggg    |1234   |subset1
2   |111.222 |ggg    |3456   |subset2
3   |111.333 |hhh    |6789   |subset1
4   |111.333 |hhh    |7890   |subset2
5   |111.444 |jjj    |2345   |subset1
5   |111.444 |jjj    |5678   |subset2

After:

TxID|RecordID|ColumnA|ColumnX|ColumnY
1   |111.222 |ggg    |1234   |subset1
2   |111.222 |ggg    |1234   |subset2
3   |111.333 |hhh    |6789   |subset1
4   |111.333 |hhh    |6789   |subset2
5   |111.444 |jjj    |2345   |subset1
5   |111.444 |jjj    |2345   |subset2

Self-taught, relatively new to SQL.  Patience is appreciated.

Body:
I would do something like:

UPDATE table t1 SET columnX=sq.columnXmin
FROM  (
   SELECT t2.RecordID, MIN(t2.columnX) as columnXmin
   FROM   table t2
   GROUP  BY t2.RecordID
   ) AS sq
WHERE  t1.RecordID = sq.RecordID;


问:
Difficulty with Inventory and Room system in a text based game
I'm a fairly new programmer, been struggling for a few years on and off with brief exposure to a few languages. I'm trying to finally get a firm grasp with Python, and to do so my current project is to design a simple text based game like "Zork".

I've successfully made an EXTREMELY simple version of this using functions for each room, however this isn't generalizable at all. Before I explain what I'm currently working on poorly, I'll link the code. Now as you can see, this is a very inefficient way of building rooms as it requires tons of code and I can't use it for anything except this exact game.

To start I created a list to be used as the player inventory

```<code>    inventory = []

def addToInventory(item):
    inventory.append(item)
</code>```

This is the class I am using to construct weapons, and is where my trouble starts. The class works fine, and I can even add instances of it to my inventory list successfully.

```<code>class Weapon:

    def __init__(self, name, damage, speed, weight):
        self.name = name
        self.damage = damage
        self.speed = speed
        self.weight = weight

sword = Weapon("Sword", 7, 5, 5)
knife = Weapon("Knife", 5, 7, 3)
stick = Weapon("Stick", 2, 3, 3)
</code>```

This is the class I am attempting to design to create rooms. It has not been implemented yet. Right now the issue that I'm facing is that unable to add instances of the Weapon class to the argument for Roominv. So for example, I could not use the sword instance of my weapon class as an argument for the contents of a Room, it tells me that sword is undefined.

```<code>Entrance = Room("You are at an entrance", "N", "Search the ground", sword)
</code>```

Now my goal with this project really is to learn, so I don't want any code, but am I going down the right path with this? How can I tie certain instances of the weapons class to certain rooms?  Should I be using dictionaries to build the rooms instead? If I SHOULD be using dictionaries, do I have to create an individual dictionary for each room or are nested dictionaries a thing?

I've searched a lot for the answers to these as I'm sure similar questions have been asked, but I can't seem to find a straight answer.

```<code>class Room:

def __init__(self, description, exits, actions, Roominv): #Runs every time a new room is created
    self.description = description
    self.exits = exits
    self.actions = actions
    self.Roominv = Roominv

def GAMEOVER():
    print("Oh no, it appears you have died. Press 1 to restart")

    choice = input(">>> ")

    if choice == "1":
        intro()

def introstrt():
    print("WELCOME TO FLUBBO'S MAGIC FOREST! HAVE YOU EVER WONDERED WHAT IT WAS LIKE TO")
    print("PLAY A VIDEO GAME THAT MORE OR LESS RELIES ENTIRELY ON IMAGINATION?")
    print("THEN LOOK NO FURTHER!")
    print("BEFORE YOU BEGIN, BE FOREWARNED THAT THIS ADVENTURE WILL BE VIOLENT, CRUDE,")
    print("AND ALSO VERY POOR QUALITY OVERALL, BECAUSE CLEARLY")
    print("THE DEVELOPER IS A TALENTLESS HACK WITH NO BUSINESS BEHIND A KEYBOARD.")
    print("AND NOW, FOR YOUR PLEASURE, FLUBBO'S MAGIC FOREST!!")
    print("  A     A     A      A     ooo")
    print(" vvv   vvv   vvv    vvv   ooooo")
    print("vvvvv vvvvv vvvvv  vvvvv   ooo")
    print("  H     H     H      H")
    print("  A     A     A      A")
    print(" vvv   vvv   vvv    vvv    | O  __")
    print("vvvvv vvvvv vvvvv  vvvvv   +-|-(__) ")
    print("  H     H     H      H      / \ ")
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    print("PRESS 1 TO BEGIN")

    choice = input(">>> ")

    if choice == "1":
        intro()
    else:
        print("I can't understand that command")
        intro()

def intro():
    global inventory
    print("You are in a forest, you can hear wildlife all around you. Your sword lies at your feet. There seems to be a clearing in the distance.")
    print("You can:")
    print("1.Look for sticks")
    print("2. Do a backflip")
    print("3.Attempt to befriend wildlife")
    print("4.Go to Clearing ")
    print("5.View Intro")

    choice = input(">>> ")

if choice == "1":
    print("You don't find any sticks. This is a poorly designed forest.")
    intro()
elif choice == "2":
    print("Sweet backflip, what now?")
    intro()
elif choice == "3":
    print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death.")
    print("GAME OVER.")
    GAMEOVER()
elif choice == "4":
    print("You move towards the clearing.")
    clearing()
elif choice == "Pick up sword":
    addToInventory(sword)
    print("Your bag contains", inventory)
    intro()
elif choice == "5":
    introstrt()
else:
    print("I can't understand that command")
    intro()
def clearing():
    print("You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.")
    print("You can:")
    print("1.Pick the flower")
    print("2.Go towards the harp")
    print("3.Curse the sun whilst masturbating vigorously")
    print("4.Go back")

    choice = input(">>> ")

    if choice == "1":
        print("You pick the white flower and put it in your bag. You notice that it glows slightly.")
        clearingnofl()
    elif choice == "2":
        print("You can't tell which direction the music is coming from!.")
        clearing()
    elif choice == "3":
        print("CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.")
        print("The sun is deeply offended and goes away. It is dark now.")
        clearingdrk()
    elif choice == "4":
        print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
        intro()
    else:
        print("I can't understand that command")
    clearing()

def clearingnofl():
    print("You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating the center of the clearing. In the distance a harp can be heard.")
    print("You can:")
    print("1.Go towards the harp")
    print("2.Curse the sun whilst masturbating vigorously")
    print("3.Go back")

    choice = input(">>> ")

    if choice == "1":
        print("You can't tell which direction the music is coming from!.")
        clearingnofl()
    elif choice == "2":
        print("CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.")
        print("The sun is deeply offended and goes away. It is dark now.")
        print("You notice the flower glowing brightly in your bag.")
        clearingnofldrk()
    elif choice == "3":
         print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
        intronofl()
    else:
        print("I can't understand that command")
        clearingnofl()
def clearingdrk():
    print("You are in a clearing surrounded by forest. Moonlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.")
    print("You can:")
    print("1.Pick the flower")
    print("2.Go towards the harp")
    print("3.Apologize to the sun, promise that you'll change and things will be like they used to be.")
    print("4.Go back")

    choice = input(">>> ")

    if choice == "1":
        print("You pick the white flower and put it in your bag. You notice that it glows brightly in the dark.")
        clearingnofldrk()
    elif choice == "2":
        print("You can't tell which direction the music is coming from!.")
        clearingdrk()
    elif choice == "3":
        print("The sun reluctantly forgives you, it is sunny again.")
        clearing()
    elif choice == "4":
        print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
        introdrk()
    else:
        print("I can't understand that command")
        clearingdrk()
def clearingnofldrk():
    print("You are in a clearing surrounded by forest. Moonlight is streaming in, illuminating the center of the clearing. In the distance a harp can be heard.")
    print("You can:")
    print("1.Go towards the harp")
    print("2.Apologize to the sun, promise that you'll change and things will be like they used to be.")
   print("3.Go back")

    choice = input(">>> ")

    if choice == "1":
        print("You can't tell which direction the music is coming from!.")
        clearingnofldrk()
    elif choice == "2":
        print("The sun reluctantly forgives you, it is sunny again.")
    clearingnofl()
    elif choice == "3":
        print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
        intronofldrk()
    else:
        print("I can't understand that command")
        clearingnofldrk()
def intronofldrk():
    print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
    print("You can:")
    print("1.Look for sticks")
    print("2.Do a backflip")
    print("3.Attempt to befriend wildlife")
    print("4.Go to Clearing ")

    choice = input(">>> ")

    if choice == "1":
        print("You don't find any sticks. This is a poorly designed forest AND it's dark now.")
        intronofldrk()
    elif choice == "2":
        print("Sweet backflip, what now?")
        intronofldrk()
    elif choice == "3":
        print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
    elif choice == "4":
        print("You move towards the clearing.")
        clearingnofldrk()
    else:
        print("I can't understand that command")
        intronofldrk()
def introdrk():
    print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
    print("You can:")
    print("1.Look for sticks")
    print("2.Do a backflip")
    print("3.Attempt to befriend wildlife")
    print("4.Go to Clearing ")

    choice = input(">>> ")

    if choice == "1":
        print("You don't find any sticks. This is a poorly designed forest AND it's dark now.")
        introdrk()
    elif choice == "2":
        print("Sweet backflip, what now?")
        introdrk()
    elif choice == "3":
        print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
    elif choice == "4":
        print("You move towards the clearing.")
        clearingdrk()
    else:
        print("I can't understand that command")
    introdrk()
def intronofl():
    print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
    print("You can:")
    print("1.Look for sticks")
    print("2.Do a backflip")
    print("3.Attempt to befriend wildlife")
    print("4.Go to Clearing ")

    choice = input(">>> ")

    if choice == "1":
        print("You don't find any sticks. This is a poorly designed forest.")
        intronofl()
    elif choice == "2":
        print("Sweet backflip, what now?")
        intronofl()
    elif choice == "3":
        print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
    elif choice == "4":
        print("You move towards the clearing.")
        clearingnofl()
    else:
        print("I can't understand that command")
        intronofl()
introstrt()
</code>```

答:
I would start by adding more structure, separating the definition of the rooms from the IO/action evaluation.

In terms of maintining state, one possibility (using introSword as an example) is to modify the containing Room within the action, changing the available future actions.

You'd have to change the input and output definitions for Python 3. Hopefully those are the only changes needed.

```<code>import traceback as tb

try:
  input = raw_input

  def output(*args):
    print ''.join(map(str,args))

  inventory = []

  class Weapon:
    def __init__(self, name, damage, speed, weight):
      self.name = name
      self.damage = damage
      self.speed = speed
      self.weight = weight

    def __repr__(self):
      return self.name

  sword = Weapon("Sword", 7, 5, 5)
  knife = Weapon("Knife", 5, 7, 3)
  stick = Weapon("Stick", 2, 3, 3)

  class Room:
    def __init__(self,description,exits,actions,others=[]):
      self.description = description
      self.exits = exits
      self.actions = actions
      self.others = others

    def render(self):
      output(self.description)

      if self.actions:
        output('You can:')
        for id,name,_ in self.actions:
          output(id,'. ',name)

      choice = input('>>> ').upper()

      for id,_,action in self.actions:
        if choice == id.upper():
          action(self)
          break
      else:
        for id,action in self.others:
          if choice == id.upper():
            action(self)
            break
        else:
          output('I can\'t understand that command')
          self.render()

  quit = False

  while not quit:
    def introstrtBegin(room):
      intro.render()

    introstrt = Room(
      '''
WELCOME TO FLUBBO'S MAGIC FOREST! HAVE YOU EVER WONDERED WHAT IT WAS LIKE TO
PLAY A VIDEO GAME THAT MORE OR LESS RELIES ENTIRELY ON IMAGINATION?
THEN LOOK NO FURTHER!
BEFORE YOU BEGIN, BE FOREWARNED THAT THIS ADVENTURE WILL BE VIOLENT, CRUDE,
AND ALSO VERY POOR QUALITY OVERALL, BECAUSE CLEARLY
THE DEVELOPER IS A TALENTLESS HACK WITH NO BUSINESS BEHIND A KEYBOARD.
AND NOW, FOR YOUR PLEASURE, FLUBBO'S MAGIC FOREST!!
  A     A     A      A     ooo
 vvv   vvv   vvv    vvv   ooooo
vvvvv vvvvv vvvvv  vvvvv   ooo
  H     H     H      H
  A     A     A      A
 vvv   vvv   vvv    vvv    | O  __
vvvvv vvvvv vvvvv  vvvvv   +-|-(__)
  H     H     H      H      / \
~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~
PRESS 1 TO BEGIN
      ''',
      [],
      [],
      [('1',introstrtBegin)]
    )

    def gameoverRestart(_):
      global quit
      quit = False

    def gameoverQuit(_):
      global quit
      quit = True

    gameover = Room(
      'Oh no, it appears you have died. Press 1 to restart, or 2 to quit.',
      [],
      [],
      [('1',gameoverRestart)
      ,('2',gameoverQuit)
      ]
    )

    def introSticks(room):
      output('You don\'t find any sticks. This is a poorly designed forest.')
      room.render()

    def introBackflip(room):
      output('Sweet backflip, what now?')
      room.render()

    def introWildlife(room):
      output('Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death.')
      output('GAME OVER.')
      gameover.render()

    def introClearing(room):
      output('You move towards the clearing.')
      clearing.render()

    def introNoSword(room):
      output('You already picked up the sword')
      room.render()

    def introSword(room):
      global inventory
      inventory.append(sword)
      output('Your bag contains: ',inventory)

      room.description = 'You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.'
      room.others = [
        ('pick up sword',introNoSword)
      ]

      room.render()

    intro = Room(
      '''
You are in a forest, you can hear wildlife all around you. Your sword lies at your feet. There seems to be a clearing in the distance.
      ''',
      [],
      [('1','Look for sticks',introSticks)
      ,('2','Do a backflip',introBackflip)
      ,('3','Attempt to befriend wildlife',introWildlife)
      ,('4','Go to Clearing',introClearing)
      ,('5','View Intro',lambda _: introstrt.render())
      ],
      [('pick up sword',introSword)]
    )

    def clearingFlower(room):
      output('You pick the white flower and put it in your bag. You notice that it glows slightly.')
      room.render()

    def clearingHarp(room):
      output('You can\'t tell which direction the music is coming from!.')
      room.render()

    def clearingCurse(room):
      output('CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.')
      output('The sun is deeply offended and goes away. It is dark now.')
      room.render()

    def clearingBack(room):
      output('You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.')
      intro.render()

    clearing = Room(
      '''
You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.
      ''',
      [],
      [('1','Pick the flower',clearingFlower)
      ,('2','Go towards the harp',clearingHarp)
      ,('3','Curse the sun whilst masturbating vigorously',clearingCurse)
      ,('4','Go back',clearingBack)
      ]
    )

    introstrt.render()
except:
  tb.print_exc()
finally:
  input('#')
</code>```

Body:
I'm a fairly new programmer, been struggling for a few years on and off with brief exposure to a few languages. I'm trying to finally get a firm grasp with Python, and to do so my current project is to design a simple text based game like "Zork".

I've successfully made an EXTREMELY simple version of this using functions for each room, however this isn't generalizable at all. Before I explain what I'm currently working on poorly, I'll link the code. Now as you can see, this is a very inefficient way of building rooms as it requires tons of code and I can't use it for anything except this exact game.

To start I created a list to be used as the player inventory

    inventory = []

def addToInventory(item):
    inventory.append(item)

This is the class I am using to construct weapons, and is where my trouble starts. The class works fine, and I can even add instances of it to my inventory list successfully.

class Weapon:

    def __init__(self, name, damage, speed, weight):
        self.name = name
        self.damage = damage
        self.speed = speed
        self.weight = weight

sword = Weapon("Sword", 7, 5, 5)
knife = Weapon("Knife", 5, 7, 3)
stick = Weapon("Stick", 2, 3, 3)

This is the class I am attempting to design to create rooms. It has not been implemented yet. Right now the issue that I'm facing is that unable to add instances of the Weapon class to the argument for Roominv. So for example, I could not use the sword instance of my weapon class as an argument for the contents of a Room, it tells me that sword is undefined.

Entrance = Room("You are at an entrance", "N", "Search the ground", sword)

Now my goal with this project really is to learn, so I don't want any code, but am I going down the right path with this? How can I tie certain instances of the weapons class to certain rooms?  Should I be using dictionaries to build the rooms instead? If I SHOULD be using dictionaries, do I have to create an individual dictionary for each room or are nested dictionaries a thing?

I've searched a lot for the answers to these as I'm sure similar questions have been asked, but I can't seem to find a straight answer.

class Room:

def __init__(self, description, exits, actions, Roominv): #Runs every time a new room is created
    self.description = description
    self.exits = exits
    self.actions = actions
    self.Roominv = Roominv

def GAMEOVER():
    print("Oh no, it appears you have died. Press 1 to restart")

    choice = input(">>> ")

    if choice == "1":
        intro()

def introstrt():
    print("WELCOME TO FLUBBO'S MAGIC FOREST! HAVE YOU EVER WONDERED WHAT IT WAS LIKE TO")
    print("PLAY A VIDEO GAME THAT MORE OR LESS RELIES ENTIRELY ON IMAGINATION?")
    print("THEN LOOK NO FURTHER!")
    print("BEFORE YOU BEGIN, BE FOREWARNED THAT THIS ADVENTURE WILL BE VIOLENT, CRUDE,")
    print("AND ALSO VERY POOR QUALITY OVERALL, BECAUSE CLEARLY")
    print("THE DEVELOPER IS A TALENTLESS HACK WITH NO BUSINESS BEHIND A KEYBOARD.")
    print("AND NOW, FOR YOUR PLEASURE, FLUBBO'S MAGIC FOREST!!")
    print("  A     A     A      A     ooo")
    print(" vvv   vvv   vvv    vvv   ooooo")
    print("vvvvv vvvvv vvvvv  vvvvv   ooo")
    print("  H     H     H      H")
    print("  A     A     A      A")
    print(" vvv   vvv   vvv    vvv    | O  __")
    print("vvvvv vvvvv vvvvv  vvvvv   +-|-(__) ")
    print("  H     H     H      H      / \ ")
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~")
    print("~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    print("PRESS 1 TO BEGIN")

    choice = input(">>> ")

    if choice == "1":
        intro()
    else:
        print("I can't understand that command")
        intro()

def intro():
    global inventory
    print("You are in a forest, you can hear wildlife all around you. Your sword lies at your feet. There seems to be a clearing in the distance.")
    print("You can:")
    print("1.Look for sticks")
    print("2. Do a backflip")
    print("3.Attempt to befriend wildlife")
    print("4.Go to Clearing ")
    print("5.View Intro")

    choice = input(">>> ")

if choice == "1":
    print("You don't find any sticks. This is a poorly designed forest.")
    intro()
elif choice == "2":
    print("Sweet backflip, what now?")
    intro()
elif choice == "3":
    print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death.")
    print("GAME OVER.")
    GAMEOVER()
elif choice == "4":
    print("You move towards the clearing.")
    clearing()
elif choice == "Pick up sword":
    addToInventory(sword)
    print("Your bag contains", inventory)
    intro()
elif choice == "5":
    introstrt()
else:
    print("I can't understand that command")
    intro()
def clearing():
    print("You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.")
    print("You can:")
    print("1.Pick the flower")
    print("2.Go towards the harp")
    print("3.Curse the sun whilst masturbating vigorously")
    print("4.Go back")

    choice = input(">>> ")

    if choice == "1":
        print("You pick the white flower and put it in your bag. You notice that it glows slightly.")
        clearingnofl()
    elif choice == "2":
        print("You can't tell which direction the music is coming from!.")
        clearing()
    elif choice == "3":
        print("CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.")
        print("The sun is deeply offended and goes away. It is dark now.")
        clearingdrk()
    elif choice == "4":
        print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
        intro()
    else:
        print("I can't understand that command")
    clearing()

def clearingnofl():
    print("You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating the center of the clearing. In the distance a harp can be heard.")
    print("You can:")
    print("1.Go towards the harp")
    print("2.Curse the sun whilst masturbating vigorously")
    print("3.Go back")

    choice = input(">>> ")

    if choice == "1":
        print("You can't tell which direction the music is coming from!.")
        clearingnofl()
    elif choice == "2":
        print("CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.")
        print("The sun is deeply offended and goes away. It is dark now.")
        print("You notice the flower glowing brightly in your bag.")
        clearingnofldrk()
    elif choice == "3":
         print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
        intronofl()
    else:
        print("I can't understand that command")
        clearingnofl()
def clearingdrk():
    print("You are in a clearing surrounded by forest. Moonlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.")
    print("You can:")
    print("1.Pick the flower")
    print("2.Go towards the harp")
    print("3.Apologize to the sun, promise that you'll change and things will be like they used to be.")
    print("4.Go back")

    choice = input(">>> ")

    if choice == "1":
        print("You pick the white flower and put it in your bag. You notice that it glows brightly in the dark.")
        clearingnofldrk()
    elif choice == "2":
        print("You can't tell which direction the music is coming from!.")
        clearingdrk()
    elif choice == "3":
        print("The sun reluctantly forgives you, it is sunny again.")
        clearing()
    elif choice == "4":
        print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
        introdrk()
    else:
        print("I can't understand that command")
        clearingdrk()
def clearingnofldrk():
    print("You are in a clearing surrounded by forest. Moonlight is streaming in, illuminating the center of the clearing. In the distance a harp can be heard.")
    print("You can:")
    print("1.Go towards the harp")
    print("2.Apologize to the sun, promise that you'll change and things will be like they used to be.")
   print("3.Go back")

    choice = input(">>> ")

    if choice == "1":
        print("You can't tell which direction the music is coming from!.")
        clearingnofldrk()
    elif choice == "2":
        print("The sun reluctantly forgives you, it is sunny again.")
    clearingnofl()
    elif choice == "3":
        print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
        intronofldrk()
    else:
        print("I can't understand that command")
        clearingnofldrk()
def intronofldrk():
    print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
    print("You can:")
    print("1.Look for sticks")
    print("2.Do a backflip")
    print("3.Attempt to befriend wildlife")
    print("4.Go to Clearing ")

    choice = input(">>> ")

    if choice == "1":
        print("You don't find any sticks. This is a poorly designed forest AND it's dark now.")
        intronofldrk()
    elif choice == "2":
        print("Sweet backflip, what now?")
        intronofldrk()
    elif choice == "3":
        print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
    elif choice == "4":
        print("You move towards the clearing.")
        clearingnofldrk()
    else:
        print("I can't understand that command")
        intronofldrk()
def introdrk():
    print("You are in a forest, you can hear wildlife all around you. It is dark. There seems to be a clearing in the distance.")
    print("You can:")
    print("1.Look for sticks")
    print("2.Do a backflip")
    print("3.Attempt to befriend wildlife")
    print("4.Go to Clearing ")

    choice = input(">>> ")

    if choice == "1":
        print("You don't find any sticks. This is a poorly designed forest AND it's dark now.")
        introdrk()
    elif choice == "2":
        print("Sweet backflip, what now?")
        introdrk()
    elif choice == "3":
        print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
    elif choice == "4":
        print("You move towards the clearing.")
        clearingdrk()
    else:
        print("I can't understand that command")
    introdrk()
def intronofl():
    print("You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.")
    print("You can:")
    print("1.Look for sticks")
    print("2.Do a backflip")
    print("3.Attempt to befriend wildlife")
    print("4.Go to Clearing ")

    choice = input(">>> ")

    if choice == "1":
        print("You don't find any sticks. This is a poorly designed forest.")
        intronofl()
    elif choice == "2":
        print("Sweet backflip, what now?")
        intronofl()
    elif choice == "3":
        print("Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death. GAME OVER.")
    elif choice == "4":
        print("You move towards the clearing.")
        clearingnofl()
    else:
        print("I can't understand that command")
        intronofl()
introstrt()

Body:
I would start by adding more structure, separating the definition of the rooms from the IO/action evaluation.

In terms of maintining state, one possibility (using introSword as an example) is to modify the containing Room within the action, changing the available future actions.

You'd have to change the input and output definitions for Python 3. Hopefully those are the only changes needed.

import traceback as tb

try:
  input = raw_input

  def output(*args):
    print ''.join(map(str,args))

  inventory = []

  class Weapon:
    def __init__(self, name, damage, speed, weight):
      self.name = name
      self.damage = damage
      self.speed = speed
      self.weight = weight

    def __repr__(self):
      return self.name

  sword = Weapon("Sword", 7, 5, 5)
  knife = Weapon("Knife", 5, 7, 3)
  stick = Weapon("Stick", 2, 3, 3)

  class Room:
    def __init__(self,description,exits,actions,others=[]):
      self.description = description
      self.exits = exits
      self.actions = actions
      self.others = others

    def render(self):
      output(self.description)

      if self.actions:
        output('You can:')
        for id,name,_ in self.actions:
          output(id,'. ',name)

      choice = input('>>> ').upper()

      for id,_,action in self.actions:
        if choice == id.upper():
          action(self)
          break
      else:
        for id,action in self.others:
          if choice == id.upper():
            action(self)
            break
        else:
          output('I can\'t understand that command')
          self.render()

  quit = False

  while not quit:
    def introstrtBegin(room):
      intro.render()

    introstrt = Room(
      '''
WELCOME TO FLUBBO'S MAGIC FOREST! HAVE YOU EVER WONDERED WHAT IT WAS LIKE TO
PLAY A VIDEO GAME THAT MORE OR LESS RELIES ENTIRELY ON IMAGINATION?
THEN LOOK NO FURTHER!
BEFORE YOU BEGIN, BE FOREWARNED THAT THIS ADVENTURE WILL BE VIOLENT, CRUDE,
AND ALSO VERY POOR QUALITY OVERALL, BECAUSE CLEARLY
THE DEVELOPER IS A TALENTLESS HACK WITH NO BUSINESS BEHIND A KEYBOARD.
AND NOW, FOR YOUR PLEASURE, FLUBBO'S MAGIC FOREST!!
  A     A     A      A     ooo
 vvv   vvv   vvv    vvv   ooooo
vvvvv vvvvv vvvvv  vvvvv   ooo
  H     H     H      H
  A     A     A      A
 vvv   vvv   vvv    vvv    | O  __
vvvvv vvvvv vvvvv  vvvvv   +-|-(__)
  H     H     H      H      / \
~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~
PRESS 1 TO BEGIN
      ''',
      [],
      [],
      [('1',introstrtBegin)]
    )

    def gameoverRestart(_):
      global quit
      quit = False

    def gameoverQuit(_):
      global quit
      quit = True

    gameover = Room(
      'Oh no, it appears you have died. Press 1 to restart, or 2 to quit.',
      [],
      [],
      [('1',gameoverRestart)
      ,('2',gameoverQuit)
      ]
    )

    def introSticks(room):
      output('You don\'t find any sticks. This is a poorly designed forest.')
      room.render()

    def introBackflip(room):
      output('Sweet backflip, what now?')
      room.render()

    def introWildlife(room):
      output('Attempting to befriend what you believe to be a cuddly critter in a nearby bush, you are surprised as a bear appears to your left and mauls you to death.')
      output('GAME OVER.')
      gameover.render()

    def introClearing(room):
      output('You move towards the clearing.')
      clearing.render()

    def introNoSword(room):
      output('You already picked up the sword')
      room.render()

    def introSword(room):
      global inventory
      inventory.append(sword)
      output('Your bag contains: ',inventory)

      room.description = 'You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.'
      room.others = [
        ('pick up sword',introNoSword)
      ]

      room.render()

    intro = Room(
      '''
You are in a forest, you can hear wildlife all around you. Your sword lies at your feet. There seems to be a clearing in the distance.
      ''',
      [],
      [('1','Look for sticks',introSticks)
      ,('2','Do a backflip',introBackflip)
      ,('3','Attempt to befriend wildlife',introWildlife)
      ,('4','Go to Clearing',introClearing)
      ,('5','View Intro',lambda _: introstrt.render())
      ],
      [('pick up sword',introSword)]
    )

    def clearingFlower(room):
      output('You pick the white flower and put it in your bag. You notice that it glows slightly.')
      room.render()

    def clearingHarp(room):
      output('You can\'t tell which direction the music is coming from!.')
      room.render()

    def clearingCurse(room):
      output('CURSE YOU FIERY BALL OF SATAN!!! You below with fury as you cum all over the clearing.')
      output('The sun is deeply offended and goes away. It is dark now.')
      room.render()

    def clearingBack(room):
      output('You are in a forest, you can hear wildlife all around you. There seems to be a clearing in the distance.')
      intro.render()

    clearing = Room(
      '''
You are in a clearing surrounded by forest. Sunlight is streaming in, illuminating a bright white flower in the center of the clearing. In the distance a harp can be heard.
      ''',
      [],
      [('1','Pick the flower',clearingFlower)
      ,('2','Go towards the harp',clearingHarp)
      ,('3','Curse the sun whilst masturbating vigorously',clearingCurse)
      ,('4','Go back',clearingBack)
      ]
    )

    introstrt.render()
except:
  tb.print_exc()
finally:
  input('#')


问:
Trigger action of a view controller from another view controller
Hi I'm here for advice to see whether what I'm doing is the best option is is fine for swift. I have a view controller that I present from viewcontroller1. In viewcontroller2 I have a textfield and when the text is full I save the text to my singleton and initiate an action in view controller 1 through a protocol to save that text to the database and update the uilabels in view controller 1 with those labels and then I dismiss view controller two. I initiate a function from view controller2 in view controller1 to save the data from the singleton to the database. Is this fine to do. If you have any questions feel free to ask. </p>

```<code>class ViewController1: UIViewController, EditProtocol{
   var label = UIlabel()
   @IBAction func Editname(_ sender: Any) {
    if let vc = storyboard.instantiateViewController(withIdentifier: "ViewController2Identifier") as? ViewController2{
        vc.controller = self
        vc.modalPresentationStyle = .custom
        vc.modalTransitionStyle = .crossDissolve
        vc.setViewControllers([ProductInformation], animated: true)
        self.present(vc, animated:true, completion: nil)
    }
}

func SaveName() {
    label.text = singleton.shared.text
}

  protocol EditProtocol {
      func SaveName()
   }

 class ViewController2: UIViewController{
       var controller: EditProtocol?
        @IBOutlet weak var Name: UITextField!
        @IBAction func Back(_ sender: AnyObject) {
             singleton.shared.text = Name.text
             controller?. SaveName()
             self.dismiss(animated: true, completion: nil)
           }
     }
</code>```

答:
If the only purpose of your singleton is to record this piece of data, then you don't need it. You can directly pass data from VC2 to VC1 and then do saving to database and displaying on UI.

There are several ways to pass data from VC2 back to VC1. Your delegate is fine, you can also use unwind segue, or NotificationCenter (my favorite). All three methods allow you to pass data without need of a singleton object to hold your data. Even more, you can save the data from VC2 directly to database and then read it from VC1. In this way you don't even need one of the three options above to pass data

Body:
Hi I'm here for advice to see whether what I'm doing is the best option is is fine for swift. I have a view controller that I present from viewcontroller1. In viewcontroller2 I have a textfield and when the text is full I save the text to my singleton and initiate an action in view controller 1 through a protocol to save that text to the database and update the uilabels in view controller 1 with those labels and then I dismiss view controller two. I initiate a function from view controller2 in view controller1 to save the data from the singleton to the database. Is this fine to do. If you have any questions feel free to ask.

class ViewController1: UIViewController, EditProtocol{
   var label = UIlabel()
   @IBAction func Editname(_ sender: Any) {
    if let vc = storyboard.instantiateViewController(withIdentifier: "ViewController2Identifier") as? ViewController2{
        vc.controller = self
        vc.modalPresentationStyle = .custom
        vc.modalTransitionStyle = .crossDissolve
        vc.setViewControllers([ProductInformation], animated: true)
        self.present(vc, animated:true, completion: nil)
    }
}

func SaveName() {
    label.text = singleton.shared.text
}

  protocol EditProtocol {
      func SaveName()
   }

 class ViewController2: UIViewController{
       var controller: EditProtocol?
        @IBOutlet weak var Name: UITextField!
        @IBAction func Back(_ sender: AnyObject) {
             singleton.shared.text = Name.text
             controller?. SaveName()
             self.dismiss(animated: true, completion: nil)
           }
     }


问:
Check chained association existence in rails
I have a rails Model association setup where every User has_one Buyer and specific Users can register as a Seller as well (has_one association).

Also some of the buyers can be specified as Elite as another has_one relation to a Buyer.

Now I have a situation where I want to setup a cron job to check the activity of different buyers and exclude all sellers and elite buyers.

My method for the same is:

```<code>def self.create_daily_user_notifications
  @users = User.where({ banned: false, admin: false })
  @users = @users.reject {|u| u.seller or u.buyer.elite }
end
</code>```

The problem in this situation is that if there is a condition where a buyer doesn't have an associated elite relation it actually gives an error undefined method elite for buyer.

I would guess it's because the join doesn't exist for situations where a buyer is not elite. Is there a way I can just add this check?

答:
Well, then you can use try to silence the error and proceed with the check.

```<code>@users = @users.reject {|u| u.seller or u.buyer.try(:elite) }
</code>```

Body:
I have a rails Model association setup where every User has_one Buyer and specific Users can register as a Seller as well (has_one association).

Also some of the buyers can be specified as Elite as another has_one relation to a Buyer.

Now I have a situation where I want to setup a cron job to check the activity of different buyers and exclude all sellers and elite buyers.

My method for the same is:

def self.create_daily_user_notifications
  @users = User.where({ banned: false, admin: false })
  @users = @users.reject {|u| u.seller or u.buyer.elite }
end

The problem in this situation is that if there is a condition where a buyer doesn't have an associated elite relation it actually gives an error undefined method elite for buyer.

I would guess it's because the join doesn't exist for situations where a buyer is not elite. Is there a way I can just add this check?

Body:
Well, then you can use try to silence the error and proceed with the check.

@users = @users.reject {|u| u.seller or u.buyer.try(:elite) }


问:
Activity to Fragment communication onlocation changed
I have implemented location service on my activity ,,,,when i get the location on onlocation changed....i'll b using Geocoder to convert it into a address...now i need to set the value in a fragment within view pager...how to do that..please help..</p>

```<code>  @Override
public void onLocationChanged(Location location) {

    latitude = location.getLatitude();
    longitude = location.getLongitude();

    address = Utility.getAddress(RegistrationPersonaliseActivity.this, location);

    Log.e("tag", "Lat-->" + latitude + "long-->" + longitude + "Address-->" + address);

}
</code>```

答:
```<code>    @Override
public void onLocationChanged(Location location) {

    latitude = location.getLatitude();
    longitude = location.getLongitude();

    address = Utility.getAddress(RegistrationPersonaliseActivity.this, location);

    Prefs.setLoc(address);
}

    final Handler ha=new Handler();
    ha.postDelayed(new Runnable() {

        @Override
        public void run() {
            //call function
            place.setText(Prefs.getLoc());
            ha.postDelayed(this, 10000);
        }
    }, 10000);
</code>```

Body:
I have implemented location service on my activity ,,,,when i get the location on onlocation changed....i'll b using Geocoder to convert it into a address...now i need to set the value in a fragment within view pager...how to do that..please help..

  @Override
public void onLocationChanged(Location location) {

    latitude = location.getLatitude();
    longitude = location.getLongitude();

    address = Utility.getAddress(RegistrationPersonaliseActivity.this, location);

    Log.e("tag", "Lat-->" + latitude + "long-->" + longitude + "Address-->" + address);

}


问:
How to rotate camera around group of objects? (not using 3d engines)
So I create a point cloud, in 3d with code like (flash 10.1 CS5):

```<code>import flash.display.Bitmap;
import flash.display.BitmapData;

var bmd:BitmapData = new BitmapData(400, 400, true, 0xFFCCCCCC);

                var xn:Number;
                var yn:Number;
                var zn:Number;
                var norm:Number;
                var c1:Number;
                var c2:Number;
                var c3:Number;
                var c4:Number;
                var counter:int;
    var color:uint

                while (counter < 100000)
                {
                    xn = Math.random() * 600 - 200;
                    yn = Math.random() * 600 - 200;
                    zn = Math.random() * 600 - 200;
                    norm = Math.sqrt(xn * xn + yn * yn + zn * zn);
                    c1 = (1 - norm / 200) * 255;
                    c2 = (1 - norm / 250) * 255;
                    c3 = Math.abs(xn) / norm * 255;
                    c4 = Math.abs(yn) / norm * 255;
                    color =  (c1 << 24 | c2 << 16 | c3 << 8 | c4);
                    counter++;

      var pointGraphicData = new BitmapData(1,1,true,color)
var pointGraphic:Bitmap = new Bitmap(pointGraphicData);

pointGraphic.x = xn;
pointGraphic.y = yn;
pointGraphic.z = zn;
addChild(pointGraphic);
}
</code>```

How to move and rotate camera that looks onto the screen in sphere like path

around created box?

答:
There's a javascript example of how to create a spiral on a sphere surface at this link:

http://lines-about-to-be-generated.blogspot.com/2009/06/image-spiral-sphere.html

Body:
So I create a point cloud, in 3d with code like (flash 10.1 CS5):

import flash.display.Bitmap;
import flash.display.BitmapData;

var bmd:BitmapData = new BitmapData(400, 400, true, 0xFFCCCCCC);

                var xn:Number;
                var yn:Number;
                var zn:Number;
                var norm:Number;
                var c1:Number;
                var c2:Number;
                var c3:Number;
                var c4:Number;
                var counter:int;
    var color:uint

                while (counter < 100000)
                {
                    xn = Math.random() * 600 - 200;
                    yn = Math.random() * 600 - 200;
                    zn = Math.random() * 600 - 200;
                    norm = Math.sqrt(xn * xn + yn * yn + zn * zn);
                    c1 = (1 - norm / 200) * 255;
                    c2 = (1 - norm / 250) * 255;
                    c3 = Math.abs(xn) / norm * 255;
                    c4 = Math.abs(yn) / norm * 255;
                    color =  (c1 << 24 | c2 << 16 | c3 << 8 | c4);
                    counter++;

      var pointGraphicData = new BitmapData(1,1,true,color)
var pointGraphic:Bitmap = new Bitmap(pointGraphicData);

pointGraphic.x = xn;
pointGraphic.y = yn;
pointGraphic.z = zn;
addChild(pointGraphic);
}

How to move and rotate camera that looks onto the screen in sphere like path

around created box?


问:
Could not load file or assembly 'Microsoft.SqlServer.DTSRuntimeWrap
I made a SSIS package that would export data to msaccess. If i try to run the package on its solution project it will execute without error. But when I call the package inside my program, I will get an error

Could not load file or assembly 'Microsoft.SqlServer.DTSRuntimeWrap, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91'. This assembly was compiled for a different processor.

Here is my code:

```<code>public void RunPackage()
    {
        textstring("Locating Package...");
        m_worker2.ReportProgress(20);
        string PkgLocation;
        Package pkg;
        Microsoft.SqlServer.Dts.Runtime.Application _app = new Microsoft.SqlServer.Dts.Runtime.Application(); --> I got an exception here.
        DTSExecResult pkgResult;

        PkgLocation = Properties.Settings.Default.PackageLoc + "\"Package1.dtsx";
        textstring("Loading Package...");
        m_worker2.ReportProgress(30);
        pkg = _app.LoadPackage(PkgLocation, null);
        textstring("Executing Package...");
        m_worker2.ReportProgress(30);
        pkgResult = pkg.Execute();
        textstring("Finished...");
        m_worker2.ReportProgress(30);
        textstring(pkgResult.ToString());
        m_worker2.ReportProgress(30);
    }
</code>```

Can anyone point me out the right way. I don't know what is meant by that error. Please enlighten me?

答: I recently upgraded to SQL 2016 and my VB app stopped running my package.  I saved the package no problem to SQL 2016.  VB wouldn't run it via the LoadFromSqlServer method.  Just reported Could not load file or assembly 'Microsoft.SqlServer.DTSRuntimeWrap'  What fixed it for me was to delete the old 12.0 manageddts reference and adding the new 13.0 reference  (see image)

ContentLicense: CC BY-SA 4.0

Body:
I made a SSIS package that would export data to msaccess. If i try to run the package on its solution project it will execute without error. But when I call the package inside my program, I will get an error

Could not load file or assembly 'Microsoft.SqlServer.DTSRuntimeWrap, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91'. This assembly was compiled for a different processor.

Here is my code:

public void RunPackage()
    {
        textstring("Locating Package...");
        m_worker2.ReportProgress(20);
        string PkgLocation;
        Package pkg;
        Microsoft.SqlServer.Dts.Runtime.Application _app = new Microsoft.SqlServer.Dts.Runtime.Application(); --> I got an exception here.
        DTSExecResult pkgResult;

        PkgLocation = Properties.Settings.Default.PackageLoc + "\"Package1.dtsx";
        textstring("Loading Package...");
        m_worker2.ReportProgress(30);
        pkg = _app.LoadPackage(PkgLocation, null);
        textstring("Executing Package...");
        m_worker2.ReportProgress(30);
        pkgResult = pkg.Execute();
        textstring("Finished...");
        m_worker2.ReportProgress(30);
        textstring(pkgResult.ToString());
        m_worker2.ReportProgress(30);
    }

Can anyone point me out the right way. I don't know what is meant by that error. Please enlighten me?


问:
How to get key names from JSON using jq
curl http://testhost.test.com:8080/application/app/version | jq '.version' | jq '.[]'

The above command outputs only the values as below:

```<code>"madireddy@test.com"

"2323"

"test"

"02-03-2014-13:41"

"application"
</code>```

How can I get the key names instead like the below:

```<code>email

versionID

context

date

versionName
</code>```

答:
You need to use jq 'keys[]'. For example:

```<code>echo '{"example1" : 1, "example2" : 2, "example3" : 3}' | jq 'keys[]'
</code>```

Will output a line separated list:

```<code>"example1"
"example2"
"example3"
</code>```

Title: How to get key names from JSON using jq

Body:
curl http://testhost.test.com:8080/application/app/version | jq '.version' | jq '.[]'

The above command outputs only the values as below:

"madireddy@test.com"

"2323"

"test"

"02-03-2014-13:41"

"application"

How can I get the key names instead like the below:

email

versionID

context

date

versionName

Body:
You need to use jq 'keys[]'. For example:

echo '{"example1" : 1, "example2" : 2, "example3" : 3}' | jq 'keys[]'

Will output a line separated list:

"example1"
"example2"
"example3"


问:
Select fields on Microsoft Graph list of Messages
I'm using Microsoft Graph to get a list of messages for a user.

I'm using the following URL
https://graph.microsoft.com/v1.0/me/mailFolders/inbox/messages

One important thing that is returned by this is the meetingMessageType when the message revolves around a meeting request.

I would also like to get the uniqueBody of the message.  However, that's not provided by default.  One needs to specifically ask for that field.  I can do that by adding ?$select=uniqueBody to the URL.

However, that now means that I need to add the rest of the fields I want to the $select query parameter.  That's not a big deal until I run into meetingMessageType.  Microsoft Graph returns:

Could not find a property named 'meetingMessageType' on type 'Microsoft.OutlookServices.Message'.

What can I do to ensure I get both uniqueBody and meetingMessageType?

答:
Yogesh's answer is close but will result in a Only one level select is supported error.

As long as you don't care about the value of meetingMessageType, you can use this select:

$select=microsoft.graph.eventMessage, uniqueBody

You'll note that the results no longer include meetingMessageType as a property. The list however is limited to only those messages that are eventMessage, effectively giving you a result set filtered to only show meeting requests.


问:
Python Socket Programming - Server Client basic
I recently started learning socket programming with python. Starting with the most basic scripts of server and client on the same computer, I wrote the following code.

Server.py

```<code>import socket
import time

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
serversocket.bind((host,port))
serversocket.listen(5)

while True:
    clientsocket, addr = serversocket.accept()
    print("Got a connection from %s" %str(addr))
    currentTime = time.ctime(time.time()) + "\r\n"
    clientsocket.send(currentTime.encode('ascii'))
    clientsocket.close()
</code>```

Client.py

```<code>import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
s.connect((host,port))
tm = s.recv(1024)
s.close()
print("The time got from the server is %s" %tm.decode('ascii'))
</code>```

I'm using spyder IDE. Whenever I run the client in the IPython Console, this is what I get:
"ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it."

and whenever I run the Server I get an unending process.

So, what should I do to make this work?

Thank you for any help!

Credits :- http://www.bogotobogo.com/python/python_network_programming_server_client.php

答: Try changing socket.gethostname() to socket.gethostbyname(socket.gethostname()). gethostbyname returns the ip for the hostname. You want to setup a socket to connect to an ip, port. Alternatively, since you are running everything locally, just set your host to "127.0.0.1" directly for both the client/server.

Body:
I recently started learning socket programming with python. Starting with the most basic scripts of server and client on the same computer, I wrote the following code.

Server.py

import socket
import time

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
serversocket.bind((host,port))
serversocket.listen(5)

while True:
    clientsocket, addr = serversocket.accept()
    print("Got a connection from %s" %str(addr))
    currentTime = time.ctime(time.time()) + "\r\n"
    clientsocket.send(currentTime.encode('ascii'))
    clientsocket.close()

Client.py

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
port = 9999
s.connect((host,port))
tm = s.recv(1024)
s.close()
print("The time got from the server is %s" %tm.decode('ascii'))

I'm using spyder IDE. Whenever I run the client in the IPython Console, this is what I get:
"ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it."

and whenever I run the Server I get an unending process.

So, what should I do to make this work?

Thank you for any help!

Credits :- http://www.bogotobogo.com/python/python_network_programming_server_client.php


问:
Segfault while using emalloc from thread in PHP extension
I cannot emalloc any amount of memory inside of a thread without triggering a segfault at https://github.com/php/php-src/blob/master/Zend/zend_alloc.c#L2409.

The segfault occurs (ironically) only when running on a thread-safe version of PHP (ZTS).

When running on a plain NTS build, everything works normally.

Here's some code that can be used to reproduce the issue (I'm using php-cpp to simplify the creation of the extension).

```<code>void* test(void* wrapper){
    emalloc(sizeof(Php::Value));
    return NULL;
}

void VoIP::__construct()
{
    pthread_t a;
    pthread_create(&a, NULL, test, this);
}
extern "C" {
PHPCPP_EXPORT void *get_module()
{
    static Php::Extension extension("php-libtgvoip", "1.0");

    Php::Class<VoIP> voip("VoIP");

    voip.method<&VoIP::__construct>("__construct", Php::Public | Php::Final);
    Php::Namespace danog("danog");
    Php::Namespace MadelineProto("MadelineProto");

    MadelineProto.add(std::move(voip));
    danog.add(std::move(MadelineProto));
    extension.add(std::move(danog));

    return extension;
}
}
</code>```

Header:

```<code>#include <php.h>
#include <php_ini.h>
#include <ext/standard/info.h>
#include <phpcpp.h>

class VoIP : public Php::Base {
public:

    void __construct();

}
</code>```

Instantiation of the \danog\MadelineProto\VoIP class throws a segfault, caused by the emalloc in test():

```<code>Thread 2 "php" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7fffe91ff700 (LWP 4267)]
0x0000555555cfc7ed in _emalloc (size=32, __zend_filename=0x7fffed9c88a8 "main.cpp", __zend_lineno=30, __zend_orig_filename=0x0, __zend_orig_lineno=0)
    at /root/php-src/Zend/zend_alloc.c:2409
2409            if (UNEXPECTED(AG(mm_heap)->use_custom_heap)) {
(gdb) backtrace
#0  0x0000555555cfc7ed in _emalloc (size=32, __zend_filename=0x7fffed9c88a8 "main.cpp", __zend_lineno=30, __zend_orig_filename=0x0, __zend_orig_lineno=0)
    at /root/php-src/Zend/zend_alloc.c:2409
#1  0x00007fffed94e80e in test (wrapper=0x555556a73310) at main.cpp:30
#2  0x00007ffff572a494 in start_thread (arg=0x7fffe91ff700) at pthread_create.c:333
#3  0x00007ffff206eaff in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:97
(gdb)
</code>```

The full source code can be found @ https://github.com/danog/php-libtgvoip

答:
My answer might be rather obvious, but just don't use emalloc and all the other php/zend methods outside of php threads. Your code fails regardless of whether ZTS is on or off. Take a look at line where application is crashing:

```<code>if (UNEXPECTED(AG(mm_heap)->use_custom_heap))
</code>```

AG is declared as

```<code>#ifdef ZTS

static int alloc_globals_id;
#define AG(v) ZEND_TSRMG(alloc_globals_id, zend_alloc_globals *, v)

#else

#define AG(v) (alloc_globals.v)
static zend_alloc_globals alloc_globals;

#endif
</code>```

When ZTS is on there will be a straight segfault because the calling thread was not initialized properly as php thread to use TSRMG (Thread Safe Resource Manager), when ZTS is off there will be a race condition to modify a global variable.

Body:
I cannot emalloc any amount of memory inside of a thread without triggering a segfault at https://github.com/php/php-src/blob/master/Zend/zend_alloc.c#L2409.

The segfault occurs (ironically) only when running on a thread-safe version of PHP (ZTS).

When running on a plain NTS build, everything works normally.

Here's some code that can be used to reproduce the issue (I'm using php-cpp to simplify the creation of the extension).

void* test(void* wrapper){
    emalloc(sizeof(Php::Value));
    return NULL;
}

void VoIP::__construct()
{
    pthread_t a;
    pthread_create(&a, NULL, test, this);
}
extern "C" {
PHPCPP_EXPORT void *get_module()
{
    static Php::Extension extension("php-libtgvoip", "1.0");

    Php::Class<VoIP> voip("VoIP");

    voip.method<&VoIP::__construct>("__construct", Php::Public | Php::Final);
    Php::Namespace danog("danog");
    Php::Namespace MadelineProto("MadelineProto");

    MadelineProto.add(std::move(voip));
    danog.add(std::move(MadelineProto));
    extension.add(std::move(danog));

    return extension;
}
}

Header:

#include <php.h>
#include <php_ini.h>
#include <ext/standard/info.h>
#include <phpcpp.h>

class VoIP : public Php::Base {
public:

    void __construct();

}

Instantiation of the \danog\MadelineProto\VoIP class throws a segfault, caused by the emalloc in test():

Thread 2 "php" received signal SIGSEGV, Segmentation fault.
[Switching to Thread 0x7fffe91ff700 (LWP 4267)]
0x0000555555cfc7ed in _emalloc (size=32, __zend_filename=0x7fffed9c88a8 "main.cpp", __zend_lineno=30, __zend_orig_filename=0x0, __zend_orig_lineno=0)
    at /root/php-src/Zend/zend_alloc.c:2409
2409            if (UNEXPECTED(AG(mm_heap)->use_custom_heap)) {
(gdb) backtrace
#0  0x0000555555cfc7ed in _emalloc (size=32, __zend_filename=0x7fffed9c88a8 "main.cpp", __zend_lineno=30, __zend_orig_filename=0x0, __zend_orig_lineno=0)
    at /root/php-src/Zend/zend_alloc.c:2409
#1  0x00007fffed94e80e in test (wrapper=0x555556a73310) at main.cpp:30
#2  0x00007ffff572a494 in start_thread (arg=0x7fffe91ff700) at pthread_create.c:333
#3  0x00007ffff206eaff in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:97
(gdb)

The full source code can be found @ https://github.com/danog/php-libtgvoip

Body:
My answer might be rather obvious, but just don't use emalloc and all the other php/zend methods outside of php threads. Your code fails regardless of whether ZTS is on or off. Take a look at line where application is crashing:

if (UNEXPECTED(AG(mm_heap)->use_custom_heap))

AG is declared as

#ifdef ZTS

static int alloc_globals_id;
#define AG(v) ZEND_TSRMG(alloc_globals_id, zend_alloc_globals *, v)

#else

#define AG(v) (alloc_globals.v)
static zend_alloc_globals alloc_globals;

#endif

When ZTS is on there will be a straight segfault because the calling thread was not initialized properly as php thread to use TSRMG (Thread Safe Resource Manager), when ZTS is off there will be a race condition to modify a global variable.


问:
Check if Assembly Exists by name before loading it
I want to take this:

```<code>try
{
    Assembly assembly = Assembly.Load("This.Is.My.Assembly.Name");
}
catch (Exception)
{
}
</code>```

And do something similar, but instead never have it throw an exception. Perhaps do something that gets null back instead of an exception, checking if the assembly exists before even attempting to load it. What's the most elegant way to accomplish this?

答:
You can check to see if the executing assembly has a reference to your assembly.  Something like this.</p>

```<code>if (Assembly.GetExecutingAssembly().GetReferencedAssemblies()
                .FirstOrDefault(c => c.FullName == "This.Is.My.Assembly.Name") == null)
{
    var assembly = Assembly.Load("This.Is.My.Assembly.Name");
}
</code>```

Body:
I want to take this:

try
{
    Assembly assembly = Assembly.Load("This.Is.My.Assembly.Name");
}
catch (Exception)
{
}

And do something similar, but instead never have it throw an exception. Perhaps do something that gets null back instead of an exception, checking if the assembly exists before even attempting to load it. What's the most elegant way to accomplish this?

Body:
You can check to see if the executing assembly has a reference to your assembly.  Something like this.

if (Assembly.GetExecutingAssembly().GetReferencedAssemblies()
                .FirstOrDefault(c => c.FullName == "This.Is.My.Assembly.Name") == null)
{
    var assembly = Assembly.Load("This.Is.My.Assembly.Name");
}


问:
selecting bootstrap dropdown value by key press
I am using bootstrap btn-group dropdown menu as my combo box for dropdown.
Working fine.

```<code><div class="btn-group insertText insertTextSMSTemplate">
    <button class="btn btn-small dropdown-toggle" data-toggle="dropdown">Select a Value</button>
    <button class="btn btn-mini dropdown-toggle" data-toggle="dropdown" style='padding:2px;'><span class="icon-chevron-down"></span>
    </button>
    <ul class="dropdown-menu" style="height: 100px; overflow: auto">
        <li><a href="#"></a>
        </li>
        <!-- <li class="divider"></li>
        <li><a href="#">Separated link</a></li> -->
    </ul>
</div>
</code>```

and I wrote a jquery function to select the selected li value and make button text.

But problem is that My list is long and I have scroll in the dropdown.So If I want to select say 70th li element from the dropdown I have to scroll down and select.

I want to add a feature to it that if 70th value is "Temp" then If I press "T" the words starting from T from the list only show in the dropdown.

答:
modified verison of jenkilabs' code.
if you wanted to loop thru the items that begin with the key press then use this:

```

        $(".dropdown").bind('keydown', function (event) {
            //this will open the list if it is not open and select a value
            if (event.keyCode != 13){
                    if ($(this).find('button').attr('aria-expanded') == 'false')
                    {
                        $(this).find('.dropdown-toggle').dropdown('toggle');
                    }
            }
            var keyChar = String.fromCharCode(event.keyCode).toLowerCase();
            var selectedItems = $(this).find('a').filter(function () {
                return $(this).text().toLowerCase().indexOf(keyChar) === 0;
            });
            var f = $(selectedItems).is(':focus');
            if (f)
            {
                selectedItems = $('a:focus').parent().nextAll().find('a').filter(function () {
                    return $(this).text().toLowerCase().indexOf(keyChar) === 0;
                }).first();
                if (selectedItems.length == 0)
                {
                    selectedItems = $(this).find('a').filter(function () {
                        return $(this).text().toLowerCase().indexOf(keyChar) === 0;
                    });
                }
            }
            selectedItems.first().focus();
        });

```

the .ToLowerCase will allow you to select items that begin with lowercase
characters, and you don't have to group items that begin with the same
character together ex.

a

a

b

a

this code will find the third 'a' at no. 4, if you kept pressing a, then it will go back up to the first 'a'.

this will work as long as this(see below) is the structure of the dropdown.

```<code><div class="dropdown">
      <button class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button>
<ul class="dropdown-menu">
 <li><a>text here</a></li>
</ul>
</div>
</code>```

make sure  is nested within the

 and that there is a div with class="dropdown" surrounding the <button> and

Body:
I am using bootstrap btn-group dropdown menu as my combo box for dropdown.
Working fine.

    <button class="btn btn-small dropdown-toggle" data-toggle="dropdown">Select a Value</button>
    <button class="btn btn-mini dropdown-toggle" data-toggle="dropdown" style='padding:2px;'>
    </button>

and I wrote a jquery function to select the selected li value and make button text.

But problem is that My list is long and I have scroll in the dropdown.So If I want to select say 70th li element from the dropdown I have to scroll down and select.

I want to add a feature to it that if 70th value is "Temp" then If I press "T" the words starting from T from the list only show in the dropdown.

Body:
modified verison of jenkilabs' code.
if you wanted to loop thru the items that begin with the key press then use this:

        $(".dropdown").bind('keydown', function (event) {
            //this will open the list if it is not open and select a value
            if (event.keyCode != 13){
                    if ($(this).find('button').attr('aria-expanded') == 'false')
                    {
                        $(this).find('.dropdown-toggle').dropdown('toggle');
                    }
            }
            var keyChar = String.fromCharCode(event.keyCode).toLowerCase();
            var selectedItems = $(this).find('a').filter(function () {
                return $(this).text().toLowerCase().indexOf(keyChar) === 0;
            });
            var f = $(selectedItems).is(':focus');
            if (f)
            {
                selectedItems = $('a:focus').parent().nextAll().find('a').filter(function () {
                    return $(this).text().toLowerCase().indexOf(keyChar) === 0;
                }).first();
                if (selectedItems.length == 0)
                {
                    selectedItems = $(this).find('a').filter(function () {
                        return $(this).text().toLowerCase().indexOf(keyChar) === 0;
                    });
                }
            }
            selectedItems.first().focus();
        });

the .ToLowerCase will allow you to select items that begin with lowercase
characters, and you don't have to group items that begin with the same
character together ex.

a

a

b

a

this code will find the third 'a' at no. 4, if you kept pressing a, then it will go back up to the first 'a'.

this will work as long as this(see below) is the structure of the dropdown.

<div class="dropdown">
      <button class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button>
<ul class="dropdown-menu">
 <li><a>text here</a></li>
</ul>
</div>

make sure <a> is nested within the <li></li> and that there is a div with class="dropdown" surrounding the <button> and <ul>


问:
Is this good design of a workflow-esque system?
I'm in the process of designing a system that will allow me to represent broad-scope tasks as workflows, which expose their workitems via an IEnumerable method. The intention here is to use C#'s 'yield' mechanism to allow me to write psuedo-procedural code that the workflow execution system can execute as it sees fit.

For example, say I have a workflow that includes running a query on the database and sending an email alert if the query returns a certain result. This might be the workflow:

```<code>public override IEnumerable<WorkItem> Workflow() {
    // These would probably be injected from elsewhere
    var db = new DB();
    var emailServer = new EmailServer();

    // other workitems here

    var ci = new FindLowInventoryItems(db);
    yield return ci;

    if (ci.LowInventoryItems.Any()) {
        var email = new SendEmailToWarehouse("Inventory is low.", ci.LowInventoryItems);
        yield return email;
    }

    // other workitems here
}
</code>```

CheckInventory and EmailWarehouse are objects deriving from WorkItem, which has an abstract Execute() method that the subclasses implement, encapsulating the behavior for those actions. The Execute() method gets called in the workflow framework - I have a WorkflowRunner class which enumerates the Workflow(), wraps pre- and post- events around the workitem, and calls Execute in between the events. This allows the consuming application to do whatever it needs in before or after workitems, including canceling, changing workitem properties, etc.

The benefit to all this, I think, is that I can express the core logic of a task in terms of the workitems responsible for getting the work done, and I can do it in a fairly straightforward, almost procedural way. Also because I'm using IEnumerable, and C#'s syntactic sugar that supports it, I can compose these workflows - like higher-level workflows that consume and manipulate sub-workflows. For example I wrote a simple workflow that just interleaves two child workflows together.

My question is this - does this sort of architecture seem reasonable, especially from a maintainability perspective? It seems to achieve several goals for me - self-documenting code (the workflow reads procedurally, so I know what will be executed in what steps), separation of concerns (finding low inventory items does not depend on sending email to the warehouse), etc. Also - are there any potential problems with this sort of architecture that I'm not seeing? Finally, has this been tried before - am I just re-discovering this?

答:
@Erik: (Addressing a comment about the applicability of my answer.)  If you enjoy the technical challenge of designing and building your own custom workflow system then my answer is not helpful.  But if you are trying to solve a real-world WF problem with code that needs to be supported into the future then I recommend using the built-in WF system.

Workflow support is now part of the .Net framework and is called "Workflow Foundation (WF)".  It is almost certainly easier to learn how to use the built-in library than to write one of your own, as duffymo pointed out in his "buy before build" comment.

Workflows are expressed in XAML and are supported by a designer in Visual Studio.
There are three types of Workflows (from Wikipedia, link below)

Sequential Workflow (Typically Flow
  Chart based, progresses from one stage
  to next and does not step back)

State
  Machine Workflow (Progress from
  'State' to 'State', these workflows
  are more complex and return to a
  previous point if required)

Rules-driven Workflow (Implemented
  based on Sequential/StateMachine
  workflow. The rules dictate the
  progress of the workflow)

Wikipedia: Windows Workflow Foundation

MSDN: Getting Started with Workflow Foundation (WF)

OwnerDisplayName: Erik

Body:
I'm in the process of designing a system that will allow me to represent broad-scope tasks as workflows, which expose their workitems via an IEnumerable method. The intention here is to use C#'s 'yield' mechanism to allow me to write psuedo-procedural code that the workflow execution system can execute as it sees fit.

For example, say I have a workflow that includes running a query on the database and sending an email alert if the query returns a certain result. This might be the workflow:

public override IEnumerable<WorkItem> Workflow() {
    // These would probably be injected from elsewhere
    var db = new DB();
    var emailServer = new EmailServer();

    // other workitems here

    var ci = new FindLowInventoryItems(db);
    yield return ci;

    if (ci.LowInventoryItems.Any()) {
        var email = new SendEmailToWarehouse("Inventory is low.", ci.LowInventoryItems);
        yield return email;
    }

    // other workitems here
}

CheckInventory and EmailWarehouse are objects deriving from WorkItem, which has an abstract Execute() method that the subclasses implement, encapsulating the behavior for those actions. The Execute() method gets called in the workflow framework - I have a WorkflowRunner class which enumerates the Workflow(), wraps pre- and post- events around the workitem, and calls Execute in between the events. This allows the consuming application to do whatever it needs in before or after workitems, including canceling, changing workitem properties, etc.

The benefit to all this, I think, is that I can express the core logic of a task in terms of the workitems responsible for getting the work done, and I can do it in a fairly straightforward, almost procedural way. Also because I'm using IEnumerable, and C#'s syntactic sugar that supports it, I can compose these workflows - like higher-level workflows that consume and manipulate sub-workflows. For example I wrote a simple workflow that just interleaves two child workflows together.

My question is this - does this sort of architecture seem reasonable, especially from a maintainability perspective? It seems to achieve several goals for me - self-documenting code (the workflow reads procedurally, so I know what will be executed in what steps), separation of concerns (finding low inventory items does not depend on sending email to the warehouse), etc. Also - are there any potential problems with this sort of architecture that I'm not seeing? Finally, has this been tried before - am I just re-discovering this?

LastEditorDisplayName: Erik

OwnerDisplayName: Tom A

LastEditorDisplayName: Tom A


问:
Basic Flow Control in JavaScript
Could you, please, explain to me, how to write really basic flow control in JavaScript? Thank you.</p>

```<code>flow([

  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback();  }

], function() {

  alert("Done.");

});
</code>```

答:
```<code>(function(){
    function a(cb) { alert('hi'); cb(); }
    function b(cb) { alert('there'); cb(); }
    function c(cb) { alert('replace alert with console.log for ease'); cb(); }
    var done = function() { alert('done'); }
    a(b(c(done)));
})()
</code>```

Title: Basic Flow Control in JavaScript

Body:
Could you, please, explain to me, how to write really basic flow control in JavaScript? Thank you.

flow([

  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback(); /* run next function */ },
  function(callback) { /* do something */ callback();  }

], function() {

  alert("Done.");

});


问:
How to properly make a object file from header file (using an I2C board with a debian linux machine)
I have some source files that previously have been compiled for X86 architecture. Now I need to compile them for ARM architecture. When I try to use something like

g++ -c -x c++ foo.h

gcc -c -x c foo.h

it only gives me few instructions. I believe it doesn't link my header file to other included files. I only get "Disassembly of section .comment:".
Please note it does prompt me for other files, for example if foo includes foo1.h and foo2.h, if I don't include foo1 and foo2 headers in the same directory the compiler doesn't work.

Another thing which I don't understand is that both gcc and g++ produce the same assembly code, maybe because they only generate the comment section they look the same.

A little bit more details about my problem:
I'm using a USB-I2C converter board. The board provides only support for x86/x64 architecture. I managed to access the source file and to get the driver setup. Now I need to test everything together. In order to do so I need to be able to compile a sample code. When I want to do so, it calls on static libraries that need to be in .a extension. I need to create my own library.a file. In order to do so, I have found the source c files (.h header). Now I need to link them together during compilation and make object files, and eventually archive them together in a .a file.
Thank you for your help.

Edit (update):

A quick summary of what I have achieved so far:
- I was able to find a driver from a github repo.
- I was able to make the module
- I also compiled a new fresh kernel from a raspbian source code (I'm doing this for a Raspberry PI3):

```<code>uname -a
Linux raspberrypi 4.9.35-v7+ #1 SMP Tue Jul 4 22:40:25 BST 2017 armv7l GNU/Linux
</code>```

I was able to load the module properly:

lsmod
Module                  Size  Used by
spi_diolan_u2c          3247  0
i2c_diolan_u2c          3373  0
diolan_u2c_core         4268  2 i2c_diolan_u2c,spi_diolan_u2c

lsusb
Bus 001 Device 010: ID a257:2014

dmesg
[  126.758990] i2c_diolan_u2c: loading out-of-tree module taints kernel.
[  126.759241] i2c_diolan_u2c: Unknown symbol diolan_u2c_transfer (err 0)
[  130.651475] i2c_diolan_u2c: Unknown symbol diolan_u2c_transfer (err 0)
[  154.671532] usbcore: registered new interface driver diolan-u2c-core
[ 5915.799739] usb 1-1.2: USB disconnect, device number 4
[10591.295014] usb 1-1.2: new full-speed USB device number 6 using dwc_otg
[10591.425984] usb 1-1.2: New USB device found, idVendor=a257, idProduct=2014
[10591.425997] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[10591.426005] usb 1-1.2: Product: Diolan DLN1
[10591.426012] usb 1-1.2: Manufacturer: Diolan

What I'm not sure:
If the kernel space is properly mapped to physical hardware (if the loaded module can get ahold of my diolan-board)!!!
progress: based on my research, I think a hot-plug protocol would take care of that, but not sure!
confusion: why the lsusb still only shows the device ID. I know the manufacturer and kernel driver can determine what info to be shown, but only showing ID doesn't seem right to me

What I want to do now:
I would like to write a simple c source or python code to interact with my device. Basically I don't know how I can make connection between user space and kernel space. The manufacturer has provided some source code examples, libraries, etc. . However, I have given up on using them because they are for another architecture , based on qt, and I find it near impossible to find replacement for libraries they use in their static libraries ( I figured those libraries by restoring their .a archived file provided for x86)

I just need to know exactly what the next step should be for me to move on towards getting the board working with the PI.
Thank you :)

答:
You don't compile header files, you compile the C files that include them.

All code in a header file should be declarations and type definitions, which give information to the compiler, but don't actually produce any machine code. That's why there's nothing in your object files.

Body:
I have some source files that previously have been compiled for X86 architecture. Now I need to compile them for ARM architecture. When I try to use something like

g++ -c -x c++ foo.h

gcc -c -x c foo.h

it only gives me few instructions. I believe it doesn't link my header file to other included files. I only get "Disassembly of section .comment:".
Please note it does prompt me for other files, for example if foo includes foo1.h and foo2.h, if I don't include foo1 and foo2 headers in the same directory the compiler doesn't work.

Another thing which I don't understand is that both gcc and g++ produce the same assembly code, maybe because they only generate the comment section they look the same.

A little bit more details about my problem:
I'm using a USB-I2C converter board. The board provides only support for x86/x64 architecture. I managed to access the source file and to get the driver setup. Now I need to test everything together. In order to do so I need to be able to compile a sample code. When I want to do so, it calls on static libraries that need to be in .a extension. I need to create my own library.a file. In order to do so, I have found the source c files (.h header). Now I need to link them together during compilation and make object files, and eventually archive them together in a .a file.
Thank you for your help.

Edit (update):

A quick summary of what I have achieved so far:
- I was able to find a driver from a github repo.
- I was able to make the module
- I also compiled a new fresh kernel from a raspbian source code (I'm doing this for a Raspberry PI3):

uname -a
Linux raspberrypi 4.9.35-v7+ #1 SMP Tue Jul 4 22:40:25 BST 2017 armv7l GNU/Linux

I was able to load the module properly:

lsmod
Module                  Size  Used by
spi_diolan_u2c          3247  0
i2c_diolan_u2c          3373  0
diolan_u2c_core         4268  2 i2c_diolan_u2c,spi_diolan_u2c

lsusb
Bus 001 Device 010: ID a257:2014

dmesg
[  126.758990] i2c_diolan_u2c: loading out-of-tree module taints kernel.
[  126.759241] i2c_diolan_u2c: Unknown symbol diolan_u2c_transfer (err 0)
[  130.651475] i2c_diolan_u2c: Unknown symbol diolan_u2c_transfer (err 0)
[  154.671532] usbcore: registered new interface driver diolan-u2c-core
[ 5915.799739] usb 1-1.2: USB disconnect, device number 4
[10591.295014] usb 1-1.2: new full-speed USB device number 6 using dwc_otg
[10591.425984] usb 1-1.2: New USB device found, idVendor=a257, idProduct=2014
[10591.425997] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=0
[10591.426005] usb 1-1.2: Product: Diolan DLN1
[10591.426012] usb 1-1.2: Manufacturer: Diolan

What I'm not sure:
If the kernel space is properly mapped to physical hardware (if the loaded module can get ahold of my diolan-board)!!!
progress: based on my research, I think a hot-plug protocol would take care of that, but not sure!
confusion: why the lsusb still only shows the device ID. I know the manufacturer and kernel driver can determine what info to be shown, but only showing ID doesn't seem right to me

What I want to do now:
I would like to write a simple c source or python code to interact with my device. Basically I don't know how I can make connection between user space and kernel space. The manufacturer has provided some source code examples, libraries, etc. . However, I have given up on using them because they are for another architecture , based on qt, and I find it near impossible to find replacement for libraries they use in their static libraries ( I figured those libraries by restoring their .a archived file provided for x86)

I just need to know exactly what the next step should be for me to move on towards getting the board working with the PI.
Thank you :)