问:
How to Authorize AD users with .Net Core
I'm trying to stop requests on a route using the Authorize annotation, but I can't get it to work with Active Directory. Had anyone got this working yet?

[HttpGet]
[Authorize(Roles = "DOMAIN\\Group A")]
[Route("/")] // GET: /
public IActionResult Index()
{
    return View();
}
```

<p>Note: I've also tried <code>Authorize(Roles = @"DOMAIN\\Group A")</code></p>

<p>Just to give some background, I'm running Windows, Visual Studio Pro 2015 (Update 3)</p>

<p>Heres a bit from my project.json file:</p>

```"dependencies": {
    "Microsoft.AspNetCore.Authorization": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.Extensions.Configuration.CommandLine": "1.0.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "Swashbuckle.SwaggerGen": "6.0.0-beta901",
    "Swashbuckle.SwaggerUi": "6.0.0-beta901"
  }
```

答:
If you just wish to allow / deny users as per standard MVC, and use IIS reverse proxy to Kestrel, then you can add a web.config and add

<system.webServer>
  <security>
    <authorization>
      <remove users="*" roles="" verbs="" />
      <add accessType="Allow" roles="my AD User Group" />
      <add accessType="Allow" roles="uk\myUsercode" />
    </authorization>
  </security>
</system.webServer>
```

Body:
I'm trying to stop requests on a route using the Authorize annotation, but I can't get it to work with Active Directory. Had anyone got this working yet?

[HttpGet]
[Authorize(Roles = "DOMAIN\\Group A")]
[Route("/")] // GET: /
public IActionResult Index()
{
    return View();
}

Note: I've also tried Authorize(Roles = @"DOMAIN\\Group A")

Just to give some background, I'm running Windows, Visual Studio Pro 2015 (Update 3)

Heres a bit from my project.json file:

"dependencies": {
    "Microsoft.AspNetCore.Authorization": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
    "Microsoft.Extensions.Configuration.CommandLine": "1.0.0",
    "Microsoft.Extensions.Configuration.EnvironmentVariables": "1.0.0",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.Extensions.Logging.Debug": "1.0.0",
    "Microsoft.Extensions.Options.ConfigurationExtensions": "1.0.0",
    "Microsoft.NETCore.App": {
      "version": "1.0.0",
      "type": "platform"
    },
    "Swashbuckle.SwaggerGen": "6.0.0-beta901",
    "Swashbuckle.SwaggerUi": "6.0.0-beta901"
  }


来源: stackexchange

问:
Swift - How to know when the file is successfully download from url using FileManager.default.copyItem
I have a scenario in which i have to download a zip file from url and once download completed i need to unzip it in async fashion. Problem here is FileManager.default.copyItem  takes sometime therefore i cannot immediately unzip the file. below is code for downloading zip file :

```<code>   func saveZipFile(url: URL, directory: String) -> Void {
        let request = URLRequest(url: url)

        let task = URLSession.shared.downloadTask(with: request) { (tempLocalUrl, response, error) in
            if let tempLocalUrl = tempLocalUrl, error == nil {
                // Success
                if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                    print("Successfully downloaded. Status code: \(statusCode)")
                }

                do {
                   try FileManager.default.copyItem(at: tempLocalUrl as URL, to: FileChecker().getPathURL(filename: url.lastPathComponent, directory: directory))

                    print("sucessfully downloaded the zip file ...........")
                    //unziping it
                    //self.unzipFile(url: url, directory: directory)

                } catch (let writeError) {
                        print("Error creating a file  : \(writeError)")
                }

            } else {
                print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
            }
        }
        task.resume()
    }
</code>```

Being a beginner i want to know is there is any callback available in swift which can tell me the file is downloaded and is available for unzipping. I am using SSZipArchive library for unzipping the file.

below is code for unzipping it using

```<code>   SSZipArchive.unzipFile(atPath: path, toDestination: destinationpath)
</code>```

答:
URLSession works with two kinds of callback mechanisms:

Completion handler - this is what your code is using

URLSession delegates

To answer your question specifically, the completion handler that you have written in the code above will be invoked when the download is completed. Alternatively, if you want to do the same in a delegate method, the code should be something like this:

```<code>import Foundation
import Dispatch //you won't need this in your app

public class DownloadTask : NSObject {

    var currDownload: Int64 = -1

    func download(urlString: String) {
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config, delegate: self,   delegateQueue: nil)

        let url = URL(string: urlString)
        let task = session.downloadTask(with: url!)
        task.resume()
    }
}

extension DownloadTask : URLSessionDownloadDelegate {

    //this delegate method is called everytime a block of data is received
    public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64,
                       totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) -> Void {
        let percentage = (Double(totalBytesWritten)/Double(totalBytesExpectedToWrite)) * 100
        if Int64(percentage) != currDownload  {
            print("\(Int(percentage))%")
            currDownload = Int64(percentage)
        }
    }

    //this delegate method is called when the download completes
    public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        //You can copy the file or unzip it using `location`
        print("\nFinished download at \(location.absoluteString)!")
    }

}

let e = DownloadTask()
e.download(urlString: "https://swift.org/LICENSE.txt")
dispatchMain() //you won't need this in your app
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a scenario in which i have to download a zip file from url and once download completed i need to unzip it in async fashion. Problem here is FileManager.default.copyItem  takes sometime therefore i cannot immediately unzip the file. below is code for downloading zip file :

   func saveZipFile(url: URL, directory: String) -> Void {
        let request = URLRequest(url: url)

        let task = URLSession.shared.downloadTask(with: request) { (tempLocalUrl, response, error) in
            if let tempLocalUrl = tempLocalUrl, error == nil {
                // Success
                if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                    print("Successfully downloaded. Status code: \(statusCode)")
                }

                do {
                   try FileManager.default.copyItem(at: tempLocalUrl as URL, to: FileChecker().getPathURL(filename: url.lastPathComponent, directory: directory))

                    print("sucessfully downloaded the zip file ...........")
                    //unziping it
                    //self.unzipFile(url: url, directory: directory)

                } catch (let writeError) {
                        print("Error creating a file  : \(writeError)")
                }

            } else {
                print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
            }
        }
        task.resume()
    }

Being a beginner i want to know is there is any callback available in swift which can tell me the file is downloaded and is available for unzipping. I am using SSZipArchive library for unzipping the file.

below is code for unzipping it using

   SSZipArchive.unzipFile(atPath: path, toDestination: destinationpath)

Body:
URLSession works with two kinds of callback mechanisms:

Completion handler - this is what your code is using

URLSession delegates

To answer your question specifically, the completion handler that you have written in the code above will be invoked when the download is completed. Alternatively, if you want to do the same in a delegate method, the code should be something like this:

import Foundation
import Dispatch //you won't need this in your app

public class DownloadTask : NSObject {

    var currDownload: Int64 = -1

    func download(urlString: String) {
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config, delegate: self,   delegateQueue: nil)

        let url = URL(string: urlString)
        let task = session.downloadTask(with: url!)
        task.resume()
    }
}

extension DownloadTask : URLSessionDownloadDelegate {

    //this delegate method is called everytime a block of data is received
    public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64,
                       totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) -> Void {
        let percentage = (Double(totalBytesWritten)/Double(totalBytesExpectedToWrite)) * 100
        if Int64(percentage) != currDownload  {
            print("\(Int(percentage))%")
            currDownload = Int64(percentage)
        }
    }

    //this delegate method is called when the download completes
    public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
        //You can copy the file or unzip it using `location`
        print("\nFinished download at \(location.absoluteString)!")
    }

}

let e = DownloadTask()
e.download(urlString: "https://swift.org/LICENSE.txt")
dispatchMain() //you won't need this in your app


问:
How to send cookie with scrapy CrawlSpider requests?
I am trying to create this Reddit scraper using Python's Scrapy framework.

I have used the CrawSpider to crawl through Reddit and its subreddits. But, when I come across pages that have adult content, the site asks for a cookie over18=1.

So, I have been trying to send a cookie with every request that the spider makes, but, its not working out.

Here, is my spider code. As you can see I tried to add a cookie with every spider request using the start_requests() method.

Could anyone here tell me how to do this? Or what I have been doing wrong?

```<code>from scrapy import Spider
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from reddit.items import RedditItem
from scrapy.http import Request, FormRequest

class MySpider(CrawlSpider):
    name = 'redditscraper'
    allowed_domains = ['reddit.com', 'imgur.com']
    start_urls = ['https://www.reddit.com/r/nsfw']

    rules = (
        Rule(LinkExtractor(
            allow=['/r/nsfw/\?count=\d*&after=\w*']),
            callback='parse_item',
            follow=True),
    )

    def start_requests(self):
        for i,url in enumerate(self.start_urls):
            print(url)
            yield Request(url,cookies={'over18':'1'},callback=self.parse_item)

    def parse_item(self, response):
        titleList = response.css('a.title')

        for title in titleList:
            item = RedditItem()
            item['url'] = title.xpath('@href').extract()
            item['title'] = title.xpath('text()').extract()
            yield item
</code>```

答:
The Scrapy Docs

1.Using a dict:

```<code>request_with_cookies = Request(url="http://www.example.com",
                               cookies={'currency': 'USD', 'country': 'UY'})
</code>```

2.Using a list of dicts:

```<code>request_with_cookies = Request(url="http://www.example.com",
                               cookies=[{'name': 'currency',
                                        'value': 'USD',
                                        'domain': 'example.com',
                                        'path': '/currency'}])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create this Reddit scraper using Python's Scrapy framework.

I have used the CrawSpider to crawl through Reddit and its subreddits. But, when I come across pages that have adult content, the site asks for a cookie over18=1.

So, I have been trying to send a cookie with every request that the spider makes, but, its not working out.

Here, is my spider code. As you can see I tried to add a cookie with every spider request using the start_requests() method.

Could anyone here tell me how to do this? Or what I have been doing wrong?

from scrapy import Spider
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from reddit.items import RedditItem
from scrapy.http import Request, FormRequest

class MySpider(CrawlSpider):
    name = 'redditscraper'
    allowed_domains = ['reddit.com', 'imgur.com']
    start_urls = ['https://www.reddit.com/r/nsfw']

    rules = (
        Rule(LinkExtractor(
            allow=['/r/nsfw/\?count=\d*&after=\w*']),
            callback='parse_item',
            follow=True),
    )

    def start_requests(self):
        for i,url in enumerate(self.start_urls):
            print(url)
            yield Request(url,cookies={'over18':'1'},callback=self.parse_item)

    def parse_item(self, response):
        titleList = response.css('a.title')

        for title in titleList:
            item = RedditItem()
            item['url'] = title.xpath('@href').extract()
            item['title'] = title.xpath('text()').extract()
            yield item

Body:
The Scrapy Docs

1.Using a dict:

request_with_cookies = Request(url="http://www.example.com",
                               cookies={'currency': 'USD', 'country': 'UY'})

2.Using a list of dicts:

request_with_cookies = Request(url="http://www.example.com",
                               cookies=[{'name': 'currency',
                                        'value': 'USD',
                                        'domain': 'example.com',
                                        'path': '/currency'}])


问:
Sql 2008 r2 - Datename
This is copied ditto from example given in Sql2008 R2 doc - Syntax: DATENAME (datepart ,date )

```<code>SELECT DATENAME(datepart,'2007-10-30 12:15:32.1234567 +05:10')
</code>```

And it throws

```<code>Msg 155, Level 15, State 1, Line 4
'datepart' is not a recognized datename option.
</code>```

What is wrong here ? Where is Bill...

答:
You should specify what part of the date you want in the place of datepart parameter.
Check this link:

http://msdn.microsoft.com/en-us/library/ms174420.aspx

So in case you need year part of the date it would be:

```<code>SELECT DATENAME(year,'2007-10-30 12:15:32.1234567 +05:10')
</code>```

ContentLicense: CC BY-SA 2.5

Title: Sql 2008 r2 - Datename

Body:
This is copied ditto from example given in Sql2008 R2 doc - Syntax: DATENAME (datepart ,date )

SELECT DATENAME(datepart,'2007-10-30 12:15:32.1234567 +05:10')

And it throws

Msg 155, Level 15, State 1, Line 4
'datepart' is not a recognized datename option.

What is wrong here ? Where is Bill...

Body:
You should specify what part of the date you want in the place of datepart parameter.
Check this link:

http://msdn.microsoft.com/en-us/library/ms174420.aspx

So in case you need year part of the date it would be:

SELECT DATENAME(year,'2007-10-30 12:15:32.1234567 +05:10')


问:
How to show a form on startup if there is data found in database in C#
What I am trying to do is if for example a user has registered or saved data in the database they will be automatically redirected to a certain form on startup...

Here is the code I've tried so far and it it is not working according to how I want it to be...

In Form1:

```<code>// I declared the rowcounts as public
public int rowcounts;

public void Form1_Load(object sender, EventArgs e)
{
        SqlConnection connCount = locald.DB.GetSqlConnection();
        System.Data.SqlClient.SqlCommand com = new
        System.Data.SqlClient.SqlCommand();
        com.Connection = connCount;
        com.CommandType = CommandType.StoredProcedure;
        com.CommandText = @"countval";
        rowcounts = Convert.ToInt32(com.ExecuteScalar());
        label1.Text = rowcounts.ToString();
}
</code>```

In Program.cs:

```<code>static void Main()
{
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Form1 f1 = new Form1();

        if (f1.rowcounts == 0)
        {
            Application.Run(new Form2());    // if database has no records
        }
        else
        {
            Application.Run(new Form1());
        }
}
</code>```

I created a class DB.cs for connection

```<code>public class DB
{
    public static string ConnectionString
    {
        get
        {
            string connStr = ConfigurationManager.ConnectionStrings["locald.Properties.Settings.localdConnectionString"].ToString();

            SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(connStr);
            sb.ApplicationName = ApplicationName ?? sb.ApplicationName;
            sb.ConnectTimeout = (ConnectionTimeout > 0) ? ConnectionTimeout : sb.ConnectTimeout;

            return sb.ToString();
        }
    }

    public static string ApplicationName { get; set; }
    public static int ConnectionTimeout { get; set; }

    public static SqlConnection GetSqlConnection()
    {
        SqlConnection cnn = new SqlConnection(ConnectionString);
        cnn.Open();
        return cnn;
    }
}
</code>```

The problem is even if the database has or without data it would still show the Form1 on startup. What I want is if the database has data it would automatically be redirected to the Form1 and if it has not then it will be in Form2 on startup...

Please help.. Thanks in advance...

答:
I'd post it as a comment, but can't comment with low reputation...
First of all, you're missing "if" in your Program.cs (I believe it's not the real problem, or is it?)

Secondly, you can try to call "Close" on form1 if you don't want it to show, right in its "Initialize", just as an easy solution.

Like that:

```<code>private void Form1_Load(object sender, EventArgs e)
        {
            //...
            //Your code
            //...

            // If no data
            this.Close();
        }
</code>```

Body:
What I am trying to do is if for example a user has registered or saved data in the database they will be automatically redirected to a certain form on startup...

Here is the code I've tried so far and it it is not working according to how I want it to be...

In Form1:

// I declared the rowcounts as public
public int rowcounts;

public void Form1_Load(object sender, EventArgs e)
{
        SqlConnection connCount = locald.DB.GetSqlConnection();
        System.Data.SqlClient.SqlCommand com = new
        System.Data.SqlClient.SqlCommand();
        com.Connection = connCount;
        com.CommandType = CommandType.StoredProcedure;
        com.CommandText = @"countval";
        rowcounts = Convert.ToInt32(com.ExecuteScalar());
        label1.Text = rowcounts.ToString();
}

In Program.cs:

static void Main()
{
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Form1 f1 = new Form1();

        if (f1.rowcounts == 0)
        {
            Application.Run(new Form2());    // if database has no records
        }
        else
        {
            Application.Run(new Form1());
        }
}

I created a class DB.cs for connection

public class DB
{
    public static string ConnectionString
    {
        get
        {
            string connStr = ConfigurationManager.ConnectionStrings["locald.Properties.Settings.localdConnectionString"].ToString();

            SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder(connStr);
            sb.ApplicationName = ApplicationName ?? sb.ApplicationName;
            sb.ConnectTimeout = (ConnectionTimeout > 0) ? ConnectionTimeout : sb.ConnectTimeout;

            return sb.ToString();
        }
    }

    public static string ApplicationName { get; set; }
    public static int ConnectionTimeout { get; set; }

    public static SqlConnection GetSqlConnection()
    {
        SqlConnection cnn = new SqlConnection(ConnectionString);
        cnn.Open();
        return cnn;
    }
}

The problem is even if the database has or without data it would still show the Form1 on startup. What I want is if the database has data it would automatically be redirected to the Form1 and if it has not then it will be in Form2 on startup...

Please help.. Thanks in advance...

Body:
I'd post it as a comment, but can't comment with low reputation...
First of all, you're missing "if" in your Program.cs (I believe it's not the real problem, or is it?)

Secondly, you can try to call "Close" on form1 if you don't want it to show, right in its "Initialize", just as an easy solution.

Like that:

private void Form1_Load(object sender, EventArgs e)
        {
            //...
            //Your code
            //...

            // If no data
            this.Close();
        }


问:
Salforce login session issue
Please help me for login session issue for Android SDk
Hi,

I have an Android app in which we have to login using Salesforce, we have used https://github.com/forcedotcom/SalesforceMobileSDK-Android SDK (Native) .
Below are the session expired scenario:
1. After successful login on https://ABC.force.com from mobile app.
2. I am able to see this link https://ABC.force.com /customers/one/one.app in android native WebView
3. But after 24 hours I am again seeing login screen.

How can I preserve session until user manually logout from my app.
Please suggest.

答:
User can get the new access token for session as

Using the refresh token authentication flow involves the following steps.
  The consumer uses the existing refresh token to request a new access token.
After the request is verified, Salesforce sends a response to client.

POST /services/oauth2/token HTTP/1.1
Host: https://login.salesforce.com/
grant_type=refresh_token&client_id=3MVG9lKcPoNINVBIPJjdw1J9LLM82HnFVVX19KY1uA5mu0
QqEWhqKpoW3svG3XHrXDiCQjK1mdgAvhCscA9GE&client_secret=1955279925675241571
&refresh_token=your token here

Title: Salforce login session issue


问:
Why React's PureComponent is recommended to have all its children "pure"
Having read the official React documentation, I've came across this regarding PureComponent:

Furthermore, React.PureComponent’s shouldComponentUpdate() skips prop
  updates for the whole component subtree. Make sure all the children
  components are also “pure”.

Why exactly does skipping props updates for the whole subtree means avoiding non-pure components? what would be the consequences of a non-pure component inside a PureComponent's component subtree (both in general and in the case when it's not designed/supposed to respond to props change).

答:
A Pure Component for the same set of input props will give absolutely the same result, not just for itself but for the entire DOM tree. When you declare a PureComponent, not only do you need to think about props and state, but also context. PureComponents Block any context changes. Consider an example

```<code><MyApp>
 <Router>    // react-router.
  <App>   // A PureComponent
   <Switch>  // react-router Switch
     <Route ....>
   </Switch>
  </App>
 </Router>
</MyApp>
</code>```

React-router’s Router will store current location in router props of context. And React-router’s Switch will read it back and choose a Route.But since App is a very pure component, and will not react to context change in Router, because it not using that values and should ignore them. And hence when you have a PureComponent in place, you should think about not only the component but also its nested children. So essentially you would also keep all your children Pure.

Body:
A Pure Component for the same set of input props will give absolutely the same result, not just for itself but for the entire DOM tree. When you declare a PureComponent, not only do you need to think about props and state, but also context. PureComponents Block any context changes. Consider an example

<MyApp>
 <Router>    // react-router.
  <App>   // A PureComponent
   <Switch>  // react-router Switch
     <Route ....>
   </Switch>
  </App>
 </Router>
</MyApp>

React-router’s Router will store current location in router props of context. And React-router’s Switch will read it back and choose a Route.But since App is a very pure component, and will not react to context change in Router, because it not using that values and should ignore them. And hence when you have a PureComponent in place, you should think about not only the component but also its nested children. So essentially you would also keep all your children Pure.


问:
Glide resizing image via override does not resize the image
I'm using Glide to download and display image, however, when I tried to resize the image, it does not do so. I get random size (or perhaps its the actual size of the image).

Here's the code I used for loading via Glide

```<code>Glide.with(context)
     .load(file.getUrl())
     .asBitmap()
     .diskCacheStrategy(DiskCacheStrategy.ALL)
     .centerCrop()
     .transform(new CropCircleTransform(context))
     .override(dimen, dimen)
     .into(new SimpleTarget<Bitmap>() {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
          bitmap = resource;

          Log.info(resource.getWidth() + "x" + resource.getHeight());
        }
      });
</code>```

the CropCircleTransform just render the bitmap circular and center crop. I tried removing it just to test if this method causes the problem but still the image doesn't resize to the dimension I specified.

Anything wrong with my code? or Am I misunderstanding the override method here?

EDIT:

Tried to remove the override, and it seems to have loaded the image in large size so it means there's actually a resizing that happens when using the override.

How come, it doesn't resize to the actual value I specified though?

EDIT:

As a sample, the value for dimen is 96, but the dimension displayed in the log for the images are like 97x97, 117x117, 154x154, etc.

Does that mean, the value for the override method is the baseline for resize and not the actual dimension to be used?

答:
```<code>ImageView iv = (ImageView) findViewById(R.id.left);

int width = 60;
int height = 60;

LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
iv.setLayoutParams(parms);

Glide.with(context).load(path).centerCrop().crossFade().into(iv);
</code>```

Body:
I'm using Glide to download and display image, however, when I tried to resize the image, it does not do so. I get random size (or perhaps its the actual size of the image).

Here's the code I used for loading via Glide

Glide.with(context)
     .load(file.getUrl())
     .asBitmap()
     .diskCacheStrategy(DiskCacheStrategy.ALL)
     .centerCrop()
     .transform(new CropCircleTransform(context))
     .override(dimen, dimen)
     .into(new SimpleTarget<Bitmap>() {
        @Override
        public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
          bitmap = resource;

          Log.info(resource.getWidth() + "x" + resource.getHeight());
        }
      });

the CropCircleTransform just render the bitmap circular and center crop. I tried removing it just to test if this method causes the problem but still the image doesn't resize to the dimension I specified.

Anything wrong with my code? or Am I misunderstanding the override method here?

EDIT:

Tried to remove the override, and it seems to have loaded the image in large size so it means there's actually a resizing that happens when using the override.

How come, it doesn't resize to the actual value I specified though?

EDIT:

As a sample, the value for dimen is 96, but the dimension displayed in the log for the images are like 97x97, 117x117, 154x154, etc.

Does that mean, the value for the override method is the baseline for resize and not the actual dimension to be used?


问:
Using pandas and scipy regression line slope to identify growth
My goal is to be able to identify price growth in a table of records.

I know this is probably far off from what is possible with data tools, so I appreciate any help or suggestions for improvement.

The immediate trouble I'm having is that scipy.stats.linregress does not return if some data in the pandas rows is absent. I think some kind of masking or filling will be necessary to return the slope measure for rows where there are nulls. There is an exception thrown but it still works.

Also, am I using the best solution to find the growth?
I've observed that if I filter for the records that have a positive slope, higher rvalue (correlation) and lower stderr (standard error) the trendline for these rows is upward and consistent.

The reason I tried quantifying the price growth with the slope and other numeric values is because if I plot the lines from all the data in an excel chart, it's overwhelming to select the lines that show consistent upward movement because there is so much noise. Can it be done in a better way?

Here is the working sample:

```<code># credit  jezrael

import pandas as pd
import numpy as np
import scipy
from scipy import stats

def calc_slope(row):
    a = scipy.stats.linregress(row, y=axisvalues)
    return pd.Series(a._asdict())

table=pd.DataFrame({'Category':['A','A','A','B','C','C','C','B','B','A','A','A','B','B','D','A','B','B'],
           'Quarter':['2016-Q1','2017-Q2','2017-Q3','2017-Q4','2017-Q2','2016-Q2','2017-Q2','2016-Q3','2016-Q4','2016-Q2','2016-Q3','2017-Q4','2016-Q1','2016-Q2','2016-Q4','2016-Q4','2017-Q2','2017-Q3'],
            'Value':[100,200,500,800,700,900,300,400,600,200,300,400,200,300,100,300,500,600]})

db=(table.groupby(['Category','Quarter']).filter(lambda group: len(group) >= 1)).groupby(['Category','Quarter'])["Value"].mean()

db=db.unstack()

axisvalues=list(range(1,len(db.columns)+1)) #used in calc_slope function

db = db.join(db.apply(calc_slope,axis=1))
</code>```

答:
You can use:

```<code>#np.arange instead range
axisvalues= np.arange(1,len(db.columns)+1)

def calc_slope(row):
    #mask NaNs out
    mask = row.notnull()
    a = scipy.stats.linregress(row[mask.values], y=axisvalues[mask])
    return pd.Series(a._asdict())

db = db.join(db.apply(calc_slope,axis=1))
print (db)

print (db)
          2016-Q1  2016-Q2  2016-Q3  2016-Q4  2017-Q2  2017-Q3  2017-Q4  \
Category
A           100.0    200.0    300.0    300.0    200.0    500.0    400.0
B           200.0    300.0    400.0    600.0    500.0    600.0    800.0
C             NaN    900.0      NaN      NaN    500.0      NaN      NaN
D             NaN      NaN      NaN    100.0      NaN      NaN      NaN

             slope  intercept    rvalue    pvalue    stderr
Category
A         0.012895   0.315789  0.802955  0.029677  0.004281
B         0.010057  -0.885057  0.947623  0.001172  0.001516
C        -0.007500   8.750000 -1.000000  0.000000  0.000000
D              NaN        NaN  0.000000       NaN       NaN
</code>```

But for last row get RuntimeWarnings, because only one value in 2016-Q4.

And for remove warnings is possible use filterwarnings, thank Kdog:

```<code>import warnings
warnings.filterwarnings("ignore")
</code>```

Body:
My goal is to be able to identify price growth in a table of records.

I know this is probably far off from what is possible with data tools, so I appreciate any help or suggestions for improvement.

The immediate trouble I'm having is that scipy.stats.linregress does not return if some data in the pandas rows is absent. I think some kind of masking or filling will be necessary to return the slope measure for rows where there are nulls. There is an exception thrown but it still works.

Also, am I using the best solution to find the growth?
I've observed that if I filter for the records that have a positive slope, higher rvalue (correlation) and lower stderr (standard error) the trendline for these rows is upward and consistent.

The reason I tried quantifying the price growth with the slope and other numeric values is because if I plot the lines from all the data in an excel chart, it's overwhelming to select the lines that show consistent upward movement because there is so much noise. Can it be done in a better way?

Here is the working sample:

# credit  jezrael

import pandas as pd
import numpy as np
import scipy
from scipy import stats

def calc_slope(row):
    a = scipy.stats.linregress(row, y=axisvalues)
    return pd.Series(a._asdict())

table=pd.DataFrame({'Category':['A','A','A','B','C','C','C','B','B','A','A','A','B','B','D','A','B','B'],
           'Quarter':['2016-Q1','2017-Q2','2017-Q3','2017-Q4','2017-Q2','2016-Q2','2017-Q2','2016-Q3','2016-Q4','2016-Q2','2016-Q3','2017-Q4','2016-Q1','2016-Q2','2016-Q4','2016-Q4','2017-Q2','2017-Q3'],
            'Value':[100,200,500,800,700,900,300,400,600,200,300,400,200,300,100,300,500,600]})

db=(table.groupby(['Category','Quarter']).filter(lambda group: len(group) >= 1)).groupby(['Category','Quarter'])["Value"].mean()

db=db.unstack()

axisvalues=list(range(1,len(db.columns)+1)) #used in calc_slope function

db = db.join(db.apply(calc_slope,axis=1))

Body:
You can use:

#np.arange instead range
axisvalues= np.arange(1,len(db.columns)+1)

def calc_slope(row):
    #mask NaNs out
    mask = row.notnull()
    a = scipy.stats.linregress(row[mask.values], y=axisvalues[mask])
    return pd.Series(a._asdict())

db = db.join(db.apply(calc_slope,axis=1))
print (db)

print (db)
          2016-Q1  2016-Q2  2016-Q3  2016-Q4  2017-Q2  2017-Q3  2017-Q4  \
Category
A           100.0    200.0    300.0    300.0    200.0    500.0    400.0
B           200.0    300.0    400.0    600.0    500.0    600.0    800.0
C             NaN    900.0      NaN      NaN    500.0      NaN      NaN
D             NaN      NaN      NaN    100.0      NaN      NaN      NaN

             slope  intercept    rvalue    pvalue    stderr
Category
A         0.012895   0.315789  0.802955  0.029677  0.004281
B         0.010057  -0.885057  0.947623  0.001172  0.001516
C        -0.007500   8.750000 -1.000000  0.000000  0.000000
D              NaN        NaN  0.000000       NaN       NaN

But for last row get RuntimeWarnings, because only one value in 2016-Q4.

And for remove warnings is possible use filterwarnings, thank Kdog:

import warnings
warnings.filterwarnings("ignore")


问:
Random BigFloats Julia
Is it possible to generate random numbers of BigFloat type uniformly distributed in the interval [0,1)?

I mean, since rand(BigFloat) is not available it seems we have to use BigFloat(rand()) for that ending. However this is not satisfactory for me as  we are generating random Float64 numbers that are converted to BigFloats basically by "adding" a string of zeros, but in essence they are Float64 random numbers. Is this correct? If yes, is there any special library to generate random numbers with arbitrary precision?

答:
This answer is similar to @Dan Getz's
but I'm more confidant that it is uniform (honestly I've not done chi^2 test to check, or plots or anything).
@Dan's might be, I'm just not sure.
This answer also takes into account the precision level of BigFloat, which can be adjusted. (Counter-intuitively perhaps some BigFloats can have less precision than normal Float64s etc)

```<code>Base.rand(::Type{BigFloat}) =  get(tryparse(BigFloat, "0." .* join(rand(['0','1'], precision(BigFloat))), 2))
</code>```

Example:

```<code>julia> rand(BigFloat)
5.775971375531676786209502831045802088939348666270278366043732289527176430673822e-02

julia> rand(BigFloat)
3.061194516436133765062723761241255852372302334681778915000436918803432772307184e-01

julia> rand(BigFloat)
     1.39772524343615633719535808470123032232713877796596771875414945796651457395665e-01
</code>```

Notion is that the BigFloat has a known precision, so we should generate that many random bits.
As we are generating between [0,1), we know the base-2 representation is 0. something.
So we generate the string in base-2 and parse it in base 2.

Title: Random BigFloats Julia

Body:
This answer is similar to @Dan Getz's
but I'm more confidant that it is uniform (honestly I've not done chi^2 test to check, or plots or anything).
@Dan's might be, I'm just not sure.
This answer also takes into account the precision level of BigFloat, which can be adjusted. (Counter-intuitively perhaps some BigFloats can have less precision than normal Float64s etc)

Base.rand(::Type{BigFloat}) =  get(tryparse(BigFloat, "0." .* join(rand(['0','1'], precision(BigFloat))), 2))

Example:

julia> rand(BigFloat)
5.775971375531676786209502831045802088939348666270278366043732289527176430673822e-02

julia> rand(BigFloat)
3.061194516436133765062723761241255852372302334681778915000436918803432772307184e-01

julia> rand(BigFloat)
     1.39772524343615633719535808470123032232713877796596771875414945796651457395665e-01

Notion is that the BigFloat has a known precision, so we should generate that many random bits.
As we are generating between [0,1), we know the base-2 representation is 0. something.
So we generate the string in base-2 and parse it in base 2.


问:
Getting Null Pointer Exception While reading value from Config Properties File in Selenium
```<code>package com.HybridFramework.testbase;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestBase {

public WebDriver driver;

 public Properties a1;
 public File f1;
 public FileInputStream file;
public void loadPropertiesFile() throws IOException{
        Properties a1 = new Properties();
        System.out.println(System.getProperty("user.dir"));
        //f1= new File("E:\\Selenium-2017\\HybridFramework\\src\\main\\java\\com\\HybridFramework\\config\\config.properties");
    f1 = new File(System.getProperty("user.dir")+"/src/main/java/com/HybridFramework/config/config.properties");
    System.out.println("lola");
    file= new FileInputStream(f1);
    a1.load(file);

    f1 = new File(System.getProperty("user.dir")+"/src/main/java/com/HybridFramework/config/or.properties");
    file= new FileInputStream(f1);
    a1.load(file);

    }
    public void getPropertiesData(){

    }
public static void main(String[] args) throws IOException   {
    TestBase test = new  TestBase();
    //test.getBrowser("firefox");
    System.out.println("Start");
    test.loadPropertiesFile();
System.out.println(test.a1.getProperty("Username"));
    test.a1.getProperty("testname");
}

 }
</code>```

Below is my properties file which I am referencing to.

config.properties file

```<code>Username=Bhanu
Password=password
url=https://www.google.com
</code>```

or.properties file

```<code>test=test1
testname=login
</code>```

Error is Below

Exception in thread "main" java.lang.NullPointerException
    at com.HybridFramework.testbase.TestBase.main(TestBase.java:61)

答:
Use environment to get property from properties file first.
Then you can set it to System property and afterward you can use from System.getProperty()</p>

Body:
package com.HybridFramework.testbase;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class TestBase {

public WebDriver driver;

 public Properties a1;
 public File f1;
 public FileInputStream file;
public void loadPropertiesFile() throws IOException{
        Properties a1 = new Properties();
        System.out.println(System.getProperty("user.dir"));
        //f1= new File("E:\\Selenium-2017\\HybridFramework\\src\\main\\java\\com\\HybridFramework\\config\\config.properties");
    f1 = new File(System.getProperty("user.dir")+"/src/main/java/com/HybridFramework/config/config.properties");
    System.out.println("lola");
    file= new FileInputStream(f1);
    a1.load(file);

    f1 = new File(System.getProperty("user.dir")+"/src/main/java/com/HybridFramework/config/or.properties");
    file= new FileInputStream(f1);
    a1.load(file);

    }
    public void getPropertiesData(){

    }
public static void main(String[] args) throws IOException   {
    TestBase test = new  TestBase();
    //test.getBrowser("firefox");
    System.out.println("Start");
    test.loadPropertiesFile();
System.out.println(test.a1.getProperty("Username"));
    test.a1.getProperty("testname");
}

 }

Below is my properties file which I am referencing to.

config.properties file

Username=Bhanu
Password=password
url=https://www.google.com

or.properties file

test=test1
testname=login

Error is Below

Exception in thread "main" java.lang.NullPointerException
    at com.HybridFramework.testbase.TestBase.main(TestBase.java:61)


问:
Can I change hash error message "No token was provided to match against" "The two given tokens do not match"
I want to change the default error messages "No token was provided to match against" and "The two given tokens do not match". For the second one (tokens don't match), I thought readding the Identical validator would do it, but in the form I don't have access to the <code>$value_to_match_against</code> so maybe this is the wrong way. For the first one (no token provided), I don't know how to change it at all.  </p>

```<code>->addValidator('Identical', true, $value_to_match_against, $msg);
</code>```

答:
A simple search on Stack Overflow gives quite a lot of different way to do it:

By using .ini files

Altering the element or using SetMessages

Using options in an array definition

Using translation files

All these ways are valid, choosing the best depends on how you manage your code/application/classes. The most important point is to get either the name or the constant of the available error messages. You can find they quite easily by reading the source code of the Validator you are using (usually on top of these files), or by using the translation files.

Body:
I want to change the default error messages "No token was provided to match against" and "The two given tokens do not match". For the second one (tokens don't match), I thought readding the Identical validator would do it, but in the form I don't have access to the $value_to_match_against so maybe this is the wrong way. For the first one (no token provided), I don't know how to change it at all.

->addValidator('Identical', true, $value_to_match_against, $msg);


问:
How to write a nice Low-Pass-Filter in Scala
I needed a Low-Pass-Filter in one of my Scala projects and came up with this:

```<code>def filter(numbers: Seq[Double], filterSize: Int): Seq[Double] = {
  assert(filterSize > 0)
  val ringBuffer = new Array[Double](filterSize)
  var ringBufferIndex = 0

  numbers.map(x => {
    // update ring buffer
    ringBuffer(ringBufferIndex) = x

    // increase ring index
    ringBufferIndex += 1
    if (ringBufferIndex == filterSize) {
      ringBufferIndex = 0
    }

    // get avarage
    ringBuffer.foldLeft(0.0)(_ + _) / filterSize
  })
}
</code>```

However, there are some things I don't like about it:

It uses map (nicely functional) but needs a mutable variable (ringBufferIndex - BAD).

It work's on Seq[Double] (which is fine), but returns Seq[Double], which is bad cause it requires the caller to call .toList or whatever he actually uses. I tried using Generics here like this:

def filter\[T <% Seq[Double]](numbers: T, filterSize: Int): T

but that would not compile.

Does anyone have suggestionts how to improve those two issues?

答:
While I don't know Scala, I wouldn't use a ring buffer here. As I understand it, you want to take the average, at each array position, of the preceding filterSize elements. So go through the array left to right, keeping an accumulator holding the sum of the previous filterSize elements (at each step adding the rightmost and subtracting the leftmost) and yielding accumulator/filterSize as the value at that position. A factor of filterSize fewer additions, and in principle purely functional. Is that inconvenient to code in Scala?

(If overflow is not a concern, I'd do something a bit simpler and more parallelizable: compute the running sum of the whole array (scanl (+) 0 numbers in Haskell) and produce the running sum minus the running sum displaced filterSize positions.)

OwnerDisplayName: Lemmy

Body:
I needed a Low-Pass-Filter in one of my Scala projects and came up with this:

def filter(numbers: Seq[Double], filterSize: Int): Seq[Double] = {
  assert(filterSize > 0)
  val ringBuffer = new Array[Double](filterSize)
  var ringBufferIndex = 0

  numbers.map(x => {
    // update ring buffer
    ringBuffer(ringBufferIndex) = x

    // increase ring index
    ringBufferIndex += 1
    if (ringBufferIndex == filterSize) {
      ringBufferIndex = 0
    }

    // get avarage
    ringBuffer.foldLeft(0.0)(_ + _) / filterSize
  })
}

However, there are some things I don't like about it:

It uses map (nicely functional) but needs a mutable variable (ringBufferIndex - BAD).

It work's on Seq[Double] (which is fine), but returns Seq[Double], which is bad cause it requires the caller to call .toList or whatever he actually uses. I tried using Generics here like this:

def filter\[T <% Seq[Double]](numbers: T, filterSize: Int): T

but that would not compile.

Does anyone have suggestionts how to improve those two issues?

OwnerDisplayName: Darius Bacon


问:
PDOStatement - Use grave accents (`) in columns?
Looking at the PHP manual, does not, at any time, the suggestion to include the grave accents on the columns.

For example: recently, I was trying to run the function below:

``` $pdo->prepare("UPDATE name_table SET convert= :convert, payment = :payment WHERE id = :id") ```

After repeated attempts to try to update the data in MySQL, I noticed that the CONVERT function is a function of the native MySQL.

So after that, put the backticks in the columns and it worked:

``` $pdo->prepare("UPDATE name_table SET `convert`= :convert, `payment` = :payment WHERE id = :id") ```

Does anyone believe that the grave accents are not essential to the object PDOStatements? Just tried to MySQL, but do not know if it really is good to use backticks to further change the database.

答:
As you say yourself, your query didn't work because CONVERT is a reserved word in mySQL, and whenever using column names that are reserved words - or have other weird characteristics - you need to wrap them in backticks.

There's no harm in using backticks for every column and table name. Just don't use them on data - that doesn't work. For data, use quotes instead.

Edit after @Beau's answer: Note that this applies only to mySQL!

Body:
Looking at the PHP manual, does not, at any time, the suggestion to include the grave accents on the columns.

For example: recently, I was trying to run the function below:

 $pdo->prepare("UPDATE name_table SET convert= :convert, payment = :payment WHERE id = :id")

After repeated attempts to try to update the data in MySQL, I noticed that the CONVERT function is a function of the native MySQL.

So after that, put the backticks in the columns and it worked:

 $pdo->prepare("UPDATE name_table SET `convert`= :convert, `payment` = :payment WHERE id = :id")

Does anyone believe that the grave accents are not essential to the object PDOStatements? Just tried to MySQL, but do not know if it really is good to use backticks to further change the database.


问:
Permitting user agent (chrome) CORS requests programmatically
I need to get some data from external API, from other domain.
I use test app, runned on localhost and I get error:

Origin http://localhost is not allowed by Access-Control-Allow-Origin.

I try to get access to: https://api.coinmarketcap.com/v1/ticker/ by get method

I did a lot of search and:

I know that I can ask that API by using node.js, CURL, and also by running my frontend code in jest tests

By using chrome extension - https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en also everything works correctly

But unfortunatelly by simply AJAX request on my page load I can't reach that API and get an error.

And my prediction is that user agent (chrome) somehow block my request.
I can't use chrome extension because I want also access my website from my mobile phone which can't get that desktop extension.

For now my solution is "proxy", node.js server which can access that API and flow looks like:

FE

-- ASK BE -->

BE

-- ASK API -->

-- RESPONSE TO BE -->

BE

-- RESPONSE TO FE -->

FE SHOWS EVERYTHING

FE - Frontend, BE - Backend (node.js proxy), API - external API

But I want to avoid unnecessary code on the BE. Maybe there is some solution?
Like some magical header which will tell chrome to let me pass to external domain without any additional extension?

答:
You are correct you cannot bypass the CORS rules unless you are using jsonp and the server in question supports it.  When working with that ticker in the past I had to build a backend exactly as you describe with express.

FE => BE => Ticker => BE => FE


问:
Is there a hotkey in Android Studio's commit dialog to show changes without touching the mouse?
I commit often in Android Studio and I always check the changes first. I can press Ctrl-K to open the commit dialog and there I should be able to use F7 to go through the changes.

The problem is by default the commit message editor is selected and there F7 does not work for some reason.

Is there a hotkey to focus the changes pane, so F7 works?  I can do it with the mouse, but I commit frequently, so I'd like to do all these from the keyboard without using the mouse.

答:
The direct answer is no.

In commit changes window, it focus on commit Message by default, and it can not be changed. So hotkey can not be used since no files is focused in the commit changes window.

The work around is view diff of the un-committed files before opening the commit changes window:

First add two keyboard shortcuts in keymap:

Such as Alt+A for compare with Same Repository Verison, and Alt+D for Show Local Changes.

Before commit changes, you can check the local changes by Alt+D, and check the diff of a file by Alt+A.

After view the diff the the un-committed files, then you can open commit changes window to commit directly.


问:
jQuery: Suppress `click` when `dblclick` is imminent?
Let's say I have a . When you single-click this span, I want a save() function to fire. When you double-click the span, I want a rename() function to fire.

If you double-click the span, however, first the click event will fire, then the dblclick event. Since the click precedes dblclick, how can I tell click to not fire save() and instead defer to dblclick where rename() will be fired?

I can probably come up with a few workarounds, but is there any existing functionality in jQuery or previous (code) work that helps me with this already?

答:
This looks helpful:
single and double-click</p>


问:
How to resolve 'Initialize the log4j system properly' error?
I've created a maven project and under src -> test -> java, I created package learnlog4j and under that package, I've test classes.

I've created log4j.properties under root of the project, which has following content -

```<code>log4j.rootLogger=INFO, stdout

log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{HH:mm:ss:SSS} %p [%C{1}] %m%n
</code>```

But when I run following test class,

```<code>public class Log4jExample1 {
    final static Logger logger = Logger.getLogger(Log4jExample1.class);

    @BeforeClass
    public void beforeClass(){
        logger.info("IN Before Class");
    }

    @Test
    public void test1(){
        logger.info("IN Test");
    }

    @AfterClass
    public void afterClass(){
        logger.info("IN After Class");
    }
}
</code>```

it gives error -

```<code>log4j:WARN No appenders could be found for logger (learnlog4j.Log4jExample1).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
</code>```

I searched over stackoverflow but that did not help. Could you please tell me if log4j.properties is at correct location? Or let me know if something that needs to be corrected.

答:
You cann add a

```<code>BasicConfigurator.configure();
</code>```

in beforeClass()-Method to get a basic Console adapter.

To use your log4j.properties, use

```<code>PropertyConfigurator.configure("log4j.properties");
</code>```

See No appenders could be found for logger(log4j)? for details.

Body:
I've created a maven project and under src -> test -> java, I created package learnlog4j and under that package, I've test classes.

I've created log4j.properties under root of the project, which has following content -

log4j.rootLogger=INFO, stdout

log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{HH:mm:ss:SSS} %p [%C{1}] %m%n

But when I run following test class,

public class Log4jExample1 {
    final static Logger logger = Logger.getLogger(Log4jExample1.class);

    @BeforeClass
    public void beforeClass(){
        logger.info("IN Before Class");
    }

    @Test
    public void test1(){
        logger.info("IN Test");
    }

    @AfterClass
    public void afterClass(){
        logger.info("IN After Class");
    }
}

it gives error -

log4j:WARN No appenders could be found for logger (learnlog4j.Log4jExample1).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

I searched over stackoverflow but that did not help. Could you please tell me if log4j.properties is at correct location? Or let me know if something that needs to be corrected.

Body:
You cann add a

BasicConfigurator.configure();

in beforeClass()-Method to get a basic Console adapter.

To use your log4j.properties, use

PropertyConfigurator.configure("log4j.properties");

See No appenders could be found for logger(log4j)? for details.


问:
Url of large image of a YouTube video
I'm interested in getting a preview image of a youtube video for my application
I'm using the url to the previews:

http://img.youtube.com/vi/EqWRZrupLrI/0.jpg

but this has little two black rows, up and down, and I wish it were bigger.
I have read that the 0 is the bigger picture.

anyone know if it is possible to obtain a url with a better image?, for my project, I need the image is on a url

I appreciate the help

Regards :)

答:
Each of every image has 4 category like </p>

```<code>https://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/2.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/3.jpg
</code>```

<p>Also you can get more image size by this </p>

<p>-- For default </p>

```<code>https://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg
</code>```

<p>-- For high quality </p>

```<code>https://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg
</code>```

<p>-- For medium quality </p>

```<code>https://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg
</code>```

<p>-- For max size </p>

```<code>https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg
</code>```

Title: Url of large image of a YouTube video

Body:
Each of every image has 4 category like

https://img.youtube.com/vi/<insert-youtube-video-id-here>/0.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/1.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/2.jpg
https://img.youtube.com/vi/<insert-youtube-video-id-here>/3.jpg

Also you can get more image size by this

-- For default

https://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg

-- For high quality

https://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg

-- For medium quality

https://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg

-- For max size

https://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg


问:
How to access existing Amazon DynamoDB Table?
General Problem

I have followed this tutorial on creating and accessing an Amazon DynamoDB from an Android application, and then adapted it for use in an app I am writing. It works great despite the difficulties I faced getting it up and running. However, I would also like to be able to access the database using a python script running on my Raspberry Pi.

I have found this tutorial, but it seems to only describe how to interact with a local DynamoDB table.

Specific Problem

The following code connects and writes an item to a DynamoDB table. I can't find any sort of endpoint URL for my Amazon DynamoDB, only the ARN, and there is no passing of a password or username as I use in my App.

```<code># Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)

dynamodb = boto3.resource('dynamodb', region_name='us-west-2', endpoint_url="http://localhost:8000")

table = dynamodb.Table('Movies')

title = "The Big New Movie"
year = 2015

response = table.put_item(
   Item={
        'year': year,
        'title': title,
        'info': {
            'plot':"Nothing happens at all.",
            'rating': decimal.Decimal(0)
        }
    }
)
</code>```

I have searched for any sort of instructions for connecting to an Amazon DynamoDB instance, but everything I have found describes a local table. If anyone can give advice for the specific issue or recommend a tutorial to that effect, I would appreciate it immensely.

答:
Change

```<code>dynamodb = boto3.resource('dynamodb',endpoint_url="http://localhost:8000")
</code>```

To

```<code>dynamodb = boto3.resource('dynamodb',region_name='REGION')
</code>```

Where REGION is the name of your dynamodb region, such as 'us-west-2'. It will then connect to AWS DynamoDB instance.

EDIT: If you haven't do so already, you will need to setup your AWS Credentials. There are several options for this. One option is to use environment variables

Boto3 will check these environment variables for credentials:

AWS_ACCESS_KEY_ID The access key for your AWS account.

AWS_SECRET_ACCESS_KEY The secret key for your AWS account.

Body:
General Problem

I have followed this tutorial on creating and accessing an Amazon DynamoDB from an Android application, and then adapted it for use in an app I am writing. It works great despite the difficulties I faced getting it up and running. However, I would also like to be able to access the database using a python script running on my Raspberry Pi.

I have found this tutorial, but it seems to only describe how to interact with a local DynamoDB table.

Specific Problem

The following code connects and writes an item to a DynamoDB table. I can't find any sort of endpoint URL for my Amazon DynamoDB, only the ARN, and there is no passing of a password or username as I use in my App.

# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
    def default(self, o):
        if isinstance(o, decimal.Decimal):
            if o % 1 > 0:
                return float(o)
            else:
                return int(o)
        return super(DecimalEncoder, self).default(o)

dynamodb = boto3.resource('dynamodb', region_name='us-west-2', endpoint_url="http://localhost:8000")

table = dynamodb.Table('Movies')

title = "The Big New Movie"
year = 2015

response = table.put_item(
   Item={
        'year': year,
        'title': title,
        'info': {
            'plot':"Nothing happens at all.",
            'rating': decimal.Decimal(0)
        }
    }
)

I have searched for any sort of instructions for connecting to an Amazon DynamoDB instance, but everything I have found describes a local table. If anyone can give advice for the specific issue or recommend a tutorial to that effect, I would appreciate it immensely.

Body:
Change

dynamodb = boto3.resource('dynamodb',endpoint_url="http://localhost:8000")

To

dynamodb = boto3.resource('dynamodb',region_name='REGION')

Where REGION is the name of your dynamodb region, such as 'us-west-2'. It will then connect to AWS DynamoDB instance.

EDIT: If you haven't do so already, you will need to setup your AWS Credentials. There are several options for this. One option is to use environment variables

Boto3 will check these environment variables for credentials:

AWS_ACCESS_KEY_ID The access key for your AWS account.

AWS_SECRET_ACCESS_KEY The secret key for your AWS account.


问:
Chat type - scroll to bottom - angular 2
Need to scroll to bottom automatically once messages are being added in a chat.

Tried AfterViewChecked method of implementing this, as suggessted in
[angular2 scroll to bottom (chat style)  - It works fine as it makes the scroll move to bottom. But when we try scrolling up as soon as we add a message in the chat, it is not allowing and it again pushes the view to the bottom of the chat

Please suggest a workaround on this.

答:
The below code worked for me for my angular 4 chat application

My component.html

```<code><div class="feedBody"  #scrollMe (scroll)="onScroll()" >
  <div class="feedList">
  </div>
</div>
</code>```

My component.css

```<code>.feedBody {
  height: 235px;
  overflow-y: auto;
}
</code>```

My component.ts

```<code>scrollToBottom():void{
    if (this.disableScrollDown) {
      return
    }
    try {
      this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
    } catch(err) { }
  }
onScroll(){
    let element = this.myScrollContainer.nativeElement;
    let atBottom = (element.scrollTop+200) >= (element.scrollHeight - element.offsetHeight);
    if (atBottom) {
        this.disableScrollDown = false
    } else {
        this.disableScrollDown = true
    }
  }
</code>```

I was using element.scrollTop+200 because I wanted a behaviour where I should not compulsorily present at the bottom of the screen but can be a little top by 200px.

Hope it works for you.

Body:
The below code worked for me for my angular 4 chat application

My component.html

<div class="feedBody"  #scrollMe (scroll)="onScroll()" >
  <div class="feedList">
  </div>
</div>

My component.css

.feedBody {
  height: 235px;
  overflow-y: auto;
}

My component.ts

scrollToBottom():void{
    if (this.disableScrollDown) {
      return
    }
    try {
      this.myScrollContainer.nativeElement.scrollTop = this.myScrollContainer.nativeElement.scrollHeight;
    } catch(err) { }
  }
onScroll(){
    let element = this.myScrollContainer.nativeElement;
    let atBottom = (element.scrollTop+200) >= (element.scrollHeight - element.offsetHeight);
    if (atBottom) {
        this.disableScrollDown = false
    } else {
        this.disableScrollDown = true
    }
  }

I was using element.scrollTop+200 because I wanted a behaviour where I should not compulsorily present at the bottom of the screen but can be a little top by 200px.

Hope it works for you.


问:
Delete rows not having data after comma
I have a file consisting of comma separated pairs, for example:

```<code>a, 123
b,   456
c,
d,345
</code>```

I want the output to be like this:

```<code>a, 123
b,   456
d,345
</code>```

Since c doesn't have data after the comma, I don't want that line to be displayed. I would like this removal to occur for every line with missing data.

答:
Since you asked for sed, print only lines with a comma followed by a character:

```<code>sed -n /,./p
</code>```

You could do the same thing with grep, though.

```<code>grep ,.
</code>```

Title: Delete rows not having data after comma

Body:
I have a file consisting of comma separated pairs, for example:

a, 123
b,   456
c,
d,345

I want the output to be like this:

a, 123
b,   456
d,345

Since c doesn't have data after the comma, I don't want that line to be displayed. I would like this removal to occur for every line with missing data.

Body:
Since you asked for sed, print only lines with a comma followed by a character:

sed -n /,./p

You could do the same thing with grep, though.

grep ,.


问:
Unable to submit binary image into database in laravel
I am trying to submit an image into the database but I keep getting this error: Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, null given, called in C:\xampp\htdocs\Evaluation\app\Http\Controllers\ImageController.php on line 24.

I checked with other questions in StackOverflow and mostly they said it was the fault of the saving part where they put something like this, $post but I have checked and there is nothing wrong with it. The relationship doesn't seem to have any problem as well but why is it still not working? The error also return me a null when I upload image. The null is returning at the part here,  $UserImage = $request->input('UserImage'); So could my problem be in image1.blade.php?

ImageController:

```<code>public function test(personal_info $user){
    return view('image1',compact('user'));
}

public function test1(Request $request){
    $UserImage = new Image;
    $personal_info = new personal_info;
    $UserImage = $request->input('UserImage');
    $id = $request->user_id;
    $id = personal_info::find($id);
    $id->Images()->save($UserImage);
       return redirect('/summary');
    }
</code>```

image1.blade.php (where i submit the form)

```<code> <form class="form-horizontal" method="post" action="{{ url('/Upload')}}" enctype="multipart/form-data">

                        {{  csrf_field()  }}
<input type="hidden" name="user_id" value="{{$user->id}}">

<div class="form-group">
    <label for="imageInput" class="control-label col-sm-3">Upload Image</label>
            <div class="col-sm-9">
                <input type="file" name="UserImage">

        </div>
    </div>

 <div class="form-group">
            <div class="col-md-6-offset-2" style="padding-left: 30px">
              <input type="submit" class="btn btn-primary" value="Save">
            </div>
          </div>
          </form>
</code>```

Image.php:

```<code>public function personal_infos() {
    return $this->belongsTo('App\personal_info', 'user_id', 'id');
}
</code>```

personal_info.php:

```<code>public function Images() {
    return $this->hasOne('App\Image','user_id');
}
</code>```

答:
```<code>public function test1(Request $request)
{
    // make new instance of Image Model
    $imageModel = new Image;
    // find personal_info Model by id
    $personal_info = personal_info::findOrFail($request->input('user_id'));

    // UploadedFile
    $image = $request->file('UserImage');

    // get the file contents?
    $imageModel->content = ...

    // save the relationships, pass a model instance to `save`
    $personal_info->Images()->save($imageModel);

    return redirect('/summary');
}
</code>```

Body:
I am trying to submit an image into the database but I keep getting this error: Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, null given, called in C:\xampp\htdocs\Evaluation\app\Http\Controllers\ImageController.php on line 24.

I checked with other questions in StackOverflow and mostly they said it was the fault of the saving part where they put something like this, $post but I have checked and there is nothing wrong with it. The relationship doesn't seem to have any problem as well but why is it still not working? The error also return me a null when I upload image. The null is returning at the part here,  $UserImage = $request->input('UserImage'); So could my problem be in image1.blade.php?

ImageController:

public function test(personal_info $user){
    return view('image1',compact('user'));
}

public function test1(Request $request){
    $UserImage = new Image;
    $personal_info = new personal_info;
    $UserImage = $request->input('UserImage');
    $id = $request->user_id;
    $id = personal_info::find($id);
    $id->Images()->save($UserImage);
       return redirect('/summary');
    }

image1.blade.php (where i submit the form)

 <form class="form-horizontal" method="post" action="{{ url('/Upload')}}" enctype="multipart/form-data">

                        {{  csrf_field()  }}
<input type="hidden" name="user_id" value="{{$user->id}}">

    Upload Image

                <input type="file" name="UserImage">

              <input type="submit" class="btn btn-primary" value="Save">

          </form>

Image.php:

public function personal_infos() {
    return $this->belongsTo('App\personal_info', 'user_id', 'id');
}

personal_info.php:

public function Images() {
    return $this->hasOne('App\Image','user_id');
}


问:
Django forms.VaildationError not showing on a class based view
My forms.validationerror is not showing. Below is my form that I am using. The if statement works and it detects the issue, and prints out the content successfully. As a lot the existing errors on stackoverflow suggest, the content is not None as shown in the print statement.

```<code>            class PollItemMessageAddForm(forms.ModelForm):
                class Meta:
                    model = Message
                    fields = [
                        "content"
                    ]

                    labels = {
                        'content': 'Add your comment',
                    }

                    widgets = {
                        'content': Textarea(attrs={'cols': 10, 'rows': 5}),
                    }

                def __init__(self, *args, **kwargs):

                    # this line should be before a super call
                    self.request = kwargs.pop('request', None)

                    super(PollItemMessageAddForm, self).__init__(*args, **kwargs)
                    self.helper = FormHelper()
                    self.helper.form_method = 'post'
                    self.helper.add_input(Submit('submit', value='Post', css_class='buttonspace btn-success'))

                def clean_content(self):
                    content = self.cleaned_data.get("content")

                    if len(content) > 50:
                        print content
                        raise forms.ValidationError("Please limit your message to less the 50 characters")

                    return content
</code>```

Below is my views.py post statement in my class based view, which skips the form.isvalid to be redirected to the same url where the error message should appear. I am using a detailview and formmixin in my class based view if it helps. I cant see where the issue is coming from in the absence of a traceback. Any help would be appreciated.

```<code>                def post(self, request, *args, **kwargs):
                    url = "/polls/" + str(self.get_object().id)

                    form = self.get_form()
                    if request.method == "POST":

                        if form.is_valid():

                            print "works"

                            return self.form_valid(form)

                    return HttpResponseRedirect(url)
</code>```

答:
Here if the form is not valid, you have to return like this:

```<code>return render(request, self.template_name, {'errors': form.errors, 'form':form})
</code>```

and display the errors in the template or {{ form.non_field_errors }} inside the template will show the error.

Body:
My forms.validationerror is not showing. Below is my form that I am using. The if statement works and it detects the issue, and prints out the content successfully. As a lot the existing errors on stackoverflow suggest, the content is not None as shown in the print statement.

            class PollItemMessageAddForm(forms.ModelForm):
                class Meta:
                    model = Message
                    fields = [
                        "content"
                    ]

                    labels = {
                        'content': 'Add your comment',
                    }

                    widgets = {
                        'content': Textarea(attrs={'cols': 10, 'rows': 5}),
                    }

                def __init__(self, *args, **kwargs):

                    # this line should be before a super call
                    self.request = kwargs.pop('request', None)

                    super(PollItemMessageAddForm, self).__init__(*args, **kwargs)
                    self.helper = FormHelper()
                    self.helper.form_method = 'post'
                    self.helper.add_input(Submit('submit', value='Post', css_class='buttonspace btn-success'))

                def clean_content(self):
                    content = self.cleaned_data.get("content")

                    if len(content) > 50:
                        print content
                        raise forms.ValidationError("Please limit your message to less the 50 characters")

                    return content

Below is my views.py post statement in my class based view, which skips the form.isvalid to be redirected to the same url where the error message should appear. I am using a detailview and formmixin in my class based view if it helps. I cant see where the issue is coming from in the absence of a traceback. Any help would be appreciated.

                def post(self, request, *args, **kwargs):
                    url = "/polls/" + str(self.get_object().id)

                    form = self.get_form()
                    if request.method == "POST":

                        if form.is_valid():

                            print "works"

                            return self.form_valid(form)

                    return HttpResponseRedirect(url)

Body:
Here if the form is not valid, you have to return like this:

return render(request, self.template_name, {'errors': form.errors, 'form':form})

and display the errors in the template or {{ form.non_field_errors }} inside the template will show the error.


问:
Javascript get textContent of a div by his id console cannot read property of null
Simple problem I guess, I have a simple div:

hello

I want to extract the text content, so I did:

```<code>document.getElementById("#test").textContent;
</code>```

When I do that in the console, it tells me

"Cannot read property 'textContent' of null".

What is the problem?

答:
Assuming the id of the div is test,in that case there is no need of hash #

```<code>document.getElementById("test").
</code>```

will able to retrieve the element from the DOM

Body:
Simple problem I guess, I have a simple div:

hello

I want to extract the text content, so I did:

document.getElementById("#test").textContent;

When I do that in the console, it tells me

"Cannot read property 'textContent' of null".

What is the problem?

Body:
Assuming the id of the div is test,in that case there is no need of hash #

document.getElementById("test").

will able to retrieve the element from the DOM


问:
Post data from angular to php api side
Here is my (login.service.ts) code:

```<code>private pageURL = 'http://localhost/social/src/app/api/ws/react_signup_login/login.php';
    user = new UserLogin();

    login(value: Object): Observable<any> {
        const body = new URLSearchParams();
        Object.keys(value).forEach(key => {
            body.set(key, value[key]);
        });

        let headers = new Headers();
        headers.append('Content-Type',
            'application/x-www-form-urlencoded');
        return this._http.post(this.pageURL, this.user.toString(), {
            headers: headers
        }).map(res => res.json());
    }
</code>```

And this is my login.ts class

```<code>export class UserLogin {
    username: string;
    password: string;
    constructor() {
    }
}
</code>```

in (login.component.ts)

```<code>user = new UserLogin();
login(value) {
        this._loginService.login({value})
            .subscribe(
                response => this.user = response,
                error => console.log(error)
            );
    }
</code>```

Finally my (login.php) that I expect the error is here

```<code>header("Access-Control-Allow-Origin: *");
header("Content-type:application/json");

if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST))
    $_POST = json_decode(file_get_contents('php://input'), true);

$params['username'] = $_POST['username'];
$params['password'] = $_POST['password'];
</code>```

When I'm trying to (var_dump) the $params I got this:

```<code>array(2) {
  ["username"]=>
  NULL
  ["password"]=>
  NULL
}
</code>```

答:
In your POST Http call you should use your defined URLSearchParams as body and not user, because your user object is empty.

Change your http call code block in login.service.ts from this:

```<code>return this._http.post(this.pageURL, this.user.toString(), {
            headers: headers
        }).map(res => res.json());
</code>```

to this:

```<code>return this._http.post(this.pageURL, body.toString(), {
            headers: headers
        }).map(res => res.json());
</code>```

Title: Post data from angular to php api side

Body:
Here is my (login.service.ts) code:

private pageURL = 'http://localhost/social/src/app/api/ws/react_signup_login/login.php';
    user = new UserLogin();

    login(value: Object): Observable<any> {
        const body = new URLSearchParams();
        Object.keys(value).forEach(key => {
            body.set(key, value[key]);
        });

        let headers = new Headers();
        headers.append('Content-Type',
            'application/x-www-form-urlencoded');
        return this._http.post(this.pageURL, this.user.toString(), {
            headers: headers
        }).map(res => res.json());
    }

And this is my login.ts class

export class UserLogin {
    username: string;
    password: string;
    constructor() {
    }
}

in (login.component.ts)

user = new UserLogin();
login(value) {
        this._loginService.login({value})
            .subscribe(
                response => this.user = response,
                error => console.log(error)
            );
    }

Finally my (login.php) that I expect the error is here

header("Access-Control-Allow-Origin: *");
header("Content-type:application/json");

if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($_POST))
    $_POST = json_decode(file_get_contents('php://input'), true);

$params['username'] = $_POST['username'];
$params['password'] = $_POST['password'];

When I'm trying to (var_dump) the $params I got this:

array(2) {
  ["username"]=>
  NULL
  ["password"]=>
  NULL
}

Body:
In your POST Http call you should use your defined URLSearchParams as body and not user, because your user object is empty.

Change your http call code block in login.service.ts from this:

return this._http.post(this.pageURL, this.user.toString(), {
            headers: headers
        }).map(res => res.json());

to this:

return this._http.post(this.pageURL, body.toString(), {
            headers: headers
        }).map(res => res.json());


问:
R: "label" a row based on conditions from another data.table
I have a data.table (A) that is over 100,000 rows long. There are 3 columns.

         chrom     start      end
     1:  chr1   6484847   6484896
     2:  chr1   6484896   6484945
     3:  chr1   6484945   6484994
     4:  chr1   6484994   6485043
     5:  chr1   6485043   6485092
    ---

183569:  chrX 106893605 106893654
183570:  chrX 106893654 106893703
183571:  chrX 106893703 106893752
183572:  chrX 106893752 106893801
183573:  chrX 106893801 106894256

I'd like to generate a new column named "gene" that provides a label for each row based annotations from another data.table which has ~90 rows (B). Seen below:

    chrom     start       end     gene
 1:  chr1   6484847   6521004     ESPN
 2:  chr1  41249683  41306124     KCNQ4
 3:  chr1  55464616  55474465     BSND
42:  chrX  82763268  82764775     POU3F4
43:  chrX 100600643 100603957     TIMM8A
44:  chrX 106871653 106894256     PRPS1

If the row start value in data.table A is within the row start and end values of data.table B I need the row in A to be labeled with the correct gene accordingly.

For example the resulting complete data.table A would be

         chrom     start      end   gene
     1:  chr1   6484847   6484896   ESPN
     2:  chr1   6484896   6484945   ESPN
     3:  chr1   6484945   6484994   ESPN
     4:  chr1   6484994   6485043   ESPN
     5:  chr1   6485043   6485092   ESPN
    ---

183569:  chrX 106893605 106893654   TIMM8A
183570:  chrX 106893654 106893703   TIMM8A
183571:  chrX 106893703 106893752   TIMM8A
183572:  chrX 106893752 106893801   TIMM8A
183573:  chrX 106893801 106894256   TIMM8A

I've attempted some nested loops to do this but that seems like it would take WAY too long. I think there must be a way to do this with the data.table package but I can't seem to figure it out.

Any and all suggestions would be greatly appreciated.

Body:
Besides the GRanges/IRanges solution by Maurits Evers, there is an alternative data.table approach using non-equi join and update on join.

A[B, on = .(chrom, start >= start, start <= end), gene := i.gene][]

    chrom     start       end  gene
 1:  chr1   6484847   6484896  ESPN
 2:  chr1   6484896   6484945  ESPN
 3:  chr1   6484945   6484994  ESPN
 4:  chr1   6484994   6485043  ESPN
 5:  chr1   6485043   6485092  ESPN
 6:  chrX 106893605 106893654 PRPS1
 7:  chrX 106893654 106893703 PRPS1
 8:  chrX 106893703 106893752 PRPS1
 9:  chrX 106893752 106893801 PRPS1
10:  chrX 106893801 106894256 PRPS1

According to the OP, A and B are already data.table objects. So, this approach avoids the coercion to GRanges objects.

Reproducible Data

library(data.table)
A <- fread("rn         chrom     start      end
     1:  chr1   6484847   6484896
     2:  chr1   6484896   6484945
     3:  chr1   6484945   6484994
     4:  chr1   6484994   6485043
     5:  chr1   6485043   6485092
183569:  chrX 106893605 106893654
183570:  chrX 106893654 106893703
183571:  chrX 106893703 106893752
183572:  chrX 106893752 106893801
183573:  chrX 106893801 106894256", drop = 1L)

B <- fread("rn    chrom     start       end     gene
 1:  chr1   6484847   6521004     ESPN
 2:  chr1  41249683  41306124     KCNQ4
 3:  chr1  55464616  55474465     BSND
42:  chrX  82763268  82764775     POU3F4
43:  chrX 100600643 100603957     TIMM8A
44:  chrX 106871653 106894256     PRPS1", drop = 1L)


问:
What is the difference between Targets, Executables and Products in Xcode
In Xcode under Groups & Files panel, what is the difference between Targets, Executables and Products?</p>

答:
Target: Defines how to build products. A target organizes the files and instructions needed to build a product into a sequence of build actions that can be taken.

Product: The result of building a target. (MyAppName.app) The resulting bundle, in other words.

Executable: Defines the environment in which to run/debug the product. An executable environment defines the program that should be used to run the product with. In many cases, this will be the product itself, but doesn't have to be. In addition, the executable environment defines any command-line arguments and environment variables which should be used.

http://developer.apple.com/tools/xcode/xcodeprojects.html


问:
How to remove decimal from Year, in google chart API?
I have implemented the google chart API in an Admin panel.
All have successfully worked, the data is successfully loaded in the jQuery.

Here's my code:-

```<code>google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
 function drawChart() {
    /*--------This code is for Line Chart ----------*/
    var optionsLine = {
      title: 'User Enrollment Statistics',
      curveType: 'function',
      legend: { position: 'bottom' }
    };

    $.ajax({
        type: "POST",
        url: "<?php echo base_url();?>ajax-graph-user-join",
        data: {'type':'yearwise','year':'','month':''},
        dataType: "json",
        success: function (data) {
            var dataArr = [];
            for(var i = 0; i < data.length; i++)
            {
                var ar = [data[i].Year, data[i].User];
                dataArr.push(ar);
            }
            console.log(dataArr);
            var dataLine = google.visualization.arrayToDataTable(dataArr);
            var chartLine = new google.visualization.LineChart($("#lineChart")[0]);
            chartLine.draw(dataLine, optionsLine);
        },
        failure: function (r) {
            alert(r.d);
        },
        error: function (r) {
            alert(r.d);
        }
    });
}
</code>```

Now, to explain my issue, I am sharing the image:-

As you can see, the years(along the x-axis) is showing as decimals with zero and .5

I want the Years to be shown as integer only, and without the comma i.e. 2,014.

How can I do that?

Edit:-

After been suggested to put hAxis: {format: '0000'} in the optionsLine, my graph is coming like this:

Two 2015 and two 2016

答:
Just add

hAxis: {
                      gridlines: {
                          color:'transparent'
                      },
                      format:'0'
                  },

It will work!

Body:
I have implemented the google chart API in an Admin panel.
All have successfully worked, the data is successfully loaded in the jQuery.

Here's my code:-

google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
 function drawChart() {
    /*--------This code is for Line Chart ----------*/
    var optionsLine = {
      title: 'User Enrollment Statistics',
      curveType: 'function',
      legend: { position: 'bottom' }
    };

    $.ajax({
        type: "POST",
        url: "<?php echo base_url();?>ajax-graph-user-join",
        data: {'type':'yearwise','year':'','month':''},
        dataType: "json",
        success: function (data) {
            var dataArr = [];
            for(var i = 0; i < data.length; i++)
            {
                var ar = [data[i].Year, data[i].User];
                dataArr.push(ar);
            }
            console.log(dataArr);
            var dataLine = google.visualization.arrayToDataTable(dataArr);
            var chartLine = new google.visualization.LineChart($("#lineChart")[0]);
            chartLine.draw(dataLine, optionsLine);
        },
        failure: function (r) {
            alert(r.d);
        },
        error: function (r) {
            alert(r.d);
        }
    });
}

Now, to explain my issue, I am sharing the image:-

As you can see, the years(along the x-axis) is showing as decimals with zero and .5

I want the Years to be shown as integer only, and without the comma i.e. 2,014.

How can I do that?

Edit:-

After been suggested to put hAxis: {format: '0000'} in the optionsLine, my graph is coming like this:

Two 2015 and two 2016


问:
How to make a cube expand as it moves in unity?
Cheetah mobiles dancing line inspired me help me in this case how to make the cube expand in length in unity game engine.</p>

答:
Try increasing the size of your cube by adding a Vector3(sizeToIncrease, sizeToIncrease, sizeToIncrease) to your transform.localScale. Like this:</p>

```<code>if(moving){
    transform.localScale += new Vector3(sizeToIncrease, sizeToIncrease,
sizeToIncrease);
}
</code>```

Body:
Try increasing the size of your cube by adding a Vector3(sizeToIncrease, sizeToIncrease, sizeToIncrease) to your transform.localScale. Like this:

if(moving){
    transform.localScale += new Vector3(sizeToIncrease, sizeToIncrease,
sizeToIncrease);
}


问:
how to sorting according to the value of a field? mongo
I have a set of data. When I select the filter conditions, I want to query all the data and put the values that conform to the screening conditions to display in front of the query results.

for example

```<code>[
    {color: 'blue', name: 'four'},
    {color: 'green', name: 'five'},
    {color: 'red', name: 'one'},
    {color: 'red', name: 'two'},
    {color: 'red', name: 'three'}
]
</code>```

when i choose color:red, and limit 4, I want to get the data

```<code>[
    {color: 'red', name: 'one'},
    {color: 'red', name: 'two'},
    {color: 'red', name: 'three'},
    {color .........}// the fourth of data are not concerned for now
]
</code>```

and when i choose color:blue, and limit 4, I want to get the data

```<code>[
    {color: 'blue', name: 'four'},
    {color  ........},
    {color  ........},
    {color .........}// now just care the first data
]
</code>```

Have some function to achieve this？

My english is so poor, I hope the meaning is clear.

anyway, thanks!

答:
If you are using the find function, then you can use the sort function.
If the aggregation framework, then the pipeline $sort stage.

Body:
I have a set of data. When I select the filter conditions, I want to query all the data and put the values that conform to the screening conditions to display in front of the query results.

for example

[
    {color: 'blue', name: 'four'},
    {color: 'green', name: 'five'},
    {color: 'red', name: 'one'},
    {color: 'red', name: 'two'},
    {color: 'red', name: 'three'}
]

when i choose color:red, and limit 4, I want to get the data

[
    {color: 'red', name: 'one'},
    {color: 'red', name: 'two'},
    {color: 'red', name: 'three'},
    {color .........}// the fourth of data are not concerned for now
]

and when i choose color:blue, and limit 4, I want to get the data

[
    {color: 'blue', name: 'four'},
    {color  ........},
    {color  ........},
    {color .........}// now just care the first data
]

Have some function to achieve this？

My english is so poor, I hope the meaning is clear.

anyway, thanks!


问:
While iterating through a loop some items are getting missed out
The method that I am trying to run is as below where I try iterate through the sub contracts in a GBP and then I have an inner loop to iterate through the coverages in each sub contract.</p>

```<code>forEach curSubscribedSubContract in theSubContracts
   ; Avoid building empty contract node
   if subOptions.count > 0
      new(ParamProduct)
      new(ParamSubscribedProduct)
      forEach curOption in subOptions downTo
         theProduct = curOption.GetProduct
         new(ListOfCoverages)
         if Motor.AreSameThings(theProduct, curSubscribedSubContract.GetProduct)
            ParamSubscribedProduct.InitParamFromObjectAtDate(curSubscribedSubContract,
               AtDate)
            ParamProduct.Product = ParamSubscribedProduct
            ;Set Context for PlanDesign options
            AFCI_SLI.CoverageInContext = curOption
            covData = self._GetCoverageData(curOption, AtDate)
            ;Reset coverage context
            AFCI_SLI.CoverageInContext = Nil
            ListOfCoverages.AppendObject(covData)
            if subOptions.RemoveObject(curOption)
            endIf
         endIf
         forEach curCoverageData in ListOfCoverages
            ParamProduct.Coverages[-1] = curCoverageData
         endFor
         dispose(ListOfCoverages)
      endFor
      _Result[-1] = ParamProduct
   endIf
endFor
</code>```

答:
are items missing from the subcontracts or suboptions?

I think the following line of code has something to do with it:

```<code>if subOptions.RemoveObject(curOption)
endIf
</code>```

I am not sure if it is a good practice to remove objects from a list which is being iterated..

also

try removing the 'down to" from the foreach loop of suboptions

Body:
The method that I am trying to run is as below where I try iterate through the sub contracts in a GBP and then I have an inner loop to iterate through the coverages in each sub contract.

forEach curSubscribedSubContract in theSubContracts
   ; Avoid building empty contract node
   if subOptions.count > 0
      new(ParamProduct)
      new(ParamSubscribedProduct)
      forEach curOption in subOptions downTo
         theProduct = curOption.GetProduct
         new(ListOfCoverages)
         if Motor.AreSameThings(theProduct, curSubscribedSubContract.GetProduct)
            ParamSubscribedProduct.InitParamFromObjectAtDate(curSubscribedSubContract,
               AtDate)
            ParamProduct.Product = ParamSubscribedProduct
            ;Set Context for PlanDesign options
            AFCI_SLI.CoverageInContext = curOption
            covData = self._GetCoverageData(curOption, AtDate)
            ;Reset coverage context
            AFCI_SLI.CoverageInContext = Nil
            ListOfCoverages.AppendObject(covData)
            if subOptions.RemoveObject(curOption)
            endIf
         endIf
         forEach curCoverageData in ListOfCoverages
            ParamProduct.Coverages[-1] = curCoverageData
         endFor
         dispose(ListOfCoverages)
      endFor
      _Result[-1] = ParamProduct
   endIf
endFor

Body:
are items missing from the subcontracts or suboptions?

I think the following line of code has something to do with it:

if subOptions.RemoveObject(curOption)
endIf

I am not sure if it is a good practice to remove objects from a list which is being iterated..

also

try removing the 'down to" from the foreach loop of suboptions