问:
Update new color in Spectrum JS Colorpicker Palette
I'm useing spectrum jQuery colorpicker and changing the background-color working properly but there's just one problem. after refreshing the page,the color of the chooser button gets black instead of selected color (for example, red)
background color of the page changed without any problem and everything worked properly except that. Look at this(click to see images):

Selected Color ->  after refreshing the page

This is my code:

HTML:

```<code><input id="colorpicker" style="display: none;">
</code>```

JS:

```<code>var currColor = $.cookie('body_color') || 'rgba(0, 0, 0, 0.5)';
 $('body').css('background-color', currColor);
 $("#colorpicker").spectrum({
    preferredFormat: 'rgb',
     showInput: true,
     showAlpha: true,
     color: currColor.substring(1),
     move: function(color) {
         $('body').css('background-color', color.toRgbString());
         $.cookie('body_color', color.toRgbString(), {
             expires: 365
         });
     }
 });
</code>```

how can I fix this?

If I change color.toRgbString() to color.toHexString() this issue get fixed but another issue occurs (after that I cant use rgba colors for page's background and transparency not work):

```<code>var currColor = $.cookie('body_color') || 'rgba(0, 0, 0, 0.5)';
     $('body').css('background-color', currColor);
     $("#colorpicker").spectrum({
        preferredFormat: 'rgb',
         showInput: true,
         showAlpha: true,
         color: currColor.substring(1),
         move: function(color) {
             $('body').css('background-color', color.toHexString());
             $.cookie('body_color', color.toHexString(), {
                 expires: 365
             });
         }
     });
</code>```

答:
I have an idea, but you should edit the spectrum.js file.
This function function inputToRGB(color) forced rgba color of color chooser buttons to set to the rgb(0, 0, 0) (when you choose rgba color, after refreshing the page, the colorpicker button's color forced to set to that but there is no problem with hex).

to fix this:

Find this code in spectrum.js:

```<code>function inputToRGB(color) {

    var rgb = { r: 0, g: 0, b: 0 };
    var a = 1;
</code>```

then change above codes to:

```<code>    function inputToRGB(color) {

   var colorString = color.toString(),
       colorsOnly = colorString.substring(colorString.indexOf('(') + 1, colorString.lastIndexOf(')')).split(/,\s*/),
       red = colorsOnly[0],
       green = colorsOnly[1],
       blue = colorsOnly[2],
       opacity = colorsOnly[3];

    var rgb = { r: red, g: green, b: blue };
    var a = opacity;
</code>```

Use above regex to get color values from browser cookie then extract color values of 4 sections of rgba color codes, then use those in 'rgb' & 'a' variables!
you can use both of color.toString() or color.toRgbString().

Body:
I'm useing spectrum jQuery colorpicker and changing the background-color working properly but there's just one problem. after refreshing the page,the color of the chooser button gets black instead of selected color (for example, red)
background color of the page changed without any problem and everything worked properly except that. Look at this(click to see images):

Selected Color ->  after refreshing the page

This is my code:

HTML:

<input id="colorpicker" style="display: none;">

JS:

var currColor = $.cookie('body_color') || 'rgba(0, 0, 0, 0.5)';
 $('body').css('background-color', currColor);
 $("#colorpicker").spectrum({
    preferredFormat: 'rgb',
     showInput: true,
     showAlpha: true,
     color: currColor.substring(1),
     move: function(color) {
         $('body').css('background-color', color.toRgbString());
         $.cookie('body_color', color.toRgbString(), {
             expires: 365
         });
     }
 });

how can I fix this?

If I change color.toRgbString() to color.toHexString() this issue get fixed but another issue occurs (after that I cant use rgba colors for page's background and transparency not work):

var currColor = $.cookie('body_color') || 'rgba(0, 0, 0, 0.5)';
     $('body').css('background-color', currColor);
     $("#colorpicker").spectrum({
        preferredFormat: 'rgb',
         showInput: true,
         showAlpha: true,
         color: currColor.substring(1),
         move: function(color) {
             $('body').css('background-color', color.toHexString());
             $.cookie('body_color', color.toHexString(), {
                 expires: 365
             });
         }
     });

Body:
I have an idea, but you should edit the spectrum.js file.
This function function inputToRGB(color) forced rgba color of color chooser buttons to set to the rgb(0, 0, 0) (when you choose rgba color, after refreshing the page, the colorpicker button's color forced to set to that but there is no problem with hex).

to fix this:

Find this code in spectrum.js:

function inputToRGB(color) {

    var rgb = { r: 0, g: 0, b: 0 };
    var a = 1;

then change above codes to:

    function inputToRGB(color) {

   var colorString = color.toString(),
       colorsOnly = colorString.substring(colorString.indexOf('(') + 1, colorString.lastIndexOf(')')).split(/,\s*/),
       red = colorsOnly[0],
       green = colorsOnly[1],
       blue = colorsOnly[2],
       opacity = colorsOnly[3];

    var rgb = { r: red, g: green, b: blue };
    var a = opacity;

Use above regex to get color values from browser cookie then extract color values of 4 sections of rgba color codes, then use those in 'rgb' & 'a' variables!
you can use both of color.toString() or color.toRgbString().


来源: stackexchange

问:
Takes to many RAM when start Android Studio and only one emulator
Windows 7 (64 bit), RAM = 8 GB, Processor: Intel(R) Core(TM), 3.10 GHz.
Android Studio 2.3.

My machine before start Android Studio:

My machine after start Android Studio AND only one emulator(RAM 512 MB):

It's take 7 GB. As result work very difficult.

Any advice, how fix this problem?
Thanks.

答:
I realize that you're not working with Xamarin.

However, I would like to share the following:

I Recommend at least 16 gigs of RAM when doing mobile development with Xamarin.
I had the same issue with my previous machine that was 12 gigs of RAM.

In my case I was doing Xamarin development which consumes a huge amount of resources. In addition, I also upgraded to SSD.

ContentLicense: CC BY-SA 3.0


问:
How to make a progress-bar in copy or query?
How can I make a progress-bar in copy or SQL query or file transfer (rapi)?

Or some thing's that I can't measure?

Thanks for any help.

答:
Well... really since you can't measure you just have to guess. You ever installed windows and the progress bar is very slow to move but then all of a sudden it jumps a great deal?

A couple ideas. If you have only one SQL query then you could slowly move the progress bar over time (like 0.5% per second?). Then if the the query hasn't finished by the time it hits 90% stop it. Then don't let it finish until it is done. If it finishes early (while the slow climb is going on) just jump to 100%.

Another idea is to run the query many times over to figure out an average time. Use this to do the same thing I mentioned in the last paragraph, but with the average time you can probably make the increments match better with the real progress.

Good luck!

OwnerDisplayName: Gold

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Federico Ramponi

OwnerDisplayName: Rob Ottaway


问:
Insert a string at a specific index
How can I insert a string at a specific index of another string?

```<code> var txt1 = "foo baz"
</code>```

Suppose I want to insert "bar " after the "foo" how can I achieve that?

I thought of substring(), but there must be a simpler more straight forward way.

答:
You could prototype your own splice() into String.

Polyfill

```<code>if (!String.prototype.splice) {
    /**
     * {JSDoc}
     *
     * The splice() method changes the content of a string by removing a range of
     * characters and/or adding new characters.
     *
     * @this {String}
     * @param {number} start Index at which to start changing the string.
     * @param {number} delCount An integer indicating the number of old chars to remove.
     * @param {string} newSubStr The String that is spliced in.
     * @return {string} A new string with the spliced substring.
     */
    String.prototype.splice = function(start, delCount, newSubStr) {
        return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
    };
}
</code>```

Example

String.prototype.splice = function(idx, rem, str) {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};

var result = "foo baz".splice(4, 0, "bar ");

document.body.innerHTML = result; // "foo bar baz"```

EDIT: Modified it to ensure that rem is an absolute value.

ContentLicense: CC BY-SA 4.0

Title: Insert a string at a specific index

Body:
How can I insert a string at a specific index of another string?

 var txt1 = "foo baz"

Suppose I want to insert "bar " after the "foo" how can I achieve that?

I thought of substring(), but there must be a simpler more straight forward way.

Body:
You could prototype your own splice() into String.

Polyfill

if (!String.prototype.splice) {
    /**
     * {JSDoc}
     *
     * The splice() method changes the content of a string by removing a range of
     * characters and/or adding new characters.
     *
     * @this {String}
     * @param {number} start Index at which to start changing the string.
     * @param {number} delCount An integer indicating the number of old chars to remove.
     * @param {string} newSubStr The String that is spliced in.
     * @return {string} A new string with the spliced substring.
     */
    String.prototype.splice = function(start, delCount, newSubStr) {
        return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
    };
}

Example

String.prototype.splice = function(idx, rem, str) {
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));
};

var result = "foo baz".splice(4, 0, "bar ");

document.body.innerHTML = result; // "foo bar baz"

EDIT: Modified it to ensure that rem is an absolute value.


问:
Recurring message Masstransit rabbitmq
I am trying to implement a heartbeat feature for my application hence was trying to implement recurring message feature from masstransit rabbitmq. I was trying to implement it on the sample given on masstransit's website. Here's all of the code.

```<code>namespace MasstransitBasicSample
{
    using System;
    using System.Threading.Tasks;
    using MassTransit;
    using MassTransit.Scheduling;

    class Program
    {
        static void Main(string[] args)
        {
            var bus = Bus.Factory.CreateUsingRabbitMq(sbc =>
            {
                var host = sbc.Host(new Uri("rabbitmq://localhost"), h =>
                {
                    h.Username("guest");
                    h.Password("guest");
                });

                sbc.UseMessageScheduler(new Uri("rabbitmq://localhost/quartz"));

                sbc.ReceiveEndpoint(host, "test_queue", ep =>
                {
                    ep.Handler<YourMessage>(context =>
                    {
                        return Console.Out.WriteLineAsync($"Received: {context.Message.Text}");
                    });
                    ep.Handler<PollExternalSystem>(context =>
                    {
                        return Console.Out.WriteLineAsync($"Received: {context.Message}");
                    });
                });
            });

            bus.Start();
            SetRecurring(bus);

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();

            bus.Stop();
        }

        private static async Task SetRecurring(IBusControl bus)
        {
            var schedulerEndpoint = await bus.GetSendEndpoint(new Uri("rabbitmq://localhost/quartz"));

            var scheduledRecurringMessage = await schedulerEndpoint.ScheduleRecurringSend(
               new Uri("rabbitmq://localhost/test_queue"), new PollExternalSystemSchedule(), new PollExternalSystem());
        }
    }

    public class YourMessage { public string Text { get; set; } }

    public class PollExternalSystemSchedule : DefaultRecurringSchedule
    {
        public PollExternalSystemSchedule()
        {
            CronExpression = "* * * * *"; // this means every minute
        }
    }

    public class PollExternalSystem { }
}
</code>```

I have created a queue called quartz in my rabbitmq queue.

When i run the application it sends a message to the quartz queue and that message just stays there , it does not go to the test queue.

I was also expecting another message to be sent to the quartz queue after a minute based on the cron expression, that also does not happen.

Is my setup wrong?

Any help would be much appreciated.

答:
You need to run the scheduling service that listens on rabbitmq://localhost/quartz, where your messages are being sent.

The documentation page says:

There is a standalone MassTransit service, MassTransit.QuartzService,
  which can be installed and used on servers for this purpose. It is
  configured via the App.config file and is a good example of how to
  build a standalone MassTransit service.

Alternatively, you can host Quartz scheduling in the same process by using in-memory scheduling, described here, by configuring it like this:

```<code>var busControl = Bus.Factory.CreateUsingRabbitMq(cfg =>
{
    var host = cfg.Host(new Uri("rabbitmq://localhost/"), h =>
    {
        h.Username("guest");
        h.Password("guest");
    });

    cfg.UseInMemoryScheduler();
});
</code>```

Title: Recurring message Masstransit rabbitmq

Body:
I am trying to implement a heartbeat feature for my application hence was trying to implement recurring message feature from masstransit rabbitmq. I was trying to implement it on the sample given on masstransit's website. Here's all of the code.

namespace MasstransitBasicSample
{
    using System;
    using System.Threading.Tasks;
    using MassTransit;
    using MassTransit.Scheduling;

    class Program
    {
        static void Main(string[] args)
        {
            var bus = Bus.Factory.CreateUsingRabbitMq(sbc =>
            {
                var host = sbc.Host(new Uri("rabbitmq://localhost"), h =>
                {
                    h.Username("guest");
                    h.Password("guest");
                });

                sbc.UseMessageScheduler(new Uri("rabbitmq://localhost/quartz"));

                sbc.ReceiveEndpoint(host, "test_queue", ep =>
                {
                    ep.Handler<YourMessage>(context =>
                    {
                        return Console.Out.WriteLineAsync($"Received: {context.Message.Text}");
                    });
                    ep.Handler<PollExternalSystem>(context =>
                    {
                        return Console.Out.WriteLineAsync($"Received: {context.Message}");
                    });
                });
            });

            bus.Start();
            SetRecurring(bus);

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();

            bus.Stop();
        }

        private static async Task SetRecurring(IBusControl bus)
        {
            var schedulerEndpoint = await bus.GetSendEndpoint(new Uri("rabbitmq://localhost/quartz"));

            var scheduledRecurringMessage = await schedulerEndpoint.ScheduleRecurringSend(
               new Uri("rabbitmq://localhost/test_queue"), new PollExternalSystemSchedule(), new PollExternalSystem());
        }
    }

    public class YourMessage { public string Text { get; set; } }

    public class PollExternalSystemSchedule : DefaultRecurringSchedule
    {
        public PollExternalSystemSchedule()
        {
            CronExpression = "* * * * *"; // this means every minute
        }
    }

    public class PollExternalSystem { }
}

I have created a queue called quartz in my rabbitmq queue.

When i run the application it sends a message to the quartz queue and that message just stays there , it does not go to the test queue.

I was also expecting another message to be sent to the quartz queue after a minute based on the cron expression, that also does not happen.

Is my setup wrong?

Any help would be much appreciated.

Body:
You need to run the scheduling service that listens on rabbitmq://localhost/quartz, where your messages are being sent.

The documentation page says:

There is a standalone MassTransit service, MassTransit.QuartzService,
  which can be installed and used on servers for this purpose. It is
  configured via the App.config file and is a good example of how to
  build a standalone MassTransit service.

Alternatively, you can host Quartz scheduling in the same process by using in-memory scheduling, described here, by configuring it like this:

var busControl = Bus.Factory.CreateUsingRabbitMq(cfg =>
{
    var host = cfg.Host(new Uri("rabbitmq://localhost/"), h =>
    {
        h.Username("guest");
        h.Password("guest");
    });

    cfg.UseInMemoryScheduler();
});


问:
Creating image pull secret for google container registry that doesn't expire?
I'm trying to get Kubernetes to download images from a Google Container Registry from another project. According to the docs you should create an image pull secret using:

```<code>$ kubectl create secret docker-registry myregistrykey --docker-server=DOCKER_REGISTRY_SERVER --docker-username=DOCKER_USER --docker-password=DOCKER_PASSWORD --docker-email=DOCKER_EMAIL
</code>```

But I wonder what DOCKER_USER and DOCKER_PASSWORD I should use for authenticating with Google Container Registry? Looking at the GCR docs it says that the password is the access token that you can get by running:

```<code>$ gcloud auth print-access-token
</code>```

This actually works... for a while. The problem seems to be that this access token expires after (what I believe to be) one hour. I need a password (or something) that doesn't expire when creating my image pull secret. Otherwise the Kubernetes cluster can't download the new images after an hour or so. What's the correct way to do this?

答:
From the official ways, you can:

```<code>$ docker login -e 1234@5678.com -u _json_key -p "$JSON_KEY" https://gcr.io
</code>```

Note: The e-mail is not used, so you can put whatever you want in it.

Change gcr.io to whatever is your domain shown in your Google Container Registry (e.g. eu.gcr.io).

To get that $JSON_KEY:

Go to API Manager > Credentials

Click "Create credentials" > Service account key:

Service account: New service account

Name: Anything you want, like Docker Registry (read-only)

Role: Storage (scroll down) > Storage Object Viewer

Key type: JSON

Download as keyfile.json

JSON_KEY=$(cat keyfile.json | tr '\n' ' ')

Now you can use it.

Once logged in you can just run docker pull. You can also copy the updated ~/.dockercfg to preserve the settings.

Body:
I'm trying to get Kubernetes to download images from a Google Container Registry from another project. According to the docs you should create an image pull secret using:

$ kubectl create secret docker-registry myregistrykey --docker-server=DOCKER_REGISTRY_SERVER --docker-username=DOCKER_USER --docker-password=DOCKER_PASSWORD --docker-email=DOCKER_EMAIL

But I wonder what DOCKER_USER and DOCKER_PASSWORD I should use for authenticating with Google Container Registry? Looking at the GCR docs it says that the password is the access token that you can get by running:

$ gcloud auth print-access-token

This actually works... for a while. The problem seems to be that this access token expires after (what I believe to be) one hour. I need a password (or something) that doesn't expire when creating my image pull secret. Otherwise the Kubernetes cluster can't download the new images after an hour or so. What's the correct way to do this?

Body:
From the official ways, you can:

$ docker login -e 1234@5678.com -u _json_key -p "$JSON_KEY" https://gcr.io

Note: The e-mail is not used, so you can put whatever you want in it.

Change gcr.io to whatever is your domain shown in your Google Container Registry (e.g. eu.gcr.io).

To get that $JSON_KEY:

Go to API Manager > Credentials

Click "Create credentials" > Service account key:

Service account: New service account

Name: Anything you want, like Docker Registry (read-only)

Role: Storage (scroll down) > Storage Object Viewer

Key type: JSON

Download as keyfile.json

JSON_KEY=$(cat keyfile.json | tr '\n' ' ')

Now you can use it.

Once logged in you can just run docker pull. You can also copy the updated ~/.dockercfg to preserve the settings.


问:
Wildcard query on Firebase?
Is it possible to do wildcard queries on Firebase? For example:</p>

```<code>https://foo.firebaseio.com/person.json?orderBy="name"&equalTo="Lun*"
</code>```

答:
I know it's been a while but I thought that others might be interested. You can "fake" a wildcard search for things like foo* (so basically you can search for values beginning with a specified string).

For iOS & Swift it would look like this:

```<code>dbReference.child("person").queryOrdered(byChild: "name").queryStarting(atValue: "foo").queryEnding(atValue: "foo\u{f8ff}").observe(.childAdded) { (snapshot: FIRDataSnapshot) in
    print("\(snapshot.key) - \(String(describing: snapshot.value))")
}
</code>```

What this does is using a start and end values for name property where the end key is equal to the start + a very high code point in the Unicode range. Because it is after most regular characters in Unicode, the query matches all values that start with foo.

Title: Wildcard query on Firebase?

Body:
Is it possible to do wildcard queries on Firebase? For example:

https://foo.firebaseio.com/person.json?orderBy="name"&equalTo="Lun*"

Body:
I know it's been a while but I thought that others might be interested. You can "fake" a wildcard search for things like foo* (so basically you can search for values beginning with a specified string).

For iOS & Swift it would look like this:

dbReference.child("person").queryOrdered(byChild: "name").queryStarting(atValue: "foo").queryEnding(atValue: "foo\u{f8ff}").observe(.childAdded) { (snapshot: FIRDataSnapshot) in
    print("\(snapshot.key) - \(String(describing: snapshot.value))")
}

What this does is using a start and end values for name property where the end key is equal to the start + a very high code point in the Unicode range. Because it is after most regular characters in Unicode, the query matches all values that start with foo.


问:
Android, how to get the list of the apps that open a URL without using createChooser
To find all the apps that open a URL I would do like this:

```<code>    Uri uri = Uri.parse(URL);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    Intent intentChooser = Intent.createChooser(intent,"Choose navigator");
    activity.startActivity(intentChooser);
</code>```

The problem is that I don't want to user the Chooser control, because of some developing specifications.

The question is how can I get the list of apps that open URL (that's what I get with the code above) to pass them to an ArrayAdapter / Spinner.

Body:
To find all the apps that open a URL I would do like this:

    Uri uri = Uri.parse(URL);
    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
    Intent intentChooser = Intent.createChooser(intent,"Choose navigator");
    activity.startActivity(intentChooser);

The problem is that I don't want to user the Chooser control, because of some developing specifications.

The question is how can I get the list of apps that open URL (that's what I get with the code above) to pass them to an ArrayAdapter / Spinner.

Body: Try asking PackageManager (http://developer.android.com/reference/android/content/pm/PackageManager.html#queryBroadcastReceivers%28android.content.Intent,%20int%29)


问:
Finding the VBIDE.Reference.Name of object libraries vba
I've found how to add a reference programmatically with VBA,

This explains how to add object references programmatically using the name of the Library,

with the example "VBScript_RefExp_55".

My question is how do I find this reference name to use in this code for different object libraries?

Such as the PowerPoint Library for example?

答:
I use this to get the info on my references :

```<code>Private Sub ListProjectReferencesList()
    Dim i                   As Long
    Dim VBProj              As Object  'VBIDE.VBProject
    Dim VBComp              As Object 'VBIDE.VBComponent
    Set VBProj = Application.VBE.ActiveVBProject
    Dim strTmp              As String
    On Error Resume Next
    For i = 1 To VBProj.References.Count
        With VBProj.References.Item(i)
            Debug.Print "Description: " & .Description & vbNewLine & _
                        "FullPath: " & .FullPath & vbNewLine & _
                        "Major.Minor: " & .Major & "." & .Minor & vbNewLine & _
                        "Name: " & .Name & vbNewLine & _
                        "GUID: " & .GUID & vbNewLine & _
                        "Type: " & .Type
            Debug.Print "-------------------"
        End With 'VBProj.References.Item(i)
    Next i
End Sub
</code>```

And generally, I prefer to add it with GUID rather than name.

But as pointed out by @Rory,

you should use Late Binding rather than adding References programmatically!

Why?

Because in order to add them programmatically, your users will have to go into :

Options of the Application (Excel, ...) from which it's launched

Trust Center

Trust Center Settings

Macro Settings tab

Tick Trust access to the VBA project object model check box

OK

OK

So you'd better finish your code with references, then :

Remove the references

Change all declarations using those librairies to Dim ??? As Object

Check if you have Option Explicit at the top of the module (add it if not)

Look for app-specific variables (Option Explicit should throw an message on them)

Test your code a lot

Export module to be used by others!

Body:
I use this to get the info on my references :

Private Sub ListProjectReferencesList()
    Dim i                   As Long
    Dim VBProj              As Object  'VBIDE.VBProject
    Dim VBComp              As Object 'VBIDE.VBComponent
    Set VBProj = Application.VBE.ActiveVBProject
    Dim strTmp              As String
    On Error Resume Next
    For i = 1 To VBProj.References.Count
        With VBProj.References.Item(i)
            Debug.Print "Description: " & .Description & vbNewLine & _
                        "FullPath: " & .FullPath & vbNewLine & _
                        "Major.Minor: " & .Major & "." & .Minor & vbNewLine & _
                        "Name: " & .Name & vbNewLine & _
                        "GUID: " & .GUID & vbNewLine & _
                        "Type: " & .Type
            Debug.Print "-------------------"
        End With 'VBProj.References.Item(i)
    Next i
End Sub

And generally, I prefer to add it with GUID rather than name.

But as pointed out by @Rory,

you should use Late Binding rather than adding References programmatically!

Why?

Because in order to add them programmatically, your users will have to go into :

Options of the Application (Excel, ...) from which it's launched

Trust Center

Trust Center Settings

Macro Settings tab

Tick Trust access to the VBA project object model check box

OK

OK

So you'd better finish your code with references, then :

Remove the references

Change all declarations using those librairies to Dim ??? As Object

Check if you have Option Explicit at the top of the module (add it if not)

Look for app-specific variables (Option Explicit should throw an message on them)

Test your code a lot

Export module to be used by others!


问:
TouchableNativeFeedbackSafe.SelectableBackgroundBorderless is not a function
I am trying to use @exponent/react-native-touchable-native-feedback-safe in my react-native based app. I can't seem to set background prop without upsetting either ios or android.
I did:

```<code><TouchableNativeFeedbackSafe onPress={this.props.onPress}
    background={TouchableNativeFeedbackSafe.SelectableBackgroundBorderless()}>
</code>```

this works on android but gives error on iOS: SelectableBackgroundBorderless is not a function.

If I change it from TouchableNativeFeedbackSafe.SelectableBackgroundBorderless() to TouchableNativeFeedbackSafe.SelectableBackgroundBorderless then iOS works but android throws error:

```<code>Error while updating property 'nativeBackgroundAndroid' of a view managed by: RCTView
updateViewProp
    ViewManagersPropertyCache.java:89
setProperty
    ViewManagerPropertyUpdater.java:123
updateProps
    ViewManagerPropertyUpdater.java:42
updateProperties
    ViewManager.java:36
createView
    NativeViewHierarchyManager.java:227
execute
   UIViewOperationQueue.java:148
dispatchPendingNonBatchedOperations
   UIViewOperationQueue.java:890
doFrameGuarded
   UIViewOperationQueue.java:863
doFrame
   GuardedChoreographerFrameCallback.java:32
doFrame
   ReactChoreographer.java:131
run
   Choreographer.java:872
...
</code>```

答:
The reason is a typo in the expo package. Someone forked it and corrected it already: https://github.com/netbeast/react-native-touchable-native-feedback-safe
However, I don't think they sent a pull request because the original code isn't publicly available anywhere.

EDIT:

```<code>TouchableNativeFeedbackSafe.SelectableBackgroundBorderless()
</code>```

is the correct way to go with the package mentioned above.

Body:
I am trying to use @exponent/react-native-touchable-native-feedback-safe in my react-native based app. I can't seem to set background prop without upsetting either ios or android.
I did:

<TouchableNativeFeedbackSafe onPress={this.props.onPress}
    background={TouchableNativeFeedbackSafe.SelectableBackgroundBorderless()}>

this works on android but gives error on iOS: SelectableBackgroundBorderless is not a function.

If I change it from TouchableNativeFeedbackSafe.SelectableBackgroundBorderless() to TouchableNativeFeedbackSafe.SelectableBackgroundBorderless then iOS works but android throws error:

Error while updating property 'nativeBackgroundAndroid' of a view managed by: RCTView
updateViewProp
    ViewManagersPropertyCache.java:89
setProperty
    ViewManagerPropertyUpdater.java:123
updateProps
    ViewManagerPropertyUpdater.java:42
updateProperties
    ViewManager.java:36
createView
    NativeViewHierarchyManager.java:227
execute
   UIViewOperationQueue.java:148
dispatchPendingNonBatchedOperations
   UIViewOperationQueue.java:890
doFrameGuarded
   UIViewOperationQueue.java:863
doFrame
   GuardedChoreographerFrameCallback.java:32
doFrame
   ReactChoreographer.java:131
run
   Choreographer.java:872
...

Body:
The reason is a typo in the expo package. Someone forked it and corrected it already: https://github.com/netbeast/react-native-touchable-native-feedback-safe
However, I don't think they sent a pull request because the original code isn't publicly available anywhere.

EDIT:

TouchableNativeFeedbackSafe.SelectableBackgroundBorderless()

is the correct way to go with the package mentioned above.


问:
Auto implement Unique ID in a hashable class
I create a new class that I want to be Hashable and Equatable so I can easily loop through it, a class example is below:

```<code>class MyClass: Hashable {
    var uid: Int
    var myName: String
    var myAge:Int
    var hashValue: Int {
        return self.uid
    }
    init(uid: Int, name: String, age: Int) {
        self.uid = uid
        self.myName = name
        self.myAge = age
    }
}

func ==(lhs: MyClass, rhs: MyClass) -> Bool {
    return lhs.uid == rhs.uid
}
</code>```

The problem is that now I have to pass a uid when I create the class, like so:

```<code>let user1 = MyUser(uid: 1, name: "Me", age: 36)
</code>```

I want to make the uid static and auto generate a new one for each object I create, like so:

```<code>let user2 = User(name: "The other guy", age: 23)
</code>```

In this case the uid for user2 would be equals 2, it is just a set property it does not need to have a get as it should work completely transparent to the person using the class.

However everytime I try to change uid to be a static var or a class var I cannot make it conform with Hashable protocol

Thanks in advance

答:
The solution marked as right is good and right to the point. My only concern is that nextUid is a var that any other method in the class can update. If you want more secure (and even reusable) solution, you can do something like this:

```<code>class HashableIdGenerator {

    private var nextId = 0

    func generate() -> Int {
        nextId += 1
        return nextId
    }
}

class AClass: Hashable {

    private static let idGenerator = HashableIdGenerator()

    let uid: Int

    init() {
        uid = AClass.idGenerator.generate()
    }

    var hashValue: Int { return uid }

    // implement Equatable here
}
</code>```

Body:
I create a new class that I want to be Hashable and Equatable so I can easily loop through it, a class example is below:

class MyClass: Hashable {
    var uid: Int
    var myName: String
    var myAge:Int
    var hashValue: Int {
        return self.uid
    }
    init(uid: Int, name: String, age: Int) {
        self.uid = uid
        self.myName = name
        self.myAge = age
    }
}

func ==(lhs: MyClass, rhs: MyClass) -> Bool {
    return lhs.uid == rhs.uid
}

The problem is that now I have to pass a uid when I create the class, like so:

let user1 = MyUser(uid: 1, name: "Me", age: 36)

I want to make the uid static and auto generate a new one for each object I create, like so:

let user2 = User(name: "The other guy", age: 23)

In this case the uid for user2 would be equals 2, it is just a set property it does not need to have a get as it should work completely transparent to the person using the class.

However everytime I try to change uid to be a static var or a class var I cannot make it conform with Hashable protocol

Thanks in advance

Body:
The solution marked as right is good and right to the point. My only concern is that nextUid is a var that any other method in the class can update. If you want more secure (and even reusable) solution, you can do something like this:

class HashableIdGenerator {

    private var nextId = 0

    func generate() -> Int {
        nextId += 1
        return nextId
    }
}

class AClass: Hashable {

    private static let idGenerator = HashableIdGenerator()

    let uid: Int

    init() {
        uid = AClass.idGenerator.generate()
    }

    var hashValue: Int { return uid }

    // implement Equatable here
}


问:
how to transfer data from fragment(contains recyclerview) to dialog fragment which is show selected items on dialog fragment
how to transfer data from fragment(contains recyclerview) to dialog fragment which is show selected items on dialog fragment , in my case i am getting error .

this is RecyclerViewCollegeNewsLetter.java ,

```<code>public class RecyclerViewCollegeNewsLetter extends RecyclerView.Adapter<RecyclerViewCollegeNewsLetter.MyCollege> {

static List<Topics> topicses = new ArrayList<>();
Context context;
Topics topics;

public RecyclerViewCollegeNewsLetter(Context context, ArrayList<Topics> topicses) {
    this.context = context;
    this.topicses = topicses;
}

@Override
public RecyclerViewCollegeNewsLetter.MyCollege onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_row, parent, false);
    Log.d("ssss", "in oncreate");

    return new MyCollege(view);
}

@Override
public void onBindViewHolder(final RecyclerViewCollegeNewsLetter.MyCollege holder, final int position) {
    topics = topicses.get(position);
    holder.id.setText(topics.getId());
    holder.givenby.setText(topics.getGivenby());
    holder.article.setText(topics.getArticle());

    holder.more.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            FilterDialogFragment filterDialogFragment = new FilterDialogFragment();
            int pos=holder.getAdapterPosition();
            Bundle bundle = new Bundle();
            bundle.putString("more_id",topicses.get(pos).getId() );
            Log.e("rrrr",topicses.get(pos).getId());
            bundle.putString("more_given_by",topicses.get(pos).getGivenby());
            bundle.putString("more_article", topicses.get(pos).getArticle());
            bundle.putString("more_content", topicses.get(pos).getContent());

            //pasing data to filterDialogFragment
            filterDialogFragment.setArguments(bundle);

            showDialog();
        }
    });
    // holder.content.setText(topics.getContent());

    if (topics.getContent().length() > 100) {
        holder.content.setText((topics.getContent().substring(0, 99)) + "...");
    } else
        holder.content.setText(topics.getContent());

}

@Override
public int getItemCount() {
    return topicses.size();
}

public class MyCollege extends RecyclerView.ViewHolder {
    TextView id, content, article, givenby;
    Button more;

    public MyCollege(View itemView) {
        super(itemView);
        id = (TextView) itemView.findViewById(R.id.id);
        givenby = (TextView) itemView.findViewById(R.id.givenby);
        article = (TextView) itemView.findViewById(R.id.article);
        content = (TextView) itemView.findViewById(R.id.content);
        more = (Button) itemView.findViewById(R.id.more);

    }

}
void showDialog() {
    FilterDialogFragment filterDialogFragment = new FilterDialogFragment();
   // MoreDetails moreDetails = new MoreDetails();
    FragmentManager ft = ((MainActivity) context).getSupportFragmentManager();
    DialogFragment newFragment = filterDialogFragment.newInstance();
    newFragment.show(ft, "dialog");
 }
</code>```

this is FilterDialogFragment.java

```<code> public class FilterDialogFragment extends DialogFragment {

private AdView mAdView;
Bundle mArgs;
TextView more_id, more_content, more_article, more_givenby;

static FilterDialogFragment newInstance() {
    FilterDialogFragment f = new FilterDialogFragment();
    return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.more_details, container, false);
    mAdView = (AdView) v.findViewById(R.id.adView);
    more_id = (TextView) v.findViewById(R.id.more_id);
    more_content = (TextView) v.findViewById(R.id.more_content);
    more_article = (TextView) v.findViewById(R.id.more_article);
    more_givenby = (TextView) v.findViewById(R.id.more_givenby);

    return v;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    AdRequest adRequest = new AdRequest.Builder()
            .build();
    mAdView.loadAd(adRequest);

    Bundle mArgs = getArguments();
    more_id.setText(mArgs.getString("more_id"));
}

@Override
public void onPause() {
    if (mAdView != null) {
        mAdView.pause();
    }
    super.onPause();
}

@Override
public void onResume() {
    super.onResume();
    if (mAdView != null) {
        mAdView.resume();
    }
}

@Override
public void onDestroy() {
    if (mAdView != null) {
        mAdView.destroy();
    }
    super.onDestroy();
}

@Override
public void onStart() {
    super.onStart();
    Dialog dialog = getDialog();
    if (dialog != null) {
        int width = ViewGroup.LayoutParams.MATCH_PARENT;
        int height = ViewGroup.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setLayout(width, height);
    }
}
</code>```

i put Bundle mArgs = getArguments();

more_id.setText(mArgs.getString("more_id"));

in onActivityCreated but gives me error:-

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                                                                                at com.example.kulde.itechvcet.FilterDialogFragment.onViewCreated(FilterDialogFragment.java:52)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1314)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
                                                                                at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
                                                                                at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
                                                                                at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
                                                                                at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:152)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5497)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
</code>```

Help me Pro Devs !

答:
You are seting bundle values for FilterDialogFragment but you are not using it as you are creating a new instance of FilterDialogFragment inside your showDialog() method

```<code>   FilterDialogFragment filterDialogFragment = new FilterDialogFragment();
    int pos=holder.getAdapterPosition();
    Bundle bundle = new Bundle();
    bundle.putString("more_id",topicses.get(pos).getId() );
    Log.e("rrrr",topicses.get(pos).getId());
                bundle.putString("more_given_by",topicses.get(pos).getGivenby());
    bundle.putString("more_article", topicses.get(pos).getArticle());
    bundle.putString("more_content", topicses.get(pos).getContent());

    //pasing data to filterDialogFragment
    filterDialogFragment.setArguments(bundle);

    showDialog(filterDialogFragment);
</code>```

Pass FilterDialogFragment variable

```<code>void showDialog(FilterDialogFragment ff) {
   // MoreDetails moreDetails = new MoreDetails();
    FragmentManager ft = ((MainActivity) context).getSupportFragmentManager();
    DialogFragment newFragment = ff.newInstance();
    newFragment.show(ft, "dialog");
 }
</code>```

You are not passing any value to your DialogFragment and trying to retrieve value for more_id key which is not present actually.

```<code>Bundle mArgs = getArguments();
more_id.setText(mArgs.getString("more_id"));
</code>```

Change your implementation as below

```<code>static FilterDialogFragment newInstance(String moreId) {
    FilterDialogFragment f = new FilterDialogFragment();
    Bundle bundle = new Bundle();
    bundle.putSTring("more_id", moreId);
    f.setArguments(bundle);
    return f;
}
</code>```

and accordingly change your code while calling the DialogFragment

Body:
how to transfer data from fragment(contains recyclerview) to dialog fragment which is show selected items on dialog fragment , in my case i am getting error .

this is RecyclerViewCollegeNewsLetter.java ,

public class RecyclerViewCollegeNewsLetter extends RecyclerView.Adapter<RecyclerViewCollegeNewsLetter.MyCollege> {

static List<Topics> topicses = new ArrayList<>();
Context context;
Topics topics;

public RecyclerViewCollegeNewsLetter(Context context, ArrayList<Topics> topicses) {
    this.context = context;
    this.topicses = topicses;
}

@Override
public RecyclerViewCollegeNewsLetter.MyCollege onCreateViewHolder(ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_row, parent, false);
    Log.d("ssss", "in oncreate");

    return new MyCollege(view);
}

@Override
public void onBindViewHolder(final RecyclerViewCollegeNewsLetter.MyCollege holder, final int position) {
    topics = topicses.get(position);
    holder.id.setText(topics.getId());
    holder.givenby.setText(topics.getGivenby());
    holder.article.setText(topics.getArticle());

    holder.more.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            FilterDialogFragment filterDialogFragment = new FilterDialogFragment();
            int pos=holder.getAdapterPosition();
            Bundle bundle = new Bundle();
            bundle.putString("more_id",topicses.get(pos).getId() );
            Log.e("rrrr",topicses.get(pos).getId());
            bundle.putString("more_given_by",topicses.get(pos).getGivenby());
            bundle.putString("more_article", topicses.get(pos).getArticle());
            bundle.putString("more_content", topicses.get(pos).getContent());

            //pasing data to filterDialogFragment
            filterDialogFragment.setArguments(bundle);

            showDialog();
        }
    });
    // holder.content.setText(topics.getContent());

    if (topics.getContent().length() > 100) {
        holder.content.setText((topics.getContent().substring(0, 99)) + "...");
    } else
        holder.content.setText(topics.getContent());

}

@Override
public int getItemCount() {
    return topicses.size();
}

public class MyCollege extends RecyclerView.ViewHolder {
    TextView id, content, article, givenby;
    Button more;

    public MyCollege(View itemView) {
        super(itemView);
        id = (TextView) itemView.findViewById(R.id.id);
        givenby = (TextView) itemView.findViewById(R.id.givenby);
        article = (TextView) itemView.findViewById(R.id.article);
        content = (TextView) itemView.findViewById(R.id.content);
        more = (Button) itemView.findViewById(R.id.more);

    }

}
void showDialog() {
    FilterDialogFragment filterDialogFragment = new FilterDialogFragment();
   // MoreDetails moreDetails = new MoreDetails();
    FragmentManager ft = ((MainActivity) context).getSupportFragmentManager();
    DialogFragment newFragment = filterDialogFragment.newInstance();
    newFragment.show(ft, "dialog");
 }

this is FilterDialogFragment.java

 public class FilterDialogFragment extends DialogFragment {

private AdView mAdView;
Bundle mArgs;
TextView more_id, more_content, more_article, more_givenby;

static FilterDialogFragment newInstance() {
    FilterDialogFragment f = new FilterDialogFragment();
    return f;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.more_details, container, false);
    mAdView = (AdView) v.findViewById(R.id.adView);
    more_id = (TextView) v.findViewById(R.id.more_id);
    more_content = (TextView) v.findViewById(R.id.more_content);
    more_article = (TextView) v.findViewById(R.id.more_article);
    more_givenby = (TextView) v.findViewById(R.id.more_givenby);

    return v;
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    AdRequest adRequest = new AdRequest.Builder()
            .build();
    mAdView.loadAd(adRequest);

    Bundle mArgs = getArguments();
    more_id.setText(mArgs.getString("more_id"));
}

@Override
public void onPause() {
    if (mAdView != null) {
        mAdView.pause();
    }
    super.onPause();
}

@Override
public void onResume() {
    super.onResume();
    if (mAdView != null) {
        mAdView.resume();
    }
}

@Override
public void onDestroy() {
    if (mAdView != null) {
        mAdView.destroy();
    }
    super.onDestroy();
}

@Override
public void onStart() {
    super.onStart();
    Dialog dialog = getDialog();
    if (dialog != null) {
        int width = ViewGroup.LayoutParams.MATCH_PARENT;
        int height = ViewGroup.LayoutParams.MATCH_PARENT;
        dialog.getWindow().setLayout(width, height);
    }
}

i put Bundle mArgs = getArguments();

more_id.setText(mArgs.getString("more_id"));

in onActivityCreated but gives me error:-

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                                                                                at com.example.kulde.itechvcet.FilterDialogFragment.onViewCreated(FilterDialogFragment.java:52)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1314)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1528)
                                                                                at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1595)
                                                                                at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:758)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2363)
                                                                                at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2149)
                                                                                at android.support.v4.app.FragmentManagerImpl.optimizeAndExecuteOps(FragmentManager.java:2103)
                                                                                at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2013)
                                                                                at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:710)
                                                                                at android.os.Handler.handleCallback(Handler.java:739)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:152)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5497)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Help me Pro Devs !

Body:
You are seting bundle values for FilterDialogFragment but you are not using it as you are creating a new instance of FilterDialogFragment inside your showDialog() method

   FilterDialogFragment filterDialogFragment = new FilterDialogFragment();
    int pos=holder.getAdapterPosition();
    Bundle bundle = new Bundle();
    bundle.putString("more_id",topicses.get(pos).getId() );
    Log.e("rrrr",topicses.get(pos).getId());
                bundle.putString("more_given_by",topicses.get(pos).getGivenby());
    bundle.putString("more_article", topicses.get(pos).getArticle());
    bundle.putString("more_content", topicses.get(pos).getContent());

    //pasing data to filterDialogFragment
    filterDialogFragment.setArguments(bundle);

    showDialog(filterDialogFragment);

Pass FilterDialogFragment variable

void showDialog(FilterDialogFragment ff) {
   // MoreDetails moreDetails = new MoreDetails();
    FragmentManager ft = ((MainActivity) context).getSupportFragmentManager();
    DialogFragment newFragment = ff.newInstance();
    newFragment.show(ft, "dialog");
 }

You are not passing any value to your DialogFragment and trying to retrieve value for more_id key which is not present actually.

Bundle mArgs = getArguments();
more_id.setText(mArgs.getString("more_id"));

Change your implementation as below

static FilterDialogFragment newInstance(String moreId) {
    FilterDialogFragment f = new FilterDialogFragment();
    Bundle bundle = new Bundle();
    bundle.putSTring("more_id", moreId);
    f.setArguments(bundle);
    return f;
}

and accordingly change your code while calling the DialogFragment


问:
Why does NPM's policy of duplicated dependencies work?
By default, when I use NPM to manage a package depending on foo and bar, both of which depend on corelib, by default, NPM will install corelib twice (once for foo, and once for bar). They might even be different versions.

Now, let's suppose that corelib defined some data structure (e.g. a URL object) which is passed between foo, bar and the main application. Now, what I would expect, is if there was ever a backwards incompatible change to this object (e.g. one of the field names changed), and foo depended on corelib-1.0 and bar depended on corelib-2.0, I'd be a very sad panda: bar's version of corelib-2.0 might see a data structure created by the old version of corelib-1.0 and things would not work very well.

I was really surprised to discover that this situation basically never happens (I trawled Google, Stack Overflow, etc, looking for examples of people whose applications had stopped working, but who could have fixed it by running dedupe.) So my question is, why is this the case? Is it because node.js libraries never define data structures that are shared outside of the programmers? Is it because node.js developers never break backwards compatibility of their data structures? I'd really like to know!

答:
this situation basically never happens

Yes, my experience is indeed that that is not a problem in the Node/JS ecosystem. And I think it is, in part, thanks to the robustness principle.

Below is my view on why and how.

Primitives, the early days

I think the first and foremost reason is that the language provides a common basis for primitive types (Number, String, Bool, Null, Undefined) and some basic compound types (Object, Array, RegExp, etc...).

So if I receive a String from one of the libs' APIs I use, and pass it to another, it cannot go wrong because there is just a single String type.

This is what used to happen, and still happens to some extent to this day: Library authors try to rely on the built-ins as much as possible and only diverge when there is sufficient reason to, and with sufficient care and thought.

Not so in Haskell. Before I started using stack, I've run into the following situation quite a few times with Text and ByteString:

```<code>Couldn't match type ‘T.Text’
               with ‘Text’
NB: ‘T.Text’
      is defined in ‘Data.Text.Internal’ in package ‘text-1.2.2.1’
    ‘Text’ is defined in ‘Data.Text.Internal’ in package ‘text-1.2.2.0’
Expected type: String -> Text
  Actual type: String -> T.Text
</code>```

This is quite frustrating, because in the above example only the patch version is different. The two data types may only be different nominally, and the ADT definition and the underlying memory representation may be completely identical.

As an example, it could have been a minor bugfix to the intersperse function that warranted the release of 1.2.2.1. Which is completely irrelevant to me if all I care about, in this hypothetical example, is concatenating some Texts and comparing their lengths.

Compound types, objects

Sometimes there is sufficient reason to diverge in JS from the built in data types: Take Promises as an example. It's such a useful abstraction over async computations compared to callbacks that many APIs started using them. What now? How come we don't run into many incompatibilities when different versions of these {then(), fail(), ...} objects are being passed up, down and around the dependency tree?

I think it's thanks to the robustness principle.

Be conservative in what you send, be liberal in what you accept.

So if I am authoring a JS library which I know returns promises and takes promises as part of its API, I'll be very careful how I interact with the received objects. E.g. I won't be calling fancy .success(), .finally(), ['catch']() methods on it, since I want to be as compatible as possible with different users, with different implementations of Promises. So, very conservatively, I may just use .then(done, fail), and nothing more. At this point, it doesn't matter if the user uses the promises that my lib returns, or Bluebirds' or even if they hand-write their own, so long as those adhere to the most basic Promise 'laws' -- the most basic API contracts.

Can this still lead to breakage at runtime? Yes, it can. If even the most basic API contract is not fulfilled, you may get an exception saying "Uncaught TypeError: promise.then is not a function". I think the trick here is that library authors are explicit about what their API needs: e.g. a .then method on the supplied object. And then its up to whoever is building on top of that API to make it damn sure that that method is available on the object they pass in.

I'd like to also point out here that this is also the case for Haskell, isn't it? Should I be so foolish as to write an instance for a typeclass that still type-checks without following its laws, I'll get runtime errors, won't I?

Where do we go from here?

Having thought through all this just now, I think we might be able to have the benefits of the robustness principle even in Haskell with much less (or even no(?)) risk for runtime exceptions/errors compared to JavaScript: We just need the typesystem be granular enough so it can distinguish what we want to do with the data we manipulate, and determine if that is still safe or not. E.g. The hypothetical Text example above, I would wager is still safe. And the compiler should only complain if I'm trying to use intersperse, and asks me to qualify it. E.g. with T.intersperse so it can be sure which one I want to use.

How do we do this in practice? Do we need extra support, e.g. language extension flags from GHC? We might not.

Just recently I found bookkeeper, which is a compile-time type-checked anonymous records implementation.

Please note: The following is conjecture on my part, I haven't taken much time to try and experiment with Bookkeeper. But I intend to in my Haskell projects to see if what I write about below could really be achieved with an approach such as this.

With Bookkeeper I could define an API like so:

```<code>emptyBook & #then =: id & #fail =: const
  :: Bookkeeper.Internal.Book'
       '["fail" 'Data.Type.Map.:-> (a -> b -> a),
         "then" 'Data.Type.Map.:-> (a1 -> a1)]
</code>```

Since functions are also first-class values. And whichever API takes this Book as an argument can be very specific what it demands from it: Namely the #then function, and that it has to match a certain type signature. And it cares not for any other function that may or may not be present with whatever signature. All this checked at compile time.

```<code>Prelude Bookkeeper
> let f o = (o ?: #foo) "a" "b" in f $ emptyBook & #foo =: (++)
"ab"
</code>```

Conclusion

Maybe Bookkeeper or something similar will turn out to be useful in my experiments. Maybe Backpack will rush to the rescue with its common interface definitions. Or some other solution comes along. But either way, I hope we can move towards being able to take advantage of the robustness principle. And that Haskell's dependency management can also "just work" most of the time and fail with type errors only when it is truly warranted.

Does the above make sense? Anything unclear? Does it answer your question? I'd be curious to hear.

Further possibly relevant discussion may be found in this /r/haskell reddit thread, where this topic came up just not long ago, and I thought to post this answer to both places.

Body:
this situation basically never happens

Yes, my experience is indeed that that is not a problem in the Node/JS ecosystem. And I think it is, in part, thanks to the robustness principle.

Below is my view on why and how.

Primitives, the early days

I think the first and foremost reason is that the language provides a common basis for primitive types (Number, String, Bool, Null, Undefined) and some basic compound types (Object, Array, RegExp, etc...).

So if I receive a String from one of the libs' APIs I use, and pass it to another, it cannot go wrong because there is just a single String type.

This is what used to happen, and still happens to some extent to this day: Library authors try to rely on the built-ins as much as possible and only diverge when there is sufficient reason to, and with sufficient care and thought.

Not so in Haskell. Before I started using stack, I've run into the following situation quite a few times with Text and ByteString:

Couldn't match type ‘T.Text’
               with ‘Text’
NB: ‘T.Text’
      is defined in ‘Data.Text.Internal’ in package ‘text-1.2.2.1’
    ‘Text’ is defined in ‘Data.Text.Internal’ in package ‘text-1.2.2.0’
Expected type: String -> Text
  Actual type: String -> T.Text

This is quite frustrating, because in the above example only the patch version is different. The two data types may only be different nominally, and the ADT definition and the underlying memory representation may be completely identical.

As an example, it could have been a minor bugfix to the intersperse function that warranted the release of 1.2.2.1. Which is completely irrelevant to me if all I care about, in this hypothetical example, is concatenating some Texts and comparing their lengths.

Compound types, objects

Sometimes there is sufficient reason to diverge in JS from the built in data types: Take Promises as an example. It's such a useful abstraction over async computations compared to callbacks that many APIs started using them. What now? How come we don't run into many incompatibilities when different versions of these {then(), fail(), ...} objects are being passed up, down and around the dependency tree?

I think it's thanks to the robustness principle.

Be conservative in what you send, be liberal in what you accept.

So if I am authoring a JS library which I know returns promises and takes promises as part of its API, I'll be very careful how I interact with the received objects. E.g. I won't be calling fancy .success(), .finally(), ['catch']() methods on it, since I want to be as compatible as possible with different users, with different implementations of Promises. So, very conservatively, I may just use .then(done, fail), and nothing more. At this point, it doesn't matter if the user uses the promises that my lib returns, or Bluebirds' or even if they hand-write their own, so long as those adhere to the most basic Promise 'laws' -- the most basic API contracts.

Can this still lead to breakage at runtime? Yes, it can. If even the most basic API contract is not fulfilled, you may get an exception saying "Uncaught TypeError: promise.then is not a function". I think the trick here is that library authors are explicit about what their API needs: e.g. a .then method on the supplied object. And then its up to whoever is building on top of that API to make it damn sure that that method is available on the object they pass in.

I'd like to also point out here that this is also the case for Haskell, isn't it? Should I be so foolish as to write an instance for a typeclass that still type-checks without following its laws, I'll get runtime errors, won't I?

Where do we go from here?

Having thought through all this just now, I think we might be able to have the benefits of the robustness principle even in Haskell with much less (or even no(?)) risk for runtime exceptions/errors compared to JavaScript: We just need the typesystem be granular enough so it can distinguish what we want to do with the data we manipulate, and determine if that is still safe or not. E.g. The hypothetical Text example above, I would wager is still safe. And the compiler should only complain if I'm trying to use intersperse, and asks me to qualify it. E.g. with T.intersperse so it can be sure which one I want to use.

How do we do this in practice? Do we need extra support, e.g. language extension flags from GHC? We might not.

Just recently I found bookkeeper, which is a compile-time type-checked anonymous records implementation.

Please note: The following is conjecture on my part, I haven't taken much time to try and experiment with Bookkeeper. But I intend to in my Haskell projects to see if what I write about below could really be achieved with an approach such as this.

With Bookkeeper I could define an API like so:

emptyBook & #then =: id & #fail =: const
  :: Bookkeeper.Internal.Book'
       '["fail" 'Data.Type.Map.:-> (a -> b -> a),
         "then" 'Data.Type.Map.:-> (a1 -> a1)]

Since functions are also first-class values. And whichever API takes this Book as an argument can be very specific what it demands from it: Namely the #then function, and that it has to match a certain type signature. And it cares not for any other function that may or may not be present with whatever signature. All this checked at compile time.

Prelude Bookkeeper
> let f o = (o ?: #foo) "a" "b" in f $ emptyBook & #foo =: (++)
"ab"

Conclusion

Maybe Bookkeeper or something similar will turn out to be useful in my experiments. Maybe Backpack will rush to the rescue with its common interface definitions. Or some other solution comes along. But either way, I hope we can move towards being able to take advantage of the robustness principle. And that Haskell's dependency management can also "just work" most of the time and fail with type errors only when it is truly warranted.

Does the above make sense? Anything unclear? Does it answer your question? I'd be curious to hear.

Further possibly relevant discussion may be found in this /r/haskell reddit thread, where this topic came up just not long ago, and I thought to post this answer to both places.


问:
If-else without else causes recursive function to repeat
Why does the following produce the output "ayyayy" and not just "ayy" (once)?

```<code>def iftest(b: Boolean): Unit = {
  if(b) iftest(false)
  print("ayy")
}
</code>```

I run it in REPL as iftest(true) which should cause it to fail on the first pass but succeed on the second (hence only one "ayy"). So why does it act like both succeed?

Is there some sort of recursive "backfolding" in scala that I don't know about?

答:
Is there some sort of recursive "backfolding" in scala that I don't
  know about?

No, the method operates as you've defined it. Lets analyze:

You call iftest(true) and invoke the method.

if(b) is true, so you call iftest(false) and start a new stack frame.

if(b) is now false, so we don't recursively call the method again.

The next line of code is print("ayy"), so it prints it out and the method completes

We go back up one frame, we now finished calling iftest(false) and the next line of code is println("ayy"), so it prints it out again

Method completes.

Perhaps what you want is:

```<code>def iftest(b: Boolean): Unit = {
  if (b) {
    iftest(false)
    print("ayy")
  }
}
</code>```

Body:
Why does the following produce the output "ayyayy" and not just "ayy" (once)?

def iftest(b: Boolean): Unit = {
  if(b) iftest(false)
  print("ayy")
}

I run it in REPL as iftest(true) which should cause it to fail on the first pass but succeed on the second (hence only one "ayy"). So why does it act like both succeed?

Is there some sort of recursive "backfolding" in scala that I don't know about?

Body:
Is there some sort of recursive "backfolding" in scala that I don't
  know about?

No, the method operates as you've defined it. Lets analyze:

You call iftest(true) and invoke the method.

if(b) is true, so you call iftest(false) and start a new stack frame.

if(b) is now false, so we don't recursively call the method again.

The next line of code is print("ayy"), so it prints it out and the method completes

We go back up one frame, we now finished calling iftest(false) and the next line of code is println("ayy"), so it prints it out again

Method completes.

Perhaps what you want is:

def iftest(b: Boolean): Unit = {
  if (b) {
    iftest(false)
    print("ayy")
  }
}


问:
all the data is gone in the form when i put ng-model angularjs
I want to load data of a selected row in a form in order to update it. I successfully had the data loaded in the form, the but the problem is when I use ng model to save the data all the stuff have been put in the form fields disappear.

```<code><div class="panel-body pan" ng-if="loadedpr">
<form action="#">
    <div class="form-body pal">
        <div class="row">
            <div class="col-md-2">
                <div class="form-group">
                    <label for="refprojet" class="control-label">
                        Référence Projet *</label>
                    <input id="refprojet" type="text" value="{{loadedpr.ref_projet}}"  class="form-control" disabled ng-model="ref_projet"/>
                </div>
            </div>
            <div class="col-md-5">
                <div class="form-group">
                    <label for="intitulefr" class="control-label">
                        Intitulé *</label>
                    <input id="intitulefr" type="text" value="{{loadedpr.intitule_fr}}" class="form-control" ng-model="intitule_fr" />
                </div>
            </div>
            <div class="col-md-5">
                <div class="form-group">
                    <label for="ctot" class="control-label"> Coût Total (TND) *</label>
                    <input id="ctot" type="text" value="{{loadedpr.cout_total}}" ng-model="cout_total" class="form-control" disabled ng-model="cout_total" />
                </div>
            </div>
        </div>

        <div class="form-group">
            <label for="description" class="control-label">
                Description</label><textarea id="description" rows="3" value="{{loadedpr.description}}" ng-model="description" class="form-control"></textarea>
        </div>
        <div class="form-actions text-center pal">
            <button type="submit" class="btn btn-primary" ng-click="upadateProjet()">Valider</button>
        </div>
    </div>
</form>
</code>```

this is the angularjs method:

```<code>$scope.updateProjet= function(){
    $scope.projet={'ref_projet':$scope.refprojet,'intitule_fr':$scope.intitule_fr,'description':$scope.description,cout_total':$scope.cout_total};
    $http.put("/editprojet", $scope.projet)
    .success(function(data,status,headers,config){

    });

}
</code>```

rest controller

```<code>@RequestMapping(value="/editprojet",method=RequestMethod.PUT)
public Projet editProjet(@RequestBody Projet p) {
    return projetMetier.editProjet(p);
}
</code>```

答:
you are using button type="submit"
it will clear the form use button tag

```<code><button></button>
</code>```

Body:
I want to load data of a selected row in a form in order to update it. I successfully had the data loaded in the form, the but the problem is when I use ng model to save the data all the stuff have been put in the form fields disappear.

<form action="#">

                        Référence Projet *
                    <input id="refprojet" type="text" value="{{loadedpr.ref_projet}}"  class="form-control" disabled ng-model="ref_projet"/>

                        Intitulé *
                    <input id="intitulefr" type="text" value="{{loadedpr.intitule_fr}}" class="form-control" ng-model="intitule_fr" />

                     Coût Total (TND) *
                    <input id="ctot" type="text" value="{{loadedpr.cout_total}}" ng-model="cout_total" class="form-control" disabled ng-model="cout_total" />

                Description<textarea id="description" rows="3" value="{{loadedpr.description}}" ng-model="description" class="form-control"></textarea>

            <button type="submit" class="btn btn-primary" ng-click="upadateProjet()">Valider</button>

</form>

this is the angularjs method:

$scope.updateProjet= function(){
    $scope.projet={'ref_projet':$scope.refprojet,'intitule_fr':$scope.intitule_fr,'description':$scope.description,cout_total':$scope.cout_total};
    $http.put("/editprojet", $scope.projet)
    .success(function(data,status,headers,config){

    });

}

rest controller

@RequestMapping(value="/editprojet",method=RequestMethod.PUT)
public Projet editProjet(@RequestBody Projet p) {
    return projetMetier.editProjet(p);
}

Body:
you are using button type="submit"
it will clear the form use button tag

<button></button>


问:
How to run a SSIS Package which has a file based source automatically
I have a similar issue as this question:  How to run a SSIS Package which has a file based source and a target.  At first, there was no known program to open the dtsx package (my package grabs a table from one server and places it on another).  I did some digging and found the DTEXECUI program file, and now it does open the Execute Package Utility, but it doesn't populate the Package Source (file) or Package Name (Desktop\xxx.dtsx).  How can I get it so that double-clicking the file just executes the SSIS package - or at least populates the names for the file I clicked on?  Thanks in advance.

答:
I'm guessing that since Windows didn't automatically create that association for you, the default is missing some parameters for the executable (because that program should open with those fields populated).

Try this:

Download Default Programs Editor and run it

Click File type settings

Click Context menu

Locate .dtsx in the list and click Next

Click the Open list item and then Edit Selected Command

The path should look something like "C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\ManagementStudio\DtExecUI.exe" /F "%L" - your path to the DtExecUI may be different, but of special note is the /F "%L"

Click Next and then Save Context Menu


问:
How to delete data based on the params url selected on rails?
I have two models on rails with following associations:

```<code>class Manufacturer
  has_many :equipments
end

class Equipments
  belongs_to :manufacturer
end
</code>```

I have an Equipments show page with following fields:

```<code>title,
category_id,
sub_category_id,
manufacturer_id
</code>```

When I am on the equipment show page

I am trying to give a button which when clicked will fetch the manufacturer_id on that page based on the equipment_id on the url and delete it from the record of the Manufacturer table.
I know how to do it from Manufacturer show page. It will be like:

Manufacturer.find(params[:manufacturer_id]).

But how can I do it same from the Equipment show page ?

答:
There are many ways to achieve this. The 'correct' way would be having a link in your equipment show page that makes a delete request to the ManufacturersController#destroy action, sending the @equipment.manufacturer_id as a parameter. Like this:

```<code><%= link_to 'Delete Manufacturer', manufacturer_path(@equipment.manufacturer_id), method: :delete, data: {confirm: 'Some confirmation message'} %>
</code>```

This will send the manufacturer_id as the param id. This also assumes that you have in your routes.rb something like:

```<code>resources :manufacturers
</code>```

Then, in your manufacturers_controller.rb:

```<code>def destroy:
    @manufacturer = Manufacturer.find(params[:id])
    @manufacturer.destroy
    redirect_to some_place, notice: 'Manufacturer successfully deleted'
end
</code>```

Aditionaly, if you have only the equipment_id and want to retrieve the associated Manufacturer, you can do something like this:

```<code>@manufacturer = Manufacturer.joins(:equipments).where(equipments: {id: params[:equipment_id]}).first
@manufacturer.destroy if @manufacturer.present?
</code>```

Body:
I have two models on rails with following associations:

class Manufacturer
  has_many :equipments
end

class Equipments
  belongs_to :manufacturer
end

I have an Equipments show page with following fields:

title,
category_id,
sub_category_id,
manufacturer_id

When I am on the equipment show page

I am trying to give a button which when clicked will fetch the manufacturer_id on that page based on the equipment_id on the url and delete it from the record of the Manufacturer table.
I know how to do it from Manufacturer show page. It will be like:

Manufacturer.find(params[:manufacturer_id]).

But how can I do it same from the Equipment show page ?

Body:
There are many ways to achieve this. The 'correct' way would be having a link in your equipment show page that makes a delete request to the ManufacturersController#destroy action, sending the @equipment.manufacturer_id as a parameter. Like this:

<%= link_to 'Delete Manufacturer', manufacturer_path(@equipment.manufacturer_id), method: :delete, data: {confirm: 'Some confirmation message'} %>

This will send the manufacturer_id as the param id. This also assumes that you have in your routes.rb something like:

resources :manufacturers

Then, in your manufacturers_controller.rb:

def destroy:
    @manufacturer = Manufacturer.find(params[:id])
    @manufacturer.destroy
    redirect_to some_place, notice: 'Manufacturer successfully deleted'
end

Aditionaly, if you have only the equipment_id and want to retrieve the associated Manufacturer, you can do something like this:

@manufacturer = Manufacturer.joins(:equipments).where(equipments: {id: params[:equipment_id]}).first
@manufacturer.destroy if @manufacturer.present?


问:
Add http header to all requests to GeckoFx
I am trying to figure out a way to add a custom http header to all requests made through geckoFX. I tried to add a header using

```<code>GeckoMIMEInputStream strea=new GeckoMIMEInputStream();
strea.AddHeader("head","val");
geckoWebBrowser1.Navigate("http://google.com",GeckoLoadFlags.None,"",null,strea);
</code>```

I need a way to add a custom header, to absolutely ALL requests made when going to a webpage.
Thank you

答:
You can use ObserveHttpModifyRequest event:

```<code>var browser = new GeckoWebBrowser();
browser.UseHttpActivityObserver = true;
browser.ObserveHttpModifyRequest +=
    (sender, e) => e.Channel.SetRequestHeader(name, value, merge: true);
</code>```

For more information check nsIRequest and nsIHttpChannel pages on MDN.

Body:
I am trying to figure out a way to add a custom http header to all requests made through geckoFX. I tried to add a header using

GeckoMIMEInputStream strea=new GeckoMIMEInputStream();
strea.AddHeader("head","val");
geckoWebBrowser1.Navigate("http://google.com",GeckoLoadFlags.None,"",null,strea);

I need a way to add a custom header, to absolutely ALL requests made when going to a webpage.
Thank you

Body:
You can use ObserveHttpModifyRequest event:

var browser = new GeckoWebBrowser();
browser.UseHttpActivityObserver = true;
browser.ObserveHttpModifyRequest +=
    (sender, e) => e.Channel.SetRequestHeader(name, value, merge: true);

For more information check nsIRequest and nsIHttpChannel pages on MDN.


问:
404 error when trying to create subgroup
Here are some illustrations.
I've got a group without subgroups:

And when I push create subgroup, I see this:

Also posted this issue on gitlab forum

答:
I've run into the same issue. Apparently, the button is displayed even though you don't have rights to create a new subgroup.

Here's a link to the issue:
https://gitlab.com/gitlab-org/gitlab-ce/issues/30139


问:
Multiprocessing in a pipeline done right
I'd like to know how multiprocessing is done right. Assuming I have a list [1,2,3,4,5] generated by function f1 which is written to a Queue (left green circle). Now I start two processes pulling from that queue (by executing f2 in the processes). They process the data, say: doubling the value, and write it to the second queue. Now, function f3 reads this data and prints it out.

Inside the functions there is a kind of a loop, trying to read from the queue forever. How do I stop this process?

Idea 1

f1 does not only send the list, but also a None object or a custon object, class PipelineTerminator: pass or some such which is just being propagated all the way down. f3 now waits for None to come, when it's there, it breaks out of the loop. Problem: it's possible that one of the two f2s  reads and propagates the None while the other one it still processing a number. Then the last value is lost.

Idea 2

f3 is f1. So the function f1 generates the data and the pipes, spawns the processes with f2 and feeds all data. After spawning and feeding, it listens on the second pipe, simply counting and processing the received objects. Because it knows how much data fed, it can terminate the processes executing f2. But if the target is to set up a processing pipeline, the different steps should be separable. So f1, f2 and f3 are different elements of a pipeline, and the expensive steps are done in parallel.

Idea 3

Each piece of the pipeline is a function, this function spawns processes as it likes to and is responsible to manage them. It knows, how much data came in and how much data has been returned (with yield maybe). So it's safe to propagate a None object.

```<code>setup child processes

execute thread one and two and wait until both finished

thread 1:
    while True:
        pull from input queue
        if None: break and set finished_flag
        else: push to queue1 and increment counter1

thread 2:
    while True:
        pull from queue2
        increment counter2
        yield result
        if counter1 == counter2 and finished_flag: break

when both threads finished: kill process pool and return.
</code>```

(Instead of using threads, maybe one can think of a smarter solution.)

So ...

I have implemented a solution following idea 2, feeding and waiting for the results to arrive, but it was not really a pipeline with independent functions plugged together. It worked for the task I had to manage, but was hard to maintain.

I'd like to hear from you now how you implement pipelines (easy in one process with generator functions and so on, but with multiple processes?) and manage them usually.

答:
The easiest way to do exactly that is using semaphores.

F1

F1 is populating your 'Queue' with the data you want to process. End the end of this push, you put n 'Stop' keywords in your queue. n = 2 for your example, but usually the number of involved workers.
Code would look like:

```<code>for n in no_of_processes:
    tasks.put('Stop')
</code>```

F2

F2 is pulling from the provided queue by a get-command. The element is taken from the queue and deleted in the queue. Now, you can put the pop into a loop while paying attention to the stop signal:

```<code>for elem in iter(tasks.get, 'STOP'):
   do something
</code>```

F3

This one is a bit tricky. You could generate a semaphore in F2 that acts as a signal to F3. But you do not know when this signal arrives and you may loose data. However, F3 pulls the data the same way as F2 and you could put that into a try... except-statement.
queue.get raises an queue.Emptywhen there are no elements in the queue. So your pull in F3 would look like:

```<code>while control:
    try:
        results.get()
    except queue.Empty:
        control = False
</code>```

With tasks and results being queues. So you do not need anything which is not already included in Python.

Body:
I'd like to know how multiprocessing is done right. Assuming I have a list [1,2,3,4,5] generated by function f1 which is written to a Queue (left green circle). Now I start two processes pulling from that queue (by executing f2 in the processes). They process the data, say: doubling the value, and write it to the second queue. Now, function f3 reads this data and prints it out.

Inside the functions there is a kind of a loop, trying to read from the queue forever. How do I stop this process?

Idea 1

f1 does not only send the list, but also a None object or a custon object, class PipelineTerminator: pass or some such which is just being propagated all the way down. f3 now waits for None to come, when it's there, it breaks out of the loop. Problem: it's possible that one of the two f2s  reads and propagates the None while the other one it still processing a number. Then the last value is lost.

Idea 2

f3 is f1. So the function f1 generates the data and the pipes, spawns the processes with f2 and feeds all data. After spawning and feeding, it listens on the second pipe, simply counting and processing the received objects. Because it knows how much data fed, it can terminate the processes executing f2. But if the target is to set up a processing pipeline, the different steps should be separable. So f1, f2 and f3 are different elements of a pipeline, and the expensive steps are done in parallel.

Idea 3

Each piece of the pipeline is a function, this function spawns processes as it likes to and is responsible to manage them. It knows, how much data came in and how much data has been returned (with yield maybe). So it's safe to propagate a None object.

setup child processes

execute thread one and two and wait until both finished

thread 1:
    while True:
        pull from input queue
        if None: break and set finished_flag
        else: push to queue1 and increment counter1

thread 2:
    while True:
        pull from queue2
        increment counter2
        yield result
        if counter1 == counter2 and finished_flag: break

when both threads finished: kill process pool and return.

(Instead of using threads, maybe one can think of a smarter solution.)

So ...

I have implemented a solution following idea 2, feeding and waiting for the results to arrive, but it was not really a pipeline with independent functions plugged together. It worked for the task I had to manage, but was hard to maintain.

I'd like to hear from you now how you implement pipelines (easy in one process with generator functions and so on, but with multiple processes?) and manage them usually.

Body:
The easiest way to do exactly that is using semaphores.

F1

F1 is populating your 'Queue' with the data you want to process. End the end of this push, you put n 'Stop' keywords in your queue. n = 2 for your example, but usually the number of involved workers.
Code would look like:

for n in no_of_processes:
    tasks.put('Stop')

F2

F2 is pulling from the provided queue by a get-command. The element is taken from the queue and deleted in the queue. Now, you can put the pop into a loop while paying attention to the stop signal:

for elem in iter(tasks.get, 'STOP'):
   do something

F3

This one is a bit tricky. You could generate a semaphore in F2 that acts as a signal to F3. But you do not know when this signal arrives and you may loose data. However, F3 pulls the data the same way as F2 and you could put that into a try... except-statement.
queue.get raises an queue.Emptywhen there are no elements in the queue. So your pull in F3 would look like:

while control:
    try:
        results.get()
    except queue.Empty:
        control = False

With tasks and results being queues. So you do not need anything which is not already included in Python.


问:
Error: Cannot read property 'replace' of undefined when building iOS Cordova
I created a cordova project using cordova create project hello com.hello Hello.

And added iOS platform using cordova platform add iOS.
And tried to do cordova run ios after cordova build ios.

But it shows me this error(I used --d/ --verbose to get the details).

/usr/bin/codesign --force --sign - --timestamp=none
  /Volumes/Untitled/Plot/PlotReel/platforms/ios/build/emulator/PlotReel.app
  /Volumes/Untitled/Plot/PlotReel/platforms/ios/build/emulator/PlotReel.app:
  replacing existing signature

** BUILD SUCCEEDED **

No scripts found for hook "before_deploy". Error: TypeError: Cannot
  read property 'replace' of undefined

```<code>at remove (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/ios-sim/src/lib.js:282:70)
at Array.forEach (native)
at Object.getdevicetypes (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/ios-sim/src/lib.js:292:22)
at Object.listEmulatorImages [as run] (/Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/list-emulator-images:34:29)
at deployToSim (/Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/run.js:146:50)
at /Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/run.js:88:20
at _fulfilled (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:834:54)
at self.promiseDispatch.done (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:863:30)
at Promise.promise.promiseDispatch (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:796:13)
at /Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:604:44
</code>```

I have tried uninstalling and installing cordova again, but the problem is still remaining.

Please help me.

答:
I had the same error. For me I traced this down into a bug in platforms/ios/cordova/node_modules/ios-sim/src/lib.js

```<code>getdevicetypes: function(args) {
...
    list.devicetypes.forEach(function(device) {
        name_id_map[ filterDeviceName(device.name) ] = device.id;
    });

    list = [];
    var remove = function(runtime) {
        // remove "iOS" prefix in runtime, remove prefix "com.apple.CoreSimulator.SimDeviceType." in id
        list.push(util.format('%s, %s', name_id_map[ deviceName ].replace(/^com.apple.CoreSimulator.SimDeviceType./, ''), runtime.replace(/^iOS /, '')));
    };
</code>```

The error always occured as "TypeError: Cannot read property 'replace' of undefined" in lib.js:289

```<code>list.push(util.format('%s, %s', name_id_map[ deviceName ].replace(/^com.apple.CoreSimulator.SimDeviceType./, ''), runtime.replace(/^iOS /, '')));
</code>```

So I inserted some debug code:

```<code>    list.devicetypes.forEach(function(device) {
        console.log('test 1 ' + device.name);
        console.log('test 2 ' + filterDeviceName(device.name));
        name_id_map[ filterDeviceName(device.name) ] = device.id;
    });
</code>```

This worked for me. Good luck.

```<code>    list = [];
    var remove = function(runtime) {
        // remove "iOS" prefix in runtime, remove prefix "com.apple.CoreSimulator.SimDeviceType." in id
        console.log('remove 1 ' + runtime);
        console.log('remove 2 ' + deviceName);
        console.log('remove 3 ' + name_id_map[ deviceName ]);
        list.push(util.format('%s, %s', name_id_map[ deviceName ].replace(/^com.apple.CoreSimulator.SimDeviceType./, ''), runtime.replace(/^iOS /, '')));
    };
</code>```

and got the following output:

```<code>test 1 iPhone 5
test 2 iPhone 5
test 1 iPad Pro (9.7-inch)
test 2 iPad Pro (9.7 inch)
remove 1 iOS 10.2
remove 2 iPhone 5
remove 3 com.apple.CoreSimulator.SimDeviceType.iPhone-5
remove 1 iOS 10.2
remove 2 iPad Pro (9.7-inch)
remove 3 undefined
</code>```

Notice how filterDeviceName removed the minus character while filling the hash. When the value is retrieved again, the filter is not applied and the program fails.

Bug fix: apply the filter while writing to and reading from the hash.

```<code> list.push(util.format('%s, %s', name_id_map[ filterDeviceName(deviceName) ].replace(/^com.apple.CoreSimulator.SimDeviceType./, ''), runtime.replace(/^iOS /, '')));
</code>```

Body:
I created a cordova project using cordova create project hello com.hello Hello.

And added iOS platform using cordova platform add iOS.
And tried to do cordova run ios after cordova build ios.

But it shows me this error(I used --d/ --verbose to get the details).

/usr/bin/codesign --force --sign - --timestamp=none
  /Volumes/Untitled/Plot/PlotReel/platforms/ios/build/emulator/PlotReel.app
  /Volumes/Untitled/Plot/PlotReel/platforms/ios/build/emulator/PlotReel.app:
  replacing existing signature

** BUILD SUCCEEDED **

No scripts found for hook "before_deploy". Error: TypeError: Cannot
  read property 'replace' of undefined

at remove (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/ios-sim/src/lib.js:282:70)
at Array.forEach (native)
at Object.getdevicetypes (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/ios-sim/src/lib.js:292:22)
at Object.listEmulatorImages [as run] (/Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/list-emulator-images:34:29)
at deployToSim (/Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/run.js:146:50)
at /Volumes/Untitled/Plot/test/platforms/ios/cordova/lib/run.js:88:20
at _fulfilled (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:834:54)
at self.promiseDispatch.done (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:863:30)
at Promise.promise.promiseDispatch (/Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:796:13)
at /Volumes/Untitled/Plot/test/platforms/ios/cordova/node_modules/q/q.js:604:44

I have tried uninstalling and installing cordova again, but the problem is still remaining.

Please help me.

Body:
I had the same error. For me I traced this down into a bug in platforms/ios/cordova/node_modules/ios-sim/src/lib.js

getdevicetypes: function(args) {
...
    list.devicetypes.forEach(function(device) {
        name_id_map[ filterDeviceName(device.name) ] = device.id;
    });

    list = [];
    var remove = function(runtime) {
        // remove "iOS" prefix in runtime, remove prefix "com.apple.CoreSimulator.SimDeviceType." in id
        list.push(util.format('%s, %s', name_id_map[ deviceName ].replace(/^com.apple.CoreSimulator.SimDeviceType./, ''), runtime.replace(/^iOS /, '')));
    };

The error always occured as "TypeError: Cannot read property 'replace' of undefined" in lib.js:289

list.push(util.format('%s, %s', name_id_map[ deviceName ].replace(/^com.apple.CoreSimulator.SimDeviceType./, ''), runtime.replace(/^iOS /, '')));

So I inserted some debug code:

    list.devicetypes.forEach(function(device) {
        console.log('test 1 ' + device.name);
        console.log('test 2 ' + filterDeviceName(device.name));
        name_id_map[ filterDeviceName(device.name) ] = device.id;
    });

This worked for me. Good luck.

    list = [];
    var remove = function(runtime) {
        // remove "iOS" prefix in runtime, remove prefix "com.apple.CoreSimulator.SimDeviceType." in id
        console.log('remove 1 ' + runtime);
        console.log('remove 2 ' + deviceName);
        console.log('remove 3 ' + name_id_map[ deviceName ]);
        list.push(util.format('%s, %s', name_id_map[ deviceName ].replace(/^com.apple.CoreSimulator.SimDeviceType./, ''), runtime.replace(/^iOS /, '')));
    };

and got the following output:

test 1 iPhone 5
test 2 iPhone 5
test 1 iPad Pro (9.7-inch)
test 2 iPad Pro (9.7 inch)
remove 1 iOS 10.2
remove 2 iPhone 5
remove 3 com.apple.CoreSimulator.SimDeviceType.iPhone-5
remove 1 iOS 10.2
remove 2 iPad Pro (9.7-inch)
remove 3 undefined

Notice how filterDeviceName removed the minus character while filling the hash. When the value is retrieved again, the filter is not applied and the program fails.

Bug fix: apply the filter while writing to and reading from the hash.

 list.push(util.format('%s, %s', name_id_map[ filterDeviceName(deviceName) ].replace(/^com.apple.CoreSimulator.SimDeviceType./, ''), runtime.replace(/^iOS /, '')));


问:
How to list the deleted contacts by Microsoft Graph API
I want to do a sync action in my client side, so need to know how to get all deleted contact list.

By the api (GET /me/contacts), I could get all contact list
But it wastes much time when the user has large contacts.

This api (GET /me/contacts/{id}) tell us the contact is exist or not.

it is inefficient to check every contacts are deleted or not for me.

Which apis do I use? thanks for your help.

答: Why not use the delta query preview in the /beta endpoint? That should do what you want.


问:
How can I add a number twice after every 6 rows?
I'm working on installment plan. Lets suppose we have a plan of 1,250,000 with 35 installments and payment frequency is after 1 month.

customer has to pay 5% extra after every 6 months. So regularly he will pay 1% and after every 6 months he will pay 6%.

So suppose after other payment charges we have payment of 812,500 that is 65% of total payment.

Now every 6th month customer will pay 1% of regular fee with 5% extra that is 62500.

For clearfication see screenshot. Currently I have to manually add that values but I need to automate this process to save time.

答:
you can use the mod operator to find every 6th row like this . </p>

```<code>for($i=1;$i<=20;$i++){
    if($i%6 == 0)
        echo $i;
}
</code>```

Body:
you can use the mod operator to find every 6th row like this .

for($i=1;$i<=20;$i++){
    if($i%6 == 0)
        echo $i;
}