问:
Comparing elements in a list with its neighbours
I have a list of 29400 values in Python and I'm trying to check if each element of the list is larger than both the 2000 neighbors to its left and the 2000 neighbors to its right. If the element is larger than its 4000 neighbors, I want to retrieve the index of the element. If there aren't 2000 neighbors to the right I just want to compare it with future elements until I reach the end of the list, and vice versa if there aren't 2000 values to the left.

```<code>def find_peaks(t):
prev = []
future = []
peak_index = []
for i in range(len(t)-2000): # compare element with previous values
    for j in range(1,2001):
        if t[i]<t[i+j]:
            prev.append(False)
            break
        if j==2000:
            if t[i]<t[i+j]:
                prev.append(False)
                break
            prev.append(True)

for i in range(1999,len(t)-1): # compare element with future values
    for j in range(1,2001):
        if t[i]<t[i-j]:
            future.append(False)
            break
        if j==2000:
            if t[i]<t[i-j]:
                future.append(False)
                break
            future.append(True)
future = future[::-1] # reverse list
for i in range(0,len(prev)-1):
    if prev[i] == True:
        if prev[i] == True:
            peak_index.append(i)
</code>```

Does anyone know of any better ways to go about this? I was having trouble comparing elements near the end and the beginning of the list- If there aren't 2000 elements left in the list for me to compare with, then the list wraps around to the beginning of the list, which isn't something I want.

答:
You can use some list comprehension, so the actual search becomes a one-liner. I cannot judge about speed and beauty, but it takes just some seconds on my machine.</p>

```<code>import random

# create list of random numbers and manually insert two peaks
t = [random.randrange(1, 1000) for r in range(29400)]  # found this here: https://stackoverflow.com/questions/16655089/python-random-numbers-into-a-list
t[666] = 2000
t[6666] = 2000

# finds the peak elements
peaks = [index for index, value in enumerate(t) if value == max(t[max(index-2000, 0):min(index+2000, len(t))])]
print peaks  # includes 666 and 6666
</code>```

Body:
I have a list of 29400 values in Python and I'm trying to check if each element of the list is larger than both the 2000 neighbors to its left and the 2000 neighbors to its right. If the element is larger than its 4000 neighbors, I want to retrieve the index of the element. If there aren't 2000 neighbors to the right I just want to compare it with future elements until I reach the end of the list, and vice versa if there aren't 2000 values to the left.

def find_peaks(t):
prev = []
future = []
peak_index = []
for i in range(len(t)-2000): # compare element with previous values
    for j in range(1,2001):
        if t[i]<t[i+j]:
            prev.append(False)
            break
        if j==2000:
            if t[i]<t[i+j]:
                prev.append(False)
                break
            prev.append(True)

for i in range(1999,len(t)-1): # compare element with future values
    for j in range(1,2001):
        if t[i]<t[i-j]:
            future.append(False)
            break
        if j==2000:
            if t[i]<t[i-j]:
                future.append(False)
                break
            future.append(True)
future = future[::-1] # reverse list
for i in range(0,len(prev)-1):
    if prev[i] == True:
        if prev[i] == True:
            peak_index.append(i)

Does anyone know of any better ways to go about this? I was having trouble comparing elements near the end and the beginning of the list- If there aren't 2000 elements left in the list for me to compare with, then the list wraps around to the beginning of the list, which isn't something I want.

Body:
You can use some list comprehension, so the actual search becomes a one-liner. I cannot judge about speed and beauty, but it takes just some seconds on my machine.

import random

# create list of random numbers and manually insert two peaks
t = [random.randrange(1, 1000) for r in range(29400)]  # found this here: https://stackoverflow.com/questions/16655089/python-random-numbers-into-a-list
t[666] = 2000
t[6666] = 2000

# finds the peak elements
peaks = [index for index, value in enumerate(t) if value == max(t[max(index-2000, 0):min(index+2000, len(t))])]
print peaks  # includes 666 and 6666


来源: stackexchange

问:
Swift 3 button.addTarget not working on all table cells
I have created an app to allow users to store various voice recordings against reviews. When I display this a table and the data is populated with the following code:

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let row = (indexPath as NSIndexPath).item
    let cell = tableView.dequeueReusableCell(withIdentifier: "voiceRecordingCell", for: indexPath) as! VoiceRecordingTableViewCell
    let voiceRecording = self.voiceRecordings[row] as! NSDictionary

    let isoFormatter = DateFormatter()
    isoFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'.000Z'"
    let createdAt = isoFormatter.date(from: voiceRecording["created_at"] as! String)
    self.recordingIndexPaths.insert(indexPath, at: row)

    cell.recording = voiceRecording
    cell.date.text = getDateFormatter("dd-MM-y").string(from: createdAt!)
    cell.time.text = getDateFormatter("HH:mm").string(from: createdAt!)
    cell.length.text = voiceRecording["length"] as? String
    cell.location.text = voiceRecording["location"] as? String

    let audioPlayerController = self.storyboard?.instantiateViewController(withIdentifier: "AudioPlayerController") as! AudioPlayerController

    audioPlayerController.voiceRecording = voiceRecording

    cell.audioPlayer.addSubview(audioPlayerController.view)
    self.addChildViewController(audioPlayerController)
    audioPlayerController.didMove(toParentViewController: self)

    cell.deleteRecordingButton.tag = row
    cell.deleteRecordingButton.addTarget(self, action: #selector(deleteRecordingPressed(_:)), for: .touchUpInside)

    return cell
}
</code>```

The cells all appear to be rendering correctly however for the cells that are not initially rendered with the page, the ones I have to scroll down to view, when I click on the buttons either on the audio player controls or the deleteRecordingButton nothing happens, its as though the addTarget is not being set. The code to set the buttons is being called and doesn't create an error, its just not applying to those button.

The buttons that are initially displayed on the screen have the correct actions and all work perfectly so I know that works.

I'm really at a loss as to what is causing this. I did try searching google and stackoverflow but I've not found anything. Any assistance with this would be greatly received.

--------------- UPDATE -----------

I just tried putting some breakpoints in

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

}
</code>```

That also only works get called on the top 2 cells or the top one if in landscape!

答:
Since the cell gets reused all the time the reference get lost.
Try something like this:

```<code>class ButtonTableViewCell: UITableViewCell {

    typealias TapClosure = () -> Void

    var buttonTapped: TapClosure?

    @IBAction func buttonTouchUpInside(sender: UIButton) {
        buttonTapped?()
    }

}

extension TestViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) as! ButtonTableViewCell

        cell.buttonTapped = {
            print("Button tapped")
        }

        return cell
    }

}
</code>```

And another tipp. Never init an DateFormatter in cellForRowAtIndexPath. Instead create it in viewDidLoad or in a static struct for reuse.

ContentLicense: CC BY-SA 3.0

Body:
I have created an app to allow users to store various voice recordings against reviews. When I display this a table and the data is populated with the following code:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let row = (indexPath as NSIndexPath).item
    let cell = tableView.dequeueReusableCell(withIdentifier: "voiceRecordingCell", for: indexPath) as! VoiceRecordingTableViewCell
    let voiceRecording = self.voiceRecordings[row] as! NSDictionary

    let isoFormatter = DateFormatter()
    isoFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'.000Z'"
    let createdAt = isoFormatter.date(from: voiceRecording["created_at"] as! String)
    self.recordingIndexPaths.insert(indexPath, at: row)

    cell.recording = voiceRecording
    cell.date.text = getDateFormatter("dd-MM-y").string(from: createdAt!)
    cell.time.text = getDateFormatter("HH:mm").string(from: createdAt!)
    cell.length.text = voiceRecording["length"] as? String
    cell.location.text = voiceRecording["location"] as? String

    let audioPlayerController = self.storyboard?.instantiateViewController(withIdentifier: "AudioPlayerController") as! AudioPlayerController

    audioPlayerController.voiceRecording = voiceRecording

    cell.audioPlayer.addSubview(audioPlayerController.view)
    self.addChildViewController(audioPlayerController)
    audioPlayerController.didMove(toParentViewController: self)

    cell.deleteRecordingButton.tag = row
    cell.deleteRecordingButton.addTarget(self, action: #selector(deleteRecordingPressed(_:)), for: .touchUpInside)

    return cell
}

The cells all appear to be rendering correctly however for the cells that are not initially rendered with the page, the ones I have to scroll down to view, when I click on the buttons either on the audio player controls or the deleteRecordingButton nothing happens, its as though the addTarget is not being set. The code to set the buttons is being called and doesn't create an error, its just not applying to those button.

The buttons that are initially displayed on the screen have the correct actions and all work perfectly so I know that works.

I'm really at a loss as to what is causing this. I did try searching google and stackoverflow but I've not found anything. Any assistance with this would be greatly received.

--------------- UPDATE -----------

I just tried putting some breakpoints in

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

}

That also only works get called on the top 2 cells or the top one if in landscape!

Body:
Since the cell gets reused all the time the reference get lost.
Try something like this:

class ButtonTableViewCell: UITableViewCell {

    typealias TapClosure = () -> Void

    var buttonTapped: TapClosure?

    @IBAction func buttonTouchUpInside(sender: UIButton) {
        buttonTapped?()
    }

}

extension TestViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        let cell = tableView.dequeueReusableCell(withIdentifier: "identifier", for: indexPath) as! ButtonTableViewCell

        cell.buttonTapped = {
            print("Button tapped")
        }

        return cell
    }

}

And another tipp. Never init an DateFormatter in cellForRowAtIndexPath. Instead create it in viewDidLoad or in a static struct for reuse.


问:
Matplotlib, multiple scatter subplots with shared colour bar
I am trying to create a collection of scatter subplots and would like them to share the same colour bar.

I have followed the guidance here but it seems only applicable to plotting of images where the object has an autoscale property.

The code I am using is as follows:

```<code>import matplotlib.pyplot as plt
import numpy
import random

x = []
y = []

for i in range(100):
    x.append(random.normalvariate(100,10))
    y.append(random.normalvariate(100,10))

#Creates a list of length n
def getRand(n):
    l = []
    for i in range(n):
        l.append(random.normalvariate(1,10))
    return l

f = plt.figure()
f, axes = plt.subplots(nrows = 2, ncols = 2, sharex=True, sharey = True)

axes[0][0].scatter(getRand(100),getRand(100), c = getRand(100), marker = "x")
axes[0][0].set_xlabel('Crosses', labelpad = 5)

axes[0][1].scatter(getRand(100),getRand(100), c = getRand(100), marker = 'o')
axes[0][1].set_xlabel('Circles', labelpad = 5)

axes[1][0].scatter(getRand(100),getRand(100), c = getRand(100), marker = '*')
axes[1][0].set_xlabel('Stars')

axes[1][1].scatter(getRand(100),getRand(100), c = getRand(100), marker = 's' )
axes[1][1].set_xlabel('Squares')

#Add separate colourbar axes
cbar_ax = f.add_axes([0.85, 0.15, 0.05, 0.7])

#Autoscale none
f.colorbar(axes[0][0], cax=cbar_ax)

plt.show()
</code>```

This generates the error:

AttributeError: 'AxesSubplot' object has no attribute 'autoscale_None'

The problem is happening when I send the data to the colour bar here:

```<code>f.colorbar(axes[0][0], cax=cbar_ax)
</code>```

Here is the current output, Obviously I would like the colour of the markers to be on the scale bar to the right (I will worry about placing it correctly later):

Is there a away of achieving this for a group of scatter plots such as this and if so how can I modify my code to achieve it?

答:
The signature of figure.colorbar is

```<code>colorbar(mappable, cax=None, ax=None, use_gridspec=True, **kw)
</code>```

This means that the first argument must be a ScalarMappable, not an axes.

```<code>sc = axes[0][0].scatter(..)
fig.colorbar(sc, cax=cbar_ax)
</code>```

If you want to use the same colorbar for all scatterplots, you would need to use the same normalization for them all.

```<code>norm=plt.Normalize(-22,22)
sc = axes[0][0].scatter(getRand(100),getRand(100), c = getRand(100), norm=norm)
fig.colorbar(sc, cax=cbar_ax)
</code>```

A complete example:

```<code>import matplotlib.pyplot as plt
import numpy as np

def getRand(n):
    return np.random.normal(scale=10, size=n)

f = plt.figure()
f, axes = plt.subplots(nrows = 2, ncols = 2, sharex=True, sharey = True)
norm=plt.Normalize(-22,22)
sc = axes[0][0].scatter(getRand(100),getRand(100), c = getRand(100), marker = "x", norm=norm)
axes[0][0].set_xlabel('Crosses', labelpad = 5)

axes[0][1].scatter(getRand(100),getRand(100), c = getRand(100), marker = 'o', norm=norm)
axes[0][1].set_xlabel('Circles', labelpad = 5)

axes[1][0].scatter(getRand(100),getRand(100), c = getRand(100), marker = '*', norm=norm)
axes[1][0].set_xlabel('Stars')

axes[1][1].scatter(getRand(100),getRand(100), c = getRand(100), marker = 's', norm=norm )
axes[1][1].set_xlabel('Squares')

cbar_ax = f.add_axes([0.85, 0.15, 0.05, 0.7])

f.colorbar(sc, cax=cbar_ax)

plt.show()
</code>```

Body:
I am trying to create a collection of scatter subplots and would like them to share the same colour bar.

I have followed the guidance here but it seems only applicable to plotting of images where the object has an autoscale property.

The code I am using is as follows:

import matplotlib.pyplot as plt
import numpy
import random

x = []
y = []

for i in range(100):
    x.append(random.normalvariate(100,10))
    y.append(random.normalvariate(100,10))

#Creates a list of length n
def getRand(n):
    l = []
    for i in range(n):
        l.append(random.normalvariate(1,10))
    return l

f = plt.figure()
f, axes = plt.subplots(nrows = 2, ncols = 2, sharex=True, sharey = True)

axes[0][0].scatter(getRand(100),getRand(100), c = getRand(100), marker = "x")
axes[0][0].set_xlabel('Crosses', labelpad = 5)

axes[0][1].scatter(getRand(100),getRand(100), c = getRand(100), marker = 'o')
axes[0][1].set_xlabel('Circles', labelpad = 5)

axes[1][0].scatter(getRand(100),getRand(100), c = getRand(100), marker = '*')
axes[1][0].set_xlabel('Stars')

axes[1][1].scatter(getRand(100),getRand(100), c = getRand(100), marker = 's' )
axes[1][1].set_xlabel('Squares')

#Add separate colourbar axes
cbar_ax = f.add_axes([0.85, 0.15, 0.05, 0.7])

#Autoscale none
f.colorbar(axes[0][0], cax=cbar_ax)

plt.show()

This generates the error:

AttributeError: 'AxesSubplot' object has no attribute 'autoscale_None'

The problem is happening when I send the data to the colour bar here:

f.colorbar(axes[0][0], cax=cbar_ax)

Here is the current output, Obviously I would like the colour of the markers to be on the scale bar to the right (I will worry about placing it correctly later):

Is there a away of achieving this for a group of scatter plots such as this and if so how can I modify my code to achieve it?

Body:
The signature of figure.colorbar is

colorbar(mappable, cax=None, ax=None, use_gridspec=True, **kw)

This means that the first argument must be a ScalarMappable, not an axes.

sc = axes[0][0].scatter(..)
fig.colorbar(sc, cax=cbar_ax)

If you want to use the same colorbar for all scatterplots, you would need to use the same normalization for them all.

norm=plt.Normalize(-22,22)
sc = axes[0][0].scatter(getRand(100),getRand(100), c = getRand(100), norm=norm)
fig.colorbar(sc, cax=cbar_ax)

A complete example:

import matplotlib.pyplot as plt
import numpy as np

def getRand(n):
    return np.random.normal(scale=10, size=n)

f = plt.figure()
f, axes = plt.subplots(nrows = 2, ncols = 2, sharex=True, sharey = True)
norm=plt.Normalize(-22,22)
sc = axes[0][0].scatter(getRand(100),getRand(100), c = getRand(100), marker = "x", norm=norm)
axes[0][0].set_xlabel('Crosses', labelpad = 5)

axes[0][1].scatter(getRand(100),getRand(100), c = getRand(100), marker = 'o', norm=norm)
axes[0][1].set_xlabel('Circles', labelpad = 5)

axes[1][0].scatter(getRand(100),getRand(100), c = getRand(100), marker = '*', norm=norm)
axes[1][0].set_xlabel('Stars')

axes[1][1].scatter(getRand(100),getRand(100), c = getRand(100), marker = 's', norm=norm )
axes[1][1].set_xlabel('Squares')

cbar_ax = f.add_axes([0.85, 0.15, 0.05, 0.7])

f.colorbar(sc, cax=cbar_ax)

plt.show()


问:
JQuery create a form and add elements to it programmatically
Hi I need to create a form and add elements to it programatically.

```<code>$form = $("<form></form>");
$form.append("<input type=button value=button");
</code>```

this doesn't seem to work right.

答:
You need to append form itself to body too:

```<code>$form = $("<form></form>");
$form.append('<input type="button" value="button">');
$('body').append($form);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Hi I need to create a form and add elements to it programatically.

$form = $("<form></form>");
$form.append("<input type=button value=button");

this doesn't seem to work right.

Body:
You need to append form itself to body too:

$form = $("<form></form>");
$form.append('<input type="button" value="button">');
$('body').append($form);


问:
Javascript Concat Multidimensional Array
I am trying to concat a multidimensional array so I can iterate and display all the data.  There is a very good post on how to access nested data here, but I am looking for a solution that works with a specific data structure.

Here is my data:

```<code>var data = {
"Nike": [
    {
    "id": "1",
    "name": "test",
    "myimage": "image.gif"},

     {
    "id": "2",
    "name": "test",
    "myimage": "image.gif"}
],

"Adidas": [
    {
    "id": "3",
    "name": "Football Boots",
    "myimage": "image.gif"},

     {
    "id": "4",
    "name": "Running Shoes",
    "myimage": "image.gif"}
]}
</code>```

I seem to be able to get the values from the Nike array if I do this:

```<code>var result = data.Adidas;

for (var i = 0; i < result.length; i++) {
 var object = result[i];
 for (property in object) {
    var value = object[property];
    alert(property + "=" + value + "<br>");
 }
}
</code>```

However I would like to be able to display all the array items (id's 1-4).

What I have tried to do is:

```<code>var result = [].concat.apply([], data);
</code>```

... and loop over the result variable using the same for loop, but it doesn't work.

My ideal end result would be to display the four products under each brand name. I don't require to show the actual brand name itself.  For example:

```<code> "id": "1",
    "name": "test",
    "myimage": "image.gif"

 "id": "2",
    "name": "test",
    "myimage": "image.gif"

"id": "3",
    "name": "Football Boots",
    "myimage": "image.gif",

"id": "4",
    "name": "Running Shoes",
    "myimage": "image.gif"
</code>```

Any help appreciated.

Cheers

答:
An alternative to reduce would be a for in loop:

```<code>let res = [];
for (let key in data) res = res.concat(data[key]);
console.log(res);
</code>```

Body:
I am trying to concat a multidimensional array so I can iterate and display all the data.  There is a very good post on how to access nested data here, but I am looking for a solution that works with a specific data structure.

Here is my data:

var data = {
"Nike": [
    {
    "id": "1",
    "name": "test",
    "myimage": "image.gif"},

     {
    "id": "2",
    "name": "test",
    "myimage": "image.gif"}
],

"Adidas": [
    {
    "id": "3",
    "name": "Football Boots",
    "myimage": "image.gif"},

     {
    "id": "4",
    "name": "Running Shoes",
    "myimage": "image.gif"}
]}

I seem to be able to get the values from the Nike array if I do this:

var result = data.Adidas;

for (var i = 0; i < result.length; i++) {
 var object = result[i];
 for (property in object) {
    var value = object[property];
    alert(property + "=" + value + "
");
 }
}

However I would like to be able to display all the array items (id's 1-4).

What I have tried to do is:

var result = [].concat.apply([], data);

... and loop over the result variable using the same for loop, but it doesn't work.

My ideal end result would be to display the four products under each brand name. I don't require to show the actual brand name itself.  For example:

 "id": "1",
    "name": "test",
    "myimage": "image.gif"

 "id": "2",
    "name": "test",
    "myimage": "image.gif"

"id": "3",
    "name": "Football Boots",
    "myimage": "image.gif",

"id": "4",
    "name": "Running Shoes",
    "myimage": "image.gif"

Any help appreciated.

Cheers

Body:
An alternative to reduce would be a for in loop:

let res = [];
for (let key in data) res = res.concat(data[key]);
console.log(res);


问:
Can xcodebuild manage automatic signing?
SUMMARY:

If you open a project in Xcode 8 with "Automatically manage signing" enabled and a new bundle ID, it will automatically create and download a provisioning profile for it. But how can I make the same thing happen with xcodebuild, so I can use it on a remote build server?

DETAILS:

I'm trying to build a Cordova app on a Mac. Cordova configures the Xcode project to use "Automatically manage signing", so I'm trying to use that.

I change the bundle ID often, so I want Cordova to be able to build it with a new bundle ID, that hasn't been used before.

But when I run cordova build ios --release --device --buildConfig build.json, I get a return code 65 and the following error:

```<code>Check dependencies
No profiles for 'com.my.bundle.id' were found:  Xcode couldn't find a provisioning profile matching 'com.my.bundle.id'.
Code signing is required for product type 'Application' in SDK 'iOS 10.3'

** ARCHIVE FAILED **

The following build commands failed:
    Check dependencies
(1 failure)
Error: Error code 65 for command: xcodebuild with args: -xcconfig,/cordova-project/platforms/ios/cordova/build-debug.xcconfig,-workspace,MyApp.xcworkspace,-scheme,MyApp,-configuration,Debug,-destination,generic/platform=iOS,-archivePath,MyApp.xcarchive,archive,CONFIGURATION_BUILD_DIR=/cordova-project/platforms/ios/build/device,SHARED_PRECOMPS_DIR=/cordova-project/platforms/ios/build/sharedpch
</code>```

(I can manually run that xcodebuild command and get the same error, so it's probably not a Cordova issue.)

My build.json file looks like this:

```<code>{
    "ios": {
        "debug": {
            "codeSignIdentity": "iPhone Developer",
            "developmentTeam": "MY_TEAM_ID",
            "packageType": "development"
        },
        "release": {
            "codeSignIdentity": "iPhone Developer",
            "developmentTeam": "MY_TEAM_ID",
            "packageType": "enterprise"
        }
    }
}
</code>```

I'm using cordova 7.0.1, cordova-ios 4.4.0, Xcode 8.3.3, and MacOS 10.12.5. I have an Apple Enterprise account.

WHAT I TRIED:

If I open the generated project in Xcode, it fixes the automatic signing, and from then on I can run cordova successfully with that bundle ID. But if I try to run it with a different bundle ID, it will fail again.

I tried using security unlock-keychain ~/Library/Keychains/login.keychain-db first, since that's worked in the past, but it didn't help.

I also tried opening my private signing key in Keychain Access and setting it to "Allow all applications to access this item", without any luck.

I get the same error regardless of whether I pass --debug or --release to cordova.

答:
You can do it using fastlane.

https://fastlane.tools/

cert : Fetch or generate the latest available code signing identity

sigh : Generates a provisioning profile. Stores the profile in the current folder

ps : If you are running it from a CI server (for example jenkins) you need then to unlock login keychain :

```<code>security unlock-keychain -p PASSWORD /Users/YOUR-USER/Library/Keychains/login.keychain
</code>```

Example within the fastfile :

```<code>cert(
  development: true,
)

sigh(
  development: true,
  app_identifier: "YOUR_APP_IDENTIFIER"
)
</code>```

Here's an example of a basic Fastfile :

```<code>fastlane_version "2.27.0"
default_platform :ios

platform :ios do

lane :beta do
   cert
   sigh
   gym
end

error do |lane, exception|
  puts "Got an error! #{exception.error_info.to_s}"
end

end
</code>```

Body:
SUMMARY:

If you open a project in Xcode 8 with "Automatically manage signing" enabled and a new bundle ID, it will automatically create and download a provisioning profile for it. But how can I make the same thing happen with xcodebuild, so I can use it on a remote build server?

DETAILS:

I'm trying to build a Cordova app on a Mac. Cordova configures the Xcode project to use "Automatically manage signing", so I'm trying to use that.

I change the bundle ID often, so I want Cordova to be able to build it with a new bundle ID, that hasn't been used before.

But when I run cordova build ios --release --device --buildConfig build.json, I get a return code 65 and the following error:

Check dependencies
No profiles for 'com.my.bundle.id' were found:  Xcode couldn't find a provisioning profile matching 'com.my.bundle.id'.
Code signing is required for product type 'Application' in SDK 'iOS 10.3'

** ARCHIVE FAILED **

The following build commands failed:
    Check dependencies
(1 failure)
Error: Error code 65 for command: xcodebuild with args: -xcconfig,/cordova-project/platforms/ios/cordova/build-debug.xcconfig,-workspace,MyApp.xcworkspace,-scheme,MyApp,-configuration,Debug,-destination,generic/platform=iOS,-archivePath,MyApp.xcarchive,archive,CONFIGURATION_BUILD_DIR=/cordova-project/platforms/ios/build/device,SHARED_PRECOMPS_DIR=/cordova-project/platforms/ios/build/sharedpch

(I can manually run that xcodebuild command and get the same error, so it's probably not a Cordova issue.)

My build.json file looks like this:

{
    "ios": {
        "debug": {
            "codeSignIdentity": "iPhone Developer",
            "developmentTeam": "MY_TEAM_ID",
            "packageType": "development"
        },
        "release": {
            "codeSignIdentity": "iPhone Developer",
            "developmentTeam": "MY_TEAM_ID",
            "packageType": "enterprise"
        }
    }
}

I'm using cordova 7.0.1, cordova-ios 4.4.0, Xcode 8.3.3, and MacOS 10.12.5. I have an Apple Enterprise account.

WHAT I TRIED:

If I open the generated project in Xcode, it fixes the automatic signing, and from then on I can run cordova successfully with that bundle ID. But if I try to run it with a different bundle ID, it will fail again.

I tried using security unlock-keychain ~/Library/Keychains/login.keychain-db first, since that's worked in the past, but it didn't help.

I also tried opening my private signing key in Keychain Access and setting it to "Allow all applications to access this item", without any luck.

I get the same error regardless of whether I pass --debug or --release to cordova.

Body:
You can do it using fastlane.

https://fastlane.tools/

cert : Fetch or generate the latest available code signing identity

sigh : Generates a provisioning profile. Stores the profile in the current folder

ps : If you are running it from a CI server (for example jenkins) you need then to unlock login keychain :

security unlock-keychain -p PASSWORD /Users/YOUR-USER/Library/Keychains/login.keychain

Example within the fastfile :

cert(
  development: true,
)

sigh(
  development: true,
  app_identifier: "YOUR_APP_IDENTIFIER"
)

Here's an example of a basic Fastfile :

fastlane_version "2.27.0"
default_platform :ios

platform :ios do

lane :beta do
   cert
   sigh
   gym
end

error do |lane, exception|
  puts "Got an error! #{exception.error_info.to_s}"
end

end


问:
Delete all rows in an HTML table
How can I delete all rows of an HTML table except the 's using Javascript, and without looping through all the rows in the table? I have a very huge table and I don't want to freeze the UI while I'm looping through the rows to delete them

答:
If you can declare an ID for tbody you can simply run this function:

```<code>var node = document.getElementById("tablebody");
while (node.hasChildNodes()) {
  node.removeChild(node.lastChild);
}
</code>```

Title: Delete all rows in an HTML table

Body:
If you can declare an ID for tbody you can simply run this function:

var node = document.getElementById("tablebody");
while (node.hasChildNodes()) {
  node.removeChild(node.lastChild);
}


问:
HTML as a server-side programming language
I was reading a Wikipedia article when I came accross this page.

Can anyone explain to me the meaning of HTML used as a server-side programming language?

答: HTML is used for rendering contents of a web page.I am not sure if it can be used as a programming language.It is a markup language as I understand.</p>


问:
Convert database string to array
I have a field in one of my database tables, a sample of this field looks like so ; ["1","4","7"]. Those are keys to a reference in another table. What i want to do is fetch the field and ideally loop through the values and get the data from the referenced table. As you will notice, ["1","4","7"] is PHP declaration for an array but for the life of me, I am unable to parse it as an array. How do i parse it as an array? What am I missing?

答:
You should be able to decode and convert it into an array with PHP's json_decode function.

Example:

```<code><?php
echo '```';
print_r(json_decode('["1","4","7"]'));
echo '```';
?>
</code>```

ContentLicense: CC BY-SA 4.0

Title: Convert database string to array

Body:
You should be able to decode and convert it into an array with PHP's json_decode function.

Example:

<?php
echo '<pre>';
print_r(json_decode('["1","4","7"]'));
echo '</pre>';
?>


问:
Combining Union results with duplicate lines
I have the below SQL Query:

```<code>SELECT qryRef_Routes_tbl.Ref_Route_Name, qryRef_Routes_tbl.Ref_Route_ID, tblFMS_Data.FM_FinYear, tblFMS_Data.FM_Period,
 tblPeriod_Lookup.PL_ID, Sum(IIf([FM_TrustNo]=0 And [FM_Incident]=25 And [Ref_Fault_Valid_Combo]=-1,1,0)) AS Success,
 Sum(IIf([FM_Incident]=25 And [Ref_Fault_Valid_Combo]=-1,1,0)) AS CountPrevent
FROM
(
 (
  ( tblFMS_Data INNER JOIN qryRef_Routes_tbl ON tblFMS_Data.FM_Route = qryRef_Routes_tbl.Ref_Route_ID )
    INNER JOIN tblRCM_II_Assets ON tblFMS_Data.FM_EllipseNo = tblRCM_II_Assets.RI_Number
  )
  INNER JOIN tblPeriod_Lookup ON tblFMS_Data.FM_FinYear = tblPeriod_Lookup.PL_FinYear
   AND tblFMS_Data.FM_Period = tblPeriod_Lookup.PL_PeriodNo
)
INNER JOIN qryRef_Detectable_Failure_Valid_Combo ON tblFMS_Data.FM_Component2 = qryRef_Detectable_Failure_Valid_Combo.Ref_Fault_Comp2_ID
 AND tblFMS_Data.FM_Component = qryRef_Detectable_Failure_Valid_Combo.Ref_Fault_Comp1_ID
GROUP BY qryRef_Routes_tbl.Ref_Route_Name, qryRef_Routes_tbl.Ref_Route_ID, tblFMS_Data.FM_FinYear, tblFMS_Data.FM_Period, tblPeriod_Lookup.PL_ID
HAVING
(
 (
  tblPeriod_Lookup.PL_ID Between [Forms]![frmMainMenu]![PriorPeriodID] And
  ([Forms]![frmMainMenu]![PriorPeriodID]-12)
  )
)
UNION
SELECT qryRef_Routes_tbl.Ref_Route_Name, qryRef_Routes_tbl.Ref_Route_ID, tblFMS_Data.FM_FinYear, tblFMS_Data.FM_Period,
 tblPeriod_Lookup.PL_ID, Sum(IIf([FM_TrustNo]=0 And [FM_Incident]=25 And [Ref_Fault_Valid_Combo]=-1,1,0)) AS Success,
 Sum(IIf([FM_Incident]=25 And [Ref_Fault_Valid_Combo]=-1,1,0)) AS CountPrevent
FROM
(
 (
  ( tblFMS_Data INNER JOIN qryRef_Routes_tbl ON tblFMS_Data.FM_Route = qryRef_Routes_tbl.Ref_Route_ID)
    INNER JOIN tblRCM_II_Assets ON tblFMS_Data.FM_EllipseNo = tblRCM_II_Assets.RI_Pway_Number
  )
  INNER JOIN tblPeriod_Lookup ON tblFMS_Data.FM_FinYear = tblPeriod_Lookup.PL_FinYear
   AND tblFMS_Data.FM_Period = tblPeriod_Lookup.PL_PeriodNo
)
INNER JOIN qryRef_Detectable_Failure_Valid_Combo ON tblFMS_Data.FM_Component2 = qryRef_Detectable_Failure_Valid_Combo.Ref_Fault_Comp2_ID
 AND tblFMS_Data.FM_Component = qryRef_Detectable_Failure_Valid_Combo.Ref_Fault_Comp1_ID
GROUP BY qryRef_Routes_tbl.Ref_Route_Name, qryRef_Routes_tbl.Ref_Route_ID, tblFMS_Data.FM_FinYear, tblFMS_Data.FM_Period, tblPeriod_Lookup.PL_ID
HAVING
(
 (
   tblPeriod_Lookup.PL_ID Between [Forms]![frmMainMenu]![PriorPeriodID] And [Forms]![frmMainMenu]![PriorPeriodID]-12
  )
);
</code>```

The results from this are duplicated.  I want the results of the duplicated lines to be combined.

Note the Join queries are slightly different in the 2 queries being Union'd

答: Use UNION DISTINCT if you do not want duplicated values

Body:
I have the below SQL Query:

SELECT qryRef_Routes_tbl.Ref_Route_Name, qryRef_Routes_tbl.Ref_Route_ID, tblFMS_Data.FM_FinYear, tblFMS_Data.FM_Period,
 tblPeriod_Lookup.PL_ID, Sum(IIf([FM_TrustNo]=0 And [FM_Incident]=25 And [Ref_Fault_Valid_Combo]=-1,1,0)) AS Success,
 Sum(IIf([FM_Incident]=25 And [Ref_Fault_Valid_Combo]=-1,1,0)) AS CountPrevent
FROM
(
 (
  ( tblFMS_Data INNER JOIN qryRef_Routes_tbl ON tblFMS_Data.FM_Route = qryRef_Routes_tbl.Ref_Route_ID )
    INNER JOIN tblRCM_II_Assets ON tblFMS_Data.FM_EllipseNo = tblRCM_II_Assets.RI_Number
  )
  INNER JOIN tblPeriod_Lookup ON tblFMS_Data.FM_FinYear = tblPeriod_Lookup.PL_FinYear
   AND tblFMS_Data.FM_Period = tblPeriod_Lookup.PL_PeriodNo
)
INNER JOIN qryRef_Detectable_Failure_Valid_Combo ON tblFMS_Data.FM_Component2 = qryRef_Detectable_Failure_Valid_Combo.Ref_Fault_Comp2_ID
 AND tblFMS_Data.FM_Component = qryRef_Detectable_Failure_Valid_Combo.Ref_Fault_Comp1_ID
GROUP BY qryRef_Routes_tbl.Ref_Route_Name, qryRef_Routes_tbl.Ref_Route_ID, tblFMS_Data.FM_FinYear, tblFMS_Data.FM_Period, tblPeriod_Lookup.PL_ID
HAVING
(
 (
  tblPeriod_Lookup.PL_ID Between [Forms]![frmMainMenu]![PriorPeriodID] And
  ([Forms]![frmMainMenu]![PriorPeriodID]-12)
  )
)
UNION
SELECT qryRef_Routes_tbl.Ref_Route_Name, qryRef_Routes_tbl.Ref_Route_ID, tblFMS_Data.FM_FinYear, tblFMS_Data.FM_Period,
 tblPeriod_Lookup.PL_ID, Sum(IIf([FM_TrustNo]=0 And [FM_Incident]=25 And [Ref_Fault_Valid_Combo]=-1,1,0)) AS Success,
 Sum(IIf([FM_Incident]=25 And [Ref_Fault_Valid_Combo]=-1,1,0)) AS CountPrevent
FROM
(
 (
  ( tblFMS_Data INNER JOIN qryRef_Routes_tbl ON tblFMS_Data.FM_Route = qryRef_Routes_tbl.Ref_Route_ID)
    INNER JOIN tblRCM_II_Assets ON tblFMS_Data.FM_EllipseNo = tblRCM_II_Assets.RI_Pway_Number
  )
  INNER JOIN tblPeriod_Lookup ON tblFMS_Data.FM_FinYear = tblPeriod_Lookup.PL_FinYear
   AND tblFMS_Data.FM_Period = tblPeriod_Lookup.PL_PeriodNo
)
INNER JOIN qryRef_Detectable_Failure_Valid_Combo ON tblFMS_Data.FM_Component2 = qryRef_Detectable_Failure_Valid_Combo.Ref_Fault_Comp2_ID
 AND tblFMS_Data.FM_Component = qryRef_Detectable_Failure_Valid_Combo.Ref_Fault_Comp1_ID
GROUP BY qryRef_Routes_tbl.Ref_Route_Name, qryRef_Routes_tbl.Ref_Route_ID, tblFMS_Data.FM_FinYear, tblFMS_Data.FM_Period, tblPeriod_Lookup.PL_ID
HAVING
(
 (
   tblPeriod_Lookup.PL_ID Between [Forms]![frmMainMenu]![PriorPeriodID] And [Forms]![frmMainMenu]![PriorPeriodID]-12
  )
);

The results from this are duplicated.  I want the results of the duplicated lines to be combined.

Note the Join queries are slightly different in the 2 queries being Union'd


问:
Why is toggleClass not working here?
I'm trying to add / remove a class on click here, but toggleClass is not working as I'm expecting it to. On the contrary, addClass works fine, but I need it to remove the class on the second click.

```<code>$('.label1').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');
    $(this).toggleClass('checked');
    $checkItem.prop("checked", !$checkItem.prop("checked"));
})

$('.label2').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');
    $(this).addClass('checked');
    $checkItem.prop("checked", !$checkItem.prop("checked"));
})
</code>```

Can you tell me what am I doing wrong?

See it in action here: Test jquery.

Thanks!

答:
This is a compact solution

```<code>$('input[type=checkbox].BorderRed').change(function() {
      $($(this).parent()).toggleClass('checked');
});
</code>```

NEW checkbox Object,

if you wont the effect

```<code>  <div class="checkbox">
    <label class="label2">
      <input class="BorderRed" type="checkbox">
      Check me out
    </label>
  </div>
</code>```

if you dont wont the effect

```<code>  <div class="checkbox">
    <label class="label2">
      <input type="checkbox">
      Check me out
    </label>
  </div>
</code>```

Title: Why is toggleClass not working here?

Body:
I'm trying to add / remove a class on click here, but toggleClass is not working as I'm expecting it to. On the contrary, addClass works fine, but I need it to remove the class on the second click.

$('.label1').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');
    $(this).toggleClass('checked');
    $checkItem.prop("checked", !$checkItem.prop("checked"));
})

$('.label2').on('click', function() {
    var $checkItem = $(this).find('input[type=checkbox]');
    $(this).addClass('checked');
    $checkItem.prop("checked", !$checkItem.prop("checked"));
})

Can you tell me what am I doing wrong?

See it in action here: Test jquery.

Thanks!

Body:
This is a compact solution

$('input[type=checkbox].BorderRed').change(function() {
      $($(this).parent()).toggleClass('checked');
});

NEW checkbox Object,

if you wont the effect

  <div class="checkbox">
    <label class="label2">
      <input class="BorderRed" type="checkbox">
      Check me out
    </label>
  </div>

if you dont wont the effect

  <div class="checkbox">
    <label class="label2">
      <input type="checkbox">
      Check me out
    </label>
  </div>


问:
How to pass fragment from fragment manager to viewpager inside dashboard activity
I need to give horizontal swipe navigation to custom tab layout. I think this code snippet will help you to fix the issue. There are 3 fragments attached to viewpageradapter. I have declared the viewpager object of the Viewpager class but the problem still exists.</p>

```<code>public class DashboardActivity extends AppCompatActivity {

//    private SectionsPagerAdapter mSectionsPagerAdapter;
//    private ViewPager mViewPager;

    ViewPagerAdapter viewPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("Toolbar");
        setSupportActionBar(toolbar);
        TabLayout tabLayout;
        ViewPager viewPager;
        tabLayout=(TabLayout) findViewById(R.id.tabs);
        viewPager=(ViewPager)findViewById(R.id.ViewPager);

        viewPager= new ViewPagerAdapter(getSupportFragmentManager());
        viewPagerAdapter.addFragments(new HomeFragment(),"HOME");
        viewPagerAdapter.addFragments(new TopPaidFragment(),"TOP PAID");
        viewPagerAdapter.addFragments(new TopFreeFragment(),"TOP FREE");

        viewPager = (ViewPager)findViewById(R.id.ViewPager);
        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_dashboard, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:

                return true;

            case R.id.add_pic:

                return true;
            case R.id.Add_Story:

                return true;
            case R.id.delete:

                return true;
            case R.id.home:
                NavUtils.navigateUpFromSameTask(this);

            default:`enter code here`
                // If we got here, the user's action was not recognized.
                // Invoke the superclass to handle it.
                return super.onOptionsItemSelected(item);

        }
    }

}

`enter code here`layout_xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"
        android:id="@+id/appBarLayout">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill"
            />
        <android.support.v4.view.ViewPager
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:id="@+id/ViewPager"/>

    </android.support.design.widget.AppBarLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/floatingActionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="42dp"
        android:layout_marginEnd="33dp"
        android:layout_marginRight="33dp"
        android:clickable="true"
        app:backgroundTint="@android:color/primary_text_dark"
        app:fabSize="mini"
        app:srcCompat="@drawable/ic_plus_circle"
        android:hint="@string/add_story"/>

</RelativeLayout>
</code>```

答:
You are trying to set adapter object to viewpager

change this line

viewPager= new ViewPagerAdapter(getSupportFragmentManager());

to

viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

Body:
I need to give horizontal swipe navigation to custom tab layout. I think this code snippet will help you to fix the issue. There are 3 fragments attached to viewpageradapter. I have declared the viewpager object of the Viewpager class but the problem still exists.

public class DashboardActivity extends AppCompatActivity {

//    private SectionsPagerAdapter mSectionsPagerAdapter;
//    private ViewPager mViewPager;

    ViewPagerAdapter viewPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("Toolbar");
        setSupportActionBar(toolbar);
        TabLayout tabLayout;
        ViewPager viewPager;
        tabLayout=(TabLayout) findViewById(R.id.tabs);
        viewPager=(ViewPager)findViewById(R.id.ViewPager);

        viewPager= new ViewPagerAdapter(getSupportFragmentManager());
        viewPagerAdapter.addFragments(new HomeFragment(),"HOME");
        viewPagerAdapter.addFragments(new TopPaidFragment(),"TOP PAID");
        viewPagerAdapter.addFragments(new TopFreeFragment(),"TOP FREE");

        viewPager = (ViewPager)findViewById(R.id.ViewPager);
        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_dashboard, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_settings:

                return true;

            case R.id.add_pic:

                return true;
            case R.id.Add_Story:

                return true;
            case R.id.delete:

                return true;
            case R.id.home:
                NavUtils.navigateUpFromSameTask(this);

            default:`enter code here`
                // If we got here, the user's action was not recognized.
                // Invoke the superclass to handle it.
                return super.onOptionsItemSelected(item);

        }
    }

}

`enter code here`layout_xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay"
        android:id="@+id/appBarLayout">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />
        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabMode="fixed"
            app:tabGravity="fill"
            />
        <android.support.v4.view.ViewPager
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:id="@+id/ViewPager"/>

    </android.support.design.widget.AppBarLayout>

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/floatingActionButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="42dp"
        android:layout_marginEnd="33dp"
        android:layout_marginRight="33dp"
        android:clickable="true"
        app:backgroundTint="@android:color/primary_text_dark"
        app:fabSize="mini"
        app:srcCompat="@drawable/ic_plus_circle"
        android:hint="@string/add_story"/>

</RelativeLayout>


问:
Angular2 composure
I'm looking into microservices and to be more exact Angular2 microservices. The main idea seems easy enough but it gets complicated as I want to make a composure of different Angular2 apps.

What I mean by this, imagine I have 2 apps which I don't have a lot of control over, app A and app B, created by different teams, each one serving a different thing (one might be a 2D viewer, the other a 3D viewer). I was thinking of building some kind of composition proxy in which I define a html file with some custom tags such as <service target = "url"> and then have the proxy make a composition and serve it to the user.

I've been researching the web for a while now and I can't seem to find anything on angular2 compositions. Here are a few of the problems I encountered :

The order of the included scripts. Since each app might require different scripts to be included, not including them in the right order might crash the entire app.

Building a totally new "core" component that is properly bootstrapped, having only the right components being bootstrapped and all that.

Making sure css from one app doesn't overwrite css from the other

Naming issues, since apps are different I might encounter components with the same name.

All those issues seem fixable to me by just parsing every file and modifying it accordingly. Problem is the same idea won't exactly work if the js files are both minified and unified. Also it would take a lot of processing power to do this for every request (I'd like it to be a bit hot-builded/loaded).

What are some ways I should go about building such a composition proxy and is there any examples/documentation on how to do this?

答:
I am not sure I understand what you want to do but I can see from your requirement all you need is out of the box Angular2 functionality.

1) The order of the included scripts. Since each app might require
  different scripts to be included, not including them in the right
  order might crash the entire app.

2) Building a totally new "core"
  component that is properly bootstrapped, having only the right
  components being bootstrapped and all that.

3) Making sure css from one
  app doesn't overwrite css from the other Naming issues, since apps are
  different I might encounter components with the same name

I'll answer to your points:

1) You just use dynamic module loading in you "app-routing", like the following:

```<code>export function loadModuleA() {
    return System.import('./pages/module-A-view/a.module').then(mod => mod.ModuleA)
}

export function loadModuleB() {
    return System.import('./pages/module-B-view/a.module').then(mod => mod.ModuleA)
}

export const routes: Routes = [
    {
        path: 'core/sectionA',
        loadChildren: loadModuleA
    },
     {
        path: 'core/sectionB',
        loadChildren: loadModuleB
    },
</code>```

If you import a library in ModuleA is not going to be available in ModuleB unless you explicitly export it each module A and module B will have their own dependencies

2) you specify your "core" as you main app.module.tsand module dependencies in their own module file, simple.

3) you only need a main stylesheet really, then every component can have their custom files. If you use angular cli, for example every time you create a new component, the cli will generate the component file, the scss file, the html file and the spec file. Otherwise you can just as easily do it yourself:

```<code>@Component({
    selector: 'whatever',
    templateUrl: './whatever.component.html',
    styleUrls: [ './whatever.component.scss' ]
})
export class WhateverComponent
</code>```

If you instead wanted a StyleSheet specific to all components of (let's say) Module A, then I don't know how to do that.

Title: Angular2 composure

Body:
I am not sure I understand what you want to do but I can see from your requirement all you need is out of the box Angular2 functionality.

1) The order of the included scripts. Since each app might require
  different scripts to be included, not including them in the right
  order might crash the entire app.

2) Building a totally new "core"
  component that is properly bootstrapped, having only the right
  components being bootstrapped and all that.

3) Making sure css from one
  app doesn't overwrite css from the other Naming issues, since apps are
  different I might encounter components with the same name

I'll answer to your points:

1) You just use dynamic module loading in you "app-routing", like the following:

export function loadModuleA() {
    return System.import('./pages/module-A-view/a.module').then(mod => mod.ModuleA)
}

export function loadModuleB() {
    return System.import('./pages/module-B-view/a.module').then(mod => mod.ModuleA)
}

export const routes: Routes = [
    {
        path: 'core/sectionA',
        loadChildren: loadModuleA
    },
     {
        path: 'core/sectionB',
        loadChildren: loadModuleB
    },

If you import a library in ModuleA is not going to be available in ModuleB unless you explicitly export it each module A and module B will have their own dependencies

2) you specify your "core" as you main app.module.tsand module dependencies in their own module file, simple.

3) you only need a main stylesheet really, then every component can have their custom files. If you use angular cli, for example every time you create a new component, the cli will generate the component file, the scss file, the html file and the spec file. Otherwise you can just as easily do it yourself:

@Component({
    selector: 'whatever',
    templateUrl: './whatever.component.html',
    styleUrls: [ './whatever.component.scss' ]
})
export class WhateverComponent

If you instead wanted a StyleSheet specific to all components of (let's say) Module A, then I don't know how to do that.


答:
The tag is not closed:

```<code>$form.append("<input type=button value=button");
</code>```

Should be:

```<code>$form.append('<input type="button" value="button">');
</code>```

Title: JQuery create a form and add elements to it programmatically

Body:
The tag is not closed:

$form.append("<input type=button value=button");

Should be:

$form.append('<input type="button" value="button">');


问:
Implementation of virtual functions from a third party class
Summary

I want to design a class which will hold all my problem data so that its member functions can be used to pass information to the third party member functions. How can I do it for the below two functions?

My Problem:

I'm coding a program for scientific computation. To solve my problem I have to use some third party libraries. Currently I'm using Ipopt (for numerical optimization).

To use Ipopt, I have to provide enough information in the following way.

First I need to create a class which should inherit the third party class TNLP.

Then I have to provide implementation to the 8 virtual functions, of which two of them is as below with its implementation.

```<code>// MyNLP is the class which I coded to inherit from TNLP.
bool MyNLP::get_starting_point(Index n, bool init_x, Number* x,
                           bool init_z, Number* z_L, Number* z_U,
                           Index m, bool init_lambda,
                           Number* lambda)
{
   // Here, we assume we only have starting values for x, if you code
   // your own NLP, you can provide starting values for the others if
   // you wish.
    assert(init_x == true);
    assert(init_z == false);
    assert(init_lambda == false);

   // we initialize x in bounds, in the upper right quadrant
    x[0]=0.5;
    x[1]=1.5;
    return true;
}
</code>```

and

```<code>bool MyNLP::eval_f(Index n, const Number* x, bool new_x, Number&
obj_value)
{
    // return the value of the objective function
   Number x2 = x[1];
   obj_value = -(x2 - 2.0) * (x2 - 2.0);
   return true;
}
</code>```

In the above implementations I've provided values to the parameters within the function call directly. Now to make the program more general, instead of directly entering the required information in the above functions, I wish to use a class which contain all the information regarding my problem and use function members in the third party virtual function.

For example, if NLP is the class which hold my problem content and m_nlp is its incident in the class MyNLP then I'll rewrite the virtual functions as below.

```<code>bool MyNLP::get_starting_point(Index n, bool init_x, Number* x,
                           bool init_z, Number* z_L, Number* z_U,
                           Index m, bool init_lambda,
                           Number* lambda)
{
   // Here, we assume we only have starting values for x, if you code
   // your own NLP, you can provide starting values for the others if
   // you wish.
    assert(init_x == true);
    assert(init_z == false);
    assert(init_lambda == false);

    x = m_nlp->get_initial_values();

}
</code>```

and

```<code>bool MyNLP::eval_f(Index n, const Number* x, bool new_x, Number&
obj_value)
{
    // return the value of the objective function
    obj_value = m_nlp->get_obj_value();
}
</code>```

But I cannot do this in the above fashion, since  second function uses x to calculate object_val. How can I design a class to hold all the data and uses its member functions to give required information to Ipopt.

What I thought as a solution:

define a std::vector<Number> values as a member of nlp class and point the x to the first element of the values.

```<code> x = &(m_nlp->get_values()).at(0);
</code>```

in the second function, I can modify values instead of x and calculate obj_val.

答:
You could derive a class from MyNLP.  Or

```<code>class NLPWithStuff : public MyNLP {
   //...
   virtual bool get_starting_point(/*...*/)
    {
        // optional boost::signals that do their stuff ??
        // do my stuff, set flags so that no-one touches my stuff
        // don't assert

        return MyNLP::get_starting_point(/*.+.*/);
    }
};
</code>```

You'll have to declare MyNLP::get_starting_point virtual to make it work.

Body:
Summary

I want to design a class which will hold all my problem data so that its member functions can be used to pass information to the third party member functions. How can I do it for the below two functions?

My Problem:

I'm coding a program for scientific computation. To solve my problem I have to use some third party libraries. Currently I'm using Ipopt (for numerical optimization).

To use Ipopt, I have to provide enough information in the following way.

First I need to create a class which should inherit the third party class TNLP.

Then I have to provide implementation to the 8 virtual functions, of which two of them is as below with its implementation.

// MyNLP is the class which I coded to inherit from TNLP.
bool MyNLP::get_starting_point(Index n, bool init_x, Number* x,
                           bool init_z, Number* z_L, Number* z_U,
                           Index m, bool init_lambda,
                           Number* lambda)
{
   // Here, we assume we only have starting values for x, if you code
   // your own NLP, you can provide starting values for the others if
   // you wish.
    assert(init_x == true);
    assert(init_z == false);
    assert(init_lambda == false);

   // we initialize x in bounds, in the upper right quadrant
    x[0]=0.5;
    x[1]=1.5;
    return true;
}

and

bool MyNLP::eval_f(Index n, const Number* x, bool new_x, Number&
obj_value)
{
    // return the value of the objective function
   Number x2 = x[1];
   obj_value = -(x2 - 2.0) * (x2 - 2.0);
   return true;
}

In the above implementations I've provided values to the parameters within the function call directly. Now to make the program more general, instead of directly entering the required information in the above functions, I wish to use a class which contain all the information regarding my problem and use function members in the third party virtual function.

For example, if NLP is the class which hold my problem content and m_nlp is its incident in the class MyNLP then I'll rewrite the virtual functions as below.

bool MyNLP::get_starting_point(Index n, bool init_x, Number* x,
                           bool init_z, Number* z_L, Number* z_U,
                           Index m, bool init_lambda,
                           Number* lambda)
{
   // Here, we assume we only have starting values for x, if you code
   // your own NLP, you can provide starting values for the others if
   // you wish.
    assert(init_x == true);
    assert(init_z == false);
    assert(init_lambda == false);

    x = m_nlp->get_initial_values();

}

and

bool MyNLP::eval_f(Index n, const Number* x, bool new_x, Number&
obj_value)
{
    // return the value of the objective function
    obj_value = m_nlp->get_obj_value();
}

But I cannot do this in the above fashion, since  second function uses x to calculate object_val. How can I design a class to hold all the data and uses its member functions to give required information to Ipopt.

What I thought as a solution:

define a std::vector<Number> values as a member of nlp class and point the x to the first element of the values.

 x = &(m_nlp->get_values()).at(0);

in the second function, I can modify values instead of x and calculate obj_val.

Body:
You could derive a class from MyNLP.  Or

class NLPWithStuff : public MyNLP {
   //...
   virtual bool get_starting_point(/*...*/)
    {
        // optional boost::signals that do their stuff ??
        // do my stuff, set flags so that no-one touches my stuff
        // don't assert

        return MyNLP::get_starting_point(/*.+.*/);
    }
};

You'll have to declare MyNLP::get_starting_point virtual to make it work.


问:
How should I close a socket in a signal handler?
I'm writing a very simple server that loops forever until Ctrl-C is pressed. I'd like to have the signal handler for ctrl-c close the open sockets and shut down the server, but I don't know what the scope is for a signal handler, and I don't like the idea of declaring the socket(s) I would need to close to be global.

Can someone offer suggestions? Is there some standard way to do this?

答:
Normally, it's advisable not to do anything much in a signal handler; other than set a flag.

Then when control returns to your main loop you can examine this flag, exit the loop, close sockets, run destructors on your objects etc, and exit cleanly.

Signal handlers can get called at almost any time, including in the middle of C or C++ library calls, which could be a problem.

OwnerDisplayName: Zxaos

LastEditorDisplayName: Greg Hewgill

OwnerDisplayName: MarkR


问:
With regards to urllib AttributeError: 'module' object has no attribute 'urlopen'
```<code>import re
import string
import shutil
import os
import os.path
import time
import datetime
import math
import urllib
from array import array
import random

filehandle = urllib.urlopen('http://www.google.com/') #open webpage
s = filehandle.read() #read
print s #display

#what i plan to do with it once i get the first part working
#results = re.findall('[<td style="font-weight:bold;" nowrap>$][0-9][0-9][0-9][.][0-9][0-9][</td></tr></tfoot></table>]',s)
#earnings = '$ '
#for money in results:
#earnings = earnings + money[1]+money[2]+money[3]+'.'+money[5]+money[6]
#print earnings
#raw_input()
</code>```

this is the code that i have so far. now i have looked at all the other forums that give solutions such as the name of the script, which is parse_Money.py, and i have tried doing it with urllib.request.urlopen AND i have tried running it on python 2.5, 2.6, and 2.7. If anybody has any suggestions it would be really welcome, thanks everyone!!
--Matt

---EDIT---
I also tried this code and it worked, so im thinking its some kind of syntax error, so if anybody with a sharp eye can point it out, i would be very appreciative.

```<code>import shutil
import os
import os.path
import time
import datetime
import math
import urllib
from array import array
import random
b = 3

#find URL
URL = raw_input('Type the URL you would like to read from[Example: http://www.google.com/] :')

while b == 3:
    #get file name
    file1 = raw_input('Enter a file name for the downloaded code:')
    filepath = file1 + '.txt'
    if os.path.isfile(filepath):
        print 'File already exists'
        b = 3
    else:
        print 'Filename accepted'
        b = 4

file_path = filepath
#open file
FileWrite = open(file_path, 'a')

#acces URL
filehandle = urllib.urlopen(URL)

#display souce code
for lines in filehandle.readlines():
    FileWrite.write(lines)
    print lines
print 'The above has been saved in both a text and html file'

#close files
filehandle.close()
FileWrite.close()
</code>```

答: The urlopen function is actually in the urllib2 module.  Try import urllib2 and use urllib2.urlopen</p>

Body:
import re
import string
import shutil
import os
import os.path
import time
import datetime
import math
import urllib
from array import array
import random

filehandle = urllib.urlopen('http://www.google.com/') #open webpage
s = filehandle.read() #read
print s #display

#what i plan to do with it once i get the first part working
#results = re.findall('[$][0-9][0-9][0-9][.][0-9][0-9][

]',s)
#earnings = '$ '
#for money in results:
#earnings = earnings + money[1]+money[2]+money[3]+'.'+money[5]+money[6]
#print earnings
#raw_input()

this is the code that i have so far. now i have looked at all the other forums that give solutions such as the name of the script, which is parse_Money.py, and i have tried doing it with urllib.request.urlopen AND i have tried running it on python 2.5, 2.6, and 2.7. If anybody has any suggestions it would be really welcome, thanks everyone!!
--Matt

---EDIT---
I also tried this code and it worked, so im thinking its some kind of syntax error, so if anybody with a sharp eye can point it out, i would be very appreciative.

import shutil
import os
import os.path
import time
import datetime
import math
import urllib
from array import array
import random
b = 3

#find URL
URL = raw_input('Type the URL you would like to read from[Example: http://www.google.com/] :')

while b == 3:
    #get file name
    file1 = raw_input('Enter a file name for the downloaded code:')
    filepath = file1 + '.txt'
    if os.path.isfile(filepath):
        print 'File already exists'
        b = 3
    else:
        print 'Filename accepted'
        b = 4

file_path = filepath
#open file
FileWrite = open(file_path, 'a')

#acces URL
filehandle = urllib.urlopen(URL)

#display souce code
for lines in filehandle.readlines():
    FileWrite.write(lines)
    print lines
print 'The above has been saved in both a text and html file'

#close files
filehandle.close()
FileWrite.close()


问:
PySide\PyQt - Menu Add Action at index (before or between)
I'm creating a custom context menu for a widget in PySide, and I want to preserve Standard menu options, but I want to put them after custom actions.

Is there a way to add actions to QMenu and set specific order for them?

Here's my current code:

```<code>def buildRightClickMenu(self):

    self.textBox.setContextMenuPolicy(Qt.CustomContextMenu)
    self.textBox.customContextMenuRequested.connect(self.contextMenuRequested)

    self.actionSave = QAction(self)
    self.actionSave.setText("Save File")
    self.actionSave.triggered.connect(self.saveFile)

    self.actionOpen = QAction(self)
    self.actionOpen.setText("Open File")
    self.actionOpen.triggered.connect(self.openFile)

    self.menu = self.textBox.createStandardContextMenu()

    self.menu.addSeparator()
    self.menu.addAction(self.actionOpen)
</code>```

As expected, this first creates default menu options, and adds a separator and actionOpen afterwards. I want to put actionOpen at the start of the context menu, followed by default actions for the widget.

答:
It is PySide.QtGui.QWidget.insertAction(before, action), in QWidget class.

PySide - Insert action

Body:
I'm creating a custom context menu for a widget in PySide, and I want to preserve Standard menu options, but I want to put them after custom actions.

Is there a way to add actions to QMenu and set specific order for them?

Here's my current code:

def buildRightClickMenu(self):

    self.textBox.setContextMenuPolicy(Qt.CustomContextMenu)
    self.textBox.customContextMenuRequested.connect(self.contextMenuRequested)

    self.actionSave = QAction(self)
    self.actionSave.setText("Save File")
    self.actionSave.triggered.connect(self.saveFile)

    self.actionOpen = QAction(self)
    self.actionOpen.setText("Open File")
    self.actionOpen.triggered.connect(self.openFile)

    self.menu = self.textBox.createStandardContextMenu()

    self.menu.addSeparator()
    self.menu.addAction(self.actionOpen)

As expected, this first creates default menu options, and adds a separator and actionOpen afterwards. I want to put actionOpen at the start of the context menu, followed by default actions for the widget.


答:
If I understood your problem is that your database column store a string PHP array representation.

So you should use the function json_decode

By the way it's a strange way to store relation in a database

Title: Convert database string to array

Body: I have a field in one of my database tables, a sample of this field looks like so ; ["1","4","7"]. Those are keys to a reference in another table. What i want to do is fetch the field and ideally loop through the values and get the data from the referenced table. As you will notice, ["1","4","7"] is PHP declaration for an array but for the life of me, I am unable to parse it as an array. How do i parse it as an array? What am I missing?


问:
Trust anchor for certification path not found error with AeroGear PushPlugin and cordova android platform
I am creating a android  application with cordova and AeroGear PushPlugin  which uses https for communication with the unified push server.I use a valid CA certification support (TLS1.2) in my server.

When executing with  cordova run android return this error in my device :

error javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

knowing, i added the certificat in:

platforms/android/res/raw/myCert.crt

And this tag in the config.xml:

```<code>  <platform name="android">
    <network-security-config>
        <base-config cleartextTrafficPermitted="true">
            <trust-anchors>
                <certificates src="myCert.crt" />
            </trust-anchors>
        </base-config>
    </network-security-config>
    </platform>
</code>```

I followed several solutions proposed but dosen't work for my case.

thanks for Help.

答:
it was certificat generation problem in the UPS widfly server.

If you have certification authority CA delivered by trsut provider.

Follow the steps:

1- You must first convert the PEM certificate delivered by your provider to p12 with this command:

```<code>$ openssl pkcs12 -export -out yourCertificategenerate.p12 -inkey yourCertificatekey.key  -in certifacteDelivedFromProvider.pem -certfile yourCertificateFromProvider.pem // file contains -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----)
</code>```

2- create the local keystore with this commande will be (yourCertificategenerate.jks), and copy it to the standalone/configuration directory with this command:

```<code>$ keytool -importkeystore -deststorepass yourpassword -destkeypass yourpassword -destkeystore yourNewCertificateGenerate.jks -srckeystore yourCertificateGenerate.p12 -srcstoretype PKCS12 -srcstorepass ""
</code>```

To check the certification chain

```<code>openssl s_client -connect yourDomaine.com -debug
</code>```

if all things is ok you should have something like this :

Body:
I am creating a android  application with cordova and AeroGear PushPlugin  which uses https for communication with the unified push server.I use a valid CA certification support (TLS1.2) in my server.

When executing with  cordova run android return this error in my device :

error javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

knowing, i added the certificat in:

platforms/android/res/raw/myCert.crt

And this tag in the config.xml:

  <platform name="android">
    <network-security-config>
        <base-config cleartextTrafficPermitted="true">
            <trust-anchors>
                <certificates src="myCert.crt" />
            </trust-anchors>
        </base-config>
    </network-security-config>
    </platform>

I followed several solutions proposed but dosen't work for my case.

thanks for Help.

Body:
it was certificat generation problem in the UPS widfly server.

If you have certification authority CA delivered by trsut provider.

Follow the steps:

1- You must first convert the PEM certificate delivered by your provider to p12 with this command:

$ openssl pkcs12 -export -out yourCertificategenerate.p12 -inkey yourCertificatekey.key  -in certifacteDelivedFromProvider.pem -certfile yourCertificateFromProvider.pem // file contains -----BEGIN CERTIFICATE----- ... -----END CERTIFICATE-----)

2- create the local keystore with this commande will be (yourCertificategenerate.jks), and copy it to the standalone/configuration directory with this command:

$ keytool -importkeystore -deststorepass yourpassword -destkeypass yourpassword -destkeystore yourNewCertificateGenerate.jks -srckeystore yourCertificateGenerate.p12 -srcstoretype PKCS12 -srcstorepass ""

To check the certification chain

openssl s_client -connect yourDomaine.com -debug

if all things is ok you should have something like this :


问:
How to delete lines matching a pattern from a file using Tcl/Expect
I am trying to understand how to work with expect.

I want to check if a file has a certain string in it and if it does contain it than delete the whole line, i know how i would do that with bash with if and grep, but im fairly new to expect and i am having issues with getting it to work the basic idea is this ( in bash script )

```<code>if grep -q "string" "file";
then
    echo "something is getting deleted".
    sed -i "something"/d "file"
    echo Starting SCP protocol
else
    echo "something was not found"
    echo Starting SCP protocol.
fi
</code>```

Thanks in advance.

答:
Since @whjm deleted his answer, here's a pure-Tcl way to accomplish your task:</p>

```<code>set filename "file"
set found false
set fh [open $filename r]
while {[gets $fh line] != -1} {
    if {[regexp {string} $line]} {
        puts "something is getting deleted"
        close $fh

        set fh_in [open $filename r]
        set fh_out [file tempfile tmpname]
        while {[gets $fh_in line] != -1} {
            if {![regexp {something} $line]} {
                puts $fh_out $line
            }
        }
        close $fh_in
        close $fh_out
        file rename -force $tmpname $filename

        set found true
        break
    }
}
if {!$found} {close $fh}
puts "Starting SCP protocol"
</code>```

Body:
I am trying to understand how to work with expect.

I want to check if a file has a certain string in it and if it does contain it than delete the whole line, i know how i would do that with bash with if and grep, but im fairly new to expect and i am having issues with getting it to work the basic idea is this ( in bash script )

if grep -q "string" "file";
then
    echo "something is getting deleted".
    sed -i "something"/d "file"
    echo Starting SCP protocol
else
    echo "something was not found"
    echo Starting SCP protocol.
fi

Thanks in advance.

Body:
Since @whjm deleted his answer, here's a pure-Tcl way to accomplish your task:

set filename "file"
set found false
set fh [open $filename r]
while {[gets $fh line] != -1} {
    if {[regexp {string} $line]} {
        puts "something is getting deleted"
        close $fh

        set fh_in [open $filename r]
        set fh_out [file tempfile tmpname]
        while {[gets $fh_in line] != -1} {
            if {![regexp {something} $line]} {
                puts $fh_out $line
            }
        }
        close $fh_in
        close $fh_out
        file rename -force $tmpname $filename

        set found true
        break
    }
}
if {!$found} {close $fh}
puts "Starting SCP protocol"


问:
Add events to Calendar programmatically
I'm using below code in Marshmellow device to add the event to the Calendar programmatically but it's not working. Any idea? I cannot see this event in the Calendar app.

```<code>        long startMillis = 0;
        long endMillis = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = null, endDate = null;
        try{
            startDate = simpleDateFormat.parse("2017-05-01 01:30:00");
            startMillis = startDate.getTime();
            endDate = simpleDateFormat.parse("2017-05-01 03:30:00");
            endMillis = endDate.getTime();
        }catch (ParseException e){
            e.printStackTrace();
        }

        ContentResolver cr = this.getContentResolver();
        ContentValues values = new ContentValues();
        TimeZone timeZone = TimeZone.getDefault();
        values.put(CalendarContract.Events.DTSTART, startMillis);
        values.put(CalendarContract.Events.DTEND, endMillis);
        values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
        values.put(CalendarContract.Events.TITLE, "Hello Title");
        values.put(CalendarContract.Events.DESCRIPTION, "Add events to Calendar");
        values.put(CalendarContract.Events.CALENDAR_ID, 879);
        Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);
</code>```

PS: It works if only one gmail account is synced with the calendar app.

答:
Am also find so many solutions finally i got solution and successfully calendar event added with Schedule event.</p>

```<code> Step -1 > Enable Google calnedar API From google console.
 Step - 2 > Add the permission in Androidmanifest.xml

           <uses-permission android:name="android.permission.WRITE_CALENDAR"/>

 Step =3 > Add library for checking Permissions in your  .gradle

          compile 'com.karumi:dexter:4.1.0'

    Dexter.withActivity(YoutActivityName.this)
                    .withPermission(Manifest.permission.WRITE_CALENDAR)
                    .withListener(new PermissionListener()
                    {
                        @Override
                        public void onPermissionGranted(PermissionGrantedResponse response) {
                            try {

                                int calenderId = -1;
                                String calenderEmaillAddress = "sathishmicit2012@gmail.com";
                                String[] projection = new String[]{
                                        CalendarContract.Calendars._ID,
                                        CalendarContract.Calendars.ACCOUNT_NAME};
                                ContentResolver cr = context.getContentResolver();
                                Cursor cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), projection,
                                        CalendarContract.Calendars.ACCOUNT_NAME + "=? and (" +
                                                CalendarContract.Calendars.NAME + "=? or " +
                                                CalendarContract.Calendars.CALENDAR_DISPLAY_NAME + "=?)",
                                        new String[]{calenderEmaillAddress, calenderEmaillAddress,
                                                calenderEmaillAddress}, null);

                                if (cursor.moveToFirst()) {

                                    if (cursor.getString(1).equals(calenderEmaillAddress)) {

                                        calenderId = cursor.getInt(0);
                                    }
                                }

                                long start2 = Calendar.getInstance().getTimeInMillis(); // 2011-02-12 12h00
                                long end2 = Calendar.getInstance().getTimeInMillis() + (4 * 60 * 60 * 1000);   // 2011-02-12 13h00

                                String title = "This is my demo test with alaram with 5 minutes";

                                ContentValues cvEvent = new ContentValues();
                                cvEvent.put("calendar_id", calenderId);
                                cvEvent.put(CalendarContract.Events.TITLE, title);

                                cvEvent.put(CalendarContract.Events.DESCRIPTION, String.valueOf(start2));
                                cvEvent.put(CalendarContract.Events.EVENT_LOCATION, "Bhatar,Surat");
                                cvEvent.put("dtstart", start2);
                                cvEvent.put("hasAlarm", 1);
                                cvEvent.put("dtend", end2);

                                cvEvent.put("eventTimezone", TimeZone.getDefault().getID());

                                Uri uri = getContentResolver().insert(Uri.parse("content://com.android.calendar/events"), cvEvent);

     // get the event ID that is the last element in the Uri

                                long eventID = Long.parseLong(uri.getLastPathSegment());

                                ContentValues values = new ContentValues();

                                values.put(CalendarContract.Reminders.MINUTES, 2);
                                values.put(CalendarContract.Reminders.EVENT_ID, eventID);
                                values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALARM);
                                cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
                                //Uri uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values);

                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void onPermissionDenied(PermissionDeniedResponse response) {/* ... */}

                        @Override
                        public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {/* ... */}
                    }).check();
</code>```

Title: Add events to Calendar programmatically

Body:
I'm using below code in Marshmellow device to add the event to the Calendar programmatically but it's not working. Any idea? I cannot see this event in the Calendar app.

        long startMillis = 0;
        long endMillis = 0;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date startDate = null, endDate = null;
        try{
            startDate = simpleDateFormat.parse("2017-05-01 01:30:00");
            startMillis = startDate.getTime();
            endDate = simpleDateFormat.parse("2017-05-01 03:30:00");
            endMillis = endDate.getTime();
        }catch (ParseException e){
            e.printStackTrace();
        }

        ContentResolver cr = this.getContentResolver();
        ContentValues values = new ContentValues();
        TimeZone timeZone = TimeZone.getDefault();
        values.put(CalendarContract.Events.DTSTART, startMillis);
        values.put(CalendarContract.Events.DTEND, endMillis);
        values.put(CalendarContract.Events.EVENT_TIMEZONE, timeZone.getID());
        values.put(CalendarContract.Events.TITLE, "Hello Title");
        values.put(CalendarContract.Events.DESCRIPTION, "Add events to Calendar");
        values.put(CalendarContract.Events.CALENDAR_ID, 879);
        Uri uri = cr.insert(CalendarContract.Events.CONTENT_URI, values);

PS: It works if only one gmail account is synced with the calendar app.

Body:
Am also find so many solutions finally i got solution and successfully calendar event added with Schedule event.

 Step -1 > Enable Google calnedar API From google console.
 Step - 2 > Add the permission in Androidmanifest.xml

           <uses-permission android:name="android.permission.WRITE_CALENDAR"/>

 Step =3 > Add library for checking Permissions in your  .gradle

          compile 'com.karumi:dexter:4.1.0'

    Dexter.withActivity(YoutActivityName.this)
                    .withPermission(Manifest.permission.WRITE_CALENDAR)
                    .withListener(new PermissionListener()
                    {
                        @Override
                        public void onPermissionGranted(PermissionGrantedResponse response) {
                            try {

                                int calenderId = -1;
                                String calenderEmaillAddress = "sathishmicit2012@gmail.com";
                                String[] projection = new String[]{
                                        CalendarContract.Calendars._ID,
                                        CalendarContract.Calendars.ACCOUNT_NAME};
                                ContentResolver cr = context.getContentResolver();
                                Cursor cursor = cr.query(Uri.parse("content://com.android.calendar/calendars"), projection,
                                        CalendarContract.Calendars.ACCOUNT_NAME + "=? and (" +
                                                CalendarContract.Calendars.NAME + "=? or " +
                                                CalendarContract.Calendars.CALENDAR_DISPLAY_NAME + "=?)",
                                        new String[]{calenderEmaillAddress, calenderEmaillAddress,
                                                calenderEmaillAddress}, null);

                                if (cursor.moveToFirst()) {

                                    if (cursor.getString(1).equals(calenderEmaillAddress)) {

                                        calenderId = cursor.getInt(0);
                                    }
                                }

                                long start2 = Calendar.getInstance().getTimeInMillis(); // 2011-02-12 12h00
                                long end2 = Calendar.getInstance().getTimeInMillis() + (4 * 60 * 60 * 1000);   // 2011-02-12 13h00

                                String title = "This is my demo test with alaram with 5 minutes";

                                ContentValues cvEvent = new ContentValues();
                                cvEvent.put("calendar_id", calenderId);
                                cvEvent.put(CalendarContract.Events.TITLE, title);

                                cvEvent.put(CalendarContract.Events.DESCRIPTION, String.valueOf(start2));
                                cvEvent.put(CalendarContract.Events.EVENT_LOCATION, "Bhatar,Surat");
                                cvEvent.put("dtstart", start2);
                                cvEvent.put("hasAlarm", 1);
                                cvEvent.put("dtend", end2);

                                cvEvent.put("eventTimezone", TimeZone.getDefault().getID());

                                Uri uri = getContentResolver().insert(Uri.parse("content://com.android.calendar/events"), cvEvent);

     // get the event ID that is the last element in the Uri

                                long eventID = Long.parseLong(uri.getLastPathSegment());

                                ContentValues values = new ContentValues();

                                values.put(CalendarContract.Reminders.MINUTES, 2);
                                values.put(CalendarContract.Reminders.EVENT_ID, eventID);
                                values.put(CalendarContract.Reminders.METHOD, CalendarContract.Reminders.METHOD_ALARM);
                                cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
                                //Uri uri = cr.insert(CalendarContract.Reminders.CONTENT_URI, values);

                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void onPermissionDenied(PermissionDeniedResponse response) {/* ... */}

                        @Override
                        public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {/* ... */}
                    }).check();


问:
overwrite in the middle of a File
The Problem is I am in the Middle of a File with fseek Next exists some Bytes of Length m that I want to replace with Bytes of length n. simple write will keep m-n bytes still there. If m > n and if m < n some Bytes (n-m) that I am not willing to change will be overwritten.

I just want to replace a known startPos to endPos Byte Stream with variable length Bytes. What is the Best Solution.

-- EDIT --
Though It can be done by taking a Backup. do there exists any direct solution ?
This is too Messy ? and Kind of Poor Coding.

```<code>o = fopen(original, 'r')
b = fopen(backup, 'w')
while(fpos(o) <= startPos){
    buffer += fgetc(o)
}
fwrite(b, buffer)
fwrite(b, replaceMentBytes)
buffer = ""
fseek(o, endPos)
while(!feof(o)){
    buffer += fgetc(o)
}
fwrite(b, buffer)
</code>```

//now Copy backup to original

答: The most robust solution is to re-write the whole file, from scratch. Most operating systems will only let you overwrite bytes, not insert or remove them, from a file, so to accomplish that, you have to essentially copy the file, replacing the target bytes during the copy.</p>

Title: overwrite in the middle of a File

Body:
The Problem is I am in the Middle of a File with fseek Next exists some Bytes of Length m that I want to replace with Bytes of length n. simple write will keep m-n bytes still there. If m > n and if m < n some Bytes (n-m) that I am not willing to change will be overwritten.

I just want to replace a known startPos to endPos Byte Stream with variable length Bytes. What is the Best Solution.

-- EDIT --
Though It can be done by taking a Backup. do there exists any direct solution ?
This is too Messy ? and Kind of Poor Coding.

o = fopen(original, 'r')
b = fopen(backup, 'w')
while(fpos(o) <= startPos){
    buffer += fgetc(o)
}
fwrite(b, buffer)
fwrite(b, replaceMentBytes)
buffer = ""
fseek(o, endPos)
while(!feof(o)){
    buffer += fgetc(o)
}
fwrite(b, buffer)

//now Copy backup to original