问:
How to run a custom grails command from grails executable jar/war
I'm using grails 3.2.8. I am generating an executable war file from my grails project that has web functionality in it. However, I've also written some custom grails commands that I'd like to be able to run in production (as cron jobs) from an executable jar/war that I build from the same grails project. I can run them in my development environment as "grails run-cmd ...", but I'd like to be able to deploy an executable jar/war file and run the custom command from the executable jar/war. In other words, I want to deploy a war file for web stuff to one server, and I want to deploy an executable jar file for some cron jobs all from a single grails project. I know how build/run the war file--grails makes that easy. However, I really have no idea how to generate an executable jar file from my project that allows me to run my custom grails commands as cron jobs. Can anyone tell me how to do this?</p>

答:
I have found something that seems to work. I've modified the Application.groovy class in my grails project to look like this:

```<code>import grails.boot.GrailsApp
import grails.boot.config.GrailsAutoConfiguration
import grails.ui.command.GrailsApplicationContextCommandRunner

class Application extends GrailsAutoConfiguration {
  static void main(String[] args) {
    if (args.length > 0 && args[0] == "run-command") {
      // If the first argument is 'run-command', then we just want to run a command as if we were running
      // 'grails run-command <grails-custom-command> <args>...'. We are adding the capability of running commands here
      // because this is the class that is run from the executable war generated by running 'grails war'. If we just do the same
      // thing that grails does to run a command, then the commands seem to execute just fine.
      args = args.tail()
      // The following code is copied from GrailsApplicationContextCommandRunner.main(). It is what grails does to make
      // 'grails run-command' work from the grails console/command line. When upgrading grails, it may be necessary to update
      // this code...
      def runner = new GrailsApplicationContextCommandRunner(args[0], Application)
      runner.run(args)
    } else {
      GrailsApp.run(Application, args)
    }
  }
}
</code>```

I have also changed the dependency in build.gradle for the grails-console dependency from 'console' to 'compile':

```<code>compile "org.grails:grails-console" // changed from 'console' dependency since we want to be able to run custom grails commands from the executable jar/war
</code>```

This is because the GrailsApplicationContextCommandRunner class is in grails-console.

With these changes in place, I can still run the war file with:

```<code>java -jar myWarFile.war
</code>```

However, I am now also able to run my custom commands with the exact same war file like this:

```<code>java -jar myWarFile.war run-command my-command <command args>
</code>```

It seems like there should be a better way to do this, so it would be great if the grails team would comment (and if there isn't a better way, then the grails team should consider adding running custom commands from the executable war file as a grails feature request), but I do seem to be able to run my custom commands from the executable war file this way.

Body:
I have found something that seems to work. I've modified the Application.groovy class in my grails project to look like this:

import grails.boot.GrailsApp
import grails.boot.config.GrailsAutoConfiguration
import grails.ui.command.GrailsApplicationContextCommandRunner

class Application extends GrailsAutoConfiguration {
  static void main(String[] args) {
    if (args.length > 0 && args[0] == "run-command") {
      // If the first argument is 'run-command', then we just want to run a command as if we were running
      // 'grails run-command <grails-custom-command> <args>...'. We are adding the capability of running commands here
      // because this is the class that is run from the executable war generated by running 'grails war'. If we just do the same
      // thing that grails does to run a command, then the commands seem to execute just fine.
      args = args.tail()
      // The following code is copied from GrailsApplicationContextCommandRunner.main(). It is what grails does to make
      // 'grails run-command' work from the grails console/command line. When upgrading grails, it may be necessary to update
      // this code...
      def runner = new GrailsApplicationContextCommandRunner(args[0], Application)
      runner.run(args)
    } else {
      GrailsApp.run(Application, args)
    }
  }
}

I have also changed the dependency in build.gradle for the grails-console dependency from 'console' to 'compile':

compile "org.grails:grails-console" // changed from 'console' dependency since we want to be able to run custom grails commands from the executable jar/war

This is because the GrailsApplicationContextCommandRunner class is in grails-console.

With these changes in place, I can still run the war file with:

java -jar myWarFile.war

However, I am now also able to run my custom commands with the exact same war file like this:

java -jar myWarFile.war run-command my-command <command args>

It seems like there should be a better way to do this, so it would be great if the grails team would comment (and if there isn't a better way, then the grails team should consider adding running custom commands from the executable war file as a grails feature request), but I do seem to be able to run my custom commands from the executable war file this way.


来源: stackexchange

问:
Insert a row after a specific text - VBA
I want to insert a row in a excel spreadsheet after a specific text is found is a column. The text appears N times and the new row need to be inserted after the last time the text appears.

An example of what I have

```<code>ColumnA
TextA
TextA
TextA
TextA
TextB
TextB
TextB
TextB
TextC
TextC
TextC
TextC
</code>```

I need to insert a new row after the last time TextA, TextB and TextC appear, each time I execute the macro.

Is there a way to find the maximum number of times a given text appears in a column? In that way it will be possible to do what I want.

EDIT:

I have tried to count the number of times each text appears and assign this value to a variable:

```<code>Sub count()
Dim A As Integer
A = Application.WorksheetFunction.CountIf(Range("B:B"), "TextA")

Dim B As Integer
B = Application.WorksheetFunction.CountIf(Range("B:B"), "TextB")

Dim C As Integer
C = Application.WorksheetFunction.CountIf(Range("B:B"), "TextC")
End Sub
</code>```

After that I tried to insert a new row

```<code>Sub insert_row ()
    Rows("4+A:4+A").Select 'The number 4 is the first row `TextA` appears. So 4+A where I need to insert my new row.
    Selection.Insert Shift:=xlDown
End Sub
</code>```

With this code I have to problems

1 - A have much more than just TextA, TextB and TextC texts to find. Actually I have 30 different texts in the column.

2 - Sub insert_row () does not work.

答:
Just my two cents, if performance is of any value to you.

The following code requires that you go into the VBE's Tools ► References and add Microsoft Scripting Runtime. This holds the library definitions for a Scripting.Dictionary. However, if you use CreateObject("Scripting.Dictionary"), you do not require the library reference.

with this code you use a scripting dictionary to find the distinct values in column A then you find the last time that value was used and insert a row right below.

```<code>Sub findlastItem()

Dim unique As Object
Dim firstcol As Variant

Set unique = CreateObject("Scripting.Dictionary")

With Worksheets("sheet1")

 firstcol = .Range(.Cells(2, "A"), .Cells(Rows.Count, "A").End(xlUp)).Value2

 For v = LBound(firstcol, 1) To UBound(firstcol, 1)
 If Not unique.Exists(firstcol(v, 1)) Then _
                unique.Add Key:=firstcol(v, 1), Item:=vbNullString
      Next v
  End With

  For Each myitem In unique
     findAndInsertRow myitem
  Next

 End Sub

Sub findAndInsertRow(findwhat As Variant)

    Dim FindString As String
    Dim Rng As Range
    Dim LastRange As Range

    listOfValues = Array(findwhat)

    If Trim(findwhat) <> "" Then
        With Sheets("Sheet1").Range("A:A")

                Set Rng = .Find(What:=listOfValues(i), _
                                After:=.Cells(.Cells.Count), _
                                LookIn:=xlValues, _
                                LookAt:=xlWhole, _
                                SearchOrder:=xlByRows, _
                                SearchDirection:=xlPrevious, _
                                MatchCase:=False)
                If Not Rng Is Nothing Then
                    Rng.Offset(1, 0).Insert
                 End If

        End With
    End If
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to insert a row in a excel spreadsheet after a specific text is found is a column. The text appears N times and the new row need to be inserted after the last time the text appears.

An example of what I have

ColumnA
TextA
TextA
TextA
TextA
TextB
TextB
TextB
TextB
TextC
TextC
TextC
TextC

I need to insert a new row after the last time TextA, TextB and TextC appear, each time I execute the macro.

Is there a way to find the maximum number of times a given text appears in a column? In that way it will be possible to do what I want.

EDIT:

I have tried to count the number of times each text appears and assign this value to a variable:

Sub count()
Dim A As Integer
A = Application.WorksheetFunction.CountIf(Range("B:B"), "TextA")

Dim B As Integer
B = Application.WorksheetFunction.CountIf(Range("B:B"), "TextB")

Dim C As Integer
C = Application.WorksheetFunction.CountIf(Range("B:B"), "TextC")
End Sub

After that I tried to insert a new row

Sub insert_row ()
    Rows("4+A:4+A").Select 'The number 4 is the first row `TextA` appears. So 4+A where I need to insert my new row.
    Selection.Insert Shift:=xlDown
End Sub

With this code I have to problems

1 - A have much more than just TextA, TextB and TextC texts to find. Actually I have 30 different texts in the column.

2 - Sub insert_row () does not work.

Body:
Just my two cents, if performance is of any value to you.

The following code requires that you go into the VBE's Tools ► References and add Microsoft Scripting Runtime. This holds the library definitions for a Scripting.Dictionary. However, if you use CreateObject("Scripting.Dictionary"), you do not require the library reference.

with this code you use a scripting dictionary to find the distinct values in column A then you find the last time that value was used and insert a row right below.

Sub findlastItem()

Dim unique As Object
Dim firstcol As Variant

Set unique = CreateObject("Scripting.Dictionary")

With Worksheets("sheet1")

 firstcol = .Range(.Cells(2, "A"), .Cells(Rows.Count, "A").End(xlUp)).Value2

 For v = LBound(firstcol, 1) To UBound(firstcol, 1)
 If Not unique.Exists(firstcol(v, 1)) Then _
                unique.Add Key:=firstcol(v, 1), Item:=vbNullString
      Next v
  End With

  For Each myitem In unique
     findAndInsertRow myitem
  Next

 End Sub

Sub findAndInsertRow(findwhat As Variant)

    Dim FindString As String
    Dim Rng As Range
    Dim LastRange As Range

    listOfValues = Array(findwhat)

    If Trim(findwhat) <> "" Then
        With Sheets("Sheet1").Range("A:A")

                Set Rng = .Find(What:=listOfValues(i), _
                                After:=.Cells(.Cells.Count), _
                                LookIn:=xlValues, _
                                LookAt:=xlWhole, _
                                SearchOrder:=xlByRows, _
                                SearchDirection:=xlPrevious, _
                                MatchCase:=False)
                If Not Rng Is Nothing Then
                    Rng.Offset(1, 0).Insert
                 End If

        End With
    End If


问:
Output to a text file
I need to output lots of different datasets to different text files. The datasets share some common variables that need to be output but also have quite a lot of different ones. I have loaded these different ones into a macro variable separated by blanks so that I can macroize this.

So I created a macro which loops over the datasets and outputs each into a different text file.

For this purpose, I used a put statement inside a data step. The PUT statement looks like this:

```<code>PUT (all the common variables shared by all the datasets), (macro variable containing all the dataset-specific variables);
</code>```

E.g.:

```<code>%MACRO OUTPUT();
    %DO N=1 %TO &TABLES_COUNT;
        DATA _NULL_;
            SET &&TABLE&N;
            FILE 'PATH/&&TABLE&N..txt';
            PUT a b c d "&vars";
        RUN;
    %END;
%MEND OUTPUT;
</code>```

Where &vars is the macro variable containing all the variables needed for outputting for a dataset in the current loop.
Which gets resolved, for example, to:

```<code>PUT a b c d special1 special2 special5 ... special329;
</code>```

Now the problem is, the quoted string can only be 262 characters long. And some of my datasets I am trying to output have so many variables to be output that this macro variable which is a quoted string and holds all those variables will be much longer than that. Is there any other way how I can do this?

答:
I would tackle this but having 1 put statement per variable.  Use the @ modifier so that you don't get a new line.

For example:

```<code>data test;
a=1;
b=2;
c=3;
output;
output;
run;

data _null_;
set test;
put a @;
put b @;
put c @;
put;
run;
</code>```

Outputs this to the log:

```<code>800  data _null_;
801  set test;
802  put a @;
803  put b @;
804  put c @;
805  put;
806  run;

1 2 3
1 2 3
NOTE: There were 2 observations read from the data set WORK.TEST.
NOTE: DATA statement used (Total process time):
      real time           0.07 seconds
      cpu time            0.03 seconds
</code>```

So modify your macro to loop through the two sets of values using this syntax.

Title: Output to a text file

Body:
I need to output lots of different datasets to different text files. The datasets share some common variables that need to be output but also have quite a lot of different ones. I have loaded these different ones into a macro variable separated by blanks so that I can macroize this.

So I created a macro which loops over the datasets and outputs each into a different text file.

For this purpose, I used a put statement inside a data step. The PUT statement looks like this:

PUT (all the common variables shared by all the datasets), (macro variable containing all the dataset-specific variables);

E.g.:

%MACRO OUTPUT();
    %DO N=1 %TO &TABLES_COUNT;
        DATA _NULL_;
            SET &&TABLE&N;
            FILE 'PATH/&&TABLE&N..txt';
            PUT a b c d "&vars";
        RUN;
    %END;
%MEND OUTPUT;

Where &vars is the macro variable containing all the variables needed for outputting for a dataset in the current loop.
Which gets resolved, for example, to:

PUT a b c d special1 special2 special5 ... special329;

Now the problem is, the quoted string can only be 262 characters long. And some of my datasets I am trying to output have so many variables to be output that this macro variable which is a quoted string and holds all those variables will be much longer than that. Is there any other way how I can do this?

Body:
I would tackle this but having 1 put statement per variable.  Use the @ modifier so that you don't get a new line.

For example:

data test;
a=1;
b=2;
c=3;
output;
output;
run;

data _null_;
set test;
put a @;
put b @;
put c @;
put;
run;

Outputs this to the log:

800  data _null_;
801  set test;
802  put a @;
803  put b @;
804  put c @;
805  put;
806  run;

1 2 3
1 2 3
NOTE: There were 2 observations read from the data set WORK.TEST.
NOTE: DATA statement used (Total process time):
      real time           0.07 seconds
      cpu time            0.03 seconds

So modify your macro to loop through the two sets of values using this syntax.


问:
Modify QT Defines in .pro file from C++ file
Sorry, if this question doesn't make any sense but It just came to my mind, I was looking for a solution on this from quite long time but in the end I thought better to check with experts. :)

Below is a scenario:

Suppose In myProject.pro file, I have
      PATH = /home/local/Projects/
for which I created a QT DEFINE using below:
 DEFINES += PATH =\\"$${PATH}\\"

Now, I can use this "PATH" any where in my Project which is based on CPP file. This if perfectly fine.

Now, depending upon the input from user, I want to change this "PATH"
say, PATH can be:
    PATH = /home/local/Projects/TEST1/

```<code>PATH = /home/local/Projects/TEST2/

        and revert to

PATH = /home/local/Projects/
</code>```

So, that wherever I am using this "PATH" in my project will be changed automatically.

I know this is done at compile time. But came a thought. So wanted to get feedbacks from experts.

答: What you call a "Qt define" is actually preprocessor macro, which is given to compiler in command line, as opposed to including it into a source code file with #define. you can use it as literal to initialize a global variable with "default" value, which, if not being const, can be changed in code.</p>

Body:
Sorry, if this question doesn't make any sense but It just came to my mind, I was looking for a solution on this from quite long time but in the end I thought better to check with experts. :)

Below is a scenario:

Suppose In myProject.pro file, I have
      PATH = /home/local/Projects/
for which I created a QT DEFINE using below:
 DEFINES += PATH =\\"$${PATH}\\"

Now, I can use this "PATH" any where in my Project which is based on CPP file. This if perfectly fine.

Now, depending upon the input from user, I want to change this "PATH"
say, PATH can be:
    PATH = /home/local/Projects/TEST1/

PATH = /home/local/Projects/TEST2/

        and revert to

PATH = /home/local/Projects/

So, that wherever I am using this "PATH" in my project will be changed automatically.

I know this is done at compile time. But came a thought. So wanted to get feedbacks from experts.


问:
Archive/pack a directory with contents as plain-text representation?
Under Linux / bash, how can I obtain a plain-text representation of a directory of its contents? (Note that by "plain-text" here I mean "UTF-8").

In other words, how could I "pack" or "archive" a directory (with contents - including binary files) as a plain text file -  such that I could "unpack" it later, and obtain the same directory with its contents?

答:
I was interested in this for a while, and I think I finally managed to cook up a script that works in both Python 2.7 and 3.4 -- however, I'd still like to know if there is something else that does the same. Here it is as a Gist (with some more comments):

https://gist.github.com/anonymous/1a68bf2c9134fd5312219c8f68713632

Otherwise, I'm posting a slightly abridged version here (below) for reference.

The usage is: to archive/pack into a .json text file:

```<code>python archdir2text-json.py -a /tmp > myarchdir.json
</code>```

... and to unpack from the .json text file into the current (calling) directory:

```<code>python archdir2text-json.py -u myarchdir.json
</code>```

Binary files are handled as base64.

Here is the script:

archdir2text-json.py

#!/usr/bin/env python

import pprint, inspect
import argparse
import os
import stat
import errno
import base64
import codecs

class SmartDescriptionFormatter(argparse.RawDescriptionHelpFormatter):
  def _fill_text(self, text, width, indent):
    if text.startswith('R|'):
      paragraphs = text[2:].splitlines()
      rebroken = [argparse._textwrap.wrap(tpar, width) for tpar in paragraphs]
      rebrokenstr = []
      for tlinearr in rebroken:
        if (len(tlinearr) == 0):
          rebrokenstr.append("")
        else:
          for tlinepiece in tlinearr:
            rebrokenstr.append(tlinepiece)
      return '\n'.join(rebrokenstr)
    return argparse.RawDescriptionHelpFormatter._fill_text(self, text, width, indent)

textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})
is_binary_string = lambda bytes: bool(bytes.translate(None, textchars))

cwd = os.getcwd()

if os.name == 'nt':
  import win32api, win32con
def folder_is_hidden(p):
  if os.name== 'nt':
    attribute = win32api.GetFileAttributes(p)
    return attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM)
  else:
    return os.path.basename(p).startswith('.') #linux-osx

def path_hierarchy(path):
  hierarchy = {
    'type': 'folder',
    'name': os.path.basename(path),
    'path': path,
  }
  try:
    cleared_contents = [contents
                        for contents in os.listdir(path)
                        if not(
                          os.path.isdir(os.path.join(path, contents))
                          and
                          folder_is_hidden(os.path.join(path, contents))
                        )]
    hierarchy['children'] = [
      path_hierarchy(os.path.join(path, contents))
      for contents in cleared_contents
    ]
  except OSError as e:
    if e.errno == errno.ENOTDIR:
      hierarchy['type'] = 'file'
    else:
      hierarchy['type'] += " " + str(e)
  if hierarchy['type'] == 'file':
    isfifo = stat.S_ISFIFO(os.stat(hierarchy['path']).st_mode)
    if isfifo:
      ftype = "fifo"
    else:
      try:
        data = open(hierarchy['path'], 'rb').read()
        ftype = "bin" if is_binary_string(data) else "txt"
        if (ftype == "txt"):
          hierarchy['content'] = data.decode("utf-8")
        else:
          hierarchy['content'] = base64.b64encode(data).decode("utf-8")
      except Exception as e:
        ftype = str(e)
    hierarchy['ftype'] = ftype
  return hierarchy

def recurse_unpack(inobj, relpath=""):
  if (inobj['type'] == "folder"):
    rpname = relpath + inobj['name']
    sys.stderr.write("folder name: " + rpname + os.linesep);
    os.mkdir(rpname)
    for tchild in inobj['children']:
      recurse_unpack(tchild, relpath=relpath+inobj['name']+os.sep)
  elif (inobj['type'] == "file"):
    rfname = relpath + inobj['name']
    sys.stderr.write("file name: " + rfname + os.linesep)
    if inobj['ftype'] == "txt":
      with codecs.open(rfname, "w", "utf-8") as text_file:
        text_file.write(inobj['content'])
    elif inobj['ftype'] == "bin":
      with open(rfname, "wb") as bin_file:
        bin_file.write(base64.b64decode(inobj['content']))

if __name__ == '__main__':
  import json
  import sys

  parser = argparse.ArgumentParser(formatter_class=SmartDescriptionFormatter, description="""R|Command-line App that packs/archives (and vice-versa) a directory to a plain-text .json file; should work w/ both Python 2.7 and 3.4

see full help text in https://gist.github.com/anonymous/1a68bf2c9134fd5312219c8f68713632""")

  parser.add_argument('input_paths', type=str, nargs='*', default=['.'],
                      help='Paths to files/directories to include in the archive; or path to .json archive file')

  group = parser.add_mutually_exclusive_group(required=True)
  group.add_argument('-a', '--archive', action='store_true', help="Interpret input_paths as paths to files/directories, and archive them to a .json file (output to stdout)")
  group.add_argument('-u', '--unpack', action='store_true', help="Interpret input_paths as path to an archive .json file, and unpack it in the current directory")

  args = parser.parse_args()

  if (args.archive):
    valid_input_paths = []
    for p in args.input_paths:
      if os.path.isdir(p) or os.path.exists(p):
        valid_input_paths.append(p)
      else:
        sys.stderr.write("Ignoring invalid input path: " + p + os.linesep)
    sys.stderr.write("Encoding input path(s): " + str(valid_input_paths) + os.linesep)
    path_hier_arr = [path_hierarchy(vp) for vp in valid_input_paths]
    outjson = json.dumps(path_hier_arr, indent=2, sort_keys=True, separators=(',', ': '))
    print(outjson)
  elif (args.unpack):
    valid_input_paths = []
    for p in args.input_paths:
      if os.path.isdir(p) or os.path.exists(p):
        valid_input_paths.append(p)
      else:
        sys.stderr.write("Ignoring invalid input path: " + p + os.linesep)
    for vp in valid_input_paths:
      with open(vp) as data_file:
        data = json.load(data_file)
      for datachunk in data:
        recurse_unpack(datachunk)
```

Body:
I was interested in this for a while, and I think I finally managed to cook up a script that works in both Python 2.7 and 3.4 -- however, I'd still like to know if there is something else that does the same. Here it is as a Gist (with some more comments):

https://gist.github.com/anonymous/1a68bf2c9134fd5312219c8f68713632

Otherwise, I'm posting a slightly abridged version here (below) for reference.

The usage is: to archive/pack into a .json text file:

python archdir2text-json.py -a /tmp > myarchdir.json

... and to unpack from the .json text file into the current (calling) directory:

python archdir2text-json.py -u myarchdir.json

Binary files are handled as base64.

Here is the script:

archdir2text-json.py

#!/usr/bin/env python

import pprint, inspect
import argparse
import os
import stat
import errno
import base64
import codecs

class SmartDescriptionFormatter(argparse.RawDescriptionHelpFormatter):
  def _fill_text(self, text, width, indent):
    if text.startswith('R|'):
      paragraphs = text[2:].splitlines()
      rebroken = [argparse._textwrap.wrap(tpar, width) for tpar in paragraphs]
      rebrokenstr = []
      for tlinearr in rebroken:
        if (len(tlinearr) == 0):
          rebrokenstr.append("")
        else:
          for tlinepiece in tlinearr:
            rebrokenstr.append(tlinepiece)
      return '\n'.join(rebrokenstr)
    return argparse.RawDescriptionHelpFormatter._fill_text(self, text, width, indent)

textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})
is_binary_string = lambda bytes: bool(bytes.translate(None, textchars))

cwd = os.getcwd()

if os.name == 'nt':
  import win32api, win32con
def folder_is_hidden(p):
  if os.name== 'nt':
    attribute = win32api.GetFileAttributes(p)
    return attribute & (win32con.FILE_ATTRIBUTE_HIDDEN | win32con.FILE_ATTRIBUTE_SYSTEM)
  else:
    return os.path.basename(p).startswith('.') #linux-osx

def path_hierarchy(path):
  hierarchy = {
    'type': 'folder',
    'name': os.path.basename(path),
    'path': path,
  }
  try:
    cleared_contents = [contents
                        for contents in os.listdir(path)
                        if not(
                          os.path.isdir(os.path.join(path, contents))
                          and
                          folder_is_hidden(os.path.join(path, contents))
                        )]
    hierarchy['children'] = [
      path_hierarchy(os.path.join(path, contents))
      for contents in cleared_contents
    ]
  except OSError as e:
    if e.errno == errno.ENOTDIR:
      hierarchy['type'] = 'file'
    else:
      hierarchy['type'] += " " + str(e)
  if hierarchy['type'] == 'file':
    isfifo = stat.S_ISFIFO(os.stat(hierarchy['path']).st_mode)
    if isfifo:
      ftype = "fifo"
    else:
      try:
        data = open(hierarchy['path'], 'rb').read()
        ftype = "bin" if is_binary_string(data) else "txt"
        if (ftype == "txt"):
          hierarchy['content'] = data.decode("utf-8")
        else:
          hierarchy['content'] = base64.b64encode(data).decode("utf-8")
      except Exception as e:
        ftype = str(e)
    hierarchy['ftype'] = ftype
  return hierarchy

def recurse_unpack(inobj, relpath=""):
  if (inobj['type'] == "folder"):
    rpname = relpath + inobj['name']
    sys.stderr.write("folder name: " + rpname + os.linesep);
    os.mkdir(rpname)
    for tchild in inobj['children']:
      recurse_unpack(tchild, relpath=relpath+inobj['name']+os.sep)
  elif (inobj['type'] == "file"):
    rfname = relpath + inobj['name']
    sys.stderr.write("file name: " + rfname + os.linesep)
    if inobj['ftype'] == "txt":
      with codecs.open(rfname, "w", "utf-8") as text_file:
        text_file.write(inobj['content'])
    elif inobj['ftype'] == "bin":
      with open(rfname, "wb") as bin_file:
        bin_file.write(base64.b64decode(inobj['content']))

if __name__ == '__main__':
  import json
  import sys

  parser = argparse.ArgumentParser(formatter_class=SmartDescriptionFormatter, description="""R|Command-line App that packs/archives (and vice-versa) a directory to a plain-text .json file; should work w/ both Python 2.7 and 3.4

see full help text in https://gist.github.com/anonymous/1a68bf2c9134fd5312219c8f68713632""")

  parser.add_argument('input_paths', type=str, nargs='*', default=['.'],
                      help='Paths to files/directories to include in the archive; or path to .json archive file')

  group = parser.add_mutually_exclusive_group(required=True)
  group.add_argument('-a', '--archive', action='store_true', help="Interpret input_paths as paths to files/directories, and archive them to a .json file (output to stdout)")
  group.add_argument('-u', '--unpack', action='store_true', help="Interpret input_paths as path to an archive .json file, and unpack it in the current directory")

  args = parser.parse_args()

  if (args.archive):
    valid_input_paths = []
    for p in args.input_paths:
      if os.path.isdir(p) or os.path.exists(p):
        valid_input_paths.append(p)
      else:
        sys.stderr.write("Ignoring invalid input path: " + p + os.linesep)
    sys.stderr.write("Encoding input path(s): " + str(valid_input_paths) + os.linesep)
    path_hier_arr = [path_hierarchy(vp) for vp in valid_input_paths]
    outjson = json.dumps(path_hier_arr, indent=2, sort_keys=True, separators=(',', ': '))
    print(outjson)
  elif (args.unpack):
    valid_input_paths = []
    for p in args.input_paths:
      if os.path.isdir(p) or os.path.exists(p):
        valid_input_paths.append(p)
      else:
        sys.stderr.write("Ignoring invalid input path: " + p + os.linesep)
    for vp in valid_input_paths:
      with open(vp) as data_file:
        data = json.load(data_file)
      for datachunk in data:
        recurse_unpack(datachunk)


问:
How can I install a python .egg file
I am trying to install twisted on python 2.6 and it seems that the Zop interface is missing.
Also it seems that it is a .egg file.  I downloaded this .egg file, now how can I install it?

答:
Install virtualenv, which includes pip. Then you can simply run:

```<code>pip install twisted
</code>```

pip will handle installing the zope.interface.

Instructions for installing virtualenv and pip on OS X

This is how I installed virtualenv and pip on OS X:

```<code>curl -O http://peak.telecommunity.com/dist/ez_setup.py
sudo python ez_setup.py
sudo easy_install pip
sudo pip install virtualenv
</code>```

I also like to use virtualenvwrapper with virtualenv, so I installed it using:

```<code>sudo pip install virtualenvwrapper
</code>```

Instructions for installing Twisted in a virtualenv

Now to create a new virtual environment and install Twisted, I simply issue:

```<code>mkvirtualenv twisted-env
pip install twisted
</code>```

Title: How can I install a python .egg file

Body:
Install virtualenv, which includes pip. Then you can simply run:

pip install twisted

pip will handle installing the zope.interface.

Instructions for installing virtualenv and pip on OS X

This is how I installed virtualenv and pip on OS X:

curl -O http://peak.telecommunity.com/dist/ez_setup.py
sudo python ez_setup.py
sudo easy_install pip
sudo pip install virtualenv

I also like to use virtualenvwrapper with virtualenv, so I installed it using:

sudo pip install virtualenvwrapper

Instructions for installing Twisted in a virtualenv

Now to create a new virtual environment and install Twisted, I simply issue:

mkvirtualenv twisted-env
pip install twisted

ContentLicense: CC BY-SA 2.5


问:
cascaded_union(polygons) recover circumference point indices
My question is simple, but the solution might be very tricky. I have a collection of triangles, and I want to find their union. The triangles are given in the standard way: by a list of coordinate points (2 coordinates for each point) and a list of connections, where each line is a triangle given by the indices of its vertices:

points:

```<code>[ 15.02716923  81.72425842]
[ 21.42242702  79.91459549]
[ 24.87068939  79.0222168 ]
[ 29.25767326  77.96657562]
[ 34.07667923  76.65890503]
</code>```

triangles:

```<code>7 8 9
8 18 20
8 20 10
8 10 9
9 10 11
9 11 108
</code>```

I can very efficiently find the union using cascaded_union:

```<code>import shapely.geometry as geometry
from shapely.ops import cascaded_union, polygonize

polys = [geometry.Polygon([[points[point, 0], points[point, 1]] for point in triangle]) for triangle in triangles]
result = cascaded_union (polys)
</code>```

The problem is, this gives the coordinates of the resulting polygon. Whereas, I would like the circumference of result as indices in the initial points array. So far I have not found a way to do this. One way may be to write my own combining function which spits out the point indices instead of the coordinates themselves.

答:
If the union always return polygons with points from your list, you can just lookup the indexes. Build a dictionary where a tuple of coordinates point to the index you use (named coord_to_pointer in the code), then you can get the indexes easily:

```<code>polys = [geometry.Polygon([[points[point, 0], points[point, 1]]
                          for point in triangle]) for triangle in triangles]
result = cascaded_union (polys)
geom_indexes = [coord_to_pointer[p] for p in list(result.exterior.coords)]
</code>```

Body:
My question is simple, but the solution might be very tricky. I have a collection of triangles, and I want to find their union. The triangles are given in the standard way: by a list of coordinate points (2 coordinates for each point) and a list of connections, where each line is a triangle given by the indices of its vertices:

points:

[ 15.02716923  81.72425842]
[ 21.42242702  79.91459549]
[ 24.87068939  79.0222168 ]
[ 29.25767326  77.96657562]
[ 34.07667923  76.65890503]

triangles:

7 8 9
8 18 20
8 20 10
8 10 9
9 10 11
9 11 108

I can very efficiently find the union using cascaded_union:

import shapely.geometry as geometry
from shapely.ops import cascaded_union, polygonize

polys = [geometry.Polygon([[points[point, 0], points[point, 1]] for point in triangle]) for triangle in triangles]
result = cascaded_union (polys)

The problem is, this gives the coordinates of the resulting polygon. Whereas, I would like the circumference of result as indices in the initial points array. So far I have not found a way to do this. One way may be to write my own combining function which spits out the point indices instead of the coordinates themselves.

Body:
If the union always return polygons with points from your list, you can just lookup the indexes. Build a dictionary where a tuple of coordinates point to the index you use (named coord_to_pointer in the code), then you can get the indexes easily:

polys = [geometry.Polygon([[points[point, 0], points[point, 1]]
                          for point in triangle]) for triangle in triangles]
result = cascaded_union (polys)
geom_indexes = [coord_to_pointer[p] for p in list(result.exterior.coords)]


问:
How to style drop down list for Ajax / jQuery results
I'm using ajax and jquery UI to search and select in the input field. How can I style the drop down thing to not to show me
 bullets and also have a white background? I have been trying to target the search field using ID but it changes the input box and not the drop down box. I'm attaching the screenshot here.

答:
If someone like me is struggling with jQuery UI stylying for Ajax calls, here is bootstrap code which I'm copy pasting from a blog and it is working perfectly for me.</p>

```<code>.ui-autocomplete {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    float: left;
    display: none;
    min-width: 160px;
    padding: 4px 0;
    margin: 0 0 10px 25px;
    list-style: none;
    background-color: #ffffff;
    border-color: #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    border-style: solid;
    border-width: 1px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    -webkit-background-clip: padding-box;
    -moz-background-clip: padding;
    background-clip: padding-box;
    *border-right-width: 2px;
    *border-bottom-width: 2px;
    }

.ui-menu-item > a.ui-corner-all {
    display: block;
    padding: 3px 15px;
    clear: both;
    font-weight: normal;
    line-height: 18px;
    color: #555555;
    white-space: nowrap;
    text-decoration: none;
    }

.ui-state-hover, .ui-state-active {
    color: #ffffff;
    text-decoration: none;
    background-color: #0088cc;
    border-radius: 0px;
    -webkit-border-radius: 0px;
    -moz-border-radius: 0px;
    background-image: none;
    }
</code>```

Body:
If someone like me is struggling with jQuery UI stylying for Ajax calls, here is bootstrap code which I'm copy pasting from a blog and it is working perfectly for me.

.ui-autocomplete {
    position: absolute;
    top: 100%;
    left: 0;
    z-index: 1000;
    float: left;
    display: none;
    min-width: 160px;
    padding: 4px 0;
    margin: 0 0 10px 25px;
    list-style: none;
    background-color: #ffffff;
    border-color: #ccc;
    border-color: rgba(0, 0, 0, 0.2);
    border-style: solid;
    border-width: 1px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    border-radius: 5px;
    -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
    -webkit-background-clip: padding-box;
    -moz-background-clip: padding;
    background-clip: padding-box;
    *border-right-width: 2px;
    *border-bottom-width: 2px;
    }

.ui-menu-item > a.ui-corner-all {
    display: block;
    padding: 3px 15px;
    clear: both;
    font-weight: normal;
    line-height: 18px;
    color: #555555;
    white-space: nowrap;
    text-decoration: none;
    }

.ui-state-hover, .ui-state-active {
    color: #ffffff;
    text-decoration: none;
    background-color: #0088cc;
    border-radius: 0px;
    -webkit-border-radius: 0px;
    -moz-border-radius: 0px;
    background-image: none;
    }


问:
Trying to update a row (table) using codeigniter
Im trying without success to update a row in a table. I mean, when i click on "update" button it goes to another page and i got the previous "values" so i can edit them and finally click on "save".

But it is not working in my program :/..When i click on "edit" button it goes to another page and i only have the previous values of a single field (Field subject). AND when i click on save it does not update anything, it creates a new row.

Here is my code:
The index file, here i put the button "edit".

```<code>                        <a href='".site_url('Home/editar')."/$record->id'>
                     <button type='button' class='btn btn-primary'>EDIT</button></a>
</code>```

My controller file, with the function "editar" and "saveupdate":

```<code>        public function editar($id){
        $data['carreras'] = $this->Crudmodel->get_carreras();
        $data['record']=$this->Crudmodel->get_id_row($id);
        $this->load->view('editar',$data);
        }
          public function saveupdate(){
            $id=$this->input->post("txtid");
            $txtcarr=$this->input->post("txtcarr");
            $txtmat=$this->input->post("txtmat");
            $txtdesc=$this->input->post("txtdesc");
            $txtcarga=$this->input->post("txtcarga");

        $this->Crudmodel->saveup($txtcarr,$txtmat,$txtdesc,$txtcarga);
         $this->db->where("id", $id);
        redirect('Home/index');

    }
</code>```

The Crudmodel with the function "saveup"

```<code>    public function saveup($txtcarr, $txtmat, $txtdesc, $txtcarga){

      $data=array(
        'carrera_id'=>$txtcarr,
        'nombre'=>$txtmat,
        'descripcion'=>$txtdesc,
        'carga_horaria'=>$txtcarga

    );

      $this->db->update('materias', $data);

}
</code>```

Here is the get_id_row from crudmodel:

Function

Finally, the "editar" file which contains all the fields.

```<code><body>

<div class="container">
<div class="row">
<div class="col-md-12">

    <h2 align="center">UPDATE SUBJECTS</h2>
    <form method="post" action='<?php echo site_url('Home/saveupdate'); ?>'>
    <tr>

        <td><input type="text" hidden name="txtid" value="<?php echo $record->id ?>"/></td>

    </tr>
    <tr>

        <td>
            <select name="txtcarr">
                <?php foreach($carreras as $item):?>
                <option value="<?php echo $item->id;?>"><?php echo $item->nombre;?></option>
                 <?php endforeach;?>
            </select>
        </td>
    </tr>
    <tr>

        <td>Subject : </td>
        <td><input type="text" name="txtmat" value="<?php echo $record->nombre ?>"/></td>

    </tr>
    <tr>

        <td>Description : </td>
        <td><textarea name="txtdesc" value="<?php echo $record->descripcion ?>"></textarea></td>

    </tr>
    <tr>

        <td>Hours : </td>
        <td><input type="text" name="txtcarga"/></td>

    </tr>
    <tr>

        <td></td>
        <td><input type="submit" value="Save"/></td>

    </tr>

        <table class="table table-hover" align="center" border="0" cellspacing="0" cellpadding="0" width="300">

        </table>

    </div>
    </div>
    </div>
</code>```

Do not understand what should i do :S

答:
I think Rushabh thinks you should pass your $id with your data to the model like this:

```<code>$this->Crudmodel->saveup($txtcarr,$txtmat,$txtdesc,$txtcarga, $id);
</code>```

and in your model you can:

```<code>$this->db->where("id", $id);
$this->db->update('materias', $data);
</code>```

and don't forget to remove your where condition in the controller;

Edit:

your get_id_row() function needs to be:

```<code>public function get_id_row($id){
  $query = $this->db->get_where('your_table_name', array('id' => $id));
  return $query->row();
}
</code>```

Body:
Im trying without success to update a row in a table. I mean, when i click on "update" button it goes to another page and i got the previous "values" so i can edit them and finally click on "save".

But it is not working in my program :/..When i click on "edit" button it goes to another page and i only have the previous values of a single field (Field subject). AND when i click on save it does not update anything, it creates a new row.

Here is my code:
The index file, here i put the button "edit".

                        id'>
                     <button type='button' class='btn btn-primary'>EDIT</button>

My controller file, with the function "editar" and "saveupdate":

        public function editar($id){
        $data['carreras'] = $this->Crudmodel->get_carreras();
        $data['record']=$this->Crudmodel->get_id_row($id);
        $this->load->view('editar',$data);
        }
          public function saveupdate(){
            $id=$this->input->post("txtid");
            $txtcarr=$this->input->post("txtcarr");
            $txtmat=$this->input->post("txtmat");
            $txtdesc=$this->input->post("txtdesc");
            $txtcarga=$this->input->post("txtcarga");

        $this->Crudmodel->saveup($txtcarr,$txtmat,$txtdesc,$txtcarga);
         $this->db->where("id", $id);
        redirect('Home/index');

    }

The Crudmodel with the function "saveup"

    public function saveup($txtcarr, $txtmat, $txtdesc, $txtcarga){

      $data=array(
        'carrera_id'=>$txtcarr,
        'nombre'=>$txtmat,
        'descripcion'=>$txtdesc,
        'carga_horaria'=>$txtcarga

    );

      $this->db->update('materias', $data);

}

Here is the get_id_row from crudmodel:

Function

Finally, the "editar" file which contains all the fields.

UPDATE SUBJECTS

    <form method="post" action='<?php echo site_url('Home/saveupdate'); ?>'>

        <input type="text" hidden name="txtid" value="<?php echo $record->id ?>"/>

            <select name="txtcarr">
                <?php foreach($carreras as $item):?>
                <option value="<?php echo $item->id;?>"><?php echo $item->nombre;?></option>
                 <?php endforeach;?>
            </select>

        Subject :
        <input type="text" name="txtmat" value="<?php echo $record->nombre ?>"/>

        Description :
        <textarea name="txtdesc" value="<?php echo $record->descripcion ?>"></textarea>

        Hours :
        <input type="text" name="txtcarga"/>

        <input type="submit" value="Save"/>

Do not understand what should i do :S

Body:
I think Rushabh thinks you should pass your $id with your data to the model like this:

$this->Crudmodel->saveup($txtcarr,$txtmat,$txtdesc,$txtcarga, $id);

and in your model you can:

$this->db->where("id", $id);
$this->db->update('materias', $data);

and don't forget to remove your where condition in the controller;

Edit:

your get_id_row() function needs to be:

public function get_id_row($id){
  $query = $this->db->get_where('your_table_name', array('id' => $id));
  return $query->row();
}


问:
nao/pepper soft-bank html
hi I have a pepper from Softbank

and I can't figure out how to send a string from pepper behavior to a HTML page. dos anybody now wat API or what method pepper can send a string to a HTML page that is showing on pepper tablet.

HTML is in pepper behavior and is running on the tablet of pepper
behavior need send just a string of info
and HTML page on pepper need to catch it

html script

```<code>function yourMethod(data) {
var a = angular.fromJson(data);
var weekday = new Array(7);
console.log(str(data));
console.log('test1');

window.addEventListener("message", yourMethod, false);
</code>```

答:
Within the naoqi sdk you can find a "qimessaging.js" file(/var/www/libs/qimessaging/1.0/qimessaging.js)  that helps you connect a webpage (running on the tablet) to the head of pepper.

You use these functionalities by adding the following line to the head of your html script:

```<code><script src="/libs/qimessaging/1.0/qimessaging.js"></script>
</code>```

You can also find a complete tutorial here:
http://protolab.aldebaran.com:9000/protolab/tutorials/tree/master/ConnectionHtmlChoregraphe

Title: nao/pepper soft-bank html

Body:
hi I have a pepper from Softbank

and I can't figure out how to send a string from pepper behavior to a HTML page. dos anybody now wat API or what method pepper can send a string to a HTML page that is showing on pepper tablet.

HTML is in pepper behavior and is running on the tablet of pepper
behavior need send just a string of info
and HTML page on pepper need to catch it

html script

function yourMethod(data) {
var a = angular.fromJson(data);
var weekday = new Array(7);
console.log(str(data));
console.log('test1');

window.addEventListener("message", yourMethod, false);

Body:
Within the naoqi sdk you can find a "qimessaging.js" file(/var/www/libs/qimessaging/1.0/qimessaging.js)  that helps you connect a webpage (running on the tablet) to the head of pepper.

You use these functionalities by adding the following line to the head of your html script:

<script src="/libs/qimessaging/1.0/qimessaging.js"></script>

You can also find a complete tutorial here:
http://protolab.aldebaran.com:9000/protolab/tutorials/tree/master/ConnectionHtmlChoregraphe


问:
SQL, OR AND STATEMENT
Does the AND Statement after the OR statement have the same logic as something similar to

```<code>where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
 and
  d.status = ('C')
 OR
  d.status IN ('R' ,'D')
     AND
    t.done_dt = DATEADD(month, -1, GETDATE())

where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
IF d.status  IN ('R','D')
  t.done_dt = DATEADD(month, -1, GETDATE())
 ELSE
  d.status = 'C'
</code>```

Which one is the correct way to format it?

I'm trying to display all d.status with the 'C' status. But only if the t.done_dt is the previous month, do I want to display d.status IN ('R', 'D')

答:
In the first place don't bother with operators precedence and use explicit ( ). It will add to your readability.

If you want to see all status 'R','D' of your previous month you would need to change a bit your query:

```<code>where d.res_id = 125 and t.task_type in ('PPB', 'PPO') AND
   (  d.status = 'C'
   OR ( d.status IN ('R', 'D') and
        -- Compare the first day of the month of your date and first day of the current month
        CONVERT(DATE,dateadd(dd,-(day(t.done_dt)-1),t.done_dt)) = DATEADD(MONTH, -1, CONVERT(DATE,dateadd(dd,-(day(getdate())-1),getdate()))
      )
    )
</code>```

Title: SQL, OR AND STATEMENT

Body:
Does the AND Statement after the OR statement have the same logic as something similar to

where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
 and
  d.status = ('C')
 OR
  d.status IN ('R' ,'D')
     AND
    t.done_dt = DATEADD(month, -1, GETDATE())

where  d.res_id = 125 and t.task_type in( 'PPB', 'PPO')
IF d.status  IN ('R','D')
  t.done_dt = DATEADD(month, -1, GETDATE())
 ELSE
  d.status = 'C'

Which one is the correct way to format it?

I'm trying to display all d.status with the 'C' status. But only if the t.done_dt is the previous month, do I want to display d.status IN ('R', 'D')

Body:
In the first place don't bother with operators precedence and use explicit ( ). It will add to your readability.

If you want to see all status 'R','D' of your previous month you would need to change a bit your query:

where d.res_id = 125 and t.task_type in ('PPB', 'PPO') AND
   (  d.status = 'C'
   OR ( d.status IN ('R', 'D') and
        -- Compare the first day of the month of your date and first day of the current month
        CONVERT(DATE,dateadd(dd,-(day(t.done_dt)-1),t.done_dt)) = DATEADD(MONTH, -1, CONVERT(DATE,dateadd(dd,-(day(getdate())-1),getdate()))
      )
    )


问:
Optimize a algorithm that find a specific Fibonacci number

Given an number A, I want to find the Ath Fibonacci number
  that is multiple of 3 or if the number representation has at least a 3
  on it.

Example:

Fibonacci > 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ...

Input: 1, Output: 3;

3 is the first Fibonacci number that is multiple of 3 or has an 3 on
  it.

Input: 3, Output: 21;

21 is the third Fibonacci number that is multiple of 3 or has an 3 on
  it.

Edit: Variable type changed to unsigned long long int and ajust on Fibonacci generator. Thanks @rcgldr and @Jarod42 for the help!

My code:

```<code>#include<bits/stdc++.h>

using namespace std;

int tem(unsigned long long int i){

    while(i != 0){
        if(i%10 == 3){
            return true;
        }
        i = i/10;
    }
    return false;
}

int main(){

    int a, count = 0;
    unsigned long long int f1 = 1, f2 = 1;

    while(scanf("%d", &a) != EOF){
        for(unsigned long long int i = 2; i > 0; i++){
            i = f1 + f2;
            f1 = f2;
            f2 = i;
                if((i%3 == 0) || tem(i)){
                    count++;
                    if(count == a){
                        cout << i << endl;
                        break;
                    }
                }

        }
    }
}
</code>```

When A > 20, it starts to slow down. Makes sense because it tends to be exponecial. My code is not very efficient, but I didn't find an better logic to use.

I looked into these links, but didn't find an conclusion:

1 - Recursive Fibonacci

2 - Fibonacci Optimization

Any ideas? Thanks for the help!

答:
There's a clever way to do Fibonacci.

http://stsievert.com/blog/2015/01/31/the-mysterious-eigenvalue/

Code's in python and is just for the nth number, but I think you get the idea.

```<code>def fib(n):
    lambda1 = (1 + sqrt(5))/2
    lambda2 = (1 - sqrt(5))/2
    return (lambda1**n - lambda2**n) / sqrt(5)
def fib_approx(n)
    # for practical range, percent error < 10^-6
    return 1.618034**n / sqrt(5)
</code>```

Body:
Given an number A, I want to find the Ath Fibonacci number
  that is multiple of 3 or if the number representation has at least a 3
  on it.

Example:

Fibonacci > 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, ...

Input: 1, Output: 3;

3 is the first Fibonacci number that is multiple of 3 or has an 3 on
  it.

Input: 3, Output: 21;

21 is the third Fibonacci number that is multiple of 3 or has an 3 on
  it.

Edit: Variable type changed to unsigned long long int and ajust on Fibonacci generator. Thanks @rcgldr and @Jarod42 for the help!

My code:

#include<bits/stdc++.h>

using namespace std;

int tem(unsigned long long int i){

    while(i != 0){
        if(i%10 == 3){
            return true;
        }
        i = i/10;
    }
    return false;
}

int main(){

    int a, count = 0;
    unsigned long long int f1 = 1, f2 = 1;

    while(scanf("%d", &a) != EOF){
        for(unsigned long long int i = 2; i > 0; i++){
            i = f1 + f2;
            f1 = f2;
            f2 = i;
                if((i%3 == 0) || tem(i)){
                    count++;
                    if(count == a){
                        cout << i << endl;
                        break;
                    }
                }

        }
    }
}

When A > 20, it starts to slow down. Makes sense because it tends to be exponecial. My code is not very efficient, but I didn't find an better logic to use.

I looked into these links, but didn't find an conclusion:

1 - Recursive Fibonacci

2 - Fibonacci Optimization

Any ideas? Thanks for the help!

Body:
There's a clever way to do Fibonacci.

http://stsievert.com/blog/2015/01/31/the-mysterious-eigenvalue/

Code's in python and is just for the nth number, but I think you get the idea.

def fib(n):
    lambda1 = (1 + sqrt(5))/2
    lambda2 = (1 - sqrt(5))/2
    return (lambda1**n - lambda2**n) / sqrt(5)
def fib_approx(n)
    # for practical range, percent error < 10^-6
    return 1.618034**n / sqrt(5)


问:
Angular2 - Supplied parameters do not match any signature of call target
```<code>import { Component, Input, OnChanges } from '@angular/core';

@Component({
  selector: 'image-display',
  templateUrl: './image-display.component.html'
})
export class ImageDisplayComponent implements OnChanges {
  @Input() image: File;
  @Input() imagePath?: string;

  private fileReader: FileReader;

  constructor() { }

  ngOnChanges() {
    if (this.image && this.fileReader) {
      this.fileReader.readAsDataURL(this.image);
    }
  }
}
</code>```

On compiling this with AOT getting below error:

```<code>PRINHYLTPAP0592:matata ajays$ ng build --prod --aot
/myApp/src/$$_gendir/app/image-uploader/image-display/image-display.component.ngfactory.ts (61,9):
Supplied parameters do not match any signature of call target.
</code>```

答:
AOT forces you to inform every single mandatory parameter for every method call.

In your example, the method ngOnChanges() should actually be ngOnChanges(changes: SimpleChanges).

Body:
import { Component, Input, OnChanges } from '@angular/core';

@Component({
  selector: 'image-display',
  templateUrl: './image-display.component.html'
})
export class ImageDisplayComponent implements OnChanges {
  @Input() image: File;
  @Input() imagePath?: string;

  private fileReader: FileReader;

  constructor() { }

  ngOnChanges() {
    if (this.image && this.fileReader) {
      this.fileReader.readAsDataURL(this.image);
    }
  }
}

On compiling this with AOT getting below error:

PRINHYLTPAP0592:matata ajays$ ng build --prod --aot
/myApp/src/$$_gendir/app/image-uploader/image-display/image-display.component.ngfactory.ts (61,9):
Supplied parameters do not match any signature of call target.


问:
Using Simple Injector with Background worker in WinForms to Save to DB using EF6
I've been given an old WinForms app to update and improve. I am trying to add DI using SimpleInjector. I'm used to .Net MVC but this is my first time working with WinForms.

The application uses a lot of BackGround workers. My understanding is that this is specific to WinForms and each Background worker creates a new thread.

I think my problem is that when I want to save data to the DB using EF6 the SaveChanges method isn't able to save because of the multiple threads.

My SimpleInjector container is set up as follows

```<code>_container = new Container();
_container.Options.DefaultScopedLifestyle = new ThreadScopedLifestyle();

// Register DbContext
_container.Register<DbContext, MyDbContext>(Lifestyle.Scoped);
</code>```

When I call SaveChanges on my dbContext I get a result of 0, which indicates that no records were saved to the database. In my debugger I get an error saying that the DbContext has been disposed. If this is happening before the save it explains why a 0 is returned from SaveChanges. Unfortunately the previous developer caught every exception so the application is trying to handle every error and this is making troubleshooting difficult and leading to unexpected behavior.

I am expecting a new DbContext to be created for each thread and that SaveChanges will save the changes made in each thread, so that what happens in one context won't affect other DbContexts in other threads.

When I am reading from the database I manually create a new DbContext in each method. Is it possible that when the using block has completed it is disposing the DbContext ?

```<code>using (var newDbContext = new MyDbContext())
{
    return newDbContext.Set<TableA>().First(x => x.Id == id);
}
</code>```

I'm hoping that if I have SimpleInjector configured correctly I won't need to do this either.

I'm a little lost at this stage and think I might not be understanding the documentation correctly, any advise would be greatly appreciated. Thanks in advance.

答:
I am expecting a new DbContext to be created for each thread

This is not how TheadScopedLifestyle works. With the ThreadScopedLifestyle, there will be one instance of your registration within the context of an explicitly started Scope and this scope is thread-specific. This means that one thread can have many instances of that service, since a thread can live for a long time, while a Scope will typically only live for a short amount of time.

A typical use for ThreadScopedLifestyle is the following:

```<code>void MethodThatRunsInABackGroundThread()
{
    using (ThreadScopedLifestyle.BeginScope(container))
    {
        var service = container.GetInstance<ISomeService>();
        service.DoWork();
    }
}
</code>```

When you resolve Scoped instances (or some object graph that contains scoped instances) outside an active scope, Simple Injector will throw an exception.

Body:
I've been given an old WinForms app to update and improve. I am trying to add DI using SimpleInjector. I'm used to .Net MVC but this is my first time working with WinForms.

The application uses a lot of BackGround workers. My understanding is that this is specific to WinForms and each Background worker creates a new thread.

I think my problem is that when I want to save data to the DB using EF6 the SaveChanges method isn't able to save because of the multiple threads.

My SimpleInjector container is set up as follows

_container = new Container();
_container.Options.DefaultScopedLifestyle = new ThreadScopedLifestyle();

// Register DbContext
_container.Register<DbContext, MyDbContext>(Lifestyle.Scoped);

When I call SaveChanges on my dbContext I get a result of 0, which indicates that no records were saved to the database. In my debugger I get an error saying that the DbContext has been disposed. If this is happening before the save it explains why a 0 is returned from SaveChanges. Unfortunately the previous developer caught every exception so the application is trying to handle every error and this is making troubleshooting difficult and leading to unexpected behavior.

I am expecting a new DbContext to be created for each thread and that SaveChanges will save the changes made in each thread, so that what happens in one context won't affect other DbContexts in other threads.

When I am reading from the database I manually create a new DbContext in each method. Is it possible that when the using block has completed it is disposing the DbContext ?

using (var newDbContext = new MyDbContext())
{
    return newDbContext.Set<TableA>().First(x => x.Id == id);
}

I'm hoping that if I have SimpleInjector configured correctly I won't need to do this either.

I'm a little lost at this stage and think I might not be understanding the documentation correctly, any advise would be greatly appreciated. Thanks in advance.

Body:
I am expecting a new DbContext to be created for each thread

This is not how TheadScopedLifestyle works. With the ThreadScopedLifestyle, there will be one instance of your registration within the context of an explicitly started Scope and this scope is thread-specific. This means that one thread can have many instances of that service, since a thread can live for a long time, while a Scope will typically only live for a short amount of time.

A typical use for ThreadScopedLifestyle is the following:

void MethodThatRunsInABackGroundThread()
{
    using (ThreadScopedLifestyle.BeginScope(container))
    {
        var service = container.GetInstance<ISomeService>();
        service.DoWork();
    }
}

When you resolve Scoped instances (or some object graph that contains scoped instances) outside an active scope, Simple Injector will throw an exception.


问:
adding variables numical values (newb question)
Yesterday i had a look at how to set values of variables from nummbers stored in external txt files

the variables then needed to be added up so i used trial and  error first

((XVAL) + (NEWVAL))

assuming that XVAL was set to 10 and NEWVAL was set to 20 i expected to get the answer of thirty but waqs presented with the new value of 10 20

VB.net pysicaly added the two values together but i wanted the mathematical product of the two which is ((10) + (20)) = 30

yep its a newb question could anyone explain how to achieve what im affter

答:
The + operator in VB.NET (for backwards-compatibility reasons) means both add and concatenate depending on the types of the variables it is being used with. With two numeric types (Integer, Single, Double, etc.), it adds the values together as you would expect. However, with String types, it concatenates the two strings.

Presumably, then, your XVAL and NEWVAL variables are String types because they're being read out of a text file, which is causing VB.NET to concatenate them into a new string instead of add them together. To get the behavior you're expecting, you need to convert them to numeric types.

Some of the other answers suggest casting simply casting the string values to numeric types (CInt, CSng, CDbl, etc.), but this may not work as expected if the value contained by your string cannot be converted to number. The Int32.Parse method will throw an exception if the value held by your string cannot be represented as a number. This is especially important to keep in mind if you're reading values from a text file that are not guaranteed to adhere to any particular constraints.

Instead, you probably want to use something like Int32.TryParse, which returns a Boolean value indicating whether or not the conversion succeeded and will not throw an exception.


问:
Angular UI Grid - Exporting an image to a pdf
I want to add an image to the header of the pdf.

I am trying to add the image, which I converted to base 64, to exporterPdfHeader.

```<code> $scope.gmGrid.exporterPdfHeader = {
            margin: [30, 5, 30, 15],

                table: {

                widths: [ '*', '*' ],

                body: [
                  [ 'MC #: ' + $scope.mc, 'Week Ending Date: ' + $scope.weekEndDate ],

                ],

                  //ADD IMAGE
                    myImage:    'data:image/false;base64,[encoded data, 4980 characters]',
                    width: 150,
                    height: 150,

              },

            },
</code>```

There is no error in the console.  Not sure what I am missing.  Any help is appreciated.

UPDATE***

I added in the column with the image inside exporterPdfHeader, but when I do this it does not show the header which is contained in the body.  It just shows the image and the table.

```<code>$scope.gridOptions.exporterPdfHeader ={

                    //title: 'test',

                    //LOGO TEST (causes the header to disappear..
                    columns: [{
                            image: 'data:image/false;base64,[encoded data, 4980 characters]',
                            width: 150
                    }],

                    margin: [30, 5, 30, 15],
                    table: {
                    widths: [ '*', '*', '*' /*, '*'*/ ],

                    body: [

                           [ 'Region: ' + $scope.region, 'Group: ' + $scope.group, 'MC: ' + $scope.mc /*, 'The last one'*/ ],
                           [ 'District #: ' + $scope.district, 'Route #: ' + $scope.route, 'Week Ending Date: ' + $scope.weekEndDate, /*, 'Value 4' */],

                    ]
                  },

    };
</code>```

答:
This should get you started:

And here's the relevant angularJS code:

```<code>$scope.export = function() {
  var exportData = [];
  var exportColumnHeaders = $scope.gridOptions.showHeader ? uiGridExporterService.getColumnHeaders($scope.gridApi.grid, uiGridExporterConstants.VISIBLE) : [];
  angular.forEach($scope.gridApi.grid.rows, function(row) {
    if (row.visible) {
      var values = [];
      angular.forEach(exportColumnHeaders, function(column) {
        var value = row.entity[column.name];
        if (column.name == 'rentalCreditPercentTues') value = $filter('percentFilter')(value);
        values.push({
          value: value
        });
      });
      exportData.push(values);
    }
  });
  var content = uiGridExporterService.prepareAsPdf($scope.gridApi.grid, exportColumnHeaders, exportData);
  content.pageMargins = [40, 80, 40, 60];
  pdfMake.createPdf(content).open();
};
$scope.gridOptions = {
  exporterPdfHeader: {
    margin: 20,
    columns: [{
      image: 'data:image/false;base64,[encoded data, 4980 characters]',
      width: 150
    }]
  }
};
</code>```

The trick is creating enough space in the page header using the pageMargins.

Here's the all important Plunker, http://plnkr.co/edit/1rL7ZBPu9mPym8SEjMxe?p=preview.

Let me know if you need anymore help.

Body:
I want to add an image to the header of the pdf.

I am trying to add the image, which I converted to base 64, to exporterPdfHeader.

 $scope.gmGrid.exporterPdfHeader = {
            margin: [30, 5, 30, 15],

                table: {

                widths: [ '*', '*' ],

                body: [
                  [ 'MC #: ' + $scope.mc, 'Week Ending Date: ' + $scope.weekEndDate ],

                ],

                  //ADD IMAGE
                    myImage:    'data:image/false;base64,[encoded data, 4980 characters]',
                    width: 150,
                    height: 150,

              },

            },

There is no error in the console.  Not sure what I am missing.  Any help is appreciated.

UPDATE***

I added in the column with the image inside exporterPdfHeader, but when I do this it does not show the header which is contained in the body.  It just shows the image and the table.

$scope.gridOptions.exporterPdfHeader ={

                    //title: 'test',

                    //LOGO TEST (causes the header to disappear..
                    columns: [{
                            image: 'data:image/false;base64,[encoded data, 4980 characters]',
                            width: 150
                    }],

                    margin: [30, 5, 30, 15],
                    table: {
                    widths: [ '*', '*', '*' /*, '*'*/ ],

                    body: [

                           [ 'Region: ' + $scope.region, 'Group: ' + $scope.group, 'MC: ' + $scope.mc /*, 'The last one'*/ ],
                           [ 'District #: ' + $scope.district, 'Route #: ' + $scope.route, 'Week Ending Date: ' + $scope.weekEndDate, /*, 'Value 4' */],

                    ]
                  },

    };

Body:
This should get you started:

And here's the relevant angularJS code:

$scope.export = function() {
  var exportData = [];
  var exportColumnHeaders = $scope.gridOptions.showHeader ? uiGridExporterService.getColumnHeaders($scope.gridApi.grid, uiGridExporterConstants.VISIBLE) : [];
  angular.forEach($scope.gridApi.grid.rows, function(row) {
    if (row.visible) {
      var values = [];
      angular.forEach(exportColumnHeaders, function(column) {
        var value = row.entity[column.name];
        if (column.name == 'rentalCreditPercentTues') value = $filter('percentFilter')(value);
        values.push({
          value: value
        });
      });
      exportData.push(values);
    }
  });
  var content = uiGridExporterService.prepareAsPdf($scope.gridApi.grid, exportColumnHeaders, exportData);
  content.pageMargins = [40, 80, 40, 60];
  pdfMake.createPdf(content).open();
};
$scope.gridOptions = {
  exporterPdfHeader: {
    margin: 20,
    columns: [{
      image: 'data:image/false;base64,[encoded data, 4980 characters]',
      width: 150
    }]
  }
};

The trick is creating enough space in the page header using the pageMargins.

Here's the all important Plunker, http://plnkr.co/edit/1rL7ZBPu9mPym8SEjMxe?p=preview.

Let me know if you need anymore help.


问:
C# USB eToken signature and validation issue
I have an x509 certificate with a public and private key that is stored on a safenet usb token.

I have some data I want to sign.  I need to use the public key of the certificate to verify the signature.

Ultimate code doing the signing with my own self signed certificate:

```<code>RSACryptoServiceProvider rsa1 = (RSACryptoServiceProvider)useCertificate.PrivateKey;
byte[] digitalSignature = rsa1.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
</code>```

And the code to verify using the public key of the certificate:

```<code>RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)useCertificate.PublicKey.Key;
Verified = rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), digitalSignature);
</code>```

With the self signed certificate this works fine.  The signature I get back is 256

Bytes.

With the token using this code to obtain the signature and then verify it, I get only 128 Byte signature and the verify fails:

```<code>CspParameters csp = new CspParameters(1, "SafeNet RSA CSP");
csp.Flags = CspProviderFlags.UseDefaultKeyContainer;
csp.KeyNumber = (int)KeyNumber.Signature;
RSACryptoServiceProvider rsa1 = new RSACryptoServiceProvider(csp);
</code>```

Verify code same as above.

I note that the certificate I want to use is the default in the token.  Why am I only getting a 128 Byte signature back instead of 256?  I suspect that is why it won't verify.

Do I need some other parameters and settings in my csp?

Thanks

* Update based on comments *

It's clear that I am using 1024 bits when I specify the csp.keyNumber = (int)KeyNumber.Signature - but this is the only way the token actually returns anything.  Even though the token key size is 2048 bits and the key specification is AT_KEYEXCHANGE.  When I use the exchange keynumber which I think is actually correct, then when I try to compute a signature I am prompted to login, but then I get an exception "The parameter is invalid".   So I need one of 2 things as far as I can see:

1 - how to use the public key to verify the signature using 1024 bits (without the token - we need to verify on a machine without the token).

or

2 - how to set whatever is incorrect so that we can get passed the exception -- which I think is the better idea.

Does anyone have any advice on what I can do about this exception or what might be causing it?

Full exception details below:

HResult = -2147024809
Message = The parameter is incorrect.
Stack Trace

at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
   at System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey, Int32 keyNumber, Int32 calgKey, Int32 calgHash, Byte[] hash, Int32 cbHash, ObjectHandleOnStack retSignature)
   at System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey, Int32 keyNumber, Int32 calgKey, Int32 calgHash, Byte[] hash)
   at System.Security.Cryptography.RSACryptoServiceProvider.SignHash(Byte[] rgbHash, Int32 calgHash)
   at System.Security.Cryptography.RSACryptoServiceProvider.SignHash(Byte[] rgbHash, String str)
   at TE.Program.Main(String[] args) in z:\Work\compusolve\enctest\TE\TE\Program.cs:line 77

答:
The answer to this is two fold.  If you are using one of these devices, I found that in the registry under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\Defaults\Provider

There are 3 different providers.  Each with identical settings for type and even image - the dll used.  But selecting a different one, in my case Datakey RSP CSP, provided the 256 byte signature based on the 2048 bit key.  You also have to ensure that the certificate you are using is the default certificate in the token.  In my case there were two different certificates.  I was verifying using one, but signing using another.

Complete source code for a test client is below:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;

namespace TE
{
class Program
{
    static void Main(string[] args)
    {
        try
        {

            // these variables should be changed to math your installation

            // find CSP's in this windows registry key:  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\Defaults\Provider
            string TokenCSPName = "Datakey RSA CSP";
            string TokenCertificateName = "ACME Inc";
            string NonTokenCertificateName = "SelfSigned";
            string certLocation = "Token"; // change to something else to use self signed "Token" for token
            // the certificate on the token should be installed into the local users certificate store
            // tokens will not store or export the private key, only the public key

            // find the certificate we want to use - there's no recovery if the certificate is not found

            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.OpenExistingOnly);
            X509Certificate2Collection certificates = store.Certificates;
            X509Certificate2 certificate = new X509Certificate2();
            X509Certificate2 useCertificate = new X509Certificate2();
            if (certLocation == "Token")
            {
                for (int i = 0; i < certificates.Count; i++)
                {
                    certificate = certificates[i];
                    string subj = certificate.Subject;
                    List<X509KeyUsageExtension> extensions = certificate.Extensions.OfType<X509KeyUsageExtension>().ToList();
                    if (certificate.GetNameInfo(X509NameType.SimpleName, false).ToString() == TokenCertificateName)
                    {
                        for (int j = 0; j < extensions.Count; j++)
                        {
                            if ((extensions[j].KeyUsages & X509KeyUsageFlags.DigitalSignature) == X509KeyUsageFlags.DigitalSignature)
                            {
                                useCertificate = certificate;
                                j = extensions.Count + 1;
                            }

                        }

                    }
                }
            } else
            {
                for (int i = 0; i < certificates.Count; i++)
                {
                    certificate = certificates[i];
                    string subj = certificate.Subject;
                    List<X509KeyUsageExtension> extensions = certificate.Extensions.OfType<X509KeyUsageExtension>().ToList();
                    if (certificate.GetNameInfo(X509NameType.SimpleName, false).ToString() == NonTokenCertificateName)
                        useCertificate = certificate;
                }

            }
            CspParameters csp = new CspParameters(1, TokenCSPName);

            csp.Flags = CspProviderFlags.UseDefaultKeyContainer;
            csp.KeyNumber = (int)KeyNumber.Exchange;
            RSACryptoServiceProvider rsa1 = new RSACryptoServiceProvider(csp);
            string SignatureString = "Data that is to be signed";
            byte[] plainTextBytes = Encoding.ASCII.GetBytes(SignatureString);
            bool Verified = false;
            using (SHA1CryptoServiceProvider shaM = new SHA1CryptoServiceProvider())
            {
                // hash the data to be signed - you can use signData and avoid the hashing if you like

                byte[] hash = shaM.ComputeHash(plainTextBytes);
                // sign the hash
                byte[] digitalSignature = rsa1.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
                // check your signature size here - if not 256 bytes then you may not be using the proper
                // crypto provider

                // Verify the signature with the hash

                RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)useCertificate.PublicKey.Key;
                Verified = rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), digitalSignature);
                if (Verified)
                {
                    Console.WriteLine("Signature Verified");
                }
                else
                {
                    Console.WriteLine("Signature Failed Verification");
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
  }
}
</code>```

Body:
I have an x509 certificate with a public and private key that is stored on a safenet usb token.

I have some data I want to sign.  I need to use the public key of the certificate to verify the signature.

Ultimate code doing the signing with my own self signed certificate:

RSACryptoServiceProvider rsa1 = (RSACryptoServiceProvider)useCertificate.PrivateKey;
byte[] digitalSignature = rsa1.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));

And the code to verify using the public key of the certificate:

RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)useCertificate.PublicKey.Key;
Verified = rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), digitalSignature);

With the self signed certificate this works fine.  The signature I get back is 256

Bytes.

With the token using this code to obtain the signature and then verify it, I get only 128 Byte signature and the verify fails:

CspParameters csp = new CspParameters(1, "SafeNet RSA CSP");
csp.Flags = CspProviderFlags.UseDefaultKeyContainer;
csp.KeyNumber = (int)KeyNumber.Signature;
RSACryptoServiceProvider rsa1 = new RSACryptoServiceProvider(csp);

Verify code same as above.

I note that the certificate I want to use is the default in the token.  Why am I only getting a 128 Byte signature back instead of 256?  I suspect that is why it won't verify.

Do I need some other parameters and settings in my csp?

Thanks

* Update based on comments *

It's clear that I am using 1024 bits when I specify the csp.keyNumber = (int)KeyNumber.Signature - but this is the only way the token actually returns anything.  Even though the token key size is 2048 bits and the key specification is AT_KEYEXCHANGE.  When I use the exchange keynumber which I think is actually correct, then when I try to compute a signature I am prompted to login, but then I get an exception "The parameter is invalid".   So I need one of 2 things as far as I can see:

1 - how to use the public key to verify the signature using 1024 bits (without the token - we need to verify on a machine without the token).

or

2 - how to set whatever is incorrect so that we can get passed the exception -- which I think is the better idea.

Does anyone have any advice on what I can do about this exception or what might be causing it?

Full exception details below:

HResult = -2147024809
Message = The parameter is incorrect.
Stack Trace

at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
   at System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey, Int32 keyNumber, Int32 calgKey, Int32 calgHash, Byte[] hash, Int32 cbHash, ObjectHandleOnStack retSignature)
   at System.Security.Cryptography.Utils.SignValue(SafeKeyHandle hKey, Int32 keyNumber, Int32 calgKey, Int32 calgHash, Byte[] hash)
   at System.Security.Cryptography.RSACryptoServiceProvider.SignHash(Byte[] rgbHash, Int32 calgHash)
   at System.Security.Cryptography.RSACryptoServiceProvider.SignHash(Byte[] rgbHash, String str)
   at TE.Program.Main(String[] args) in z:\Work\compusolve\enctest\TE\TE\Program.cs:line 77

Body:
The answer to this is two fold.  If you are using one of these devices, I found that in the registry under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\Defaults\Provider

There are 3 different providers.  Each with identical settings for type and even image - the dll used.  But selecting a different one, in my case Datakey RSP CSP, provided the 256 byte signature based on the 2048 bit key.  You also have to ensure that the certificate you are using is the default certificate in the token.  In my case there were two different certificates.  I was verifying using one, but signing using another.

Complete source code for a test client is below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;

namespace TE
{
class Program
{
    static void Main(string[] args)
    {
        try
        {

            // these variables should be changed to math your installation

            // find CSP's in this windows registry key:  HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\Defaults\Provider
            string TokenCSPName = "Datakey RSA CSP";
            string TokenCertificateName = "ACME Inc";
            string NonTokenCertificateName = "SelfSigned";
            string certLocation = "Token"; // change to something else to use self signed "Token" for token
            // the certificate on the token should be installed into the local users certificate store
            // tokens will not store or export the private key, only the public key

            // find the certificate we want to use - there's no recovery if the certificate is not found

            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.OpenExistingOnly);
            X509Certificate2Collection certificates = store.Certificates;
            X509Certificate2 certificate = new X509Certificate2();
            X509Certificate2 useCertificate = new X509Certificate2();
            if (certLocation == "Token")
            {
                for (int i = 0; i < certificates.Count; i++)
                {
                    certificate = certificates[i];
                    string subj = certificate.Subject;
                    List<X509KeyUsageExtension> extensions = certificate.Extensions.OfType<X509KeyUsageExtension>().ToList();
                    if (certificate.GetNameInfo(X509NameType.SimpleName, false).ToString() == TokenCertificateName)
                    {
                        for (int j = 0; j < extensions.Count; j++)
                        {
                            if ((extensions[j].KeyUsages & X509KeyUsageFlags.DigitalSignature) == X509KeyUsageFlags.DigitalSignature)
                            {
                                useCertificate = certificate;
                                j = extensions.Count + 1;
                            }

                        }

                    }
                }
            } else
            {
                for (int i = 0; i < certificates.Count; i++)
                {
                    certificate = certificates[i];
                    string subj = certificate.Subject;
                    List<X509KeyUsageExtension> extensions = certificate.Extensions.OfType<X509KeyUsageExtension>().ToList();
                    if (certificate.GetNameInfo(X509NameType.SimpleName, false).ToString() == NonTokenCertificateName)
                        useCertificate = certificate;
                }

            }
            CspParameters csp = new CspParameters(1, TokenCSPName);

            csp.Flags = CspProviderFlags.UseDefaultKeyContainer;
            csp.KeyNumber = (int)KeyNumber.Exchange;
            RSACryptoServiceProvider rsa1 = new RSACryptoServiceProvider(csp);
            string SignatureString = "Data that is to be signed";
            byte[] plainTextBytes = Encoding.ASCII.GetBytes(SignatureString);
            bool Verified = false;
            using (SHA1CryptoServiceProvider shaM = new SHA1CryptoServiceProvider())
            {
                // hash the data to be signed - you can use signData and avoid the hashing if you like

                byte[] hash = shaM.ComputeHash(plainTextBytes);
                // sign the hash
                byte[] digitalSignature = rsa1.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
                // check your signature size here - if not 256 bytes then you may not be using the proper
                // crypto provider

                // Verify the signature with the hash

                RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)useCertificate.PublicKey.Key;
                Verified = rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), digitalSignature);
                if (Verified)
                {
                    Console.WriteLine("Signature Verified");
                }
                else
                {
                    Console.WriteLine("Signature Failed Verification");
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
  }
}


问:
How to stop a self hosted Kestrel application?
I have the canonical code to self host an asp.net mvc application, inside a task:

```<code>            Task hostingtask = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("hosting ffoqsi");
                IWebHost host = new WebHostBuilder()
                    .UseKestrel()
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseIISIntegration()
                    .UseStartup<Startup>()
                    .UseApplicationInsights()
                    .Build();

                host.Run();
            }, canceltoken);
</code>```

When I cancel this task, an ObjectDisposedException throws. How can I gracefully shut down the host?

答:
You could send a request to your web server that would call a controller action that, via the injected IApplicationLifetime, would call a StopApplication(). Would it work for you?

https://learn.microsoft.com/en-us/aspnet/core/api/microsoft.aspnetcore.hosting.iapplicationlifetime

ContentLicense: CC BY-SA 4.0

Body:
I have the canonical code to self host an asp.net mvc application, inside a task:

            Task hostingtask = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("hosting ffoqsi");
                IWebHost host = new WebHostBuilder()
                    .UseKestrel()
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseIISIntegration()
                    .UseStartup<Startup>()
                    .UseApplicationInsights()
                    .Build();

                host.Run();
            }, canceltoken);

When I cancel this task, an ObjectDisposedException throws. How can I gracefully shut down the host?


问:
Capitalizing last letter in Java using String methods
how can i capitalize the last letter of a String? Is there a method in the String Class to do this?

I'm practicing with some exercise, and i was asked to do this with a method.

答:
No there is not. but you can write one yourself. </p>

```<code> public String capitalizeLastLetter(String word) {
    //null check
    int length = word.length();
    String capitalizedLetter = word.substring(length - 2, length - 1).toUppercase();
    return word.substring(0, length - 2) + capitalizedLetter;
}
</code>```

Body:
No there is not. but you can write one yourself.

 public String capitalizeLastLetter(String word) {
    //null check
    int length = word.length();
    String capitalizedLetter = word.substring(length - 2, length - 1).toUppercase();
    return word.substring(0, length - 2) + capitalizedLetter;
}


问:
h2o basic parse file
I am new to h2o. I am using h2o-3.10.4.2 on Windows 7, java 1.8. I am using h2o flow. Just going through the k-modes demo. If I import seeds_dataset.txt     file from https://archive.ics.uci.edu/ml/machine-learning-databases/00236/ and try to parse it then at record number 8, parser fails to capture column 7 and 8. This is most probably due to 2 tabs. I want the parser to consider any white spaces as a separator. Please note that if i use "http://s3.amazonaws.com/h2o-public-test-data/smalldata/flow_examples/seeds_dataset.txt" then i do not face any issues as tabs are sorted out.

So finally i want to know that when i use parseFiles in h2o how do i set any whitespaces as separator. i tried using startoftext etc but i am not able to get all the columns.

答:
I followed Flow's suggested parse setup and it worked fine (found the \t separator and 8 columns) - no manual intervention needed. Can you compare your steps with these please?

```<code>importFiles [ "https://archive.ics.uci.edu/ml/machine-learning-databases/00236/seeds_dataset.txt" ]

setupParse source_frames: [ "https://archive.ics.uci.edu/ml/machine-learning-databases/00236/seeds_dataset.txt" ]

parseFiles
  source_frames: ["https://archive.ics.uci.edu/ml/machine-learning-databases/00236/seeds_dataset.txt"]
  destination_frame: "seeds_dataset1.hex"
  parse_type: "CSV"
  separator: 9
  number_columns: 8
  single_quotes: false
  column_names: null
  column_types: ["Numeric","Numeric","Numeric","Numeric","Numeric","Numeric","Numeric","Numeric"]
  delete_on_done: true
  check_header: -1
  chunk_size: 4194304
</code>```

This is the view from
    getFrameSummary "seeds_dataset1.hex"

Clicked on 'View Data":

```<code>Row C1  C2  C3  C4  C5  C6  C7  C8
1   15.2600 14.8400 0.8710  5.7630  3.3120  2.2210  5.2200  1.0
2   14.8800 14.5700 0.8811  5.5540  3.3330  1.0180  4.9560  1.0
3   14.2900 14.0900 0.9050  5.2910  3.3370  2.6990  4.8250  1.0
etc.
</code>```

Title: h2o basic parse file

Body:
I followed Flow's suggested parse setup and it worked fine (found the \t separator and 8 columns) - no manual intervention needed. Can you compare your steps with these please?

importFiles [ "https://archive.ics.uci.edu/ml/machine-learning-databases/00236/seeds_dataset.txt" ]

setupParse source_frames: [ "https://archive.ics.uci.edu/ml/machine-learning-databases/00236/seeds_dataset.txt" ]

parseFiles
  source_frames: ["https://archive.ics.uci.edu/ml/machine-learning-databases/00236/seeds_dataset.txt"]
  destination_frame: "seeds_dataset1.hex"
  parse_type: "CSV"
  separator: 9
  number_columns: 8
  single_quotes: false
  column_names: null
  column_types: ["Numeric","Numeric","Numeric","Numeric","Numeric","Numeric","Numeric","Numeric"]
  delete_on_done: true
  check_header: -1
  chunk_size: 4194304

This is the view from
    getFrameSummary "seeds_dataset1.hex"

Clicked on 'View Data":

Row C1  C2  C3  C4  C5  C6  C7  C8
1   15.2600 14.8400 0.8710  5.7630  3.3120  2.2210  5.2200  1.0
2   14.8800 14.5700 0.8811  5.5540  3.3330  1.0180  4.9560  1.0
3   14.2900 14.0900 0.9050  5.2910  3.3370  2.6990  4.8250  1.0
etc.


问:
How to find out the coordinates of rotated textframe
With the help of (idml) itemtransform horizontal / vertical distances and path point arrays, I can find out the coordinates of text frame (x1,y1), (x2,y2), (x3,y3), (x4,y4). If the textframe is rotated then item transform values are getting changed, but the path point array values are same. I can find rotation angle by the matrix [cos(θ) sin(θ) -sin(θ) cos(θ) 0 0], But I could not get the exact coordinates of rotated textframe. The textframes are given below.

Normal Text frame

```<code>  <TextFrame Self="u136" ParentStory="u124" ItemTransform="1 0 0 1 101.72727272727272 -349.41818181818184">
        <Properties>
            <PathGeometry>
                <GeometryPathType PathOpen="false">
                    <PathPointArray>
                        <PathPointType Anchor="-101.72727272727272 -46.581818181818164" LeftDirection="-101.72727272727272 -46.581818181818164" RightDirection="-101.72727272727272 -46.581818181818164"/>
                        <PathPointType Anchor="-101.72727272727272 -0.3272727272727103" LeftDirection="-101.72727272727272 -0.3272727272727103" RightDirection="-101.72727272727272 -0.3272727272727103"/>
                        <PathPointType Anchor="115.9090909090909 -0.3272727272727103" LeftDirection="115.9090909090909 -0.3272727272727103" RightDirection="115.9090909090909 -0.3272727272727103"/>
                        <PathPointType Anchor="115.9090909090909 -46.581818181818164" LeftDirection="115.9090909090909 -46.581818181818164" RightDirection="115.9090909090909 -46.581818181818164"/>
                    </PathPointArray>
                </GeometryPathType>
            </PathGeometry>
        </Properties>
</code>```

Rotated textframe

```<code> <TextFrame Self="u136" ParentStory="u124" ItemTransform="0 1 -1 0 320.3805483338268 -125.07900895050204">
        <Properties>
            <PathGeometry>
                <GeometryPathType PathOpen="false">
                    <PathPointArray>
                        <PathPointType Anchor="-101.72727272727272 -46.581818181818164" LeftDirection="-101.72727272727272 -46.581818181818164" RightDirection="-101.72727272727272 -46.581818181818164"/>
                        <PathPointType Anchor="-101.72727272727272 -0.3272727272727103" LeftDirection="-101.72727272727272 -0.3272727272727103" RightDirection="-101.72727272727272 -0.3272727272727103"/>
                        <PathPointType Anchor="115.9090909090909 -0.3272727272727103" LeftDirection="115.9090909090909 -0.3272727272727103" RightDirection="115.9090909090909 -0.3272727272727103"/>
                        <PathPointType Anchor="115.9090909090909 -46.581818181818164" LeftDirection="115.9090909090909 -46.581818181818164" RightDirection="115.9090909090909 -46.581818181818164"/>
                    </PathPointArray>
                </GeometryPathType>
            </PathGeometry>
        </Properties>
</code>```

When I converted the values of rotated textframe in to coordinates and drawn in a screen then  I am not getting the exact position where it drawn in the original.

Can anyone help me to find out the cordinates of rotated textframe.

Thanks in advance.

答:
The values in the TextFrame's ItemTransform property (a b c d e f) represent a 2D-space transformation matrix for transforming from the TextFrame's inner coordinate system back to the parent coordinate system according to the following matrix multiplication formula:

```<code>| Xparent |   | a  c  e |   | X |
| Yparent | = | b  d  f | * | Y |
| 1       |   | 0  0  1 |   | 1 |
</code>```

Where X, Y are the coordinates in the TextFrame's inner coordinate system and Xparent and Yparent are the corresponding ones in the parent (Spread, etc.) coordinate system.

For more information see 7 Coordinate Systems, Transformations and Units

Body:
With the help of (idml) itemtransform horizontal / vertical distances and path point arrays, I can find out the coordinates of text frame (x1,y1), (x2,y2), (x3,y3), (x4,y4). If the textframe is rotated then item transform values are getting changed, but the path point array values are same. I can find rotation angle by the matrix [cos(θ) sin(θ) -sin(θ) cos(θ) 0 0], But I could not get the exact coordinates of rotated textframe. The textframes are given below.

Normal Text frame

  <TextFrame Self="u136" ParentStory="u124" ItemTransform="1 0 0 1 101.72727272727272 -349.41818181818184">
        <Properties>
            <PathGeometry>
                <GeometryPathType PathOpen="false">
                    <PathPointArray>
                        <PathPointType Anchor="-101.72727272727272 -46.581818181818164" LeftDirection="-101.72727272727272 -46.581818181818164" RightDirection="-101.72727272727272 -46.581818181818164"/>
                        <PathPointType Anchor="-101.72727272727272 -0.3272727272727103" LeftDirection="-101.72727272727272 -0.3272727272727103" RightDirection="-101.72727272727272 -0.3272727272727103"/>
                        <PathPointType Anchor="115.9090909090909 -0.3272727272727103" LeftDirection="115.9090909090909 -0.3272727272727103" RightDirection="115.9090909090909 -0.3272727272727103"/>
                        <PathPointType Anchor="115.9090909090909 -46.581818181818164" LeftDirection="115.9090909090909 -46.581818181818164" RightDirection="115.9090909090909 -46.581818181818164"/>
                    </PathPointArray>
                </GeometryPathType>
            </PathGeometry>
        </Properties>

Rotated textframe

 <TextFrame Self="u136" ParentStory="u124" ItemTransform="0 1 -1 0 320.3805483338268 -125.07900895050204">
        <Properties>
            <PathGeometry>
                <GeometryPathType PathOpen="false">
                    <PathPointArray>
                        <PathPointType Anchor="-101.72727272727272 -46.581818181818164" LeftDirection="-101.72727272727272 -46.581818181818164" RightDirection="-101.72727272727272 -46.581818181818164"/>
                        <PathPointType Anchor="-101.72727272727272 -0.3272727272727103" LeftDirection="-101.72727272727272 -0.3272727272727103" RightDirection="-101.72727272727272 -0.3272727272727103"/>
                        <PathPointType Anchor="115.9090909090909 -0.3272727272727103" LeftDirection="115.9090909090909 -0.3272727272727103" RightDirection="115.9090909090909 -0.3272727272727103"/>
                        <PathPointType Anchor="115.9090909090909 -46.581818181818164" LeftDirection="115.9090909090909 -46.581818181818164" RightDirection="115.9090909090909 -46.581818181818164"/>
                    </PathPointArray>
                </GeometryPathType>
            </PathGeometry>
        </Properties>

When I converted the values of rotated textframe in to coordinates and drawn in a screen then  I am not getting the exact position where it drawn in the original.

Can anyone help me to find out the cordinates of rotated textframe.

Thanks in advance.

Body:
The values in the TextFrame's ItemTransform property (a b c d e f) represent a 2D-space transformation matrix for transforming from the TextFrame's inner coordinate system back to the parent coordinate system according to the following matrix multiplication formula:

| Xparent |   | a  c  e |   | X |
| Yparent | = | b  d  f | * | Y |
| 1       |   | 0  0  1 |   | 1 |

Where X, Y are the coordinates in the TextFrame's inner coordinate system and Xparent and Yparent are the corresponding ones in the parent (Spread, etc.) coordinate system.

For more information see 7 Coordinate Systems, Transformations and Units