问:
can't close recordset in asp&sql server
I keep getting this error:

ADODB.Recordset error '800a0e78'
  Operation is not allowed when the
  object is closed.

The Asp code i'm using:

```<code>    rs.open "usp_reply_insert 132 ,N'abc',N'teeeeeeext',0,N'gest','x@x.com' ",conn
    rs.close
</code>```

The problem is with the rs.close command

This is the Stored Procedure

```<code>    ALTER  PROCEDURE [dbo].[usp_reply_insert]
    @maamar_id int,
    @subject nvarchar(200),
    @text nvarchar(max),
    @userid int,
    @name nvarchar(50),
    @email nvarchar(150)
    AS
    begin

    set nocount on

INSERT INTO dbo.tbl_reply
      (maamar_id,
      userid,
      reply_subject,
      reply_text,
      reply_name,
      reply_email,
      reply_date,
      reply_status
      )
VALUES
      (
      @maamar_id,
      @userid,
      @subject,
      @text,
      @name,
      @email,
      getdate(),
      0
      )

    end
</code>```

How can I close this recored set?

10x

答:
From the MSDN documentation on the Recordset.Open method:

It is not a good idea to use the
  Source argument of the Open  method to
  perform an action query that does not
  return records because there is no
  easy way to determine whether the call
  succeeded. The Recordset  returned by
  such a query will be closed.

To
  perform a query that does not return
  records, such as a SQL INSERT
  statement, call the Execute method of
  a Command object or the Execute method
  of a Connection object instead.

In short, your rs.open call is not resulting in an open recordset, so the rs.close statement doesn't function and should be removed. Better yet, follow the example given in the quoted text, as using ADODB.Recordset to invoke an INSERT op is not recommended.

Title: can't close recordset in asp&sql server

Body:
I keep getting this error:

ADODB.Recordset error '800a0e78'
  Operation is not allowed when the
  object is closed.

The Asp code i'm using:

    rs.open "usp_reply_insert 132 ,N'abc',N'teeeeeeext',0,N'gest','x@x.com' ",conn
    rs.close

The problem is with the rs.close command

This is the Stored Procedure

    ALTER  PROCEDURE [dbo].[usp_reply_insert]
    @maamar_id int,
    @subject nvarchar(200),
    @text nvarchar(max),
    @userid int,
    @name nvarchar(50),
    @email nvarchar(150)
    AS
    begin

    set nocount on

INSERT INTO dbo.tbl_reply
      (maamar_id,
      userid,
      reply_subject,
      reply_text,
      reply_name,
      reply_email,
      reply_date,
      reply_status
      )
VALUES
      (
      @maamar_id,
      @userid,
      @subject,
      @text,
      @name,
      @email,
      getdate(),
      0
      )

    end

How can I close this recored set?

10x


来源: stackexchange

问:
phoenix translate msg without put_locale
I have an array of users, each with its own locale.

I need to get a translation of the message into the language of each user.

```<code>...
Enum.map(user.tokens, fn(t) -> t.token end)
|> Sender.send(translated_msg(user.locale, msg))
...
  defp translated_msg(locale, msg) do
    message = Gettext.with_locale MyApp.Gettext, locale, fn ->
      MyApp.Gettext.gettext(msg.body, msg.bindings)
    end
    message
  end
</code>```

where

```<code>msg = %{body: "%{login} added a new operation", bindings: %{login: current_user.login}}
</code>```

But such code is not compiled

```<code>== Compilation error on file web/helpers/sender_helper.ex ==
** (ArgumentError) *gettext macros expect translation keys (msgid and msgid_plural) and
domains to expand to strings at compile-time, but the given msgid
doesn't.

Dynamic translations should be avoided as they limit gettext's
ability to extract translations from your source code. If you are
sure you need dynamic lookup, you can use the functions in the Gettext
module:

    string = "hello world"
    Gettext.gettext(MyApp.Gettext, string)

    (gettext) lib/gettext/compiler.ex:196: anonymous fn/2 in Gettext.Compiler.expand_to_binary/4
    expanding macro: MyApp.Gettext.dgettext_noop/2
    web/helpers/push_helper.ex:23: MyApp.SenderHelper.translated_msg/2
    expanding macro: MyApp.Gettext.dgettext/3
    web/helpers/push_helper.ex:23: MyApp.SenderHelper.translated_msg/2
    expanding macro: MyApp.Gettext.gettext/1
    web/helpers/push_helper.ex:23: MyApp.SenderHelper.translated_msg/2
    (elixir) lib/kernel/parallel_compiler.ex:117: anonymous fn/4 in Kernel.ParallelCompiler.spawn_compilers/1
</code>```

How can I manually translate a message into another language?

答:
Just like the error message says, if the string to translate is dynamic, you need to use Gettext.gettext/{2,3} passing in your app's Gettext module as the first argument. Since you're passing bindings as well, you need to use Gettext.gettext/3:

```<code>Gettext.gettext(MyApp.Gettext, msg.body, msg.bindings)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have an array of users, each with its own locale.

I need to get a translation of the message into the language of each user.

...
Enum.map(user.tokens, fn(t) -> t.token end)
|> Sender.send(translated_msg(user.locale, msg))
...
  defp translated_msg(locale, msg) do
    message = Gettext.with_locale MyApp.Gettext, locale, fn ->
      MyApp.Gettext.gettext(msg.body, msg.bindings)
    end
    message
  end

where

msg = %{body: "%{login} added a new operation", bindings: %{login: current_user.login}}

But such code is not compiled

== Compilation error on file web/helpers/sender_helper.ex ==
** (ArgumentError) *gettext macros expect translation keys (msgid and msgid_plural) and
domains to expand to strings at compile-time, but the given msgid
doesn't.

Dynamic translations should be avoided as they limit gettext's
ability to extract translations from your source code. If you are
sure you need dynamic lookup, you can use the functions in the Gettext
module:

    string = "hello world"
    Gettext.gettext(MyApp.Gettext, string)

    (gettext) lib/gettext/compiler.ex:196: anonymous fn/2 in Gettext.Compiler.expand_to_binary/4
    expanding macro: MyApp.Gettext.dgettext_noop/2
    web/helpers/push_helper.ex:23: MyApp.SenderHelper.translated_msg/2
    expanding macro: MyApp.Gettext.dgettext/3
    web/helpers/push_helper.ex:23: MyApp.SenderHelper.translated_msg/2
    expanding macro: MyApp.Gettext.gettext/1
    web/helpers/push_helper.ex:23: MyApp.SenderHelper.translated_msg/2
    (elixir) lib/kernel/parallel_compiler.ex:117: anonymous fn/4 in Kernel.ParallelCompiler.spawn_compilers/1

How can I manually translate a message into another language?

Body:
Just like the error message says, if the string to translate is dynamic, you need to use Gettext.gettext/{2,3} passing in your app's Gettext module as the first argument. Since you're passing bindings as well, you need to use Gettext.gettext/3:

Gettext.gettext(MyApp.Gettext, msg.body, msg.bindings)


问:
How to Traverse the blocks of transactions in hyperlegder fabric?
Is there any chaincode API that gives an iterator over the blocks of transactions in hyperledger fabric?
I want to get a list of all transactions in the ledger.

答:
You can use the QSCC (query system chaincode) and query 1 by 1 starting from block 0 until H where H is the ledger Height - whom you can obtain using the QSCC call GetChainInfo.

https://github.com/hyperledger/fabric/blob/master/core/scc/qscc/query.go


问:
how to write a locate-function for ede
I use emacs as a C++ IDE.
I have CEDET and EDE configured and working nicely, but i have a minor problem.

In my project header files are spread all over the project tree, so i need to write a function to help ede to find my headers.
I have been looking for an example for some time, but I have not found anything.
Would anyone be so kind to help me?

Thanks in advance.

答:
Here's an example for a "quick find file" in a project using EDE and ido:</p>

```
(defun DE-ido-find-files-in-project ()
  (interactive)
  (let ((allfiles nil)
 choice)
    (ede-map-all-subprojects
     ede-object-root-project
     (lambda (p)
       (let ((targets (oref p targets)))
  (dolist (target targets)
    (setq allfiles (append allfiles (oref target source)))))))
    (setq choice
   (ido-completing-read
    (format "File in project %s: " (oref ede-object-root-project name))
    allfiles nil t))
    (when choice
      (ede-find-file choice))))
```

ContentLicense: CC BY-SA 2.5

Title: how to write a locate-function for ede

Body:
Here's an example for a "quick find file" in a project using EDE and ido:

(defun DE-ido-find-files-in-project ()
  (interactive)
  (let ((allfiles nil)
 choice)
    (ede-map-all-subprojects
     ede-object-root-project
     (lambda (p)
       (let ((targets (oref p targets)))
  (dolist (target targets)
    (setq allfiles (append allfiles (oref target source)))))))
    (setq choice
   (ido-completing-read
    (format "File in project %s: " (oref ede-object-root-project name))
    allfiles nil t))
    (when choice
      (ede-find-file choice))))


问:
Similar image search using an image
I am working on a project in which the two images will be checked for similarity like 'Google Image Search by image'.

I searched through Google and also on various sites including stackoverflow and learnt about various techniques like histogram, sift, fourier transform, pixel grabbing, etc.

The things are too complex for me to understand being a beginner in this field.

My questions are:

From where can i get started?? Is there any book available or a site which give tutorials for learning about how to actually use these techniques?

Are there new techniques which can be implemented for this purpose??

I want to start searching images via color then if possible other attributes later.

Language preferred is Java.

There is a similar thread on this topic but it was written years ago.

答:
I got satisfactory results by resizing images to an 8x8 thumbnail and then taking the Mean Square Error of the 8-bit RGB color differences between the corresponding pixel in each image.

Step 1. Create thumbnails:

```<code>        BufferedImage img = ImageIO.read(src);
        Image thumbnail = img.getScaledInstance(8, 8, Image.SCALE_AREA_AVERAGING);
</code>```

Check https://community.oracle.com/docs/DOC-983611 to understand why I chose the slower SCALE_AREA_AVERAGING over newer, faster methods.

Step 2. Convert Image thumbnails to BufferedImage by using the toBufferedImage method from  Java converting Image to BufferedImage. Place the result into a List<BufferedImage>.

Step 3. Calculate the Mean Squared Error

This method takes two thumbnail-sized images of identical size and returns the difference. Zero means the images are very very similar:

```<code>public static double compare(BufferedImage img1, BufferedImage img2) {
    int width1 = img1.getWidth();
    int width2 = img2.getWidth();
    int height1 = img1.getHeight();
    int height2 = img2.getHeight();
    if ((width1 != width2) || (height1 != height2)) {
        throw new IllegalArgumentException("Error: Images dimensions mismatch");
    }

    int diff2 = 0;

    for (int i = 0; i < height1; i++) {
        for (int j = 0; j < width1; j++) {
            int rgb1 = img1.getRGB(j, i);
            int rgb2 = img2.getRGB(j, i);
            int r1 = (rgb1 >> 16) & 0xff;
            int g1 = (rgb1 >> 8) & 0xff;
            int b1 = (rgb1) & 0xff;
            int r2 = (rgb2 >> 16) & 0xff;
            int g2 = (rgb2 >> 8) & 0xff;
            int b2 = (rgb2) & 0xff;

            diff2 += Math.pow(r1 - r2, 2) + Math.pow(g1 - g2, 2) + Math.pow(b1 - b2, 2);
        }
    }
    return diff2 * 1.0 / (height1*width1);
}
</code>```

Step 4. Implement Search

This works by simply finding the image with the smallest difference. Depending on your use-case you may also want to set a threshold above which no image is returned. In my application the best match is always shown to the user so the user can decide if it is the correct image or not, so a hard-coded threshold is not necessary.

```<code>public BufferedImage findImage(List<BufferedImage> haystack, BufferedImage needle) {

    double lastDiff = Double.MAX_VALUE;
    BufferedImage winner = null;

    for(BufferedImage candidate: haystack) {
        double diff = compare(candidate, needle);
        if(diff < lastDiff) {
            lastDiff = diff;
            winner = candidate;
        }
    }
    return winner;
}
</code>```

Title: Similar image search using an image

Body:
I got satisfactory results by resizing images to an 8x8 thumbnail and then taking the Mean Square Error of the 8-bit RGB color differences between the corresponding pixel in each image.

Step 1. Create thumbnails:

        BufferedImage img = ImageIO.read(src);
        Image thumbnail = img.getScaledInstance(8, 8, Image.SCALE_AREA_AVERAGING);

Check https://community.oracle.com/docs/DOC-983611 to understand why I chose the slower SCALE_AREA_AVERAGING over newer, faster methods.

Step 2. Convert Image thumbnails to BufferedImage by using the toBufferedImage method from  Java converting Image to BufferedImage. Place the result into a List<BufferedImage>.

Step 3. Calculate the Mean Squared Error

This method takes two thumbnail-sized images of identical size and returns the difference. Zero means the images are very very similar:

public static double compare(BufferedImage img1, BufferedImage img2) {
    int width1 = img1.getWidth();
    int width2 = img2.getWidth();
    int height1 = img1.getHeight();
    int height2 = img2.getHeight();
    if ((width1 != width2) || (height1 != height2)) {
        throw new IllegalArgumentException("Error: Images dimensions mismatch");
    }

    int diff2 = 0;

    for (int i = 0; i < height1; i++) {
        for (int j = 0; j < width1; j++) {
            int rgb1 = img1.getRGB(j, i);
            int rgb2 = img2.getRGB(j, i);
            int r1 = (rgb1 >> 16) & 0xff;
            int g1 = (rgb1 >> 8) & 0xff;
            int b1 = (rgb1) & 0xff;
            int r2 = (rgb2 >> 16) & 0xff;
            int g2 = (rgb2 >> 8) & 0xff;
            int b2 = (rgb2) & 0xff;

            diff2 += Math.pow(r1 - r2, 2) + Math.pow(g1 - g2, 2) + Math.pow(b1 - b2, 2);
        }
    }
    return diff2 * 1.0 / (height1*width1);
}

Step 4. Implement Search

This works by simply finding the image with the smallest difference. Depending on your use-case you may also want to set a threshold above which no image is returned. In my application the best match is always shown to the user so the user can decide if it is the correct image or not, so a hard-coded threshold is not necessary.

public BufferedImage findImage(List<BufferedImage> haystack, BufferedImage needle) {

    double lastDiff = Double.MAX_VALUE;
    BufferedImage winner = null;

    for(BufferedImage candidate: haystack) {
        double diff = compare(candidate, needle);
        if(diff < lastDiff) {
            lastDiff = diff;
            winner = candidate;
        }
    }
    return winner;
}


问:
Remove duplicate values of specific key in multidimensional array in PHP but remove the last?
I have an array like this

```<code> Array
(
    [1] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )

    [2] => Array
        (
            [clave] => 10315484
            [descripcion] => Azucena cortada fresca de agua
        )

    [3] => Array
        (
            [clave] => 10415484
            [descripcion] => Azucena cortada seca de agua
        )

    [4] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )
)
</code>```

As you can see the first and last arrays are the same, so my code to remove the duplicates is like this

```<code>foreach ($my_array as $k => $v) {

    foreach ($my_arrays as $key => $value) {

        if ($k != $key && $v['clave'] == $value['clave']) {

            unset($my_array[$k]);
        }
    }
}
</code>```

And this works fine but I would like to remove the last array and let the first one to keep the order in which I added every array, so the result should be

```<code>Array
(
    [1] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )

    [2] => Array
        (
            [clave] => 10315484
            [descripcion] => Azucena cortada fresca de agua
        )

    [3] => Array
        (
            [clave] => 10415484
            [descripcion] => Azucena cortada seca de agua
        )
)
</code>```

Because in the way I do it is removing always the first duplicates and the last always remains, some idea how to achieve this? I hope you can help me, thanks.

答:
You can try like the code below:</p>

```<code>$my_arrays = array_unique($my_arrays, SORT_REGULAR);

var_dump($my_arrays);
</code>```

Body:
I have an array like this

 Array
(
    [1] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )

    [2] => Array
        (
            [clave] => 10315484
            [descripcion] => Azucena cortada fresca de agua
        )

    [3] => Array
        (
            [clave] => 10415484
            [descripcion] => Azucena cortada seca de agua
        )

    [4] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )
)

As you can see the first and last arrays are the same, so my code to remove the duplicates is like this

foreach ($my_array as $k => $v) {

    foreach ($my_arrays as $key => $value) {

        if ($k != $key && $v['clave'] == $value['clave']) {

            unset($my_array[$k]);
        }
    }
}

And this works fine but I would like to remove the last array and let the first one to keep the order in which I added every array, so the result should be

Array
(
    [1] => Array
        (
            [clave] => 10215484
            [descripcion] => Azucena viva de agua
        )

    [2] => Array
        (
            [clave] => 10315484
            [descripcion] => Azucena cortada fresca de agua
        )

    [3] => Array
        (
            [clave] => 10415484
            [descripcion] => Azucena cortada seca de agua
        )
)

Because in the way I do it is removing always the first duplicates and the last always remains, some idea how to achieve this? I hope you can help me, thanks.

Body:
You can try like the code below:

$my_arrays = array_unique($my_arrays, SORT_REGULAR);

var_dump($my_arrays);


问:
Editing date axis and breaks
I am working with a time line, and for some reason I end up with a more or less random time-scale. Here we go:

```<code>df <- data.frame(balance=c(100,242,156,430,224),
  date = as.Date(c("2017-01-03", "2017-01-14", "2017-02-03", "2017-02-17", "2017-03-02")))
</code>```

I us the following to plot:

```<code>plot(balance ~ date, df, type = "l", xaxt='n', xlab = "Date",
                                 yaxt='n', ylab = "Balance [$]", main = "Personal finance")
axis(1, df$date, format(df$date, "%b %d"), cex.axis = .7, tick = FALSE, line=-0.5)
</code>```

What I get is this:

How do I control the date axis? Instead of Jan 03, Jan 14, Feb 03, Feb 17, Mar 02 I would like Jan 01, Jan 15, Feb 01, Feb 15, Mar 01

Any help is appreciated!

答:
You need to give those specific dates to your axis function; this works for you:

```<code>date_lab <-
           as.Date(c("2017-01-01", "2017-01-15", "2017-02-01", "2017-02-15", "2017-03-01"))

plot(balance ~ date, df, type = "l", xaxt='n', xlab = "Date",
                             yaxt='n', ylab = "Balance [$]", main = "Personal finance")
axis(1, date_lab, format(date_lab, "%b %d"), cex.axis = .7, tick = FALSE, line=-0.5)
</code>```

If you use ggplot2 it usually makes the axis cleaner than base plot:

```<code>library(ggplot2)
ggplot(df, aes(x=date, y=balance))+geom_line()+
                                   labs(title = "Personal finance",
                                        x = "Date", y="Balance [$]")
</code>```

ContentLicense: CC BY-SA 4.0

Title: Editing date axis and breaks

Body:
I am working with a time line, and for some reason I end up with a more or less random time-scale. Here we go:

df <- data.frame(balance=c(100,242,156,430,224),
  date = as.Date(c("2017-01-03", "2017-01-14", "2017-02-03", "2017-02-17", "2017-03-02")))

I us the following to plot:

plot(balance ~ date, df, type = "l", xaxt='n', xlab = "Date",
                                 yaxt='n', ylab = "Balance [$]", main = "Personal finance")
axis(1, df$date, format(df$date, "%b %d"), cex.axis = .7, tick = FALSE, line=-0.5)

What I get is this:

How do I control the date axis? Instead of Jan 03, Jan 14, Feb 03, Feb 17, Mar 02 I would like Jan 01, Jan 15, Feb 01, Feb 15, Mar 01

Any help is appreciated!

Body:
You need to give those specific dates to your axis function; this works for you:

date_lab <-
           as.Date(c("2017-01-01", "2017-01-15", "2017-02-01", "2017-02-15", "2017-03-01"))

plot(balance ~ date, df, type = "l", xaxt='n', xlab = "Date",
                             yaxt='n', ylab = "Balance [$]", main = "Personal finance")
axis(1, date_lab, format(date_lab, "%b %d"), cex.axis = .7, tick = FALSE, line=-0.5)

If you use ggplot2 it usually makes the axis cleaner than base plot:

library(ggplot2)
ggplot(df, aes(x=date, y=balance))+geom_line()+
                                   labs(title = "Personal finance",
                                        x = "Date", y="Balance [$]")


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

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

STDOUT:

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

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

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

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

答:
You can use a script like this:</p>

```<code>for file in *.gz; do
   gzcat "$file" | awk -v fn="$file" -v OFS='\t' 'END{print fn, int(NR/4)}'
done
</code>```

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

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

STDOUT:

AB.gz
12
CD.gz
4

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

AB.gz 12
CD.gz 4

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

Body:
You can use a script like this:

for file in *.gz; do
   gzcat "$file" | awk -v fn="$file" -v OFS='\t' 'END{print fn, int(NR/4)}'
done


问:
In Blackberry, can we create common library that can be used by different applications?
I want to create a common 3rd party library, that can be shared and used by different applications and be consistent. Can we acheive this ?.If yes, how and where will this library be installed ?

and how can these library files be accessed from other apps ?

答: What is your goal with a BlackBerry library?  rapc can compile jar libraries into your application, which would be the easist way to do this.</p>


问:
JFileChooser check if really a File is selected?
I noticed the following: If I start my application and go to open a file, then the JFileChooser appears. I tried writing a filename and I did not get an error, even though the file does not exist. What I get is a file path.

```<code> JFileChooser fileChooser = new JFileChooser();
    int values = fileChooser.showOpenDialog(null);
    File file = fileChooser.getSelectedFile();

    if (values == JFileChooser.APPROVE_OPTION) {
        System.out.println(file.getPath());
    } else if (values == JFileChooser.CANCEL_OPTION) {
        System.out.println("No file is selected");
    } else if (values == JFileChooser.ERROR_OPTION) {
        System.out.println("Error!");
    } else if (file == null) {
        System.out.println("No File is chosen");
    }
</code>```

I hope you guys can help. I hope my question is clear because I have problems with explanations and with the English language.

答:
you can check if a file exists with: file.exists(). Already answered in another post.

The creation of a file object does not garuantee that a file at your path does exist.

```<code>...
if (values == JFileChooser.APPROVE_OPTION) {
    if(file.exists()){
        System.out.println(file.getPath());
    }else{
        System.out.println("file does not exist");
    }
}
...
</code>```

Body:
I noticed the following: If I start my application and go to open a file, then the JFileChooser appears. I tried writing a filename and I did not get an error, even though the file does not exist. What I get is a file path.

 JFileChooser fileChooser = new JFileChooser();
    int values = fileChooser.showOpenDialog(null);
    File file = fileChooser.getSelectedFile();

    if (values == JFileChooser.APPROVE_OPTION) {
        System.out.println(file.getPath());
    } else if (values == JFileChooser.CANCEL_OPTION) {
        System.out.println("No file is selected");
    } else if (values == JFileChooser.ERROR_OPTION) {
        System.out.println("Error!");
    } else if (file == null) {
        System.out.println("No File is chosen");
    }

I hope you guys can help. I hope my question is clear because I have problems with explanations and with the English language.

Body:
you can check if a file exists with: file.exists(). Already answered in another post.

The creation of a file object does not garuantee that a file at your path does exist.

...
if (values == JFileChooser.APPROVE_OPTION) {
    if(file.exists()){
        System.out.println(file.getPath());
    }else{
        System.out.println("file does not exist");
    }
}
...


问:
Google Appengine Error: Unable to update app: Applications are limited to 10000 files
I am new to Google App Engine and I am having problem with deploying my application as I am getting the following errors

```<code>"SEVERE: Invalid character in filename: __static__/resources/js/morris.js-0.5.1/node_modules/gaze/test/fixtures/Project (LO)/one.js"

"com.google.appengine.tools.admin.LocalIOException: Applications are limited to 10000 files, you have 18867.
Unable to update app: Applications are limited to 10000 files, you have 18867."
</code>```

The application has only 300 files and I am using eclipse neon. I have uninstalled eclipse and reinstalled it. I have deleted all the node modules in my local disk. I don't know from where the files are getting pulled.

When I searched the site one of the suggestions was to remove unwanted plugins. I looked at my Eclipse plugins, there are lots of them. I did not install anything, so I don't have any idea what to remove.

Eclipse Plugin window image

Is it a bug in eclipse or any configuration setting I have to take care? Please help.

答:
First, delete the parentheses in your directory name: /Project (LO)/

You will need to use skip_files to not upload any unnecessary files inside included packages.

Body:
I am new to Google App Engine and I am having problem with deploying my application as I am getting the following errors

"SEVERE: Invalid character in filename: __static__/resources/js/morris.js-0.5.1/node_modules/gaze/test/fixtures/Project (LO)/one.js"

"com.google.appengine.tools.admin.LocalIOException: Applications are limited to 10000 files, you have 18867.
Unable to update app: Applications are limited to 10000 files, you have 18867."

The application has only 300 files and I am using eclipse neon. I have uninstalled eclipse and reinstalled it. I have deleted all the node modules in my local disk. I don't know from where the files are getting pulled.

When I searched the site one of the suggestions was to remove unwanted plugins. I looked at my Eclipse plugins, there are lots of them. I did not install anything, so I don't have any idea what to remove.

Eclipse Plugin window image

Is it a bug in eclipse or any configuration setting I have to take care? Please help.


问:
popToViewController isn't popping all of the view controllers
So I have 3 view controllers: TableViewController, A, and B. The user is able to navigate to any view controller from any view controller.

When the user goes back and forth between A, and B view controllers I want them to be pushed onto the nav. stack. When the "home" button is pressed, I would like for the view controllers to all be popped back to the TableViewController using popToViewController, not popToRootViewController (for reasons).

I have partly working code that pops the last visited view controller, but now all the ones in between.

```<code>func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    if indexPath.row == 0 {
        if let navController = self.navigationController {
            for controller in navController.viewControllers {
                if controller is TableViewController {
                    navController.popToViewController(controller, animated: true)
                    break
                }
            }
        }
    } else {

        let vcName = identities[indexPath.row]
        let viewController = storyboard?.instantiateViewController(withIdentifier: vcName)
        self.navigationController?.pushViewController(viewController!, animated: true)
    }

}
</code>```

I'm not sure why all the view controllers aren't being popped.

Code I use to check what's being pushed and popped:

```<code>override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(true)

    if self.isMovingToParentViewController {
        print("A is pushed")
    }
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(true)

    if self.isMovingFromParentViewController {
        print("A is popped")
    }
}
</code>```

I'm also checking increase in memory.

I will provide more code/info in needed.

Any help would be greatly appreciated.

答:
Your confusion may simply be the way you are trying to "check" that the VCs are "popped".

Suppose you have gone:

```<code>root->TableView->A->B->A->B->B->B->`
</code>```

At that point, the only VC that is visible is the last instance of A. So when you call

```<code>navController.popToViewController(controller, animated: true)
</code>```

viewWillDisappear() will only be called on the last instance of A - none of the other VC instances will "disappear" because they are not visible.

If you want to confirm the other VCs in the stack are being "removed", put this in each view controller:

```<code>deinit() {
    print("I'm being removed:", self)
}
</code>```

The other part of the question - do you want to animate through the process? So you would actually see the VCs "walk back up the stack"? If so, follow @FryAnEgg's link to Completion block for popViewController

Body:
So I have 3 view controllers: TableViewController, A, and B. The user is able to navigate to any view controller from any view controller.

When the user goes back and forth between A, and B view controllers I want them to be pushed onto the nav. stack. When the "home" button is pressed, I would like for the view controllers to all be popped back to the TableViewController using popToViewController, not popToRootViewController (for reasons).

I have partly working code that pops the last visited view controller, but now all the ones in between.

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    if indexPath.row == 0 {
        if let navController = self.navigationController {
            for controller in navController.viewControllers {
                if controller is TableViewController {
                    navController.popToViewController(controller, animated: true)
                    break
                }
            }
        }
    } else {

        let vcName = identities[indexPath.row]
        let viewController = storyboard?.instantiateViewController(withIdentifier: vcName)
        self.navigationController?.pushViewController(viewController!, animated: true)
    }

}

I'm not sure why all the view controllers aren't being popped.

Code I use to check what's being pushed and popped:

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(true)

    if self.isMovingToParentViewController {
        print("A is pushed")
    }
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(true)

    if self.isMovingFromParentViewController {
        print("A is popped")
    }
}

I'm also checking increase in memory.

I will provide more code/info in needed.

Any help would be greatly appreciated.

Body:
Your confusion may simply be the way you are trying to "check" that the VCs are "popped".

Suppose you have gone:

root->TableView->A->B->A->B->B->B->`

At that point, the only VC that is visible is the last instance of A. So when you call

navController.popToViewController(controller, animated: true)

viewWillDisappear() will only be called on the last instance of A - none of the other VC instances will "disappear" because they are not visible.

If you want to confirm the other VCs in the stack are being "removed", put this in each view controller:

deinit() {
    print("I'm being removed:", self)
}

The other part of the question - do you want to animate through the process? So you would actually see the VCs "walk back up the stack"? If so, follow @FryAnEgg's link to Completion block for popViewController


问:
DropDown to select data from MS SQL server
I'm trying to make a PHP web application display the data from specific Countries from a dropdown but I can't figure it out how to use the WHERE [Column] = [Value1, Value2, Value3] on a PHP dropdown.

I'm using the "Adventure Works 2014 Full Database Backup" for test purpose.

```<code><html>
</body>
<!-- form for tower selection -->
<form action="test20.php" method="POST">
Please select the tower you are about to work on. </br></br>
<select name="TowerSelect"><option> Choose </option>
<?php
$serverName = 'SERVERNAME';
$uid = 'USERNAME';
$pwd = 'PASSWORD';
$databaseName = 'AdWorks';

$connectionInfo = array( 'UID'=>$uid,
                        'PWD'=>$pwd,
                        'Database'=>$databaseName);

$conn = sqlsrv_connect($serverName,$connectionInfo);
if($conn){
    echo '';
}else{
    echo 'Connection failure<br />';
die(print_r(sqlsrv_errors(),TRUE));
}
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE CountryRegionName = 'United States'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){

    echo "<option value=";
    echo $data['BusinessEntityID'];
    echo ">";
    echo $data['BusinessEntityID'];
    echo "</option>";
}
?>
<input type="submit" value="Select Tower">
</select></br></br>
</form>
</body></html>
<?php
if(empty($_POST['TowerSelect'])){
    $_SESSION['tower'] = '';
} else {
    $_SESSION['tower'] = $_POST['TowerSelect'];
    echo "<tr>";
    echo $_SESSION['tower'];
    echo "  selected. </p>";
    echo('<td>'.$row['BusinessEntityID'].'</td><td>'.$row['FirstName'].'</td></tr>');
}
</code>```

答:
I believe I have this fixed.  There were a number of problems with the code.  You were referencing a $row but there was no SQL query that would have resulted in a $row, you were trying to post data after the closing HTML tag, you were trying to create rows for a table without declaring the table, and a few other things.  Some of this was probably a result of quickly creating the test case.  No problem.  Try this...

```<code><?php
$serverName = 'SERVERNAME';
$uid = 'USERNAME';
$pwd = 'PASSWORD';
$databaseName = 'AdWorks';
$connectionInfo = array( 'UID'=>$uid,'PWD'=>$pwd,'Database'=>$databaseName);
$conn = sqlsrv_connect($serverName,$connectionInfo);
if($conn){echo '';}else{echo 'Connection failure<br />';die(print_r(sqlsrv_errors(),TRUE));}

?><html><body>
<!-- form for tower selection -->
<form action="test20.php" method="POST">
Please select the tower you are about to work on. </br></br>
<select name="TowerSelect"><option> Choose </option>
<?php

$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE CountryRegionName = 'United States'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
    echo '<option value="'.$data['BusinessEntityID'].'">';
    echo $data['BusinessEntityID'];
    echo "</option>";
}

?><input type="submit" value="Select Tower">
</select></br></br>
</form>
<table cols="3" cellpadding="0" cellspacing="0" border="0">
<?php

if(empty($_POST['TowerSelect'])){
    $_SESSION['tower'] = '';
} else {
    $sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE BusinessEntityID = '".$_POST['TowerSelect']."'";
    $result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
    while ($row=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
        $_SESSION['tower'] = $_POST['TowerSelect'];
        echo '<tr><td>'.$_SESSION['tower'].'  selected.</td>';
        echo     '<td>'.$row['BusinessEntityID'].'</td>';
        echo     '<td>'.$row['FirstName'].'</td></tr>';
    }
}

?></table></body></html>
</code>```

Note: Though not important to answer your question, it is a best practice to use PDO and bound paramters when making database calls to protect yourself against SQL injection and other nasties.  I recommend you look into it to protect your database.  Cheers!

Body:
I'm trying to make a PHP web application display the data from specific Countries from a dropdown but I can't figure it out how to use the WHERE [Column] = [Value1, Value2, Value3] on a PHP dropdown.

I'm using the "Adventure Works 2014 Full Database Backup" for test purpose.

<form action="test20.php" method="POST">
Please select the tower you are about to work on.

<select name="TowerSelect"><option> Choose </option>
<?php
$serverName = 'SERVERNAME';
$uid = 'USERNAME';
$pwd = 'PASSWORD';
$databaseName = 'AdWorks';

$connectionInfo = array( 'UID'=>$uid,
                        'PWD'=>$pwd,
                        'Database'=>$databaseName);

$conn = sqlsrv_connect($serverName,$connectionInfo);
if($conn){
    echo '';
}else{
    echo 'Connection failure
';
die(print_r(sqlsrv_errors(),TRUE));
}
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE CountryRegionName = 'United States'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){

    echo "<option value=";
    echo $data['BusinessEntityID'];
    echo ">";
    echo $data['BusinessEntityID'];
    echo "</option>";
}
?>
<input type="submit" value="Select Tower">
</select>

</form>

<?php
if(empty($_POST['TowerSelect'])){
    $_SESSION['tower'] = '';
} else {
    $_SESSION['tower'] = $_POST['TowerSelect'];
    echo "
";
    echo $_SESSION['tower'];
    echo "  selected.
";
    echo(''.$row['BusinessEntityID'].'	'.$row['FirstName'].'
');
}

Body:
I believe I have this fixed.  There were a number of problems with the code.  You were referencing a $row but there was no SQL query that would have resulted in a $row, you were trying to post data after the closing HTML tag, you were trying to create rows for a table without declaring the table, and a few other things.  Some of this was probably a result of quickly creating the test case.  No problem.  Try this...

<?php
$serverName = 'SERVERNAME';
$uid = 'USERNAME';
$pwd = 'PASSWORD';
$databaseName = 'AdWorks';
$connectionInfo = array( 'UID'=>$uid,'PWD'=>$pwd,'Database'=>$databaseName);
$conn = sqlsrv_connect($serverName,$connectionInfo);
if($conn){echo '';}else{echo 'Connection failure<br />';die(print_r(sqlsrv_errors(),TRUE));}

?><html><body>
<!-- form for tower selection -->
<form action="test20.php" method="POST">
Please select the tower you are about to work on. </br></br>
<select name="TowerSelect"><option> Choose </option>
<?php

$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE CountryRegionName = 'United States'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
    echo '<option value="'.$data['BusinessEntityID'].'">';
    echo $data['BusinessEntityID'];
    echo "</option>";
}

?><input type="submit" value="Select Tower">
</select></br></br>
</form>
<table cols="3" cellpadding="0" cellspacing="0" border="0">
<?php

if(empty($_POST['TowerSelect'])){
    $_SESSION['tower'] = '';
} else {
    $sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE BusinessEntityID = '".$_POST['TowerSelect']."'";
    $result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
    while ($row=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
        $_SESSION['tower'] = $_POST['TowerSelect'];
        echo '<tr><td>'.$_SESSION['tower'].'  selected.</td>';
        echo     '<td>'.$row['BusinessEntityID'].'</td>';
        echo     '<td>'.$row['FirstName'].'</td></tr>';
    }
}

?></table></body></html>

Note: Though not important to answer your question, it is a best practice to use PDO and bound paramters when making database calls to protect yourself against SQL injection and other nasties.  I recommend you look into it to protect your database.  Cheers!


问:
Web API post Body object is null
I have a Web api  method like this

```<code>        [HttpPost]
        public IHttpActionResult Login(ILogin request)
        {
             // do stuff
        }
</code>```

My Login object is

```<code> public interface ILogin
    {
        string UserName { get; set; }
        string Password { get; set; }
    }
</code>```

I am trying to call from fiddler with the following details

url - myapi.com/login

Request Body

```<code>  {
    "UserName": "ingridmooney@insurity.com",
    "Password": "adfdfdf"
  }
</code>```

I tried various combinations of request body  - but whenever i debug  - the ILogin request is always null. What am i doing wrong?

答: You can't instantiate an interface. Your webapi should expect a class that implements the ILogin interface.</p>

Title: Web API post Body object is null

Body:
I have a Web api  method like this

        [HttpPost]
        public IHttpActionResult Login(ILogin request)
        {
             // do stuff
        }

My Login object is

 public interface ILogin
    {
        string UserName { get; set; }
        string Password { get; set; }
    }

I am trying to call from fiddler with the following details

url - myapi.com/login

Request Body

  {
    "UserName": "ingridmooney@insurity.com",
    "Password": "adfdfdf"
  }

I tried various combinations of request body  - but whenever i debug  - the ILogin request is always null. What am i doing wrong?


问:
How do I gather integration test coverage reports with the Sonarqube Maven plugin?
I am trying to gather code coverage metrics on both unit and integration tests run by Maven following directions linked to by the SonarQube Maven plugin guide. I believe I have successfully generated coverage metrics with jacoco: I have files jacoco.exec and jacoco-it.exec, and though I don't know how to look inside them to find useful information, they do have different sizes in accordance with different numbers of unit and integration tests, FWIW.

From there I can run e.g. mvn sonar:sonar to upload unit test coverage to my local server, but I have not been able to upload integration test coverage. In my pom file I have a property <sonar.junit.reportPaths>target/failsafe-reports,target/failsafe-reports</sonar.junit.reportPaths> which seems to do nothing. I have tried both the latest official and codehaus versions of sonar-maven-plugin (version 3.3.0.603). I am using the latest official SonarQube Docker image (v. 6.4) which evidently contains SonarQube Version 6.3.1 according to the SQ UI (why the discrepancy there?).

I noticed in the console output when running mvn sonar:sonar, it says

```<code>[INFO] Sensor SurefireSensor [java]
[INFO] parsing /home/jason/.../target/surefire-reports
[INFO] Sensor SurefireSensor [java] (done) | time=57ms
[INFO] Sensor JaCoCoSensor [java]
[INFO] Analysing /home/jason/.../target/jacoco-it.exec
[INFO] Analysing /home/jason/.../target/jacoco.exec
[INFO] Analysing /home/jason/.../target/sonar/jacoco-merged.exec
</code>```

so it's picking up both jacoco coverage reports, yet showing only unit tests in the UI. Since that output mentions target/surefire-reports but never mentions failsafe-reports, as an experiment, I tried copying everything from failsafe-reports to surefire-reports, and the IT information was present in the SQ UI, but that is a hack, and I found a similar SO question advising configuring failsafe to output to surefire-reports to trick SQ in this way.

So my ultimate question is how do I get SQ to upload IT information? Simpler questions are, how do I tell it to parse failsafe-reports, and what difference does sonar.junit.reportPaths make?

答: I think this link should have you covered: https://theholyjava.wordpress.com/2012/02/05/separating-integration-and-unit-tests-with-maven-sonar-failsafe-and-jacoco/ </p>

Body:
I am trying to gather code coverage metrics on both unit and integration tests run by Maven following directions linked to by the SonarQube Maven plugin guide. I believe I have successfully generated coverage metrics with jacoco: I have files jacoco.exec and jacoco-it.exec, and though I don't know how to look inside them to find useful information, they do have different sizes in accordance with different numbers of unit and integration tests, FWIW.

From there I can run e.g. mvn sonar:sonar to upload unit test coverage to my local server, but I have not been able to upload integration test coverage. In my pom file I have a property <sonar.junit.reportPaths>target/failsafe-reports,target/failsafe-reports</sonar.junit.reportPaths> which seems to do nothing. I have tried both the latest official and codehaus versions of sonar-maven-plugin (version 3.3.0.603). I am using the latest official SonarQube Docker image (v. 6.4) which evidently contains SonarQube Version 6.3.1 according to the SQ UI (why the discrepancy there?).

I noticed in the console output when running mvn sonar:sonar, it says

[INFO] Sensor SurefireSensor [java]
[INFO] parsing /home/jason/.../target/surefire-reports
[INFO] Sensor SurefireSensor [java] (done) | time=57ms
[INFO] Sensor JaCoCoSensor [java]
[INFO] Analysing /home/jason/.../target/jacoco-it.exec
[INFO] Analysing /home/jason/.../target/jacoco.exec
[INFO] Analysing /home/jason/.../target/sonar/jacoco-merged.exec

so it's picking up both jacoco coverage reports, yet showing only unit tests in the UI. Since that output mentions target/surefire-reports but never mentions failsafe-reports, as an experiment, I tried copying everything from failsafe-reports to surefire-reports, and the IT information was present in the SQ UI, but that is a hack, and I found a similar SO question advising configuring failsafe to output to surefire-reports to trick SQ in this way.

So my ultimate question is how do I get SQ to upload IT information? Simpler questions are, how do I tell it to parse failsafe-reports, and what difference does sonar.junit.reportPaths make?


问:
HighCharts adding line
I have this simple HighCharts chart and I need to add a horizontal line by clicking a button, I added a button but the code which suppose to add a line won't work!
Can someone help please?

https://jsfiddle.net/khalifa/pskx5qLb/

答:
try using chart.update() instead

```<code> $button.click(function() {
  if (!hasPlotLine) {
    chart.update({
        yAxis:{
        plotLines: [{
               value: 40,
                        color: 'red',
                        width: 2,
                        id: 'plot-line-1'
            }]
      }
    })
    $button.html('Remove plot line');
  } else {
    chart.yAxis[0].removePlotLine('plot-line-1');
    $button.html('Add plot line');
  }
  hasPlotLine = !hasPlotLine;
});
</code>```

Title: HighCharts adding line

Body:
try using chart.update() instead

 $button.click(function() {
  if (!hasPlotLine) {
    chart.update({
        yAxis:{
        plotLines: [{
               value: 40,
                        color: 'red',
                        width: 2,
                        id: 'plot-line-1'
            }]
      }
    })
    $button.html('Remove plot line');
  } else {
    chart.yAxis[0].removePlotLine('plot-line-1');
    $button.html('Add plot line');
  }
  hasPlotLine = !hasPlotLine;
});


问:
No prompt ubuntu virtual machine using vagrant on Git Bash
After logging into the VM using vagrant ssh using GitBash on Windows 10, I don't see any directory prompts. While it does run the python web forum (for a tutorial on Udacity on Intro to Relational Databases), it won't let me run psql so I can continue the lesson. I can change directories, list information about the files, and run python but the prompt isn't working like normal.

Screenshot here: screenshot.

Please note the forum is running, this screenshot was taken after I exited and restarted vagrant.

Vagrant version 1.9.6

Ubuntu version 16.04.2 LTS

All programs installed or running in administrator mode.

答:
I had the same problem attempting to set up Laravel Homestead - in my case it seems to be an issue with Git Bash / MINGW64.

My work-around was to use PuTTY

Install PuTTY, PuTTYgen

Create a .ppk of the key you're using to connect to the vagrant vm by loading the private key in PuTTYgen and saving the private key

Create a new PuTTY session with your vagrant details, in my case I just copied what was displayed after running "vagrant up" as far as SSH address, username (my PuTTY session Host Name would be "vagrant@localhost" port: 2222)

specify the ppk in the PuTTY configuration under Connection-> SSH-> Auth-> Private key for authentication

In short, try connecting with PuTTY or some other terminal emulator and see if you have any luck.


问:
Get Database Table Name from Entity Framework MetaData
I'm trying to figure out a way to get the underlying SQL table name for a given entity type. I've experimented around with the MetadataWorkspace queries and while I can get lots of information from the object or the storage space, I can't seem to figure out how to map between the two.

So say I have a type in the object model called Lookup - how do I find the tablename (wws_lookups) in the database?

I can query all the EntityType objects for CSpace and SSpace and I can see both listed correctly but I can't figure out how to get SSpace from CSpace.

Is there any way to do this?

答:
Here is another way to find the table name. It is a bit odd but works.
VB:</p>

```<code>For Each Table In northwind.MetadataWorkspace.GetItemCollection(New System.Data.Metadata.Edm.DataSpace)
        'adds table name to a list of strings all table names in EF have the project namespace in front of it.'
        If Table.ToString.Contains("namespace of project") then
            'using substring to remove project namespace from the table name.'
            TableNames.Add(Table.ToString.Substring("length of namespace name"))
        End If
    Next
</code>```

Body:
Here is another way to find the table name. It is a bit odd but works.
VB:

For Each Table In northwind.MetadataWorkspace.GetItemCollection(New System.Data.Metadata.Edm.DataSpace)
        'adds table name to a list of strings all table names in EF have the project namespace in front of it.'
        If Table.ToString.Contains("namespace of project") then
            'using substring to remove project namespace from the table name.'
            TableNames.Add(Table.ToString.Substring("length of namespace name"))
        End If
    Next


问:
React.js filter and collecting data from local JSON file
This question regards collecting JSON-data from a local file and doing multiple state updates.

Im using import database from './db.json' to collect JSON-data in my parent component (app.js) is this a proper way to import local data?

db.json

```<code>{
    "items": [
        {
            "key": 1,
            "name": "Item 1",
        },
        {
            "key": 2,
            "name": "Item 2",
        },
        ...
</code>```

App.js

```<code>import React, { Component } from 'react';
import db from './db.json';

export default class App extends Component {
    ...
}
</code>```

After import, database get set as a state

```<code>    this.state = {
        database: db,
        term: '',
    };
</code>```

Example of a method

```<code>onChange = (e) => {
    this.setState({term: e.target.value})
};
</code>```

State and methods transfers as props to child components (stateless)

```<code><Component onChange={this.onChange} stateOfDb={this.state.database} />
</code>```

All my methods are placed in App.js and being passed down to stateless components, is this a good practice?

What if I want to create a search function and be able to filter thru each item in the database, how could a example of this look?

答:
You can always filter stuff directly on render-time.

Ex:

```<code>updateSearch(ev){
    this.setState({searchString: ev.target.value});
}
render(){
  const filterData = this.state.searchString ? this.state.database.filter(row => row.someProperty.indexOf(this.state.searchString) > -1) : this.state.database;

  <div>
    <input type="text" onChange={(ev) => this.updateSearch(ev)} />
    <ChildComponentToRenderData data={filteredData} />
  </div>
}
</code>```

You dont even have to put the database in state, since it is in fact just held in memory after the import. So in fact, instead of filtering using this.state.database, you can actually just do db.filter. Probably also nice to check if the searchString is actually set when filtering.

Body:
This question regards collecting JSON-data from a local file and doing multiple state updates.

Im using import database from './db.json' to collect JSON-data in my parent component (app.js) is this a proper way to import local data?

db.json

{
    "items": [
        {
            "key": 1,
            "name": "Item 1",
        },
        {
            "key": 2,
            "name": "Item 2",
        },
        ...

App.js

import React, { Component } from 'react';
import db from './db.json';

export default class App extends Component {
    ...
}

After import, database get set as a state

    this.state = {
        database: db,
        term: '',
    };

Example of a method

onChange = (e) => {
    this.setState({term: e.target.value})
};

State and methods transfers as props to child components (stateless)

<Component onChange={this.onChange} stateOfDb={this.state.database} />

All my methods are placed in App.js and being passed down to stateless components, is this a good practice?

What if I want to create a search function and be able to filter thru each item in the database, how could a example of this look?

Body:
You can always filter stuff directly on render-time.

Ex:

updateSearch(ev){
    this.setState({searchString: ev.target.value});
}
render(){
  const filterData = this.state.searchString ? this.state.database.filter(row => row.someProperty.indexOf(this.state.searchString) > -1) : this.state.database;

  <div>
    <input type="text" onChange={(ev) => this.updateSearch(ev)} />
    <ChildComponentToRenderData data={filteredData} />
  </div>
}

You dont even have to put the database in state, since it is in fact just held in memory after the import. So in fact, instead of filtering using this.state.database, you can actually just do db.filter. Probably also nice to check if the searchString is actually set when filtering.


问:
delete tableView cells
I have a table view controller and I have embedded a left bar edit item button.

```<code> override func viewDidLoad() {
        super.viewDidLoad()
navigationItem.leftBarButtonItem = self.editButtonItem
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        if (editingStyle == UITableViewCellEditingStyle.delete) {

            MessageTableView.deleteRows(at: [indexPath], with: .fade)
        }

}
</code>```

When I click the edit button, a circle pops up in order to place a check mark in it

But when I click the edit button I want the red minus sign to appear

But every tutorial I follow, I get the first picture and I don't want that.

答:
Based on your comments below the question, you have enabled the allowsMultipleSelectionDuringEditing property for the table view. With this enabled, the table supports multiple selection while the table view is being edited. This takes precedence over supporting "normal" editing features such as deletion. This is why you get the checkbox (for selection) instead of the red deletion circle.

If you want to support deleting cells with the red circle while in editing mode, you need to disable multiple selection during editing.

Title: delete tableView cells

Body:
I have a table view controller and I have embedded a left bar edit item button.

 override func viewDidLoad() {
        super.viewDidLoad()
navigationItem.leftBarButtonItem = self.editButtonItem
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {

        if (editingStyle == UITableViewCellEditingStyle.delete) {

            MessageTableView.deleteRows(at: [indexPath], with: .fade)
        }

}

When I click the edit button, a circle pops up in order to place a check mark in it

But when I click the edit button I want the red minus sign to appear

But every tutorial I follow, I get the first picture and I don't want that.


问:
Looking for assistance with Bash script for checking if updates are available in lubuntu
I am looking for a simple script that i can use in a bash file to check if there are any system updates available.

I started with

```<code>#!/bin/bash

clear
updates=$(apt list upgradeable)
if [-n ${updates} ]; then
echo "updates available"
else
echo "no updates!"
fi
</code>```

However, the problem is that even if there is no updates, you still get a return of "Listing... Done"

Look forward to any help or advise.

Cheers,
Darren

答:
You can use aptitude for that.</p>

```<code>aptitude -q -F%p --disable-columns search "~U"
</code>```

Body:
I am looking for a simple script that i can use in a bash file to check if there are any system updates available.

I started with

#!/bin/bash

clear
updates=$(apt list upgradeable)
if [-n ${updates} ]; then
echo "updates available"
else
echo "no updates!"
fi

However, the problem is that even if there is no updates, you still get a return of "Listing... Done"

Look forward to any help or advise.

Cheers,
Darren

Body:
You can use aptitude for that.

aptitude -q -F%p --disable-columns search "~U"


问:
How does React know to render component when non prop or state variable changed?
I have the following code for a navigation link which more or less simply handles displaying an active state.

This is working perfectly! My question is: Why? As you can see, I'm checking if the link should be active based on the window.location.pathname matching the url for this link. Inside the render function, I check if this link is active (when calling activeIndicator()).

It seems to be the case that anytime window.location.pathname updates, this re-renders. Is React's lifecycle method shouldComponentUpdate() being updated somehow when there's any change to a variable inside the component? It might be worth noting that I am using React Router in my application and clicking a link does trigger React Router.

Is doing this unsafe or fragile? Would it necessarily be better to track state in a container? Or manually override shouldComponentUpdate()?

Any information around how this is 'magically' working is much appreciated!

Thanks!

```<code>const Navlink = ({text, url}) => {

  const isActive = () => {
    return window.location.pathname === url;
  }

  const activeIndicator = () => {
    if( isActive() ) {
      return (
        <div className="active-indicator">
          <svg height="6" width="6">
            <circle cx="3" cy="3" r="3" fill="black" />
          </svg>
        </div>
      );
    }

    return null;
  }

  return (
    <span className="navbar-link">
      <Link to={ url } style={ (isActive()) ? {color:"black"} : {} }>
        { text }
      </Link>
      { activeIndicator() }
    </span>
  );
}
</code>```

Update

To understand the answer better, it might help to understand how Navlinks is nested.

Top level:

```<code><Router>
  <Main />
</Router>
</code>```

Main:

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

  <Route exact path="/" component={Home} />
  ...
</code>```

And the Navlinks are inside Navbar.

答:
It might be worth noting that I am using React Router in my
  application and clicking a link does trigger React Router.

This is your answer! React Router sends updated props to your components when it routes to them. So when you trigger the link, it routes to the component with some props which triggers the render.

Body:
I have the following code for a navigation link which more or less simply handles displaying an active state.

This is working perfectly! My question is: Why? As you can see, I'm checking if the link should be active based on the window.location.pathname matching the url for this link. Inside the render function, I check if this link is active (when calling activeIndicator()).

It seems to be the case that anytime window.location.pathname updates, this re-renders. Is React's lifecycle method shouldComponentUpdate() being updated somehow when there's any change to a variable inside the component? It might be worth noting that I am using React Router in my application and clicking a link does trigger React Router.

Is doing this unsafe or fragile? Would it necessarily be better to track state in a container? Or manually override shouldComponentUpdate()?

Any information around how this is 'magically' working is much appreciated!

Thanks!

const Navlink = ({text, url}) => {

  const isActive = () => {
    return window.location.pathname === url;
  }

  const activeIndicator = () => {
    if( isActive() ) {
      return (

          <svg height="6" width="6">
            <circle cx="3" cy="3" r="3" fill="black" />
          </svg>

      );
    }

    return null;
  }

  return (

      <Link to={ url } style={ (isActive()) ? {color:"black"} : {} }>
        { text }
      </Link>
      { activeIndicator() }

  );
}

Update

To understand the answer better, it might help to understand how Navlinks is nested.

Top level:

<Router>

</Router>

Main:

  <Navbar />

  <Route exact path="/" component={Home} />
  ...

And the Navlinks are inside Navbar.


问:
How to change results in Access query?
I have a table, we'll call it users.

```<code>id username type
</code>```

The type field is a two character type, so each user either has US, MO, AD.  Not sure why the original developer did this, but I cannot change this method, unfortunately.

```<code>1 mike US
2 Tim AD
3 mark MO
</code>```

Instead of returning US, AD... etc types in Access, I'd like the query to replace the US with USER, replace MO with MODERATOR, and replace AD with ADMIN.

Is this possible?

Kind of like SELECT * FROM USERS and then if statements within Access (if US, then USER).  Not sure how to proceed?

答:
If you had another table called user type that looked like this

```<code>UserType (typeid, description)
US  USER
AD  ADMIN
MO  MODERATOR
</code>```

it would be trivial

```<code> SELECT users.id, users.username, UserType.description as type
 FROM
    USERS
    INNER JOIN UserType
    ON USERS.Type = UserType.TypeID;
</code>```

you could also use a VBA function, or nested IIF

You could also change your Look up Display Control to a Combo Box and set the row source type to value list

Title: How to change results in Access query?

Body:
I have a table, we'll call it users.

id username type

The type field is a two character type, so each user either has US, MO, AD.  Not sure why the original developer did this, but I cannot change this method, unfortunately.

1 mike US
2 Tim AD
3 mark MO

Instead of returning US, AD... etc types in Access, I'd like the query to replace the US with USER, replace MO with MODERATOR, and replace AD with ADMIN.

Is this possible?

Kind of like SELECT * FROM USERS and then if statements within Access (if US, then USER).  Not sure how to proceed?

Body:
If you had another table called user type that looked like this

UserType (typeid, description)
US  USER
AD  ADMIN
MO  MODERATOR

it would be trivial

 SELECT users.id, users.username, UserType.description as type
 FROM
    USERS
    INNER JOIN UserType
    ON USERS.Type = UserType.TypeID;

you could also use a VBA function, or nested IIF

You could also change your Look up Display Control to a Combo Box and set the row source type to value list


问:
Redirect to https but only specific domains/subdomains and specific url
I want to redirect all traffic from  HTTP to HTTPS, but only if a specific url is different from /oldsite (but only in subdomains sub1 and sub2)

for example:

```<code>http://example.com/any/thing --> redirects to --> https://example.com/any/thing

http://sub1.example.com/any/thing --> redirects to --> https://sub1.example.com/any/thing
</code>```

but

```<code>http://example.com/oldsite/any/thing
</code>```

and

```<code>http://sub1.example.com/oldsite/any/thing -> do not cause this redirect
</code>```

I tried:

```<code>RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:(sub1|sub2)\.)?example\.com
RewriteCond %{REQUEST_URI} !^/oldsite [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</code>```

Thank you.

UPDATE: Also tested last two lines as:

```<code>RewriteCond %{THE_REQUEST} !/oldsite [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301, NE]
</code>```

答:
Make sure to have your rule when HTTPS is off and use THE_REQUEST variable instead of REQUEST_URI:

```<code>RewriteCond %{HTTPS} off
RewriteCond %{THE_REQUEST} !/oldsite [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]
</code>```

Body:
I want to redirect all traffic from  HTTP to HTTPS, but only if a specific url is different from /oldsite (but only in subdomains sub1 and sub2)

for example:

http://example.com/any/thing --> redirects to --> https://example.com/any/thing

http://sub1.example.com/any/thing --> redirects to --> https://sub1.example.com/any/thing

but

http://example.com/oldsite/any/thing

and

http://sub1.example.com/oldsite/any/thing -> do not cause this redirect

I tried:

RewriteEngine on
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:(sub1|sub2)\.)?example\.com
RewriteCond %{REQUEST_URI} !^/oldsite [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Thank you.

UPDATE: Also tested last two lines as:

RewriteCond %{THE_REQUEST} !/oldsite [NC]
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301, NE]

Body:
Make sure to have your rule when HTTPS is off and use THE_REQUEST variable instead of REQUEST_URI:

RewriteCond %{HTTPS} off
RewriteCond %{THE_REQUEST} !/oldsite [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301,NE]


问:
React native setting/accessing a variable inside a function
I'm trying to set the variables lat and lng to the coordinates returned by the geocoder. I think that lat and lng are accessible from inside the geocoder code where it says Geocoder.getFromLocation(inputWhere).then(...), but then outside of that, it doesn't seem to have set the variables to the geocoder's coordinates. Am I missing something about the variable scope? I've commented what the alerts are returning. I've tested that the geocoder works fine and that the "if" condition is being satisfied. Any help appreciated, thanks!</p>

```<code>submitData = (inputWhere) => {

var lat = 0;
var lng = 0;

if(inputWhere != '') {
  Geocoder.getFromLocation(inputWhere).then(
   json => {
    var location = json.results[0].geometry.location;
    alert(lat); // Here it says 0
    lat = location.lat; // 40
    lng = location.lng;
    alert(lat); // Here it says 40
   },
   error => {
    alert(error);
   }
 );
 alert(lat); // Here it says 0
}
alert(lat); // Here it says 0

}
</code>```

答:
Geocoder.getFromLocation() takes time to occur.

You need to wait until it finishes

Body:
I'm trying to set the variables lat and lng to the coordinates returned by the geocoder. I think that lat and lng are accessible from inside the geocoder code where it says Geocoder.getFromLocation(inputWhere).then(...), but then outside of that, it doesn't seem to have set the variables to the geocoder's coordinates. Am I missing something about the variable scope? I've commented what the alerts are returning. I've tested that the geocoder works fine and that the "if" condition is being satisfied. Any help appreciated, thanks!

submitData = (inputWhere) => {

var lat = 0;
var lng = 0;

if(inputWhere != '') {
  Geocoder.getFromLocation(inputWhere).then(
   json => {
    var location = json.results[0].geometry.location;
    alert(lat); // Here it says 0
    lat = location.lat; // 40
    lng = location.lng;
    alert(lat); // Here it says 40
   },
   error => {
    alert(error);
   }
 );
 alert(lat); // Here it says 0
}
alert(lat); // Here it says 0

}


问:
Create custom Range in Word Javascript API / Office.js
I understand that many methods of the Word Javascript API return a Range or RangeCollection. But, is there a constructor function developers can use to create a new Range directly?

My use case is that I need to look at each paragraph, identify errors, and syntax highlight them. So, I'd like to just get the plain text of the paragraph using the API, find the errors on my own, and then use that information to create a Range that I can use to decorate the text (or add a Bounday/ContentControl to refer to it later).

答:
there are a couple of options for you.

a. Use search - you can scope it to the paragraph. You can also use range.compareLocationWith to compare if the found range is the same and remove dupes. So the idea is you grab a paragraph, analyze, find an issue, do a search to get the range (and make sure is the range you need). Once you have a range you can apply formatting, insert content controls or insert, replace content.

b. Use split - is a method you can use to decompose a paragraph into words (each a range).

c. ExpandTo - to extend a given range to another.

d. on any object you can use .getRange() to get its associated range.


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

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

Whereas I'd rather it expand to the left.

Markup/Blade (I'm using Laravel):

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

CSS:

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

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

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

答:
Try setting a float left for your fallback class
, it might be taking the parent property of float right </p>

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

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

Whereas I'd rather it expand to the left.

Markup/Blade (I'm using Laravel):

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

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

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

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

CSS:

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

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

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


问:
Is there a better way to produce a membership matrix (one-hot array) for an array of cluster assignments in Python?
After running kmeans I can easily get an array with the assigned clusters for ever data point. Now I want to get a membership matrix (one-hot array) which has the different clusters as columns and indicates the cluster assignment by either 1 or 0 in the matrix for each data point.

My code is shown below and it works but I am wondering if there is a more elegant way to do the same.

```<code>km = KMeans(n_clusters=3).fit(data)
membership_matrix = np.stack([np.where(km.labels_ == 0, 1,0),
                              np.where(km.labels_ == 1, 1,0),
                              np.where(km.labels_ == 2, 1,0)]
                              axis = 1)
</code>```

答:
So you can create 'one-hot array' which is equivalent to your membership array from array of cluster according to this question. Here is how you do it using np.eye

```<code>import numpy as np

clusters = np.array([2,1,2,2,0,1])
n_clusters = max(clusters) + 1
membership_matrix = np.eye(n_clusters)[clusters]
</code>```

Output is as follows

```<code>array([[ 0.,  0.,  1.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 1.,  0.,  0.],
       [ 0.,  1.,  0.]])
</code>```

Body:
After running kmeans I can easily get an array with the assigned clusters for ever data point. Now I want to get a membership matrix (one-hot array) which has the different clusters as columns and indicates the cluster assignment by either 1 or 0 in the matrix for each data point.

My code is shown below and it works but I am wondering if there is a more elegant way to do the same.

km = KMeans(n_clusters=3).fit(data)
membership_matrix = np.stack([np.where(km.labels_ == 0, 1,0),
                              np.where(km.labels_ == 1, 1,0),
                              np.where(km.labels_ == 2, 1,0)]
                              axis = 1)

Body:
So you can create 'one-hot array' which is equivalent to your membership array from array of cluster according to this question. Here is how you do it using np.eye

import numpy as np

clusters = np.array([2,1,2,2,0,1])
n_clusters = max(clusters) + 1
membership_matrix = np.eye(n_clusters)[clusters]

Output is as follows

array([[ 0.,  0.,  1.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.],
       [ 0.,  0.,  1.],
       [ 1.,  0.,  0.],
       [ 0.,  1.,  0.]])


问:
UIWebView font is thinner in portrait than landscape
My app contains a UIWebView. When the app rotates from portrait to landscape or back, the font weight appears to slightly change. Both bold text and regular text get slightly bolder in landscape, and slightly thinner in portrait.

This does not appear to be the case in Safari, only in my app. Here is an example image, taken as a screenshot on the iPad. I have rotated and cropped an example section.

alt text http://dl.swankdb.com/font-change-example.png

I have the following CSS configured, but it seems to prevent the drastic font size change, not the subtle weight change that I am observing:

```<code>html {
    -webkit-text-size-adjust: none; /* Prevent font scaling in landscape */
}
</code>```

Can anyone explain this? The simulator does not do it -- but my iPad, iPhone 3GS and iPhone 4 all have it. I've also received reports from customers that it happens to them, so I know it's not in my head!

答:
Well after spending a rediculous amount of time trying to figure this out I have found a solution:

Use this:

html {

-webkit-font-smoothing: none;

}

Body:
My app contains a UIWebView. When the app rotates from portrait to landscape or back, the font weight appears to slightly change. Both bold text and regular text get slightly bolder in landscape, and slightly thinner in portrait.

This does not appear to be the case in Safari, only in my app. Here is an example image, taken as a screenshot on the iPad. I have rotated and cropped an example section.

alt text http://dl.swankdb.com/font-change-example.png

I have the following CSS configured, but it seems to prevent the drastic font size change, not the subtle weight change that I am observing:

html {
    -webkit-text-size-adjust: none; /* Prevent font scaling in landscape */
}

Can anyone explain this? The simulator does not do it -- but my iPad, iPhone 3GS and iPhone 4 all have it. I've also received reports from customers that it happens to them, so I know it's not in my head!


问:
'Double join' nested MySQL query?
as a beginner, I'm struggling with this for a few hours now, any help is much appreciated :D

I have 3 tables:

```<code>threads (id, title)
tags (id, name)
tag_thread (thread_id, tag_id)
</code>```

The following, working code returns the 5 most used tags (names) of the latest 100 threads:

```<code>select ta.name
from tags ta
join tag_thread tt on tt.tag_id = ta.id
join (select * from threads order by id desc limit 100) th on tt.thread_id = th.id
group by ta.name
order by count(ta.name) desc
limit 5
</code>```

Question: Given there is a $tagId, how would I have to change to query to filter the results so that only those tags show up, which are connected to threads that use tags with $tagId?

Thank you very much!

答:
If i've understood correctly, I would recommend you create a temporary table to store the threads which have the tags you are interested in

```<code>    CREATE TEMPORARY TABLE tmp_threads AS
    SELECT distinct tt.thread_id
    FROM tag_thread tt
    WHERE tt.tag_id IN (123,46,12,121)
-- (put tag ids in above query)
</code>```

next you change your query to something like this

```<code>select ta.name
from tags ta
join tag_thread tt on tt.tag_id = ta.id
join tmp_threads th on tt.thread_id = th.id
group by ta.name
order by count(ta.name) desc
limit 5
</code>```

Title: 'Double join' nested MySQL query?

Body:
as a beginner, I'm struggling with this for a few hours now, any help is much appreciated :D

I have 3 tables:

threads (id, title)
tags (id, name)
tag_thread (thread_id, tag_id)

The following, working code returns the 5 most used tags (names) of the latest 100 threads:

select ta.name
from tags ta
join tag_thread tt on tt.tag_id = ta.id
join (select * from threads order by id desc limit 100) th on tt.thread_id = th.id
group by ta.name
order by count(ta.name) desc
limit 5

Question: Given there is a $tagId, how would I have to change to query to filter the results so that only those tags show up, which are connected to threads that use tags with $tagId?

Thank you very much!

Body:
If i've understood correctly, I would recommend you create a temporary table to store the threads which have the tags you are interested in

    CREATE TEMPORARY TABLE tmp_threads AS
    SELECT distinct tt.thread_id
    FROM tag_thread tt
    WHERE tt.tag_id IN (123,46,12,121)
-- (put tag ids in above query)

next you change your query to something like this

select ta.name
from tags ta
join tag_thread tt on tt.tag_id = ta.id
join tmp_threads th on tt.thread_id = th.id
group by ta.name
order by count(ta.name) desc
limit 5


问:
Can More Than One Tenant Read/Write a Contact?
I have a very basic requirement for a CRM I'm building in the Consumer Debt space.  An issuer, say Bank of America, has to charge off a credit card, so then send the credit card with the information to the collections department which can either farm it out to a collection agency, or sell the charged-off debt to another debt buying company.  While they're trying to collect the debt, they'll log bits of information about the customer: last address, are they working, did a collection company get involved.  That is, they'll collect information about the consumer behind the credit card.

Usually, the debt is passed on to a debt buyer who goes through this whole process again, usually with almost no information from BofA about the previous attempt to collect.

So here's the question: is there any capability in Microsoft CRM (or Salesforce) that would allow this customer record to be sold/transferred/shared between tenants?  The idea is that the consumer would be much better represented if their information flowed with the credit card as it made it's way through the debt buyers and collection agencies.

答:
Salesforce has a feature called Salesforce-to-Salesforce that does allow the sharing of data between two previously linked orgs.

You could also build your Managed Package that included web services/callouts to do this.


问:
In BASH, can we assign and display the value in the variable _ (underscore)?
Answering to the following question:
 Allowed characters in linux environment variable names @aiden-bell writes that the following patterns gives all allowed shell variable names in BASH : [a-zA-Z_]+[a-zA-Z0-9_]*

I found this to be true. In fact I can export value _="Just for fun". Unfortunately though, whenever I print it I get __bp_preexec_invoke_exec

I went through this thread and while it is instructive it doesn't actually answer my question. Irrespective of whatever the shell might do with the variable $_, can I use it for my own means? Also, whatever exactly is __bp_preexec_invoke_exec? Thanks and regards.

答:
You can assign to the special parameter _, but the shell will also update its value after each command. Typically, you only use it as a dummy variable where you don't care about the result, such as in something like

```<code>while read _ second _ ; do ...; done < input.txt
</code>```

where you only care about the second column of each input line.

From the man page:

```<code>  _      At  shell  startup,  set to the absolute pathname used to invoke
          the shell or shell script being executed as passed in the  envi-
          ronment  or  argument  list.   Subsequently, expands to the last
          argument to the previous command, after expansion.  Also set  to
          the  full  pathname  used  to  invoke  each command executed and
          placed in the environment exported to that command.  When check-
          ing  mail,  this  parameter holds the name of the mail file cur-
          rently being checked.
</code>```

Body:
You can assign to the special parameter _, but the shell will also update its value after each command. Typically, you only use it as a dummy variable where you don't care about the result, such as in something like

while read _ second _ ; do ...; done < input.txt

where you only care about the second column of each input line.

From the man page:

  _      At  shell  startup,  set to the absolute pathname used to invoke
          the shell or shell script being executed as passed in the  envi-
          ronment  or  argument  list.   Subsequently, expands to the last
          argument to the previous command, after expansion.  Also set  to
          the  full  pathname  used  to  invoke  each command executed and
          placed in the environment exported to that command.  When check-
          ing  mail,  this  parameter holds the name of the mail file cur-
          rently being checked.


问:
google email app and a web host switch: redirecting?
I have an organization using google email app. They just switched hosts for their website and now the email is disabled because google doesn't have the right configurations for the new host of the web. How do I deliver the correct info to google to get the email enabled again? </p>

答: It is probably due to changes in DNS rather switching web hosting provider. You should read the guide to setting up DNS for google mail.</p>


问:
How to merge remote master to local branch
I have a local branch of a project ("configUpdate") that I've forked from somebody else's project and I've done a load of changes on it and would like to merge the changes they've made in to my local branch.

I've tried

```<code>git pull --rebase origin configUpdate
</code>```

but it hasn't grabbed the latest changes - how can I merge the two?  (also for bonus points what did I do with the pull --rebase command?)

答:
git rebase didn't seem to work for me. After git rebase, when I try to push changes to my local branch, I kept getting an error ("hint: Updates were rejected because the tip of your current branch is behind its remote counterpart. Integrate the remote changes (e.g. 'git pull ...') before pushing again.") even after git pull. What finally worked for me was git merge.

```<code>git checkout <local_branch>
git merge <master>
</code>```

If you are a beginner like me, here is a good article on git merge vs git rebase.
https://www.atlassian.com/git/tutorials/merging-vs-rebasing

Body:
I have a local branch of a project ("configUpdate") that I've forked from somebody else's project and I've done a load of changes on it and would like to merge the changes they've made in to my local branch.

I've tried

git pull --rebase origin configUpdate

but it hasn't grabbed the latest changes - how can I merge the two?  (also for bonus points what did I do with the pull --rebase command?)

Body:
git rebase didn't seem to work for me. After git rebase, when I try to push changes to my local branch, I kept getting an error ("hint: Updates were rejected because the tip of your current branch is behind its remote counterpart. Integrate the remote changes (e.g. 'git pull ...') before pushing again.") even after git pull. What finally worked for me was git merge.

git checkout <local_branch>
git merge <master>

If you are a beginner like me, here is a good article on git merge vs git rebase.
https://www.atlassian.com/git/tutorials/merging-vs-rebasing