问:
How can define subfolder to look for config files for jhipster registry
I just ran jhipster registry and its working fine. It's looking for config files from central-config folder. I want to refactor my config files under folders in the central-config folder itself. That's something that I can achieve running Spring Cloud Config server with a configuration like this:

```<code>spring:
       cloud:
            config:
                   server:
                         git:
                            default-label: develop
                            uri: file://${user.home}/config-repo
                            search-paths: employee-service, enterprise-service
</code>```

How can I achieve such behavior with 'composite thing' in jhipster-registry. For info, this is the bootstrap.yml file from jhipster registry:

```<code># ===================================================================
# Spring Cloud Config bootstrap configuration for the "dev" profile
# In prod profile, properties will be overwriten by the ones defined in bootstrap-prod.yml
# ===================================================================

spring:
    application:
        name: jhipster-registry
    profiles:
        active: dev
        include: composite
    cloud:
        config:
            server:
                bootstrap: true
                composite:
                    - type: native
                      search-locations: file:./central-config
                     #search-locations: file://${user.home}/Acensi/isupplier/config-repo

                prefix: /config
            fail-fast: true
            # name of the config server's property source (file.yml) that we want to use
            name: jhipster-registry
            profile: dev # profile(s) of the property source
            label: master # toggle to switch to a different version of the configuration as stored in git
            # it can be set to any label, branch or commit of the config source git repository

info:
    project:
        version: #project.version#

# uncomment to enable encryption features
#encrypt:
#    key: my-secret-encryption-key-to-change-in-production
</code>```

答:
I was upgrading an existing older JHipster Registry to 5.0.1. I was also using the git repo. The problem with the above configurations is that the property is not called search-locations for the git repo it is search-paths. In order to keep everything working as before which was had the search paths specified via an environment variable SPRING_CLOUD_CONFIG_SERVER_GIT_SEARCH-PATHS, I use the following configuration in my prod bootstrap.

bootstrap-prod.yml:

```<code>spring:
    cloud:
        config:
            server:
                bootstrap: true
                composite:
                    - type: git
                    uri: git@bitbucket.org:whatever/repo
                    search-paths: ${spring.cloud.config.server.git.search-paths}
                    ignore-local-ssh-settings: true
                    private-key: |
                      -----BEGIN RSA PRIVATE KEY-----
</code>```

Body:
I just ran jhipster registry and its working fine. It's looking for config files from central-config folder. I want to refactor my config files under folders in the central-config folder itself. That's something that I can achieve running Spring Cloud Config server with a configuration like this:

spring:
       cloud:
            config:
                   server:
                         git:
                            default-label: develop
                            uri: file://${user.home}/config-repo
                            search-paths: employee-service, enterprise-service

How can I achieve such behavior with 'composite thing' in jhipster-registry. For info, this is the bootstrap.yml file from jhipster registry:

# ===================================================================
# Spring Cloud Config bootstrap configuration for the "dev" profile
# In prod profile, properties will be overwriten by the ones defined in bootstrap-prod.yml
# ===================================================================

spring:
    application:
        name: jhipster-registry
    profiles:
        active: dev
        include: composite
    cloud:
        config:
            server:
                bootstrap: true
                composite:
                    - type: native
                      search-locations: file:./central-config
                     #search-locations: file://${user.home}/Acensi/isupplier/config-repo

                prefix: /config
            fail-fast: true
            # name of the config server's property source (file.yml) that we want to use
            name: jhipster-registry
            profile: dev # profile(s) of the property source
            label: master # toggle to switch to a different version of the configuration as stored in git
            # it can be set to any label, branch or commit of the config source git repository

info:
    project:
        version: #project.version#

# uncomment to enable encryption features
#encrypt:
#    key: my-secret-encryption-key-to-change-in-production

Body:
I was upgrading an existing older JHipster Registry to 5.0.1. I was also using the git repo. The problem with the above configurations is that the property is not called search-locations for the git repo it is search-paths. In order to keep everything working as before which was had the search paths specified via an environment variable SPRING_CLOUD_CONFIG_SERVER_GIT_SEARCH-PATHS, I use the following configuration in my prod bootstrap.

bootstrap-prod.yml:

spring:
    cloud:
        config:
            server:
                bootstrap: true
                composite:
                    - type: git
                    uri: git@bitbucket.org:whatever/repo
                    search-paths: ${spring.cloud.config.server.git.search-paths}
                    ignore-local-ssh-settings: true
                    private-key: |
                      -----BEGIN RSA PRIVATE KEY-----


来源: stackexchange

问:
Using Twilio in Node.js,
I am trying to make an automated SMS text app using Twilio and I am having a hard time connecting it to my localhost. I keep receiving a "cannot /get" error. Basically, I am trying to send and receive messages using a webhook. Can someone take a look and see what's going on? This code was given to me by Twilio:</p>

```<code>const http = require('http');
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;

const app = express();

app.post('/sms', (req, res) => {
  const twiml = new MessagingResponse();

  twiml.message('The Robots are coming! Head for the hills!');

  res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});

http.createServer(app).listen(2001, () => {
  console.log('Express server listening on port 2001');
});
</code>```

答:
Looks like you've misplaced post but wanted get (since you're trying to access the route via a get request)

change

```<code>app.post('/sms' ...
</code>```

to

```<code>app.get('/sms' ...
</code>```

OwnerDisplayName: Aimee Casden

ContentLicense: CC BY-SA 4.0

Title: Using Twilio in Node.js,

Body:
I am trying to make an automated SMS text app using Twilio and I am having a hard time connecting it to my localhost. I keep receiving a "cannot /get" error. Basically, I am trying to send and receive messages using a webhook. Can someone take a look and see what's going on? This code was given to me by Twilio:

const http = require('http');
const express = require('express');
const MessagingResponse = require('twilio').twiml.MessagingResponse;

const app = express();

app.post('/sms', (req, res) => {
  const twiml = new MessagingResponse();

  twiml.message('The Robots are coming! Head for the hills!');

  res.writeHead(200, {'Content-Type': 'text/xml'});
  res.end(twiml.toString());
});

http.createServer(app).listen(2001, () => {
  console.log('Express server listening on port 2001');
});

Body:
Looks like you've misplaced post but wanted get (since you're trying to access the route via a get request)

change

app.post('/sms' ...

to

app.get('/sms' ...


问:
I want to convert razor syntax into comma shape " " so I will be able to render div dynamically with jquery
I want to convert RazorSyntax into concatenation (StringFormat) in JavaScript

Asp.Net Mvc

```<code>              @Html.TextBox("questionChoice", null, new { @required = "required", @class = "form-control" })
</code>```

JavaScript

```<code>     var answersDiv = " <div class='row myrow' >" +
         "<div class='col-md-5'>" +
              @Html.TextBox('questionChoice', null, new { @required = 'required', @class = 'form-control' }) +
            "</div>" +
       " <div class='col-md-2 mt-1'> " +
              " <label style='font-weight:normal'> <label><input type='checkbox'  name='isCorrect'>Option 1</label> " +
        " </div> " +
</code>```

same sentence output show

答:
Switch the quotes and apostrophes</p>

```<code>var answersDiv = ' <div class="row myrow" >' +
     '<div class="col-md-5">' +
          '@Html.TextBox("questionChoice", null, new { @required = "required", @class = "form-control" })' +
        '</div>' +
   ' <div class="col-md-2 mt-1"> ' +
          ' <label style="font-weight:normal"> <label><input type="checkbox"  name="isCorrect">Option 1</label> ' +
    '</div>' +
</code>```

Body:
I want to convert RazorSyntax into concatenation (StringFormat) in JavaScript

Asp.Net Mvc

              @Html.TextBox("questionChoice", null, new { @required = "required", @class = "form-control" })

JavaScript

     var answersDiv = "
" +
         "
" +
              @Html.TextBox('questionChoice', null, new { @required = 'required', @class = 'form-control' }) +
            "
" +
       "
 " +
              "  <input type='checkbox'  name='isCorrect'>Option 1 " +
        "
 " +

same sentence output show

Body:
Switch the quotes and apostrophes

var answersDiv = ' <div class="row myrow" >' +
     '<div class="col-md-5">' +
          '@Html.TextBox("questionChoice", null, new { @required = "required", @class = "form-control" })' +
        '</div>' +
   ' <div class="col-md-2 mt-1"> ' +
          ' <label style="font-weight:normal"> <label><input type="checkbox"  name="isCorrect">Option 1</label> ' +
    '</div>' +


问:
I've to create a deepArray2String method that expects a 2D int array 'x' and returns its string representation
Create a deepArray2String method that expects a 2D int array 'a1' and returns its string representation, which can be written to the console.

I've tried some logics but i'm getting this error:

tester.java:18: error: incompatible types: StringBuffer cannot be converted to String
   return result;
           ^

```<code>public String deepArray2String(int[][] a1){

    StringBuffer result = new StringBuffer();
    for (int i = 0; i < a1.length; i++) {
        for (int j = 0; j < a1[i].length; j++) {
            result.append("[" + a1[i][j] + "]");
            if (j == a1.length && i != a1.length-1) {
                result.append(",");
            }
        }
    }
    return result;
}
</code>```

System.out.println (deepArray2String (new int [] [] {{1}, {2}, {4}}));

Output should be [1], [2], [4]]

System.out.println (deepArray2String (new int [] [] {{1}, {2, 3}}));

Output should be [[1], [2, 3]]

System.out.println (deepArray2String (new int [] [] {}));

Output should be []

System.out.println (deepArray2String (new int [] [] {{5, 3}, {1}, {-1, 1}}));

Output should be [[5, 3], [1], [-1, 1]]

答:
There is no need to reinvent the wheel, Java already has a built static method in  java.util.Arrays that does this. Autoboxing means it will work with arrays of any primitive type.

```<code>import java.util.Arrays;
import org.junit.Test;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ExampleTest {

    @Test
    public void test() {
        log.info(Arrays.deepToString(new int[][] { { 1 }, { 2 }, { 4 } }));
        log.info(Arrays.deepToString(new int[][] { { 1 }, { 2, 3 } }));
        log.info(Arrays.deepToString(new int[][] {}));
        log.info(Arrays.deepToString(new int[][] { { 5, 3 }, { 1 }, { -1, 1 } }));
    }
}
</code>```

Results

```<code>[main] INFO coaching.arrays.ExampleTest - [[1], [2], [4]]
[main] INFO coaching.arrays.ExampleTest - [[1], [2, 3]]
[main] INFO coaching.arrays.ExampleTest - []
[main] INFO coaching.arrays.ExampleTest - [[5, 3], [1], [-1, 1]]
</code>```

Parameters works exactly the same way.

```<code>@Test
public void test() {
    int[][] a = new int[][] { { 1 }, { 2 }, { 4 } };
    log.info(Arrays.deepToString(a));

    int[][] a2 = new int[][] { { 1 }, { 2, 3 } };
    log.info(Arrays.deepToString(a2));

    int[][] a3 = new int[][] {};
    log.info(Arrays.deepToString(a3));

    int[][] a4 = new int[][] { { 5, 3 }, { 1 }, { -1, 1 } };
    log.info(Arrays.deepToString(a4));
}
</code>```

Body:
Create a deepArray2String method that expects a 2D int array 'a1' and returns its string representation, which can be written to the console.

I've tried some logics but i'm getting this error:

tester.java:18: error: incompatible types: StringBuffer cannot be converted to String
   return result;
           ^

public String deepArray2String(int[][] a1){

    StringBuffer result = new StringBuffer();
    for (int i = 0; i < a1.length; i++) {
        for (int j = 0; j < a1[i].length; j++) {
            result.append("[" + a1[i][j] + "]");
            if (j == a1.length && i != a1.length-1) {
                result.append(",");
            }
        }
    }
    return result;
}

System.out.println (deepArray2String (new int [] [] {{1}, {2}, {4}}));

Output should be [1], [2], [4]]

System.out.println (deepArray2String (new int [] [] {{1}, {2, 3}}));

Output should be [[1], [2, 3]]

System.out.println (deepArray2String (new int [] [] {}));

Output should be []

System.out.println (deepArray2String (new int [] [] {{5, 3}, {1}, {-1, 1}}));

Output should be [[5, 3], [1], [-1, 1]]

Body:
There is no need to reinvent the wheel, Java already has a built static method in  java.util.Arrays that does this. Autoboxing means it will work with arrays of any primitive type.

import java.util.Arrays;
import org.junit.Test;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ExampleTest {

    @Test
    public void test() {
        log.info(Arrays.deepToString(new int[][] { { 1 }, { 2 }, { 4 } }));
        log.info(Arrays.deepToString(new int[][] { { 1 }, { 2, 3 } }));
        log.info(Arrays.deepToString(new int[][] {}));
        log.info(Arrays.deepToString(new int[][] { { 5, 3 }, { 1 }, { -1, 1 } }));
    }
}

Results

[main] INFO coaching.arrays.ExampleTest - [[1], [2], [4]]
[main] INFO coaching.arrays.ExampleTest - [[1], [2, 3]]
[main] INFO coaching.arrays.ExampleTest - []
[main] INFO coaching.arrays.ExampleTest - [[5, 3], [1], [-1, 1]]

Parameters works exactly the same way.

@Test
public void test() {
    int[][] a = new int[][] { { 1 }, { 2 }, { 4 } };
    log.info(Arrays.deepToString(a));

    int[][] a2 = new int[][] { { 1 }, { 2, 3 } };
    log.info(Arrays.deepToString(a2));

    int[][] a3 = new int[][] {};
    log.info(Arrays.deepToString(a3));

    int[][] a4 = new int[][] { { 5, 3 }, { 1 }, { -1, 1 } };
    log.info(Arrays.deepToString(a4));
}


问:
Compiling a C program using ant-contrib using cpptasks
This is what my build.xml file looks like:

```<code><project name="test" xmlns:cpptasks="antlib:net.sf.antcontrib.cpptasks">
    <target name="build-native">
        <mkdir dir="/home/varun/Desktop/lucene/3018-test/check"/>
        <cpptasks:cc outtype="executable" subsystem="console" outfile="BuildNativeDir" objdir="/home/varun/Desktop/lucene/3018-test">
           <fileset file="/home/varun/Desktop/lucene/3018-test/hello.c" />
        </cpptasks:cc>
    </target>
</project>
</code>```

When I run the command ant build-native I get an error:

```<code>BUILD FAILED
/home/varun/Desktop/lucene/3018-test/build.xml:4: Problem: failed to create task or type antlib:net.sf.antcontrib.cpptasks:cc
Cause: The name is undefined.
Action: Check the spelling.
Action: Check that any custom tasks/types have been declared.
Action: Check that any <presetdef>/<macrodef> declarations have taken place.
No types or tasks have been defined in this namespace yet

This appears to be an antlib declaration.
Action: Check that the implementing library exists in one of:
        -/usr/share/ant/lib
        -/home/varun/.ant/lib
        -a directory added on the command line with the -lib argument

Total time: 0 seconds
</code>```

But my CLASSPATH is set to /usr/share/ant/lib and I have placed the ant-contrib-1.0b3.jar in /usr/share/ant/lib/ant-contrib-1.0b3.jar.

What am I doing wrong?

答:
cpptask is not included in ant-contrib-*.jar. You have to download that separately.

I just tried cpptasks-1.0-beta5 but it did not compile. cpptasks-1.0-beta4 had a precompiled jar in the archive and that worked fine.

ContentLicense: CC BY-SA 3.0

Body:
This is what my build.xml file looks like:

<project name="test" xmlns:cpptasks="antlib:net.sf.antcontrib.cpptasks">
    <target name="build-native">
        <mkdir dir="/home/varun/Desktop/lucene/3018-test/check"/>
        <cpptasks:cc outtype="executable" subsystem="console" outfile="BuildNativeDir" objdir="/home/varun/Desktop/lucene/3018-test">
           <fileset file="/home/varun/Desktop/lucene/3018-test/hello.c" />
        </cpptasks:cc>
    </target>
</project>

When I run the command ant build-native I get an error:

BUILD FAILED
/home/varun/Desktop/lucene/3018-test/build.xml:4: Problem: failed to create task or type antlib:net.sf.antcontrib.cpptasks:cc
Cause: The name is undefined.
Action: Check the spelling.
Action: Check that any custom tasks/types have been declared.
Action: Check that any <presetdef>/<macrodef> declarations have taken place.
No types or tasks have been defined in this namespace yet

This appears to be an antlib declaration.
Action: Check that the implementing library exists in one of:
        -/usr/share/ant/lib
        -/home/varun/.ant/lib
        -a directory added on the command line with the -lib argument

Total time: 0 seconds

But my CLASSPATH is set to /usr/share/ant/lib and I have placed the ant-contrib-1.0b3.jar in /usr/share/ant/lib/ant-contrib-1.0b3.jar.

What am I doing wrong?


问:
Is there a way to stop incrementing rows at n when the primary key is set to AUTO_INCREMENT?
I want only  6400 number of rows in my newtable. How do I do this?

I have a table that looks like this:

```<code>CREATE TABLE `newtable` (
    ID_NT int(10) NOT NULL AUTO_INCREMENT
)ENGINE=InnoDB DEFAULT CHARSET=latin1;
</code>```

答:
You can use a trigger on your table. This works of course only if you don't delete rows

```<code>DELIMITER $$
CREATE TRIGGER InsertPreventTrigger BEFORE INSERT ON yourtable
FOR EACH ROW
BEGIN
DECLARE idcount INT;
set idcount = ( select count(*) from id where request = new.request );
IF idcount> 6400
THEN
  SIGNAL SQLSTATE '45000'
  SET MESSAGE_TEXT = 'You can not insert record';
END $$
DELIMITER ;
</code>```

And you have ti change yourtable and id ti fit to your needs

Updates to with count rows, that fits the request better

Body:
I want only  6400 number of rows in my newtable. How do I do this?

I have a table that looks like this:

CREATE TABLE `newtable` (
    ID_NT int(10) NOT NULL AUTO_INCREMENT
)ENGINE=InnoDB DEFAULT CHARSET=latin1;

Body:
You can use a trigger on your table. This works of course only if you don't delete rows

DELIMITER $$
CREATE TRIGGER InsertPreventTrigger BEFORE INSERT ON yourtable
FOR EACH ROW
BEGIN
DECLARE idcount INT;
set idcount = ( select count(*) from id where request = new.request );
IF idcount> 6400
THEN
  SIGNAL SQLSTATE '45000'
  SET MESSAGE_TEXT = 'You can not insert record';
END $$
DELIMITER ;

And you have ti change yourtable and id ti fit to your needs

Updates to with count rows, that fits the request better


问:
Using freedesktop portal to take screenshots with Python
I have been trying to write a flatpak application in python, which uses the freedesktop portal to take screenshots. I am adapting Gimp's freedesktop screenshot plugin which is written in c and I am running into trouble when it comes to accessing the screenshot after it is taken and shared with my application. I get a uri of the form '/org/freedesktop/portal/desktop/request/1_326/t' and the freedesktop portal documentation says that the uri points into a fuse file system mounted at run/user/$UID/doc/ and I can confirm that the screenshots are being saved there. However, t I can't seem to be able to get a useful identifier for them so that I can attach them to an email with my app.

I have experimented with all of the methods in the freedesktop Documents portal and have had no success there. After calling a dbus proxy which returns a uri which is saved in the opath variable the Gimp implementation sets up another dbus proxy and then connects that proxy to a callback function here: the full file that I copied these snippets from is available here <https://github.com/GNOME/gimp/blob/master/plug-ins/screenshot/screenshot-freedesktop.c>

```<code>if (opath)
    {
      GDBusProxy *proxy2 = NULL;

      proxy2 = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION,
                                              G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START,
                                              NULL,
                                              "org.freedesktop.portal.Desktop",
                                              opath,
                                              "org.freedesktop.portal.Request",
                                              NULL, NULL);
      *image_ID = 0;
      g_signal_connect (proxy2, "g-signal",
                        G_CALLBACK (screenshot_freedesktop_dbus_signal),
                        image_ID);

      gtk_main ();
      g_object_unref (proxy2);
      g_free (opath);
</code>```

And the screenshot_freedesktop_dbus_signal function looks like this:

```<code>static void
screenshot_freedesktop_dbus_signal (GDBusProxy *proxy,
                                    gchar      *sender_name,
                                    gchar      *signal_name,
                                    GVariant   *parameters,
                                    gint32     *image_ID)
{
  if (g_strcmp0 (signal_name, "Response") == 0)
    {
      GVariant *results;
      guint32   response;

      g_variant_get (parameters, "(u@a{sv})",
                     &response,
                     &results);

      /* Possible values:
       * 0: Success, the request is carried out
       * 1: The user cancelled the interaction
       * 2: The user interaction was ended in some other way
       * Cf. https://github.com/flatpak/xdg-desktop-portal/blob/master/data/org.freedesktop.portal.Request.xml
       */
      if (response == 0)
        {
          gchar *uri;

          if (g_variant_lookup (results, "uri", "s", &uri))
            {
              GFile *file = g_file_new_for_uri (uri);
              gchar *path = g_file_get_path (file);

              *image_ID = gimp_file_load (GIMP_RUN_NONINTERACTIVE,
                                          path, path);
              gimp_image_set_filename (*image_ID, "screenshot.png");

              /* Delete the actual file. */
              g_file_delete (file, NULL, NULL);

              g_object_unref (file);
              g_free (path);
              g_free (uri);
            }
        }

      g_variant_unref (results);
      gtk_main_quit ();
    }
}
</code>```

My code works the same way until the callback function. I can't find the pythonic equivalent of the g_signal_connect function. I have tried adding the callback to the new proxy's initialization like this

```<code>proxy2 = Gio.DBusProxy.new_for_bus(Gio.BusType.SESSION,
                                            Gio.DBusProxyFlags.NONE,
                                            None,
                                            "org.freedesktop.portal.Desktop",
                                            returned_uri[0],
                                            "org.freedesktop.portal.Request",
                                            None,
                                            G_CALLBACK(self.receive_screenshot_signal),
                                            None)
</code>```

but my receive_screenshot_signal function is not passed any values and the task objects which are passed in say that they are not finished.

I am not sure where to go from here so any advice or insight into how I can use the dbusproxy library and/or the freedesktop portals more effectively would be appreciated. Thanks!

答:
I resolved this issue by subscribing to the signal from the bus on the path of the request handle.

```<code>        args = GLib.Variant('(sa{sv})', (filename, {}))
        result = self.proxy.call_sync('Screenshot',
                                      args,
                                      Gio.DBusCallFlags.NONE,
                                      -1,
                                      None)
        request_handle = result.unpack()[0]
        self.bus.signal_subscribe("org.freedesktop.portal.Desktop",
                                  "org.freedesktop.portal.Request",
                                  "Response",
                                  request_handle,
                                  None,
                                  Gio.DBusSignalFlags.NO_MATCH_RULE,
                                  self.receive_screenshot_signal)
</code>```

I couldn't find any specific documention on Gio.bus.signal_subscribe but here is how the callback function handles the return:

```<code>  def receive_screenshot_signal(self,
                                  connection,
                                  sender,
                                  path,
                                  interface,
                                  signal,
                                  params):
        if not isinstance(params, GLib.Variant):
            print("It's not a variant")
            return
        response_code, results = params.unpack()
        # Response code 0 signifies success
        if response_code != 0 or 'uri' not in results:
            print("Error taking screenshot")
            return
        parsed_uri = urlparse(results['uri'])
        assert parsed_uri.scheme == "file"
        self.screenshot = unquote(parsed_uri.path)
</code>```

Body:
I have been trying to write a flatpak application in python, which uses the freedesktop portal to take screenshots. I am adapting Gimp's freedesktop screenshot plugin which is written in c and I am running into trouble when it comes to accessing the screenshot after it is taken and shared with my application. I get a uri of the form '/org/freedesktop/portal/desktop/request/1_326/t' and the freedesktop portal documentation says that the uri points into a fuse file system mounted at run/user/$UID/doc/ and I can confirm that the screenshots are being saved there. However, t I can't seem to be able to get a useful identifier for them so that I can attach them to an email with my app.

I have experimented with all of the methods in the freedesktop Documents portal and have had no success there. After calling a dbus proxy which returns a uri which is saved in the opath variable the Gimp implementation sets up another dbus proxy and then connects that proxy to a callback function here: the full file that I copied these snippets from is available here <https://github.com/GNOME/gimp/blob/master/plug-ins/screenshot/screenshot-freedesktop.c>

if (opath)
    {
      GDBusProxy *proxy2 = NULL;

      proxy2 = g_dbus_proxy_new_for_bus_sync (G_BUS_TYPE_SESSION,
                                              G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START,
                                              NULL,
                                              "org.freedesktop.portal.Desktop",
                                              opath,
                                              "org.freedesktop.portal.Request",
                                              NULL, NULL);
      *image_ID = 0;
      g_signal_connect (proxy2, "g-signal",
                        G_CALLBACK (screenshot_freedesktop_dbus_signal),
                        image_ID);

      gtk_main ();
      g_object_unref (proxy2);
      g_free (opath);

And the screenshot_freedesktop_dbus_signal function looks like this:

static void
screenshot_freedesktop_dbus_signal (GDBusProxy *proxy,
                                    gchar      *sender_name,
                                    gchar      *signal_name,
                                    GVariant   *parameters,
                                    gint32     *image_ID)
{
  if (g_strcmp0 (signal_name, "Response") == 0)
    {
      GVariant *results;
      guint32   response;

      g_variant_get (parameters, "(u@a{sv})",
                     &response,
                     &results);

      /* Possible values:
       * 0: Success, the request is carried out
       * 1: The user cancelled the interaction
       * 2: The user interaction was ended in some other way
       * Cf. https://github.com/flatpak/xdg-desktop-portal/blob/master/data/org.freedesktop.portal.Request.xml
       */
      if (response == 0)
        {
          gchar *uri;

          if (g_variant_lookup (results, "uri", "s", &uri))
            {
              GFile *file = g_file_new_for_uri (uri);
              gchar *path = g_file_get_path (file);

              *image_ID = gimp_file_load (GIMP_RUN_NONINTERACTIVE,
                                          path, path);
              gimp_image_set_filename (*image_ID, "screenshot.png");

              /* Delete the actual file. */
              g_file_delete (file, NULL, NULL);

              g_object_unref (file);
              g_free (path);
              g_free (uri);
            }
        }

      g_variant_unref (results);
      gtk_main_quit ();
    }
}

My code works the same way until the callback function. I can't find the pythonic equivalent of the g_signal_connect function. I have tried adding the callback to the new proxy's initialization like this

proxy2 = Gio.DBusProxy.new_for_bus(Gio.BusType.SESSION,
                                            Gio.DBusProxyFlags.NONE,
                                            None,
                                            "org.freedesktop.portal.Desktop",
                                            returned_uri[0],
                                            "org.freedesktop.portal.Request",
                                            None,
                                            G_CALLBACK(self.receive_screenshot_signal),
                                            None)

but my receive_screenshot_signal function is not passed any values and the task objects which are passed in say that they are not finished.

I am not sure where to go from here so any advice or insight into how I can use the dbusproxy library and/or the freedesktop portals more effectively would be appreciated. Thanks!

Body:
I resolved this issue by subscribing to the signal from the bus on the path of the request handle.

        args = GLib.Variant('(sa{sv})', (filename, {}))
        result = self.proxy.call_sync('Screenshot',
                                      args,
                                      Gio.DBusCallFlags.NONE,
                                      -1,
                                      None)
        request_handle = result.unpack()[0]
        self.bus.signal_subscribe("org.freedesktop.portal.Desktop",
                                  "org.freedesktop.portal.Request",
                                  "Response",
                                  request_handle,
                                  None,
                                  Gio.DBusSignalFlags.NO_MATCH_RULE,
                                  self.receive_screenshot_signal)

I couldn't find any specific documention on Gio.bus.signal_subscribe but here is how the callback function handles the return:

  def receive_screenshot_signal(self,
                                  connection,
                                  sender,
                                  path,
                                  interface,
                                  signal,
                                  params):
        if not isinstance(params, GLib.Variant):
            print("It's not a variant")
            return
        response_code, results = params.unpack()
        # Response code 0 signifies success
        if response_code != 0 or 'uri' not in results:
            print("Error taking screenshot")
            return
        parsed_uri = urlparse(results['uri'])
        assert parsed_uri.scheme == "file"
        self.screenshot = unquote(parsed_uri.path)


问:
How can I generate every combination of pattern of 4 numbers and 2 A-Z characters
I wrote a small script to talk with a database that I got from a friend so I can link a dutch zip code with a street name. But I want to do it by myself

The ZIP codes are build up like NNNNCC where N is a number 0-9 (Ignoring the first 0's 0000-0999 isn't possible) and C = character A-Z.

How can I generate every possible combination in PHP?

答:
Simple foreach nested loop as:

```<code>foreach(range(1000,9999) as $num)
    foreach(range('A', 'Z') as $c1)
        foreach(range('A', 'Z') as $c2)
            $res[] = $num . $c1 . $c2;
</code>```

I am not at my computer so sorry for syntax error if any (you may need to convert the $num to string but I guess PHP will handle it...

Body:
Simple foreach nested loop as:

foreach(range(1000,9999) as $num)
    foreach(range('A', 'Z') as $c1)
        foreach(range('A', 'Z') as $c2)
            $res[] = $num . $c1 . $c2;

I am not at my computer so sorry for syntax error if any (you may need to convert the $num to string but I guess PHP will handle it...


问:
Sorting array of objects by string vs numeric values behaving differently
This question is a little long-winded, but please bear with me.

I have a general-purpose value-comparison function to use with .sort():

```<code>export function compareObjectValues(key: string, direction: string = 'asc') {
  // used as a comparator supplied to .sort() for sorting arrays of objects

  return function(a: Object, b: Object): number {
    const propertyA = getDescendantProperty(a, key);
    const propertyB = getDescendantProperty(b, key);

    if (!propertyA || !propertyB) {
      return 0;
    }

    const normalizedPropA = (typeof propertyA === 'string') ? (propertyA as string).toLocaleLowerCase() : propertyA;
    const normalizedPropB = (typeof propertyB === 'string') ? (propertyB as string).toLocaleLowerCase() : propertyB;
    let comparison = 0;

    if (normalizedPropA > normalizedPropB) {
      comparison = 1;
    }
    else {
      comparison = -1;
    }

    if (typeof normalizedPropA === 'number' && typeof normalizedPropB === 'number') {
      console.log('comparison', comparison);
      return comparison;
    }
    else {
      console.log('string comparison', comparison);
      return (direction === 'desc') ? (comparison * -1) : comparison;
    }
  };
}
</code>```

The inner helper function, getDescendantProperty() is to access values on an object by dot path safely:

```<code>export function getDescendantProperty(obj: object, path: string) {
  // safely access nested properties if the property of the object is itself, an object

  if (path.includes('.')) {
    return path.split('.').reduce((accumulator: object, part: string) => accumulator && accumulator[part] || undefined, obj);
  }
  else {
    return obj[path];
  }
}
</code>```

When I sort an array of objects using a string to sort by, compareObjectValues() works as expected. When using numeric values, it fails, and doesn't iterate through all of the expected values to compare.

Example:

```<code>describe('on an object that uses a number for sorting', () => {
  it('should return the comparison of the values in the correct order', () => {
    const objects = [
      { id: 4 },
      { id: 0 },
      { id: 2 },
      { id: 3 },
      { id: 1 },
    ];

    const sortedObjects = objects.sort(utils.compareObjectValues('id'));

    expect(sortedObjects).toEqual([{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]);
  });
});
</code>```

Karma output:

```<code>LOG: 'comparison', 1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 0 of 2 SUCCESS (0 secs / 0 secs)
LOG: 'comparison', -1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 0 of 2 SUCCESS (0 secs / 0 secs)
LOG: 'comparison', -1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 0 of 2 SUCCESS (0 secs / 0 secs)
Chrome 74.0.3729 (Mac OS X 10.14.5) Utils tests When calling `compareObjectValues` on an object that uses a number for sorting should return the comparison of the numbers in the correct order FAILED
        Error: Expected $[0].id = 4 to equal 0.
        Expected $[1].id = 0 to equal 1.
        Expected $[2].id = 1 to equal 2.
        Expected $[3].id = 2 to equal 3.
        Expected $[4].id = 3 to equal 4.
            at <Jasmine>
            at UserContext.<anonymous> (src/app/lib/utils.spec.ts:133:31)
            at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:391:1)
            at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/zone-testing.js:308:1)
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
Chrome 74.0.3729 (Mac OS X 10.14.5) Utils tests When calling `compareObjectValues` on an object that uses a number for sorting should return the comparison of the numbers in the correct order FAILED
        Error: Expected $[0].id = 4 to equal 0.
        Expected $[1].id = 0 to equal 1.
        Expected $[2].id = 1 to equal 2.
        Expected $[3].id = 2 to equal 3.
        Expected $[4].id = 3 to equal 4.
            at <Jasmine>
            at UserContext.<anonymous> (src/app/lib/utils.spec.ts:133:31)
            at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:391:1)
LOG: 'string comparison', -1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
LOG: 'string comparison', 1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
LOG: 'string comparison', -1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
LOG: 'string comparison', 1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
LOG: 'string comparison', 1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
LOG: 'string comparison', -1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
LOG: 'string comparison', -1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
LOG: 'string comparison', -1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
LOG: 'string comparison', 1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 2 of 2 (1 FAILED) (0.19 secs / 0.16 secs)
TOTAL: 1 FAILED, 1 SUCCESS
TOTAL: 1 FAILED, 1 SUCCESS
npm ERR! Test failed.  See above for more details.
</code>```

As you can see from the log, when processing the objects with numeric values, it stopped after 3 iterations. With string values, it processed 9.

I have verified that getDescendantProperty() returns the expected value. I have also verified that the logic of compareObjectValues() works as expected if I apply the same comparisons manually by passing a function to .sort() in my test.

I'm having some difficulty isolating my error and would greatly appreciate some help.

答:
The problem lies in this lazy check for properties:

```<code>if (!propertyA || !propertyB) return 0;
</code>```

This works fine for checking certain types of values, but will give you unexpected results when checking against numbers (!0 === true), empty strings (!'' === true) etc.

Use strict checks instead:

```<code>if (typeof propertyA === 'undefined' || typeof propertyB === 'undefined') return 0;
</code>```

Body:
This question is a little long-winded, but please bear with me.

I have a general-purpose value-comparison function to use with .sort():

export function compareObjectValues(key: string, direction: string = 'asc') {
  // used as a comparator supplied to .sort() for sorting arrays of objects

  return function(a: Object, b: Object): number {
    const propertyA = getDescendantProperty(a, key);
    const propertyB = getDescendantProperty(b, key);

    if (!propertyA || !propertyB) {
      return 0;
    }

    const normalizedPropA = (typeof propertyA === 'string') ? (propertyA as string).toLocaleLowerCase() : propertyA;
    const normalizedPropB = (typeof propertyB === 'string') ? (propertyB as string).toLocaleLowerCase() : propertyB;
    let comparison = 0;

    if (normalizedPropA > normalizedPropB) {
      comparison = 1;
    }
    else {
      comparison = -1;
    }

    if (typeof normalizedPropA === 'number' && typeof normalizedPropB === 'number') {
      console.log('comparison', comparison);
      return comparison;
    }
    else {
      console.log('string comparison', comparison);
      return (direction === 'desc') ? (comparison * -1) : comparison;
    }
  };
}

The inner helper function, getDescendantProperty() is to access values on an object by dot path safely:

export function getDescendantProperty(obj: object, path: string) {
  // safely access nested properties if the property of the object is itself, an object

  if (path.includes('.')) {
    return path.split('.').reduce((accumulator: object, part: string) => accumulator && accumulator[part] || undefined, obj);
  }
  else {
    return obj[path];
  }
}

When I sort an array of objects using a string to sort by, compareObjectValues() works as expected. When using numeric values, it fails, and doesn't iterate through all of the expected values to compare.

Example:

describe('on an object that uses a number for sorting', () => {
  it('should return the comparison of the values in the correct order', () => {
    const objects = [
      { id: 4 },
      { id: 0 },
      { id: 2 },
      { id: 3 },
      { id: 1 },
    ];

    const sortedObjects = objects.sort(utils.compareObjectValues('id'));

    expect(sortedObjects).toEqual([{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }]);
  });
});

Karma output:

LOG: 'comparison', 1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 0 of 2 SUCCESS (0 secs / 0 secs)
LOG: 'comparison', -1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 0 of 2 SUCCESS (0 secs / 0 secs)
LOG: 'comparison', -1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 0 of 2 SUCCESS (0 secs / 0 secs)
Chrome 74.0.3729 (Mac OS X 10.14.5) Utils tests When calling `compareObjectValues` on an object that uses a number for sorting should return the comparison of the numbers in the correct order FAILED
        Error: Expected $[0].id = 4 to equal 0.
        Expected $[1].id = 0 to equal 1.
        Expected $[2].id = 1 to equal 2.
        Expected $[3].id = 2 to equal 3.
        Expected $[4].id = 3 to equal 4.
            at <Jasmine>
            at UserContext.<anonymous> (src/app/lib/utils.spec.ts:133:31)
            at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:391:1)
            at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke (node_modules/zone.js/dist/zone-testing.js:308:1)
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
Chrome 74.0.3729 (Mac OS X 10.14.5) Utils tests When calling `compareObjectValues` on an object that uses a number for sorting should return the comparison of the numbers in the correct order FAILED
        Error: Expected $[0].id = 4 to equal 0.
        Expected $[1].id = 0 to equal 1.
        Expected $[2].id = 1 to equal 2.
        Expected $[3].id = 2 to equal 3.
        Expected $[4].id = 3 to equal 4.
            at <Jasmine>
            at UserContext.<anonymous> (src/app/lib/utils.spec.ts:133:31)
            at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke (node_modules/zone.js/dist/zone.js:391:1)
LOG: 'string comparison', -1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
LOG: 'string comparison', 1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
LOG: 'string comparison', -1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
LOG: 'string comparison', 1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
LOG: 'string comparison', 1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
LOG: 'string comparison', -1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
LOG: 'string comparison', -1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
LOG: 'string comparison', -1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
LOG: 'string comparison', 1
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 1 of 2 (1 FAILED) (0 secs / 0.159 secs)
Chrome 74.0.3729 (Mac OS X 10.14.5): Executed 2 of 2 (1 FAILED) (0.19 secs / 0.16 secs)
TOTAL: 1 FAILED, 1 SUCCESS
TOTAL: 1 FAILED, 1 SUCCESS
npm ERR! Test failed.  See above for more details.

As you can see from the log, when processing the objects with numeric values, it stopped after 3 iterations. With string values, it processed 9.

I have verified that getDescendantProperty() returns the expected value. I have also verified that the logic of compareObjectValues() works as expected if I apply the same comparisons manually by passing a function to .sort() in my test.

I'm having some difficulty isolating my error and would greatly appreciate some help.

Body:
The problem lies in this lazy check for properties:

if (!propertyA || !propertyB) return 0;

This works fine for checking certain types of values, but will give you unexpected results when checking against numbers (!0 === true), empty strings (!'' === true) etc.

Use strict checks instead:

if (typeof propertyA === 'undefined' || typeof propertyB === 'undefined') return 0;


问:
Any ideas why VBA isn't being case-sensitive in a VLookup?
I've created a VBA Macro to look at a string of input text in the cell E3, split it into individual characters and then VLookup those characters against a table of individual character pixel widths, which is added to the code using a named range, "pw_Table".

The pixel-widths for each letter are then summed and displayed in a cell below the text input box - "Cells(4,5)". Hitting return is meant to show the combined pixel-width total for the complete string.

The problem is that it is not being case sensitive and is using the same VLookup value for both upper and lower case characters.

All the manuals I've seen say VBA is case sensitive on VLookup, and all I can find are ways to get around this.

For my issue, however, the VLookup must be case sensitive to make sure I get the correct pixel width for each letter, for example, "c" is 9 pixels wide, "C" is 13.

I have tried reordering the upper and lower case characters in the table to see if that made a difference, but it only uses the first values it encounters for each letter of the alphabet, whether they be upper- or lower-case.

I thought that I might use INDEX, MATCH, and EXACT, but couldn't see how to implement that in VBA.

This is the Macro code ...

```<code>Private Sub ReadCharacter()
    cell_value = ThisWorkbook.Sheets("Pixel-widths").Range("E3")
    Character_Value = 0
    For rep = 1 To Len(cell_value)
        Character = Mid(cell_value, rep, 1)
        On Error GoTo MyErrorHandler
        Character_Value = Application.WorksheetFunction.VLookup(Character, [pw_Table], 2, 0)
        Pixel_Width = Pixel_Width + Character_Value
MyErrorHandler:
        Character_Value = 10
        Resume Next
    Next rep
        Cells(4, 5) = Pixel_Width
End Sub
</code>```

I had some issues with numbers, with VBA reporting Run-time Error 1004, but I bodged this by adding an error trap because all the numerals from 0-9 are 10 pixels wide.

I simply can't see why VBA is breaking its own rules.

答:
Here's another way...

```<code>Character_Value = Evaluate("INDEX(" & Range("pw_Table").Address(, , , True) & _
    ",MATCH(TRUE,EXACT(INDEX(" & Range("pw_Table").Address(, , , True) & ",0,1),""" & Character & """),0),2)")
</code>```

Hope this helps!

Body:
I've created a VBA Macro to look at a string of input text in the cell E3, split it into individual characters and then VLookup those characters against a table of individual character pixel widths, which is added to the code using a named range, "pw_Table".

The pixel-widths for each letter are then summed and displayed in a cell below the text input box - "Cells(4,5)". Hitting return is meant to show the combined pixel-width total for the complete string.

The problem is that it is not being case sensitive and is using the same VLookup value for both upper and lower case characters.

All the manuals I've seen say VBA is case sensitive on VLookup, and all I can find are ways to get around this.

For my issue, however, the VLookup must be case sensitive to make sure I get the correct pixel width for each letter, for example, "c" is 9 pixels wide, "C" is 13.

I have tried reordering the upper and lower case characters in the table to see if that made a difference, but it only uses the first values it encounters for each letter of the alphabet, whether they be upper- or lower-case.

I thought that I might use INDEX, MATCH, and EXACT, but couldn't see how to implement that in VBA.

This is the Macro code ...

Private Sub ReadCharacter()
    cell_value = ThisWorkbook.Sheets("Pixel-widths").Range("E3")
    Character_Value = 0
    For rep = 1 To Len(cell_value)
        Character = Mid(cell_value, rep, 1)
        On Error GoTo MyErrorHandler
        Character_Value = Application.WorksheetFunction.VLookup(Character, [pw_Table], 2, 0)
        Pixel_Width = Pixel_Width + Character_Value
MyErrorHandler:
        Character_Value = 10
        Resume Next
    Next rep
        Cells(4, 5) = Pixel_Width
End Sub

I had some issues with numbers, with VBA reporting Run-time Error 1004, but I bodged this by adding an error trap because all the numerals from 0-9 are 10 pixels wide.

I simply can't see why VBA is breaking its own rules.

Body:
Here's another way...

Character_Value = Evaluate("INDEX(" & Range("pw_Table").Address(, , , True) & _
    ",MATCH(TRUE,EXACT(INDEX(" & Range("pw_Table").Address(, , , True) & ",0,1),""" & Character & """),0),2)")

Hope this helps!


问:
How can I store the value of a Css Property (height in px) in a Javascript variable as a number?
How can I store the value of a Css Property (height in px) in a    Javascript variable as a number?
somediv.style.height (in px) should be stored in a
    variable.

```<code><style>

     #somediv {
        width: 100px;
        height: 20px;
     }

</style>

<script>

    let somediv = document.getElementById('somediv');
    let height = somediv.style.height;

</script
</code>```

but this doesnt work. Please help me!

答:
Use window.getComputedStyle to get CSS values after they have been computed by the browser:

```<code>const divElement = document.getElementById("somediv");
const style = window.getComputedStyle(divElement);
const height = style.getPropertyValue("height");
</code>```

Body:
How can I store the value of a Css Property (height in px) in a    Javascript variable as a number?
somediv.style.height (in px) should be stored in a
    variable.

but this doesnt work. Please help me!

Body:
Use window.getComputedStyle to get CSS values after they have been computed by the browser:

const divElement = document.getElementById("somediv");
const style = window.getComputedStyle(divElement);
const height = style.getPropertyValue("height");


问:
Sidekiq StatsD Tagging in perform job
I am implementing statsd publishing in Sidekiq and I was able to do it successfully, however tags only seem to be added to the "global" statsd messages. As you can see below the app: is not appended for the actual sidekiq.job messages, all the other messages do have it. Why is this? I'd like for the app tag to always be present.

```<code>sidekiq.processed:16|g|#app:test-app
sidekiq.enqueued:0|g|#app:test-app
sidekiq.retries:2|g|#app:test-app
sidekiq.dead:0|g|#app:test-app
sidekiq.scheduled:0|g|#app:test-app
sidekiq.busy:0|g|#app:test-app
sidekiq.enqueued.low:0|g|#app:test-app
sidekiq.enqueued.default:0|g|#app:test-app
sidekiq.job:1|c|#host:MacBook-Pro.local,env:development,name:test_cache_job,queue:default,status:ok
sidekiq.job.time:16034|ms|#host:MacBook-Pro.local,env:development,name:test_cache_job,queue:default,status:ok
</code>```

Here is how I've implemented it in the sidekiq.rb initializer.

```<code>Sidekiq::Pro.dogstatsd = ->{ Datadog::Statsd.new(ENV['DD_HOST'], ENV['DD_PORT'], tags: ["app:#{ENV['APP_NAME']}"]) }

Sidekiq.configure_server do |config|
  # Middleware for StatsD
  config.server_middleware do |chain|
    require 'sidekiq/middleware/server/datadog'
    chain.add Sidekiq::Middleware::Server::Datadog
  end

  config.save_history(Sidekiq::Pro.metrics, 30)
...
</code>```

答:
My colleague just pointed out this to me: https://github.com/mperham/sidekiq/wiki/Middleware#client-middleware-registered-in-both-places

I guess this works:

```<code>  config.server_middleware do |chain|
    require 'sidekiq/middleware/server/datadog'
    chain.add Sidekiq::Middleware::Server::Datadog, tags: ["test:app"]
  end
</code>```

Title: Sidekiq StatsD Tagging in perform job

Body:
I am implementing statsd publishing in Sidekiq and I was able to do it successfully, however tags only seem to be added to the "global" statsd messages. As you can see below the app: is not appended for the actual sidekiq.job messages, all the other messages do have it. Why is this? I'd like for the app tag to always be present.

sidekiq.processed:16|g|#app:test-app
sidekiq.enqueued:0|g|#app:test-app
sidekiq.retries:2|g|#app:test-app
sidekiq.dead:0|g|#app:test-app
sidekiq.scheduled:0|g|#app:test-app
sidekiq.busy:0|g|#app:test-app
sidekiq.enqueued.low:0|g|#app:test-app
sidekiq.enqueued.default:0|g|#app:test-app
sidekiq.job:1|c|#host:MacBook-Pro.local,env:development,name:test_cache_job,queue:default,status:ok
sidekiq.job.time:16034|ms|#host:MacBook-Pro.local,env:development,name:test_cache_job,queue:default,status:ok

Here is how I've implemented it in the sidekiq.rb initializer.

Sidekiq::Pro.dogstatsd = ->{ Datadog::Statsd.new(ENV['DD_HOST'], ENV['DD_PORT'], tags: ["app:#{ENV['APP_NAME']}"]) }

Sidekiq.configure_server do |config|
  # Middleware for StatsD
  config.server_middleware do |chain|
    require 'sidekiq/middleware/server/datadog'
    chain.add Sidekiq::Middleware::Server::Datadog
  end

  config.save_history(Sidekiq::Pro.metrics, 30)
...

Body:
My colleague just pointed out this to me: https://github.com/mperham/sidekiq/wiki/Middleware#client-middleware-registered-in-both-places

I guess this works:

  config.server_middleware do |chain|
    require 'sidekiq/middleware/server/datadog'
    chain.add Sidekiq::Middleware::Server::Datadog, tags: ["test:app"]
  end


问:
How to add dynamic uuid to apigee proxies?
What should be of uuid instead of {java.util.UUID.randomUUID()} to get a random UUID in every request sent to backend ?</p>

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true"
    name="HeaderAddition">
    <DisplayName>HeaderAddition</DisplayName>
    <Properties/>
    <Add>
        <Headers>
            <Header name="uuid">{java.util.UUID.randomUUID()}</Header>
        </Headers>
    </Add>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>
</code>```

答:
I have got the solution .
I have added a Javascript in the preflow to generate the uuid.Then created a assign message policy to have that variable in the request.

JS:

```<code> function generateUUID() { // Public Domain/MIT
    var d = new Date().getTime();
    if (typeof performance !== 'undefined' && typeof performance.now === 'function'){
        d += performance.now(); //use high-precision timer if available
    }
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
}

var uuid = generateUUID();
context.setVariable('x-apigee-uuid', uuid);
</code>```

Assign Message Policy:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true"
name="HeaderAddition-123">
    <DisplayName>HeaderAddition-123</DisplayName>
    <Add>
        <Headers>
            <Header name="uuid">{x-apigee-uuid}</Header>
        </Headers>
    </Add>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>
</code>```

Body:
What should be of uuid instead of {java.util.UUID.randomUUID()} to get a random UUID in every request sent to backend ?

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true"
    name="HeaderAddition">
    <DisplayName>HeaderAddition</DisplayName>
    <Properties/>
    <Add>
        <Headers>
            {java.util.UUID.randomUUID()}
        </Headers>
    </Add>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>

Body:
I have got the solution .
I have added a Javascript in the preflow to generate the uuid.Then created a assign message policy to have that variable in the request.

JS:

 function generateUUID() { // Public Domain/MIT
    var d = new Date().getTime();
    if (typeof performance !== 'undefined' && typeof performance.now === 'function'){
        d += performance.now(); //use high-precision timer if available
    }
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = (d + Math.random() * 16) % 16 | 0;
        d = Math.floor(d / 16);
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
}

var uuid = generateUUID();
context.setVariable('x-apigee-uuid', uuid);

Assign Message Policy:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<AssignMessage async="false" continueOnError="false" enabled="true"
name="HeaderAddition-123">
    <DisplayName>HeaderAddition-123</DisplayName>
    <Add>
        <Headers>
            <Header name="uuid">{x-apigee-uuid}</Header>
        </Headers>
    </Add>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>


问:
How change a iframe content?

Possible Duplicate:

  How to change style of iframe content cross-domain?

Hi everybody.

Is it possible to change an iframe content if it comes from another site?
e.g.

```<code><html>
<head></head>
 <body>
  <iframe src="http://www.google.com"></iframe>
 </body>
</html>
</code>```

Thanks.

答:
Simple answer... no.
If your referring to dom manipulation of the document loaded in the iframe.

For a longer answer see http://en.wikipedia.org/wiki/Cross-site_scripting

Title: How change a iframe content?

Body:
Possible Duplicate:

  How to change style of iframe content cross-domain?

Hi everybody.

Is it possible to change an iframe content if it comes from another site?
e.g.

Thanks.


问:
Can you use instanceOf to determine if an Object is an array and then iterate over that array?
Say I have a method that accepts an instance of a java Object (Java.lang.Object) as a parameter. Is there a way of determining if this passed in Object is an array (of anything) and then iterating over it?

This is what I'm currently trying to do

public static void isThisAnArray(Object x) {
     if (x instanceof Object[]){
         for (Object item : x) {
             //do something with item
         }
     }
}
```

But I get "Can only iterate over an array or an instance of java.lang.Iterable" on the for (Object item : x) line Which makes sense, since I'm passing in an Object and not an array of Objects. But what if that object is an array of objects? Sorry if this is confusing but is there a way to figure out if a passed in java  object is an array?

答:
Putting stuff inside a conditional with an instanceof doesn't magically let the compiler know the thing is an instance of that. You've actually got to cast:</p>

```<code>if (x instanceof Object[]){
  for (Object item : (Object[]) x) {
  }
}
</code>```

Body:
Say I have a method that accepts an instance of a java Object (Java.lang.Object) as a parameter. Is there a way of determining if this passed in Object is an array (of anything) and then iterating over it?

This is what I'm currently trying to do

public static void isThisAnArray(Object x) {
     if (x instanceof Object[]){
         for (Object item : x) {
             //do something with item
         }
     }
}

But I get "Can only iterate over an array or an instance of java.lang.Iterable" on the for (Object item : x) line Which makes sense, since I'm passing in an Object and not an array of Objects. But what if that object is an array of objects? Sorry if this is confusing but is there a way to figure out if a passed in java  object is an array?

Body:
Putting stuff inside a conditional with an instanceof doesn't magically let the compiler know the thing is an instance of that. You've actually got to cast:

if (x instanceof Object[]){
  for (Object item : (Object[]) x) {
  }
}


问:
Greedy Algorithms and Time Complexity #2
We have a bomb that is ticking and may explode. This bomb has n switches, that can be moved up or down. Certain combinations of these switches trigger the bomb, but only one combination disables it.

Our task is to move the switches from the current position to a position that disables the bomb, without exploding it in the meantime. The switches are big and awkward, so we can move only one switch at a time.

We have, lets say, n = 4 switches currently in position ^vvv. We need to get them to the position ^v^^. Forbidden positions are vvv^, ^vv^, ^v^v, and ^^^v.

a.) I had to draw this by hand and find the shortest sequence of switch movements that solves the task - result I got was 4 ...and I found two such sequences, if i am right...

b.) this is where it gets a hard - write a code that answers the above question/questions (the shortest sequence and how many). The code should be generalized so that it would work with another number of switches and other starting, targeted, and forbidden combinations; targeted and forbidden combinations may be multiple or even fewer. Only thing we know for sure is that the switches have only two positions. It should also provide the possibility that the desired condition is unavailable; in this case, the program should of course tell.

c.) Next questions is the time complexity of the code this but for now I think I will just stop here...

I used '0' and '1' instead, because it is easier for me to imagine this.

So my approach towards this was something of a greedy algorithm (I think) - starting position, you think of all the possible (allowed) positions, you ignore the forbidden ones, then pick the one that the sequence of positions has the fewest difference from our targeting sequence.

The key part of the code I am yet to write and that's the part I need help with.

```<code>
all_combinations = ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011' , '1100', '1101', '1110', '1111']

def distance (position1, position2):
     distance = 0
     for i in range (len (position1)):
         if position1 [i]! = position2 [i]:
             distance + = 1
     return distance

def allowed_positions (current, all_combinations):
     allowed = set ()
     for combination and all combinations:
         if the distance (current, combination) == 1:
             allowed.add (combination)
     return allowed

def best_name (current, all_combinations, target):
     list = []
     for option and permitted_mood (current, all_combinations):
         list.append (distance (option, target), option)

</code>```

答:
```<code>start = 8
target = 11
forbidden = {1: -1 , 9: -1, 10: -1, 14: -1}
dimensions = 4

def distance(start, target, forbidden, dimensions):
stack1 = []

stack1.append(start)
forbidden[start] = -1

while(len(stack1) > 0):
    top = stack1.pop()
    for i in range(dimensions):
        testVal = top ^ (1 << i)

        if testVal is target:
            forbidden[testVal] = top
            result = [testVal]
            while testVal is not start:
                testVal = forbidden[testVal]
                result.insert(0, testVal)
            return result

        if testVal not in forbidden:
            forbidden[testVal] = top
            stack1.append(testVal)

return [-1]

print(distance(start, target, forbidden, dimensions))
</code>```

Here is my code for your example in your question. Instead of using bits, I went ahead and used the base 10 number to represent the codes. Forbidden codes are mapped to a hashmap which is used later to trace the path upwards after the target is found. I use a stack to keep track of which code to try. Each time the while loop passes, the last code added is popped and it's unvisited neighbors are added to the stack. Importantly, to prevent cycles, codes on the stack or seen before are added to the list of forbidden nodes. When the target code is found for the first time, an early return is called and the path is traced through the hashmap.

This solution uses breadth first search and returns the first time the target is found. That means it does not guarantee the shortest path from start to target, but it does guarantee a working path if it's available. Since all possible codes are possibly traversed and there are 2^dimensions number of nodes, the time complexity of this algorithm is also O(2^n)

Body:
We have a bomb that is ticking and may explode. This bomb has n switches, that can be moved up or down. Certain combinations of these switches trigger the bomb, but only one combination disables it.

Our task is to move the switches from the current position to a position that disables the bomb, without exploding it in the meantime. The switches are big and awkward, so we can move only one switch at a time.

We have, lets say, n = 4 switches currently in position ^vvv. We need to get them to the position ^v^^. Forbidden positions are vvv^, ^vv^, ^v^v, and ^^^v.

a.) I had to draw this by hand and find the shortest sequence of switch movements that solves the task - result I got was 4 ...and I found two such sequences, if i am right...

b.) this is where it gets a hard - write a code that answers the above question/questions (the shortest sequence and how many). The code should be generalized so that it would work with another number of switches and other starting, targeted, and forbidden combinations; targeted and forbidden combinations may be multiple or even fewer. Only thing we know for sure is that the switches have only two positions. It should also provide the possibility that the desired condition is unavailable; in this case, the program should of course tell.

c.) Next questions is the time complexity of the code this but for now I think I will just stop here...

I used '0' and '1' instead, because it is easier for me to imagine this.

So my approach towards this was something of a greedy algorithm (I think) - starting position, you think of all the possible (allowed) positions, you ignore the forbidden ones, then pick the one that the sequence of positions has the fewest difference from our targeting sequence.

The key part of the code I am yet to write and that's the part I need help with.

all_combinations = ['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011' , '1100', '1101', '1110', '1111']

def distance (position1, position2):
     distance = 0
     for i in range (len (position1)):
         if position1 [i]! = position2 [i]:
             distance + = 1
     return distance

def allowed_positions (current, all_combinations):
     allowed = set ()
     for combination and all combinations:
         if the distance (current, combination) == 1:
             allowed.add (combination)
     return allowed

def best_name (current, all_combinations, target):
     list = []
     for option and permitted_mood (current, all_combinations):
         list.append (distance (option, target), option)

Body:
start = 8
target = 11
forbidden = {1: -1 , 9: -1, 10: -1, 14: -1}
dimensions = 4

def distance(start, target, forbidden, dimensions):
stack1 = []

stack1.append(start)
forbidden[start] = -1

while(len(stack1) > 0):
    top = stack1.pop()
    for i in range(dimensions):
        testVal = top ^ (1 << i)

        if testVal is target:
            forbidden[testVal] = top
            result = [testVal]
            while testVal is not start:
                testVal = forbidden[testVal]
                result.insert(0, testVal)
            return result

        if testVal not in forbidden:
            forbidden[testVal] = top
            stack1.append(testVal)

return [-1]

print(distance(start, target, forbidden, dimensions))

Here is my code for your example in your question. Instead of using bits, I went ahead and used the base 10 number to represent the codes. Forbidden codes are mapped to a hashmap which is used later to trace the path upwards after the target is found. I use a stack to keep track of which code to try. Each time the while loop passes, the last code added is popped and it's unvisited neighbors are added to the stack. Importantly, to prevent cycles, codes on the stack or seen before are added to the list of forbidden nodes. When the target code is found for the first time, an early return is called and the path is traced through the hashmap.

This solution uses breadth first search and returns the first time the target is found. That means it does not guarantee the shortest path from start to target, but it does guarantee a working path if it's available. Since all possible codes are possibly traversed and there are 2^dimensions number of nodes, the time complexity of this algorithm is also O(2^n)


问:
How to override Spring Boot library properties?
I would like to override the library properties that I've written in project that is using it. I'm using this Spring guide on creating library: https://spring.io/guides/gs/multi-module/

I would like to know how to override for example my.properties file in the project that uses my library.

Is it even possible?

答:
Do not add application.properties files to a library. It could cause a myriad of problems. If you want to set a default property do it like this:

```<code>@ConfigurationProperties("foo")
public class FooConfig {

    private int bar = 999;

    // getter / setter

}
</code>```

Every application should configure the library values for itself in its own application.properties file.

Body:
Do not add application.properties files to a library. It could cause a myriad of problems. If you want to set a default property do it like this:

@ConfigurationProperties("foo")
public class FooConfig {

    private int bar = 999;

    // getter / setter

}

Every application should configure the library values for itself in its own application.properties file.


答:
Spring Boot property order precedence is described here:

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

From the link:

```<code>Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values. Properties are considered in the following order:
</code>```

The order is 1-17 then. For example, 4 on the list (command-line arguments) overrides 15 on the list (your application.properties file) and so on.

Title: How to override Spring Boot library properties?

Body:
I would like to override the library properties that I've written in project that is using it. I'm using this Spring guide on creating library: https://spring.io/guides/gs/multi-module/

I would like to know how to override for example my.properties file in the project that uses my library.

Is it even possible?

Body:
Spring Boot property order precedence is described here:

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

From the link:

Spring Boot uses a very particular PropertySource order that is designed to allow sensible overriding of values. Properties are considered in the following order:

The order is 1-17 then. For example, 4 on the list (command-line arguments) overrides 15 on the list (your application.properties file) and so on.


问:
Replace spaces with colons in python
I have a string which is in keys-value pair format and separated by space. I want to separated by comma instead of space.

I tried replace function but its also replacing my values spaces with comma.

```<code>val = 'name=Ajay age=21 company=abc PVT LTD empid=12345'
</code>```

my desired output:

```<code>'name=Ajay,age=21,company=abc PVT LTD,empid=12345'
</code>```

答:
How about:

```<code>\w+=[^=]+(?: |$)
</code>```

Check it on Regex101: https://regex101.com/r/GgbqxB/1

Title: Replace spaces with colons in python

Body:
I have a string which is in keys-value pair format and separated by space. I want to separated by comma instead of space.

I tried replace function but its also replacing my values spaces with comma.

val = 'name=Ajay age=21 company=abc PVT LTD empid=12345'

my desired output:

'name=Ajay,age=21,company=abc PVT LTD,empid=12345'

Body:
How about:

\w+=[^=]+(?: |$)

Check it on Regex101: https://regex101.com/r/GgbqxB/1


问:
Codeigniter DB or URI problem with unicode
I'm having a weird problem.

I have this code

$topic contains "海賊_(ONE_PIECE)" from URI /trends/about/海賊_(ONE_PIECE)
I checked to echo $topic and it prints out 海賊_(ONE_PIECE)

```<code>$sql="SELECT wti.redirect_title FROM wikipedia_timelines AS wti WHERE wti.redirect_title = ? LIMIT 1";
$query = $this->db->query($sql,array($topic));
if ($row = $query->result_array())
{
</code>```

The problem is that this code returns $row to be an empty array

```<code>Array
(
    [0] => Array
        (
            [redirect_title] =>
        )

)
</code>```

However, if I use this code (replacing ? with the actual value of $topic, it works perfectly

```<code> $sql="SELECT wti.redirect_title FROM wikipedia_timelines AS wti WHERE wti.redirect_title = '海賊_(ONE_PIECE)' LIMIT 1";
 $query = $this->db->query($sql,array($topic));
 if ($row = $query->result_array())
 {
</code>```

Replacing ? with {$topic} will not make it working too.

This problem only occurs when $topic contains ( ) if it doesn't have () it works fine

I wonder what is the problem.
I suppose there is a problem with URI encoding, but I'm not sure how to fix it.

Please help me.
Thank you

答:
I'm pretty sure your problem is that query binding escapes your input values (im guessing it doesn't like brackets).

try building your sql string with concatenation, like:

```<code>$sql = "SELECT wti.redirect_title FROM wikipedia_timelines AS wti WHERE wti.redirect_title = '".$topic."' LIMIT 1";
$query = $this->db->query($sql);
</code>```

and see if that helps. Or try the active record class, I use it for japanese characters all the time and it seems to work ok.

// EDIT:

To allow brackets in the URI, try and change application/config.config.php and set

```<code>$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-()';
</code>```

also try urldecode($topic); to get the kanji out.

Body:
I'm having a weird problem.

I have this code

$topic contains "海賊_(ONE_PIECE)" from URI /trends/about/海賊_(ONE_PIECE)
I checked to echo $topic and it prints out 海賊_(ONE_PIECE)

$sql="SELECT wti.redirect_title FROM wikipedia_timelines AS wti WHERE wti.redirect_title = ? LIMIT 1";
$query = $this->db->query($sql,array($topic));
if ($row = $query->result_array())
{

The problem is that this code returns $row to be an empty array

Array
(
    [0] => Array
        (
            [redirect_title] =>
        )

)

However, if I use this code (replacing ? with the actual value of $topic, it works perfectly

 $sql="SELECT wti.redirect_title FROM wikipedia_timelines AS wti WHERE wti.redirect_title = '海賊_(ONE_PIECE)' LIMIT 1";
 $query = $this->db->query($sql,array($topic));
 if ($row = $query->result_array())
 {

Replacing ? with {$topic} will not make it working too.

This problem only occurs when $topic contains ( ) if it doesn't have () it works fine

I wonder what is the problem.
I suppose there is a problem with URI encoding, but I'm not sure how to fix it.

Please help me.
Thank you

Body:
I'm pretty sure your problem is that query binding escapes your input values (im guessing it doesn't like brackets).

try building your sql string with concatenation, like:

$sql = "SELECT wti.redirect_title FROM wikipedia_timelines AS wti WHERE wti.redirect_title = '".$topic."' LIMIT 1";
$query = $this->db->query($sql);

and see if that helps. Or try the active record class, I use it for japanese characters all the time and it seems to work ok.

// EDIT:

To allow brackets in the URI, try and change application/config.config.php and set

$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-()';

also try urldecode($topic); to get the kanji out.


问:
Avoid lazyloader attribute
I´ve been looking for how avoid return a list without the attribute lazyLoader, I want to continue using the lazyLoader but I don´t want return the attribute when I return the whole list of my entity from my controller

I´m working with .NET core.

```<code>[
  {
    "lazyLoader": {},
    "id": "id1"
    "name": "name"
  },
  {
    "lazyLoader": {},
    "id": "id2",
    "name": "name2"
  }
]
</code>```

答:
I know this is old, but add

```<code>public boolean ShouldSerializeLazyLoader() { return false; }
</code>```

to all the classes down the tree of the ones you want to serialize, and you will get a lazyloader free JSON.

Ref.: https://www.newtonsoft.com/json/help/html/ConditionalProperties.htm

Title: Avoid lazyloader attribute

Body:
I´ve been looking for how avoid return a list without the attribute lazyLoader, I want to continue using the lazyLoader but I don´t want return the attribute when I return the whole list of my entity from my controller

I´m working with .NET core.

[
  {
    "lazyLoader": {},
    "id": "id1"
    "name": "name"
  },
  {
    "lazyLoader": {},
    "id": "id2",
    "name": "name2"
  }
]

Body:
I know this is old, but add

public boolean ShouldSerializeLazyLoader() { return false; }

to all the classes down the tree of the ones you want to serialize, and you will get a lazyloader free JSON.

Ref.: https://www.newtonsoft.com/json/help/html/ConditionalProperties.htm


问:
How to properly add FontAwesome icons on d3 nodes?
I am trying to add icons on my text nodes from font-awesome. Instead of showing me the proper icon, the whole html gets class fontawesome-i2svg-active fontawesome-i2svg-complete and i get a big question mark/exclamation mark are shown on the page.

I tried applying the following code which i found as a reply on fontawesome github page.

```<code>const textEnter = textElements
  .enter()
  .append('text')
  .attr('x', 15)
  .attr('y', -17)
  .attr('fill', 'black')
  .attr('class', 'fa')
  .attr('font-size', '20')
  .text('\uf2b9');
</code>```

EDIT:

The solution which is offered here doesn't work:

Adding FontAwesome icons to a D3 graph

答:
Are you using the Font-Awesome font?
Double check with the inspector that FontAwesome is set as the font-family

Another solution would be to use font awesomes svg files as images.
or depending on your setup you could even inline the svg files directly in the source code.

Body:
I am trying to add icons on my text nodes from font-awesome. Instead of showing me the proper icon, the whole html gets class fontawesome-i2svg-active fontawesome-i2svg-complete and i get a big question mark/exclamation mark are shown on the page.

I tried applying the following code which i found as a reply on fontawesome github page.

const textEnter = textElements
  .enter()
  .append('text')
  .attr('x', 15)
  .attr('y', -17)
  .attr('fill', 'black')
  .attr('class', 'fa')
  .attr('font-size', '20')
  .text('\uf2b9');

EDIT:

The solution which is offered here doesn't work:

Adding FontAwesome icons to a D3 graph


问:
Rails default error page doesn't show on development
I built an error handler that, when there's an error in any controller method in production, reroutes the user to an error page and sends me, the developer, a notification email. This works, but I want the normal error screen to appear when I'm in development. I assumed the code to produce this was just raise e, but instead in development I'm now getting the default production error page (the one that says "We're sorry, but something went wrong".), instead of the detailed error message and trace that used to appear.

```<code>class ApplicationController < ActionController::Base
  rescue_from StandardError, with: :handle_error

  #error handler
  def handle_error(e)
    if Rails.env.production?
      #code to send email and redirect to error page
    else
      raise e
    end
  end
end
</code>```

I also tried the following:

```<code>raise
raise StandardError.new e
raise e, e.message
raise e.message
</code>```

and if I run any of those in a binding.pry console, they produce the error message I'm looking for, but the error page still just says "We're sorry, but something went wrong."

Anyone know how I can just show the default development error page?

UPDATE

This is insane...so the code to display an error normally should definitely work, but something somewhere is preventing that. If I change config.consider_all_requests_local = true on production, the errors show up on production, but then even if I copy and paste my config/environments/production.rb file into my config/environments/development.rb, the errors still don't show on development. If I enter a pry console, request.local? returns "0", signifying true, and Rails.env returns "development". I have no idea what is going on.

UPDATE 2

Apparently I'm not supposed to be rescuing exceptions on development, but even if I delete every bit of custom error handling code so my Application Controller is just empty, my errors still don't show on development. Further, I have a different app with the same exact error handling code, and for that the errors do show.

答:
Search your code for consider_all_requests_local, it's this configuration that show the full error log.

It must be set as true on your development.rb config file. It's either missing from your configs, or other config is overwriting it

Body:
I built an error handler that, when there's an error in any controller method in production, reroutes the user to an error page and sends me, the developer, a notification email. This works, but I want the normal error screen to appear when I'm in development. I assumed the code to produce this was just raise e, but instead in development I'm now getting the default production error page (the one that says "We're sorry, but something went wrong".), instead of the detailed error message and trace that used to appear.

class ApplicationController < ActionController::Base
  rescue_from StandardError, with: :handle_error

  #error handler
  def handle_error(e)
    if Rails.env.production?
      #code to send email and redirect to error page
    else
      raise e
    end
  end
end

I also tried the following:

raise
raise StandardError.new e
raise e, e.message
raise e.message

and if I run any of those in a binding.pry console, they produce the error message I'm looking for, but the error page still just says "We're sorry, but something went wrong."

Anyone know how I can just show the default development error page?

UPDATE

This is insane...so the code to display an error normally should definitely work, but something somewhere is preventing that. If I change config.consider_all_requests_local = true on production, the errors show up on production, but then even if I copy and paste my config/environments/production.rb file into my config/environments/development.rb, the errors still don't show on development. If I enter a pry console, request.local? returns "0", signifying true, and Rails.env returns "development". I have no idea what is going on.

UPDATE 2

Apparently I'm not supposed to be rescuing exceptions on development, but even if I delete every bit of custom error handling code so my Application Controller is just empty, my errors still don't show on development. Further, I have a different app with the same exact error handling code, and for that the errors do show.


问:
Understanding the types of functions
I am trying to understand the types of functions and being able to explain them.

Two functions:

```<code>insert :: t -> Bool -> ([t],[t]) -> ([t],[t])
insert a True (b,c) = (a:b,c)
insert a False (b,c) = (b,a:c)

partition :: (t -> Bool) -> [t] -> ([t],[t])
partition p [] = ([],[])
partition p (x : xs) = insert x (p x) (partition p xs)
</code>```

From my limited knowledge I think that insert function:

insert is of type t, it takes two arguments one of bool and one of a tuple of two lists of type t and returns a tuple of two lists of type t.

partition is a tuple of type t which returns a bool, and it takes a list of type t as it's argument and returns a tuple of two lists of type t.

Is that the right way of thinking about it or am I getting it wrong? I have been following some tutorials and this is what I've u   nderstood so far.

答:
insert is of type t, it takes two arguments one of Bool and one of a tuple of two lists of type t and returns a tuple of two lists of type t.

No. First of all it is important to notice that in Haskell each function takes exactly one parameter. Indeed

```<code>insert :: t -> Bool -> ([t],[t]) -> ([t],[t])
</code>```

is a short and compact form of:

```<code>insert :: t -> (Bool -> (([t],[t]) -> ([t],[t])))
</code>```

in fact the above is still not very verbose, a canonical form would be:

```<code>insert :: ((->) t) (((->) Bool) (((->) ((,) ([] t)) ([] t))  ((,) ([] t)) ([] t)))
</code>```

but the above is of course not very readable, let us thus stick to the second form.

Each function in Haskell takes exactly one parameter. What here happens is that the result of applying a parameter to a certain function, generates a new function.

So if we would generate an expression insert x, we have constructed a function of the type Bool -> (([t], [t]) -> ([t], [t])).

Informally, one indeed sometimes says that a "function takes n parameters". But it is important to keep that in mind.

Secondly you forgot about the t. We can informally say that insert takes three parameters, a value of type t, a boolean (type Bool), and a 2-tuple with two lists of ts. It will return a 2-tuple of two lists of ts. Depending on whether the Bool is True or False it prepends one of the two lists with the given value.

For example:

```<code>Prelude> insert 5 False ([], [])
([],[5])
Prelude> insert 5 False ([1,4], [2,5])
([1,4],[5,2,5])
Prelude> insert 5 True ([1,4], [2,5])
([5,1,4],[2,5])
Prelude> insert 3 True ([1,4], [2,5])
([3,1,4],[2,5])
Prelude> insert 3 False ([1,4], [2,5])
([1,4],[3,2,5])
</code>```

partition is a tuple of type t which returns a bool, and it takes a list of type t as it's argument and returns a tuple of two lists of type t.

No, the parameter here has type (t -> Bool) that is a function. Indeed in Haskell you can pass functions as parameters.

Informally we can say that partition takes a "predicate" (a function that maps values to Bools) and a list of ts, and it returns a 2-tuple with two lists of ts. Depending on whether the predicate holds for the values in the list, these are sorted in the first or the second list in the 2-tuple.

For example:

```<code>Prelude> partition (>3) [1,4,2,5]
([4,5],[1,2])
Prelude> partition (>3) [1,3,0,2]
([],[1,3,0,2])
Prelude> partition (>3) [1,7,8,0]
([7,8],[1,0])
Prelude> partition (>3) [1,7,8,9]
([7,8,9],[1])
</code>```

Title: Understanding the types of functions

Body:
I am trying to understand the types of functions and being able to explain them.

Two functions:

insert :: t -> Bool -> ([t],[t]) -> ([t],[t])
insert a True (b,c) = (a:b,c)
insert a False (b,c) = (b,a:c)

partition :: (t -> Bool) -> [t] -> ([t],[t])
partition p [] = ([],[])
partition p (x : xs) = insert x (p x) (partition p xs)

From my limited knowledge I think that insert function:

insert is of type t, it takes two arguments one of bool and one of a tuple of two lists of type t and returns a tuple of two lists of type t.

partition is a tuple of type t which returns a bool, and it takes a list of type t as it's argument and returns a tuple of two lists of type t.

Is that the right way of thinking about it or am I getting it wrong? I have been following some tutorials and this is what I've u   nderstood so far.

Body:
insert is of type t, it takes two arguments one of Bool and one of a tuple of two lists of type t and returns a tuple of two lists of type t.

No. First of all it is important to notice that in Haskell each function takes exactly one parameter. Indeed

insert :: t -> Bool -> ([t],[t]) -> ([t],[t])

is a short and compact form of:

insert :: t -> (Bool -> (([t],[t]) -> ([t],[t])))

in fact the above is still not very verbose, a canonical form would be:

insert :: ((->) t) (((->) Bool) (((->) ((,) ([] t)) ([] t))  ((,) ([] t)) ([] t)))

but the above is of course not very readable, let us thus stick to the second form.

Each function in Haskell takes exactly one parameter. What here happens is that the result of applying a parameter to a certain function, generates a new function.

So if we would generate an expression insert x, we have constructed a function of the type Bool -> (([t], [t]) -> ([t], [t])).

Informally, one indeed sometimes says that a "function takes n parameters". But it is important to keep that in mind.

Secondly you forgot about the t. We can informally say that insert takes three parameters, a value of type t, a boolean (type Bool), and a 2-tuple with two lists of ts. It will return a 2-tuple of two lists of ts. Depending on whether the Bool is True or False it prepends one of the two lists with the given value.

For example:

Prelude> insert 5 False ([], [])
([],[5])
Prelude> insert 5 False ([1,4], [2,5])
([1,4],[5,2,5])
Prelude> insert 5 True ([1,4], [2,5])
([5,1,4],[2,5])
Prelude> insert 3 True ([1,4], [2,5])
([3,1,4],[2,5])
Prelude> insert 3 False ([1,4], [2,5])
([1,4],[3,2,5])

partition is a tuple of type t which returns a bool, and it takes a list of type t as it's argument and returns a tuple of two lists of type t.

No, the parameter here has type (t -> Bool) that is a function. Indeed in Haskell you can pass functions as parameters.

Informally we can say that partition takes a "predicate" (a function that maps values to Bools) and a list of ts, and it returns a 2-tuple with two lists of ts. Depending on whether the predicate holds for the values in the list, these are sorted in the first or the second list in the 2-tuple.

For example:

Prelude> partition (>3) [1,4,2,5]
([4,5],[1,2])
Prelude> partition (>3) [1,3,0,2]
([],[1,3,0,2])
Prelude> partition (>3) [1,7,8,0]
([7,8],[1,0])
Prelude> partition (>3) [1,7,8,9]
([7,8,9],[1])


问:
Only extract those words from a list that include no repeating letters, using regex
I have a large word list file with one word per line. I would like to filter out the words with repeating alphabets.

```<code>INPUT:
  abducts
  abe
  abeam
  abel
  abele

OUTPUT:
  abducts
  abe
  abel
</code>```

I'd like to do this using Regex (grep or perl or python). Is that possible?

答:
In response to cjm's solution, I wondered about how it compared to some rather terse Perl:

```<code>my @output = grep { my @l = split ''; my %l; @l{@l} = (); keys %l == @l } @input;
</code>```

Since I am not constrained in character count and formatting here, I'll be a bit clearer, even to the point of over-documenting:

```<code>my @output = grep {

    # Split $_ on the empty string to get letters in $_.
    my @letters = split '';

    # Use a hash to remove duplicate letters.
    my %unique_letters;
    @unique_letters{@letters} = ();  # This is a hash slice assignment.
                                     # See perldoc perlvar for more info

    # is the number of unique letters equal to the number of letters?
    keys %unique_letters == @letters

} @input;
</code>```

And, of course in production code, please do something like this:

```<code>my @output = grep ! has_repeated_chars($_), @input;

sub has_repeated_letters {
    my $word = shift;
    #blah blah blah
    # see example above for the code to use here, with a nip and a tuck.
}
</code>```

Body:
I have a large word list file with one word per line. I would like to filter out the words with repeating alphabets.

INPUT:
  abducts
  abe
  abeam
  abel
  abele

OUTPUT:
  abducts
  abe
  abel

I'd like to do this using Regex (grep or perl or python). Is that possible?

Body:
In response to cjm's solution, I wondered about how it compared to some rather terse Perl:

my @output = grep { my @l = split ''; my %l; @l{@l} = (); keys %l == @l } @input;

Since I am not constrained in character count and formatting here, I'll be a bit clearer, even to the point of over-documenting:

my @output = grep {

    # Split $_ on the empty string to get letters in $_.
    my @letters = split '';

    # Use a hash to remove duplicate letters.
    my %unique_letters;
    @unique_letters{@letters} = ();  # This is a hash slice assignment.
                                     # See perldoc perlvar for more info

    # is the number of unique letters equal to the number of letters?
    keys %unique_letters == @letters

} @input;

And, of course in production code, please do something like this:

my @output = grep ! has_repeated_chars($_), @input;

sub has_repeated_letters {
    my $word = shift;
    #blah blah blah
    # see example above for the code to use here, with a nip and a tuck.
}


问:
Regex in Java for "greater than" or "less than" without using bracket "<|>" symbols
I need a regular expression for Java Pattern.compile("<|>") that would match greater than and less than symbols without actually using bracket symbols. Is there some special character that would mean ">" or "<" symbol?

Additional info: The reason is that my legacy system passes regular expressions from a resource file that first gets parsed using some html tags, and extra brackets confuse the parser, so it errors out. The solution is to substitute ">" and "<" with something else that Java Pattern would interpret as ">" and "<".

What I tried: Pattern.compile("&grt;") does not get interpreted as ">"

答: I'm on mobile and can't run this to test, but I believe that you can use unicode code points to match on the brackets.  So this should work: Pattern.compile("\\u003c|\\u003e");


问:
How to initialize an empty array that can accept any size?
```<code>def __init__(self):
        self.b = []
        for i in range(2):
            board_num = input("Type something to test this out: ")
            n = int(input("enter n: "))
            if board_num == 2:
                self.b = ['R', 'B', 'R', 'B']
    #            n==4
            elif board_num == 3:
                self.b = ['R', 'B', 'R', 'B', 'R', 'B', 'R', 'B', 'B']
    #            n==6
            elif board_num == 4:
                self.b = ['R', 'B', 'R', 'B', 'R', 'B', 'R', 'B', 'B', 'R',
                            'B', 'R', 'R', 'B', 'R', 'B']
        numpy.arange(n*n).reshape((n,n))
        self.b=numpy.array(self.b)
        numpy.random.shuffle(self.b)
        self.b=self.b.reshape(n,n)

  line 30, in __init__
    self.b=self.b.reshape(n,n)

ValueError: cannot reshape array of size 0 into shape (2,2)
</code>```

答:
I'm guessing a bit at what you're trying to accomplish, but here is how I might implement it:

```<code>$ python
Python 3.7.2 (default, Dec 27 2018, 07:35:06)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> n = 4
>>> board = numpy.array(['R', 'B'])
>>> board = numpy.resize(board, (n, n))
>>> board
array([['R', 'B', 'R', 'B'],
       ['R', 'B', 'R', 'B'],
       ['R', 'B', 'R', 'B'],
       ['R', 'B', 'R', 'B']], dtype='<U1')
</code>```

Or with the shuffle step:

```<code>>>> n = 4
>>> board = numpy.array(['R', 'B'])
>>> board = numpy.resize(board, n*n)
>>> board
array(['R', 'B', 'R', 'B', 'R', 'B', 'R', 'B', 'R', 'B', 'R', 'B', 'R',
       'B', 'R', 'B'], dtype='<U1')
>>> numpy.random.shuffle(board)
>>> board
array(['R', 'B', 'R', 'R', 'B', 'R', 'R', 'B', 'R', 'R', 'B', 'B', 'B',
       'B', 'R', 'B'], dtype='<U1')
>>> board = numpy.resize(board, (n, n))
>>> board
array([['R', 'B', 'R', 'R'],
       ['B', 'R', 'R', 'B'],
       ['R', 'R', 'B', 'B'],
       ['B', 'B', 'R', 'B']], dtype='<U1')
</code>```

Body:
I'm guessing a bit at what you're trying to accomplish, but here is how I might implement it:

$ python
Python 3.7.2 (default, Dec 27 2018, 07:35:06)
[Clang 10.0.0 (clang-1000.11.45.5)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> n = 4
>>> board = numpy.array(['R', 'B'])
>>> board = numpy.resize(board, (n, n))
>>> board
array([['R', 'B', 'R', 'B'],
       ['R', 'B', 'R', 'B'],
       ['R', 'B', 'R', 'B'],
       ['R', 'B', 'R', 'B']], dtype='<U1')

Or with the shuffle step:

>>> n = 4
>>> board = numpy.array(['R', 'B'])
>>> board = numpy.resize(board, n*n)
>>> board
array(['R', 'B', 'R', 'B', 'R', 'B', 'R', 'B', 'R', 'B', 'R', 'B', 'R',
       'B', 'R', 'B'], dtype='<U1')
>>> numpy.random.shuffle(board)
>>> board
array(['R', 'B', 'R', 'R', 'B', 'R', 'R', 'B', 'R', 'R', 'B', 'B', 'B',
       'B', 'R', 'B'], dtype='<U1')
>>> board = numpy.resize(board, (n, n))
>>> board
array([['R', 'B', 'R', 'R'],
       ['B', 'R', 'R', 'B'],
       ['R', 'R', 'B', 'B'],
       ['B', 'B', 'R', 'B']], dtype='<U1')


答:
It is possible to use regex:</p>

```<code>import re

inp = [
    'abducts'
,   'abe'
,   'abeam'
,   'abel'
,   'abele'
]

# detect word which contains a character at least twice
rgx = re.compile(r'.*(.).*\1.*')

def filter_words(inp):
    for word in inp:
        if rgx.match(word) is None:
            yield word

print list(filter_words(inp))
</code>```

Title: Only extract those words from a list that include no repeating letters, using regex

Body:
It is possible to use regex:

import re

inp = [
    'abducts'
,   'abe'
,   'abeam'
,   'abel'
,   'abele'
]

# detect word which contains a character at least twice
rgx = re.compile(r'.*(.).*\1.*')

def filter_words(inp):
    for word in inp:
        if rgx.match(word) is None:
            yield word

print list(filter_words(inp))