问:
React - I need advise how to design state data structure
I am working on cricket scoring Single page application in react.

It is using Redux to maintain its data and with every action i will be getting a new state.

My app has single rootReducer because everything is mingled. If a ball is thrown, batting and bowling both sides are updated.

The state is pretty complicated but I'm of opinion that it should be like this.

Please tell me if this state design is fine or I should somehow simplify it or change it?

```<code>var playerType = {
    id:             0,
    name:           '',

    // Batting stats
    runs:           0,
    four:           0,
    six:            0,
    ballsFaced:     0,
    battingNumber:  false,
    isBatting:      false,
    isOnStrike:     false,
    isOut:          false,
    outType:        '',

    // Batting Walkin stats
    walkInOver:     0,
    walkInBalls:    0,
    walkInTeamRuns: 0,

    // Batting Out stats
    walkoutWicket:  0,
    walkoutOver:    0,
    walkoutBalls:   0,
    walkoutTeamRuns:0,
    wicketBowler:   0,
    wicketFilder:   0,
    notOutPlayerId: 0,
    notOutPlayerRuns:0,

    // Bowling stats
    overs:          0,
    balls:          0,
    overRuns:       0,
    wickets:        0,
    isBowling:      false,

};

var teamType = {
    id:                 0,
    name:               "",
    runs:               0,
    overs:              0,
    balls:              0,  // This are only legal balls from 0 to 5
    isTossWon:          false,
    players:playerType  = []
};

// Initial State
var initialState = {
    matchId:        0,
    thisOver:       [],
    prevOver:       [],
    oversTotal:     0,
    teamBatting:    teamType,
    teamBowling:    teamType
}
</code>```

Your thoughts?

答:
I would have a match reducer that models everything in the match, such as:

A collection of batsmen

A collection of bowlers

Fields for each extra type (byes, legbyes, noballs, wides)

To that I would add "live" information such as:

The current batsman on strike

The current batsman off strike

The current bowler bowling

Note that I would leave out data that can be "derived" from other pieces of state. For instance, the total score can be derived from the sum of the batsmen's scores plus the sum of the extras.

A possible instance of the match state might look like:

```<code>{
  batsmen: {
    48: {
      id: 48,
      name: 'David Warner'
      runs: 10,
      balls: 18,
    },
    64: {
      id: 64,
      name: 'Matthew Renshaw',
      runs: 2,
      balls: 20,
    },
  },
  byes: 2,
  legbyes: 0,
  noballs: 3,
  wides: 0,
  bowlers: {
    82: {
      name: 'Jimmy Anderson',
      balls: 18,
      runs: 6,
      wickets: 0,
    },
    93: {
      name: 'Stuart Broad',
      balls: 17,
      runs: 9,
      wickets: 0,
    },
  },
  batsmanOnStrike: 48,
  batsmanOffStrike: 64,
  currentBowler: 93,
}
</code>```

You might want to dispatch an action for a discrete scoring event. e.g.

```<code>{
  type: 'RUNS_SCORED',
  runs: 3,
}
</code>```

Your reducer might handle it in the following manner:

```<code>case 'RUNS_SCORED': {
  const batsman = state.batsmen[state.batsmanOnStrike];
  const bowler = state.batsmen[state.currentBowler];

  return {
    ...state,
    batsmen: {
      ...state.batsmen,
      [state.batsmanOnStrike]: {
        ...batsman,
        runs: batsman.runs + action.runs,
        balls: batsman.balls + 1,
      },
    },
    bowlers: {
      ...state.bowlers,
      [state.currentBowler]: {
        ...bowler,
        balls: bowler.balls + 1,
        runs: bowler.runs + action.runs,
      },
    },
    batsmanOnStrike: action.runs % 2 === 0 ? state.batsmanOnStrike : state.batsmanOffStrike,
    batsmanOffStrike: action.runs % 2 === 0 ? state.batsmanOffStrike : state.batsmanOnStrike,
  };
}
</code>```

This example is imperfect and incomplete, but I hope it gives you the general idea.

Body:
I am working on cricket scoring Single page application in react.

It is using Redux to maintain its data and with every action i will be getting a new state.

My app has single rootReducer because everything is mingled. If a ball is thrown, batting and bowling both sides are updated.

The state is pretty complicated but I'm of opinion that it should be like this.

Please tell me if this state design is fine or I should somehow simplify it or change it?

var playerType = {
    id:             0,
    name:           '',

    // Batting stats
    runs:           0,
    four:           0,
    six:            0,
    ballsFaced:     0,
    battingNumber:  false,
    isBatting:      false,
    isOnStrike:     false,
    isOut:          false,
    outType:        '',

    // Batting Walkin stats
    walkInOver:     0,
    walkInBalls:    0,
    walkInTeamRuns: 0,

    // Batting Out stats
    walkoutWicket:  0,
    walkoutOver:    0,
    walkoutBalls:   0,
    walkoutTeamRuns:0,
    wicketBowler:   0,
    wicketFilder:   0,
    notOutPlayerId: 0,
    notOutPlayerRuns:0,

    // Bowling stats
    overs:          0,
    balls:          0,
    overRuns:       0,
    wickets:        0,
    isBowling:      false,

};

var teamType = {
    id:                 0,
    name:               "",
    runs:               0,
    overs:              0,
    balls:              0,  // This are only legal balls from 0 to 5
    isTossWon:          false,
    players:playerType  = []
};

// Initial State
var initialState = {
    matchId:        0,
    thisOver:       [],
    prevOver:       [],
    oversTotal:     0,
    teamBatting:    teamType,
    teamBowling:    teamType
}

Your thoughts?

Body:
I would have a match reducer that models everything in the match, such as:

A collection of batsmen

A collection of bowlers

Fields for each extra type (byes, legbyes, noballs, wides)

To that I would add "live" information such as:

The current batsman on strike

The current batsman off strike

The current bowler bowling

Note that I would leave out data that can be "derived" from other pieces of state. For instance, the total score can be derived from the sum of the batsmen's scores plus the sum of the extras.

A possible instance of the match state might look like:

{
  batsmen: {
    48: {
      id: 48,
      name: 'David Warner'
      runs: 10,
      balls: 18,
    },
    64: {
      id: 64,
      name: 'Matthew Renshaw',
      runs: 2,
      balls: 20,
    },
  },
  byes: 2,
  legbyes: 0,
  noballs: 3,
  wides: 0,
  bowlers: {
    82: {
      name: 'Jimmy Anderson',
      balls: 18,
      runs: 6,
      wickets: 0,
    },
    93: {
      name: 'Stuart Broad',
      balls: 17,
      runs: 9,
      wickets: 0,
    },
  },
  batsmanOnStrike: 48,
  batsmanOffStrike: 64,
  currentBowler: 93,
}

You might want to dispatch an action for a discrete scoring event. e.g.

{
  type: 'RUNS_SCORED',
  runs: 3,
}

Your reducer might handle it in the following manner:

case 'RUNS_SCORED': {
  const batsman = state.batsmen[state.batsmanOnStrike];
  const bowler = state.batsmen[state.currentBowler];

  return {
    ...state,
    batsmen: {
      ...state.batsmen,
      [state.batsmanOnStrike]: {
        ...batsman,
        runs: batsman.runs + action.runs,
        balls: batsman.balls + 1,
      },
    },
    bowlers: {
      ...state.bowlers,
      [state.currentBowler]: {
        ...bowler,
        balls: bowler.balls + 1,
        runs: bowler.runs + action.runs,
      },
    },
    batsmanOnStrike: action.runs % 2 === 0 ? state.batsmanOnStrike : state.batsmanOffStrike,
    batsmanOffStrike: action.runs % 2 === 0 ? state.batsmanOffStrike : state.batsmanOnStrike,
  };
}

This example is imperfect and incomplete, but I hope it gives you the general idea.


来源: stackexchange

问:
How to create a pre-prepared database and then load that data in my ios swift app?
I have a lot of data text in a couple of text files. How can I efficiently create a (Realm?) database with the data from those text files so I can add the database to my Xcode project and load the data into my app?

I have seen many tutorials on how to create Realm database with user entered data and then load it, but none with pre-made databases. I don't know if Realm is the right program to do this, but I looked really well.
I have downloaded the Realm Browser, but I could only view databases and couldn't find out how to create them easily.

EDIT:

I managed to create a database in Realm and put it in my xcode folder.
Then I try to load it like this, but let peoples doesn't contain the file's data, what am I missing:

```<code>let path = NSBundle.mainBundle().pathForResource("data", ofType: "realm")
var config = Realm.Configuration(fileURL: NSURL(fileURLWithPath: path!))
config.readOnly = true
let realm = try! Realm(configuration: config)

let peoples =  realm.objects(Data)
</code>```

Data is class which defines the schema:

```<code>class Data : Object {
    dynamic var name  = ""
    dynamic var country = ""
    dynamic var discription = ""
    dynamic var image = ""
    dynamic var cartoon = ""
    dynamic var startYear = 0
    dynamic var endYear = 0
}
</code>```

An image of the realm file I'm trying to load:

Thanks for help!

答:
Create a Sample Model:

```<code>final class ContentModel: Object {
   dynamic var title = ""
   dynamic var content = ""
   dynamic var listName = ""
   dynamic var id = 0

   override static func primaryKey() -> String? {
       return "id"
   }
}
</code>```

Create realm database:

```<code>let model = ContentModel()
model.id = 1
model.listName = "List Item 1"
model.title = "Title of content 1"
model.content = "Sample Text"

// Get the default Realm
let realm = try! Realm()

// Persist your data easily
try! realm.write {
    realm.add(model)
}
</code>```

Use this line to print the path to database:

```<code>print(Realm.Configuration.defaultConfiguration.fileURL!)
</code>```

Now follow these steps (explained by realm)

Drag the new compacted copy of your Realm file to your final app’s Xcode Project Navigator.

Go to your app target’s build phases tab in Xcode and add the Realm file to the “Copy Bundle Resources” build phase.

At this point, your bundled Realm file will be accessible to your app. You can find its path by using NSBundle.main.pathForResource(_:ofType:).

Here's the code to get your bundled resource:

```<code>open class func getBundledRealm() -> Realm {
    let config = Realm.Configuration(
        // Get the URL to the bundled file
            fileURL: Bundle.main.url(forResource: "default", withExtension: "realm"),
            // Open the file in read-only mode as application bundles are not writeable
            readOnly: true)

    // Open the Realm with the configuration
    let realm = try! Realm(configuration: config)

    return realm
}
</code>```

To Test your database:

```<code>let realm = RealmUtils.getBundledRealm()

// Read some data from the bundled Realm
let results = realm.objects(ContentModel.self)

for item in results {
    print("Id: \(item.id)")
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a lot of data text in a couple of text files. How can I efficiently create a (Realm?) database with the data from those text files so I can add the database to my Xcode project and load the data into my app?

I have seen many tutorials on how to create Realm database with user entered data and then load it, but none with pre-made databases. I don't know if Realm is the right program to do this, but I looked really well.
I have downloaded the Realm Browser, but I could only view databases and couldn't find out how to create them easily.

EDIT:

I managed to create a database in Realm and put it in my xcode folder.
Then I try to load it like this, but let peoples doesn't contain the file's data, what am I missing:

let path = NSBundle.mainBundle().pathForResource("data", ofType: "realm")
var config = Realm.Configuration(fileURL: NSURL(fileURLWithPath: path!))
config.readOnly = true
let realm = try! Realm(configuration: config)

let peoples =  realm.objects(Data)

Data is class which defines the schema:

class Data : Object {
    dynamic var name  = ""
    dynamic var country = ""
    dynamic var discription = ""
    dynamic var image = ""
    dynamic var cartoon = ""
    dynamic var startYear = 0
    dynamic var endYear = 0
}

An image of the realm file I'm trying to load:

Thanks for help!

Body:
Create a Sample Model:

final class ContentModel: Object {
   dynamic var title = ""
   dynamic var content = ""
   dynamic var listName = ""
   dynamic var id = 0

   override static func primaryKey() -> String? {
       return "id"
   }
}

Create realm database:

let model = ContentModel()
model.id = 1
model.listName = "List Item 1"
model.title = "Title of content 1"
model.content = "Sample Text"

// Get the default Realm
let realm = try! Realm()

// Persist your data easily
try! realm.write {
    realm.add(model)
}

Use this line to print the path to database:

print(Realm.Configuration.defaultConfiguration.fileURL!)

Now follow these steps (explained by realm)

Drag the new compacted copy of your Realm file to your final app’s Xcode Project Navigator.

Go to your app target’s build phases tab in Xcode and add the Realm file to the “Copy Bundle Resources” build phase.

At this point, your bundled Realm file will be accessible to your app. You can find its path by using NSBundle.main.pathForResource(_:ofType:).

Here's the code to get your bundled resource:

open class func getBundledRealm() -> Realm {
    let config = Realm.Configuration(
        // Get the URL to the bundled file
            fileURL: Bundle.main.url(forResource: "default", withExtension: "realm"),
            // Open the file in read-only mode as application bundles are not writeable
            readOnly: true)

    // Open the Realm with the configuration
    let realm = try! Realm(configuration: config)

    return realm
}

To Test your database:

let realm = RealmUtils.getBundledRealm()

// Read some data from the bundled Realm
let results = realm.objects(ContentModel.self)

for item in results {
    print("Id: \(item.id)")
}


问:
Removing apostrophe in selected cell
I'm a beginner in VBA.
Trying to change text values in my spreadsheet (example "'123" to "123") in selected area to General or Numeric.
I have my small code that able to select (but not changing to General)

```<code>Sub Macro1()
'
' Macro1 Macro

    Rows("1:1").Select
    Selection.AutoFilter
ActiveSheet.Range("$A$1:$O$49999").AutoFilter Field:=8, Criteria1:="NUM"
ActiveSheet.Range("$A$1:$O$49999").AutoFilter Field:=10, Criteria1:="0"
ActiveSheet.Range("$A$1:$O$49999").AutoFilter Field:=6, Criteria1:="<>"

  With Selection
   .NumberFormat = "General"

    End With

End Sub
</code>```

What should I change in the code to get required result?
Thanks for help!

答:
how did you get ' in your field?

In general, you can use:

Replace ( string1, find, replacement, [start, [count, [compare]]] )

```<code>Dim LResult As String

LResult = Replace("alphabet", "a", "e")
</code>```

In this example, the variable called LResult would now contain the value "elphebet".

Title: Removing apostrophe in selected cell

Body:
I'm a beginner in VBA.
Trying to change text values in my spreadsheet (example "'123" to "123") in selected area to General or Numeric.
I have my small code that able to select (but not changing to General)

Sub Macro1()
'
' Macro1 Macro

    Rows("1:1").Select
    Selection.AutoFilter
ActiveSheet.Range("$A$1:$O$49999").AutoFilter Field:=8, Criteria1:="NUM"
ActiveSheet.Range("$A$1:$O$49999").AutoFilter Field:=10, Criteria1:="0"
ActiveSheet.Range("$A$1:$O$49999").AutoFilter Field:=6, Criteria1:="<>"

  With Selection
   .NumberFormat = "General"

    End With

End Sub

What should I change in the code to get required result?
Thanks for help!

Body:
how did you get ' in your field?

In general, you can use:

Replace ( string1, find, replacement, [start, [count, [compare]]] )

Dim LResult As String

LResult = Replace("alphabet", "a", "e")

In this example, the variable called LResult would now contain the value "elphebet".


问:
Deleting a folder using VBA and it still appears in File Explorer until the next iteration
VBA - Access

I'm using fso.DeleteFolder to delete a folder on a server that an earlier function in the same Access DB created.  The fso.DeleteFolder code runs without error and running fso.FolderExists after shows the folder no longer exists (prior to the delete, fso.FolderExists stated that the folder did exist).

However the folder is still listed in File Explorer on the server.  Refreshing does no good.  When double-clicking the folder on the server, I get an error stating that the folder is not accessible and access denied (prior to the delete, the folder was normal).

The folder may or may not have subfolders and/or files - but I do not think that is important because if I run the create / delete processes over again using a different folder name, the issue repeats - EXCEPT the prior folder is now no longer listed in File Explorer (truly deleted now as God intended), replaced with the new folder that was supposed to be deleted with the same double-click error and so on.

I kill my fso object at the end of the function, I believe the same issue also happens with KILL instead of fso.

Any help/thoughts would be appreciated.

答:
Just encountered that problem!

For some reason deleting a directory with VBA leaves that lingering "lock" on the deleted file UNTIL it performs another directory type action then it flushes the "lock" If you were to delete three directories in one script you would likely find that the only "failed" delete action would be on the last directory deleted.

Performing a "directory read" type action within the script after the RmDir action works for me. Try something like this...

If Dir("yourpath") = "" Then MkDir "yourpath"


问:
Can a constructor in Java be private?
Can a constructor be private? How is a private constructor useful?</p>

答:
Yes. Class can have private constructor. Even abstract class can have private constructor.

By making constructor private, we prevent the class from being instantiated as well as subclassing of that class.

Here are some of the uses of private constructor :

Singleton Design Pattern

To limit the number of instance creation

To give meaningful name for object creation using static factory method

Static Utility Class or Constant Class

To prevent Subclassing

Builder Design Pattern and thus for creating immutable classes

ContentLicense: CC BY-SA 2.5

Title: Can a constructor in Java be private?

LastEditorDisplayName: Roger Pate


问:
Following multiple ID / Class rules in CSS
I'm trying to have a scrolling banner on the index page which has multiple sub-properties but, the main property of:

```<code>height: 75vh;
</code>```

On all following pages I would like the same banner to have all the other rules that apply to it, but only have the height different:

```<code>height: 30vh;
</code>```

This would allow both banners to follow all the same rules for remaining mobile responsive - ie they both still come under the id="banner".

One easy fix for this would be to label one id="bannerX" and one id="bannerY" and then just copy all the subsequent CSS under the corresponding X or Y. For example:

```<code>#bannerX {
    background-color: #444;
    color: #fff;
    min-height: 40em;
    height: 75vh;
    position: relative;
}

    #bannerX input, #banner select, #banner textarea {
        color: #fff;
    }

    #bannerX a {
        color: #fff;
    }

    #bannerX strong, #banner b {
        color: #fff;
    }

   and so on...
</code>```

versus

```<code>#bannerY {
    background-color: #444;
    color: #fff;
    min-height: 40em;
    height: 30vh;
    position: relative;
}

    #bannerY input, #banner select, #banner textarea {
        color: #fff;
    }

    #bannerY a {
        color: #fff;
    }

    #bannerY strong, #banner b {
        color: #fff;
    }

   and so forth...
</code>```

But that just leads to a duplication of a lot of CSS that is the exact same, just the original ID is changing one rule within it. This would work but just seems a really messy way around it. I'm sure there must be a better way of working this but I can't seem to make it work. I've tried adding in a class="banner-thick" or class="banner-thin" to each within their own section but that didn't seem to work either because then neither banner follows the original id="banner" rules because they're now id="bannerX" or id="bannerY"! I can't seem to make it work! Does anyone have an idea of how I can fix this?

I suspect there's a simple fix and I just can't see the wood from the trees!

Thanks all.

答:
Use multiple class like this - class="bannerX height1" for 1st one. For 2nd one use class="bannerX height2". Where height only holds the value of heights. No need to use heights in bannerX.

CSS

```<code>.bannerX {
    background-color: #444;
    color: #fff;
    min-height: 40em;
    /*height: 75vh;*/ as we define different heights in height1 & height1 class
    position: relative;
}

.height1 {
    height: 75vh;
}

.height2 {
    height: 75vh;
}
</code>```

HTML

```<code><div class="bannerX height1">
</div>

<div class="bannerX height2">
</div>
</code>```

Body:
I'm trying to have a scrolling banner on the index page which has multiple sub-properties but, the main property of:

height: 75vh;

On all following pages I would like the same banner to have all the other rules that apply to it, but only have the height different:

height: 30vh;

This would allow both banners to follow all the same rules for remaining mobile responsive - ie they both still come under the id="banner".

One easy fix for this would be to label one id="bannerX" and one id="bannerY" and then just copy all the subsequent CSS under the corresponding X or Y. For example:

#bannerX {
    background-color: #444;
    color: #fff;
    min-height: 40em;
    height: 75vh;
    position: relative;
}

    #bannerX input, #banner select, #banner textarea {
        color: #fff;
    }

    #bannerX a {
        color: #fff;
    }

    #bannerX strong, #banner b {
        color: #fff;
    }

   and so on...

versus

#bannerY {
    background-color: #444;
    color: #fff;
    min-height: 40em;
    height: 30vh;
    position: relative;
}

    #bannerY input, #banner select, #banner textarea {
        color: #fff;
    }

    #bannerY a {
        color: #fff;
    }

    #bannerY strong, #banner b {
        color: #fff;
    }

   and so forth...

But that just leads to a duplication of a lot of CSS that is the exact same, just the original ID is changing one rule within it. This would work but just seems a really messy way around it. I'm sure there must be a better way of working this but I can't seem to make it work. I've tried adding in a class="banner-thick" or class="banner-thin" to each within their own section but that didn't seem to work either because then neither banner follows the original id="banner" rules because they're now id="bannerX" or id="bannerY"! I can't seem to make it work! Does anyone have an idea of how I can fix this?

I suspect there's a simple fix and I just can't see the wood from the trees!

Thanks all.

Body:
Use multiple class like this - class="bannerX height1" for 1st one. For 2nd one use class="bannerX height2". Where height only holds the value of heights. No need to use heights in bannerX.

CSS

.bannerX {
    background-color: #444;
    color: #fff;
    min-height: 40em;
    /*height: 75vh;*/ as we define different heights in height1 & height1 class
    position: relative;
}

.height1 {
    height: 75vh;
}

.height2 {
    height: 75vh;
}

HTML

<div class="bannerX height1">
</div>

<div class="bannerX height2">
</div>


答:
to convert Text to Number try this:

```<code>Sub ConvertTextNumberToNumber()
For Each WS In Sheets
On Error Resume Next
For Each r In WS.UsedRange.SpecialCells(xlCellTypeConstants)
If IsNumeric(r) Then r.Value = Val(r.Value)
Next
Next
End Sub
</code>```

And you can call this function :

```<code>Sub Macro1()
'
' Macro1 Macro

    Rows("1:1").Select
    Selection.AutoFilter
ActiveSheet.Range("$A$1:$O$49999").AutoFilter Field:=8, Criteria1:="NUM"
Call ConvertTextNumberToNumber()
ActiveSheet.Range("$A$1:$O$49999").AutoFilter Field:=10, Criteria1:="0"
Call ConvertTextNumberToNumber()
ActiveSheet.Range("$A$1:$O$49999").AutoFilter Field:=6, Criteria1:="<>"
Call ConvertTextNumberToNumber()

End Sub
</code>```

Title: Removing apostrophe in selected cell

Body:
to convert Text to Number try this:

Sub ConvertTextNumberToNumber()
For Each WS In Sheets
On Error Resume Next
For Each r In WS.UsedRange.SpecialCells(xlCellTypeConstants)
If IsNumeric(r) Then r.Value = Val(r.Value)
Next
Next
End Sub

And you can call this function :

Sub Macro1()
'
' Macro1 Macro

    Rows("1:1").Select
    Selection.AutoFilter
ActiveSheet.Range("$A$1:$O$49999").AutoFilter Field:=8, Criteria1:="NUM"
Call ConvertTextNumberToNumber()
ActiveSheet.Range("$A$1:$O$49999").AutoFilter Field:=10, Criteria1:="0"
Call ConvertTextNumberToNumber()
ActiveSheet.Range("$A$1:$O$49999").AutoFilter Field:=6, Criteria1:="<>"
Call ConvertTextNumberToNumber()

End Sub


问:
Return 410 Error Based on Part of Query String in ASP.NET MVC
Looking for a method we can use in our ASP.NET MVC-5 IIS-8 site to return a 410 error response (gone) based on a list of phrases contained in the querystrings.

Why?  We're receiving a few hundred daily junk hits from reputable bots (e.g., Google, Bing, Yahoo) for ridiculously named pages that we've never had on our site.  I'm thinking that for most of these pages I can test if a given key-phrase exists and, if it does, return the 410.  I'd like to return the 410 to tell the bots they can remove their listing permanently thereby providing a gradually improved SEO environment.

Here's a few examples of URL's we're receiving with the key-phrase I would test for in bold.

https://www.example.com:443/apple-touch-icon-precomposed.png

http://ww.w.example.com:80/zdjqhhmtkatt.html

I know this is very do-able with .htaccess in other programming environments so I'm hoping there's also an elegant solution for ASP.MVC.

答:
You can do that with URL rewrite module. The rule in your web.config should be like that:</p>

```<code><rewrite>
    <rules>
        <rule name="410response" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAny">
                <add input="{REQUEST_URI}" pattern="apple-touch" />
                <add input="{REQUEST_URI}" pattern="zdjqhhmtkatt" />
            </conditions>
            <action type="CustomResponse" statusCode="410" statusReason="System unavailable" statusDescription="Gone. The requested resource is no longer available." />
        </rule>
    </rules>
</rewrite>
</code>```

Body:
You can do that with URL rewrite module. The rule in your web.config should be like that:

<rewrite>
    <rules>
        <rule name="410response" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAny">
                <add input="{REQUEST_URI}" pattern="apple-touch" />
                <add input="{REQUEST_URI}" pattern="zdjqhhmtkatt" />
            </conditions>
            <action type="CustomResponse" statusCode="410" statusReason="System unavailable" statusDescription="Gone. The requested resource is no longer available." />
        </rule>
    </rules>
</rewrite>


问:
How to stop/shut down an elasticsearch node?
I want to restart an elasticsearch node with a new configuration. What is the best way to gracefully shut down an node?

Is killing the process the best way of shutting the server down, or is there some magic URL I can use to shut the node down?

答:
use the following command to know the pid of the node already running.

curl -XGET 'http://localhost:9200/_nodes/process'

It took me an hour to find out the way to kill the node and could finally do it after using this command in the terminal window.


问:
Gtk widget minimum and maximum width/height with resizable to true
I am new to gtk and using gtkmm-3.0, what i am trying hard is to set the minimum width and height for the gtk widget. I used set_size_request method but the widget is still crossing its min/max size when i resize the parent container.

my code looks like

```<code>foo::foo()
{
    set_default_size(400,400); // set default size for window
    add(grid_layout);

    menu_bar.append(file);
    menu_bar.append(edit);
    menu_bar.append(project);
    menu_bar.append(settings);
    menu_bar.append(help);

    right_panel_notebook.insert_page(right_btn, "Page1", Gtk::POS_RIGHT);
    right_panel_notebook.insert_page(notebook_btn, "Page2", Gtk::POS_RIGHT);
    right_panel_notebook.set_size_request(400,300); // setting size for a Notebook widget

    design_paned.set_vexpand(true);
    design_paned.add1(btn);
    design_paned.add2(right_panel_notebook);

    grid_layout.set_row_homogeneous(false);
    grid_layout.set_column_homogeneous(true);
    grid_layout.attach_next_to(menu_bar, Gtk::POS_RIGHT, 1,1);
    grid_layout.attach_next_to(design_paned, Gtk::POS_BOTTOM, 1,1);

    show_all();
}
</code>```

So, is there any way to restrict the widget's min/max size with its resizable to true.

答:
Not sure if this is what you want but looking to your code, the set_size_request is being called on the GtkNotebook which is inside a GtkPaned, so:

GtkPaned childs have two properties, resize and shrink:

Each child has two options that can be set, resize and shrink . If
  resize is true, then when the GtkPaned is resized, that child will
  expand or shrink along with the paned widget. If shrink is true, then
  that child can be made smaller than its requisition by the user.
  Setting shrink to FALSE allows the application to set a minimum size.
  If resize is false for both children, then this is treated as if
  resize is true for both children

If shrinkis set to TRUE then the notebook can be smaller that the 400x300 size you've requested.

To set these properties, use the GtkPanned pack1 and pack2 methods instead of the add1 and add2.

Body:
I am new to gtk and using gtkmm-3.0, what i am trying hard is to set the minimum width and height for the gtk widget. I used set_size_request method but the widget is still crossing its min/max size when i resize the parent container.

my code looks like

foo::foo()
{
    set_default_size(400,400); // set default size for window
    add(grid_layout);

    menu_bar.append(file);
    menu_bar.append(edit);
    menu_bar.append(project);
    menu_bar.append(settings);
    menu_bar.append(help);

    right_panel_notebook.insert_page(right_btn, "Page1", Gtk::POS_RIGHT);
    right_panel_notebook.insert_page(notebook_btn, "Page2", Gtk::POS_RIGHT);
    right_panel_notebook.set_size_request(400,300); // setting size for a Notebook widget

    design_paned.set_vexpand(true);
    design_paned.add1(btn);
    design_paned.add2(right_panel_notebook);

    grid_layout.set_row_homogeneous(false);
    grid_layout.set_column_homogeneous(true);
    grid_layout.attach_next_to(menu_bar, Gtk::POS_RIGHT, 1,1);
    grid_layout.attach_next_to(design_paned, Gtk::POS_BOTTOM, 1,1);

    show_all();
}

So, is there any way to restrict the widget's min/max size with its resizable to true.


问:
How to read and write csv file when it is opened with Excel by the user in parallel with C#?
This is the first question I asked on stackoverflow, very exciting. So sorry about my grammar and other type mistakes, I would appreciate if you correct them. I want to write a program that reads a csv file if it exists in the specific folder first, stores it in List variable, add some new lines and writes it to the same file. This process will be repeated continuously in a while block.

While the file is being read and written by the program, if it is opened with Notepad, it doesn't give an error and the program could access the file in parallel. But if it is opened with Office Excel, program gives error that says "file access is denied because it is used by another process..". I want to ask you that:

1) Is it possible to give priority to the program, so program can still access the file but user cannot? Or is it possible both program and user can access the file?

2) If the solution is opening the file with Notepad, is there a way to set default program for this file as Notepad? Or how can I change default program for csv files as Notepad from C#?

Reading and writing parts of the code is as bellows:

```<code>    List<string> csvLines = new List<string>();
    string address = folderpath + @"\PLC_LOGLARI";
    if (!Directory.Exists(address))
        Directory.CreateDirectory(address);

    string fileAddress = address + @"\" + fileName + "_" + machineNo + "_1.csv";

    if (Directory.EnumerateFiles(address).Any(f => f.Contains(fileName + "_" + machineNo)))
    {
        string[] addressArray = Directory.GetFiles(address, fileName + "_" + machineNo + "*.*");
        FileInfo fileInformation = new FileInfo(addressArray[addressArray.Length - 1]);
        long fileSize = fileInformation.Length;
        if (fileSize > 5000000)
        {
            int fileNo = int.Parse(addressArray[addressArray.Length - 1].Substring(addressArray[addressArray.Length - 1].LastIndexOf('_') + 1, 1)) + 1;
            fileAddress = addressArray[addressArray.Length - 1].Substring(0, addressArray[addressArray.Length - 1].LastIndexOf('_') + 1) + fileNo.ToString() + ".csv";
        }
        else
        {
            fileAddress = addressArray[addressArray.Length - 1];
            csvLines = File.ReadAllLines(address).ToList();
        }
    }
    else
    {
        string[] headings = makeHeadings();
        csvLines.Add(headings[0]);
        csvLines.Add(headings[1]);
    }
    string newLine = "";

    // some operations and calculations for newLine
    // some operations and calculations for newLine
    // some operations and calculations for newLine

    newLine = newLine.Substring(1, newLine.Length-1);
    csvLines.Add(newLine);
    File.WriteAllLines(fileAddress, csvLines.ToArray());
</code>```

Thanks for your help.

答:
For question 2: In order to change the default program, if you are using Windows, you could click start and find/type 'Default Programs'. Depending on the version of windows, basically find 'Associate a file type of protocol with a program' or 'choose a default application by file type' and adjust the csv file to use a new default program.

I would be very careful if both program and notepad are able accessing the file in the same time. The reason why it was blocked in the first place was to prevent overridding the content of the file, thus probably test it first if you open it in the program and notepad. Then the program make some update - and you also make a different update with the notepad. Would both changes be recorded? As I suspect the 'last save' win in which you may lost some of your changes.

For question 1: I was guessing that whoever open the file first got the lock of that file. As such, if Excel was opening the file - then the program would have that error. Vice versa, if the program had opened the file - then the Excel may have problem opening that file. I'm not sure how to give priority to the program.

Body:
This is the first question I asked on stackoverflow, very exciting. So sorry about my grammar and other type mistakes, I would appreciate if you correct them. I want to write a program that reads a csv file if it exists in the specific folder first, stores it in List variable, add some new lines and writes it to the same file. This process will be repeated continuously in a while block.

While the file is being read and written by the program, if it is opened with Notepad, it doesn't give an error and the program could access the file in parallel. But if it is opened with Office Excel, program gives error that says "file access is denied because it is used by another process..". I want to ask you that:

1) Is it possible to give priority to the program, so program can still access the file but user cannot? Or is it possible both program and user can access the file?

2) If the solution is opening the file with Notepad, is there a way to set default program for this file as Notepad? Or how can I change default program for csv files as Notepad from C#?

Reading and writing parts of the code is as bellows:

    List<string> csvLines = new List<string>();
    string address = folderpath + @"\PLC_LOGLARI";
    if (!Directory.Exists(address))
        Directory.CreateDirectory(address);

    string fileAddress = address + @"\" + fileName + "_" + machineNo + "_1.csv";

    if (Directory.EnumerateFiles(address).Any(f => f.Contains(fileName + "_" + machineNo)))
    {
        string[] addressArray = Directory.GetFiles(address, fileName + "_" + machineNo + "*.*");
        FileInfo fileInformation = new FileInfo(addressArray[addressArray.Length - 1]);
        long fileSize = fileInformation.Length;
        if (fileSize > 5000000)
        {
            int fileNo = int.Parse(addressArray[addressArray.Length - 1].Substring(addressArray[addressArray.Length - 1].LastIndexOf('_') + 1, 1)) + 1;
            fileAddress = addressArray[addressArray.Length - 1].Substring(0, addressArray[addressArray.Length - 1].LastIndexOf('_') + 1) + fileNo.ToString() + ".csv";
        }
        else
        {
            fileAddress = addressArray[addressArray.Length - 1];
            csvLines = File.ReadAllLines(address).ToList();
        }
    }
    else
    {
        string[] headings = makeHeadings();
        csvLines.Add(headings[0]);
        csvLines.Add(headings[1]);
    }
    string newLine = "";

    // some operations and calculations for newLine
    // some operations and calculations for newLine
    // some operations and calculations for newLine

    newLine = newLine.Substring(1, newLine.Length-1);
    csvLines.Add(newLine);
    File.WriteAllLines(fileAddress, csvLines.ToArray());

Thanks for your help.


问:
JS/Angular - figure out how many html-elements are within the width/height of parent element
I am trying to create something like this here: https://www.amazon.de/Meisterwerke-Weltliteratur-Sammlung-internationaler-Meistererzählungen/dp/3839892716/

if you make the width of your browser-window smaller or bigger, you will notice the suffix of the authors-element (which is always one line) will say "X-authors hidden - show all". how can I calculate how many elements/authors are out of the bounds of the authors-parent-element, so I can tell the user how many he can expand by clicking on that suffix?

I use angular 4, but if you know the solution in plain JS, I might be able to translate it.

[EDIT]: I added two screenshots to show the effect, e.g. "& 16 mehr" and "& 14 mehr" (16 or 14 more in German).

and

答:
Write a directive who will listen to window resize, something like:</p>

```<code>@HostListener('window:resize', ['$event'])
onResize(event) {

    const elementHeight = event.target.innerHeight;
    const parentHeight = window.innerHeight;
    const visibleElements = parentHeight / elementHeight;
    const hiddenElements = Math.ceil(elementHeight - visibleElements);
    console.log(hiddenElements);
}
</code>```

Body:
Write a directive who will listen to window resize, something like:

@HostListener('window:resize', ['$event'])
onResize(event) {

    const elementHeight = event.target.innerHeight;
    const parentHeight = window.innerHeight;
    const visibleElements = parentHeight / elementHeight;
    const hiddenElements = Math.ceil(elementHeight - visibleElements);
    console.log(hiddenElements);
}


问:
How to hard code the password in this script
i am very new to shell scripts and i found this code which will create or restore a db dump in mysql. but when i execute it it asks for the password for mysql. i want to hard code this password so i don't have to input it every time i am executing it.

the code:
    #!/bin/bash
    # A shell script to restore a large SQL dump using root login.
    # Usage: ./restore_dump.sh dump.sql app_devdb

```<code>(( $# != 2 )) && { echo "Usage: $0 dump.sql database_name"; exit 1; }
[ ! -f $1 ] && { echo "$1 not found1"; exit 1; }

RESULT=`mysql -u root -p --skip-column-names -e "SHOW DATABASES LIKE '$2'"`
if [ "$RESULT" != $2 ]; then
    echo "Database '$2' does not exist; creating it...";
    mysql -u root -p -e "CREATE DATABASE IF NOT EXISTS $2;"
    [ $? -ne 0 ] && { echo "Unknown error in attempting to create database '$2'"; exit 1; }
fi

(
  echo "SET AUTOCOMMIT=0;"
  echo "SET UNIQUE_CHECKS=0;"
  echo "SET FOREIGN_KEY_CHECKS=0;"
  cat $1
  echo "SET FOREIGN_KEY_CHECKS=1;"
  echo "SET UNIQUE_CHECKS=1;"
  echo "SET AUTOCOMMIT=1;"
  echo "COMMIT;"
) | mysql -o -u root -p "$2"
</code>```

答:
If you are fine with hardcoding the password, you can simply provide it as an argument on the commandline.

For example:

mysql -u root -pMYPASSWORD ...

Body:
i am very new to shell scripts and i found this code which will create or restore a db dump in mysql. but when i execute it it asks for the password for mysql. i want to hard code this password so i don't have to input it every time i am executing it.

the code:
    #!/bin/bash
    # A shell script to restore a large SQL dump using root login.
    # Usage: ./restore_dump.sh dump.sql app_devdb

(( $# != 2 )) && { echo "Usage: $0 dump.sql database_name"; exit 1; }
[ ! -f $1 ] && { echo "$1 not found1"; exit 1; }

RESULT=`mysql -u root -p --skip-column-names -e "SHOW DATABASES LIKE '$2'"`
if [ "$RESULT" != $2 ]; then
    echo "Database '$2' does not exist; creating it...";
    mysql -u root -p -e "CREATE DATABASE IF NOT EXISTS $2;"
    [ $? -ne 0 ] && { echo "Unknown error in attempting to create database '$2'"; exit 1; }
fi

(
  echo "SET AUTOCOMMIT=0;"
  echo "SET UNIQUE_CHECKS=0;"
  echo "SET FOREIGN_KEY_CHECKS=0;"
  cat $1
  echo "SET FOREIGN_KEY_CHECKS=1;"
  echo "SET UNIQUE_CHECKS=1;"
  echo "SET AUTOCOMMIT=1;"
  echo "COMMIT;"
) | mysql -o -u root -p "$2"


问:
How to remove empty space after animating a relative layout? [ANDROID]
i am animating a relative layout on scroll of recycler view. that relative layout contains a view pager. the animation works fine but after animation there is an empty space on top of recycler view. how to solve this?
here is my code any help will be appreciated</p>

```<code>private int layout_height;
myrecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
    super.onScrollStateChanged(recyclerView, newState);
}

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
    super.onScrolled(recyclerView, dx, dy);
    if (dy > 0) {
        // Scroll Down
            layout_height+= dy;
            sliderlayout.animate().translationY(-layout_height).setInterpolator(new AccelerateInterpolator()).start();
    } else if (dy < 0) {
        // Scroll Up
            sliderlayout.animate().translationY(0).setInterpolator(new DecelerateInterpolator()).start();

    }

}
});
</code>```

答: use sliderlayout.requestLayout() will make the whole layout rendering</p>

Body:
i am animating a relative layout on scroll of recycler view. that relative layout contains a view pager. the animation works fine but after animation there is an empty space on top of recycler view. how to solve this?
here is my code any help will be appreciated

private int layout_height;
myrecyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
    super.onScrollStateChanged(recyclerView, newState);
}

@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
    super.onScrolled(recyclerView, dx, dy);
    if (dy > 0) {
        // Scroll Down
            layout_height+= dy;
            sliderlayout.animate().translationY(-layout_height).setInterpolator(new AccelerateInterpolator()).start();
    } else if (dy < 0) {
        // Scroll Up
            sliderlayout.animate().translationY(0).setInterpolator(new DecelerateInterpolator()).start();

    }

}
});


问:
Common Lisp & CFFI: modifying a global variable
my goal is to modify a C global variable.

Assuming I have the following  C header file:

```<code>/* test.h */
int global_variable;
</code>```

and the C source file:

```<code>/* test.c */
#include "stdio.h"
#include "test.h"

extern int global_variable;
void test(void) {
    FILE *fp;
    fp = fopen("output.txt", "w");
    fprintf(fp, "Global variable: %d\n", global_variable);
}
</code>```

The global_variable correctly appears inside the shared library generated by

```<code>gcc -c -fPIC test.c
gcc -shared -o libtest.so test.o
</code>```

My lisp interface looks like this:

```<code>(ql:quickload :cffi)

(cffi:define-foreign-library libtest
    (:unix (:default "./libtest"))
  (t (:default "./libtest")))

(cffi:use-foreign-library libtest)

(cffi:defcvar ("global_variable" *global-variable*) :int)

(cffi:defcfun "test" :void )
</code>```

I can call test with no error, but I cannot modify the global_variable with

```<code>(setf *global-variable* 42)
</code>```

I get a warning undefined variable, and then defines (I assume) a new variable.

So the question is how to modify the global_variable in common lisp (sbcl)?

Thank you in advance!

答:
For your struct, something like this should work:</p>

```<code>(cffi:with-foreign-object (ptr 'block)
        ;; setf the slots
        (setf (cffi:foreign-slot-value ptr 'block 'a) 12) ...etc.
</code>```

Body:
my goal is to modify a C global variable.

Assuming I have the following  C header file:

/* test.h */
int global_variable;

and the C source file:

/* test.c */
#include "stdio.h"
#include "test.h"

extern int global_variable;
void test(void) {
    FILE *fp;
    fp = fopen("output.txt", "w");
    fprintf(fp, "Global variable: %d\n", global_variable);
}

The global_variable correctly appears inside the shared library generated by

gcc -c -fPIC test.c
gcc -shared -o libtest.so test.o

My lisp interface looks like this:

(ql:quickload :cffi)

(cffi:define-foreign-library libtest
    (:unix (:default "./libtest"))
  (t (:default "./libtest")))

(cffi:use-foreign-library libtest)

(cffi:defcvar ("global_variable" *global-variable*) :int)

(cffi:defcfun "test" :void )

I can call test with no error, but I cannot modify the global_variable with

(setf *global-variable* 42)

I get a warning undefined variable, and then defines (I assume) a new variable.

So the question is how to modify the global_variable in common lisp (sbcl)?

Thank you in advance!

Body:
For your struct, something like this should work:

(cffi:with-foreign-object (ptr 'block)
        ;; setf the slots
        (setf (cffi:foreign-slot-value ptr 'block 'a) 12) ...etc.


问:
Transforming xml to xml using xslt encoded hierarchy problem xslt v1
In my input xml file I have got encoded hierarchy in elements attribute "lp":

```<code><element lp="1"/>
<element lp="1.1"/>
<element lp="2"/>
<element lp="3"/>
<element lp="3.1" />
<element lp="3.2" />
<element lp="3.2.1" />
</code>```

How to transform this xml data to

```<code><element lp="1">
   <element lp="1.1"/>
</element>
<element lp="2"/>
<element lp="3">
   <element lp="3.1"/>
   <element lp="3.2">
      <element lp="3.2.1">
   </element>
</element>
</code>```

答:
There is probably a simply way to do this with XSLT2.0, but I have assumed XSLT1.0 here.

One thing to not is that your XML is not strictly valid, because it lacks a root element. For the purposes of the answer, I have assumed the root element is called elements

To achieve this, I think you need a function to determine the 'level' of an element. This can be done by counting the number of full stops in the @lp attribute. In XSLT1.0 I have done this by removing all full-stops from the text, and comparing the resultant string length with the original string length

```<code><xsl:variable name="level" select="string-length(@lp) - string-length(translate(@lp, '.', ''))" />
</code>```

Thus to match the top level elements you would do this...

```<code><xsl:apply-templates
   select="element[string-length(@lp) - string-length(translate(@lp, '.', '')) = 0]"/>
</code>```

This would match the folllowing elements

```<code><element lp="1."/>
<element lp="2."/>
<element lp="3."/>
</code>```

Next, for each matched element, it is a case of matching following elements where

The @lp attribute begins with the current @lp attribute

The level is one more than the current level

This can be done with the following select

```<code><xsl:apply-templates
   select="following-sibling::element[substring(@lp, 1, $len) = $lp][string-length(@lp) - string-length(translate(@lp, '.', '')) = $level + 1]"/>
</code>```

(Note $len and $level are variables containing the length of the current @lp attribute and the current level)

Putting this altogether gives the following XSLT....

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:template match="/elements">
      <elements>
         <xsl:apply-templates select="element[string-length(@lp) - string-length(translate(@lp, '.', '')) = 0]"/>
      </elements>
   </xsl:template>

   <xsl:template match="element">
      <xsl:variable name="lp" select="@lp"/>
      <xsl:variable name="len" select="string-length(@lp)"/>
      <xsl:variable name="level" select="$len - string-length(translate(@lp, '.', ''))" />

      <xsl:copy>
         <xsl:copy-of select="@lp"/>
         <xsl:apply-templates select="following-sibling::element[substring(@lp, 1, $len) = $lp][string-length(@lp) - string-length(translate(@lp, '.', '')) = $level + 1]"/>
      </xsl:copy>
   </xsl:template>

</xsl:stylesheet>
</code>```

When applied to the following XML

```<code><elements>
    <element lp="1"/>
    <element lp="1.1"/>
    <element lp="2"/>
    <element lp="3"/>
    <element lp="3.1"/>
    <element lp="3.2"/>
    <element lp="3.2.1"/>
</elements>
</code>```

Produces the following output

```<code><elements>
    <element lp="1">
        <element lp="1.1"/>
    </element>
    <element lp="2"/>
    <element lp="3">
        <element lp="3.1"/>
        <element lp="3.2">
            <element lp="3.2.1"/>
        </element>
    </element>
</elements>
</code>```

Body:
In my input xml file I have got encoded hierarchy in elements attribute "lp":

<element lp="1"/>
<element lp="1.1"/>
<element lp="2"/>
<element lp="3"/>
<element lp="3.1" />
<element lp="3.2" />
<element lp="3.2.1" />

How to transform this xml data to

<element lp="1">
   <element lp="1.1"/>
</element>
<element lp="2"/>
<element lp="3">
   <element lp="3.1"/>
   <element lp="3.2">
      <element lp="3.2.1">
   </element>
</element>

Body:
There is probably a simply way to do this with XSLT2.0, but I have assumed XSLT1.0 here.

One thing to not is that your XML is not strictly valid, because it lacks a root element. For the purposes of the answer, I have assumed the root element is called elements

To achieve this, I think you need a function to determine the 'level' of an element. This can be done by counting the number of full stops in the @lp attribute. In XSLT1.0 I have done this by removing all full-stops from the text, and comparing the resultant string length with the original string length

<xsl:variable name="level" select="string-length(@lp) - string-length(translate(@lp, '.', ''))" />

Thus to match the top level elements you would do this...

<xsl:apply-templates
   select="element[string-length(@lp) - string-length(translate(@lp, '.', '')) = 0]"/>

This would match the folllowing elements

<element lp="1."/>
<element lp="2."/>
<element lp="3."/>

Next, for each matched element, it is a case of matching following elements where

The @lp attribute begins with the current @lp attribute

The level is one more than the current level

This can be done with the following select

<xsl:apply-templates
   select="following-sibling::element[substring(@lp, 1, $len) = $lp][string-length(@lp) - string-length(translate(@lp, '.', '')) = $level + 1]"/>

(Note $len and $level are variables containing the length of the current @lp attribute and the current level)

Putting this altogether gives the following XSLT....

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

   <xsl:template match="/elements">
      <elements>
         <xsl:apply-templates select="element[string-length(@lp) - string-length(translate(@lp, '.', '')) = 0]"/>
      </elements>
   </xsl:template>

   <xsl:template match="element">
      <xsl:variable name="lp" select="@lp"/>
      <xsl:variable name="len" select="string-length(@lp)"/>
      <xsl:variable name="level" select="$len - string-length(translate(@lp, '.', ''))" />

      <xsl:copy>
         <xsl:copy-of select="@lp"/>
         <xsl:apply-templates select="following-sibling::element[substring(@lp, 1, $len) = $lp][string-length(@lp) - string-length(translate(@lp, '.', '')) = $level + 1]"/>
      </xsl:copy>
   </xsl:template>

</xsl:stylesheet>

When applied to the following XML

<elements>
    <element lp="1"/>
    <element lp="1.1"/>
    <element lp="2"/>
    <element lp="3"/>
    <element lp="3.1"/>
    <element lp="3.2"/>
    <element lp="3.2.1"/>
</elements>

Produces the following output

<elements>
    <element lp="1">
        <element lp="1.1"/>
    </element>
    <element lp="2"/>
    <element lp="3">
        <element lp="3.1"/>
        <element lp="3.2">
            <element lp="3.2.1"/>
        </element>
    </element>
</elements>


问:
Is there a way to get an ArrayList from a String obtained by ArrayList.toString()?
I have this code:

```<code>ArrayList<String> list = new ArrayList<>();
String str = list.toString(); // Stored in a database
</code>```

Is there a quick way to recover the ArrayList from the string ?

答:
No, there is no reliable way to do that.

Consider the following:

```<code>List<String> list = new ArrayList<>();
list.add("A");
list.add("B, C");  // this contains commas
list.add("D");

System.out.println(list);  // [A, B, C, D] : Note, only three elements were added
</code>```

A couple of solutions:

Use a proper serialisation mechanism (e.g. JSON) rather than toString().

Store your data in a more normalised way (rather than serialising into to a single record).

Body:
I have this code:

ArrayList<String> list = new ArrayList<>();
String str = list.toString(); // Stored in a database

Is there a quick way to recover the ArrayList from the string ?

Body:
No, there is no reliable way to do that.

Consider the following:

List<String> list = new ArrayList<>();
list.add("A");
list.add("B, C");  // this contains commas
list.add("D");

System.out.println(list);  // [A, B, C, D] : Note, only three elements were added

A couple of solutions:

Use a proper serialisation mechanism (e.g. JSON) rather than toString().

Store your data in a more normalised way (rather than serialising into to a single record).


问:
How to use several input files and do parallel processing in python?
I have 30 csv files. I want to give it as input in for loop, in pandas?

Each file has names such as fileaa, fileab,fileac,filead,....

I have multiple input files and And i would like to receive one output.

Usually i use read_csv but due to memory error, 'read_csv' doesn't work.

```<code>f = "./file.csv"
df = pd.read_csv(f, sep="/", header=0, dtype=str)
</code>```

So i would like to try parallel processing in python 2.7

答:
You might want to have a look at dask.

Dask docs show a demo on how to read in many csv files and output a single dask dataframe:

```<code>import dask.dataframe as dd
df = dd.read_csv('*.csv')
</code>```

And then MANY (but not all) of the pandas methods are available, i.e.:

```<code>df.head()
</code>```

It would be useful to read more on dask dataframe to understand difference with pandas dataframe

Body:
I have 30 csv files. I want to give it as input in for loop, in pandas?

Each file has names such as fileaa, fileab,fileac,filead,....

I have multiple input files and And i would like to receive one output.

Usually i use read_csv but due to memory error, 'read_csv' doesn't work.

f = "./file.csv"
df = pd.read_csv(f, sep="/", header=0, dtype=str)

So i would like to try parallel processing in python 2.7

Body:
You might want to have a look at dask.

Dask docs show a demo on how to read in many csv files and output a single dask dataframe:

import dask.dataframe as dd
df = dd.read_csv('*.csv')

And then MANY (but not all) of the pandas methods are available, i.e.:

df.head()

It would be useful to read more on dask dataframe to understand difference with pandas dataframe


问:
Golang Webserver can't be accessed from Docker
I am using the Gorilla framework in Go to expose a webservice. I have a "Hello World" endpoint at /hello which works fine when hit from Postman, browser or curl.

The problem arises when I bundle it with Docker. My Dockerfile is as below

```<code>FROM alpine
COPY ./target/himer-users-go /app
ENV PORT 9000
RUN echo $PORT
ENTRYPOINT /app
EXPOSE ${PORT}
</code>```

Now I can ssh into the container and ping the server using wget (since alpine doesn't come bundled with curl)

But when I run the image like

```<code>docker run -d -p 9000:9000 namespace/image
</code>```

I can't access the server in any way from my host system.

Any help would be greatly appreciated.

答:
I solved it by exposing the server at 0.0.0.0 instead of localhost

The problem is that I've told my webserver to only serve requests sent to localhost. Because of the network mangling that Docker does, none of the traffic showing up to your webserver look to the webserver as though they were sent to localhost. By telling the webserver to listen on 0.0.0.0, I'm effectively telling it that it doesn't care where the traffic was originally sent and it will accept it all.

Body:
I am using the Gorilla framework in Go to expose a webservice. I have a "Hello World" endpoint at /hello which works fine when hit from Postman, browser or curl.

The problem arises when I bundle it with Docker. My Dockerfile is as below

FROM alpine
COPY ./target/himer-users-go /app
ENV PORT 9000
RUN echo $PORT
ENTRYPOINT /app
EXPOSE ${PORT}

Now I can ssh into the container and ping the server using wget (since alpine doesn't come bundled with curl)

But when I run the image like

docker run -d -p 9000:9000 namespace/image

I can't access the server in any way from my host system.

Any help would be greatly appreciated.


问:
jasmine not loading helper files
I'm trying to run jasmine helpers script but they are not being picked up.
I was looking at the jasmine API and its looks straightforward, only add helpers to jasmine.json.

This is one of the helpers I was testing. It only purpose is to create a file when jasmine is invoked.

helpers/fileHelper.js

```<code>var fs = require('fs');

fs.writeFile("./jasmineHelperOutput.txt", "Hey there!", function(err) {

    if(err) {
        return console.log(err);
    }

});
</code>```

jasmine.json

```<code>{
    "spec_dir": "./spec",
    "spec_files": [
        "**/*.spec.js"
    ],
    "helpers": [
        "helpers/**/*.js"
    ]
}
</code>```

setup:

OS: win10

node: 8.1.3

npm: 5.0.3

But it doesn't work.

What am I missing ?

I have created a simple jasmine project at https://github.com/dannyhuly/jasmine-with-helpers with the issue at hand.

Thanks.

答:
It took me a bit long to get this:

In your test.spec.js add

```<code>var helpers = require('../helpers/funcHelper.js');
var helperFS = require('../helpers/fileHelper.js');

describe('test' , function(){

    it("should run", function(){

        helpers.helper_func(); // use helper
        helperFS.writeHelper();
        expect(1).toBe(1);
    })
})
</code>```

and in fileHelper.js :

```<code>var fs = require('fs');
var writeHelper = function() {
fs.writeFile("./jasmineHelperOutput.txt", "Hey there!", function(err) {
    if (err) {
        return console.log(err);
    }})
};
exports.writeHelper = writeHelper;
</code>```

Also check this:
jasmine-git resolve code

Title: jasmine not loading helper files

Body:
I'm trying to run jasmine helpers script but they are not being picked up.
I was looking at the jasmine API and its looks straightforward, only add helpers to jasmine.json.

This is one of the helpers I was testing. It only purpose is to create a file when jasmine is invoked.

helpers/fileHelper.js

var fs = require('fs');

fs.writeFile("./jasmineHelperOutput.txt", "Hey there!", function(err) {

    if(err) {
        return console.log(err);
    }

});

jasmine.json

{
    "spec_dir": "./spec",
    "spec_files": [
        "**/*.spec.js"
    ],
    "helpers": [
        "helpers/**/*.js"
    ]
}

setup:

OS: win10

node: 8.1.3

npm: 5.0.3

But it doesn't work.

What am I missing ?

I have created a simple jasmine project at https://github.com/dannyhuly/jasmine-with-helpers with the issue at hand.

Thanks.

Body:
It took me a bit long to get this:

In your test.spec.js add

var helpers = require('../helpers/funcHelper.js');
var helperFS = require('../helpers/fileHelper.js');

describe('test' , function(){

    it("should run", function(){

        helpers.helper_func(); // use helper
        helperFS.writeHelper();
        expect(1).toBe(1);
    })
})

and in fileHelper.js :

var fs = require('fs');
var writeHelper = function() {
fs.writeFile("./jasmineHelperOutput.txt", "Hey there!", function(err) {
    if (err) {
        return console.log(err);
    }})
};
exports.writeHelper = writeHelper;

Also check this:
jasmine-git resolve code


问:
Why Laravel keeps calling schedule() with every Artisan Command?
I have one table called dc_user_meta and I've created one artisan command and scheduled it in kernel.php. Just after cloning the repository, when I try to run PHP artisan migrate, I get this error.

```<code>  [Illuminate\Database\QueryException]
  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'database.dc_user_meta' doesn't exist (SQL: select * from `dc_user_met
  a` where `meta_key` = usage_in_days)
</code>```

Not only php artisan migrate but I am unable to run any artisan command at all! I don't know why PHP keeps calling schedule method every time I try to execute any artisan command.

Here in this case, What I can do to solve this error is put the cover over my logic in schedule method just like this.

```<code>if(Schema::hasTable('dc_user_meta')){
    // Code here
}
</code>```

But I don't think it's good in Long run. What's the right way to solve this error?

UPDATE:
I just tried covering call to command in kernel.php just like this but still no success!

```<code>if(Schema::hasTable('dc_user_meta')){
    $schedule->command('usage:update')->daily();
}
</code>```

UPDATE:
I got the solution. But I don't think it's the answer to the question. It solves my problem but I don't think it's standard Solution. I just covered by Command login just like this.

```<code>if(Schema::hasTable('dc_user_meta')){
    // Command Logic
}
</code>```

Any specific answer to why Laravel calls schedule() with every artisan command and how to solve the error in a standard way if something like this happens!

答: I'm convinced that table dc_user_meta doesn't exist in database.</p>

Body:
I have one table called dc_user_meta and I've created one artisan command and scheduled it in kernel.php. Just after cloning the repository, when I try to run PHP artisan migrate, I get this error.

  [Illuminate\Database\QueryException]
  SQLSTATE[42S02]: Base table or view not found: 1146 Table 'database.dc_user_meta' doesn't exist (SQL: select * from `dc_user_met
  a` where `meta_key` = usage_in_days)

Not only php artisan migrate but I am unable to run any artisan command at all! I don't know why PHP keeps calling schedule method every time I try to execute any artisan command.

Here in this case, What I can do to solve this error is put the cover over my logic in schedule method just like this.

if(Schema::hasTable('dc_user_meta')){
    // Code here
}

But I don't think it's good in Long run. What's the right way to solve this error?

UPDATE:
I just tried covering call to command in kernel.php just like this but still no success!

if(Schema::hasTable('dc_user_meta')){
    $schedule->command('usage:update')->daily();
}

UPDATE:
I got the solution. But I don't think it's the answer to the question. It solves my problem but I don't think it's standard Solution. I just covered by Command login just like this.

if(Schema::hasTable('dc_user_meta')){
    // Command Logic
}

Any specific answer to why Laravel calls schedule() with every artisan command and how to solve the error in a standard way if something like this happens!


问:
how can i access vuejs data in method
I have saved a collection of data from database to an array in vue.js using ajax request in laravel. I want to get some data from that collection inside a method so that i can make more data for the body but somehow I can not access it. for example, by using the code below.

```<code>var vm = this;
$.get('url', function (response) {
      vm.time_slots = response;
      for( i=0; i < vm.time_slots.length; i++){  //also tried with var/let i
         if(i=0){
            console.log(vm.time_slots[i].start_time);
         }else if(vm.time_slots[i].start_time > vm.time_slots[i-1].start_time){
           console.log(vm.time_slots[i].start_time);
         }
      }
     }, 'json');
</code>```

i get undifined. but if i access it through the console i get what i need. below is the data.

```<code>data: {
  time_slots: [],
  current_timeslots: []
},
</code>```

now each time_slot in time_slots has a start_date end_date etc. i want to access them but i get undefined. even this.time_slots.length is returned as 0, while if i check in console i get 12.
how can i access data with in the method.

答:
$.get performs an asynchronous HTTP request. The data you get back from that request is only available inside the callback function.

```<code>var vm = this;

$.get('url', function (response) {
  // This code executes once the data is available
  vm.time_slots = response;

  // This works
  console.log(vm.time_slots[0]);
}, 'json');

// This line executes immediately after the above HTTP request is
// sent but not yet resolved, so the data isn't available
console.log(vm.time_slots[0]);
</code>```

It's important to understand how AJAX requests work, in particular the async nature of performing such HTTP requests in JavaScript.

You should put breakpoints at various spots in the above code and step through the execution paths in the browser's debugger to see just how it works.

Here's another (simpler) example which demonstrates how this works:

```<code>var data = 'hello';

setTimeout(function() {
  data = 'world';
  console.log('inside callback: ' + data);
}, 1000);

console.log('outside callback: ' + data);
</code>```

Title: how can i access vuejs data in method

Body:
I have saved a collection of data from database to an array in vue.js using ajax request in laravel. I want to get some data from that collection inside a method so that i can make more data for the body but somehow I can not access it. for example, by using the code below.

var vm = this;
$.get('url', function (response) {
      vm.time_slots = response;
      for( i=0; i < vm.time_slots.length; i++){  //also tried with var/let i
         if(i=0){
            console.log(vm.time_slots[i].start_time);
         }else if(vm.time_slots[i].start_time > vm.time_slots[i-1].start_time){
           console.log(vm.time_slots[i].start_time);
         }
      }
     }, 'json');

i get undifined. but if i access it through the console i get what i need. below is the data.

data: {
  time_slots: [],
  current_timeslots: []
},

now each time_slot in time_slots has a start_date end_date etc. i want to access them but i get undefined. even this.time_slots.length is returned as 0, while if i check in console i get 12.
how can i access data with in the method.

Body:
$.get performs an asynchronous HTTP request. The data you get back from that request is only available inside the callback function.

var vm = this;

$.get('url', function (response) {
  // This code executes once the data is available
  vm.time_slots = response;

  // This works
  console.log(vm.time_slots[0]);
}, 'json');

// This line executes immediately after the above HTTP request is
// sent but not yet resolved, so the data isn't available
console.log(vm.time_slots[0]);

It's important to understand how AJAX requests work, in particular the async nature of performing such HTTP requests in JavaScript.

You should put breakpoints at various spots in the above code and step through the execution paths in the browser's debugger to see just how it works.

Here's another (simpler) example which demonstrates how this works:

var data = 'hello';

setTimeout(function() {
  data = 'world';
  console.log('inside callback: ' + data);
}, 1000);

console.log('outside callback: ' + data);


问:
Mobx Observable Array not updated
I am declaring a observable array in the following way in reactjs using mobx

```<code>@observable cacheditems

constructor() {
    this.cacheditems  =   []
</code>```

Now I am retrieving the data from pouch-db when offline as follows:

```<code>var items = []
db.allDocs({include_docs: true}, function(err, docs) {
                docs.rows.map((obj, id) => {
                    items.push(obj.doc)
                })
            })

 this.cacheditems = items
</code>```

But the data is not set. When I try to get the data for rendering its a empty array.

答:
When you do this.cacheditems = items you are overwriting the reference to the observable array. You can use replace instead:

```<code>class Store {
  @observable cacheditems = []

  constructor() {
    db.allDocs({include_docs: true}, (err, docs) => {
      var items = []
      docs.rows.map((obj, id) => {
        items.push(obj.doc)
      })
      this.cacheditems.replace(items)
    })
  }
}
</code>```

Title: Mobx Observable Array not updated

Body:
I am declaring a observable array in the following way in reactjs using mobx

@observable cacheditems

constructor() {
    this.cacheditems  =   []

Now I am retrieving the data from pouch-db when offline as follows:

var items = []
db.allDocs({include_docs: true}, function(err, docs) {
                docs.rows.map((obj, id) => {
                    items.push(obj.doc)
                })
            })

 this.cacheditems = items

But the data is not set. When I try to get the data for rendering its a empty array.

Body:
When you do this.cacheditems = items you are overwriting the reference to the observable array. You can use replace instead:

class Store {
  @observable cacheditems = []

  constructor() {
    db.allDocs({include_docs: true}, (err, docs) => {
      var items = []
      docs.rows.map((obj, id) => {
        items.push(obj.doc)
      })
      this.cacheditems.replace(items)
    })
  }
}


问:
Alternative to "header" for re-directs in PHP
I am working on a project and I am required to run my program on someone else's webserver. It is a pretty simple login page that I am having the problem with.  The program works correctly if I run it through my local host via WAMP.  The problem I am having is that the re-direct portion is not working correctly it validates the user and starts a session but when it gets to the redirect nothing happens.

I am either doing something wrong with my syntax which I think is highly unlikely since it does work correctly through my local host. Or alternatively I'm thinking that the server does not have that function (not sure if its possible to pick and choose which modules your server supports although I'm sure it's feasible).

I don't know if it matters but they are using "cpanel" which is where I can access the files and there all in the same directory so if someone could tell me where I am going wrong or suggest an alternative to redirecting via "header" any help would be greatly appreciated.  I've looked around but it seems that "header" is the standard work horse.

Heres the code I have:

```<code>if( (!empty($_POST['username'])) && (!empty($_POST['password'])) )
{
// username and password sent from Form
$myusername = $_POST['username'];
$mypassword = $_POST['password'];

$sql="SELECT UserName FROM User WHERE UserName='$myusername' and        Password='$mypassword'";

$result=mysql_query($sql);

$row=mysql_fetch_array($result);
//$active=$row['active'];
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
    echo "we made if to the if";
    session_start();
    session_register("myusername");
    $_SESSION['login_user']=$myusername;
    echo "right b4 the re-direct";
    header("location: UI.php");
            exit;
}
else
    echo "Your user name/password was not correct pleast TRY AGAIN!!!";

}
</code>```

Update:  In response to the statements about the echos would the problem possible by that I am processing my form in the same file and using echo $_SERVER['PHP_SELF']

Body:
I am working on a project and I am required to run my program on someone else's webserver. It is a pretty simple login page that I am having the problem with.  The program works correctly if I run it through my local host via WAMP.  The problem I am having is that the re-direct portion is not working correctly it validates the user and starts a session but when it gets to the redirect nothing happens.

I am either doing something wrong with my syntax which I think is highly unlikely since it does work correctly through my local host. Or alternatively I'm thinking that the server does not have that function (not sure if its possible to pick and choose which modules your server supports although I'm sure it's feasible).

I don't know if it matters but they are using "cpanel" which is where I can access the files and there all in the same directory so if someone could tell me where I am going wrong or suggest an alternative to redirecting via "header" any help would be greatly appreciated.  I've looked around but it seems that "header" is the standard work horse.

Heres the code I have:

if( (!empty($_POST['username'])) && (!empty($_POST['password'])) )
{
// username and password sent from Form
$myusername = $_POST['username'];
$mypassword = $_POST['password'];

$sql="SELECT UserName FROM User WHERE UserName='$myusername' and        Password='$mypassword'";

$result=mysql_query($sql);

$row=mysql_fetch_array($result);
//$active=$row['active'];
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1)
{
    echo "we made if to the if";
    session_start();
    session_register("myusername");
    $_SESSION['login_user']=$myusername;
    echo "right b4 the re-direct";
    header("location: UI.php");
            exit;
}
else
    echo "Your user name/password was not correct pleast TRY AGAIN!!!";

}

Update:  In response to the statements about the echos would the problem possible by that I am processing my form in the same file and using echo $_SERVER['PHP_SELF']

Body: echo "<script>window.location.href='yourPage.php'</script>";


问:
How do I check if a character is a Unicode new-line character (not only ASCII) in Rust?
Every programming language has their own interpretation of \n and \r.
Unicode supports multiple characters that can represent a new line.

From the Rust reference:

A whitespace escape is one of the characters U+006E (n), U+0072 (r),
  or U+0074 (t), denoting the Unicode values U+000A (LF), U+000D (CR) or
  U+0009 (HT) respectively.

Based on that statement, I'd say a Rust character is a new-line character if it is either \n or \r. On Windows it might be the combination of \r and \n. I'm not sure though.

What about the following?

Next line character (U+0085)

Line separator character (U+2028)

Paragraph separator character (U+2029)

In my opinion, we are missing something like a char.is_new_line().
I looked through the Unicode Character Categories but couldn't find a definition for new-lines.

Do I have to come up with my own definition of what a Unicode new-line character is?

答:
There is considerable practical disagreement between languages like Java, Python, Go and JavaScript as to what constitutes a newline-character and how that translates to "new lines". The disagreement is demonstrated by how the batteries-included regex engines treat patterns like $ against a string like \r\r\n\n in multi-line-mode: Are there two lines (\r\r\n, \n), three lines (\r, \r\n, \n, like Unicode says) or four (\r, \r, \n, \n, like JS sees it)? Go and Python do not treat \r\n as a single $ and neither does Rust's regex crate; Java's does however. I don't know of any language whose batteries extend newline-handling to any more Unicode characters.

So the takeaway here is

It is agreed upon that \n is a newline

\r\n may be a single newline

unless \r\n is treated as two newlines

unless \r\n is "some character followed by a newline"

You shall not have any more newlines beside that.

If you really need more Unicode characters to be treated as newlines, you'll have to define a function that does that for you. Don't expect real-world input that expects that. After all, we had the ASCII Record separator for a gazillion years and everybody uses \t instead as well.

Update: See http://www.unicode.org/reports/tr14/tr14-32.html#BreakingRules  section LB5 for why \r\r\n should be treated as two line breaks. You could read the whole page to get a grip on how your original question would have to be implemented. My guess is by the point you reach "South East Asian: line breaks require morphological analysis" you'll close the tab :-)


问:
Allow user to add and resize shapes
I want to allow a user to add shapes/resize them, with a shape panel like the one on this page:

https://logomakr.com/

I have read into this and the use HTML canvas seems inevitable. My issue is allowing the user to add more than 1 of each shape and allowing the user to resize each shape.

答:
You can achieve that using a JavaScript canvas library, called FabricJS.

ᴅᴇᴍᴏ

var canvas = new fabric.Canvas('c');

function addRectangle() {
   var rectangle = new fabric.Rect({
      top: 65,
      left: 65,
      width: 50,
      height: 50,
      fill: '#03A9F4'
   });
   canvas.add(rectangle);
}

function addTriangle() {
   var triangle = new fabric.Triangle({
      top: 65,
      left: 65,
      width: 50,
      height: 50,
      fill: '#4CAF50'
   });
   canvas.add(triangle);
}

function addCircle() {
   var circle = new fabric.Circle({
      top: 65,
      left: 65,
      radius: 25,
      fill: '#f44336'
   });
   canvas.add(circle);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body { margin: 10px 0 0 0 }
canvas { border: 1px solid #ccc }
button { margin-top: 9px }</code>```

<canvas id="c" width="180" height="180"></canvas>
<button onclick="addRectangle()">Add Rectangle</button>
<button onclick="addTriangle()">Add Triangle</button>
<button onclick="addCircle()">Add Circle</button>```

To learn more about this library, refer to the official documentation.

Title: Allow user to add and resize shapes

Body:
You can achieve that using a JavaScript canvas library, called FabricJS.

ᴅᴇᴍᴏ

var canvas = new fabric.Canvas('c');

function addRectangle() {
   var rectangle = new fabric.Rect({
      top: 65,
      left: 65,
      width: 50,
      height: 50,
      fill: '#03A9F4'
   });
   canvas.add(rectangle);
}

function addTriangle() {
   var triangle = new fabric.Triangle({
      top: 65,
      left: 65,
      width: 50,
      height: 50,
      fill: '#4CAF50'
   });
   canvas.add(triangle);
}

function addCircle() {
   var circle = new fabric.Circle({
      top: 65,
      left: 65,
      radius: 25,
      fill: '#f44336'
   });
   canvas.add(circle);
}

body { margin: 10px 0 0 0 }
canvas { border: 1px solid #ccc }
button { margin-top: 9px }

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.14/fabric.min.js"></script>
<canvas id="c" width="180" height="180"></canvas>
<button onclick="addRectangle()">Add Rectangle</button>
<button onclick="addTriangle()">Add Triangle</button>
<button onclick="addCircle()">Add Circle</button>

To learn more about this library, refer to the official documentation.


问:
How do I link the data-key attribute of two elements using javascript?
I'd been following the #javascript30 course in which he links the data-key of a div with the data-key of an audio using javascript and a keydown event as follows

html

```<code><div data-key = "65" class = "key">
<kbd> A </kbd> <br> <span> Boom </span>
</div>

<audio data-key = "65" src = "sounds/boom.wav" id = "boom"> </audio>
</code>```

javascript

```<code>function playSound(e)
{
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
audio.play();
}
</code>```

Now I want to play the audio when I click on the div but I don't know how to start. I've attempted this, but it says Uncaught ReferenceError: key is not defined. So how do I get it to play the audio on a click event?

NOTE: I have eight different audio files for eight different divs. Corresponding pairs have the same data-key.

```<code>$(".key").click(function()
{
const audio = document.getElementById(`${this.data-key}`)
console.log(audio);
audio.play();
});
</code>```

答:
If you have multiple audios, you can use this

$(".key").click(function() {
 var key = $(this).data('key');
 var audio = $('audio[data-key='+key+']');
 audio[0].play();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-key="65" class="key">
  <kbd> A </kbd> <br> <span> Boom </span>
</div>

<audio data-key="65" src="http://freewavesamples.com/files/Alesis-Sanctuary-QCard-AcoustcBas-C2.wav"> </audio></code>```

Body:
I'd been following the #javascript30 course in which he links the data-key of a div with the data-key of an audio using javascript and a keydown event as follows

html

 A
  Boom

<audio data-key = "65" src = "sounds/boom.wav" id = "boom"> </audio>

javascript

function playSound(e)
{
const audio = document.querySelector(`audio[data-key="${e.keyCode}"]`);
audio.play();
}

Now I want to play the audio when I click on the div but I don't know how to start. I've attempted this, but it says Uncaught ReferenceError: key is not defined. So how do I get it to play the audio on a click event?

NOTE: I have eight different audio files for eight different divs. Corresponding pairs have the same data-key.

$(".key").click(function()
{
const audio = document.getElementById(`${this.data-key}`)
console.log(audio);
audio.play();
});

Body:
If you have multiple audios, you can use this

$(".key").click(function() {
 var key = $(this).data('key');
 var audio = $('audio[data-key='+key+']');
 audio[0].play();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-key="65" class="key">
  <kbd> A </kbd> <br> <span> Boom </span>
</div>

<audio data-key="65" src="http://freewavesamples.com/files/Alesis-Sanctuary-QCard-AcoustcBas-C2.wav"> </audio>


问:
Translate function in Python 3
I am using Python 3 and I want to translate my file names to have no numbers. The translate function doesn't seem to work in Python 3. How can I translate the file names to have no numbers?

This is the block of code that doesn't work:

```<code>file_name = "123hello.jpg"
file_name.translate(None, "0123456789")
</code>```

Thanks

答:
Only remove numbers from the left

```<code>new_name = str.lstrip('1234567890')
</code>```

Only remove numbers from the right

```<code>new_name = str.rstrip('1234567890')
</code>```

Remove number from left and right

```<code>new_name = str.strip('1234567890')
</code>```

Remove all numbers

```<code>new_name = str.translate(str.maketrans('', '', '1234567890'))
</code>```

ContentLicense: CC BY-SA 4.0

Title: Translate function in Python 3

Body:
I am using Python 3 and I want to translate my file names to have no numbers. The translate function doesn't seem to work in Python 3. How can I translate the file names to have no numbers?

This is the block of code that doesn't work:

file_name = "123hello.jpg"
file_name.translate(None, "0123456789")

Thanks

Body:
Only remove numbers from the left

new_name = str.lstrip('1234567890')

Only remove numbers from the right

new_name = str.rstrip('1234567890')

Remove number from left and right

new_name = str.strip('1234567890')

Remove all numbers

new_name = str.translate(str.maketrans('', '', '1234567890'))


问:
How do you split an array into array pairs in JavaScript?
I want to split an array into pairs of arrays.

```<code>var arr = [2, 3, 4, 5, 6, 4, 3, 5, 5]
</code>```

would be

```<code>var newarr = [
    [2, 3],
    [4, 5],
    [6, 4],
    [3, 5],
    [5]
]
</code>```

答:
You can use js reduce </p>

```<code>initialArray.reduce(function(result, value, index, array) {
  if (index % 2 === 0)
    result.push(array.slice(index, index + 2));
  return result;
}, []);
</code>```

Body:
I want to split an array into pairs of arrays.

var arr = [2, 3, 4, 5, 6, 4, 3, 5, 5]

would be

var newarr = [
    [2, 3],
    [4, 5],
    [6, 4],
    [3, 5],
    [5]
]

Body:
You can use js reduce

initialArray.reduce(function(result, value, index, array) {
  if (index % 2 === 0)
    result.push(array.slice(index, index + 2));
  return result;
}, []);


问:
How to execute inline source blocks in an org-mode table?
I would like to have the output of src_R blocks in an org-mode table:

```<code>| Variable | Value    |
|----------+----------|
| x        | src_R{x} |
</code>```

However, when I export to PDF (via LaTeX) I get the literal src_R{x} rather than the value of the x variable in the underlying R session. I can use the same src_R{x} in text and it works as expected.

Is there a way to support inline source code in tables?

(I have seen this question with a similar title: Code blocks inside tables for org-mode, but the topic is different.)

答:
Thanks to the prompt by Juancho (see comments), I have found the answer here: http://orgmode.org/worg/org-contrib/babel/intro.html#spreadsheet. I first define a named source block to perform my R computation:

```<code>#+NAME: my-code
#+BEGIN_SRC R :results output
  message(10)
#+END_SRC
</code>```

(Imagine the output is simply the number 10). Then I insert it into the table like this:

```<code>| Variable | Value |
|----------+-------|
| Name     |       |
#+TBLFM: @2$2='(org-sbe my-code)
</code>```

Comments:

It seems that org-babel-execute is no longer there, the docs use org-sbe, which works with my 9.0.x org-mode version.

I have wrapped the code output in message() to avoid extra output from R. I have tried various header arguments to the R code (e.g., :results value raw) but I get either extra parentheses, presumably from lisp, or errors.

With org-sbe you can also pass arguments to the code, and even the output of other code blocks. This is explained in the docs referenced above.

Body:
I would like to have the output of src_R blocks in an org-mode table:

| Variable | Value    |
|----------+----------|
| x        | src_R{x} |

However, when I export to PDF (via LaTeX) I get the literal src_R{x} rather than the value of the x variable in the underlying R session. I can use the same src_R{x} in text and it works as expected.

Is there a way to support inline source code in tables?

(I have seen this question with a similar title: Code blocks inside tables for org-mode, but the topic is different.)

Body:
Thanks to the prompt by Juancho (see comments), I have found the answer here: http://orgmode.org/worg/org-contrib/babel/intro.html#spreadsheet. I first define a named source block to perform my R computation:

#+NAME: my-code
#+BEGIN_SRC R :results output
  message(10)
#+END_SRC

(Imagine the output is simply the number 10). Then I insert it into the table like this:

| Variable | Value |
|----------+-------|
| Name     |       |
#+TBLFM: @2$2='(org-sbe my-code)

Comments:

It seems that org-babel-execute is no longer there, the docs use org-sbe, which works with my 9.0.x org-mode version.

I have wrapped the code output in message() to avoid extra output from R. I have tried various header arguments to the R code (e.g., :results value raw) but I get either extra parentheses, presumably from lisp, or errors.

With org-sbe you can also pass arguments to the code, and even the output of other code blocks. This is explained in the docs referenced above.


问:
d3js - How to move x- domain values towards right
I am working on one chart using d3.js version 4.
So I want to move plotting of bar chart towards right as shown below.

Usually the bar renders from starting position as shown below

Please help ....!
    Demo fiddle

答:
Consider your svg like an HTML element. You inside, bar are grouped by a "d" element. You just have to add a transform: translateX(50px) to move the whole bar to the right.

For example, just add this css rule on your document to align the black, blue, an yellow bar :

```<code>g.stack {
    transform: translateX(48px);
}
</code>```

Body:
Consider your svg like an HTML element. You inside, bar are grouped by a "d" element. You just have to add a transform: translateX(50px) to move the whole bar to the right.

For example, just add this css rule on your document to align the black, blue, an yellow bar :

g.stack {
    transform: translateX(48px);
}


问:
How does Smule Sing Audio Effects work?
There's a Karaoke App on the Play Store and App Store called Smule - Sing Karaoke. I used that app to sing many songs. But now being an Android Developer I really wonder how those audio effects actually work. Is there anything to do with Android/Java or they just write native C++ codes manipulate the audio. How much time or what expertise needed to do something like that?</p>

答:
There are many DSP/audio processing libraries out there written both in Java or C++
such as TarsosDSP or Tuna

I cannot recommend any of them as this question might be off-topic, I suggest to google it. You will find many results

Title: How does Smule Sing Audio Effects work?


问:
Why do I get an Angular compile error in this simple component
I have just "written" (copied structure not content) this little Angular 4 module:

```<code>import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { HttpModule } from "@angular/http";

import { FooterComponent } from "./footer.component";

@NgModule({
  declarations: [
    FooterComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [FooterComponent]
})
export class FooterModule { }
</code>```

When I try an angular build, I get the following error:

ERROR in C:/Projects/Angular 4/Angular4/src/footer.module.ts (7,1):
  'from' expected.

To me, line 7, import { FooterComponent } from "./footer.component";, looks syntactically correct, and even has a from. If the from component is bad, I'd rather expect a runtime error.

答:
Type the following:

```<code>import { } from "./footer.component";
</code>```

Then place the cursor inside the curlies and hit Ctrl-Space in your IDE. See if it suggests FooterComponent. If not, the issue is in the footer.component.ts.

Body:
I have just "written" (copied structure not content) this little Angular 4 module:

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { HttpModule } from "@angular/http";

import { FooterComponent } from "./footer.component";

@NgModule({
  declarations: [
    FooterComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [],
  bootstrap: [FooterComponent]
})
export class FooterModule { }

When I try an angular build, I get the following error:

ERROR in C:/Projects/Angular 4/Angular4/src/footer.module.ts (7,1):
  'from' expected.

To me, line 7, import { FooterComponent } from "./footer.component";, looks syntactically correct, and even has a from. If the from component is bad, I'd rather expect a runtime error.

Body:
Type the following:

import { } from "./footer.component";

Then place the cursor inside the curlies and hit Ctrl-Space in your IDE. See if it suggests FooterComponent. If not, the issue is in the footer.component.ts.


问:
What is the purpose of java.util.concurrent.CompletableFuture#allOf?
If I have Collection<CompletableFuture<MyResult>>, I expect to convert this into CompletableFuture<Collection<MyResult>>. So after conversion I have only one future and can easyly write bussines logic on MyResult collection using methods from CompletableFuture like thenApply, thenAccept etc. But CompletableFuture#allOf have result type Void so after invoking it I get "no results". E.g. I can not retrieve (as I understand) any results from returned future that correspods to Collection<CompletableFuture<MyResult>>.

I have a doubt that CompletableFuture#allOf just return the Future wich is completed after all in collection. So I can invoke CompletableFuture#allOf(...).isDone and then manually (!) in cycle tranform Collection<CompletableFuture> to CompletableFuture<Collection>, Is my assumption right?

答: if you need CompletableFuture<Collection<MyResult>> as result you can get  it by using allAsList method in https://github.com/spotify/completable-futures  (spotify-completlablefutures library). CompletableFutures.allAsList(List<CompletableFuture<MyResult>>) will give you CompletableFuture<List<MyResult>>.


问:
How to put a dynamic text on top of an image for different email providers ? (Responsive Email)
I am currently working on an email template that has to be compatible with the major email providers.

According with the client I supposed to create a salutation paragraph or header on top of an image so i tried this solution which is working fine on browser but definitely not on the emails (tested on Outlook, hotmail, gmail and yahoo) and none of these read the property position: absolute(i think not sure).

The template has also to be responsive so if i resize the the screen the text should adjust regarding the width of the screen.
Because of the multiple issues on email i had to create 2 tables one inside the other in order to create a border around the image and then the second table inside to display the image itself.

The text should be inside the pink roadsign and it's Hi Margaret, which will be then dynamic.

Here is my code:

```<code><!doctype html>
 <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
   <head>
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <meta http-equiv="X-UA-Compatible" content="IE=9" />
      <meta charset="UTF-8">

<style type="text/css">
    body {
        background: #dff1f6 !important;
        font-family: Arial, sans-serif;
    }

    .preheader {
        display: none !important;
        visibility: hidden !important;
        opacity: 0 !important;
        color: transparent !important;
        height: 0 !important;
        width: 0 !important;
    }

    @media (max-width: 376px) {
        .anglianlogo {
            max-width: 250px !important;
        }

        .anglianwellcome {
            font-size: 11px !important;
        }

        .awvideopreview {
            height: 150px;
        }

        .mobileresize {
            width: 90% !important;
            font-size: 9px;
        }
    }
</style>
</code>```

```<code><div style="background: #dff1f6;">

    <!--Container-->

    <table cellpadding="0" cellspacing="0" border="0" style="padding:0px;margin:0px;width:100%;">
        <tr><td colspan="3" style="padding:0px;margin:0px;font-size:20px;height:20px;" height="20"> </td></tr>
        <tr>
            <td style="padding:0px;margin:0px;"> </td>
            <td style="padding:0px;margin:0px;" width="600">

                <!--Main Table-->

                <table width="100%" cellspacing="0" cellpadding="0" border="0" style="max-width: 600px; width: 100%; margin: 0 auto; background: white;">
                    <tr>
                        <td>

                            <!--Video-->

                            <table width="600" cellspacing="0" cellpadding="0" border="0" style="padding-bottom: 30px; padding-left:10%; padding-right:10%; width:100%;">
                                <tr>
                                    <td>
                                        <table border="0" cellspacing="0" cellpadding="0" align="center" style="text-align:center; margin: 0 auto;">
                                            <tr>
                                                <td style="padding: 0; border: 10px solid #72b8d1;">
                                                    <a style="margin: 0 auto; display: block;">
                                                        <!--href="{{ CustomerData.vidUrl }}"-->
                                                        <img class="awvideopreview" src="https://preview.ibb.co/gKOzsv/Videopreview.gif" width="450" border="0" align="center" style="width:100%;">
                                                    </a>
                                                </td>
                                            </tr>
                                        </table>
                                    </td>
                                </tr>
                            </table>

                        </td>
                    </tr>
                </table>

                      <!--End Table-->

                 </td>
                 <td style="padding:0px;margin:0px;"> </td>
             </tr>
                <tr><td colspan="3" style="padding:0px;margin:0px;font-size:20px;height:20px;" height="20"> </td></tr>
         </table>

       <!--End Container-->
    </div>

     </body>
    </html>
</code>```

答:
What do you have inside your CSS classes? Please put your code in jsfiddle so I can test it on e-mail.
HTML for e-mails takes a different approach than normaly. A lot of tables and inline styling and compatibility issues.

Checkout this link. It can help find you some problems. (but for now show us the fiddle)

https://www.htmlemailcheck.com/

Body:
I am currently working on an email template that has to be compatible with the major email providers.

According with the client I supposed to create a salutation paragraph or header on top of an image so i tried this solution which is working fine on browser but definitely not on the emails (tested on Outlook, hotmail, gmail and yahoo) and none of these read the property position: absolute(i think not sure).

The template has also to be responsive so if i resize the the screen the text should adjust regarding the width of the screen.
Because of the multiple issues on email i had to create 2 tables one inside the other in order to create a border around the image and then the second table inside to display the image itself.

The text should be inside the pink roadsign and it's Hi Margaret, which will be then dynamic.

Here is my code:

<!doctype html>

      <meta name="viewport" content="width=device-width, initial-scale=1">
      <meta http-equiv="X-UA-Compatible" content="IE=9" />
      <meta charset="UTF-8">