问:
Telegram Bot API Webhooks with Go, GoLang on Heroku
I use go-telegram-bot-api for building a Telegram Bot and deploying it on Heroku.

I need to set Webhooks as I used to do in Python like in this Python case.

Can't understand how to set Webhooks in go-telegram-bot-api without providing certificate files.

The main example contains such lines:

If you need to use webhooks (if you wish to run on Google App Engine), you may use a slightly different method.

```<code>package main

import (
    "gopkg.in/telegram-bot-api.v4"
    "log"
    "net/http"
)

func main() {
    bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
    if err != nil {
        log.Fatal(err)
    }

    bot.Debug = true

    log.Printf("Authorized on account %s", bot.Self.UserName)

    _, err = bot.SetWebhook(tgbotapi.NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem"))
    if err != nil {
        log.Fatal(err)
    }

    updates := bot.ListenForWebhook("/" + bot.Token)
    go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)

    for update := range updates {
        log.Printf("%+v\n", update)
    }
}
</code>```

But using Heroku for deploying how could I listen to Webhooks without providing pem certificate files?

答:
Following this https://devcenter.heroku.com/articles/getting-started-with-go to get the starter code.

initTelegram() and webhookHandler() are functions to study.

Once code is deployed to Heroku, run:

heroku logs --tail -a <YOUR-APP-NAME>

send some messages to the bot, you should see messages logged.

UPDATE 1

Check your app URL is the same as baseURL variable in your code -- run heroku info -a <YOUR-APP-NAME> -- your URL should be equal to what Web URL is.

UPDATE 2

In order to check your Telegram API Webhooks response ping this address in your browser: https://api.telegram.org/bot<YOUR BOT TOKEN GOES HERE>/getWebhookInfo where you should concatenate string bot and your actual Telegram Bot Token in that address string.

Optionally if you run your code not on Heroku, running curl from terminal could be an option according to Official Telegram API Reference:

$ curl -F "url=https://your.domain.or.ip.com" -F "certificate=@/etc/ssl/certs/bot.pem" https://api.telegram.org/bot<YOUR BOT TOKEN GOES HERE>/setWebhook

THE CODE:

```<code>package main

import (
    "encoding/json"
    "io"
    "io/ioutil"
    "log"
    "os"

    "github.com/gin-gonic/gin"
    "gopkg.in/telegram-bot-api.v4"

    _ "github.com/heroku/x/hmetrics/onload"
    _ "github.com/lib/pq"
)

var (
    bot      *tgbotapi.BotAPI
    botToken = "<YOUR BOT TOKEN GOES HERE>"
    baseURL  = "https://<YOUR-APP-NAME>.herokuapp.com/"
)

func initTelegram() {
    var err error

    bot, err = tgbotapi.NewBotAPI(botToken)
    if err != nil {
        log.Println(err)
        return
    }

    // this perhaps should be conditional on GetWebhookInfo()
    // only set webhook if it is not set properly
    url := baseURL + bot.Token
    _, err = bot.SetWebhook(tgbotapi.NewWebhook(url))
    if err != nil {
        log.Println(err)
    }
}

func webhookHandler(c *gin.Context) {
    defer c.Request.Body.Close()

    bytes, err := ioutil.ReadAll(c.Request.Body)
    if err != nil {
        log.Println(err)
        return
    }

    var update tgbotapi.Update
    err = json.Unmarshal(bytes, &update)
    if err != nil {
        log.Println(err)
        return
    }

    // to monitor changes run: heroku logs --tail
    log.Printf("From: %+v Text: %+v\n", update.Message.From, update.Message.Text)
}

func main() {
    port := os.Getenv("PORT")

    if port == "" {
        log.Fatal("$PORT must be set")
    }

    // gin router
    router := gin.New()
    router.Use(gin.Logger())

    // telegram
    initTelegram()
    router.POST("/" + bot.Token, webhookHandler)

    err := router.Run(":" + port)
    if err != nil {
        log.Println(err)
    }
}
</code>```

Good luck and have fun!

Body:
I use go-telegram-bot-api for building a Telegram Bot and deploying it on Heroku.

I need to set Webhooks as I used to do in Python like in this Python case.

Can't understand how to set Webhooks in go-telegram-bot-api without providing certificate files.

The main example contains such lines:

If you need to use webhooks (if you wish to run on Google App Engine), you may use a slightly different method.

package main

import (
    "gopkg.in/telegram-bot-api.v4"
    "log"
    "net/http"
)

func main() {
    bot, err := tgbotapi.NewBotAPI("MyAwesomeBotToken")
    if err != nil {
        log.Fatal(err)
    }

    bot.Debug = true

    log.Printf("Authorized on account %s", bot.Self.UserName)

    _, err = bot.SetWebhook(tgbotapi.NewWebhookWithCert("https://www.google.com:8443/"+bot.Token, "cert.pem"))
    if err != nil {
        log.Fatal(err)
    }

    updates := bot.ListenForWebhook("/" + bot.Token)
    go http.ListenAndServeTLS("0.0.0.0:8443", "cert.pem", "key.pem", nil)

    for update := range updates {
        log.Printf("%+v\n", update)
    }
}

But using Heroku for deploying how could I listen to Webhooks without providing pem certificate files?

Body:
Following this https://devcenter.heroku.com/articles/getting-started-with-go to get the starter code.

initTelegram() and webhookHandler() are functions to study.

Once code is deployed to Heroku, run:

heroku logs --tail -a <YOUR-APP-NAME>

send some messages to the bot, you should see messages logged.

UPDATE 1

Check your app URL is the same as baseURL variable in your code -- run heroku info -a <YOUR-APP-NAME> -- your URL should be equal to what Web URL is.

UPDATE 2

In order to check your Telegram API Webhooks response ping this address in your browser: https://api.telegram.org/bot<YOUR BOT TOKEN GOES HERE>/getWebhookInfo where you should concatenate string bot and your actual Telegram Bot Token in that address string.

Optionally if you run your code not on Heroku, running curl from terminal could be an option according to Official Telegram API Reference:

$ curl -F "url=https://your.domain.or.ip.com" -F "certificate=@/etc/ssl/certs/bot.pem" https://api.telegram.org/bot<YOUR BOT TOKEN GOES HERE>/setWebhook

THE CODE:

package main

import (
    "encoding/json"
    "io"
    "io/ioutil"
    "log"
    "os"

    "github.com/gin-gonic/gin"
    "gopkg.in/telegram-bot-api.v4"

    _ "github.com/heroku/x/hmetrics/onload"
    _ "github.com/lib/pq"
)

var (
    bot      *tgbotapi.BotAPI
    botToken = "<YOUR BOT TOKEN GOES HERE>"
    baseURL  = "https://<YOUR-APP-NAME>.herokuapp.com/"
)

func initTelegram() {
    var err error

    bot, err = tgbotapi.NewBotAPI(botToken)
    if err != nil {
        log.Println(err)
        return
    }

    // this perhaps should be conditional on GetWebhookInfo()
    // only set webhook if it is not set properly
    url := baseURL + bot.Token
    _, err = bot.SetWebhook(tgbotapi.NewWebhook(url))
    if err != nil {
        log.Println(err)
    }
}

func webhookHandler(c *gin.Context) {
    defer c.Request.Body.Close()

    bytes, err := ioutil.ReadAll(c.Request.Body)
    if err != nil {
        log.Println(err)
        return
    }

    var update tgbotapi.Update
    err = json.Unmarshal(bytes, &update)
    if err != nil {
        log.Println(err)
        return
    }

    // to monitor changes run: heroku logs --tail
    log.Printf("From: %+v Text: %+v\n", update.Message.From, update.Message.Text)
}

func main() {
    port := os.Getenv("PORT")

    if port == "" {
        log.Fatal("$PORT must be set")
    }

    // gin router
    router := gin.New()
    router.Use(gin.Logger())

    // telegram
    initTelegram()
    router.POST("/" + bot.Token, webhookHandler)

    err := router.Run(":" + port)
    if err != nil {
        log.Println(err)
    }
}

Good luck and have fun!


来源: stackexchange

问:
Execute a bat file when an image is viewed
I want to hide a bat file or its commands in a image file so when the image is opened the commands in the bat file is executed.</p>

答: Simplest way to do this is to just create your batch file as normal and then create a desktop shortcut of the  same batch file. Finally right-click on the shortcut and change the icon to what ever image you want. Once all changes are made then anytime the image is opened,  the batch file will run. </p>

ContentLicense: CC BY-SA 3.0


问:
How to position 3 buttons in StackLayout equal width
Anyone know how to position 3 buttons in StackLayout with equal width?  I have it working with Grid with

```<code><Grid x:Name="MyGrid" Grid.Row="0" BindingContext="{x:Reference Name=Button1}"  HeightRequest="{Binding Width}">
</code>```

I would like to find a way to show 3 buttons on same line  with same width equally without a Grid
For example all 3 buttons of equal length fitting across horizontally in StackLayout

[   Button 1   ]  [   Button 222   ]  [   Button 333333   ]

答:
RelativeLayout:

```<code><RelativeLayout HorizontalOptions="FillAndExpand">
    <Button Text="Button 1" RelativeLayout.XConstraint="{ConstraintExpression
            Type=RelativeToParent,Property=Width,Factor=.0000,Constant=0}"
            RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent,
            Property=Width,Factor=.3333,Constant=0}"/>
    <Button Text="Button 222" RelativeLayout.XConstraint="{ConstraintExpression
            Type=RelativeToParent,Property=Width,Factor=.3333,Constant=0}"
            RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent,
            Property=Width,Factor=.3333,Constant=0}"/>
    <Button Text="Button 333333" RelativeLayout.XConstraint="{ConstraintExpression
            Type=RelativeToParent,Property=Width,Factor=.6666,Constant=0}"
            RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent,
            Property=Width,Factor=.3333,Constant=0}"/>
</RelativeLayout>
</code>```

StackLayout:

```<code><StackLayout Orientation="Horizontal">
    <Button x:Name="button1" Text="Button 1"/>
    <Button Text="Button 222" WidthRequest="{Binding Path=Width, Source={x:Reference button1}}"/>
    <Button Text="Button 333333" WidthRequest="{Binding Path=Width, Source={x:Reference button1}}"/>
</StackLayout>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Anyone know how to position 3 buttons in StackLayout with equal width?  I have it working with Grid with

<Grid x:Name="MyGrid" Grid.Row="0" BindingContext="{x:Reference Name=Button1}"  HeightRequest="{Binding Width}">

I would like to find a way to show 3 buttons on same line  with same width equally without a Grid
For example all 3 buttons of equal length fitting across horizontally in StackLayout

[   Button 1   ]  [   Button 222   ]  [   Button 333333   ]

Body:
RelativeLayout:

<RelativeLayout HorizontalOptions="FillAndExpand">
    <Button Text="Button 1" RelativeLayout.XConstraint="{ConstraintExpression
            Type=RelativeToParent,Property=Width,Factor=.0000,Constant=0}"
            RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent,
            Property=Width,Factor=.3333,Constant=0}"/>
    <Button Text="Button 222" RelativeLayout.XConstraint="{ConstraintExpression
            Type=RelativeToParent,Property=Width,Factor=.3333,Constant=0}"
            RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent,
            Property=Width,Factor=.3333,Constant=0}"/>
    <Button Text="Button 333333" RelativeLayout.XConstraint="{ConstraintExpression
            Type=RelativeToParent,Property=Width,Factor=.6666,Constant=0}"
            RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent,
            Property=Width,Factor=.3333,Constant=0}"/>
</RelativeLayout>

StackLayout:

<StackLayout Orientation="Horizontal">
    <Button x:Name="button1" Text="Button 1"/>
    <Button Text="Button 222" WidthRequest="{Binding Path=Width, Source={x:Reference button1}}"/>
    <Button Text="Button 333333" WidthRequest="{Binding Path=Width, Source={x:Reference button1}}"/>
</StackLayout>


答: If I understand your question correctly, you would like to know how to build a neural-network-based classifier that maps text strings of arbitrary length to a 0 or a 1. There are multiple ways to achieve this. One way is to map each text string to a constant-sized vector using some featurization scheme (e.g., bag of words), and then feed these constant-sized vectors as input to your model. Another way is to use a sequence model like an RNN, padding your examples to a constant length (e.g., the length of the longest string).</p>

Title: tensorflow for classifying unknown input

Body:
I have been working on convolutional neural networks for image classification.  I've gotten an assignment where they gave me a text file containing input/output pairs, where the output is either 0 or 1, while input is generated values.
For example

0   X225006700,X773579,X236398246,X773545,X51769735,X315340932,X44092910,Y2,Y1132,Y2257,Y2793,Y1080,Y1555,Y1222,Y2072,Y1238,Y1791,Y1705,Y2684,Y1725,Y2641,Y2640,Y1690,Y1367,Y1353,Y2949,Y2557,Y1478,Y2024,Y1486,Y1522,Y1456,Y1940,Y977,Y1468,Z4,Z15

0   X123474229,X51578397,X40087170,X236398246,X367227997,X62716661,X127972441,X344420902,X40087738,X103413307,X51769735,X524837224,X37875376,X79805718,X773579,X44092910,Y1353,Y1555,Y2849,Y1478,Y2321,Y1238,Y1486,Y3143,Y1522,Y2817,Y1702,Y1940,Z4,Z15,Z29

1   X62716661,X277692318,Y1367,Y3269,Y1353,Y2949,Y2814,Y2267,Y2257,Y3250,Y3021,Y2557,Y3232,Y1080,Y1555,Y1222,Y2849,Y1478,Y2321,Y3145,Y1486,Y3143,Y1791,Y1522,Y2817,Y1702,Y1456,Y2641,Y2640,Y1940,Y1468,Y2170,Y3585,Z4,Z15,Z27

Now with normal neural networks, I always need (at least that I know of) specified input numbers in order to create input layer (e.g. 10x10 pixel images, or cat/dog/bird etc). Is it possible to do the same for these random inputs?

If not, is there any recommended method for solving this problem? (I'm thinking using matlab since there appears to be xyz values in the data)


问:
Deselect the text in a NSTextField
Is there an easy way to deselect an NSTextField after pressing enter?

答:
First you will need to make your view controller the delegate of your text field. Then you override NSControl instance method controlTextDidEndEditing(_:), get your textfield current editor selected range
and from the main thread set it back to your textfield:

```<code>import Cocoa

class ViewController: NSViewController, NSTextFieldDelegate {
    @IBOutlet weak var textField: NSTextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }
    override func controlTextDidEndEditing(_ obj: Notification) {
        if let selectedRange = textField.currentEditor()?.selectedRange {
            DispatchQueue.main.async {
                self.textField.currentEditor()?.selectedRange = selectedRange
            }
        }
    }
}
</code>```

Title: Deselect the text in a NSTextField

Body:
First you will need to make your view controller the delegate of your text field. Then you override NSControl instance method controlTextDidEndEditing(_:), get your textfield current editor selected range
and from the main thread set it back to your textfield:

import Cocoa

class ViewController: NSViewController, NSTextFieldDelegate {
    @IBOutlet weak var textField: NSTextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        textField.delegate = self
    }
    override func controlTextDidEndEditing(_ obj: Notification) {
        if let selectedRange = textField.currentEditor()?.selectedRange {
            DispatchQueue.main.async {
                self.textField.currentEditor()?.selectedRange = selectedRange
            }
        }
    }
}


问:
OAuth.io with Github Enterprise
It seems like OAuth.io providers (all here: https://github.com/oauth-io/oauthd/tree/master/providers) are static files; and the thing with GitHub Enterprise is, the domain name is not github.com, but something different for each customer. Is there a way to make OAuth.io work with a provider whose domain name is always different, such as for the GitHub Enterprise use case?</p>

答:
Take a look at Shopify provider implementation which have the same problematic

https://github.com/oauth-io/oauthd/blob/master/providers/shopify/conf.json

We added a parameter shop

```<code>"parameters": {
   "shop": "string",
   ...
}
</code>```

This parameter is configurable in OAuth.io when setting API keys:

and this parameter can be reused in URLs:

```<code>`"url": "https://{shop}.myshopify.com",`
</code>```

Feel free to make a pull request if you have the time to add Github Enterprise to the list of OAuth providers !

Title: OAuth.io with Github Enterprise

Body:
Take a look at Shopify provider implementation which have the same problematic

https://github.com/oauth-io/oauthd/blob/master/providers/shopify/conf.json

We added a parameter shop

"parameters": {
   "shop": "string",
   ...
}

This parameter is configurable in OAuth.io when setting API keys:

and this parameter can be reused in URLs:

`"url": "https://{shop}.myshopify.com",`

Feel free to make a pull request if you have the time to add Github Enterprise to the list of OAuth providers !


问:
jQuery intercept slideToggle()
I'm doing a very simple slideToggle() here:

```<code>            $("#loginBtn").click(function(){
                $("#login").slideToggle();
                return false;
            });
</code>```

What i'm asking is, how do i intercept the slideToggle, so once the user clicks #loginBtn and #login slides down, they can either click #loginBtn again to slide it up OR they can click another element to slide #login up? But only the #loginBtn slides down the #login?

Thanks

答:
Bind some slideUp goodness to your 'other elements'?

```<code>$(".otherButtons").click(function() {
    $("#login").slideUp();
    return false;
});
</code>```

ContentLicense: CC BY-SA 2.5

Title: jQuery intercept slideToggle()

Body:
I'm doing a very simple slideToggle() here:

            $("#loginBtn").click(function(){
                $("#login").slideToggle();
                return false;
            });

What i'm asking is, how do i intercept the slideToggle, so once the user clicks #loginBtn and #login slides down, they can either click #loginBtn again to slide it up OR they can click another element to slide #login up? But only the #loginBtn slides down the #login?

Thanks

Body:
Bind some slideUp goodness to your 'other elements'?

$(".otherButtons").click(function() {
    $("#login").slideUp();
    return false;
});


问:
Enable Incoming Telnet connection on Mac OS 10.12
I could not find anything other than the command below but this did not work either. I need to allow an incoming telnet connection from a PC app to connect to my Mac. I know SSH is better but I have to have telnet to connect to my Mac OS. Does anyone know?

This is the only thing I found to allow the incoming telnet connection, however this did not work.

sudo launchctl load -w /System/Library/LaunchDaemons/telnet.plist

-Seth

答:
According to apple support :
You can’t use Telnet to log in to your Mac.

see here


问:
Are there any git commands that will explicitly destroy a commit?
Does Git ever truly destroy commits or just orphan them? I am aware that the git garbage collector will remove orphaned commits when run with git gc on whatever interval is set in git config. Are there any other cases that will delete a commit?

答:
Git may truly destroy some object, including an unreferenced commit, eventually; but it may not.  Read through to the end for why this is so.

The most direct control is available through git prune, git repack, and git prune-packed.  Running git gc runs all of these, and more.  The main problem with assuming that git prune, or even git gc --prune=now, will do the trick is that objects that are now unreachable may have been packed.

In general, you should expire reflogs first, since removing expired reflog entries may cause objects to become unreachable.  Using git gc gets all of this done in the right order, in a relatively safe manner: expire reflogs first, then prune (carefully), then repack, then prune-packed.  The prune step tosses loose objects that are unreferenced and themselves expired.1  After that, the other steps repack older objects that are in use, and delete objects that have just become packed.

This sequence of events is why we need git repack -d, or even -ad, followed by git prune-packed.  However, if some packs are marked with a .keep file, those packs will remain, and if they contain otherwise-unreferenced objects, those objects will remain as well.

1Since multiple Git commands may be run in parallel, it's wise to provide a grace period during which unreferenced objects live on, in case they are about to become referenced.  Note that it is git gc that inserts the default 14 day grace period; git prune defaults to --expire=now rather than --expire=2.weeks.ago.  This gives Git commands 336 hours to get their work done and cement references: e.g., git commit runs git write-tree followed by git commit-tree, and this tree and commit are unreferenced until git commit also updates the current branch name.  Normally, this whole process takes just a few milliseconds, so 336 hours should be plenty of time.


问:
Adding an image to gridlayout changes entire layout
I'm new to Android development so I may have missed a simple problem, but i'm trying to create a login screen with an image at the top. I have my layout exactly the way I want, except when I add the image the entire layout changes. I've added a textbox with the same grid settings as imageview (LoginPageCharity) to test and it works perfectly with the textbox, but then i change imageview to visible and the textbox (textView1) to gone, my whole setup changes. Can you explain to me why this is and if possible how to remedy this? Thank you in advance! Here are the two layouts and my code.

```<code><?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:p1="http://schemas.android.com/apk/res/android"
    p1:layout_width="match_parent"
    p1:layout_height="match_parent"
    p1:id="@+id/gridLayout1"
    p1:columnCount="6"
    p1:rowCount="10"
    p1:alignmentMode="alignBounds"
    p1:orientation="horizontal"
    p1:columnOrderPreserved="true"
    p1:rowOrderPreserved="true"
    p1:useDefaultMargins="false">
    <TextView
        p1:id="@+id/textView1"
        p1:enabled="true"
        p1:visibility="visible"
        p1:layout_column="0"
        p1:layout_columnSpan="6"
        p1:layout_columnWeight="6"
        p1:layout_row="0"
        p1:layout_rowSpan="3"
        p1:layout_rowWeight="3" />
    <TextView
        p1:id="@+id/textView2"
        p1:layout_column="0"
        p1:layout_columnSpan="1"
        p1:layout_columnWeight="1"
        p1:layout_row="5"
        p1:layout_rowSpan="1"
        p1:layout_rowWeight="0.3"
        p1:visibility="visible" />
    <Button
        p1:text="Log In"
        p1:id="@+id/button1"
        p1:layout_column="1"
        p1:layout_columnSpan="1"
        p1:layout_columnWeight="1"
        p1:layout_row="5"
        p1:layout_rowSpan="1"
        p1:layout_rowWeight="0.3" />
    <TextView
        p1:id="@+id/textView3"
        p1:layout_column="2"
        p1:layout_columnSpan="1"
        p1:layout_columnWeight="1"
        p1:layout_row="5"
        p1:layout_rowSpan="1"
        p1:layout_rowWeight="0.3" />
    <Button
        p1:text="Create Account"
        p1:id="@+id/button2"
        p1:layout_column="4"
        p1:layout_columnSpan="1"
        p1:layout_columnWeight="1"
        p1:layout_row="5"
        p1:layout_rowSpan="1"
        p1:layout_rowWeight="0.3" />
    <TextView
        p1:id="@+id/textView4"
        p1:layout_column="5"
        p1:layout_columnSpan="1"
        p1:layout_columnWeight="1"
        p1:layout_row="5"
        p1:layout_rowSpan="1"
        p1:layout_rowWeight="0.3" />
    <TextView
        p1:id="@+id/textView5"
        p1:layout_column="0"
        p1:layout_columnSpan="6"
        p1:layout_columnWeight="6"
        p1:layout_row="6"
        p1:layout_rowSpan="4"
        p1:layout_rowWeight="4" />
    <EditText
        p1:inputType="textPassword"
        p1:id="@+id/editText1"
        p1:layout_column="1"
        p1:layout_columnSpan="4"
        p1:layout_columnWeight="4"
        p1:layout_row="4"
        p1:layout_rowSpan="1"
        p1:text="Password" />
    <EditText
        p1:inputType="textEmailAddress"
        p1:id="@+id/editText2"
        p1:layout_column="1"
        p1:layout_columnSpan="4"
        p1:layout_columnWeight="4"
        p1:layout_row="3"
        p1:layout_rowSpan="1"
        p1:text="Username" />
    <ImageView
        p1:src="@drawable/redcross2"
        p1:id="@+id/LoginPageCharity"
        p1:layout_column="0"
        p1:layout_columnSpan="6"
        p1:layout_columnWeight="6"
        p1:layout_row="0"
        p1:layout_rowSpan="3"
        p1:layout_rowWeight="3"
        p1:scaleType="centerInside"
        p1:adjustViewBounds="true"
        p1:visibility="gone"
        p1:cropToPadding="true" />
</GridLayout>
</code>```

答:
What I did was:

Take out textView1 as it is only "for bug testing".

Take out the visibility attribute of the ImageView as you always want to show it.

Take out the weight attributes of the ImageView.

And this is the result:

Is this what you wanted?

Body:
I'm new to Android development so I may have missed a simple problem, but i'm trying to create a login screen with an image at the top. I have my layout exactly the way I want, except when I add the image the entire layout changes. I've added a textbox with the same grid settings as imageview (LoginPageCharity) to test and it works perfectly with the textbox, but then i change imageview to visible and the textbox (textView1) to gone, my whole setup changes. Can you explain to me why this is and if possible how to remedy this? Thank you in advance! Here are the two layouts and my code.

<?xml version="1.0" encoding="utf-8"?>
<GridLayout xmlns:p1="http://schemas.android.com/apk/res/android"
    p1:layout_width="match_parent"
    p1:layout_height="match_parent"
    p1:id="@+id/gridLayout1"
    p1:columnCount="6"
    p1:rowCount="10"
    p1:alignmentMode="alignBounds"
    p1:orientation="horizontal"
    p1:columnOrderPreserved="true"
    p1:rowOrderPreserved="true"
    p1:useDefaultMargins="false">
    <TextView
        p1:id="@+id/textView1"
        p1:enabled="true"
        p1:visibility="visible"
        p1:layout_column="0"
        p1:layout_columnSpan="6"
        p1:layout_columnWeight="6"
        p1:layout_row="0"
        p1:layout_rowSpan="3"
        p1:layout_rowWeight="3" />
    <TextView
        p1:id="@+id/textView2"
        p1:layout_column="0"
        p1:layout_columnSpan="1"
        p1:layout_columnWeight="1"
        p1:layout_row="5"
        p1:layout_rowSpan="1"
        p1:layout_rowWeight="0.3"
        p1:visibility="visible" />
    <Button
        p1:text="Log In"
        p1:id="@+id/button1"
        p1:layout_column="1"
        p1:layout_columnSpan="1"
        p1:layout_columnWeight="1"
        p1:layout_row="5"
        p1:layout_rowSpan="1"
        p1:layout_rowWeight="0.3" />
    <TextView
        p1:id="@+id/textView3"
        p1:layout_column="2"
        p1:layout_columnSpan="1"
        p1:layout_columnWeight="1"
        p1:layout_row="5"
        p1:layout_rowSpan="1"
        p1:layout_rowWeight="0.3" />
    <Button
        p1:text="Create Account"
        p1:id="@+id/button2"
        p1:layout_column="4"
        p1:layout_columnSpan="1"
        p1:layout_columnWeight="1"
        p1:layout_row="5"
        p1:layout_rowSpan="1"
        p1:layout_rowWeight="0.3" />
    <TextView
        p1:id="@+id/textView4"
        p1:layout_column="5"
        p1:layout_columnSpan="1"
        p1:layout_columnWeight="1"
        p1:layout_row="5"
        p1:layout_rowSpan="1"
        p1:layout_rowWeight="0.3" />
    <TextView
        p1:id="@+id/textView5"
        p1:layout_column="0"
        p1:layout_columnSpan="6"
        p1:layout_columnWeight="6"
        p1:layout_row="6"
        p1:layout_rowSpan="4"
        p1:layout_rowWeight="4" />
    <EditText
        p1:inputType="textPassword"
        p1:id="@+id/editText1"
        p1:layout_column="1"
        p1:layout_columnSpan="4"
        p1:layout_columnWeight="4"
        p1:layout_row="4"
        p1:layout_rowSpan="1"
        p1:text="Password" />
    <EditText
        p1:inputType="textEmailAddress"
        p1:id="@+id/editText2"
        p1:layout_column="1"
        p1:layout_columnSpan="4"
        p1:layout_columnWeight="4"
        p1:layout_row="3"
        p1:layout_rowSpan="1"
        p1:text="Username" />
    <ImageView
        p1:src="@drawable/redcross2"
        p1:id="@+id/LoginPageCharity"
        p1:layout_column="0"
        p1:layout_columnSpan="6"
        p1:layout_columnWeight="6"
        p1:layout_row="0"
        p1:layout_rowSpan="3"
        p1:layout_rowWeight="3"
        p1:scaleType="centerInside"
        p1:adjustViewBounds="true"
        p1:visibility="gone"
        p1:cropToPadding="true" />
</GridLayout>


问:
How scikit learn implements the output layer

In scikit learn, how many neurons are in the output layer? As stated here, you can only specify the hidden layer size and their neurons but nothing about the output layer, thus I am not sure how scikit learn implements the output layer.

Does it make sense to use softmax activation function for output layer having only a single neuron?

答:
Test:

Setup:

```<code>In [227]: %paste
clf = MLPClassifier()

m = 10**3
n = 64

df = pd.DataFrame(np.random.randint(100, size=(m, n))).add_prefix('x') \
       .assign(y=np.random.choice([-1,1], m))

X_train, X_test, y_train, y_test = \
    train_test_split(df.drop('y',1), df['y'], test_size=0.2, random_state=33)

clf.fit(X_train, y_train)
## -- End pasted text --
Out[227]:
MLPClassifier(activation='relu', alpha=0.0001, batch_size='auto', beta_1=0.9,
       beta_2=0.999, early_stopping=False, epsilon=1e-08,
       hidden_layer_sizes=(100,), learning_rate='constant',
       learning_rate_init=0.001, max_iter=200, momentum=0.9,
       nesterovs_momentum=True, power_t=0.5, random_state=None,
       shuffle=True, solver='adam', tol=0.0001, validation_fraction=0.1,
       verbose=False, warm_start=False)
</code>```

Number of outputs:

```<code>In [229]: clf.n_outputs_
Out[229]: 1
</code>```

Number of layers:

```<code>In [228]: clf.n_layers_
Out[228]: 3
</code>```

The number of iterations the solver has ran:

```<code>In [230]: clf.n_iter_
Out[230]: 60
</code>```

Here is an excerpt of the source code where the activation function for the output layer will be chosen:

```<code>    # Output for regression
    if not is_classifier(self):
        self.out_activation_ = 'identity'
    # Output for multi class
    elif self._label_binarizer.y_type_ == 'multiclass':
        self.out_activation_ = 'softmax'
    # Output for binary class and multi-label
    else:
        self.out_activation_ = 'logistic'
</code>```

UPDATE:  MLPClassifier binarizes (in a one-vs-all fashion) labels internaly, so logistic regression should work well also with labels that are differ from [0,1]:

```<code>    if not incremental:
        self._label_binarizer = LabelBinarizer()
        self._label_binarizer.fit(y)
        self.classes_ = self._label_binarizer.classes_
</code>```

Body:
Test:

Setup:

In [227]: %paste
clf = MLPClassifier()

m = 10**3
n = 64

df = pd.DataFrame(np.random.randint(100, size=(m, n))).add_prefix('x') \
       .assign(y=np.random.choice([-1,1], m))

X_train, X_test, y_train, y_test = \
    train_test_split(df.drop('y',1), df['y'], test_size=0.2, random_state=33)

clf.fit(X_train, y_train)
## -- End pasted text --
Out[227]:
MLPClassifier(activation='relu', alpha=0.0001, batch_size='auto', beta_1=0.9,
       beta_2=0.999, early_stopping=False, epsilon=1e-08,
       hidden_layer_sizes=(100,), learning_rate='constant',
       learning_rate_init=0.001, max_iter=200, momentum=0.9,
       nesterovs_momentum=True, power_t=0.5, random_state=None,
       shuffle=True, solver='adam', tol=0.0001, validation_fraction=0.1,
       verbose=False, warm_start=False)

Number of outputs:

In [229]: clf.n_outputs_
Out[229]: 1

Number of layers:

In [228]: clf.n_layers_
Out[228]: 3

The number of iterations the solver has ran:

In [230]: clf.n_iter_
Out[230]: 60

Here is an excerpt of the source code where the activation function for the output layer will be chosen:

    # Output for regression
    if not is_classifier(self):
        self.out_activation_ = 'identity'
    # Output for multi class
    elif self._label_binarizer.y_type_ == 'multiclass':
        self.out_activation_ = 'softmax'
    # Output for binary class and multi-label
    else:
        self.out_activation_ = 'logistic'

UPDATE:  MLPClassifier binarizes (in a one-vs-all fashion) labels internaly, so logistic regression should work well also with labels that are differ from [0,1]:

    if not incremental:
        self._label_binarizer = LabelBinarizer()
        self._label_binarizer.fit(y)
        self.classes_ = self._label_binarizer.classes_


问:
Make Properties readonly in addContentItemPropertiesPane
I am looking for a modified add document view using AddContentItemDialog .

i manage to set parent folder , Intro Text , title and documents properties with script adapter in Work Details

```<code>    try {
         var parentFolder = self.case.getCaseFolder();
         self.addContentItemDialog = new AddContentItemDialog();

         self.addContentItemDialog.setDefaultContentClass(prefix+"_Dumy01");

         aspect.after(self.addContentItemDialog.addContentItemPropertiesPane, "onCompleteRendering", function() {

             console.log("aspect.after(self.addContentItemDialog");

              self.addContentItemDialog.addContentItemPropertiesPane.setPropertyValue("Test_1", "123");
              self.addContentItemDialog.addContentItemPropertiesPane.setPropertyValue("DocumentTitle", "YYYYYY");

              self.addContentItemDialog.set("title","This is New Add Doc Event");
              self.addContentItemDialog.setIntroText("New Msg Can Be Set In this Tab");
         }, true);
         console.log("XX");
         self.addContentItemDialog.show(parentFolder.repository,parentFolder,true,false, null, null, false, null);
}catch (exception) {
     console.log("exception" + exception);
}
</code>```

Now I am looking to make few Properties readonly after setting them up from script.

maybe like ,

```<code>self.addContentItemDialog.addContentItemPropertiesPane(Property).set("readOnly", "true");
</code>```

Thanks

答:
If I got your question correctly, I am led to believe that your best option in that case would be EDS, it would be easier and more flexible. please check the link below from ECM community blog, giving a simple example that you can leverage to achieve similar results

Sample External Data Service for IBM Case Manager by Dave Hanson

Also, Please check the ICM 5.2 Redbook, which referenced Chapter 16 of the previous edition of the ICM Redbook (the ICM 5.1 edition): Download

Finally, This link from developerWorks is a straight forward white paper with sample code that I found very useful back when I started using EDS for case manager: Download

Body:
I am looking for a modified add document view using AddContentItemDialog .

i manage to set parent folder , Intro Text , title and documents properties with script adapter in Work Details

    try {
         var parentFolder = self.case.getCaseFolder();
         self.addContentItemDialog = new AddContentItemDialog();

         self.addContentItemDialog.setDefaultContentClass(prefix+"_Dumy01");

         aspect.after(self.addContentItemDialog.addContentItemPropertiesPane, "onCompleteRendering", function() {

             console.log("aspect.after(self.addContentItemDialog");

              self.addContentItemDialog.addContentItemPropertiesPane.setPropertyValue("Test_1", "123");
              self.addContentItemDialog.addContentItemPropertiesPane.setPropertyValue("DocumentTitle", "YYYYYY");

              self.addContentItemDialog.set("title","This is New Add Doc Event");
              self.addContentItemDialog.setIntroText("New Msg Can Be Set In this Tab");
         }, true);
         console.log("XX");
         self.addContentItemDialog.show(parentFolder.repository,parentFolder,true,false, null, null, false, null);
}catch (exception) {
     console.log("exception" + exception);
}

Now I am looking to make few Properties readonly after setting them up from script.

maybe like ,

self.addContentItemDialog.addContentItemPropertiesPane(Property).set("readOnly", "true");

Thanks


问:
Inserting a javascript variable that is a mathjax command into a html page that outputs formatted maths
I have a variable in javascript that depends on an input from

```<code><input type="text" id="inputfunction" value="">
<button onclick="example">Example</button>
<p id="input"></p>
</code>```

In the js script I have used document.getElementById("input").innerHTML = inpt; to place this variable on the page.

The variable comes out similar to say '3x+8' however I want this to be formatted with mathjax. To facilitate this I currently have

```<code>  <head>
        <link rel='stylesheet' type='text/css' href='Stylesheet1.css'/>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">
        <script type="text/javascript" async
                src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.2/MathJax.js?config=TeX-MML-AM_CHTML">
        </script>
    </head>
</code>```

in my html document, however this doesn't output the variable formatted. I have tried using document.getElementById("input").innerHTML = \\(inpt\\); or placing $$ on either side of it however this just puts it on the page as \(inpt\) or $$inpt$$. Is there any way to have it so that mathjax formats the variable?

答:
Okay so I eventually found it and it was a really easy fix. I just added

MathJax.Hub.Typeset();

at the end of the function and that makes MathJax look back over the page to format anything else. Apparently you shouldn't call this directly though because MathJax may be performing other actions so to counteract any issues this may cause you can write

MathJax.Hub.Queue(["Typeset",MathJax.Hub]);

which makes sure MathJax has finished all other processes before typesetting the page stop any synchronisation errors.

Body:
I have a variable in javascript that depends on an input from

<input type="text" id="inputfunction" value="">
<button onclick="example">Example</button>

In the js script I have used document.getElementById("input").innerHTML = inpt; to place this variable on the page.

The variable comes out similar to say '3x+8' however I want this to be formatted with mathjax. To facilitate this I currently have

        <link rel='stylesheet' type='text/css' href='Stylesheet1.css'/>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width">

in my html document, however this doesn't output the variable formatted. I have tried using document.getElementById("input").innerHTML = \\(inpt\\); or placing $$ on either side of it however this just puts it on the page as \(inpt\) or $$inpt$$. Is there any way to have it so that mathjax formats the variable?


问:
Does Webpack tree shaking with dead code elimination work on node_modules?
Considering this Webpack 3.8.1 config.

```<code>// common
module.exports = {
        context: path.resolve(__dirname, './src'),
        entry: [
            'whatwg-fetch',
            './index'
        ],
        output: {
            path: path.resolve(__dirname, 'build/assets'),
            publicPath: '/assets/',
            filename: 'main.js'
        },
        plugins: [
            new CleanWebpackPlugin(['build']),
        ],
        module: {
            rules: [{
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                }
            }, {
                test: /\.(scss|css)$/,
                use: [{
                    loader: 'style-loader'
                }, {
                    loader: 'css-loader'
                }, {
                    loader: 'sass-loader'
                }],
            }, {
                test: /\.(png|jpg|gif|woff2|woff)$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 8192
                        }
                    }
                ]
            }]
        }
    };

//prod
module.exports = merge(common, {
    plugins: [
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify('production')
        }),
        new UglifyJSPlugin()
    ],
    devtool: 'none'
});
</code>```

and this Babel 6.26.0 config

```<code>{
  "presets": [
    [
      "env",
      {
        "modules": false,
        "targets": {
          "browsers": [
            ">1%"
          ]
        }
      }
    ], [
      "react"
    ]
  ],
  "plugins": [
    "transform-class-properties",
    "transform-export-extensions",
    "transform-object-rest-spread",
    "react-hot-loader/babel"
  ]
}
</code>```

I was expecting that tree shaking alongside with dead code elimination of UglifyJS should work in a way that enables me to write named imports from index.es.js modules, for example Material-UI-Icons and unused ones get removed from the bundle.

```<code>import {Menu} from 'material-ui-icons';
</code>```

This library does indeed reexport ES6 modules defined in package.json as "module": "index.es.js".

Yet my bundle size increased by 0.5MB after importing single icon. When I changed it to

```<code>import Menu from 'material-ui-icons/Menu;
</code>```

bundle size got reduced again with only this icon imported.

Is there something wrong in my configuration, or do I missunderstand how tree shaking works and does not apply to this scenario?

答:
So after some additional digging, I found the cause / temporary solution / solution. Basically, because ES Modules can have side-effects, Webpack nor UglifyJS can safely (per specification) remove unused re-exports typically found in index.es.js or similar "module" entry point.

For now, there are some ways around it. Either you can manually import only necessary modules, or you can use babel-plugin-direct-import.

Good news is that Webpack 4 adds support for pure modules thru the side-effects flag. When library author marks it as pure, tree shaking and minification will work as expected. I also recommend to read this nice summary about ESM specification support in NodeJS.

For now I would recommend to manually work thru your bundle using this wonderfull visualizer and decide how to handle each large dependency on its own.

Body:
Considering this Webpack 3.8.1 config.

// common
module.exports = {
        context: path.resolve(__dirname, './src'),
        entry: [
            'whatwg-fetch',
            './index'
        ],
        output: {
            path: path.resolve(__dirname, 'build/assets'),
            publicPath: '/assets/',
            filename: 'main.js'
        },
        plugins: [
            new CleanWebpackPlugin(['build']),
        ],
        module: {
            rules: [{
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                }
            }, {
                test: /\.(scss|css)$/,
                use: [{
                    loader: 'style-loader'
                }, {
                    loader: 'css-loader'
                }, {
                    loader: 'sass-loader'
                }],
            }, {
                test: /\.(png|jpg|gif|woff2|woff)$/,
                use: [
                    {
                        loader: 'url-loader',
                        options: {
                            limit: 8192
                        }
                    }
                ]
            }]
        }
    };

//prod
module.exports = merge(common, {
    plugins: [
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify('production')
        }),
        new UglifyJSPlugin()
    ],
    devtool: 'none'
});

and this Babel 6.26.0 config

{
  "presets": [
    [
      "env",
      {
        "modules": false,
        "targets": {
          "browsers": [
            ">1%"
          ]
        }
      }
    ], [
      "react"
    ]
  ],
  "plugins": [
    "transform-class-properties",
    "transform-export-extensions",
    "transform-object-rest-spread",
    "react-hot-loader/babel"
  ]
}

I was expecting that tree shaking alongside with dead code elimination of UglifyJS should work in a way that enables me to write named imports from index.es.js modules, for example Material-UI-Icons and unused ones get removed from the bundle.

import {Menu} from 'material-ui-icons';

This library does indeed reexport ES6 modules defined in package.json as "module": "index.es.js".

Yet my bundle size increased by 0.5MB after importing single icon. When I changed it to

import Menu from 'material-ui-icons/Menu;

bundle size got reduced again with only this icon imported.

Is there something wrong in my configuration, or do I missunderstand how tree shaking works and does not apply to this scenario?


问:
Google Sheets Scripts onOpen(e) Add New Row to Sheet
I have a custom function that inserts a new row under the last non-empty row in a sheet and copies a specific range to this new row. This functions works fine when I trigger it with a custom menu item.

However, when I add this custom function to the onOpen(e) trigger the script does not work. I troubleshooted and added an alert in my function - the alert triggers so therefore the function is read in the right place.

Please advise how to have my script work onOpen?

Here's my code for my custom function:

```<code>function onOpen(e) {
  autoAddRow();
}

function autoAddRow() {
  var updateFrequency = 3;
  var lRow = getLastRow('A');
  var lDate = all.getRange(lRow,1).getValue();
  var today = new Date();

  Date.prototype.addDays = function(days) {
    var dat = new Date(this.valueOf());
    dat.setDate(dat.getDate() + days);
    return dat;
  }
  var newDate = lDate.addDays(updateFrequency);

  if (today >= newDate) {
    var lCol = all.getLastColumn();
    var src = all.getRange(3,1,1,6);
    var dest = all.getRange(lRow+1,1,1,6);

    if(lRow > 20) {
      all.insertRowsAfter(lRow, 1);
    }

    src.copyTo(dest, {contentsOnly:false});
  } else {
    return;
  }
}
</code>```

答:
So if your example isn't psuedo-code, it wont work. It dies at the second line of your function because the method isn't attached to a class.

Here is my version of your code (I'm using the first sheet in the spreadsheet app).

```<code>function autoAddRow() {
  var updateFrequency = 3

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var data = sheet.getDataRange();
  var lRow = data.getLastRow();
  var lDate = new Date(sheet.getRange(lRow,1).getValue());
  var today = new Date();
  Logger.log(lDate);
  Logger.log(lRow);
  Logger.log(sheet.getRange(lRow,1).getValue());

  Date.prototype.addDays = function(days) {
    var dat = new Date(this.valueOf());
    dat.setDate(dat.getDate() + days);
    return dat;
  }
  var newDate = lDate.addDays(updateFrequency);

  if (today >= newDate) {
    Logger.log("passed if statement");
    var lCol = data.getLastColumn();
    var src = sheet.getRange(lRow,1,1,6);
    var dest = sheet.getRange(lRow+1,1,1,6);

    if(lRow > 20) {
      all.insertRowsAfter(lRow, 1);
    }

    src.copyTo(dest, {contentsOnly:false});
  } else {
    return;
  }
}
</code>```

The main problems were in the calls to the range and data. They didn't go anywhere. The variable lDate needed to be parsed as a date (in my version, my date column was the second column, not the first *edit: changed the code quick to point to your original date cell *end edit), but you have to call the range and get the value to parse it, but after fixing the class issues with regards to getting your data, the rest fell into place. It even works if you put in in the onOpen.

Update: I didn't fix the line

```<code>if(lRow > 20) {
  all.insertRowsAfter(lRow, 1);
}
</code>```

In fact, I'm not really sure what it does because it looks like it just inserts the row after the last row, which the rest of the function does. But the code 'as is' will break after 20 lines unless you change 'all' to reference the worksheet object.

Body:
I have a custom function that inserts a new row under the last non-empty row in a sheet and copies a specific range to this new row. This functions works fine when I trigger it with a custom menu item.

However, when I add this custom function to the onOpen(e) trigger the script does not work. I troubleshooted and added an alert in my function - the alert triggers so therefore the function is read in the right place.

Please advise how to have my script work onOpen?

Here's my code for my custom function:

function onOpen(e) {
  autoAddRow();
}

function autoAddRow() {
  var updateFrequency = 3;
  var lRow = getLastRow('A');
  var lDate = all.getRange(lRow,1).getValue();
  var today = new Date();

  Date.prototype.addDays = function(days) {
    var dat = new Date(this.valueOf());
    dat.setDate(dat.getDate() + days);
    return dat;
  }
  var newDate = lDate.addDays(updateFrequency);

  if (today >= newDate) {
    var lCol = all.getLastColumn();
    var src = all.getRange(3,1,1,6);
    var dest = all.getRange(lRow+1,1,1,6);

    if(lRow > 20) {
      all.insertRowsAfter(lRow, 1);
    }

    src.copyTo(dest, {contentsOnly:false});
  } else {
    return;
  }
}

Body:
So if your example isn't psuedo-code, it wont work. It dies at the second line of your function because the method isn't attached to a class.

Here is my version of your code (I'm using the first sheet in the spreadsheet app).

function autoAddRow() {
  var updateFrequency = 3

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheets()[0];
  var data = sheet.getDataRange();
  var lRow = data.getLastRow();
  var lDate = new Date(sheet.getRange(lRow,1).getValue());
  var today = new Date();
  Logger.log(lDate);
  Logger.log(lRow);
  Logger.log(sheet.getRange(lRow,1).getValue());

  Date.prototype.addDays = function(days) {
    var dat = new Date(this.valueOf());
    dat.setDate(dat.getDate() + days);
    return dat;
  }
  var newDate = lDate.addDays(updateFrequency);

  if (today >= newDate) {
    Logger.log("passed if statement");
    var lCol = data.getLastColumn();
    var src = sheet.getRange(lRow,1,1,6);
    var dest = sheet.getRange(lRow+1,1,1,6);

    if(lRow > 20) {
      all.insertRowsAfter(lRow, 1);
    }

    src.copyTo(dest, {contentsOnly:false});
  } else {
    return;
  }
}

The main problems were in the calls to the range and data. They didn't go anywhere. The variable lDate needed to be parsed as a date (in my version, my date column was the second column, not the first *edit: changed the code quick to point to your original date cell *end edit), but you have to call the range and get the value to parse it, but after fixing the class issues with regards to getting your data, the rest fell into place. It even works if you put in in the onOpen.

Update: I didn't fix the line

if(lRow > 20) {
  all.insertRowsAfter(lRow, 1);
}

In fact, I'm not really sure what it does because it looks like it just inserts the row after the last row, which the rest of the function does. But the code 'as is' will break after 20 lines unless you change 'all' to reference the worksheet object.


问:
Second linked stylesheet has no effect
I'm having problems linking a second stylesheet to my HTML document, and cannot find the (hopefully painfully obvious) problem.

I'm linking stylesheets in the head thus:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<link rel="stylesheet" href="assets/css/global.css" type="text/css" media="all" title="Global styles" charset="utf-8">
<link rel="stylesheet" href="assets/css/ie.css" type="text/css" media="all" title="IE Overrides" charset="utf-8">
</code>```

The problem is, the seconds stylesheet has no effect what so ever. Reversing their order proves this as well.

For testing, I put in a rule in the second stylesheet to make the body background red, even tried adding !important, but to no avail.

```<code>/* Global CSS */
body {
    background-color: #fff;
}

/* IE CSS */
body {
    background-color: #f00 !important;
}
</code>```

Firebug net panel shows that both stylesheets do load, and the style panel shows me the styles in both of them, but the rules in the latter just don't do squat.

This has left me baffled, since it is very, very basic stuff, which I've previously done successfully hundreds and hundreds of times.

答:
In my case, I had moved working CSS rulesets from a PHP string in the page source to an external CSS file:

From:

```<code>    $headCss.=
    '   <style type="text/css">
            #containBrainForHire
            {   background:url(\'/graphics/BrainForHire.png\');
                display:table;
                height:300px;
                margin:0 auto;
                width:525px;
            }
        </style>
    ';
</code>```

To:

```<code>    #containBrainForHire
    {   background:url(\'/graphics/BrainForHire.png\');
        display:table;
        height:300px;
        margin:0 auto;
        width:525px;
    }
</code>```

NOTHING in the new CSS file worked until I fixed the background definition: The backslashes needed to escape the single quotes in the PHP string are invalid in the CSS file.

Corrected CSS file contents:

```<code>    #containBrainForHire
    {   background:url('/graphics/BrainForHire.png');
        display:table;
        height:300px;
        margin:0 auto;
        width:525px;
    }
</code>```

There were no errors reported in the error console, just nothing in the new CSS file had any effect on the page's display.  (So much for useful debugging tools...)

I hope this saves someone else the time that it took me to recognize the problem.

Title: Second linked stylesheet has no effect

Body:
I'm having problems linking a second stylesheet to my HTML document, and cannot find the (hopefully painfully obvious) problem.

I'm linking stylesheets in the head thus:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">

<link rel="stylesheet" href="assets/css/global.css" type="text/css" media="all" title="Global styles" charset="utf-8">
<link rel="stylesheet" href="assets/css/ie.css" type="text/css" media="all" title="IE Overrides" charset="utf-8">

The problem is, the seconds stylesheet has no effect what so ever. Reversing their order proves this as well.

For testing, I put in a rule in the second stylesheet to make the body background red, even tried adding !important, but to no avail.

/* Global CSS */
body {
    background-color: #fff;
}

/* IE CSS */
body {
    background-color: #f00 !important;
}

Firebug net panel shows that both stylesheets do load, and the style panel shows me the styles in both of them, but the rules in the latter just don't do squat.

This has left me baffled, since it is very, very basic stuff, which I've previously done successfully hundreds and hundreds of times.

Body:
In my case, I had moved working CSS rulesets from a PHP string in the page source to an external CSS file:

From:

    $headCss.=
    '   <style type="text/css">
            #containBrainForHire
            {   background:url(\'/graphics/BrainForHire.png\');
                display:table;
                height:300px;
                margin:0 auto;
                width:525px;
            }
        </style>
    ';

To:

    #containBrainForHire
    {   background:url(\'/graphics/BrainForHire.png\');
        display:table;
        height:300px;
        margin:0 auto;
        width:525px;
    }

NOTHING in the new CSS file worked until I fixed the background definition: The backslashes needed to escape the single quotes in the PHP string are invalid in the CSS file.

Corrected CSS file contents:

    #containBrainForHire
    {   background:url('/graphics/BrainForHire.png');
        display:table;
        height:300px;
        margin:0 auto;
        width:525px;
    }

There were no errors reported in the error console, just nothing in the new CSS file had any effect on the page's display.  (So much for useful debugging tools...)

I hope this saves someone else the time that it took me to recognize the problem.


问:
Is there a way of removing pixels in an image that have less than two neighbors using opencv?
After performing a bunch of preprocessing steps, I have this image. I'd like to remove the tiny islands of noise from within the image. What I've noticed is that these noisy pixels are directly connected to less than two pixels in their neighborhood. Is there a way of extracting just the logo and the letters "PUSH TO OPEN" without the noisy pixels?

I've already tried basic morphological operations such as erosion (cv2.erode) and opening to no avail.

I apologize if I've not made any part of my question clear as I'm a beginner at opencv. Any help is appreciated!

答: I'm not sure, but it looks like salt-and-pepper noise. You can remove it using smoothing filter such as median filter in your preprocessing step. Oh since you're new to OpenCV, you might want to look at OpenCV tutorial.</p>


问:
HTML generator?
LESS is very cool. I always wondered if there are any good html generators that allow me to write a form more easily or do other things. Is there something somewhat similar but for html?</p>

答:
Tried Haml?

From its website, this Haml code:

```<code>#profile
  .left.column
    #date= print_date
    #address= current_user.address
  .right.column
    #email= current_user.email
    #bio= current_user.bio
</code>```

gets converted into this HTML.

```<code><div id="profile">
  <div class="left column">
    <div id="date"><%= print_date %></div>
    <div id="address"><%= current_user.address %></div>
  </div>
  <div class="right column">
    <div id="email"><%= current_user.email %></div>
    <div id="bio"><%= current_user.bio %></div>
  </div>
</div>
</code>```

If you like Haml, then you might also like Sass, which is Haml for CSS. Actually, Haml comes with Sass. You can still use LESS if you like.

Title: HTML generator?

Body:
Tried Haml?

From its website, this Haml code:

#profile
  .left.column
    #date= print_date
    #address= current_user.address
  .right.column
    #email= current_user.email
    #bio= current_user.bio

gets converted into this HTML.

<div id="profile">
  <div class="left column">
    <div id="date"><%= print_date %></div>
    <div id="address"><%= current_user.address %></div>
  </div>
  <div class="right column">
    <div id="email"><%= current_user.email %></div>
    <div id="bio"><%= current_user.bio %></div>
  </div>
</div>

If you like Haml, then you might also like Sass, which is Haml for CSS. Actually, Haml comes with Sass. You can still use LESS if you like.


问:
Ambiguous method call. Both findViewById (int) in AppCompactActivity and Activity
I refer this link
Error : Ambiguous method call. Both findViewById (int) in AppCompactActivity and Activity
to solve but there is no import android.app.Activity and also if I convert my import android.support.v7.app.AppCompatActivity into android.app.Activity then the error goes but I want to use AppCompatActivity.

I also update all libraries in SDK and also invalidate and restart but nothing works.

why this error occurs and how to solve this?

答: If you recently updated your project to API 26, try doing invalidate caches/restart, then re-sync gradle.</p>


问:
Pandas groupby and aggregation output should include all the original columns (including the ones not aggregated on)
I have the following data frame and want to:

Group records by month

Sum QTY_SOLDand NET_AMT of each unique UPC_ID(per month)

Include the rest of the columns as well in the resulting dataframe

The way I thought I can do this is 1st: create a month column to aggregate the D_DATES, then sum QTY_SOLD by UPC_ID.

Script:

```<code># Convert date to date time object
df['D_DATE'] = pd.to_datetime(df['D_DATE'])

# Create aggregated months column
df['month'] = df['D_DATE'].apply(dt.date.strftime, args=('%Y.%m',))

# Group by month and sum up quantity sold by UPC_ID
df = df.groupby(['month', 'UPC_ID'])['QTY_SOLD'].sum()
</code>```

Current data frame:

```<code>UPC_ID | UPC_DSC | D_DATE | QTY_SOLD | NET_AMT
----------------------------------------------
111      desc1    2/26/2017   2         10 (2 x $5)
222      desc2    2/26/2017   3         15
333      desc3    2/26/2017   1         4
111      desc1    3/1/2017    1         5
111      desc1    3/3/2017    4         20
</code>```

Desired Output:

```<code>MONTH | UPC_ID | QTY_SOLD | NET_AMT | UPC_DSC
----------------------------------------------
2017-2      111     2         10       etc...
2017-2      222     3         15
2017-2      333     1         4
2017-3      111     5         25
</code>```

Actual Output:

```<code>MONTH | UPC_ID
----------------------------------------------
2017-2      111     2
            222     3
            333     1
2017-3      111     5
...
</code>```

Questions:

How do I include the month for each row?

How do I include the rest of the columns of the dataframe?

How do also sum NET_AMT in addition to QTY_SOLD?

答:
agg with a dict of functions

Create a dict of functions and pass it to agg. You'll also need as_index=False to prevent the group columns from becoming the index in your output.

```<code>f = {'NET_AMT': 'sum', 'QTY_SOLD': 'sum', 'UPC_DSC': 'first'}
df.groupby(['month', 'UPC_ID'], as_index=False).agg(f)

     month  UPC_ID UPC_DSC  NET_AMT  QTY_SOLD
0  2017.02     111   desc1       10         2
1  2017.02     222   desc2       15         3
2  2017.02     333   desc3        4         1
3  2017.03     111   desc1       25         5
</code>```

Blanket sum

Just call sum without any column names. This handles the numeric columns. For UPC_DSC, you'll need to handle it separately.

```<code>g = df.groupby(['month', 'UPC_ID'])
i = g.sum()
j = g[['UPC_DSC']].first()

pd.concat([i, j], 1).reset_index()

     month  UPC_ID  QTY_SOLD  NET_AMT UPC_DSC
0  2017.02     111         2       10   desc1
1  2017.02     222         3       15   desc2
2  2017.02     333         1        4   desc3
3  2017.03     111         5       25   desc1
</code>```

Body:
I have the following data frame and want to:

Group records by month

Sum QTY_SOLDand NET_AMT of each unique UPC_ID(per month)

Include the rest of the columns as well in the resulting dataframe

The way I thought I can do this is 1st: create a month column to aggregate the D_DATES, then sum QTY_SOLD by UPC_ID.

Script:

# Convert date to date time object
df['D_DATE'] = pd.to_datetime(df['D_DATE'])

# Create aggregated months column
df['month'] = df['D_DATE'].apply(dt.date.strftime, args=('%Y.%m',))

# Group by month and sum up quantity sold by UPC_ID
df = df.groupby(['month', 'UPC_ID'])['QTY_SOLD'].sum()

Current data frame:

UPC_ID | UPC_DSC | D_DATE | QTY_SOLD | NET_AMT
----------------------------------------------
111      desc1    2/26/2017   2         10 (2 x $5)
222      desc2    2/26/2017   3         15
333      desc3    2/26/2017   1         4
111      desc1    3/1/2017    1         5
111      desc1    3/3/2017    4         20

Desired Output:

MONTH | UPC_ID | QTY_SOLD | NET_AMT | UPC_DSC
----------------------------------------------
2017-2      111     2         10       etc...
2017-2      222     3         15
2017-2      333     1         4
2017-3      111     5         25

Actual Output:

MONTH | UPC_ID
----------------------------------------------
2017-2      111     2
            222     3
            333     1
2017-3      111     5
...

Questions:

How do I include the month for each row?

How do I include the rest of the columns of the dataframe?

How do also sum NET_AMT in addition to QTY_SOLD?

Body:
agg with a dict of functions

Create a dict of functions and pass it to agg. You'll also need as_index=False to prevent the group columns from becoming the index in your output.

f = {'NET_AMT': 'sum', 'QTY_SOLD': 'sum', 'UPC_DSC': 'first'}
df.groupby(['month', 'UPC_ID'], as_index=False).agg(f)

     month  UPC_ID UPC_DSC  NET_AMT  QTY_SOLD
0  2017.02     111   desc1       10         2
1  2017.02     222   desc2       15         3
2  2017.02     333   desc3        4         1
3  2017.03     111   desc1       25         5

Blanket sum

Just call sum without any column names. This handles the numeric columns. For UPC_DSC, you'll need to handle it separately.

g = df.groupby(['month', 'UPC_ID'])
i = g.sum()
j = g[['UPC_DSC']].first()

pd.concat([i, j], 1).reset_index()

     month  UPC_ID  QTY_SOLD  NET_AMT UPC_DSC
0  2017.02     111         2       10   desc1
1  2017.02     222         3       15   desc2
2  2017.02     333         1        4   desc3
3  2017.03     111         5       25   desc1


问:
Determine lowest value in row & column of an NxN array
I have a list of lists that I have used to store the distances between objects.

The table looks something like this:

```<code>+----------+----------+----------+----------+----------+
|          | Object_A | Object_B | Object_C | Object_D |
+----------+----------+----------+----------+----------+
| Entity_E |     2    |     3    |     6    |     1    |
+----------+----------+----------+----------+----------+
| Entity_F |     3    |     4    |     7    |     2    |
+----------+----------+----------+----------+----------+
| Entity_G |     9    |     1    |     2    |     3    |
+----------+----------+----------+----------+----------+
</code>```

The numbers represent the distance between the row & column header.

This was calculated roughly as follows:

```<code>entites = [Entity_E, Entity_F, Entity_G]
objects = [Object_A, Object_B, Object_C, Obhect_D]
distances = []

for object in objects:

    distanceEntry = []

    for entity in entities:
        distance = getDistance(entity, object)

        distanceEntry.append(distance)
    distances.append(distanceEntry)
</code>```

This gave me roughly the information in the table above.

What I am looking to do is basically find the closest object to each entity (or vice versa). Each object or entity can only be matched with one other, and it should be based on proximity.

They way I have done this right now is by simply ordering the nested lists by size in distances (in the full code I have a way of determining which object is associated with each distance).

So, in doing that I would create the following associations:

```<code>+----------+----------+----------+
| Entity   |  Object  | Distance |
+----------+----------+----------+
| Entity_E | Object_D |     1    |
+----------+----------+----------+
| Entity_F | Object_D |     2    |
+----------+----------+----------+
| Entity_G | Object_B |     1    |
+----------+----------+----------+
</code>```

This is incorrect because it associates Object_D twice.

The association should be:

```<code>+----------+----------+----------+
| Entity   |  Object  | Distance |
+----------+----------+----------+
| Entity_E | Object_D |     1    |
+----------+----------+----------+
| Entity_F | Object_A |     3    |
+----------+----------+----------+
| Entity_G | Object_B |     1    |
+----------+----------+----------+
</code>```

This is where I am struggling - I can't figure out the best way to code logic for this.

Since Entity_E is closer to Object_D, it should get the association. So, for Entity_F, I need to take the second closest.

I was thinking about doing something where I record which Objects have already been assigned, or trying to do something where I match the min values in each column first, but they all seem to run into problems.

Is there a matrix operation or some kind of matrix math I could use to do this calculation?

Any advice would be much appreciated!

Edit - Added Full Code:

```<code># Create an array that stores the distances between each label and symbol. Only calculate the distance for label that
# are "in front" of the symbol.
# Example Table:
# +---------------+--------------+--------------+--------------+--------------+
# |               |    Label_1   |    Label_2   |    Label_3   |    Label_4   |
# +---------------+--------------+--------------+--------------+--------------+
# | Measurement_1 |       2      |       3      | Not_in_front |       1      |
# +---------------+--------------+--------------+--------------+--------------+
# | Measurement_2 |       3      |       4      |       1      | Not_in_front |
# +---------------+--------------+--------------+--------------+--------------+
# | Measurement_3 | Not_in_front | Not_in_front |       2      |       1      |
# +---------------+--------------+--------------+--------------+--------------+

# Data Structures:
# measurementsDictionary = {['Type', 'Handle', 'X-Coord', 'Y-Coord', 'Z-Coord', 'Rotation', 'True Strike']}
# dipsDictionary = {['Handle', 'Text', 'Unit', 'X-Coord', 'Y-Coord', 'Z-Coord']}

#The two functions below grab the information from a csv-like file.
measurementsDictionary = getMeasurementsInformationFromFile()
dipsDictionary = getDipsInformationFromFile()

exportHeaders = [" "]
exportArray = []

for measurementSymbol in measurementsDictionary:

    measurementEntry = measurementsDictionary[measurementSymbol]
    measurementCoord = [measurementEntry[2], measurementEntry[3]]
    measurementDistance = []
    measurementDistance.append(measurementEntry[1])
    measurementCartesianAngle = getCartesianAngle(measurementEntry[6])
    measurementLineEquation = generateLineEquation(measurementCoord,measurementCartesianAngle)

    for dip in dipsDictionary:
        dipEntry = dipsDictionary[dip]
        dipCoord = [dipEntry[3],dipEntry[4]]
        isPointInFrontOfLineTest = isPointInFrontOfLine(measurementCartesianAngle, measurementLineEquation, dipCoord)

        if isPointInFrontOfLineTest == 1:
            measurementSymbolDistance = calculateDistance(measurementCoord, dipCoord)
            # string = dipEntry[0] +":" + str(measurementSymbolDistance)
            # measurementDistance.append(string)
            measurementDistance.append(measurementSymbolDistance)
        elif isPointInFrontOfLineTest == 0:
            string = ""
            measurementDistance.append(string)
    exportArray.append(measurementDistance)

for dip in dipsDictionary:
    dipEntry = dipsDictionary[dip]
    exportHeaders.append(dipEntry[0])

exportedArray = [exportHeaders] + exportArray
export = np.array(exportedArray)
np.savetxt("exportArray2.csv", export, fmt='%5s', delimiter=",")
print(exportHeaders)
</code>```

答:
I made some code to solve a similar problem to this a while back for PE345. I'm going to use my own array for this:

```<code>[[1,2,3],
 [4,5,6],
 [7,8,9]]
</code>```

What you wanna do is get the cost of choosing a particular element. Do this by finding the cost of choosing a row, adding the cost of choosing a column, then subtracting the cost of choosing the element itself. So in my array, the cost of choosing element [0][0] is (1+2+3)+(1+4+7)-3*(1). I summed row 0, summed column 0, then subtracted out the element itself.

Now you have the cost of choosing each element. Find the element with the highest cost. That will be the lowest value in the grid. Choose it and make sure no other value in the row or column can be chosen. Repeat until a value in every row and column has been chosen.

Here's the source code from my project. Note that it finds the highest values, not the lowest.

```<code>from random import randint
from itertools import permutations
def make_a_grid(radius=5,min_val=0,max_val=999):
  """Return a radius x radius grid of numbers ranging from min_val to max_val.
    Syntax: make_a_grid(radius=5,min_val=0,max_val=999
  """
  return [[randint(min_val,max_val) for i in xrange(radius)] for j in xrange(radius)]
def print_grid(grid,rjustify = 4):
  """Print a n x m grid of numbers, justified to a column.
    Syntax: print_grid(grid,rjustify = 4)
  """
  for i in grid:
    outstr = ''
    for j in i:
      outstr += str(j).rjust(rjustify)
    print outstr
def brute_search(grid):
  """Brute force a grid to find the maximum sum in the grid."""
  mx_sum = 0
  for r in permutations('01234',5):
    mx_sum = max(sum([grid[i][int(r[i])] for i in xrange(5)]),mx_sum)
  return mx_sum
def choose(initial_grid,row,col):
  """Return a grid with a given row and column zeroed except where they intersect."""
  grid = [sub[:] for sub in initial_grid] #We don't actually want to alter initial_grid
  Special_value = grid[row][col] #This is where they intersect.
  grid[row] = [0]*len(grid[row]) #zeroes the row.
  for i in xrange(len(grid)):
    grid[i][col] = 0
    grid[row][col] = Special_value
  print_grid(grid)
  return grid
def smart_solve(grid):
  """Solve the grid intelligently.
  """
  rowsum = [sum(row) for row in grid] #This is the cost for any element in a given row.
  print rowsum
  colsum = [sum(row) for row in [[grid[i][j] for i in xrange(len(grid))] for j in xrange(len(grid[0]))]] #Cost for any element in a given column
  print colsum,"\n"
  total_cost = [map(lambda x: x+i,rowsum) for i in colsum] #This adds rowsum and colsum together, yielding the cost at a given index.
  print_grid(total_cost,5)
  print "\n"
  #Total_cost has a flaw: It counts the value of the cell twice. It needs to count it -1 times, subtracting its value from the cost.
  for i in xrange(len(grid)): #For each row
    for j in xrange(len(grid[0])): #For each column
      total_cost[i][j] -= 3*(grid[i][j]) #Remove the double addition and subtract once.
  ###Can I turn ^^that into a list comprehension? Maybe use zip or something?###
  print_grid(total_cost,5)
  return total_cost
def min_value(grid):
  """return the minimum value (And it's index) such that value>0.
     Output is: (value,col,row)"""
  min_value,row,col = grid[0][0],0,0
  for row_index,check_row in enumerate(grid):
    for col_index,check_val in enumerate(check_row):
      #print "Min_value: %d\n Check_Val: %d\n Location: (%d,%d)"%(min_value,check_val,row_index,col_index)
      if min_value>check_val>0:
        min_value = check_val
        row = row_index
        col = col_index
  return (min_value,row,col)
</code>```

Body:
I have a list of lists that I have used to store the distances between objects.

The table looks something like this:

+----------+----------+----------+----------+----------+
|          | Object_A | Object_B | Object_C | Object_D |
+----------+----------+----------+----------+----------+
| Entity_E |     2    |     3    |     6    |     1    |
+----------+----------+----------+----------+----------+
| Entity_F |     3    |     4    |     7    |     2    |
+----------+----------+----------+----------+----------+
| Entity_G |     9    |     1    |     2    |     3    |
+----------+----------+----------+----------+----------+

The numbers represent the distance between the row & column header.

This was calculated roughly as follows:

entites = [Entity_E, Entity_F, Entity_G]
objects = [Object_A, Object_B, Object_C, Obhect_D]
distances = []

for object in objects:

    distanceEntry = []

    for entity in entities:
        distance = getDistance(entity, object)

        distanceEntry.append(distance)
    distances.append(distanceEntry)

This gave me roughly the information in the table above.

What I am looking to do is basically find the closest object to each entity (or vice versa). Each object or entity can only be matched with one other, and it should be based on proximity.

They way I have done this right now is by simply ordering the nested lists by size in distances (in the full code I have a way of determining which object is associated with each distance).

So, in doing that I would create the following associations:

+----------+----------+----------+
| Entity   |  Object  | Distance |
+----------+----------+----------+
| Entity_E | Object_D |     1    |
+----------+----------+----------+
| Entity_F | Object_D |     2    |
+----------+----------+----------+
| Entity_G | Object_B |     1    |
+----------+----------+----------+

This is incorrect because it associates Object_D twice.

The association should be:

+----------+----------+----------+
| Entity   |  Object  | Distance |
+----------+----------+----------+
| Entity_E | Object_D |     1    |
+----------+----------+----------+
| Entity_F | Object_A |     3    |
+----------+----------+----------+
| Entity_G | Object_B |     1    |
+----------+----------+----------+

This is where I am struggling - I can't figure out the best way to code logic for this.

Since Entity_E is closer to Object_D, it should get the association. So, for Entity_F, I need to take the second closest.

I was thinking about doing something where I record which Objects have already been assigned, or trying to do something where I match the min values in each column first, but they all seem to run into problems.

Is there a matrix operation or some kind of matrix math I could use to do this calculation?

Any advice would be much appreciated!

Edit - Added Full Code:

# Create an array that stores the distances between each label and symbol. Only calculate the distance for label that
# are "in front" of the symbol.
# Example Table:
# +---------------+--------------+--------------+--------------+--------------+
# |               |    Label_1   |    Label_2   |    Label_3   |    Label_4   |
# +---------------+--------------+--------------+--------------+--------------+
# | Measurement_1 |       2      |       3      | Not_in_front |       1      |
# +---------------+--------------+--------------+--------------+--------------+
# | Measurement_2 |       3      |       4      |       1      | Not_in_front |
# +---------------+--------------+--------------+--------------+--------------+
# | Measurement_3 | Not_in_front | Not_in_front |       2      |       1      |
# +---------------+--------------+--------------+--------------+--------------+

# Data Structures:
# measurementsDictionary = {['Type', 'Handle', 'X-Coord', 'Y-Coord', 'Z-Coord', 'Rotation', 'True Strike']}
# dipsDictionary = {['Handle', 'Text', 'Unit', 'X-Coord', 'Y-Coord', 'Z-Coord']}

#The two functions below grab the information from a csv-like file.
measurementsDictionary = getMeasurementsInformationFromFile()
dipsDictionary = getDipsInformationFromFile()

exportHeaders = [" "]
exportArray = []

for measurementSymbol in measurementsDictionary:

    measurementEntry = measurementsDictionary[measurementSymbol]
    measurementCoord = [measurementEntry[2], measurementEntry[3]]
    measurementDistance = []
    measurementDistance.append(measurementEntry[1])
    measurementCartesianAngle = getCartesianAngle(measurementEntry[6])
    measurementLineEquation = generateLineEquation(measurementCoord,measurementCartesianAngle)

    for dip in dipsDictionary:
        dipEntry = dipsDictionary[dip]
        dipCoord = [dipEntry[3],dipEntry[4]]
        isPointInFrontOfLineTest = isPointInFrontOfLine(measurementCartesianAngle, measurementLineEquation, dipCoord)

        if isPointInFrontOfLineTest == 1:
            measurementSymbolDistance = calculateDistance(measurementCoord, dipCoord)
            # string = dipEntry[0] +":" + str(measurementSymbolDistance)
            # measurementDistance.append(string)
            measurementDistance.append(measurementSymbolDistance)
        elif isPointInFrontOfLineTest == 0:
            string = ""
            measurementDistance.append(string)
    exportArray.append(measurementDistance)

for dip in dipsDictionary:
    dipEntry = dipsDictionary[dip]
    exportHeaders.append(dipEntry[0])

exportedArray = [exportHeaders] + exportArray
export = np.array(exportedArray)
np.savetxt("exportArray2.csv", export, fmt='%5s', delimiter=",")
print(exportHeaders)

Body:
I made some code to solve a similar problem to this a while back for PE345. I'm going to use my own array for this:

[[1,2,3],
 [4,5,6],
 [7,8,9]]

What you wanna do is get the cost of choosing a particular element. Do this by finding the cost of choosing a row, adding the cost of choosing a column, then subtracting the cost of choosing the element itself. So in my array, the cost of choosing element [0][0] is (1+2+3)+(1+4+7)-3*(1). I summed row 0, summed column 0, then subtracted out the element itself.

Now you have the cost of choosing each element. Find the element with the highest cost. That will be the lowest value in the grid. Choose it and make sure no other value in the row or column can be chosen. Repeat until a value in every row and column has been chosen.

Here's the source code from my project. Note that it finds the highest values, not the lowest.

from random import randint
from itertools import permutations
def make_a_grid(radius=5,min_val=0,max_val=999):
  """Return a radius x radius grid of numbers ranging from min_val to max_val.
    Syntax: make_a_grid(radius=5,min_val=0,max_val=999
  """
  return [[randint(min_val,max_val) for i in xrange(radius)] for j in xrange(radius)]
def print_grid(grid,rjustify = 4):
  """Print a n x m grid of numbers, justified to a column.
    Syntax: print_grid(grid,rjustify = 4)
  """
  for i in grid:
    outstr = ''
    for j in i:
      outstr += str(j).rjust(rjustify)
    print outstr
def brute_search(grid):
  """Brute force a grid to find the maximum sum in the grid."""
  mx_sum = 0
  for r in permutations('01234',5):
    mx_sum = max(sum([grid[i][int(r[i])] for i in xrange(5)]),mx_sum)
  return mx_sum
def choose(initial_grid,row,col):
  """Return a grid with a given row and column zeroed except where they intersect."""
  grid = [sub[:] for sub in initial_grid] #We don't actually want to alter initial_grid
  Special_value = grid[row][col] #This is where they intersect.
  grid[row] = [0]*len(grid[row]) #zeroes the row.
  for i in xrange(len(grid)):
    grid[i][col] = 0
    grid[row][col] = Special_value
  print_grid(grid)
  return grid
def smart_solve(grid):
  """Solve the grid intelligently.
  """
  rowsum = [sum(row) for row in grid] #This is the cost for any element in a given row.
  print rowsum
  colsum = [sum(row) for row in [[grid[i][j] for i in xrange(len(grid))] for j in xrange(len(grid[0]))]] #Cost for any element in a given column
  print colsum,"\n"
  total_cost = [map(lambda x: x+i,rowsum) for i in colsum] #This adds rowsum and colsum together, yielding the cost at a given index.
  print_grid(total_cost,5)
  print "\n"
  #Total_cost has a flaw: It counts the value of the cell twice. It needs to count it -1 times, subtracting its value from the cost.
  for i in xrange(len(grid)): #For each row
    for j in xrange(len(grid[0])): #For each column
      total_cost[i][j] -= 3*(grid[i][j]) #Remove the double addition and subtract once.
  ###Can I turn ^^that into a list comprehension? Maybe use zip or something?###
  print_grid(total_cost,5)
  return total_cost
def min_value(grid):
  """return the minimum value (And it's index) such that value>0.
     Output is: (value,col,row)"""
  min_value,row,col = grid[0][0],0,0
  for row_index,check_row in enumerate(grid):
    for col_index,check_val in enumerate(check_row):
      #print "Min_value: %d\n Check_Val: %d\n Location: (%d,%d)"%(min_value,check_val,row_index,col_index)
      if min_value>check_val>0:
        min_value = check_val
        row = row_index
        col = col_index
  return (min_value,row,col)


问:
SPARQL Update: Underscore not allowed in language tag
I am trying to insert data into blazegraph using the 'Update' tab of blazegraph workbench. Below is a sample code snippet:

```<code>INSERT DATA
{
  ns:MyNode ns:hasValue "MyValue"@en_us
}
</code>```

I am specifying language tag with @ symbol. However, it throws following exception:

org.openrdf.query.MalformedQueryException: Lexical error at line 8,
  column 49.  Encountered: "u" (117), after : "_"

It seems that it does not allow an underscore as part of language tag. If try just with 'en' it works fine.

Why is that so? Is underscore a special character here? If so, what is the way to escape it?

答:
The syntax for language tags is defined by an RFC, now revised in RFC5646. Registration of language tags is controlled by IANA.

Subtags are separated by "-"; only A-Z,0-9 are legal in subtags.

When adopted for RDF syntaxes (N3, SPARQL, Turtle etc), the grammar pattern  adopted was a compromise syntax that weakly matches the RFC.  '@' [a-zA-Z]+ ('-' [a-zA-Z0-9]+)* without taking all the details. The subtag separator is "-". "_" is not allowed in a language tag.

Body:
I am trying to insert data into blazegraph using the 'Update' tab of blazegraph workbench. Below is a sample code snippet:

INSERT DATA
{
  ns:MyNode ns:hasValue "MyValue"@en_us
}

I am specifying language tag with @ symbol. However, it throws following exception:

org.openrdf.query.MalformedQueryException: Lexical error at line 8,
  column 49.  Encountered: "u" (117), after : "_"

It seems that it does not allow an underscore as part of language tag. If try just with 'en' it works fine.

Why is that so? Is underscore a special character here? If so, what is the way to escape it?


问:
ruby on rails - add end_time upon record creation
I'm trying to have a record with ends_at column which is suppose to have the created_at value with 5 minutes added to it for instance:

```<code>Class Post < ApplicationRecord
  after_create :set_end_time

  private
    def set_end_time
      self.ends_at = self.created_at + 5.minutes
    end
end
</code>```

this saves the ends_at column as a null in the database

答:
You fire after_create hook. It gets triggered after Rails calls SQL INSERT command. So you setup ends_at already when object was saved to the database and it will not be saved again. Object with initialized ends_at not going anywhere and then just get cleared from the memory.

Replace your hook with before_create and it should do the trick for you.

Body:
I'm trying to have a record with ends_at column which is suppose to have the created_at value with 5 minutes added to it for instance:

Class Post < ApplicationRecord
  after_create :set_end_time

  private
    def set_end_time
      self.ends_at = self.created_at + 5.minutes
    end
end

this saves the ends_at column as a null in the database


问:
Setting mobile user agent for iframe on desktop
I am attempting to use an iframe to preview the mobile version for a site that will be displayed on the desktop site. However the site that I am attempting to display does not use the screen size to activate the mobile version but rather a user agent. Will I be able to somehow make the iframe request the site based of a mobile user agent such as 'Mozilla/5.0 (Linux; U; Android 4.0.2; en-us; Galaxy Nexus Build/ICL53F) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30'?</p>

答:
Your question is marked with both Javascript and PHP tags, two quite different languages, one client-side, the other server-side, respectively. Changing the UserAgent string cannot be done with Javascript. It could be done with a HTTP header set by PHP running on a proxy server between your browser and the site that will load in the iFrame.

On the other hand, if you use node.js server-side, you may be able to set the userAgent header with Javascript (a related OS Q&A may help).


问:
PHP session_start cookie doesn't save session id
On my server i am starting a new session by calling a static class function.
The problem is that the session id is not being saved in the session cookie, furthermore it seems that no session cookie is being saved at the client (eg. chrome doesn't display a cookie for the website).
Printing out $_COOKIE results in array(0) { }. Same with $_SESSION.

Here is the static class function which starts a new session:

```<code><?php
class Session
{
    private function __construct() { }

    public static function sec_session_start()
    {
        $session_name = 'sec_session_id';
        $secure = TRUE;                     // https only
        $httponly = true;                   // javascript can't access session id

        $cookieParams = session_get_cookie_params();
        session_set_cookie_params($cookieParams['lifetime'],
            '/',
            'www.example-domain.de',
            $secure,
            $httponly);

        session_name($session_name);
        session_start();
        session_regenerate_id();
    }
}
?>
</code>```

And at the top of every page i am starting the session with

```<code>Session::sec_session_start();
</code>```

For example when i am at the login page of my website and print out var_dump($_COOKIE) it says array(0) { } instead of array(2) { ["PHPSESSID"]=> string(26) "..." ["sec_session_id"]=> string(26) "..." }.

The php ini looks as follows
php ini

答: You have have to have session_start as your first line before any session functions.

Body:
On my server i am starting a new session by calling a static class function.
The problem is that the session id is not being saved in the session cookie, furthermore it seems that no session cookie is being saved at the client (eg. chrome doesn't display a cookie for the website).
Printing out $_COOKIE results in array(0) { }. Same with $_SESSION.

Here is the static class function which starts a new session:

<?php
class Session
{
    private function __construct() { }

    public static function sec_session_start()
    {
        $session_name = 'sec_session_id';
        $secure = TRUE;                     // https only
        $httponly = true;                   // javascript can't access session id

        $cookieParams = session_get_cookie_params();
        session_set_cookie_params($cookieParams['lifetime'],
            '/',
            'www.example-domain.de',
            $secure,
            $httponly);

        session_name($session_name);
        session_start();
        session_regenerate_id();
    }
}
?>

And at the top of every page i am starting the session with

Session::sec_session_start();

For example when i am at the login page of my website and print out var_dump($_COOKIE) it says array(0) { } instead of array(2) { ["PHPSESSID"]=> string(26) "..." ["sec_session_id"]=> string(26) "..." }.

The php ini looks as follows
php ini


问:
CSS - Vertical line
I am trying to create an education timeline. There should be a vertical line (red) starting from behind the "graduation cap" and than going through all the timeline-post (green).

This is what I got so far:

.iconspace {
    position: relative;
    width: 40px;
    height: 40px;
    text-align: center;
    margin: 0 auto;
    border-radius: 50%;
    background-color: #25b5f1;
    z-index: 7;
}

.iconspace i {
    font-size: 18px;
    color: #FFFFFF;
    line-height: 40px;
}

.iconspace:after, .iconspace::after {
    content: "";
    display: block;
    position: absolute;
    top: 0;
    left: 49.8%;
    width: 3px;
    height: 100%;
    background-color: RED;
    z-index: 5;
}

.timeline-post {
  height: 100px;
  width: 200px;
  background-color: green;
  margin: 0 auto;
  margin-top: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>
<h3 class="entry-title" style="text-align: center;">EDUCATION</h3><span class="border"></span>
<div class="timeline">
<div class="iconspace"><i class="fa fa-graduation-cap"></i></div></div>

<div class="timeline-post">
Test 1
</div>

<div class="timeline-post">
Test 2
</div>

<div class="timeline-post">
Test 3
</div>
</div></code>```

答:
You need to apply the pseudo element to the container of timeline posts and not the icon, so you may do this instead :

You may change z-index value depending on your needs (above or below green elements)

.iconspace {
  position: relative;
  width: 40px;
  height: 40px;
  text-align: center;
  margin: 0 auto;
  border-radius: 50%;
  background-color: #25b5f1;
  z-index: 7;
}

.iconspace i {
  font-size: 18px;
  color: #FFFFFF;
  line-height: 40px;
}

.timeline {
  position: relative;
}

.timeline:before {
  content: "";
  display: block;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 49.8%;
  width: 3px;
  height: 100%;
  background-color: RED;
  z-index: -5;
}

.timeline-post {
  height: 100px;
  width: 200px;
  background-color: green;
  margin: 0 auto;
  margin-top: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" />
<h3 class="entry-title" style="text-align: center;">EDUCATION</h3><span class="border"></span>
<div class="timeline">
  <div class="iconspace"><i class="fa fa-graduation-cap"></i></div>

  <div class="timeline-post">
    Test 1
  </div>

  <div class="timeline-post">
    Test 2
  </div>

  <div class="timeline-post">
    Test 3
  </div>
</div></code>```

Title: CSS - Vertical line

Body:
I am trying to create an education timeline. There should be a vertical line (red) starting from behind the "graduation cap" and than going through all the timeline-post (green).

This is what I got so far:

.iconspace {
    position: relative;
    width: 40px;
    height: 40px;
    text-align: center;
    margin: 0 auto;
    border-radius: 50%;
    background-color: #25b5f1;
    z-index: 7;
}

.iconspace i {
    font-size: 18px;
    color: #FFFFFF;
    line-height: 40px;
}

.iconspace:after, .iconspace::after {
    content: "";
    display: block;
    position: absolute;
    top: 0;
    left: 49.8%;
    width: 3px;
    height: 100%;
    background-color: RED;
    z-index: 5;
}

.timeline-post {
  height: 100px;
  width: 200px;
  background-color: green;
  margin: 0 auto;
  margin-top: 20px;
}

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"/>

EDUCATION

Test 1

Test 2

Test 3

Body:
You need to apply the pseudo element to the container of timeline posts and not the icon, so you may do this instead :

You may change z-index value depending on your needs (above or below green elements)

.iconspace {
  position: relative;
  width: 40px;
  height: 40px;
  text-align: center;
  margin: 0 auto;
  border-radius: 50%;
  background-color: #25b5f1;
  z-index: 7;
}

.iconspace i {
  font-size: 18px;
  color: #FFFFFF;
  line-height: 40px;
}

.timeline {
  position: relative;
}

.timeline:before {
  content: "";
  display: block;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 49.8%;
  width: 3px;
  height: 100%;
  background-color: RED;
  z-index: -5;
}

.timeline-post {
  height: 100px;
  width: 200px;
  background-color: green;
  margin: 0 auto;
  margin-top: 20px;
}

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" />
<h3 class="entry-title" style="text-align: center;">EDUCATION</h3><span class="border"></span>
<div class="timeline">
  <div class="iconspace"><i class="fa fa-graduation-cap"></i></div>

  <div class="timeline-post">
    Test 1
  </div>

  <div class="timeline-post">
    Test 2
  </div>

  <div class="timeline-post">
    Test 3
  </div>
</div>


问:
How to push notification on android device in node js using GCM?
I want to push notification in android devices through node js using node</p>

答:
I think the best way is to use Firebase Cloud Message (FCM), you can send notifications to your Android and iOS devices over an fcm_token provided by Firebase SDK. They provide a super easy node js SDK. It's Google solution and simple to use.

https://firebase.google.com/docs/cloud-messaging/?refresh=1

If you dont like Google, this is an other 100% free option that allow you to do the same job, One Signal.

https://onesignal.com/


问:
Scss Structure for Angular applications and components
I am getting errors when serving my app with ng serve. The scss file within footer, references the styles.css from assets. However, some of the scss files reference svgs from icons using relative path such as background(../icons/icon.svg) from assets/styles/styles.css. When this file is imported by footer.component.scss the pathing breaks. It is trying to reference src/app/layouts/icons/icon.svg which does not exist in that folder, but exists under src/assets/icons.

```<code>├── app
|   ├── layouts
|       |──footer
|           ├── footer.component.ts
|           ├── footer.component.scss
|
├── assets
|    ├── icons
|    ├── css
|        |──pallette.scss
|        |──_helpers.scss
|        |──styles.scss
</code>```

The goal I am trying to achieve is have a modular application with components that can be shared for other projects etc. There may be a totally different structure and approach to be doing this, and I am open to all suggestions.

答:
../icons/icon.svg isn't the right path.

Try with /assets/icons/icon.svg and it should work.

Body:
I am getting errors when serving my app with ng serve. The scss file within footer, references the styles.css from assets. However, some of the scss files reference svgs from icons using relative path such as background(../icons/icon.svg) from assets/styles/styles.css. When this file is imported by footer.component.scss the pathing breaks. It is trying to reference src/app/layouts/icons/icon.svg which does not exist in that folder, but exists under src/assets/icons.

├── app
|   ├── layouts
|       |──footer
|           ├── footer.component.ts
|           ├── footer.component.scss
|
├── assets
|    ├── icons
|    ├── css
|        |──pallette.scss
|        |──_helpers.scss
|        |──styles.scss

The goal I am trying to achieve is have a modular application with components that can be shared for other projects etc. There may be a totally different structure and approach to be doing this, and I am open to all suggestions.