问:
Cross-framework Solutions for field Annotations
Does anyone have any strategies or examples of cross-framework libraries?

I am working on a project with an android app, a java server and a Java desktop client, which all use different frameworks. I need to refactor some core business logic into a separate library that can be used across all of these to ensure consistent behavior, but the field annotations are killing me.

The problem is that I am using Room in the Android app (which requires the @PrimaryKey annotation on the primary key field of a database entity) and JPA in the server and JavaFX client (which requires @Id).

Given this level of difficulty with the models, we initially copy-pasted the fields without annotations to the others when changing them. However,  the business logic needs to make use of the models and accommodate each platform's specific ORM, Http client and Json serializer. (I know that it is technically possible to get Gson, Apache Http and Hibernate to run on all of these platforms, but actually doing any of these solutions created too many nightmares of its own)

As far as I can tell, there isn't a nice solution to this. Fortunately, the same @Inject is used in Dagger2 and CDI/CDI-SE so I have created some interfaces that each platform/framework will implement.

Does anybody have any examples or case studies I could look at which might help me arrive at a solution?

(I realize this question doesn't include any code samples, but it's more of a general programming strategy question.)

答:
Disclaimer: I am the architect of JDX for Java and JDXA for Android ORMs.

You may consider using JDX for Java and JDXA for Android ORM frameworks to share the common object model, the core business logic code, and the data integration code across Java server, Java desktop, and Android platforms.

JDX and JDXA don't use annotations to define the mapping - instead they use an external text file to define the mapping specification based on a simple ORM grammar. So you may use the same mapping specification for your common object model across different platforms. Also, the APIs for both JDX and JDXA are simliar.

So, you just need to use the appropriate JDX(A) ORM library for your target platform and an appropriate JDBC driver for your target database without needing to change your object model or business logic.


来源: stackexchange

问:
Connect access query to excel with dynamic input parameter
I've got some queries I have connected to an excel sheet that I refresh in order to get the latest data.

Is it possible to make excel "ask" for input parameters for one column lets say?

I am looking to get data by company so wondering if it's possible to do it as in access (type [company]:) in the field criteria

If I save the query like that in access it won't let me connect it to excel

Thanks

答:
Alright another edit.

Here it is, I created a database, its simple.
The database is called "Database1.accdb"

There are more records than shown in the screen shot.

I created a workbook with one sheet, its name is "AccessDBtest.xlsm"

I created a button on Sheet1 and entered the field parameter I wanted in the cell beside it, C3 or (3,3) in (row,col) format.

This is the code that works returning the data set (without field names) based on the input criteria.  I made a msgBox before the SQL query execution so that I could look at it first.  You don't need that if you do not want it, good for testing.

```<code>Private Sub CommandButton1_Click()
Dim inputSheet As Worksheet
Dim fieldSTR As String
Dim placementRange As Range

Dim rs As Object 'record set

Dim conn As Object
Dim strQuery As String

Dim myDB As String

Set inputSheet = ThisWorkbook.Worksheets("Sheet1")
Set placementRange = inputSheet.Range("E2")

fieldSTR = CStr(inputSheet.Cells(3, 3).Value) 'C3 cell

myDB = "C:\Users\Documents\0_Excel Projects\Testing\Database1.accdb"

Set conn = CreateObject("ADODB.Connection")

    With conn
        .Provider = "Microsoft.ACE.OLEDB.12.0"    'For *.ACCDB Databases
        .ConnectionString = myDB
        .Open
    End With

strQuery = "SELECT * FROM " & _
            "tbl_test WHERE tbl_test.Color = " & "'" & fieldSTR & "'" & ";"

'The below gives the same result as * but you could limit the fields returned as well
'tbl_test.ID, tbl_test.Color, tbl_test.number

'just using Color also works you do not need to reference the table directly

MsgBox (strQuery)

Set rs = conn.Execute(strQuery)

placementRange.CopyFromRecordset rs

rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing

End Sub
</code>```

See if you can map what you want to do using that.
I wanted to capture a string from a cell and then use that string in the query.

Here is the MsgBox before the query executes (what access will see):
I tested it with * for all fields and below you can see that I called up specific fields, they both work.

And here is what happens after I clear the msgBox, the recordset is pulled and pasted starting in the range I specified Range.("E3") on the sheet I specified (Sheet1)

As you can see, we can pull queries from a database using input that is found on a current sheet.

Let me know if this helps your situation.

We can dig deeper if required.

-WWC

ContentLicense: CC BY-SA 3.0

Body:
Alright another edit.

Here it is, I created a database, its simple.
The database is called "Database1.accdb"

There are more records than shown in the screen shot.

I created a workbook with one sheet, its name is "AccessDBtest.xlsm"

I created a button on Sheet1 and entered the field parameter I wanted in the cell beside it, C3 or (3,3) in (row,col) format.

This is the code that works returning the data set (without field names) based on the input criteria.  I made a msgBox before the SQL query execution so that I could look at it first.  You don't need that if you do not want it, good for testing.

Private Sub CommandButton1_Click()
Dim inputSheet As Worksheet
Dim fieldSTR As String
Dim placementRange As Range

Dim rs As Object 'record set

Dim conn As Object
Dim strQuery As String

Dim myDB As String

Set inputSheet = ThisWorkbook.Worksheets("Sheet1")
Set placementRange = inputSheet.Range("E2")

fieldSTR = CStr(inputSheet.Cells(3, 3).Value) 'C3 cell

myDB = "C:\Users\Documents\0_Excel Projects\Testing\Database1.accdb"

Set conn = CreateObject("ADODB.Connection")

    With conn
        .Provider = "Microsoft.ACE.OLEDB.12.0"    'For *.ACCDB Databases
        .ConnectionString = myDB
        .Open
    End With

strQuery = "SELECT * FROM " & _
            "tbl_test WHERE tbl_test.Color = " & "'" & fieldSTR & "'" & ";"

'The below gives the same result as * but you could limit the fields returned as well
'tbl_test.ID, tbl_test.Color, tbl_test.number

'just using Color also works you do not need to reference the table directly

MsgBox (strQuery)

Set rs = conn.Execute(strQuery)

placementRange.CopyFromRecordset rs

rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing

End Sub

See if you can map what you want to do using that.
I wanted to capture a string from a cell and then use that string in the query.

Here is the MsgBox before the query executes (what access will see):
I tested it with * for all fields and below you can see that I called up specific fields, they both work.

And here is what happens after I clear the msgBox, the recordset is pulled and pasted starting in the range I specified Range.("E3") on the sheet I specified (Sheet1)

As you can see, we can pull queries from a database using input that is found on a current sheet.

Let me know if this helps your situation.

We can dig deeper if required.

-WWC


问:
In Swift 4, how can you get the string-representation of a data type stored in a variable of type 'Any'?
What is the easiest way to get the string-representation of a value's data type if that value is stored in an 'Any' variable?

For instance, I'm debugging code that has this...

```<code>extension SomeClass : Mappable{

    static func map(value:Any) -> SomeClass{

        return Parse(value)

    }
}
</code>```

I'm trying to figure out what data types are being passed through the function, but if I use type(of:) I keep getting 'Any' and not the value held in it.

```<code>extension SomeClass : Mappable{

    static func map(value:Any) -> SomeClass{

        let nameOfType = ??? <-- This is what I'm trying to figure out
        log(nameOfType)

        return Parse(value)

    }
}
</code>```

I simply want to print the data type to the debug window, not do testing with is or as, etc.  It's strictly for logging/debugging reasons.

答:
```<code>static func map(value:AnyObject) -> AnyClass{

    return value.classForCoder

}
</code>```

Or

```<code>static func map(value:Any) -> AnyClass{

    return (value as AnyObject).classForCoder

}
</code>```

Body:
What is the easiest way to get the string-representation of a value's data type if that value is stored in an 'Any' variable?

For instance, I'm debugging code that has this...

extension SomeClass : Mappable{

    static func map(value:Any) -> SomeClass{

        return Parse(value)

    }
}

I'm trying to figure out what data types are being passed through the function, but if I use type(of:) I keep getting 'Any' and not the value held in it.

extension SomeClass : Mappable{

    static func map(value:Any) -> SomeClass{

        let nameOfType = ??? <-- This is what I'm trying to figure out
        log(nameOfType)

        return Parse(value)

    }
}

I simply want to print the data type to the debug window, not do testing with is or as, etc.  It's strictly for logging/debugging reasons.

Body:
static func map(value:AnyObject) -> AnyClass{

    return value.classForCoder

}

Or

static func map(value:Any) -> AnyClass{

    return (value as AnyObject).classForCoder

}


问:
Python not allowing variables in input
In Python 3.6 when entering the code

```<code>var = 1
var1 = input("Hey var = ",(var),"Bye : ")
</code>```

for some reason it comes out with an error message

```<code>    var1 = input("Hey var = ",(var),"Bye : ")
TypeError: input expected at most 1 arguments got 1/2/3/4/5/6+
</code>```

Does anyone know how to fix this so it runs like:

```<code>Hey var = 1 Bye : (where you enter text)
</code>```

答:
input expects a string as an argument so you can't pass it multiple args like with print. Instead you can format the string before you pass it to input:

```<code>var = 1
var1 = input(f"Hey var = {var} Bye : ")
</code>```

The f before the string is short for format and is new in Python 3.6, you can read more about it here.

Title: Python not allowing variables in input

Body:
In Python 3.6 when entering the code

var = 1
var1 = input("Hey var = ",(var),"Bye : ")

for some reason it comes out with an error message

    var1 = input("Hey var = ",(var),"Bye : ")
TypeError: input expected at most 1 arguments got 1/2/3/4/5/6+

Does anyone know how to fix this so it runs like:

Hey var = 1 Bye : (where you enter text)

Body:
input expects a string as an argument so you can't pass it multiple args like with print. Instead you can format the string before you pass it to input:

var = 1
var1 = input(f"Hey var = {var} Bye : ")

The f before the string is short for format and is new in Python 3.6, you can read more about it here.


问:
Input CSV, picking a specfic column and outputing it as a txt file
I'm looking to do the following in R.

Read in a CSV.
Keep a specific column and remove, or freeze the remainder.
Export it to a .txt file

This is what I have thus far

```<code>bankData = read.csv("bank-full.csv", header = FALSE)

newBankData <- bankData[1]

write.csv(newBankData, file = "newBankData.csv", row.names = FALSE)
</code>```

Using this merges all data into one column,

Any advice?

EDIT

enter image description here

答:
The image posted seems to indicate the data is delimited by semicolon, not comma.

try again with sep = ";".

```<code>bankData = read.csv("bank-full.csv", header = FALSE, sep=";")

newBankData <- bankData[1]

write.csv(newBankData, file = "newBankData.csv", row.names = FALSE)
</code>```

Body:
I'm looking to do the following in R.

Read in a CSV.
Keep a specific column and remove, or freeze the remainder.
Export it to a .txt file

This is what I have thus far

bankData = read.csv("bank-full.csv", header = FALSE)

newBankData <- bankData[1]

write.csv(newBankData, file = "newBankData.csv", row.names = FALSE)

Using this merges all data into one column,

Any advice?

EDIT

enter image description here

Body:
The image posted seems to indicate the data is delimited by semicolon, not comma.

try again with sep = ";".

bankData = read.csv("bank-full.csv", header = FALSE, sep=";")

newBankData <- bankData[1]

write.csv(newBankData, file = "newBankData.csv", row.names = FALSE)


问:
R: invalid 'times' argument calculating CRPS
I'm trying to calculate crps using the verification package in R. The data appears to read in ok, but I get an error when trying to compute the CRPS itself: "invalid 'times' argument", however all values are real, no negative values and I'm testing for nan/na values and ignoring those. Having searched around I can't find any solution which explains why I'm getting this error. I'm reading the data in from netcdf files into larger arrays, and then computing CRPS for each grid cell in those arrays.

Any help would be greatly appreciated!

The relevant snipped from the code I'm using is:

```<code>##for each grid cell, get obs (wbarray) and 25 ensemble members of forecast eps (fcstarray)
for(x in 1:3600){
   for(y in 1:1500){

        obs=wbarray[x,y]
        eps=fcstarray[x,y,1:25]

           if(!is.na(obs)){
              print(obs)
              print(eps)
              print("calculating CRPS - real value found")
              crpsfcst=(crpsDecomposition(obs,eps)$CRPS)
              CRPSfcst[x,y,w]=crpsfcst}}}
</code>```

(w is specified in an earlier loop)

And the output I get:

```<code>obs: 0.3850737
eps: 0.3382506 0.3466184 0.3508921 0.3428135 0.3416993 0.3423528 0.3307764
0.3372431 0.3394377 0.3398165 0.3414395 0.3531360 0.3319155 0.3453161
0.3362813 0.3449474 0.3340050 0.3278898 0.3380596 0.3379150 0.3429202
0.3467927 0.3419354 0.3472489 0.3550797

"calculating CRPS - real value found"
Error in rep(0, nObs * (nMember +1)) : invalid 'times' argument
Calls: crpsDecomposition
Execution halted
</code>```

答:
If you type crpsDecomposition on your R command prompt you'll get the source code for the function. The first few lines show:

```<code>function (obs, eps)
{
    nMember = dim(eps)[2]
    nObs <- length(obs)
</code>```

Since your eps data object appears to be (from your output) a one-dimensional vector, the second element of its dimension is going to be NULL, which sets nMember to NULL. Thus nObs*(nMember + 1) gets evaluated to 0. I imagine you simply need to re-examine what form eps should take because it would appear that it needs to be a matrix where each column corresponds to a different "member" (whatever that means in this context).

Body:
I'm trying to calculate crps using the verification package in R. The data appears to read in ok, but I get an error when trying to compute the CRPS itself: "invalid 'times' argument", however all values are real, no negative values and I'm testing for nan/na values and ignoring those. Having searched around I can't find any solution which explains why I'm getting this error. I'm reading the data in from netcdf files into larger arrays, and then computing CRPS for each grid cell in those arrays.

Any help would be greatly appreciated!

The relevant snipped from the code I'm using is:

##for each grid cell, get obs (wbarray) and 25 ensemble members of forecast eps (fcstarray)
for(x in 1:3600){
   for(y in 1:1500){

        obs=wbarray[x,y]
        eps=fcstarray[x,y,1:25]

           if(!is.na(obs)){
              print(obs)
              print(eps)
              print("calculating CRPS - real value found")
              crpsfcst=(crpsDecomposition(obs,eps)$CRPS)
              CRPSfcst[x,y,w]=crpsfcst}}}

(w is specified in an earlier loop)

And the output I get:

obs: 0.3850737
eps: 0.3382506 0.3466184 0.3508921 0.3428135 0.3416993 0.3423528 0.3307764
0.3372431 0.3394377 0.3398165 0.3414395 0.3531360 0.3319155 0.3453161
0.3362813 0.3449474 0.3340050 0.3278898 0.3380596 0.3379150 0.3429202
0.3467927 0.3419354 0.3472489 0.3550797

"calculating CRPS - real value found"
Error in rep(0, nObs * (nMember +1)) : invalid 'times' argument
Calls: crpsDecomposition
Execution halted

Body:
If you type crpsDecomposition on your R command prompt you'll get the source code for the function. The first few lines show:

function (obs, eps)
{
    nMember = dim(eps)[2]
    nObs <- length(obs)

Since your eps data object appears to be (from your output) a one-dimensional vector, the second element of its dimension is going to be NULL, which sets nMember to NULL. Thus nObs*(nMember + 1) gets evaluated to 0. I imagine you simply need to re-examine what form eps should take because it would appear that it needs to be a matrix where each column corresponds to a different "member" (whatever that means in this context).


问:
Merge Two Image on to one Image programmatically in iphone
Hello I am developing the application which requires to merge two Image , My image size are 320*240 by merging both Image I want the size to be 320 * 480 . How can i do this programitically . Following are the Images

===================================================================================

答:
//ADDED Swift 3.2 and 4.0    </p>

```<code>@IBOutlet weak var imgCamera1: UIImageView!
@IBOutlet weak var imgCamera2: UIImageView!

    let image1 = imgCamera1.image
    let image2 = imgCamera2.image

    let size = CGSize(width: image1?.size.width ?? 0.0, height: (image1?.size.height)! + (image2?.size.height)!)
    UIGraphicsBeginImageContext(size)
    image1?.draw(in: CGRect(x: 0, y: 0, width: size.width, height: image1?.size.height ?? 0.0))
    image2?.draw(in: CGRect(x: 0, y: image1?.size.height ?? 0.0, width: size.width, height: image2?.size.height ?? 0.0))

    let finalImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    //Add image to view
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: finalImage?.size.width ?? 0.0, height: finalImage?.size.height ?? 0.0))
    imageView.image = finalImage

    //Displaying Image
   // view.addSubview(imageView)
</code>```

Body:
//ADDED Swift 3.2 and 4.0

@IBOutlet weak var imgCamera1: UIImageView!
@IBOutlet weak var imgCamera2: UIImageView!

    let image1 = imgCamera1.image
    let image2 = imgCamera2.image

    let size = CGSize(width: image1?.size.width ?? 0.0, height: (image1?.size.height)! + (image2?.size.height)!)
    UIGraphicsBeginImageContext(size)
    image1?.draw(in: CGRect(x: 0, y: 0, width: size.width, height: image1?.size.height ?? 0.0))
    image2?.draw(in: CGRect(x: 0, y: image1?.size.height ?? 0.0, width: size.width, height: image2?.size.height ?? 0.0))

    let finalImage = UIGraphicsGetImageFromCurrentImageContext();

    UIGraphicsEndImageContext();

    //Add image to view
    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: finalImage?.size.width ?? 0.0, height: finalImage?.size.height ?? 0.0))
    imageView.image = finalImage

    //Displaying Image
   // view.addSubview(imageView)


问:
Reset the database (purge all), then seed a database
Is there a rake command to wipe out the data in the database tables?

How do I create a db:seed script to pre-fill data to my tables?

答:
As of Rails 5, the rake commandline tool has been aliased as rails so now

rails db:reset instead of rake db:reset

will work just as well


问:
How to stop the value of an .each loop being the same when appending buttons to a website?
```<code>    var number = 0;
    $.getJSON("blogData.json", function(data) {

    $.each(data, function (index, entry) {
        console.log(index);
        $("#posts").append("<h3>" + entry.title + "</h3>");
        $("#posts").append("<h4>" + entry.desc + "</h4>");
        $("#posts").append("<h4>" + entry.author + "</h4>");
        $("#posts").append("<p>" + entry.post + "</p>");
        $("#posts").append("<br>");
        $("#posts").append('<button onclick=save(number)>Read More</button>');
        $("#posts").append("<br><br>");
        number++;
    });

});
</code>```

I want to be able to assign a unique value to every button in order to pass this value to other functions. The context of this is a blog stored in a JSON file where the values of the posts are called via index. I wish to be able to view one post individually by clicking on the button for that specific post.

答:
You have used the variable as string type. All what you need is to concatenate the variable's value.

```<code>$("#posts").append('<button onclick=save(' + number + ')>Read More</button>');
</code>```

Body:
    var number = 0;
    $.getJSON("blogData.json", function(data) {

    $.each(data, function (index, entry) {
        console.log(index);
        $("#posts").append("
" + entry.title + "
");
        $("#posts").append("
" + entry.desc + "
");
        $("#posts").append("
" + entry.author + "
");
        $("#posts").append("
" + entry.post + "
");
        $("#posts").append("
");
        $("#posts").append('<button onclick=save(number)>Read More</button>');
        $("#posts").append("

");
        number++;
    });

});

I want to be able to assign a unique value to every button in order to pass this value to other functions. The context of this is a blog stored in a JSON file where the values of the posts are called via index. I wish to be able to view one post individually by clicking on the button for that specific post.

Body:
You have used the variable as string type. All what you need is to concatenate the variable's value.

$("#posts").append('<button onclick=save(' + number + ')>Read More</button>');


问:
Undefined symbols for architecture armv7: cocoaPods iPhone 5
I'm getting this error, only when I try to build and run on an iPhone 5.  It works fine on an iPhone 6 or greater. These are all cocoaPods generating the error. I've ran pod install, pod update, wiped out the pods and started over, nothing:

I've tried all the answers from here: Undefined symbols for architecture armv7 for Cocoapods libraries with no luck.  Here is the verbose output from pod install

```<code>Analyzing dependencies

Inspecting targets to integrate
  Using `ARCHS` setting to build architectures of target `Pods-Celeo`: (``)

Finding Podfile changes
  - Braintree
  - ConciseKit
  - EDStarRating
  - Google
  - IDMPhotoBrowser
  - KAProgressLabel
  - MBProgressHUD
  - MagicalRecord
  - SFHFKeychainUtils
  - TwilioConversationsClient
  - TwilioSDK

Resolving dependencies of `Podfile`

Comparing resolved specification to the sandbox manifest
  - Braintree
  - ConciseKit
  - DACircularProgress
  - EDStarRating
  - FirebaseAnalytics
  - FirebaseInstanceID
  - Google
  - GoogleAnalytics
  - GoogleInterchangeUtilities
  - GoogleSymbolUtilities
  - GoogleUtilities
  - IDMPhotoBrowser
  - KAProgressLabel
  - MBProgressHUD
  - MagicalRecord
  - SDWebImage
  - SFHFKeychainUtils
  - TwilioCommon
  - TwilioConversationsClient
  - TwilioSDK
  - pop

Downloading dependencies

-> Using Braintree (4.3.1)

-> Using ConciseKit (0.1.2)

-> Using DACircularProgress (2.3.1)

-> Using EDStarRating (1.1)

-> Using FirebaseAnalytics (3.2.0)

-> Using FirebaseInstanceID (1.0.6)

-> Using Google (3.0.3)

-> Using GoogleAnalytics (3.14.0)

-> Using GoogleInterchangeUtilities (1.2.1)

-> Using GoogleSymbolUtilities (1.1.1)

-> Using GoogleUtilities (1.3.1)

-> Using IDMPhotoBrowser (1.8.4)

-> Using KAProgressLabel (3.2)

-> Using MBProgressHUD (0.9.2)

-> Using MagicalRecord (2.3.2)

-> Using SDWebImage (3.7.6)

-> Using SFHFKeychainUtils (0.0.1)

-> Using TwilioCommon (0.2.2)

-> Using TwilioConversationsClient (0.24.1)

-> Using TwilioSDK (1.2.10)

-> Using pop (1.0.9)
  - Running pre install hooks

Generating Pods project
  - Creating Pods project
  - Adding source files to Pods project
  - Adding frameworks to Pods project
  - Adding libraries to Pods project
  - Adding resources to Pods project
  - Linking headers
  - Installing targets
    - Installing target `Braintree` iOS 7.0
    - Installing target `ConciseKit` iOS 4.3
    - Installing target `DACircularProgress` iOS 5.0
    - Installing target `EDStarRating` iOS 4.3
    - Installing target `IDMPhotoBrowser` iOS 7.0
    - Installing target `KAProgressLabel` iOS 4.3
    - Installing target `MBProgressHUD` iOS 4.3
    - Installing target `MagicalRecord` iOS 6.1
    - Installing target `SDWebImage` iOS 5.0
    - Installing target `SFHFKeychainUtils` iOS 4.3
    - Installing target `pop` iOS 6.0
    - Installing target `Pods-Celeo` iOS 9.0
  - Running post install hooks
  - Writing Xcode project file to `Pods/Pods.xcodeproj`
    - Generating deterministic UUIDs
  - Writing Lockfile in `Podfile.lock`
  - Writing Manifest in `Pods/Manifest.lock`

Integrating client project

Integrating target `Pods-Celeo` (`Celeo.xcodeproj` project)
  - Running post install hooks
    - cocoapods-stats from
    `/Library/Ruby/Gems/2.0.0/gems/cocoapods-stats-1.0.0/lib/cocoapods_plugin.rb`

Sending stats
      - Braintree, 4.3.1
      - ConciseKit, 0.1.2
      - DACircularProgress, 2.3.1
      - EDStarRating, 1.1
      - FirebaseAnalytics, 3.2.0
      - FirebaseInstanceID, 1.0.6
      - Google, 3.0.3
      - GoogleAnalytics, 3.14.0
      - GoogleInterchangeUtilities, 1.2.1
      - GoogleSymbolUtilities, 1.1.1
      - GoogleUtilities, 1.3.1
      - IDMPhotoBrowser, 1.8.4
      - KAProgressLabel, 3.2
      - MBProgressHUD, 0.9.2
      - MagicalRecord, 2.3.2
      - SDWebImage, 3.7.6
      - SFHFKeychainUtils, 0.0.1
      - TwilioSDK, 1.2.10
      - pop, 1.0.9
  Pod installation complete! There are 11 dependencies from the Podfile and 21
  total pods installed.
</code>```

答:
None of the answers above helped me.  It turns out using frameworks for my pods instead of static libraries fixed it.  Adding use_frameworks! to Podfile fixed it:

```<code>platform :ios, '9.3'
use_frameworks!

...rest of podfile
</code>```

Body:
I'm getting this error, only when I try to build and run on an iPhone 5.  It works fine on an iPhone 6 or greater. These are all cocoaPods generating the error. I've ran pod install, pod update, wiped out the pods and started over, nothing:

I've tried all the answers from here: Undefined symbols for architecture armv7 for Cocoapods libraries with no luck.  Here is the verbose output from pod install

Analyzing dependencies

Inspecting targets to integrate
  Using `ARCHS` setting to build architectures of target `Pods-Celeo`: (``)

Finding Podfile changes
  - Braintree
  - ConciseKit
  - EDStarRating
  - Google
  - IDMPhotoBrowser
  - KAProgressLabel
  - MBProgressHUD
  - MagicalRecord
  - SFHFKeychainUtils
  - TwilioConversationsClient
  - TwilioSDK

Resolving dependencies of `Podfile`

Comparing resolved specification to the sandbox manifest
  - Braintree
  - ConciseKit
  - DACircularProgress
  - EDStarRating
  - FirebaseAnalytics
  - FirebaseInstanceID
  - Google
  - GoogleAnalytics
  - GoogleInterchangeUtilities
  - GoogleSymbolUtilities
  - GoogleUtilities
  - IDMPhotoBrowser
  - KAProgressLabel
  - MBProgressHUD
  - MagicalRecord
  - SDWebImage
  - SFHFKeychainUtils
  - TwilioCommon
  - TwilioConversationsClient
  - TwilioSDK
  - pop

Downloading dependencies

-> Using Braintree (4.3.1)

-> Using ConciseKit (0.1.2)

-> Using DACircularProgress (2.3.1)

-> Using EDStarRating (1.1)

-> Using FirebaseAnalytics (3.2.0)

-> Using FirebaseInstanceID (1.0.6)

-> Using Google (3.0.3)

-> Using GoogleAnalytics (3.14.0)

-> Using GoogleInterchangeUtilities (1.2.1)

-> Using GoogleSymbolUtilities (1.1.1)

-> Using GoogleUtilities (1.3.1)

-> Using IDMPhotoBrowser (1.8.4)

-> Using KAProgressLabel (3.2)

-> Using MBProgressHUD (0.9.2)

-> Using MagicalRecord (2.3.2)

-> Using SDWebImage (3.7.6)

-> Using SFHFKeychainUtils (0.0.1)

-> Using TwilioCommon (0.2.2)

-> Using TwilioConversationsClient (0.24.1)

-> Using TwilioSDK (1.2.10)

-> Using pop (1.0.9)
  - Running pre install hooks

Generating Pods project
  - Creating Pods project
  - Adding source files to Pods project
  - Adding frameworks to Pods project
  - Adding libraries to Pods project
  - Adding resources to Pods project
  - Linking headers
  - Installing targets
    - Installing target `Braintree` iOS 7.0
    - Installing target `ConciseKit` iOS 4.3
    - Installing target `DACircularProgress` iOS 5.0
    - Installing target `EDStarRating` iOS 4.3
    - Installing target `IDMPhotoBrowser` iOS 7.0
    - Installing target `KAProgressLabel` iOS 4.3
    - Installing target `MBProgressHUD` iOS 4.3
    - Installing target `MagicalRecord` iOS 6.1
    - Installing target `SDWebImage` iOS 5.0
    - Installing target `SFHFKeychainUtils` iOS 4.3
    - Installing target `pop` iOS 6.0
    - Installing target `Pods-Celeo` iOS 9.0
  - Running post install hooks
  - Writing Xcode project file to `Pods/Pods.xcodeproj`
    - Generating deterministic UUIDs
  - Writing Lockfile in `Podfile.lock`
  - Writing Manifest in `Pods/Manifest.lock`

Integrating client project

Integrating target `Pods-Celeo` (`Celeo.xcodeproj` project)
  - Running post install hooks
    - cocoapods-stats from
    `/Library/Ruby/Gems/2.0.0/gems/cocoapods-stats-1.0.0/lib/cocoapods_plugin.rb`

Sending stats
      - Braintree, 4.3.1
      - ConciseKit, 0.1.2
      - DACircularProgress, 2.3.1
      - EDStarRating, 1.1
      - FirebaseAnalytics, 3.2.0
      - FirebaseInstanceID, 1.0.6
      - Google, 3.0.3
      - GoogleAnalytics, 3.14.0
      - GoogleInterchangeUtilities, 1.2.1
      - GoogleSymbolUtilities, 1.1.1
      - GoogleUtilities, 1.3.1
      - IDMPhotoBrowser, 1.8.4
      - KAProgressLabel, 3.2
      - MBProgressHUD, 0.9.2
      - MagicalRecord, 2.3.2
      - SDWebImage, 3.7.6
      - SFHFKeychainUtils, 0.0.1
      - TwilioSDK, 1.2.10
      - pop, 1.0.9
  Pod installation complete! There are 11 dependencies from the Podfile and 21
  total pods installed.

Body:
None of the answers above helped me.  It turns out using frameworks for my pods instead of static libraries fixed it.  Adding use_frameworks! to Podfile fixed it:

platform :ios, '9.3'
use_frameworks!

...rest of podfile


问:
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION when ran UDATE statement
Got an error when ran update statement.
For one record it worked fine, but for a chunk of records it gives me an error.

Also, why it tells me that 64801 row(s) affected and then 1 row(s) affected and then 0? How should I interpret that?

This is the script:

```<code>update tblQuotes
set QuoteStatusID = 11, --Not Taken Up
    QuoteStatusReasonID = 9 --"Not Competitive"
where CAST(EffectiveDate as DATE) < CAST('2013-11-27' as DATE)
and CompanyLocationGuid = '32828BB4-E1FA-489F-9764-75D8AF7A78F1' -- Plaza Insurance Company
and LineGUID = '623AA353-9DFE-4463-97D7-0FD398400B6D' --Commercial Auto
</code>```

I added BEGIN TRANSACTION statement, but it still won't work.

```<code>BEGIN TRANSACTION
update tblQuotes
set QuoteStatusID = 11, --Not Taken Up
    QuoteStatusReasonID = 9 --"Not Competitive"
where CAST(EffectiveDate as DATE) < CAST('2017-11-27' as DATE)
 AND CompanyLocationGuid = '32828BB4-E1FA-489F-9764-75D8AF7A78F1' -- Plaza Insurance Company
and LineGUID = '623AA353-9DFE-4463-97D7-0FD398400B6D' --Commercial Auto
IF @@TRANCOUNT>0
COMMIT TRANSACTION
</code>```

答: There is a trigger, that making sure about the integrity of the QuoteStatusID. So im my WHERE clause I have to exactly specify what current status ID policy have to have in order to be updated.</p>

Body:
Got an error when ran update statement.
For one record it worked fine, but for a chunk of records it gives me an error.

Also, why it tells me that 64801 row(s) affected and then 1 row(s) affected and then 0? How should I interpret that?

This is the script:

update tblQuotes
set QuoteStatusID = 11, --Not Taken Up
    QuoteStatusReasonID = 9 --"Not Competitive"
where CAST(EffectiveDate as DATE) < CAST('2013-11-27' as DATE)
and CompanyLocationGuid = '32828BB4-E1FA-489F-9764-75D8AF7A78F1' -- Plaza Insurance Company
and LineGUID = '623AA353-9DFE-4463-97D7-0FD398400B6D' --Commercial Auto

I added BEGIN TRANSACTION statement, but it still won't work.

BEGIN TRANSACTION
update tblQuotes
set QuoteStatusID = 11, --Not Taken Up
    QuoteStatusReasonID = 9 --"Not Competitive"
where CAST(EffectiveDate as DATE) < CAST('2017-11-27' as DATE)
 AND CompanyLocationGuid = '32828BB4-E1FA-489F-9764-75D8AF7A78F1' -- Plaza Insurance Company
and LineGUID = '623AA353-9DFE-4463-97D7-0FD398400B6D' --Commercial Auto
IF @@TRANCOUNT>0
COMMIT TRANSACTION


问:
PHP echo total number of rows from SQL query
I'm not sure where I'm going wrong here. I've searched similar issues on here with no luck. Any help would be greatly appreciated. Thanks!</p>

```<code>$check = "SELECT Number FROM advisors";
$result = mysqli_query($check);
$count = mysqi_num_rows($result);

echo $count;
</code>```

答:
You should use COUNT in query and see if it works,
"SELECT COUNT (number) as number FROM advisors";
By the way, I noticed a typo in $count, it should be $count = mysqli_num_count($result).</p>

Body:
I'm not sure where I'm going wrong here. I've searched similar issues on here with no luck. Any help would be greatly appreciated. Thanks!

$check = "SELECT Number FROM advisors";
$result = mysqli_query($check);
$count = mysqi_num_rows($result);

echo $count;


问:
How can I list how many files are in each directory in OSX terminal?
How can I list how many files are in each directory together sub-directoies?

i found that:

```<code>find . -name "*.txt" | wc -l
</code>```

but this is count all.
I need the count for each sub-directory separately

Expected sample result is:

```<code>home/folder1 12
home/folder2 10
home/ 22
etc/folder1 100
etc/folder2 200
etc/folder3 10
etc 310
...
</code>```

Is there a way I can count the number of files in each directory like this?

答:
You have to loop over your directories and find .txt files inside each of them

```<code>find . -type d -exec sh -c 'echo -n "{} " && find {} -name "*.txt" | wc -l' \;
</code>```

Body:
How can I list how many files are in each directory together sub-directoies?

i found that:

find . -name "*.txt" | wc -l

but this is count all.
I need the count for each sub-directory separately

Expected sample result is:

home/folder1 12
home/folder2 10
home/ 22
etc/folder1 100
etc/folder2 200
etc/folder3 10
etc 310
...

Is there a way I can count the number of files in each directory like this?

Body:
You have to loop over your directories and find .txt files inside each of them

find . -type d -exec sh -c 'echo -n "{} " && find {} -name "*.txt" | wc -l' \;


问:
See who saved each version in excel
Good day,

I need to find out who saved each version of an excel file. I have the previous versions and when they were created yet do not know how to find out who saved it.
The situation cocerns the last 2 versions. 2 versions ago, i saves the file. I know for sure that the last save was done by someone else, yet in the last saved by, i am the one displayed. Please help!

Best regards,
Vlad C.

答: I believe you can enable track changes on the workbook, which will show the specific areas of the workbook that were changed each time.</p>

Title: See who saved each version in excel


问:
How to make TextView with decimal numbers Android Studio
I am the beginner of the Android SDK programming.

What I have is,a calculator that doesn't show decimals when i press calculate button and is there if there is any way to do it?Also crashes if I didn't fill the EditText.

```<code>    Button cal;
EditText n1,n2,n3;
TextView answer;

int x,y,r,z;

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

    answer = (TextView)findViewById(R.id.res);
    n1 = (EditText)findViewById(R.id.n1);
    n2 = (EditText)findViewById(R.id.n2);
    n3 = (EditText)findViewById(R.id.n3);
    cal = (Button)findViewById(R.id.calc);

    cal.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            x=Integer.parseInt(n1.getText().toString());
            y=Integer.parseInt(n2.getText().toString());
            z=Integer.parseInt(n3.getText().toString());
            r=(x+y+z)/3;

            answer.setText("" + r);
        }
    });
</code>```

答:
You are using Integer.parseInt , to get decimal use Double.parseDouble

set this for edit texts -

```<code>n1.setInputType(InputType.TYPE_CLASS_NUMBER);
n2.setInputType(InputType.TYPE_CLASS_NUMBER);
n3.setInputType(InputType.TYPE_CLASS_NUMBER);
</code>```

for crashing put checks that user can calculate only when edit texts have values

```<code>cal.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if(!n1.getText().toString().isEmpty()&&!n2.getText().toString().isEmpty()&&!n3.getText().toString().isEmpty())
        calculateResult();
 else{ //show error message
      }

    }
});

public void calculateResult()
{
      x=Double.parseDouble(n1.getText().toString());
        y=Double.parseDouble(n2.getText().toString());
        z=Double.parseDouble(n3.getText().toString());
        r=(x+y+z)/3;

        answer.setText("" + r);
 }
</code>```

and change data types of x,y,z,r to double

Body:
I am the beginner of the Android SDK programming.

What I have is,a calculator that doesn't show decimals when i press calculate button and is there if there is any way to do it?Also crashes if I didn't fill the EditText.

    Button cal;
EditText n1,n2,n3;
TextView answer;

int x,y,r,z;

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

    answer = (TextView)findViewById(R.id.res);
    n1 = (EditText)findViewById(R.id.n1);
    n2 = (EditText)findViewById(R.id.n2);
    n3 = (EditText)findViewById(R.id.n3);
    cal = (Button)findViewById(R.id.calc);

    cal.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            x=Integer.parseInt(n1.getText().toString());
            y=Integer.parseInt(n2.getText().toString());
            z=Integer.parseInt(n3.getText().toString());
            r=(x+y+z)/3;

            answer.setText("" + r);
        }
    });

Body:
You are using Integer.parseInt , to get decimal use Double.parseDouble

set this for edit texts -

n1.setInputType(InputType.TYPE_CLASS_NUMBER);
n2.setInputType(InputType.TYPE_CLASS_NUMBER);
n3.setInputType(InputType.TYPE_CLASS_NUMBER);

for crashing put checks that user can calculate only when edit texts have values

cal.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        if(!n1.getText().toString().isEmpty()&&!n2.getText().toString().isEmpty()&&!n3.getText().toString().isEmpty())
        calculateResult();
 else{ //show error message
      }

    }
});

public void calculateResult()
{
      x=Double.parseDouble(n1.getText().toString());
        y=Double.parseDouble(n2.getText().toString());
        z=Double.parseDouble(n3.getText().toString());
        r=(x+y+z)/3;

        answer.setText("" + r);
 }

and change data types of x,y,z,r to double


问:
Regex for both currency iso code and symbol
I am trying to find exact currency match with currency iso codes or symbols. I've got a list of currencies and symbols, which in regex I just use (USD|JPY) and $|£| etc for example. So criteria are:

Should be an exact match for a currency code USD JPY or symbol $ £. Currency codes are case insensitive

Before and after can have an optional number

There can only be a number before and after the currency (can contain whitespace in between).

Example:
a = 4USD - $3 + a4 USD / JPY    400 * 3USDa

Output would be (provided .scan called in ruby): ["USD", "$", "USD", "JPY"]

Incorrect would be to include 3USDa

I've been trying a lot of patterns to no avail, here some of them:

/\d+(?=(USD|JPY)(?!\w))|(USD|JPY)(?=\d+(?!\w))/i

/(?<=(JPY|USD))*\d|(?<=\d)(JPY|USD)/i

答:
If you're OK using the capture group rather than the overall match, then the following is perhaps the simplest regex solution to your requirements:

```<code>/(?<!\w)\d*\s*(JPY|USD|\$|£)\s*\d*(?!\w)/i
</code>```

Demo

If you have a list of all currencies, you could construct that regex programmatically like:

```<code>currencies = %w(USD JPN $ £)
currencies_pattern = currencies.map {|c| Regexp.escape(c) }.join("|")
full_pattern = /(?<!\w)\d*\s*(#{currencies_pattern})\s*\d*(?!\w)/i
</code>```

As commented above, not that this does return $ as a valid match from your example. Based on my understanding of your rules, I don't see why $ should be considered a non-match.

Body:
If you're OK using the capture group rather than the overall match, then the following is perhaps the simplest regex solution to your requirements:

/(?<!\w)\d*\s*(JPY|USD|\$|£)\s*\d*(?!\w)/i

Demo

If you have a list of all currencies, you could construct that regex programmatically like:

currencies = %w(USD JPN $ £)
currencies_pattern = currencies.map {|c| Regexp.escape(c) }.join("|")
full_pattern = /(?<!\w)\d*\s*(#{currencies_pattern})\s*\d*(?!\w)/i

As commented above, not that this does return $ as a valid match from your example. Based on my understanding of your rules, I don't see why $ should be considered a non-match.


问:
Setting up Mysql on EC2 (ubuntu). Having issue with XFS
I have been following the directions on setting up a MySql database on EC2 here: http://aws.amazon.com/articles/1663?_encoding=UTF8&jiveRedirect=1

I got a problem when I run:

```<code>$ sudo mkfs.xfs /dev/sdh
Cannot stat /dev/sdh: No such file or directory
</code>```

What can it be?

Edit:
I ran the following based on @karudzo advice

```<code>$ cd /dev
$ sudo /sbin/MAKEDEV sdh
$ sudo mkfs.xfs /dev/sdh
mkfs.xfs: cannot open /dev/sdh: No such device or address
</code>```

答: That means that /dev/sdh doesn't exist yet.  Try this:  http://getsatisfaction.com/cohesiveft/topics/attaching_a_ebs_volume_to_ec2_instance_at_dev_sdh_doesnt_appear_to_attach</p>

ContentLicense: CC BY-SA 2.5

Body:
I have been following the directions on setting up a MySql database on EC2 here: http://aws.amazon.com/articles/1663?_encoding=UTF8&jiveRedirect=1

I got a problem when I run:

$ sudo mkfs.xfs /dev/sdh
Cannot stat /dev/sdh: No such file or directory

What can it be?

Edit:
I ran the following based on @karudzo advice

$ cd /dev
$ sudo /sbin/MAKEDEV sdh
$ sudo mkfs.xfs /dev/sdh
mkfs.xfs: cannot open /dev/sdh: No such device or address


问:
C - dir path last folder - gibberish at the end
I want to get the last folder in a directory path.

for example I have this directory path :

```<code>/home/workspace/projects/files/example.c
</code>```

and I want to get "files"

I am using

```<code>basename((dirname("/home/workspace/projects/files/example.c")));
</code>```

I want to export "files" to .csv file and I get gibberish at the end , something like "files�"

Update:
I also tried this :

```<code>  char * path = strdup(file);
  basename(dirname(path));
</code>```

char * file points on "/home/workspace/projects/files/example.c"
and its not working too  ,"files" still written to .csv with junk in the end,but when I print basename(dirname(file)) to console it prints well "files"

答:
As was mentioned in the comments, both dirname and basename can modify the argument passed to it.  What you're passing however is a string literal, which cannot be modified.  Attempting to do so invokes undefined behavior, which in this particular case results to extra characters being printed.

Section 6.4.5 of the C standard regarding string literals says the following:

7 It is unspecified whether these arrays are distinct provided their
  elements have the appropriate values. If the program attempts to
  modify such an array, the behavior is undefined.

You need to store this string in either an array or a dynamically allocated buffer.  Then you can modify it.

```<code>char path[] = "/home/workspace/projects/files/example.c";
basename((dirname(path)));
</code>```

Here, path is declared as an array, and this array is initialized with a string literal.  It is not a string literal itself.

Body:
I want to get the last folder in a directory path.

for example I have this directory path :

/home/workspace/projects/files/example.c

and I want to get "files"

I am using

basename((dirname("/home/workspace/projects/files/example.c")));

I want to export "files" to .csv file and I get gibberish at the end , something like "files�"

Update:
I also tried this :

  char * path = strdup(file);
  basename(dirname(path));

char * file points on "/home/workspace/projects/files/example.c"
and its not working too  ,"files" still written to .csv with junk in the end,but when I print basename(dirname(file)) to console it prints well "files"

Body:
As was mentioned in the comments, both dirname and basename can modify the argument passed to it.  What you're passing however is a string literal, which cannot be modified.  Attempting to do so invokes undefined behavior, which in this particular case results to extra characters being printed.

Section 6.4.5 of the C standard regarding string literals says the following:

7 It is unspecified whether these arrays are distinct provided their
  elements have the appropriate values. If the program attempts to
  modify such an array, the behavior is undefined.

You need to store this string in either an array or a dynamically allocated buffer.  Then you can modify it.

char path[] = "/home/workspace/projects/files/example.c";
basename((dirname(path)));

Here, path is declared as an array, and this array is initialized with a string literal.  It is not a string literal itself.


问:
How to start composer-rest-server as background process?
I am trying to start composer-rest-server in background using following command :

composer-rest-server &

Its getting started as background process, but then process is getting stuck after displaying "hyperledger-Composer" banner as :

Is there anyway we can start composer-rest-server as background process?

答:
Run command like this:

```<code>nohup composer-rest-server -c <network card name> -n never -w true > rest-server.out 2> rest-server.err < /dev/null &
</code>```

all standard output will be saved in rest-server.out and errors in rest-server.err

& at the end will put it in background and you will get PID

Next time you connect to server and if you want to kill earlier instance then use ps -A | grep "node" command to get PID.

Body:
Run command like this:

nohup composer-rest-server -c <network card name> -n never -w true > rest-server.out 2> rest-server.err < /dev/null &

all standard output will be saved in rest-server.out and errors in rest-server.err

& at the end will put it in background and you will get PID

Next time you connect to server and if you want to kill earlier instance then use ps -A | grep "node" command to get PID.


问:
Explain how this javascript codes sums two numbers and those between them
I'm taking javascript lessons and I'm currently doing some little projects.

One project is this:
Given two integers, which can be positive and negative, find the sum of all the numbers between including them too and return it. If both numbers are equal return a or b.

One of the solutions I've found is this :

```<code>function GetSum(a, b) {
    if(a == b) {
        return a
    }
    else if (a < b) {
        return a + GetSum(a+1, b)
    } else {
        return a + GetSum(a-1, b)
    };
}
console.log(GetSum(-1, 2));
</code>```

Please, I would like an explanation on why the code works.

...and, I will like to know why the code below is always returning 0

```<code>function GetSum(a, b) {
    let lower, higher;
    let result = 0;
    //return either of it if they are equal
    if(a == b) {
        return a;
    } else {
        if(a > b) {
            higher = a;
            lower = b;
        } else {
            higher = b;
            lower = a;
        }
        for(i = lower; i <= higher; i++) {
            result += i;
        }
    }
    return result;
}
console.log(GetSum(3, 9))
</code>```

Thanks in advance

答:
We can simplify the code to this:

```<code>function getSum( a,b ){
   if (a == b) return a; //(1)
   if (a < b) {
      return a + getSum(a+1, b); //(2)
   }else {
      return a + getSum(a-1,b); //(3)
   }
}

getSum(1,3)
</code>```

So at the first function call a is 1 and b is 3 so it goes into branch 2:

```<code>return 1 +  getSum(1 + 1, 3)
</code>```

So now getSum is called from inside getSum, thats called recursion. Now getSum goes into branch 2 again and does

```<code> return 2 + getSum(2 + 1, 3)
</code>```

As now a equals b, getSum now goes into branch 1 and returns a (3). If we summarize the three lines above

```<code> getSum(1,3)
 1 + getSum(2,3)
 1 + ( 2 + getSum(3,3))
 1 + ( 2 + (3))
</code>```

The whole thing as a oneliner:

```<code> const getSum = (a, b) => a === b ? a : getSum(a + (a < b)?1:-1, b);
</code>```

Or using a loop:

```<code> const getSum = (a, b) => {
   const res = 0;
   if(b < a) [a,b] = [b,a];
   while(a <= b) res += a++;
   return res;
}
</code>```

or using tricky math:

```<code>const getSum = (a, b) => 1/2 * Math.abs((a ** 2 + a - b ** 2 - b));
</code>```

Body:
I'm taking javascript lessons and I'm currently doing some little projects.

One project is this:
Given two integers, which can be positive and negative, find the sum of all the numbers between including them too and return it. If both numbers are equal return a or b.

One of the solutions I've found is this :

function GetSum(a, b) {
    if(a == b) {
        return a
    }
    else if (a < b) {
        return a + GetSum(a+1, b)
    } else {
        return a + GetSum(a-1, b)
    };
}
console.log(GetSum(-1, 2));

Please, I would like an explanation on why the code works.

...and, I will like to know why the code below is always returning 0

function GetSum(a, b) {
    let lower, higher;
    let result = 0;
    //return either of it if they are equal
    if(a == b) {
        return a;
    } else {
        if(a > b) {
            higher = a;
            lower = b;
        } else {
            higher = b;
            lower = a;
        }
        for(i = lower; i <= higher; i++) {
            result += i;
        }
    }
    return result;
}
console.log(GetSum(3, 9))

Thanks in advance

Body:
We can simplify the code to this:

function getSum( a,b ){
   if (a == b) return a; //(1)
   if (a < b) {
      return a + getSum(a+1, b); //(2)
   }else {
      return a + getSum(a-1,b); //(3)
   }
}

getSum(1,3)

So at the first function call a is 1 and b is 3 so it goes into branch 2:

return 1 +  getSum(1 + 1, 3)

So now getSum is called from inside getSum, thats called recursion. Now getSum goes into branch 2 again and does

 return 2 + getSum(2 + 1, 3)

As now a equals b, getSum now goes into branch 1 and returns a (3). If we summarize the three lines above

 getSum(1,3)
 1 + getSum(2,3)
 1 + ( 2 + getSum(3,3))
 1 + ( 2 + (3))

The whole thing as a oneliner:

 const getSum = (a, b) => a === b ? a : getSum(a + (a < b)?1:-1, b);

Or using a loop:

 const getSum = (a, b) => {
   const res = 0;
   if(b < a) [a,b] = [b,a];
   while(a <= b) res += a++;
   return res;
}

or using tricky math:

const getSum = (a, b) => 1/2 * Math.abs((a ** 2 + a - b ** 2 - b));


问:
Woocommerce variation image src showing small thumbnail
I updated Woocommerce to the latest version and where i was using showing variation images in my template, they had all disappeared. Looks like they've decided to drop $variation['image_src'].

I did some research and apparently you need to use $variation['image']['thumb_src'].

Frustratingly this doesn't show the variation image at full size. Does anyone know how to do this please?

I've tried $variation['image']['large_src'] but doesn't work :(

Annoying how I can't find any instructions from Woocommerce!

答:
You can use $variation['image']['full_src']

So full_src instead of large_src.


问:
SQL use CASE statement in WHERE IN clause
Is it posible to use case in where in clause?
Something like this:

```<code> DECLARE @Status VARCHAR(50);
 SET @Status='published';

 SELECT * FROM Product P
 WHERE P.Status IN (CASE WHEN @Status='published' THEN (1,3)
                                   WHEN @Status='standby' THEN (2,5,9,6)
                                   WHEN @Status='deleted' THEN (4,5,8,10)
                                   ELSE (1,3)
                                   END)
</code>```

This code gives the error : Incorrect syntax near ','.

答:
I believe you can use a case statement in a where clause, here is how I do it:

```<code>Select
ProductID
OrderNo,
OrderType,
OrderLineNo
From Order_Detail
Where ProductID in (
Select Case when (@Varibale1 != '')
then (Select ProductID from Product P Where .......)
Else (Select ProductID from Product)
End as ProductID
)
</code>```

This method has worked for me time and again. try it!

Body:
Is it posible to use case in where in clause?
Something like this:

 DECLARE @Status VARCHAR(50);
 SET @Status='published';

 SELECT * FROM Product P
 WHERE P.Status IN (CASE WHEN @Status='published' THEN (1,3)
                                   WHEN @Status='standby' THEN (2,5,9,6)
                                   WHEN @Status='deleted' THEN (4,5,8,10)
                                   ELSE (1,3)
                                   END)

This code gives the error : Incorrect syntax near ','.

Body:
I believe you can use a case statement in a where clause, here is how I do it:

Select
ProductID
OrderNo,
OrderType,
OrderLineNo
From Order_Detail
Where ProductID in (
Select Case when (@Varibale1 != '')
then (Select ProductID from Product P Where .......)
Else (Select ProductID from Product)
End as ProductID
)

This method has worked for me time and again. try it!


问:
Deep filtering of a list of dictionaries based on two properties
I'm trying to find an efficient way to handle this problem. I have an list of dictionaries with over 400k entries. I need to first find all the entries that share a common key, let's say 'pallet-id' from that list and then from that sub-list verify that all those share the same 'location' key. I'm only interested in getting from that initial list the entries that have a similar 'pallet-id' but only if one of those have a different 'location' than the rest.

Ex.

This would be working with pallet-id 123456

```<code>entry1 = {'location': 'LOC1', 'pallet-id': '123456', ...}
entry2 = {'location': 'LOC1', 'pallet-id': '123456', ...}
entry3 = {'location': 'LOC1', 'pallet-id': '123456', ...}
entry4 = {'location': 'LOC1', 'pallet-id': '123456', ...}
</code>```

Since all share the same location, I don't care about this.

This would be working with pallet-id 5555

```<code>entry1 = {'location': 'LOC1', 'pallet-id': '5555', ...}
entry2 = {'location': 'LOC1', 'pallet-id': '5555', ...}
entry3 = {'location': 'LOC2', 'pallet-id': '5555', ...}
entry4 = {'location': 'LOC1', 'pallet-id': '5555', ...}
</code>```

In this case since one has a different location I would like to store those 4 entries.

The problem that I'm having is that the report is taking infinite amount of time by just checking each pallet-id and then looking for the rest of the same pallet-id in the initial list, is there a more efficient way of handling this?

答:
Nesting loops is a bad idea here as it leads to quadratic time complexity. You can do it in linear time though:</p>

```<code>from collections import Counter
from operator import itemgetter

pal = itemgetter('pallet-id')
pal_loc = itemgetter('pallet-id', 'location')

# unique pallet-id, location combos
pallocs = set(map(pal_loc, entries))
# set([('5555', 'LOC1'), ('5555', 'LOC2'), ('123456', 'LOC1')])

# count pallet-id occurrences in the unique combos
count = Counter(pl[0] for pl in pallocs)
# Counter({'5555': 2, '123456': 1})

# filter the entries for pallet-ids with counts greater than 1
filtered_entries = [e for e in entries if count[pal(e)] > 1]
</code>```

Body:
I'm trying to find an efficient way to handle this problem. I have an list of dictionaries with over 400k entries. I need to first find all the entries that share a common key, let's say 'pallet-id' from that list and then from that sub-list verify that all those share the same 'location' key. I'm only interested in getting from that initial list the entries that have a similar 'pallet-id' but only if one of those have a different 'location' than the rest.

Ex.

This would be working with pallet-id 123456

entry1 = {'location': 'LOC1', 'pallet-id': '123456', ...}
entry2 = {'location': 'LOC1', 'pallet-id': '123456', ...}
entry3 = {'location': 'LOC1', 'pallet-id': '123456', ...}
entry4 = {'location': 'LOC1', 'pallet-id': '123456', ...}

Since all share the same location, I don't care about this.

This would be working with pallet-id 5555

entry1 = {'location': 'LOC1', 'pallet-id': '5555', ...}
entry2 = {'location': 'LOC1', 'pallet-id': '5555', ...}
entry3 = {'location': 'LOC2', 'pallet-id': '5555', ...}
entry4 = {'location': 'LOC1', 'pallet-id': '5555', ...}

In this case since one has a different location I would like to store those 4 entries.

The problem that I'm having is that the report is taking infinite amount of time by just checking each pallet-id and then looking for the rest of the same pallet-id in the initial list, is there a more efficient way of handling this?

Body:
Nesting loops is a bad idea here as it leads to quadratic time complexity. You can do it in linear time though:

from collections import Counter
from operator import itemgetter

pal = itemgetter('pallet-id')
pal_loc = itemgetter('pallet-id', 'location')

# unique pallet-id, location combos
pallocs = set(map(pal_loc, entries))
# set([('5555', 'LOC1'), ('5555', 'LOC2'), ('123456', 'LOC1')])

# count pallet-id occurrences in the unique combos
count = Counter(pl[0] for pl in pallocs)
# Counter({'5555': 2, '123456': 1})

# filter the entries for pallet-ids with counts greater than 1
filtered_entries = [e for e in entries if count[pal(e)] > 1]


问:
C++ code gets strangely skipped with no optimizations. Any ideas why?
I looked for an answer for two days to this with no success. I've never come across this problem before so I'll try my best. Please bear with me.

I returned to a C++ project I created over a year ago, which at the time ran without problems. I came across this interesting and incredibly annoying problem the other day as I was trying to get the same program to run. The code was something like:

file.h

```<code>...
short id;
...
</code>```

file.cc

```<code>id = 0;
while (id < some_large_number)
{
   id = foo();
   if (id == 2)
   {
      //do something
   }
   else if (id == 2900)
   {
      //do something
   }
   else if (id == 30000)
   {
      //do something
   }
   else if (id == 40000)
   {
      //do something
   }
   else if (id == 45000)
   {
      //do something
   }
   else
   {
      //do something else
   }
}
</code>```

The constant numbers were macros in hex notation that I expanded for this example. Turns out that this was truly a bug, but the debugger did not make it easy to discover. Heres what happened:

As I was trying to step through the code using GDB (with no optimizations), I noticed that GDB would jump straight to the else statement after reaching if (id == 30000), everytime. Because the numbers were c macros in hex notation, I did not notice at first that 40000 was beyond the limit of a signed short. This was very misleading, and spent hours trying to figure it out: I recompiled external libraries, reinstalled g++, among other things.

Obviously, making id an unsigned short fixed the problem. The other problem seems like a compiler issue. But I still don't understand, why were those sections of code completely skipped during execution, and with no optimizations? Why would it not go through each if statement and that way I could identify the real problem? Any ideas?

Thanks so much. I hope this is okay for a first question.

答: My conclusion is the same as yours: It seems like it was optimized out even without "optimizations" turned on. Maybe these constant predicates "always true"/"always false" are used to skip the code somewhere directly in the code generation step, i.e. way sooner than any -O switch optimizations are being performed. Just a guess.</p>

Body:
I looked for an answer for two days to this with no success. I've never come across this problem before so I'll try my best. Please bear with me.

I returned to a C++ project I created over a year ago, which at the time ran without problems. I came across this interesting and incredibly annoying problem the other day as I was trying to get the same program to run. The code was something like:

file.h

...
short id;
...

file.cc

id = 0;
while (id < some_large_number)
{
   id = foo();
   if (id == 2)
   {
      //do something
   }
   else if (id == 2900)
   {
      //do something
   }
   else if (id == 30000)
   {
      //do something
   }
   else if (id == 40000)
   {
      //do something
   }
   else if (id == 45000)
   {
      //do something
   }
   else
   {
      //do something else
   }
}

The constant numbers were macros in hex notation that I expanded for this example. Turns out that this was truly a bug, but the debugger did not make it easy to discover. Heres what happened:

As I was trying to step through the code using GDB (with no optimizations), I noticed that GDB would jump straight to the else statement after reaching if (id == 30000), everytime. Because the numbers were c macros in hex notation, I did not notice at first that 40000 was beyond the limit of a signed short. This was very misleading, and spent hours trying to figure it out: I recompiled external libraries, reinstalled g++, among other things.

Obviously, making id an unsigned short fixed the problem. The other problem seems like a compiler issue. But I still don't understand, why were those sections of code completely skipped during execution, and with no optimizations? Why would it not go through each if statement and that way I could identify the real problem? Any ideas?

Thanks so much. I hope this is okay for a first question.


问:
Sending two AJAX requests at the same time
I am probably missing something very simple here, but what I am trying to do is update two divs on my page with AJAX requests that are called at the same time when an item is clicked.

I have looked at here
but unfortunately I am still missing something in the code.

I have the following JavaScript code:

```<code>$(document.body).on('click', '.details', function(event) {
    //  $(this) = your current element that clicked.
    // additional code
    var id = event.target.id;
    //alert(id);
    //alert($(this));
    _formurl = "home_stocktake_locations_list_group.php";
    _formdata = {
        'store_id': id
    };
    _formurl2 = "home_stocktake_list.php";
    $.ajax({
            type: "GET",
            url: _formurl,
            data: _formdata,
            success: function(xhrResponse) {
                $('#current').html(xhrResponse);
                var rowCount = $('#locations').length;
                row_count = parseInt(rowCount);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#alert_msg').html(errorThrown);
                $('#alert_msg').fadeIn("slow");
            }
        }),
        $.ajax({

            type: "GET",
            url: _formurl2,
            data: _formdata,
            success: function(xhrResponse) {
                $('#previous').html(xhrResponse);
                var rowCount = $('#dd_home_stocktake').length;
                row_count = parseInt(rowCount);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#alert_msg').html(errorThrown);
                $('#alert_msg').fadeIn("slow");
            }
        });

});
</code>```

When I look at what happens in the console, only home_stocktake_locations_list_group.php file gets called, the second AJAX call is completely ignored. What is causing this?

In the console I can only see the following:

答: make each request in separate promises and when all promises have been resolved on then function fire the event to change the DOM.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am probably missing something very simple here, but what I am trying to do is update two divs on my page with AJAX requests that are called at the same time when an item is clicked.

I have looked at here
but unfortunately I am still missing something in the code.

I have the following JavaScript code:

$(document.body).on('click', '.details', function(event) {
    //  $(this) = your current element that clicked.
    // additional code
    var id = event.target.id;
    //alert(id);
    //alert($(this));
    _formurl = "home_stocktake_locations_list_group.php";
    _formdata = {
        'store_id': id
    };
    _formurl2 = "home_stocktake_list.php";
    $.ajax({
            type: "GET",
            url: _formurl,
            data: _formdata,
            success: function(xhrResponse) {
                $('#current').html(xhrResponse);
                var rowCount = $('#locations').length;
                row_count = parseInt(rowCount);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#alert_msg').html(errorThrown);
                $('#alert_msg').fadeIn("slow");
            }
        }),
        $.ajax({

            type: "GET",
            url: _formurl2,
            data: _formdata,
            success: function(xhrResponse) {
                $('#previous').html(xhrResponse);
                var rowCount = $('#dd_home_stocktake').length;
                row_count = parseInt(rowCount);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $('#alert_msg').html(errorThrown);
                $('#alert_msg').fadeIn("slow");
            }
        });

});

When I look at what happens in the console, only home_stocktake_locations_list_group.php file gets called, the second AJAX call is completely ignored. What is causing this?

In the console I can only see the following:


问:
In a csv file get all values of rows and columns between 2 specific words say start and stop
I have a csv file with time,event and acceleration values(x,y,z) as columns and I want to fetch only the values between the event values start and stop(where in event column there are various words like start stop motion location). I have done using data frame in pandas but I get values of start and stop instead of all the values in between them.

Csv file:

```<code> time   event   earthAcceleration.x earthAcceleration.y earthAcceleration.z

2017-11-22T09:20:13.944 motion  -0.006380   -0.001029   -0.010781

2017-11-22T09:20:13.954 start

2017-11-22T09:20:13.964 motion  0.008521    -0.008223   0.022574

2017-11-22T09:20:13.974 stop

2017-11-22T09:20:13.984 motion  0.016283    0.003181    0.006969
</code>```

Code:

```<code>import pandas as pd
df = pd.read_csv('nehi.csv')
df = df[df['event'].between('start', 'stop', inclusive=True)]
df
</code>```

My output is: values where the words = start and stop

```<code>time    event   earthAccelerationx earthAccelerationy earthAccelerationz

2017-11-22T09:20:13.954 start   NaN NaN NaN

2017-11-22T09:20:13.974 stop    NaN NaN NaN
</code>```

Also tried

```<code>start= event[(event['event']=='start') & (event['event']=='stop')]
start.head()
</code>```

But gives empty values

Desired output is: Values of time and acceleration between the words start and stop.

```<code>time       event    earthAccelerationx  earthAccelerationy earthAccelerationz

2017-11-22T09:20:13.964 motion  0.008521    -0.008223   0.022574
</code>```

Goal: To extract all column and row values between 2 keywords in column named events.

答:
I use 'hello' and 'world' how keywords.</p>

```<code>import pandas as pd

df = pd.read_csv('two.txt', header=None, delimiter="hello", engine='python')
df2 = df.loc[:, 1]
values = []

for row in df2:
    print (row.index('world'))
    values.append(row[:row.index('world')])

print(values)
</code>```

Body:
I have a csv file with time,event and acceleration values(x,y,z) as columns and I want to fetch only the values between the event values start and stop(where in event column there are various words like start stop motion location). I have done using data frame in pandas but I get values of start and stop instead of all the values in between them.

Csv file:

 time   event   earthAcceleration.x earthAcceleration.y earthAcceleration.z

2017-11-22T09:20:13.944 motion  -0.006380   -0.001029   -0.010781

2017-11-22T09:20:13.954 start

2017-11-22T09:20:13.964 motion  0.008521    -0.008223   0.022574

2017-11-22T09:20:13.974 stop

2017-11-22T09:20:13.984 motion  0.016283    0.003181    0.006969

Code:

import pandas as pd
df = pd.read_csv('nehi.csv')
df = df[df['event'].between('start', 'stop', inclusive=True)]
df

My output is: values where the words = start and stop

time    event   earthAccelerationx earthAccelerationy earthAccelerationz

2017-11-22T09:20:13.954 start   NaN NaN NaN

2017-11-22T09:20:13.974 stop    NaN NaN NaN

Also tried

start= event[(event['event']=='start') & (event['event']=='stop')]
start.head()

But gives empty values

Desired output is: Values of time and acceleration between the words start and stop.

time       event    earthAccelerationx  earthAccelerationy earthAccelerationz

2017-11-22T09:20:13.964 motion  0.008521    -0.008223   0.022574

Goal: To extract all column and row values between 2 keywords in column named events.

Body:
I use 'hello' and 'world' how keywords.

import pandas as pd

df = pd.read_csv('two.txt', header=None, delimiter="hello", engine='python')
df2 = df.loc[:, 1]
values = []

for row in df2:
    print (row.index('world'))
    values.append(row[:row.index('world')])

print(values)


问:
Running Android Studio with an HTTP Proxy
I just downloaded and installed the latest version of Android Studio (3.0.1) at work to start a new tablet project.  During setup it needed me to enter my proxy server information which I did.  I created an empty project and it asked me to accept or reject a couple of certificates one from Google Inc (*.google.com) and another from JetBrains s.r.o. (plugins.jetbrains.com).  I accepted them and they now show up in Settings -> Tools -> Server Certificates.  It has been able to download a number of packages, but after everything appears to be installed I get a message "Gradle project sync failed.  Basic functionality will not work properly."

There are a number of error messages that look like this:

```<code>Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0.

Could not resolve com.android.support:appcompat-v7:26.1.0.
Required by:
    project :app
 > Could not resolve com.android.support:appcompat-v7:26.1.0.
    > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
          > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
                   > dl.google.com
</code>```

I tried adding http and https proxy server information to the 'gradle.properties' as suggested here.

That changed the error message to this:

```<code>Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0.

Could not resolve com.android.support:appcompat-v7:26.1.0.
Required by:
    project :app
 > Could not resolve com.android.support:appcompat-v7:26.1.0.
    > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
          > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
                   > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                               > PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                              > unable to find valid certification path to requested target
</code>```

Further digging came up with this.  Adding the URL to FireFox allows me to download the appcompat-v7-26.1.0.pom file but does not provide a "HTTPS certificate chain" to export a certificate from.  I am also not sure where I am supposed to get the keytool mentioned as well.

To verify that it is the proxy setup that is causing the problem I took my laptop home. Using my home network and turning off the HTTP Proxy caused a 3rd error (connection timed out) which was fixed by clearing the certificates.  So it appears that the certificates accepted in Android Studio are used by at least part of the process.   Now that I am back at work everything seems to work just fine.

There must be others out there running Android Studio with an HTTP Proxy set.  What is the "correct" way of fixing this?

答:
I replaced the file

```<code>C:\Program Files\Android\Android Studio\jre\jre\lib\security>\cacerts
</code>```

with the file from the jre (%JAVA_HOME%\lib\security\cacerts).

The certificates in the new cacerts file directed the android jre to go through the proxy server.

Body:
I just downloaded and installed the latest version of Android Studio (3.0.1) at work to start a new tablet project.  During setup it needed me to enter my proxy server information which I did.  I created an empty project and it asked me to accept or reject a couple of certificates one from Google Inc (*.google.com) and another from JetBrains s.r.o. (plugins.jetbrains.com).  I accepted them and they now show up in Settings -> Tools -> Server Certificates.  It has been able to download a number of packages, but after everything appears to be installed I get a message "Gradle project sync failed.  Basic functionality will not work properly."

There are a number of error messages that look like this:

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0.

Could not resolve com.android.support:appcompat-v7:26.1.0.
Required by:
    project :app
 > Could not resolve com.android.support:appcompat-v7:26.1.0.
    > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
          > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
                   > dl.google.com

I tried adding http and https proxy server information to the 'gradle.properties' as suggested here.

That changed the error message to this:

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0.

Could not resolve com.android.support:appcompat-v7:26.1.0.
Required by:
    project :app
 > Could not resolve com.android.support:appcompat-v7:26.1.0.
    > Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
          > Could not GET 'https://dl.google.com/dl/android/maven2/com/android/support/appcompat-v7/26.1.0/appcompat-v7-26.1.0.pom'.
                   > sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                               > PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
                                              > unable to find valid certification path to requested target

Further digging came up with this.  Adding the URL to FireFox allows me to download the appcompat-v7-26.1.0.pom file but does not provide a "HTTPS certificate chain" to export a certificate from.  I am also not sure where I am supposed to get the keytool mentioned as well.

To verify that it is the proxy setup that is causing the problem I took my laptop home. Using my home network and turning off the HTTP Proxy caused a 3rd error (connection timed out) which was fixed by clearing the certificates.  So it appears that the certificates accepted in Android Studio are used by at least part of the process.   Now that I am back at work everything seems to work just fine.

There must be others out there running Android Studio with an HTTP Proxy set.  What is the "correct" way of fixing this?

Body:
I replaced the file

C:\Program Files\Android\Android Studio\jre\jre\lib\security>\cacerts

with the file from the jre (%JAVA_HOME%\lib\security\cacerts).

The certificates in the new cacerts file directed the android jre to go through the proxy server.


问:
Finding a random element in an 2D array,then performing operations on it
I need to find a random element in a 2D array, as the title says.  Then I need to perform an operation on this.

For example:

```<code>Grid = np.zeros((64,64))
ones = np.ones((32,64))
minus = -1 * ones
Grid[0:32,:] = ones[:]
Grid[32:64,:] = minus[:]
</code>```

So its half full of 1's, half of -1's.  Then I need to select a random element of this 2D array,and perform an operation on it.

For example it needs to do something like:

```<code>def change(Grid):
    Grid[0,0] *= -1
</code>```

But for a random element inside this list, but obviously the below code doesn't work.

```<code>Grid[random.choice,random.choice] *= -1
</code>```

Is there a way to do this with random.choice, or is there another way to make this work?

答:
Since you're already in NumPy, you could use np.random.randint:

```<code>n, m = Grid.shape
row = np.random.randint(0, n)
col = np.random.randint(0, m)
Grid[row, col] *= -1
</code>```

Body:
I need to find a random element in a 2D array, as the title says.  Then I need to perform an operation on this.

For example:

Grid = np.zeros((64,64))
ones = np.ones((32,64))
minus = -1 * ones
Grid[0:32,:] = ones[:]
Grid[32:64,:] = minus[:]

So its half full of 1's, half of -1's.  Then I need to select a random element of this 2D array,and perform an operation on it.

For example it needs to do something like:

def change(Grid):
    Grid[0,0] *= -1

But for a random element inside this list, but obviously the below code doesn't work.

Grid[random.choice,random.choice] *= -1

Is there a way to do this with random.choice, or is there another way to make this work?

Body:
Since you're already in NumPy, you could use np.random.randint:

n, m = Grid.shape
row = np.random.randint(0, n)
col = np.random.randint(0, m)
Grid[row, col] *= -1


问:
Predictions on a two layer trained neural model on Tensorflow
I'm having trouble making predictions with a trained neural model on Tensor. Here's my attempt:

```<code>import tensorflow as tf
import pandas, numpy as np
dataset=[[0.4,0.5,0.6,0],[0.6,0.7,0.8,1],[0.3,0.8,0.5,2],....]

X = tf.placeholder(tf.float32, [None, 3])
W = tf.Variable(tf.zeros([3,10]))
b = tf.Variable(tf.zeros([10]))

Y1 = tf.matmul(X, W) + b

W1 = tf.Variable(tf.zeros([10, 1]))
b1 = tf.Variable(tf.zeros([1]))
Y = tf.nn.sigmoid(tf.matmul(Y1, W1) + b1)

# placeholder for correct labels
Y_ = tf.placeholder(tf.float32, [None, 1])
init = tf.global_variables_initializer()
# loss function

cross_entropy = -tf.reduce_sum(Y_ * tf.log(Y))
optimizer = tf.train.GradientDescentOptimizer(0.003)
train_step = optimizer.minimize(cross_entropy)

sess = tf.Session()
sess.run(init)

for i in range(1000):
    # load batch of images and correct answers
    batch_X, batch_Y = [x[:3] for x in dataset[:4000]],[x[-1:] for x in dataset[:4000]]
    train_data={X: batch_X, Y_: batch_Y}
    sess.run(train_step, feed_dict=train_data)

correct_prediction = tf.equal(tf.argmax(Y,1), tf.argmax(Y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
a,c = sess.run([accuracy, cross_entropy], feed_dict=train_data)

test, lebs=[x[:3] for x in dataset[4000:]],[x[-1:] for x in dataset[4000:]]
test_data={X: test, Y_: lebs}
a,c = sess.run([accuracy, cross_entropy], feed_dict=test_data)
prediction=tf.argmax(Y,1)
print ("predictions", prediction.eval({X:test}, session=sess))
</code>```

I got the following results when I ran the above code:

```<code>predictions [0 0 0 ..., 0 0 0]
</code>```

My expected output should be the class labels:

```<code>predictions `[0,1,2....]`
</code>```

I will appreciate your suggestions.

答:
There are multiple problems with your code:

Initialisation:  You are zero initializing your weight variable.

W = tf.Variable(tf.zeros([3,10]))

Your model will keep propogating same values at each layer for all types of inputs if you zero initialize it. Initialize it with random values. Ex:

W = tf.Variable(tf.truncated_normal((3,10)))

Loss function: I believe you are trying to replicate this familiar looking equation as your loss function:
y * log(prob) + (1 - y) * log(1 - prob). I believe you are having totally 10 classes. For each of the 10 classes, you will have to substitue the above equation and remember, you will use y value in above equation as either correct class or wrong class i.e 1 or 0 only for each class. Do not substitute y value as class label from 0 to 9.

To avoid all this calculations, I will suggest you to make use of Tensorflow's in-built functions like tf.nn.softmax_cross_entropy_with_logits. It will help you in a long way.

Sigmoid function: This is the prime culprit on why all your outputs are giving value as only 0. The output range of sigmoid is from 0 to 1. Think of replacing it with ReLU.

Output units: If you are doing classification, your number of neurons in final layers should be equal to number of classes. Each class denotes one output class. Replace it with 10 neurons.

Learning rate: Keep playing with your learning rate. I believe your learning rate is little high for such a small network.

Hope you understood the problems in your code. Please Google each of the above point I have mentioned for greater details but I have given you more than enough information to start solving the problem.

Body:
I'm having trouble making predictions with a trained neural model on Tensor. Here's my attempt:

import tensorflow as tf
import pandas, numpy as np
dataset=[[0.4,0.5,0.6,0],[0.6,0.7,0.8,1],[0.3,0.8,0.5,2],....]

X = tf.placeholder(tf.float32, [None, 3])
W = tf.Variable(tf.zeros([3,10]))
b = tf.Variable(tf.zeros([10]))

Y1 = tf.matmul(X, W) + b

W1 = tf.Variable(tf.zeros([10, 1]))
b1 = tf.Variable(tf.zeros([1]))
Y = tf.nn.sigmoid(tf.matmul(Y1, W1) + b1)

# placeholder for correct labels
Y_ = tf.placeholder(tf.float32, [None, 1])
init = tf.global_variables_initializer()
# loss function

cross_entropy = -tf.reduce_sum(Y_ * tf.log(Y))
optimizer = tf.train.GradientDescentOptimizer(0.003)
train_step = optimizer.minimize(cross_entropy)

sess = tf.Session()
sess.run(init)

for i in range(1000):
    # load batch of images and correct answers
    batch_X, batch_Y = [x[:3] for x in dataset[:4000]],[x[-1:] for x in dataset[:4000]]
    train_data={X: batch_X, Y_: batch_Y}
    sess.run(train_step, feed_dict=train_data)

correct_prediction = tf.equal(tf.argmax(Y,1), tf.argmax(Y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
a,c = sess.run([accuracy, cross_entropy], feed_dict=train_data)

test, lebs=[x[:3] for x in dataset[4000:]],[x[-1:] for x in dataset[4000:]]
test_data={X: test, Y_: lebs}
a,c = sess.run([accuracy, cross_entropy], feed_dict=test_data)
prediction=tf.argmax(Y,1)
print ("predictions", prediction.eval({X:test}, session=sess))

I got the following results when I ran the above code:

predictions [0 0 0 ..., 0 0 0]

My expected output should be the class labels:

predictions `[0,1,2....]`

I will appreciate your suggestions.


问:
Calculate Document Frequency in Multidimensinal Array PHP
I have an array like this

```<code> Array (
        [0] => Array ( [id_doc] => 1 [term] => curi )
        [1] => Array ( [id_doc] => 1 [term] => tidur )
        [2] => Array ( [id_doc] => 1 [term] => kamar )
        [3] => Array ( [id_doc] => 2 [term] => curi )
        [4] => Array ( [id_doc] => 2 [term] => cela )
        [5] => Array ( [id_doc] => 2 [term] => hukum )
        [6] => Array ( [id_doc] => 3 [term] => nyanyi )
        [7] => Array ( [id_doc] => 3 [term] => dangdut )
        [8] => Array ( [id_doc] => 3 [term] => curi )
    )
</code>```

How to get count of document frequency from term that on these document. I want the output like this.

```<code>Array (
        [0] => Array ( [id_doc] => 1 [term] => curi [doc_frequency] => 3 )
        [1] => Array ( [id_doc] => 1 [term] => tidur [doc_frequency] => 1 )
        [2] => Array ( [id_doc] => 1 [term] => kamar [doc_frequency] => 1 )
        [3] => Array ( [id_doc] => 2 [term] => curi [doc_frequency] => 3 )
        [4] => Array ( [id_doc] => 2 [term] => cela [doc_frequency] => 1 )
        [5] => Array ( [id_doc] => 2 [term] => hukum [doc_frequency] => 1 )
        [6] => Array ( [id_doc] => 3 [term] => nyanyi [doc_frequency] => 1 )
        [7] => Array ( [id_doc] => 3 [term] => dangdut [doc_frequency] => 1 )
        [8] => Array ( [id_doc] => 3 [term] => curi [doc_frequency] => 3 )
    )
</code>```

So term 'curi' have 3 document frequency, because its appear on 3 documents.
I have tried with this

```<code>$count_df = array_count_values(array_map(function($item) {
   return $item['term'];
}, $dokumen_frek));
print_r($count_df);
</code>```

but the result is

```<code>Array (
[curi] => 3
[tidur] => 1
[kamar] => 1
[cela] => 1
[hukum] => 1
[nyanyi] => 1
[dangdut] => 1
</code>```

)

答:
Use  array_count_values function

```<code>$terms = array_count_values(array_column($arr, 'term'));

foreach($arr as &$x) {
   $x['doc_frequency'] = $terms[$x['term']];
}
</code>```

demo

Body:
I have an array like this

 Array (
        [0] => Array ( [id_doc] => 1 [term] => curi )
        [1] => Array ( [id_doc] => 1 [term] => tidur )
        [2] => Array ( [id_doc] => 1 [term] => kamar )
        [3] => Array ( [id_doc] => 2 [term] => curi )
        [4] => Array ( [id_doc] => 2 [term] => cela )
        [5] => Array ( [id_doc] => 2 [term] => hukum )
        [6] => Array ( [id_doc] => 3 [term] => nyanyi )
        [7] => Array ( [id_doc] => 3 [term] => dangdut )
        [8] => Array ( [id_doc] => 3 [term] => curi )
    )

How to get count of document frequency from term that on these document. I want the output like this.

Array (
        [0] => Array ( [id_doc] => 1 [term] => curi [doc_frequency] => 3 )
        [1] => Array ( [id_doc] => 1 [term] => tidur [doc_frequency] => 1 )
        [2] => Array ( [id_doc] => 1 [term] => kamar [doc_frequency] => 1 )
        [3] => Array ( [id_doc] => 2 [term] => curi [doc_frequency] => 3 )
        [4] => Array ( [id_doc] => 2 [term] => cela [doc_frequency] => 1 )
        [5] => Array ( [id_doc] => 2 [term] => hukum [doc_frequency] => 1 )
        [6] => Array ( [id_doc] => 3 [term] => nyanyi [doc_frequency] => 1 )
        [7] => Array ( [id_doc] => 3 [term] => dangdut [doc_frequency] => 1 )
        [8] => Array ( [id_doc] => 3 [term] => curi [doc_frequency] => 3 )
    )

So term 'curi' have 3 document frequency, because its appear on 3 documents.
I have tried with this

$count_df = array_count_values(array_map(function($item) {
   return $item['term'];
}, $dokumen_frek));
print_r($count_df);

but the result is

Array (
[curi] => 3
[tidur] => 1
[kamar] => 1
[cela] => 1
[hukum] => 1
[nyanyi] => 1
[dangdut] => 1

)

Body:
Use  array_count_values function

$terms = array_count_values(array_column($arr, 'term'));

foreach($arr as &$x) {
   $x['doc_frequency'] = $terms[$x['term']];
}

demo


问:
Access object from outer select clause in LINQ statement
Suppose I have the following LINQ Statement. I would like to find a way to use "r.Portfolio" while I am in the 3rd select clause (see comment in the code):

```<code>positionsToOptimize
    .Select(p => p)
    .SelectMany(r => r.Positions)
    .Select(pos => new OptimizedPosition() {
        CalculationType = TCalculationType.Absolute,
        Position = pos.NetPositionAmount,
        SecurityID = pos.SecurityID,
        Portfolio = r.Portfolio        // <- How do I do this? (Portfolio is not in 'pos')
    });
</code>```

Essentially I am trying to replace the following foreach nested loop:

```<code>var lst = new List<OptimizedPosition>();
foreach (var r in positionsToOptimize) {
    foreach (var pos in r.Positions) {
        lst.Add(new OptimizedPosition() {
            CalculationType = TCalculationType.Absolute,
            Position = pos.NetPositionAmount,
            SecurityID = pos.SecurityID,
            SystemCode = r.SystemCode
        });
    }
}

return lst;
</code>```

答:
For cases when you need to use SelectMany and Select in the same query I would suggest to use linq syntax:

```<code>from r in positionsToOptimize
from pos in r.Positions
select new OptimizedPosition
{
    CalculationType = TCalculationType.Absolute,
    Position = pos.NetPositionAmount,
    SecurityID = pos.SecurityID,
    Portfolio = r.Portfolio
};
</code>```

As you can see it is very clean and easy to read and doesn't require any additional temporary objects.

Body:
Suppose I have the following LINQ Statement. I would like to find a way to use "r.Portfolio" while I am in the 3rd select clause (see comment in the code):

positionsToOptimize
    .Select(p => p)
    .SelectMany(r => r.Positions)
    .Select(pos => new OptimizedPosition() {
        CalculationType = TCalculationType.Absolute,
        Position = pos.NetPositionAmount,
        SecurityID = pos.SecurityID,
        Portfolio = r.Portfolio        // <- How do I do this? (Portfolio is not in 'pos')
    });

Essentially I am trying to replace the following foreach nested loop:

var lst = new List<OptimizedPosition>();
foreach (var r in positionsToOptimize) {
    foreach (var pos in r.Positions) {
        lst.Add(new OptimizedPosition() {
            CalculationType = TCalculationType.Absolute,
            Position = pos.NetPositionAmount,
            SecurityID = pos.SecurityID,
            SystemCode = r.SystemCode
        });
    }
}

return lst;

Body:
For cases when you need to use SelectMany and Select in the same query I would suggest to use linq syntax:

from r in positionsToOptimize
from pos in r.Positions
select new OptimizedPosition
{
    CalculationType = TCalculationType.Absolute,
    Position = pos.NetPositionAmount,
    SecurityID = pos.SecurityID,
    Portfolio = r.Portfolio
};

As you can see it is very clean and easy to read and doesn't require any additional temporary objects.


问:
Parse-Server delete class with Mongodb
How to delete class from mongodb?

ps. I'm using the mongodb 3.0 on windows with windows power shell.

答: I found that answer above does not answer it 100% if you do that it will still show up in the parse dashboard. If you delete the record in the _SCHEMA collection in mongodb the class will no longer show up in the parse dashboard.

Title: Parse-Server delete class with Mongodb


问:
XSLT: Getting the latest date
I have a structure like this:

```<code>  <Info ID="1">
    ...
    <Date>2009-04-21</Date>
  </Info>
  <Info ID="2">
    ...
    <Date>2009-04-22</Date>
  </Info>
  <Info ID="3">
    ...
    <Date>2009-04-20</Date>
  </Info>
</code>```

I want to get the latest date using XSLT (in this example - 2009-04-22).

答:
In XSLT 2.0 or later, you shouldn't need to sort at all; you can use max()...

```<code><xsl:value-of select="max(//Date/xs:date(.))"/>
</code>```

OwnerDisplayName: Mindaugas Mozūras

Title: XSLT: Getting the latest date

Body:
I have a structure like this:

  <Info ID="1">
    ...
    <Date>2009-04-21</Date>
  </Info>
  <Info ID="2">
    ...
    <Date>2009-04-22</Date>
  </Info>
  <Info ID="3">
    ...
    <Date>2009-04-20</Date>
  </Info>

I want to get the latest date using XSLT (in this example - 2009-04-22).

LastEditorDisplayName: Mindaugas Mozūras

Body:
In XSLT 2.0 or later, you shouldn't need to sort at all; you can use max()...

<xsl:value-of select="max(//Date/xs:date(.))"/>


问:
Format error when using Bosun save hook
I get the following error while attempting to use the "save hook" functionality in Bosun -

failed to call save hook: fork/exec /tools/bosun/bin/save-hook: exec format error. Restoring config: successful

The file is executable and I've removed all logic from it, and the error still occurs.

Should the file return anything? Or is this a bug?

The documentation indicates it should be successful as long as the hook exits ok.

https://bosun.org/system_configuration#commandhookpath

答:
I would guess the OS is not accepting this as a proper executable?

If a binary, did you compile it on the same system, or make sure your cross compiled it for the right architecture?

If a script, does your script have the bang line at the start, for example #!/bin/bash?

Title: Format error when using Bosun save hook


问:
Able to read of an object in json format, but not able read its properties in Angular2
Error image

I am able to access the object in json format, I can see all the properties and values, but I am not able to access individual property values.

I highly appreciate your help in advance !!!

```<code> example.html

<label>Name:</label>

<input type="text" [(ngModel)]="yourName" placeholder="Enter a name here">
<input type="number" [(ngModel)]="age" placeholder="Enter age here">
<br>
<button (click)="send({ name : yourName, age : age})">send</button>

<h1 [hidden]="!yourName">Hello {{yourName}}!</h1>
{{myobj | json}}
{{myobj.name}}

example.ts

import {Component} from 'angular2/core';

@Component({
 selector: 'hello-world',
 templateUrl: 'src/hello_world.html'
})
export class HelloWorld {
yourName: string = '';
myname : string;
myage : number;
send : any (obj){
  console.log(obj);
  this.myobj = obj;
}
</code>```

}

答:
This below code works for me. I just defined myobj:any in the component and modified the send method signature .

hello_world.html

```<code>    <label>Name:</label>
    <input type="text" [(ngModel)]="yourName" placeholder="Enter a name here">
    <input type="number" [(ngModel)]="age" placeholder="Enter age here">
    <br>
    <button (click)="send({ name : yourName, age : age})">send</button>

    <h1 [hidden]="!yourName">Hello {{yourName}}!</h1>
    {{myobj | json}}
    {{myobj.name}}
</code>```

helloworld.ts

```<code>import {Component} from '@angular/core'

@Component({
 selector: 'hello-world',
 templateUrl: 'src/hello_world.html'
})
export class HelloWorld {
yourName: string = '';
myname : string;
myage : number;
myobj:any;

constructor(){}

public send(obj:any):void{
  console.log(obj);
  this.myobj = obj;
}

}
</code>```

Here is a link to a working plunker

https://plnkr.co/edit/5eNU8ermOX90UThetAJX?p=preview

Body:
Error image

I am able to access the object in json format, I can see all the properties and values, but I am not able to access individual property values.

I highly appreciate your help in advance !!!

 example.html

Name:

<input type="text" [(ngModel)]="yourName" placeholder="Enter a name here">
<input type="number" [(ngModel)]="age" placeholder="Enter age here">

<button (click)="send({ name : yourName, age : age})">send</button>

Hello {{yourName}}!

{{myobj | json}}
{{myobj.name}}

example.ts

import {Component} from 'angular2/core';

@Component({
 selector: 'hello-world',
 templateUrl: 'src/hello_world.html'
})
export class HelloWorld {
yourName: string = '';
myname : string;
myage : number;
send : any (obj){
  console.log(obj);
  this.myobj = obj;
}

}

Body:
This below code works for me. I just defined myobj:any in the component and modified the send method signature .

hello_world.html

    <label>Name:</label>
    <input type="text" [(ngModel)]="yourName" placeholder="Enter a name here">
    <input type="number" [(ngModel)]="age" placeholder="Enter age here">
    <br>
    <button (click)="send({ name : yourName, age : age})">send</button>

    <h1 [hidden]="!yourName">Hello {{yourName}}!</h1>
    {{myobj | json}}
    {{myobj.name}}

helloworld.ts

import {Component} from '@angular/core'

@Component({
 selector: 'hello-world',
 templateUrl: 'src/hello_world.html'
})
export class HelloWorld {
yourName: string = '';
myname : string;
myage : number;
myobj:any;

constructor(){}

public send(obj:any):void{
  console.log(obj);
  this.myobj = obj;
}

}

Here is a link to a working plunker

https://plnkr.co/edit/5eNU8ermOX90UThetAJX?p=preview